@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.
@@ -12,9 +12,16 @@ import type {
12
12
  import { isTier, type Tier } from "../shared/scopes.js";
13
13
 
14
14
  export const CLIENT_KEY = "client";
15
- /** Non-secret automatic-setup record (confirmed publishing links). See change: add-gmail-auto-setup. */
16
- const SETUP_KEY = "setup";
17
15
  const ACCT_PREFIX = "acct:";
16
+ /** Hand-off marker to Google Connect (add-google-connect D10); the legacy data itself is never deleted. */
17
+ const MIGRATED_KEY = "migrated";
18
+
19
+ export interface MigratedRecord {
20
+ at: number;
21
+ version: number;
22
+ /** Legacy subs already handed over — later legacy accounts (added while Google Connect was off) are not in it. */
23
+ subs: string[];
24
+ }
18
25
 
19
26
  type AccountStatus = "ok" | "reauth_required";
20
27
 
@@ -120,8 +127,14 @@ export class AccountStore {
120
127
  await this.creds.set(CLIENT_KEY, { ...client });
121
128
  }
122
129
 
123
- async setSetupRecord(record: Record<string, unknown>): Promise<void> {
124
- await this.creds.set(SETUP_KEY, record);
130
+ async getMigrated(): Promise<MigratedRecord | undefined> {
131
+ const rec = await this.creds.get(MIGRATED_KEY);
132
+ if (!rec || typeof rec.at !== "number" || !Array.isArray(rec.subs)) return undefined;
133
+ return { at: rec.at, version: typeof rec.version === "number" ? rec.version : 1, subs: rec.subs.filter((s): s is string => typeof s === "string") };
134
+ }
135
+
136
+ async setMigrated(record: MigratedRecord): Promise<void> {
137
+ await this.creds.set(MIGRATED_KEY, { ...record, subs: [...record.subs] });
125
138
  }
126
139
 
127
140
  async list(): Promise<AccountRecord[]> {
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Gmail's soft link to Google Connect (add-google-connect D1/D10). Gmail declares no `dependsOn` on the
3
+ * `google` plugin: at the FIRST request after start it asks `consumeAll("google.connect")` for an entry whose
4
+ * provider is `google` (any other provider is ignored — nothing is handed over to it), hands the legacy
5
+ * client + accounts over once, and decides — for the life of the process — whether it delegates leases or
6
+ * keeps leasing from its own namespace. Enabling/disabling `google` therefore takes effect after a restart.
7
+ *
8
+ * - `usable` Google Connect is present: Gmail's management routes answer 410 `moved`.
9
+ * - `delegating` usable AND every legacy account is (now) in Google Connect: `gmail/lease` + `gmail/accounts`
10
+ * answer `{delegate:"google"}`; no fallback to legacy tokens (an imported account that was
11
+ * disconnected must stay disconnected).
12
+ * A failed / partial hand-off leaves Gmail leasing from the legacy data and is retried on the next start.
13
+ */
14
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
15
+ import { GOOGLE_CONNECT_SERVICE, GOOGLE_PLUGIN_ID } from "../shared/protocol.js";
16
+ import type { AccountStore } from "./accounts.js";
17
+
18
+ const MIGRATION_VERSION = 1;
19
+
20
+ /** Structural mirror of the google plugin's `importLegacyGmail` (no import edge between the plugins). */
21
+ interface LegacyImporter {
22
+ importLegacyGmail(snapshot: { client?: unknown; accounts: unknown[] }): Promise<
23
+ { ok: true; imported: number; skipped: number } | { ok: false; error: string }
24
+ >;
25
+ }
26
+
27
+ interface LinkState {
28
+ usable: boolean;
29
+ delegating: boolean;
30
+ }
31
+
32
+ export interface GoogleLink {
33
+ ensure(): Promise<LinkState>;
34
+ }
35
+
36
+ export function createGoogleLink(deps: {
37
+ consumeAll?: ServerPluginContext["consumeAll"];
38
+ store: AccountStore;
39
+ logger: { info(m: string): void; warn(m: string): void };
40
+ now?: () => number;
41
+ }): GoogleLink {
42
+ const { store, logger } = deps;
43
+
44
+ function provider(): LegacyImporter | undefined {
45
+ for (const e of deps.consumeAll?.<LegacyImporter>(GOOGLE_CONNECT_SERVICE) ?? []) {
46
+ if (e.provider === GOOGLE_PLUGIN_ID && typeof e.value?.importLegacyGmail === "function") return e.value;
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ async function migrate(importer: LegacyImporter): Promise<boolean> {
52
+ const accounts = await store.list();
53
+ const known = new Set((await store.getMigrated())?.subs ?? []);
54
+ // Nothing legacy, or nothing new since the last hand-off: no call, no marker for an empty namespace (B20).
55
+ if (accounts.every((a) => known.has(a.sub))) return true;
56
+ const client = await store.getClient();
57
+ const result = await importer.importLegacyGmail({ client, accounts });
58
+ if (!result.ok || result.skipped > 0) {
59
+ logger.warn(`[gmail] legacy import to Google accounts incomplete (${result.ok ? "skipped" : result.error}); using Gmail's own data`);
60
+ return false;
61
+ }
62
+ await store.setMigrated({ at: (deps.now ?? Date.now)(), version: MIGRATION_VERSION, subs: accounts.map((a) => a.sub) });
63
+ logger.info(`[gmail] legacy import to Google accounts: ${result.imported} account(s)`);
64
+ return true;
65
+ }
66
+
67
+ let state: Promise<LinkState> | undefined;
68
+ async function compute(): Promise<LinkState> {
69
+ const importer = provider();
70
+ if (!importer) return { usable: false, delegating: false };
71
+ try {
72
+ return { usable: true, delegating: await migrate(importer) };
73
+ } catch {
74
+ // Store locked / importer threw: keep leasing from the legacy data; one attempt per process.
75
+ logger.warn("[gmail] legacy import to Google accounts failed; using Gmail's own data until the next start");
76
+ return { usable: true, delegating: false };
77
+ }
78
+ }
79
+
80
+ return { ensure: () => (state ??= compute()) };
81
+ }
@@ -24,7 +24,7 @@ import type { GoogleEndpoints } from "../shared/endpoints.js";
24
24
  import { authScopeParam, type Tier } from "../shared/scopes.js";
25
25
  import type { ClientRecord } from "./accounts.js";
26
26
 
27
- /** Fixed, input-free error codes a flow can fail with (the wizard maps them to steps). */
27
+ /** Fixed, input-free error codes a flow can fail with (the Google accounts wizard maps them to steps). */
28
28
  export class GmailFlowError extends Error {
29
29
  readonly code: string;
30
30
 
@@ -39,7 +39,7 @@ const SAFE_CODE = /^[a-z_]{1,64}$/;
39
39
  const safeCode = (v: unknown, fallback: string): string =>
40
40
  typeof v === "string" && SAFE_CODE.test(v) ? v : fallback;
41
41
 
42
- export interface GoogleSignInResult extends PluginOAuthCredential {
42
+ interface GoogleSignInResult extends PluginOAuthCredential {
43
43
  sub: string;
44
44
  email: string;
45
45
  grantedScopes: string[];
@@ -1,16 +1,20 @@
1
1
  /**
2
- * Gmail plugin server entry (design D1). Wires the account store over
3
- * `ctx.credentials` (namespace `gmail`), the REST routes and the
4
- * `gmail/lease` request handler. Degrades to a 501 route set when the host
5
- * lacks the credential/OAuth seams. See change: add-gmail-plugin.
2
+ * Gmail plugin server entry (design D1). Wires the legacy account store over `ctx.credentials` (namespace
3
+ * `gmail`), the `gmail/lease` + `gmail/accounts` request handlers and the moved-route stubs. Gmail links to
4
+ * Google Connect softly (`google-link.ts`): while it owns the accounts both lanes answer
5
+ * `{delegate:"google"}` and the bridge leases from `google/lease`; otherwise Gmail leases from its own data
6
+ * as before. Degrades to inactive when the host lacks the credential seam. See change: add-google-connect.
6
7
  */
7
8
  import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
8
9
  import { resolveGoogleEndpoints } from "../shared/endpoints.js";
9
- import { ACCOUNTS_TYPE, LEASE_TYPE } from "../shared/protocol.js";
10
+ import { ACCOUNTS_TYPE, type DelegateReply, GOOGLE_PLUGIN_ID, LEASE_TYPE } from "../shared/protocol.js";
11
+ import { isOp } from "../shared/scopes.js";
10
12
  import { AccountStore, summarize } from "./accounts.js";
13
+ import { createGoogleLink } from "./google-link.js";
11
14
  import { createLeaseHandler } from "./lease.js";
12
15
  import { mountGmailRoutes } from "./routes.js";
13
- import { BROWSER_DEDICATED_SERVICE, type DedicatedBrowserService } from "./setup/browser-service.js";
16
+
17
+ const DELEGATE: DelegateReply = { delegate: GOOGLE_PLUGIN_ID };
14
18
 
15
19
  export default async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
16
20
  if (!ctx.credentials) {
@@ -19,20 +23,26 @@ export default async function registerPlugin(ctx: ServerPluginContext): Promise<
19
23
  }
20
24
  const endpoints = resolveGoogleEndpoints(process.env, (m) => ctx.logger.warn(m));
21
25
  const store = new AccountStore(ctx.credentials);
22
- ctx.registerPiRequestHandler?.(LEASE_TYPE, createLeaseHandler({ store, endpoints, logger: ctx.logger }));
23
- // Secret-free account list for `gmail_accounts` and account-required errors.
24
- ctx.registerPiRequestHandler?.(ACCOUNTS_TYPE, async () => (await store.list()).map(summarize));
25
- await mountGmailRoutes(ctx.fastify, {
26
- store,
27
- oauth: ctx.oauth,
28
- endpoints,
29
- networkGuard: ctx.networkGuard,
30
- logger: ctx.logger,
31
- // No `dependsOn` on the browser plugin (hard + it ships disabled): look the service up per request.
32
- getBrowserService: () => ctx.consume<DedicatedBrowserService>(BROWSER_DEDICATED_SERVICE),
33
- config: {
34
- get: () => ctx.getPluginConfig<Record<string, unknown>>(),
35
- update: (partial) => ctx.updatePluginConfig(partial),
26
+ const link = createGoogleLink({ consumeAll: ctx.consumeAll, store, logger: ctx.logger });
27
+ const legacyLease = createLeaseHandler({ store, endpoints, logger: ctx.logger });
28
+ // Both handlers are hub-local-only: `gmail/lease` returns a live OAuth access token (or the delegation to the
29
+ // lane that does) and `gmail/accounts` lists mailbox identities. The host refuses them (`origin_denied`) for a
30
+ // remote-origin session or a deprecated admission. See change: harden-bridge-session-claim (D3).
31
+ ctx.registerPiRequestHandler?.(
32
+ LEASE_TYPE,
33
+ async (payload: unknown) => {
34
+ if (!(await link.ensure()).delegating) return legacyLease(payload);
35
+ const p = (payload ?? {}) as { account?: unknown; op?: unknown };
36
+ if (typeof p.account !== "string" || !p.account.trim() || !isOp(p.op)) throw new Error("bad_request: expected {account, op}");
37
+ return DELEGATE;
36
38
  },
37
- });
39
+ { hubLocalOnly: true },
40
+ );
41
+ // Secret-free account list for `gmail_accounts` and account-required errors.
42
+ ctx.registerPiRequestHandler?.(
43
+ ACCOUNTS_TYPE,
44
+ async () => ((await link.ensure()).delegating ? DELEGATE : (await store.list()).map(summarize)),
45
+ { hubLocalOnly: true },
46
+ );
47
+ await mountGmailRoutes(ctx.fastify, { networkGuard: ctx.networkGuard, link });
38
48
  }
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * `gmail/lease` request handler (design D4/D5). Authorizes on the ACCOUNT LEVEL
3
- * only (the request lane is private but unauthenticated — any session of this
4
- * user may lease within the level). Returns exactly
3
+ * only; WHO may call is the host lane's job: this handler registers `hubLocalOnly`, so a
4
+ * remote-origin or deprecated-admission session is refused (`origin_denied`) before it runs
5
+ * (change: harden-bridge-session-claim). Returns exactly
5
6
  * `{accessToken, expiresAt, email, tier}` — the refresh token never leaves.
6
7
  *
7
8
  * - tier check (`tierAllows`) then granted-scope check (implication table);
@@ -1,211 +1,43 @@
1
1
  /**
2
- * Gmail plugin REST routes (design D3/D4/D7/D9). All under
3
- * `/api/plugins/gmail/`, all behind `networkGuard`, in an encapsulated scope
4
- * with `@fastify/rate-limit` (loopback allow-listed). Tiers: `operate`
5
- * (`packages/shared/src/route-tiers.ts`). Responses NEVER carry tokens or the
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.
2
+ * Gmail plugin REST routes (add-google-connect D10). Account, client and setup management moved to
3
+ * Google Connect (`/api/plugins/google/*`): every management route here answers a fixed refusal and
4
+ * stores nothing — `410 { error: "moved" }` while Google Connect is usable, `503
5
+ * { error: "google_connect_unavailable" }` while it is not (Gmail tools keep working from the plugin's own
6
+ * data). `GET /state` stays: it tells the settings section which notice to show. All routes sit behind
7
+ * `networkGuard` in an encapsulated scope with `@fastify/rate-limit` (loopback allow-listed); tiers
8
+ * `operate` (`packages/shared/src/route-tiers.ts`). See change: add-google-connect.
9
9
  */
10
-
11
- import type {
12
- PluginNetworkGuard,
13
- PluginOAuth,
14
- } from "@blackbelt-technology/dashboard-plugin-runtime/server";
10
+ import type { PluginNetworkGuard } from "@blackbelt-technology/dashboard-plugin-runtime/server";
15
11
  import rateLimit from "@fastify/rate-limit";
16
12
  import type { FastifyInstance, FastifyReply } from "fastify";
17
- import type { GoogleEndpoints } from "../shared/endpoints.js";
18
- import { knownFlowCode } from "../shared/flow-codes.js";
19
- import { isTier, scopesCoverFilters, scopesCoverTier, TIERS, type Tier } from "../shared/scopes.js";
20
- import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../shared/setup.js";
21
- import { AccountError, type AccountStore, summarize } from "./accounts.js";
22
- import { revokeToken } from "./gmail-rest.js";
23
- import {
24
- createGoogleLoginFlow,
25
- GmailFlowError,
26
- type GoogleLoginOptions, type GoogleSignInResult,
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";
13
+ import type { GoogleLink } from "./google-link.js";
32
14
 
33
15
  export interface GmailRouteDeps {
34
- store: AccountStore;
35
- oauth: PluginOAuth | undefined;
36
- endpoints: GoogleEndpoints;
37
16
  networkGuard: PluginNetworkGuard;
38
- logger: { info(m: string): void; warn(m: string): void };
39
- fetchImpl?: typeof fetch;
40
- createCallback?: GoogleLoginOptions["createCallback"];
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">;
17
+ link: GoogleLink;
51
18
  }
52
19
 
53
20
  const PREFIX = "/api/plugins/gmail";
54
21
 
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
-
83
- function accountErrorStatus(err: AccountError): number {
84
- if (err.code === "not_found") return 404;
85
- if (err.code === "alias_taken" || err.code === "ambiguous") return 409;
86
- return 400;
87
- }
88
-
89
- function sendError(reply: FastifyReply, err: unknown) {
90
- if (err instanceof AccountError) {
91
- return reply.code(accountErrorStatus(err)).send({ error: err.code, message: err.message });
92
- }
93
- const code = (err as { code?: unknown })?.code;
94
- return reply
95
- .code(502)
96
- .send({ error: typeof code === "string" && /^[a-z_]{1,64}$/.test(code) ? code : "internal_error" });
97
- }
22
+ /** Every management route of the pre-Google-Connect plugin, by method (paths are relative to {@link PREFIX}). */
23
+ const MOVED_ROUTES: ReadonlyArray<{ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; url: string }> = [
24
+ { method: "PUT", url: "/client" },
25
+ { method: "PUT", url: "/setup" },
26
+ { method: "GET", url: "/accounts" },
27
+ { method: "POST", url: "/accounts" },
28
+ { method: "PATCH", url: "/accounts/:sub" },
29
+ { method: "DELETE", url: "/accounts/:sub" },
30
+ { method: "POST", url: "/accounts/:sub/level" },
31
+ { method: "POST", url: "/accounts/:sub/reauth" },
32
+ { method: "POST", url: "/accounts/:sub/filters" },
33
+ { method: "POST", url: "/setup/run" },
34
+ { method: "GET", url: "/setup/run/:id" },
35
+ { method: "POST", url: "/setup/run/:id/continue" },
36
+ { method: "POST", url: "/setup/run/:id/takeover" },
37
+ { method: "DELETE", url: "/setup/run/:id" },
38
+ ];
98
39
 
99
40
  export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRouteDeps): Promise<void> {
100
- const { store, endpoints, logger } = deps;
101
- const newId = deps.newId ?? (() => crypto.randomUUID());
102
-
103
- /** Start a sign-in flow for `tier`; `expectSub` set for re-auth / level raise. */
104
- async function startSignIn(
105
- reply: FastifyReply,
106
- tier: Tier,
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 },
110
- ) {
111
- if (!deps.oauth) return reply.code(501).send({ error: "oauth_unavailable" });
112
- const client = await store.getClient();
113
- if (!client) return reply.code(409).send({ error: "no_client" });
114
- // One failure, one warn line: a login throwing before its first event also
115
- // rejects startFlow (login_failed), so whichever site logs first wins.
116
- // The line carries an allow-listed code only (improve-gmail-settings-ux D3).
117
- let logged = false;
118
- const logFailure = (err: unknown) => {
119
- if (logged) return;
120
- logged = true;
121
- logger.warn(`[gmail] sign-in failed: ${knownFlowCode((err as { code?: unknown } | null)?.code) ?? "sign_in_failed"}`);
122
- };
123
- const googleFlow = createGoogleLoginFlow({
124
- client,
125
- endpoints,
126
- tier,
127
- filters: opts?.filters === true,
128
- loginHint: expect?.email ?? opts?.loginHint,
129
- fetchImpl: deps.fetchImpl,
130
- createCallback: deps.createCallback,
131
- });
132
- const loginFlow = {
133
- ...googleFlow,
134
- login: async (ix: Parameters<typeof googleFlow.login>[0]) => {
135
- try {
136
- return await googleFlow.login(ix);
137
- } catch (err) {
138
- logFailure(err);
139
- throw err;
140
- }
141
- },
142
- };
143
- try {
144
- return await deps.oauth.startFlow({
145
- key: expect ? `reauth-${expect.sub}` : `add-${newId()}`,
146
- loginFlow,
147
- persist: async (credential) => {
148
- try {
149
- const c = credential as GoogleSignInResult;
150
- if (expect && c.sub !== expect.sub) throw new GmailFlowError("account_mismatch");
151
- // Consent-screen checkboxes can be cleared: never store a level the grant cannot serve.
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
- }
156
- const acct = await store.upsertFromSignIn({
157
- sub: c.sub,
158
- email: c.email,
159
- tier: c.tier,
160
- scopes: c.grantedScopes,
161
- access: c.access,
162
- refresh: c.refresh || undefined,
163
- expires: c.expires,
164
- testingHint: c.testingHint,
165
- filters: opts?.filters,
166
- });
167
- logger.info(`[gmail] sign-in ${acct.email} tier=${acct.tier}: ok`);
168
- } catch (err) {
169
- logFailure(err);
170
- throw err;
171
- }
172
- },
173
- });
174
- } catch (err) {
175
- logFailure(err);
176
- return sendError(reply, err);
177
- }
178
- }
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
-
209
41
  await fastify.register(async (scope) => {
210
42
  await scope.register(rateLimit, {
211
43
  global: true,
@@ -215,108 +47,17 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
215
47
  });
216
48
  const guarded = { preHandler: deps.networkGuard };
217
49
 
218
- scope.get(`${PREFIX}/state`, guarded, async (request) => {
219
- const client = await store.getClient();
220
- return {
221
- client: client ? { configured: true, clientId: client.clientId, projectId: client.projectId } : { configured: false },
222
- accounts: (await store.list()).map(summarize),
223
- setup: readSetup(),
224
- autoSetup: await autoSetupState(request, setupRoutes),
225
- };
50
+ scope.get(`${PREFIX}/state`, guarded, async () => {
51
+ const { usable } = await deps.link.ensure();
52
+ return usable ? { moved: true } : { moved: false, googleConnect: "unavailable" };
226
53
  });
227
54
 
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
-
241
- scope.put(`${PREFIX}/client`, guarded, async (request, reply) => {
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 });
244
- return { ok: true, clientId: result.client.clientId, projectId: result.client.projectId };
245
- });
246
-
247
- scope.post(`${PREFIX}/accounts`, guarded, async (request, reply) => {
248
- const body = (request.body ?? {}) as { tier?: unknown; email?: unknown };
249
- const tier = body.tier ?? "readonly";
250
- if (!isTier(tier)) return reply.code(400).send({ error: "invalid_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 });
255
- });
256
-
257
- scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/level`, guarded, async (request, reply) => {
258
- const tier = (request.body as { tier?: unknown } | null)?.tier;
259
- if (!isTier(tier)) return reply.code(400).send({ error: "invalid_tier" });
260
- const acct = await store.get(request.params.sub);
261
- if (!acct) return reply.code(404).send({ error: "not_found" });
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) {
273
- const next = await store.setTier(acct.sub, tier);
274
- logger.info(`[gmail] level ${next.email} → ${tier}`);
275
- return { applied: true, account: summarize(next) };
276
- }
277
- return startSignIn(reply, tier, { sub: acct.sub, email: acct.email }, { filters: acct.filters === true });
278
- });
279
-
280
- scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/reauth`, guarded, async (request, reply) => {
281
- const acct = await store.get(request.params.sub);
282
- if (!acct) return reply.code(404).send({ error: "not_found" });
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 });
298
- });
299
-
300
- scope.patch<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
301
- const body = (request.body ?? {}) as { alias?: unknown };
302
- if (body.alias !== null && body.alias !== undefined && typeof body.alias !== "string") {
303
- return reply.code(400).send({ error: "invalid_alias" });
304
- }
305
- try {
306
- const next = await store.setAlias(request.params.sub, (body.alias as string | null) ?? undefined);
307
- return { account: summarize(next) };
308
- } catch (err) {
309
- return sendError(reply, err);
310
- }
311
- });
312
-
313
- scope.delete<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
314
- const acct = await store.get(request.params.sub);
315
- if (!acct) return reply.code(404).send({ error: "not_found" });
316
- const remoteRevoked = await revokeToken(endpoints, acct.refresh, deps.fetchImpl);
317
- await store.remove(acct.sub);
318
- logger.info(`[gmail] revoke ${acct.email}: local ok, remote ${remoteRevoked ? "ok" : "failed"}`);
319
- return { removed: true, remoteRevoked };
320
- });
55
+ const refuse = async (_request: unknown, reply: FastifyReply) => {
56
+ const { usable } = await deps.link.ensure();
57
+ return usable
58
+ ? reply.code(410).send({ error: "moved" })
59
+ : reply.code(503).send({ error: "google_connect_unavailable" });
60
+ };
61
+ for (const { method, url } of MOVED_ROUTES) scope.route({ method, url: `${PREFIX}${url}`, preHandler: deps.networkGuard, handler: refuse });
321
62
  });
322
63
  }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Validate an uploaded `client_secret_*.json` (design D7 step 5). Only a
3
3
  * Desktop client (`installed` block) is accepted; a `web` block is rejected with
4
- * step-4 guidance. Pure — used by the wizard (instant feedback) AND the server
5
- * route (authoritative). See change: add-gmail-plugin.
4
+ * step-4 guidance. Pure. The setup wizard now lives in the Google accounts plugin
5
+ * (Settings → Google accounts). See change: add-gmail-plugin.
6
6
  */
7
7
 
8
8
  import { PROJECT_ID_RE } from "./setup.js";
@@ -7,6 +7,24 @@ export const PLUGIN_ID = "gmail";
7
7
  export const LEASE_TYPE = "gmail/lease";
8
8
  export const ACCOUNTS_TYPE = "gmail/accounts";
9
9
 
10
+ /**
11
+ * Google Connect (add-google-connect D1/D10): the only in-process service Gmail consumes, and the lanes
12
+ * it follows a delegation to. The provider id is checked — a spoofing plugin is ignored.
13
+ */
14
+ export const GOOGLE_PLUGIN_ID = "google";
15
+ export const GOOGLE_CONNECT_SERVICE = "google.connect";
16
+ export const GOOGLE_LEASE_TYPE = "google/lease";
17
+ export const GOOGLE_ACCOUNTS_TYPE = "google/accounts";
18
+
19
+ /** `gmail/lease` / `gmail/accounts` reply while Google Connect owns the accounts: follow it, no token inside. */
20
+ export interface DelegateReply {
21
+ delegate: typeof GOOGLE_PLUGIN_ID;
22
+ }
23
+
24
+ export function isDelegateReply(v: unknown): v is DelegateReply {
25
+ return !!v && typeof v === "object" && !Array.isArray(v) && (v as { delegate?: unknown }).delegate === GOOGLE_PLUGIN_ID;
26
+ }
27
+
10
28
  /** `gmail/lease` success reply — exactly these keys, never a refresh token. */
11
29
  export interface LeaseReply {
12
30
  accessToken: string;
@@ -7,7 +7,7 @@
7
7
  export type Tier = "readonly" | "draft" | "send";
8
8
  export type Op = "read" | "draft" | "send" | "modify" | "trash" | "filters_read" | "filters_write";
9
9
 
10
- export const TIERS: readonly Tier[] = ["readonly", "draft", "send"];
10
+ const TIERS: readonly Tier[] = ["readonly", "draft", "send"];
11
11
 
12
12
  const SCOPE_BASE = "https://www.googleapis.com/auth/";
13
13
  export const SCOPE = {
@@ -87,7 +87,7 @@ export function scopesCover(granted: readonly string[], op: Op): boolean {
87
87
  }
88
88
 
89
89
  /** True when the granted scopes cover every op of `tier` (no re-consent needed). */
90
- export function scopesCoverTier(granted: readonly string[], tier: Tier): boolean {
90
+ function scopesCoverTier(granted: readonly string[], tier: Tier): boolean {
91
91
  const eff = effectiveScopes(granted);
92
92
  return TIER_SCOPES[tier].every((s) => eff.has(s));
93
93
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Setup-field validators shared by the wizard (instant feedback) and the
3
- * server route (authoritative): project id and owner account. Pure.
2
+ * Setup-field validators (project id, owner account). Pure. The setup wizard now lives
3
+ * in the Google accounts plugin (Settings → Google accounts); kept for legacy-import code.
4
4
  * See change: improve-gmail-plugin-setup-ux.
5
5
  */
6
6