@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.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.
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Account store over `ctx.credentials` namespace `gmail` (design D2).
3
+ * Records: `client` → OAuth client; `acct:<sub>` → one account. Resolution uses
4
+ * ONE `snapshot()` read; every write goes through `update()` (atomic RMW) so a
5
+ * concurrent refresh / re-auth / level change never clobbers another.
6
+ * See change: add-gmail-plugin.
7
+ */
8
+ import type {
9
+ PluginCredentialRecord,
10
+ PluginCredentials,
11
+ } from "@blackbelt-technology/dashboard-plugin-runtime/server";
12
+ import { isTier, type Tier } from "../shared/scopes.js";
13
+
14
+ export const CLIENT_KEY = "client";
15
+ const ACCT_PREFIX = "acct:";
16
+
17
+ type AccountStatus = "ok" | "reauth_required";
18
+
19
+ export interface ClientRecord {
20
+ clientId: string;
21
+ clientSecret: string;
22
+ projectId?: string;
23
+ }
24
+
25
+ export interface AccountRecord {
26
+ sub: string;
27
+ email: string;
28
+ alias?: string;
29
+ tier: Tier;
30
+ scopes: string[];
31
+ refresh: string;
32
+ access: string;
33
+ expires: number;
34
+ status: AccountStatus;
35
+ testingHint?: boolean;
36
+ addedAt: number;
37
+ }
38
+
39
+ /** Public (secret-free) account view for the panel and `gmail_accounts`. */
40
+ export interface AccountSummary {
41
+ sub: string;
42
+ email: string;
43
+ alias?: string;
44
+ tier: Tier;
45
+ status: AccountStatus;
46
+ testingHint?: boolean;
47
+ addedAt: number;
48
+ }
49
+
50
+ export class AccountError extends Error {
51
+ constructor(
52
+ readonly code:
53
+ | "not_found"
54
+ | "ambiguous"
55
+ | "alias_taken"
56
+ | "invalid_alias"
57
+ | "missing_refresh"
58
+ | "no_client",
59
+ message: string,
60
+ ) {
61
+ super(message);
62
+ this.name = "AccountError";
63
+ }
64
+ }
65
+
66
+ export const acctKey = (sub: string): string => `${ACCT_PREFIX}${sub}`;
67
+
68
+ function asAccount(rec: PluginCredentialRecord | undefined): AccountRecord | undefined {
69
+ if (!rec || typeof rec.sub !== "string" || typeof rec.email !== "string" || !isTier(rec.tier)) {
70
+ return undefined;
71
+ }
72
+ return rec as unknown as AccountRecord;
73
+ }
74
+
75
+ export function summarize(a: AccountRecord): AccountSummary {
76
+ const s: AccountSummary = { sub: a.sub, email: a.email, tier: a.tier, status: a.status, addedAt: a.addedAt };
77
+ if (a.alias) s.alias = a.alias;
78
+ if (a.testingHint) s.testingHint = true;
79
+ return s;
80
+ }
81
+
82
+ const ALIAS_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/i;
83
+
84
+ /** Human-readable label list used in not-found / ambiguity errors. */
85
+ function labels(accounts: AccountRecord[]): string {
86
+ if (accounts.length === 0) return "none connected";
87
+ return accounts.map((a) => (a.alias ? `${a.alias} (${a.email})` : a.email)).join(", ");
88
+ }
89
+
90
+ export class AccountStore {
91
+ /** Serializes alias check+write: the store's `update()` is per-key, uniqueness is cross-key. */
92
+ private aliasChain: Promise<unknown> = Promise.resolve();
93
+
94
+ constructor(private readonly creds: PluginCredentials) {}
95
+
96
+ async getClient(): Promise<ClientRecord | undefined> {
97
+ const rec = await this.creds.get(CLIENT_KEY);
98
+ if (!rec || typeof rec.clientId !== "string" || typeof rec.clientSecret !== "string") return undefined;
99
+ return rec as unknown as ClientRecord;
100
+ }
101
+
102
+ async setClient(client: ClientRecord): Promise<void> {
103
+ await this.creds.set(CLIENT_KEY, { ...client });
104
+ }
105
+
106
+ async list(): Promise<AccountRecord[]> {
107
+ const snap = await this.creds.snapshot();
108
+ return Object.entries(snap)
109
+ .filter(([k]) => k.startsWith(ACCT_PREFIX))
110
+ .map(([, v]) => asAccount(v))
111
+ .filter((a): a is AccountRecord => a !== undefined)
112
+ .sort((a, b) => a.addedAt - b.addedAt);
113
+ }
114
+
115
+ async get(sub: string): Promise<AccountRecord | undefined> {
116
+ return asAccount(await this.creds.get(acctKey(sub)));
117
+ }
118
+
119
+ /**
120
+ * Resolve `ref` from ONE snapshot: alias first (case-insensitive), then email
121
+ * (case-insensitive). Same email on two subs → `ambiguous`. No implicit default.
122
+ */
123
+ async resolve(ref: string): Promise<AccountRecord> {
124
+ const accounts = await this.list();
125
+ const needle = ref.trim().toLowerCase();
126
+ const byAlias = accounts.find((a) => a.alias?.toLowerCase() === needle);
127
+ if (byAlias) return byAlias;
128
+ const byEmail = accounts.filter((a) => a.email.toLowerCase() === needle);
129
+ if (byEmail.length === 1) return byEmail[0] as AccountRecord;
130
+ if (byEmail.length > 1) {
131
+ throw new AccountError(
132
+ "ambiguous",
133
+ `Several connected accounts share ${ref}; set an alias on each in the Gmail panel and use the alias.`,
134
+ );
135
+ }
136
+ throw new AccountError("not_found", `No connected Gmail account matches "${ref}". Known accounts: ${labels(accounts)}.`);
137
+ }
138
+
139
+ /** Set or clear an alias. Aliases are unique (case-insensitive) across accounts. */
140
+ setAlias(sub: string, alias: string | undefined): Promise<AccountRecord> {
141
+ const run = this.aliasChain.then(() => this.setAliasNow(sub, alias));
142
+ this.aliasChain = run.catch(() => {});
143
+ return run;
144
+ }
145
+
146
+ private async setAliasNow(sub: string, alias: string | undefined): Promise<AccountRecord> {
147
+ const next = alias?.trim() || undefined;
148
+ if (next !== undefined && !ALIAS_RE.test(next)) {
149
+ throw new AccountError("invalid_alias", "Alias must be 1–40 letters, digits, '.', '_' or '-'.");
150
+ }
151
+ if (next !== undefined) {
152
+ const clash = (await this.list()).find((a) => a.sub !== sub && a.alias?.toLowerCase() === next.toLowerCase());
153
+ if (clash) throw new AccountError("alias_taken", `Alias "${next}" is already used by ${clash.email}.`);
154
+ }
155
+ return this.patch(sub, (prev) => {
156
+ const { alias: _drop, ...rest } = prev;
157
+ return next === undefined ? rest : { ...rest, alias: next };
158
+ });
159
+ }
160
+
161
+ /** Lower (or set) the tier without re-consent. */
162
+ async setTier(sub: string, tier: Tier): Promise<AccountRecord> {
163
+ return this.patch(sub, (prev) => ({ ...prev, tier }));
164
+ }
165
+
166
+ /** Mark `reauth_required` ONLY while the record still holds the grant that failed (a concurrent re-auth wins). */
167
+ async markReauthIf(sub: string, failedRefresh: string): Promise<boolean> {
168
+ let marked = false;
169
+ await this.creds.update(acctKey(sub), (prev) => {
170
+ if (!prev || prev.refresh !== failedRefresh) return prev;
171
+ marked = true;
172
+ return { ...prev, status: "reauth_required" };
173
+ });
174
+ return marked;
175
+ }
176
+
177
+ /**
178
+ * Store refreshed tokens IF the record still holds `usedRefresh` (merge —
179
+ * never clobbers alias/tier; a concurrent re-auth's new grant wins).
180
+ */
181
+ async storeTokensIf(
182
+ sub: string,
183
+ usedRefresh: string,
184
+ tokens: { access: string; expires: number; refresh?: string },
185
+ ): Promise<void> {
186
+ await this.creds.update(acctKey(sub), (prev) => {
187
+ if (!prev || prev.refresh !== usedRefresh) return prev;
188
+ const out: PluginCredentialRecord = { ...prev, access: tokens.access, expires: tokens.expires };
189
+ if (tokens.refresh) out.refresh = tokens.refresh;
190
+ return out;
191
+ });
192
+ }
193
+
194
+ async remove(sub: string): Promise<void> {
195
+ await this.creds.remove(acctKey(sub));
196
+ }
197
+
198
+ /**
199
+ * Upsert after a sign-in (design D3 persist). Re-auth of a known `sub` merges:
200
+ * keeps alias + addedAt, updates email, tokens, scopes, tier and resets status.
201
+ * A NEW account without a refresh token is rejected (nothing written).
202
+ */
203
+ async upsertFromSignIn(input: {
204
+ sub: string;
205
+ email: string;
206
+ tier: Tier;
207
+ scopes: string[];
208
+ access: string;
209
+ refresh?: string;
210
+ expires: number;
211
+ testingHint?: boolean;
212
+ now?: number;
213
+ }): Promise<AccountRecord> {
214
+ let missingRefresh = false;
215
+ const out = await this.creds.update(acctKey(input.sub), (prev) => {
216
+ const refresh = input.refresh || (typeof prev?.refresh === "string" ? prev.refresh : "");
217
+ if (!refresh) {
218
+ missingRefresh = true;
219
+ return prev;
220
+ }
221
+ const rec: PluginCredentialRecord = {
222
+ ...(prev ?? {}),
223
+ sub: input.sub,
224
+ email: input.email,
225
+ tier: input.tier,
226
+ scopes: [...input.scopes],
227
+ access: input.access,
228
+ refresh,
229
+ expires: input.expires,
230
+ status: "ok",
231
+ addedAt: typeof prev?.addedAt === "number" ? prev.addedAt : (input.now ?? Date.now()),
232
+ };
233
+ if (input.testingHint) rec.testingHint = true;
234
+ else delete rec.testingHint;
235
+ return rec;
236
+ });
237
+ if (missingRefresh) {
238
+ throw new AccountError(
239
+ "missing_refresh",
240
+ "Google returned no refresh token. Revoke this app's access at myaccount.google.com/permissions and retry.",
241
+ );
242
+ }
243
+ return asAccount(out) as AccountRecord;
244
+ }
245
+
246
+ private async patch(
247
+ sub: string,
248
+ fn: (prev: PluginCredentialRecord) => PluginCredentialRecord,
249
+ ): Promise<AccountRecord> {
250
+ let found = true;
251
+ const out = await this.creds.update(acctKey(sub), (prev) => {
252
+ if (!prev) {
253
+ found = false;
254
+ return prev;
255
+ }
256
+ return fn(prev);
257
+ });
258
+ if (!found) throw new AccountError("not_found", "Unknown account.");
259
+ return asAccount(out) as AccountRecord;
260
+ }
261
+ }
@@ -0,0 +1,27 @@
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
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Google sign-in as a `PluginOAuthLoginFlow` (design D3), built on
3
+ * `oauth4webapi` (PKCE, code exchange, id_token claim validation incl. nonce).
4
+ *
5
+ * - Loopback callback (`createLoopbackCallback`, path `/`, owns `state`, closes
6
+ * on `interaction.signal`) raced against a `manual_code` paste prompt.
7
+ * - Pasted redirect: `code` + `state` parsed and compared to `callback.state`
8
+ * (length-checked, constant-time). Errors are FIXED codes — never the input.
9
+ * - The losing branch always has a catch attached (no unhandled rejection).
10
+ * - `email_verified` must be true; no `include_granted_scopes` (installed apps).
11
+ *
12
+ * SECURITY: nothing here logs tokens, codes, the pasted URL or the client secret.
13
+ * See change: add-gmail-plugin.
14
+ */
15
+ import { timingSafeEqual } from "node:crypto";
16
+ import {
17
+ createLoopbackCallback,
18
+ type PluginLoginInteraction,
19
+ type PluginOAuthCredential,
20
+ type PluginOAuthLoginFlow,
21
+ } from "@blackbelt-technology/dashboard-plugin-runtime/server";
22
+ import * as oauth from "oauth4webapi";
23
+ import type { GoogleEndpoints } from "../shared/endpoints.js";
24
+ import { authScopeParam, type Tier } from "../shared/scopes.js";
25
+ import type { ClientRecord } from "./accounts.js";
26
+
27
+ /** Fixed, input-free error codes a flow can fail with (the wizard maps them to steps). */
28
+ export class GmailFlowError extends Error {
29
+ constructor(readonly code: string) {
30
+ super(code);
31
+ this.name = "GmailFlowError";
32
+ }
33
+ }
34
+
35
+ const SAFE_CODE = /^[a-z_]{1,64}$/;
36
+ const safeCode = (v: unknown, fallback: string): string =>
37
+ typeof v === "string" && SAFE_CODE.test(v) ? v : fallback;
38
+
39
+ export interface GoogleSignInResult extends PluginOAuthCredential {
40
+ sub: string;
41
+ email: string;
42
+ grantedScopes: string[];
43
+ tier: Tier;
44
+ testingHint: boolean;
45
+ }
46
+
47
+ type CallbackFactory = typeof createLoopbackCallback;
48
+
49
+ export interface GoogleLoginOptions {
50
+ client: ClientRecord;
51
+ endpoints: GoogleEndpoints;
52
+ tier: Tier;
53
+ /** Email of the account being re-authenticated (sets `login_hint`). */
54
+ loginHint?: string;
55
+ /** Test seam: fetch used for the token endpoint. */
56
+ fetchImpl?: typeof fetch;
57
+ /** Test seam: loopback callback factory. */
58
+ createCallback?: CallbackFactory;
59
+ now?: () => number;
60
+ }
61
+
62
+ function asServer(ep: GoogleEndpoints): oauth.AuthorizationServer {
63
+ return { issuer: ep.issuer, authorization_endpoint: ep.authorize, token_endpoint: ep.token, revocation_endpoint: ep.revoke };
64
+ }
65
+
66
+ /** Options every oauth4webapi request gets (custom fetch + plain-HTTP only under the loopback override). */
67
+ export function requestOptions(ep: GoogleEndpoints, fetchImpl?: typeof fetch, signal?: AbortSignal) {
68
+ const o: Record<string | symbol, unknown> = {};
69
+ if (ep.overridden) o[oauth.allowInsecureRequests] = true;
70
+ if (fetchImpl) o[oauth.customFetch] = fetchImpl;
71
+ if (signal) o.signal = signal;
72
+ return o as oauth.TokenEndpointRequestOptions;
73
+ }
74
+
75
+ export function oauthServer(ep: GoogleEndpoints): oauth.AuthorizationServer {
76
+ return asServer(ep);
77
+ }
78
+
79
+ export function oauthClient(c: ClientRecord): oauth.Client {
80
+ return { client_id: c.clientId };
81
+ }
82
+
83
+ /** Build the authorization URL (design D3 step 2). Pure — test E4. */
84
+ export function buildAuthUrl(p: {
85
+ endpoints: GoogleEndpoints;
86
+ clientId: string;
87
+ redirectUri: string;
88
+ tier: Tier;
89
+ state: string;
90
+ nonce: string;
91
+ codeChallenge: string;
92
+ loginHint?: string;
93
+ }): string {
94
+ const u = new URL(p.endpoints.authorize);
95
+ const q = u.searchParams;
96
+ q.set("client_id", p.clientId);
97
+ q.set("redirect_uri", p.redirectUri);
98
+ q.set("response_type", "code");
99
+ q.set("scope", authScopeParam(p.tier));
100
+ q.set("access_type", "offline");
101
+ q.set("prompt", "consent select_account");
102
+ q.set("state", p.state);
103
+ q.set("nonce", p.nonce);
104
+ q.set("code_challenge", p.codeChallenge);
105
+ q.set("code_challenge_method", "S256");
106
+ if (p.loginHint) q.set("login_hint", p.loginHint);
107
+ return u.toString();
108
+ }
109
+
110
+ function stateEquals(a: string, b: string): boolean {
111
+ const ab = Buffer.from(a);
112
+ const bb = Buffer.from(b);
113
+ return ab.length === bb.length && timingSafeEqual(ab, bb);
114
+ }
115
+
116
+ /**
117
+ * Parse a pasted redirect URL (design D3 step 3). Returns the code, or throws a
118
+ * fixed-code `GmailFlowError` (`invalid_redirect` / `state_mismatch` / a Google
119
+ * error code) that never contains the pasted input. Test E9.
120
+ */
121
+ export function parsePastedRedirect(input: string, expectedState: string): string {
122
+ let u: URL;
123
+ try {
124
+ u = new URL(input.trim());
125
+ } catch {
126
+ throw new GmailFlowError("invalid_redirect");
127
+ }
128
+ const state = u.searchParams.get("state");
129
+ if (!state) throw new GmailFlowError("invalid_redirect");
130
+ if (!stateEquals(state, expectedState)) throw new GmailFlowError("state_mismatch");
131
+ const error = u.searchParams.get("error");
132
+ if (error) throw new GmailFlowError(safeCode(error, "authorization_failed"));
133
+ const code = u.searchParams.get("code");
134
+ if (!code) throw new GmailFlowError("invalid_redirect");
135
+ return code;
136
+ }
137
+
138
+ /** Wait for the loopback callback OR a pasted redirect, whichever comes first. */
139
+ async function waitForCode(
140
+ ix: PluginLoginInteraction,
141
+ cb: Awaited<ReturnType<CallbackFactory>>,
142
+ ): Promise<string> {
143
+ const pasteAbort = new AbortController();
144
+ const fromCallback = cb.waitForCode().then(
145
+ (r) => r.code,
146
+ (err: unknown) => {
147
+ throw new GmailFlowError(safeCode((err as { code?: unknown })?.code, "callback_failed"));
148
+ },
149
+ );
150
+ const fromPaste = ix
151
+ .prompt({
152
+ type: "manual_code",
153
+ message: "Paste the full URL your browser was redirected to (needed when the dashboard runs on another machine)",
154
+ placeholder: "http://127.0.0.1:…/?code=…&state=…",
155
+ signal: pasteAbort.signal,
156
+ })
157
+ .then((input) => parsePastedRedirect(input, cb.state));
158
+ // The loser must never surface as an unhandled rejection.
159
+ fromCallback.catch(() => {});
160
+ fromPaste.catch(() => {});
161
+ try {
162
+ return await Promise.race([fromCallback, fromPaste]);
163
+ } finally {
164
+ pasteAbort.abort();
165
+ cb.close();
166
+ }
167
+ }
168
+
169
+ function tokenError(err: unknown): GmailFlowError {
170
+ if (err instanceof GmailFlowError) return err;
171
+ if (err instanceof oauth.ResponseBodyError) return new GmailFlowError(safeCode(err.error, "token_exchange_failed"));
172
+ if (err instanceof oauth.OperationProcessingError) return new GmailFlowError("id_token_invalid");
173
+ return new GmailFlowError("token_exchange_failed");
174
+ }
175
+
176
+ /** Build the login flow for one add / re-auth / level raise. */
177
+ export function createGoogleLoginFlow(opts: GoogleLoginOptions): PluginOAuthLoginFlow {
178
+ const mkCallback = opts.createCallback ?? createLoopbackCallback;
179
+ const now = opts.now ?? Date.now;
180
+ return {
181
+ name: "Google (Gmail)",
182
+ async login(ix): Promise<GoogleSignInResult> {
183
+ const as = asServer(opts.endpoints);
184
+ const client = oauthClient(opts.client);
185
+ const cb = await mkCallback({ path: "/", signal: ix.signal });
186
+ const verifier = oauth.generateRandomCodeVerifier();
187
+ const nonce = oauth.generateRandomNonce();
188
+ const url = buildAuthUrl({
189
+ endpoints: opts.endpoints,
190
+ clientId: opts.client.clientId,
191
+ redirectUri: cb.redirectUri,
192
+ tier: opts.tier,
193
+ state: cb.state,
194
+ nonce,
195
+ codeChallenge: await oauth.calculatePKCECodeChallenge(verifier),
196
+ loginHint: opts.loginHint,
197
+ });
198
+ ix.notify({
199
+ type: "auth_url",
200
+ url,
201
+ instructions: "Sign in with Google. If the dashboard runs on another machine, paste the final redirect URL below.",
202
+ });
203
+ const code = await waitForCode(ix, cb);
204
+
205
+ let tokens: oauth.TokenEndpointResponse;
206
+ try {
207
+ const params = oauth.validateAuthResponse(as, client, new URLSearchParams({ code, state: cb.state }), cb.state);
208
+ const res = await oauth.authorizationCodeGrantRequest(
209
+ as,
210
+ client,
211
+ oauth.ClientSecretPost(opts.client.clientSecret),
212
+ params,
213
+ cb.redirectUri,
214
+ verifier,
215
+ requestOptions(opts.endpoints, opts.fetchImpl, ix.signal),
216
+ );
217
+ tokens = await oauth.processAuthorizationCodeResponse(as, client, res, {
218
+ expectedNonce: nonce,
219
+ requireIdToken: true,
220
+ });
221
+ } catch (err) {
222
+ throw tokenError(err);
223
+ }
224
+ const claims = oauth.getValidatedIdTokenClaims(tokens);
225
+ if (!claims || typeof claims.sub !== "string" || typeof claims.email !== "string") {
226
+ throw new GmailFlowError("id_token_invalid");
227
+ }
228
+ if (claims.email_verified !== true) throw new GmailFlowError("email_unverified");
229
+ const granted = typeof tokens.scope === "string" ? tokens.scope.split(/\s+/).filter(Boolean) : [];
230
+ return {
231
+ type: "oauth",
232
+ access: tokens.access_token,
233
+ refresh: typeof tokens.refresh_token === "string" ? tokens.refresh_token : "",
234
+ expires: now() + (typeof tokens.expires_in === "number" ? tokens.expires_in : 3600) * 1000,
235
+ sub: claims.sub,
236
+ email: claims.email,
237
+ grantedScopes: granted,
238
+ tier: opts.tier,
239
+ // Google adds `refresh_token_expires_in` only for time-limited (Testing-mode) grants.
240
+ testingHint: typeof (tokens as Record<string, unknown>).refresh_token_expires_in === "number",
241
+ };
242
+ },
243
+ };
244
+ }
@@ -0,0 +1,31 @@
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.
6
+ */
7
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
8
+ import { resolveGoogleEndpoints } from "../shared/endpoints.js";
9
+ import { ACCOUNTS_TYPE, LEASE_TYPE } from "../shared/protocol.js";
10
+ import { AccountStore, summarize } from "./accounts.js";
11
+ import { createLeaseHandler } from "./lease.js";
12
+ import { mountGmailRoutes } from "./routes.js";
13
+
14
+ export default async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
15
+ if (!ctx.credentials) {
16
+ ctx.logger.warn("[gmail] host has no plugin credential store; plugin inactive");
17
+ return;
18
+ }
19
+ const endpoints = resolveGoogleEndpoints(process.env, (m) => ctx.logger.warn(m));
20
+ const store = new AccountStore(ctx.credentials);
21
+ ctx.registerPiRequestHandler?.(LEASE_TYPE, createLeaseHandler({ store, endpoints, logger: ctx.logger }));
22
+ // Secret-free account list for `gmail_accounts` and account-required errors.
23
+ ctx.registerPiRequestHandler?.(ACCOUNTS_TYPE, async () => (await store.list()).map(summarize));
24
+ await mountGmailRoutes(ctx.fastify, {
25
+ store,
26
+ oauth: ctx.oauth,
27
+ endpoints,
28
+ networkGuard: ctx.networkGuard,
29
+ logger: ctx.logger,
30
+ });
31
+ }