@xevrion/gsc-mcp 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +225 -2
- package/dist/analysis.js +405 -0
- package/dist/auth.js +403 -0
- package/dist/dates.js +64 -0
- package/dist/demo.js +330 -0
- package/dist/format.js +55 -0
- package/dist/gsc.js +342 -0
- package/dist/http.js +60 -0
- package/dist/index.js +185 -0
- package/dist/install.js +128 -0
- package/dist/prompts.js +16 -0
- package/dist/server.js +26 -0
- package/dist/tools.js +971 -0
- package/dist/updates.js +17 -0
- package/package.json +54 -4
package/dist/auth.js
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
// Loaded on first use: demo mode and the CLI help never pay for it.
|
|
2
|
+
const gal = () => import("google-auth-library");
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync, chmodSync, readdirSync, statSync } from "node:fs";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { createInterface } from "node:readline/promises";
|
|
10
|
+
export const SCOPE_READ = "https://www.googleapis.com/auth/webmasters.readonly";
|
|
11
|
+
export const SCOPE_WRITE = "https://www.googleapis.com/auth/webmasters";
|
|
12
|
+
export const SCOPE_INDEXING = "https://www.googleapis.com/auth/indexing";
|
|
13
|
+
export class NotConfiguredError extends Error {
|
|
14
|
+
}
|
|
15
|
+
export function configDir() {
|
|
16
|
+
if (process.env.GSC_MCP_CONFIG_DIR)
|
|
17
|
+
return process.env.GSC_MCP_CONFIG_DIR;
|
|
18
|
+
if (process.platform === "win32" && process.env.APPDATA)
|
|
19
|
+
return join(process.env.APPDATA, "gsc-mcp");
|
|
20
|
+
return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "gsc-mcp");
|
|
21
|
+
}
|
|
22
|
+
const storePath = () => join(configDir(), "credentials.json");
|
|
23
|
+
export function readStore() {
|
|
24
|
+
try {
|
|
25
|
+
const data = JSON.parse(readFileSync(storePath(), "utf8"));
|
|
26
|
+
return { profiles: data.profiles ?? {} };
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return { profiles: {} };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function writeStore(store) {
|
|
33
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
34
|
+
writeFileSync(storePath(), JSON.stringify(store, null, 2), { mode: 0o600 });
|
|
35
|
+
chmodSync(storePath(), 0o600);
|
|
36
|
+
}
|
|
37
|
+
export function profileName() {
|
|
38
|
+
return process.env.GSC_PROFILE || "default";
|
|
39
|
+
}
|
|
40
|
+
function fromClient(client, method, canWrite) {
|
|
41
|
+
return { method, canWrite, headers: () => client.getRequestHeaders() };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Credential lookup order:
|
|
45
|
+
* 1. A service account, via GSC_SERVICE_ACCOUNT (path or inline JSON) or GOOGLE_APPLICATION_CREDENTIALS
|
|
46
|
+
* 2. An OAuth profile saved by `gsc-mcp auth`
|
|
47
|
+
* 3. GSC_OAUTH_CLIENT_ID / GSC_OAUTH_CLIENT_SECRET / GSC_OAUTH_REFRESH_TOKEN from the environment
|
|
48
|
+
* 4. Application Default Credentials (gcloud)
|
|
49
|
+
*/
|
|
50
|
+
export async function resolveAuth(name = profileName()) {
|
|
51
|
+
const { GoogleAuth, OAuth2Client } = await gal();
|
|
52
|
+
const wantWrite = writesEnabled();
|
|
53
|
+
const scopes = wantWrite ? [SCOPE_WRITE, SCOPE_INDEXING] : [SCOPE_READ];
|
|
54
|
+
const sa = process.env.GSC_SERVICE_ACCOUNT || process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
55
|
+
if (sa) {
|
|
56
|
+
const trimmed = sa.trim();
|
|
57
|
+
const auth = trimmed.startsWith("{")
|
|
58
|
+
? new GoogleAuth({ credentials: JSON.parse(trimmed), scopes })
|
|
59
|
+
: new GoogleAuth({ keyFile: trimmed, scopes });
|
|
60
|
+
const client = await auth.getClient();
|
|
61
|
+
const email = (await auth.getCredentials()).client_email;
|
|
62
|
+
return fromClient(client, `service account${email ? ` (${email})` : ""}`, true);
|
|
63
|
+
}
|
|
64
|
+
const profile = readStore().profiles[name];
|
|
65
|
+
if (profile) {
|
|
66
|
+
const client = new OAuth2Client(profile.client_id, profile.client_secret);
|
|
67
|
+
client.setCredentials({ refresh_token: profile.refresh_token });
|
|
68
|
+
return fromClient(client, `OAuth profile "${name}"${profile.email ? ` (${profile.email})` : ""}`, profile.scope.split(/\s+/).includes(SCOPE_WRITE));
|
|
69
|
+
}
|
|
70
|
+
const { GSC_OAUTH_CLIENT_ID: id, GSC_OAUTH_CLIENT_SECRET: secret, GSC_OAUTH_REFRESH_TOKEN: refresh } = process.env;
|
|
71
|
+
if (id && secret && refresh) {
|
|
72
|
+
const client = new OAuth2Client(id, secret);
|
|
73
|
+
client.setCredentials({ refresh_token: refresh });
|
|
74
|
+
return fromClient(client, "OAuth refresh token from environment", "unknown");
|
|
75
|
+
}
|
|
76
|
+
// Only try Application Default Credentials when they plausibly exist. Otherwise
|
|
77
|
+
// the library probes the cloud metadata server and stalls for seconds first.
|
|
78
|
+
const gcloudDir = process.env.CLOUDSDK_CONFIG || join(process.platform === "win32" ? process.env.APPDATA ?? "" : join(homedir(), ".config"), "gcloud");
|
|
79
|
+
const adcFile = join(gcloudDir, "application_default_credentials.json");
|
|
80
|
+
const onCloud = !!(process.env.K_SERVICE || process.env.GOOGLE_CLOUD_PROJECT || process.env.GCE_METADATA_HOST);
|
|
81
|
+
if (existsSync(adcFile) || onCloud)
|
|
82
|
+
try {
|
|
83
|
+
const auth = new GoogleAuth({ scopes });
|
|
84
|
+
const client = await auth.getClient();
|
|
85
|
+
await client.getAccessToken();
|
|
86
|
+
return fromClient(client, "Application Default Credentials", "unknown");
|
|
87
|
+
}
|
|
88
|
+
catch { }
|
|
89
|
+
{
|
|
90
|
+
throw new NotConfiguredError([
|
|
91
|
+
"Google Search Console is not connected yet.",
|
|
92
|
+
"Run this once in a terminal, it opens your browser to sign in:",
|
|
93
|
+
"",
|
|
94
|
+
" npx -y @xevrion/gsc-mcp auth",
|
|
95
|
+
"",
|
|
96
|
+
"Or set GSC_SERVICE_ACCOUNT to a service account key file. See https://github.com/xevrion/gsc-mcp#authentication",
|
|
97
|
+
].join("\n"));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export function writesEnabled() {
|
|
101
|
+
return /^(1|true|yes)$/i.test(process.env.GSC_ALLOW_WRITES ?? "");
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Lazily resolves credentials on first use, so the server starts (and can explain
|
|
105
|
+
* itself) without any. When several OAuth profiles are saved and no single one
|
|
106
|
+
* is pinned with GSC_PROFILE, every profile is offered and each property is
|
|
107
|
+
* served by whichever account can see it.
|
|
108
|
+
*/
|
|
109
|
+
export class LazyAuth {
|
|
110
|
+
pending;
|
|
111
|
+
multi;
|
|
112
|
+
async get() {
|
|
113
|
+
this.pending ??= resolveAuth().catch((e) => {
|
|
114
|
+
this.pending = undefined;
|
|
115
|
+
throw e;
|
|
116
|
+
});
|
|
117
|
+
return this.pending;
|
|
118
|
+
}
|
|
119
|
+
async headers() {
|
|
120
|
+
return (await this.get()).headers();
|
|
121
|
+
}
|
|
122
|
+
async accounts() {
|
|
123
|
+
const pinned = process.env.GSC_PROFILE || process.env.GSC_SERVICE_ACCOUNT || process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
124
|
+
const names = Object.keys(readStore().profiles);
|
|
125
|
+
if (pinned || names.length < 2)
|
|
126
|
+
return [{ name: (await this.get()).method, auth: this }];
|
|
127
|
+
if (!this.multi || Date.now() - this.multi.at > 60_000) {
|
|
128
|
+
const list = await Promise.all(names.map(async (n) => ({ name: n, auth: await resolveAuth(n) })));
|
|
129
|
+
this.multi = { at: Date.now(), list };
|
|
130
|
+
}
|
|
131
|
+
return this.multi.list;
|
|
132
|
+
}
|
|
133
|
+
reset() {
|
|
134
|
+
this.pending = undefined;
|
|
135
|
+
this.multi = undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// The project's own Google OAuth app, so people can just sign in instead of
|
|
139
|
+
// creating a Google Cloud project. The values are injected into the published
|
|
140
|
+
// build by the release workflow (scripts/inject-client.mjs) and are not kept in
|
|
141
|
+
// git. Google documents that installed-app client secrets cannot be kept
|
|
142
|
+
// confidential; what protects users is that only they can approve access on
|
|
143
|
+
// Google's consent screen, and data flows straight from Google to their machine.
|
|
144
|
+
// Builds without them, and GSC_NO_SHARED_CLIENT=1, fall back to your own client.
|
|
145
|
+
const SHARED_CLIENT_ID = "159297266102-lrluoiubp6mmrfsflvreg8bve7ch51id.apps.googleusercontent.com";
|
|
146
|
+
const SHARED_CLIENT_SECRET = "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";
|
|
147
|
+
export function bundledClient() {
|
|
148
|
+
if (/^(1|true|yes)$/i.test(process.env.GSC_NO_SHARED_CLIENT ?? ""))
|
|
149
|
+
return null;
|
|
150
|
+
const client_id = process.env.GSC_BUNDLED_CLIENT_ID || SHARED_CLIENT_ID;
|
|
151
|
+
const client_secret = process.env.GSC_BUNDLED_CLIENT_SECRET || SHARED_CLIENT_SECRET;
|
|
152
|
+
if (client_id.startsWith("__") || client_secret.startsWith("__"))
|
|
153
|
+
return null;
|
|
154
|
+
return { client_id, client_secret, source: "gsc-mcp app" };
|
|
155
|
+
}
|
|
156
|
+
export function readClientFile(path) {
|
|
157
|
+
const data = JSON.parse(readFileSync(path, "utf8"));
|
|
158
|
+
const c = data.installed ?? data.web ?? data;
|
|
159
|
+
if (!c.client_id || !c.client_secret)
|
|
160
|
+
throw new Error(`${path} does not look like an OAuth client JSON (no client_id/client_secret)`);
|
|
161
|
+
return { client_id: c.client_id, client_secret: c.client_secret, source: path };
|
|
162
|
+
}
|
|
163
|
+
/** Newest client_secret*.json in ~/Downloads, which is where Google's "Download JSON" button puts it. */
|
|
164
|
+
export function findDownloadedClient(since = 0) {
|
|
165
|
+
const dir = join(homedir(), "Downloads");
|
|
166
|
+
let best = null;
|
|
167
|
+
try {
|
|
168
|
+
for (const f of readdirSync(dir)) {
|
|
169
|
+
if (!/^client_secret.*\.json$/i.test(f))
|
|
170
|
+
continue;
|
|
171
|
+
const path = join(dir, f);
|
|
172
|
+
const mtime = statSync(path).mtimeMs;
|
|
173
|
+
if (mtime >= since && (!best || mtime > best.mtime))
|
|
174
|
+
best = { path, mtime };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
if (!best)
|
|
181
|
+
return null;
|
|
182
|
+
try {
|
|
183
|
+
return readClientFile(best.path);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const savedClientPath = () => join(configDir(), "client_secret.json");
|
|
190
|
+
export function findClient(opts = {}) {
|
|
191
|
+
if (opts.clientFile)
|
|
192
|
+
return readClientFile(opts.clientFile);
|
|
193
|
+
if (process.env.GSC_OAUTH_CLIENT_ID && process.env.GSC_OAUTH_CLIENT_SECRET)
|
|
194
|
+
return { client_id: process.env.GSC_OAUTH_CLIENT_ID, client_secret: process.env.GSC_OAUTH_CLIENT_SECRET, source: "environment" };
|
|
195
|
+
const existing = readStore().profiles[opts.profile || profileName()];
|
|
196
|
+
if (existing)
|
|
197
|
+
return { client_id: existing.client_id, client_secret: existing.client_secret, source: "saved profile" };
|
|
198
|
+
if (existsSync(savedClientPath())) {
|
|
199
|
+
try {
|
|
200
|
+
return readClientFile(savedClientPath());
|
|
201
|
+
}
|
|
202
|
+
catch { }
|
|
203
|
+
}
|
|
204
|
+
return findDownloadedClient() ?? (opts.ownClient ? null : bundledClient());
|
|
205
|
+
}
|
|
206
|
+
export function saveClient(c) {
|
|
207
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
208
|
+
writeFileSync(savedClientPath(), JSON.stringify({ installed: { client_id: c.client_id, client_secret: c.client_secret } }, null, 2), { mode: 0o600 });
|
|
209
|
+
}
|
|
210
|
+
export const SETUP_STEPS = [
|
|
211
|
+
{ title: "Create a Google Cloud project (any name, free, no billing needed)", url: "https://console.cloud.google.com/projectcreate" },
|
|
212
|
+
{ title: 'Turn on the "Google Search Console API"', url: "https://console.cloud.google.com/apis/library/searchconsole.googleapis.com" },
|
|
213
|
+
{ title: "Click Get started: app name, your email, Audience External, agree, Create", url: "https://console.cloud.google.com/auth/overview/create" },
|
|
214
|
+
{
|
|
215
|
+
title: "Branding: home page https://github.com/xevrion/gsc-mcp, privacy policy https://github.com/xevrion/gsc-mcp/blob/main/PRIVACY.md, authorised domain github.com, Save",
|
|
216
|
+
url: "https://console.cloud.google.com/auth/branding",
|
|
217
|
+
},
|
|
218
|
+
{ title: 'Audience: click "Publish app" (otherwise Google signs you out every 7 days)', url: "https://console.cloud.google.com/auth/audience" },
|
|
219
|
+
{ title: 'Clients: create a "Desktop app" client, then click "Download JSON"', url: "https://console.cloud.google.com/auth/clients/create" },
|
|
220
|
+
];
|
|
221
|
+
/** Walks a person through creating an OAuth client, then waits for the JSON to show up in Downloads. */
|
|
222
|
+
export async function guidedClientSetup() {
|
|
223
|
+
const startedAt = Date.now() - 60_000;
|
|
224
|
+
log("\nFirst, a one-time setup so Google lets this tool read your Search Console (about 2 minutes, free).\n");
|
|
225
|
+
SETUP_STEPS.forEach((s, i) => log(` ${i + 1}. ${s.title}\n ${s.url}`));
|
|
226
|
+
log("");
|
|
227
|
+
if (process.stdin.isTTY) {
|
|
228
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
229
|
+
for (const [i, s] of SETUP_STEPS.entries()) {
|
|
230
|
+
await rl.question(`Press Enter to open step ${i + 1}: ${s.title} `);
|
|
231
|
+
openBrowser(s.url);
|
|
232
|
+
if (i === SETUP_STEPS.length - 1)
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
rl.close();
|
|
236
|
+
}
|
|
237
|
+
log("\nWaiting for client_secret_....json to appear in your Downloads folder (or paste its path and press Enter)...");
|
|
238
|
+
return new Promise((resolve, reject) => {
|
|
239
|
+
let rl;
|
|
240
|
+
const finish = (c) => {
|
|
241
|
+
clearInterval(timer);
|
|
242
|
+
rl?.close();
|
|
243
|
+
saveClient(c);
|
|
244
|
+
log(`Found OAuth client in ${c.source}`);
|
|
245
|
+
resolve(c);
|
|
246
|
+
};
|
|
247
|
+
const timer = setInterval(() => {
|
|
248
|
+
const c = findDownloadedClient(startedAt);
|
|
249
|
+
if (c)
|
|
250
|
+
finish(c);
|
|
251
|
+
}, 1000);
|
|
252
|
+
if (process.stdin.isTTY) {
|
|
253
|
+
rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
254
|
+
rl.on("line", (line) => {
|
|
255
|
+
const path = line.trim().replace(/^['"]|['"]$/g, "").replace(/^~/, homedir());
|
|
256
|
+
if (!path)
|
|
257
|
+
return;
|
|
258
|
+
try {
|
|
259
|
+
finish(readClientFile(path));
|
|
260
|
+
}
|
|
261
|
+
catch (e) {
|
|
262
|
+
log(e.message);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
setTimeout(() => {
|
|
267
|
+
clearInterval(timer);
|
|
268
|
+
rl?.close();
|
|
269
|
+
reject(new Error("Gave up waiting for the OAuth client JSON after 15 minutes"));
|
|
270
|
+
}, 900_000).unref();
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
export function openBrowser(url) {
|
|
274
|
+
if (process.env.GSC_NO_BROWSER)
|
|
275
|
+
return;
|
|
276
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
277
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url.replace(/&/g, "^&")] : [url];
|
|
278
|
+
try {
|
|
279
|
+
spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => { }).unref();
|
|
280
|
+
}
|
|
281
|
+
catch { }
|
|
282
|
+
}
|
|
283
|
+
function log(s) {
|
|
284
|
+
process.stderr.write(s + "\n");
|
|
285
|
+
}
|
|
286
|
+
let activeLogin;
|
|
287
|
+
/**
|
|
288
|
+
* Starts the browser sign-in and resolves once Google redirects back to the
|
|
289
|
+
* local loopback server. Single-flight: concurrent callers share one flow.
|
|
290
|
+
*/
|
|
291
|
+
export async function startLogin(opts) {
|
|
292
|
+
if (activeLogin)
|
|
293
|
+
return activeLogin;
|
|
294
|
+
const name = opts.profile || profileName();
|
|
295
|
+
const client = opts.client;
|
|
296
|
+
const scope = opts.write ? `${SCOPE_WRITE} ${SCOPE_INDEXING}` : SCOPE_READ;
|
|
297
|
+
const state = randomUUID();
|
|
298
|
+
let resolveUrl;
|
|
299
|
+
const urlReady = new Promise((r) => (resolveUrl = r));
|
|
300
|
+
const done = new Promise((resolve, reject) => {
|
|
301
|
+
let oauth;
|
|
302
|
+
let verifier = "";
|
|
303
|
+
let redirectUri = "";
|
|
304
|
+
const timeout = setTimeout(() => {
|
|
305
|
+
server.close();
|
|
306
|
+
reject(new Error("Timed out waiting for Google sign-in (10 minutes)"));
|
|
307
|
+
}, 600_000);
|
|
308
|
+
timeout.unref();
|
|
309
|
+
const server = createServer(async (req, res) => {
|
|
310
|
+
const url = new URL(req.url ?? "/", redirectUri);
|
|
311
|
+
if (url.pathname !== "/callback") {
|
|
312
|
+
res.writeHead(404).end();
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const err = url.searchParams.get("error");
|
|
316
|
+
const code = url.searchParams.get("code");
|
|
317
|
+
const page = (title, body, status = 200) => {
|
|
318
|
+
res.writeHead(status, { "content-type": "text/html; charset=utf-8" });
|
|
319
|
+
res.end(`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>gsc-mcp</title><body style="font:16px/1.5 system-ui;display:grid;place-items:center;min-height:90vh;margin:0;background:#fafafa;color:#111"><div style="max-width:28rem;padding:2rem;text-align:center"><h2 style="margin:0 0 .5rem">${title}</h2><p style="color:#555">${body}</p></div>`);
|
|
320
|
+
};
|
|
321
|
+
if (err || !code || url.searchParams.get("state") !== state) {
|
|
322
|
+
page("Sign-in did not finish", escapeHtml(err ?? "The sign-in link was stale. Run the command again."), 400);
|
|
323
|
+
clearTimeout(timeout);
|
|
324
|
+
server.close();
|
|
325
|
+
reject(new Error(`Sign-in failed: ${err ?? "state mismatch"}`));
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
const { tokens } = await oauth.getToken({ code, codeVerifier: verifier, redirect_uri: redirectUri });
|
|
330
|
+
if (!tokens.refresh_token)
|
|
331
|
+
throw new Error("Google did not return a refresh token. Remove the app at https://myaccount.google.com/permissions and try again.");
|
|
332
|
+
let email;
|
|
333
|
+
if (tokens.id_token) {
|
|
334
|
+
try {
|
|
335
|
+
email = JSON.parse(Buffer.from(tokens.id_token.split(".")[1], "base64url").toString()).email;
|
|
336
|
+
}
|
|
337
|
+
catch { }
|
|
338
|
+
}
|
|
339
|
+
const store = readStore();
|
|
340
|
+
store.profiles[name] = { type: "oauth", client_id: client.client_id, client_secret: client.client_secret, refresh_token: tokens.refresh_token, scope, email, created: new Date().toISOString() };
|
|
341
|
+
writeStore(store);
|
|
342
|
+
page("Search Console connected", `Signed in${email ? ` as <b>${escapeHtml(email)}</b>` : ""}. You can close this tab and go back to your AI assistant.`);
|
|
343
|
+
resolve({ profile: name, email, path: storePath(), scope });
|
|
344
|
+
}
|
|
345
|
+
catch (e) {
|
|
346
|
+
page("Sign-in failed", escapeHtml(e.message), 500);
|
|
347
|
+
reject(e);
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
clearTimeout(timeout);
|
|
351
|
+
server.close();
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
server.on("error", reject);
|
|
355
|
+
server.listen(0, "127.0.0.1", async () => {
|
|
356
|
+
const { OAuth2Client } = await gal();
|
|
357
|
+
redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
|
|
358
|
+
oauth = new OAuth2Client({ clientId: client.client_id, clientSecret: client.client_secret, redirectUri });
|
|
359
|
+
const pkce = await oauth.generateCodeVerifierAsync();
|
|
360
|
+
verifier = pkce.codeVerifier;
|
|
361
|
+
const authUrl = oauth.generateAuthUrl({
|
|
362
|
+
access_type: "offline",
|
|
363
|
+
prompt: "consent",
|
|
364
|
+
scope: [...scope.split(" "), "openid", "email"],
|
|
365
|
+
state,
|
|
366
|
+
code_challenge: pkce.codeChallenge,
|
|
367
|
+
code_challenge_method: "S256",
|
|
368
|
+
});
|
|
369
|
+
resolveUrl(authUrl);
|
|
370
|
+
});
|
|
371
|
+
}).finally(() => {
|
|
372
|
+
activeLogin = undefined;
|
|
373
|
+
});
|
|
374
|
+
done.catch(() => { });
|
|
375
|
+
const authUrl = await urlReady;
|
|
376
|
+
if (opts.openBrowser !== false)
|
|
377
|
+
openBrowser(authUrl);
|
|
378
|
+
activeLogin = { authUrl, done };
|
|
379
|
+
return activeLogin;
|
|
380
|
+
}
|
|
381
|
+
function escapeHtml(s) {
|
|
382
|
+
return s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
383
|
+
}
|
|
384
|
+
export async function login(opts) {
|
|
385
|
+
const client = findClient(opts) ?? (await guidedClientSetup());
|
|
386
|
+
const { authUrl, done } = await startLogin({ client, write: opts.write, profile: opts.profile, openBrowser: !opts.noBrowser });
|
|
387
|
+
log(opts.noBrowser ? `\nOpen this link to sign in with Google:\n\n${authUrl}\n` : `\nSign in with Google in the browser window that just opened. If nothing opened, visit:\n\n${authUrl}\n`);
|
|
388
|
+
log(client.source === "gsc-mcp app"
|
|
389
|
+
? 'If Google says "Google hasn\'t verified this app", click Advanced, then "Go to gsc-mcp (unsafe)". Verification is in progress; gsc-mcp only asks to read Search Console and your data goes straight to this computer.\n'
|
|
390
|
+
: 'If Google says "Google hasn\'t verified this app", click Advanced, then "Go to ... (unsafe)". It is your own app.\n');
|
|
391
|
+
return done;
|
|
392
|
+
}
|
|
393
|
+
export function logout(name = profileName()) {
|
|
394
|
+
const store = readStore();
|
|
395
|
+
if (!store.profiles[name])
|
|
396
|
+
return false;
|
|
397
|
+
delete store.profiles[name];
|
|
398
|
+
writeStore(store);
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
export function hasStoredFile() {
|
|
402
|
+
return existsSync(storePath());
|
|
403
|
+
}
|
package/dist/dates.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export const RANGE_PRESETS = ["last7d", "last28d", "last3m", "last6m", "last12m", "last16m"];
|
|
2
|
+
const PRESET_DAYS = {
|
|
3
|
+
last7d: 7,
|
|
4
|
+
last28d: 28,
|
|
5
|
+
last3m: 90,
|
|
6
|
+
last6m: 180,
|
|
7
|
+
last12m: 365,
|
|
8
|
+
last16m: 486,
|
|
9
|
+
};
|
|
10
|
+
const DAY = 86_400_000;
|
|
11
|
+
// Search Console reports in Pacific time and finalized data trails by roughly
|
|
12
|
+
// two to three days, so ranges end three days back unless fresh data is asked for.
|
|
13
|
+
export const DATA_LAG_DAYS = 3;
|
|
14
|
+
export function fmt(d) {
|
|
15
|
+
return d.toISOString().slice(0, 10);
|
|
16
|
+
}
|
|
17
|
+
export function parse(s) {
|
|
18
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(s))
|
|
19
|
+
throw new Error(`Invalid date "${s}", expected YYYY-MM-DD`);
|
|
20
|
+
const d = new Date(`${s}T00:00:00Z`);
|
|
21
|
+
if (Number.isNaN(d.getTime()))
|
|
22
|
+
throw new Error(`Invalid date "${s}"`);
|
|
23
|
+
return d;
|
|
24
|
+
}
|
|
25
|
+
function pacificToday(now) {
|
|
26
|
+
const s = new Intl.DateTimeFormat("en-CA", { timeZone: "America/Los_Angeles" }).format(now);
|
|
27
|
+
return parse(s);
|
|
28
|
+
}
|
|
29
|
+
export function daysBetween(range) {
|
|
30
|
+
return Math.round((parse(range.endDate).getTime() - parse(range.startDate).getTime()) / DAY) + 1;
|
|
31
|
+
}
|
|
32
|
+
export function resolveRange(opts, now = new Date()) {
|
|
33
|
+
let { startDate, endDate } = opts;
|
|
34
|
+
const range = opts.range?.trim();
|
|
35
|
+
if (range && range.includes(".."))
|
|
36
|
+
[startDate, endDate] = range.split("..").map((x) => x.trim());
|
|
37
|
+
if (startDate || endDate) {
|
|
38
|
+
if (!startDate || !endDate)
|
|
39
|
+
throw new Error('Give a full range like "2026-01-01..2026-01-31"');
|
|
40
|
+
if (parse(startDate) > parse(endDate))
|
|
41
|
+
throw new Error("The start date is after the end date");
|
|
42
|
+
return { startDate, endDate };
|
|
43
|
+
}
|
|
44
|
+
if (range && !RANGE_PRESETS.includes(range))
|
|
45
|
+
throw new Error(`Unknown range "${range}". Use ${RANGE_PRESETS.join(", ")}, or "YYYY-MM-DD..YYYY-MM-DD".`);
|
|
46
|
+
const days = PRESET_DAYS[range || "last28d"];
|
|
47
|
+
const end = new Date(pacificToday(now).getTime() - (opts.fresh ? 1 : DATA_LAG_DAYS) * DAY);
|
|
48
|
+
const start = new Date(end.getTime() - (days - 1) * DAY);
|
|
49
|
+
return { startDate: fmt(start), endDate: fmt(end) };
|
|
50
|
+
}
|
|
51
|
+
export function previousPeriod(range) {
|
|
52
|
+
const len = daysBetween(range);
|
|
53
|
+
const end = new Date(parse(range.startDate).getTime() - DAY);
|
|
54
|
+
const start = new Date(end.getTime() - (len - 1) * DAY);
|
|
55
|
+
return { startDate: fmt(start), endDate: fmt(end) };
|
|
56
|
+
}
|
|
57
|
+
export function yearAgo(range) {
|
|
58
|
+
const shift = (s) => {
|
|
59
|
+
const d = parse(s);
|
|
60
|
+
d.setUTCFullYear(d.getUTCFullYear() - 1);
|
|
61
|
+
return fmt(d);
|
|
62
|
+
};
|
|
63
|
+
return { startDate: shift(range.startDate), endDate: shift(range.endDate) };
|
|
64
|
+
}
|