search-console-axi 0.0.0 → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Laszlo Horanszky
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1 +1,32 @@
1
1
  # search-console-axi
2
+
3
+ [![CI](https://github.com/Dematom1/search-console-axi/actions/workflows/ci.yml/badge.svg)](https://github.com/Dematom1/search-console-axi/actions/workflows/ci.yml) [![Platform: Linux and macOS](https://img.shields.io/badge/platform-Linux%20%7C%20macOS-blue)](#)
4
+
5
+ Read-only Google Search Console reporting and URL inspection for agents. `search-console-axi` is an [AXI](https://github.com/kunchenguid/axi) CLI. Output uses compact [TOON](https://toonformat.dev/) format. Requires Node.js 22.12 or newer.
6
+
7
+ ```sh
8
+ npm install
9
+ npm run build
10
+ node dist/bin/search-console-axi.js --help
11
+ ```
12
+
13
+ ## Authentication
14
+
15
+ The CLI validates credential JSON locally and authenticates through `google-auth-library`. It never stores or prints OAuth tokens or service-account keys. For personal access, create your own Desktop OAuth client and configure ADC with `gcloud auth application-default login --client-id-file=client.json --scopes=https://www.googleapis.com/auth/webmasters.readonly,https://www.googleapis.com/auth/cloud-platform`. Google's built-in `gcloud` OAuth client cannot grant the Search Console scope.
16
+
17
+ ### Service account
18
+
19
+ 1. Create or reuse a Google Cloud project and enable the Google Search Console API.
20
+ 2. Create a service account; it needs no project-level IAM roles.
21
+ 3. Load its JSON key from your secret manager into `SEARCH_CONSOLE_AXI_SA_KEY`. Never commit the key.
22
+ 4. In Search Console, add the service-account email under **Settings > Users and permissions** with Restricted access.
23
+
24
+ For local key files, set `GOOGLE_APPLICATION_CREDENTIALS` or run `node dist/bin/search-console-axi.js setup service-account <key.json>`. Credential precedence is `SEARCH_CONSOLE_AXI_SA_KEY`, `GOOGLE_APPLICATION_CREDENTIALS` (with `google_application_credentials` as a fallback alias), the saved path configured by `setup service-account`, then user ADC. Credential files must contain `authorized_user` or `service_account` JSON; service-account registration and `SEARCH_CONSOLE_AXI_SA_KEY` require `service_account` JSON. To switch from a saved key to ADC, run `node dist/bin/search-console-axi.js setup uninstall`; this also removes the CLI's saved quota-project setting. Set the ADC quota project with `gcloud auth application-default set-quota-project <project>` or use `GOOGLE_CLOUD_QUOTA_PROJECT`.
25
+
26
+ Run `node dist/bin/search-console-axi.js setup` to check credentials and accessible sites. `node dist/bin/search-console-axi.js setup status` reports local credential configuration, not API access or token validity. It includes the credential type and available account email, never credential contents. `node dist/bin/search-console-axi.js setup uninstall` removes only the CLI's local configuration. Registration, saved quota-project updates, and removal re-read the configuration before reporting success.
27
+
28
+ Invalid setup arguments, malformed config, and malformed or unsupported credential data produce `VALIDATION_ERROR` with exit code 2. Config I/O failures produce `CONFIG_ERROR`; missing or unreadable credential-file paths produce `AUTH_CONFIG_ERROR`, both with exit code 1 and repair guidance. `setup status` instead reports invalid config or credentials as `auth.status: invalid` with exit code 0; config I/O failures remain errors. Missing credentials produce setup guidance with `auth.status: not configured` for `setup`, `setup check`, and `setup status`. The default command also reports credential status when credentials cannot be loaded.
29
+
30
+ ## Read Search Console
31
+
32
+ Run `node dist/bin/search-console-axi.js` for the default site's last seven complete days of clicks, impressions, CTR, position, top queries and pages, and low-CTR opportunities. Use `node dist/bin/search-console-axi.js inspect <url> --site <site-url>` to inspect indexing for a URL. Reporting and inspection do not modify Search Console data; setup may write or remove local configuration.
@@ -0,0 +1,375 @@
1
+ import { GoogleAuth, JWT, UserRefreshClient } from "google-auth-library";
2
+ import { encode } from "@toon-format/toon";
3
+ import { AxiError } from "axi-sdk-js";
4
+ import { inspectUrl, runSetupCheck, setupGuide } from "./setup-check.js";
5
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
7
+ import { homedir } from "node:os";
8
+ import { join, resolve } from "node:path";
9
+ const SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"];
10
+ const NO_ADC_MESSAGE = "Could not load the default credentials";
11
+ const NO_CREDENTIALS_GUIDANCE = "No service-account key or user ADC is configured. Load the key JSON into SEARCH_CONSOLE_AXI_SA_KEY or configure your own Desktop OAuth client.";
12
+ const QUOTA_PROJECT_APIS = "Enable the Google Search Console API in the quota project.";
13
+ const configDir = () => process.env["XDG_CONFIG_HOME"]
14
+ ? join(process.env["XDG_CONFIG_HOME"], "search-console-axi")
15
+ : join(homedir(), ".config", "search-console-axi");
16
+ const configFile = () => join(configDir(), "config.json");
17
+ const fail = (message) => {
18
+ throw new AxiError(message, "VALIDATION_ERROR", [
19
+ "Run `search-console-axi setup --help` to see valid actions and options",
20
+ ]);
21
+ };
22
+ const configError = (error, action) => {
23
+ const detail = error instanceof Error ? error.message : String(error);
24
+ return new AxiError(`Could not ${action} Search Console config at ${configFile()}: ${detail}`, "CONFIG_ERROR", [
25
+ `Check that ${configDir()} is writable and the config file is readable, then retry`,
26
+ ]);
27
+ };
28
+ class AuthConfigError extends AxiError {
29
+ kind;
30
+ constructor(kind, message) {
31
+ super(message, kind === "invalid-service-account" || kind === "invalid-credential-file"
32
+ ? "VALIDATION_ERROR"
33
+ : "AUTH_CONFIG_ERROR", [
34
+ kind === "missing-credentials"
35
+ ? NO_CREDENTIALS_GUIDANCE
36
+ : kind === "invalid-credentials-path"
37
+ ? "Check that the credential file exists and is readable"
38
+ : "Provide valid authorized_user or service_account JSON credentials",
39
+ ]);
40
+ this.kind = kind;
41
+ }
42
+ }
43
+ function isObject(value) {
44
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
45
+ }
46
+ function readJsonFile(path, isValid, onFailure, optional = false) {
47
+ let text;
48
+ try {
49
+ text = readFileSync(path, "utf8");
50
+ }
51
+ catch (error) {
52
+ if (optional && error && typeof error === "object" && "code" in error && error.code === "ENOENT")
53
+ return undefined;
54
+ throw onFailure("read", error);
55
+ }
56
+ let value;
57
+ try {
58
+ value = JSON.parse(text);
59
+ }
60
+ catch (error) {
61
+ throw onFailure("parse", error);
62
+ }
63
+ if (!isValid(value))
64
+ throw onFailure("shape", new Error("JSON does not match the expected format"));
65
+ return value;
66
+ }
67
+ function isConfig(value) {
68
+ return (isObject(value) &&
69
+ (!("serviceAccountPath" in value) || typeof value.serviceAccountPath === "string") &&
70
+ (!("quotaProjectId" in value) || typeof value.quotaProjectId === "string"));
71
+ }
72
+ function readConfig() {
73
+ const config = readJsonFile(configFile(), isConfig, (failure, error) => {
74
+ if (failure === "read")
75
+ return configError(error, "read");
76
+ return new AxiError(`Config file ${configFile()} contains invalid ${failure === "parse" ? "JSON" : "format"}`, "VALIDATION_ERROR", ["Repair or remove the invalid config file"]);
77
+ }, true);
78
+ return config ?? {};
79
+ }
80
+ function saveConfig(config) {
81
+ const path = configFile();
82
+ const temporaryFile = `${path}.${randomUUID()}.tmp`;
83
+ try {
84
+ mkdirSync(configDir(), { recursive: true, mode: 0o700 });
85
+ writeFileSync(temporaryFile, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600, flag: "wx" });
86
+ renameSync(temporaryFile, path);
87
+ }
88
+ catch (error) {
89
+ try {
90
+ unlinkSync(temporaryFile);
91
+ }
92
+ catch (cleanupError) {
93
+ if (!(cleanupError instanceof Error && "code" in cleanupError && cleanupError.code === "ENOENT"))
94
+ throw configError(cleanupError, "clean up temporary");
95
+ }
96
+ throw configError(error, "write");
97
+ }
98
+ }
99
+ function isCredentialFile(value) {
100
+ if (!isObject(value))
101
+ return false;
102
+ const required = value.type === "service_account"
103
+ ? ["client_email", "private_key"]
104
+ : value.type === "authorized_user"
105
+ ? ["client_id", "client_secret", "refresh_token"]
106
+ : undefined;
107
+ if (!required)
108
+ return false;
109
+ return (required.every((field) => typeof value[field] === "string" && value[field].trim().length > 0) &&
110
+ ["private_key_id", "project_id", "quota_project_id", "universe_domain"].every((field) => !(field in value) || (typeof value[field] === "string" && value[field].trim().length > 0)));
111
+ }
112
+ function isServiceAccountFile(value) {
113
+ return isCredentialFile(value) && value.type === "service_account";
114
+ }
115
+ function readServiceAccount(path, source) {
116
+ const data = readJsonFile(path, isServiceAccountFile, (failure) => failure === "read"
117
+ ? new AuthConfigError("invalid-credentials-path", `${source} at ${path} is unreadable; check that the file exists and is readable`)
118
+ : new AuthConfigError("invalid-service-account", `${source} at ${path} is not a valid Google service-account key`));
119
+ if (!data)
120
+ throw new AuthConfigError("invalid-service-account", `${source} at ${path} is invalid`);
121
+ return data;
122
+ }
123
+ export async function getAuthClient(options = {}) {
124
+ const config = readConfig();
125
+ const serviceAccountJson = process.env["SEARCH_CONSOLE_AXI_SA_KEY"];
126
+ const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] ?? process.env["google_application_credentials"];
127
+ const configuredPath = config.serviceAccountPath;
128
+ let fileCredentials;
129
+ if (serviceAccountJson !== undefined) {
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(serviceAccountJson);
133
+ }
134
+ catch {
135
+ throw new AuthConfigError("invalid-service-account", "SEARCH_CONSOLE_AXI_SA_KEY must contain valid service-account JSON");
136
+ }
137
+ if (!isServiceAccountFile(parsed))
138
+ throw new AuthConfigError("invalid-service-account", "SEARCH_CONSOLE_AXI_SA_KEY does not contain a valid Google service-account key");
139
+ fileCredentials = parsed;
140
+ }
141
+ else if (credentialsPath === undefined && configuredPath) {
142
+ fileCredentials = readServiceAccount(configuredPath, "Configured service-account key file");
143
+ }
144
+ else {
145
+ if (credentialsPath === "")
146
+ throw new AuthConfigError("invalid-credentials-path", "GOOGLE_APPLICATION_CREDENTIALS must not be empty");
147
+ const adcDir = process.env["CLOUDSDK_CONFIG"] ||
148
+ (process.platform === "win32"
149
+ ? process.env["APPDATA"] && join(process.env["APPDATA"], "gcloud")
150
+ : process.env["HOME"] && join(process.env["HOME"], ".config", "gcloud"));
151
+ const path = credentialsPath ?? (adcDir ? join(adcDir, "application_default_credentials.json") : undefined);
152
+ if (path) {
153
+ const source = credentialsPath === undefined ? "Application Default Credentials" : "GOOGLE_APPLICATION_CREDENTIALS";
154
+ fileCredentials = readJsonFile(path, isCredentialFile, (failure) => failure === "read"
155
+ ? new AuthConfigError("invalid-credentials-path", `Could not read ${source} at ${path}; check that the file exists and is readable`)
156
+ : new AuthConfigError("invalid-credential-file", `${source} at ${path} contains invalid JSON or credential data; use authorized_user or service_account credentials`), credentialsPath === undefined);
157
+ }
158
+ }
159
+ const source = serviceAccountJson !== undefined
160
+ ? "SEARCH_CONSOLE_AXI_SA_KEY"
161
+ : credentialsPath
162
+ ? "GOOGLE_APPLICATION_CREDENTIALS"
163
+ : configuredPath
164
+ ? "service-account-path"
165
+ : "ADC";
166
+ const quotaOverride = options.quotaProject ?? process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] ?? config.quotaProjectId;
167
+ if (fileCredentials) {
168
+ const credential = fileCredentials.type === "service_account"
169
+ ? new JWT({
170
+ email: fileCredentials.client_email,
171
+ key: fileCredentials.private_key,
172
+ keyId: fileCredentials.private_key_id,
173
+ projectId: fileCredentials.project_id,
174
+ universeDomain: fileCredentials.universe_domain,
175
+ scopes: SCOPES,
176
+ })
177
+ : new UserRefreshClient({
178
+ clientId: fileCredentials.client_id,
179
+ clientSecret: fileCredentials.client_secret,
180
+ refreshToken: fileCredentials.refresh_token,
181
+ universeDomain: fileCredentials.universe_domain,
182
+ });
183
+ credential.quotaProjectId = quotaOverride ?? fileCredentials.quota_project_id;
184
+ return {
185
+ client: credential,
186
+ type: fileCredentials.type,
187
+ source,
188
+ ...(fileCredentials.type === "service_account" ? { email: fileCredentials.client_email } : {}),
189
+ ...(credential.quotaProjectId ? { quotaProjectId: credential.quotaProjectId } : {}),
190
+ ...(fileCredentials.project_id ? { projectId: fileCredentials.project_id } : {}),
191
+ };
192
+ }
193
+ const auth = (options.authFactory ?? ((opts) => new GoogleAuth(opts)))({
194
+ scopes: SCOPES,
195
+ ...(quotaOverride ? { clientOptions: { quotaProjectId: quotaOverride } } : {}),
196
+ });
197
+ let credential;
198
+ let projectId;
199
+ try {
200
+ ({ credential, projectId } = await auth.getApplicationDefault());
201
+ }
202
+ catch (error) {
203
+ if (error instanceof Error && error.message.includes(NO_ADC_MESSAGE))
204
+ throw new AuthConfigError("missing-credentials", "Google Application Default Credentials are not configured");
205
+ throw error;
206
+ }
207
+ if (quotaOverride)
208
+ credential.quotaProjectId = quotaOverride;
209
+ if (credential instanceof UserRefreshClient)
210
+ return {
211
+ client: credential,
212
+ type: "authorized_user",
213
+ source,
214
+ ...((quotaOverride ?? credential.quotaProjectId)
215
+ ? { quotaProjectId: quotaOverride ?? credential.quotaProjectId }
216
+ : {}),
217
+ ...(projectId ? { projectId } : {}),
218
+ };
219
+ if (credential instanceof JWT)
220
+ return {
221
+ client: credential,
222
+ type: "service_account",
223
+ source,
224
+ ...(credential.email ? { email: credential.email } : {}),
225
+ ...((quotaOverride ?? credential.quotaProjectId)
226
+ ? { quotaProjectId: quotaOverride ?? credential.quotaProjectId }
227
+ : {}),
228
+ ...(projectId ? { projectId } : {}),
229
+ };
230
+ throw new AuthConfigError("invalid-credential-file", "Unsupported Google credentials type; use authorized_user or service_account credentials");
231
+ }
232
+ function setupGuideOutput(missing) {
233
+ return result({ auth: { status: "not configured" }, setup: { status: "incomplete", missing, guide: setupGuide } });
234
+ }
235
+ function invalidAuthOutput(message, type) {
236
+ return result({
237
+ auth: { status: "invalid", ...(type ? { type } : {}), error: message },
238
+ setup: { status: "incomplete", missing: [message], guide: setupGuide },
239
+ });
240
+ }
241
+ async function setupWithChecks(options) {
242
+ try {
243
+ const auth = await getAuthClient(options);
244
+ return runSetupCheck(auth);
245
+ }
246
+ catch (error) {
247
+ if (error instanceof AuthConfigError && error.kind === "missing-credentials")
248
+ return setupGuideOutput([NO_CREDENTIALS_GUIDANCE]);
249
+ throw error;
250
+ }
251
+ }
252
+ function result(data) {
253
+ return encode(data);
254
+ }
255
+ async function authStatus(quotaProject, providerOptions = {}) {
256
+ try {
257
+ const auth = await getAuthClient({ ...providerOptions, quotaProject });
258
+ const help = auth.type === "authorized_user" && !auth.quotaProjectId
259
+ ? [
260
+ "Set a quota project with `gcloud auth application-default set-quota-project <project>`.",
261
+ QUOTA_PROJECT_APIS,
262
+ ]
263
+ : [];
264
+ return result({
265
+ auth: {
266
+ status: "configured",
267
+ type: auth.type,
268
+ source: auth.source,
269
+ ...(auth.email ? { account_email: auth.email } : {}),
270
+ quota_project: auth.quotaProjectId ?? "none",
271
+ },
272
+ help,
273
+ });
274
+ }
275
+ catch (error) {
276
+ if (error instanceof AuthConfigError && error.kind === "missing-credentials")
277
+ return setupGuideOutput([NO_CREDENTIALS_GUIDANCE]);
278
+ if (error instanceof AuthConfigError)
279
+ return invalidAuthOutput(error.message, error.kind === "invalid-service-account" ? "service_account" : undefined);
280
+ if (error instanceof AxiError && error.code === "VALIDATION_ERROR")
281
+ return invalidAuthOutput(error.message);
282
+ throw error;
283
+ }
284
+ }
285
+ export async function setupCommand(args, providerOptions = {}) {
286
+ const [first, ...rest] = args;
287
+ if (first === "--help" || first === "-h")
288
+ return "usage: search-console-axi setup [--quota-project <project>] | check | status | service-account <key.json> | uninstall\n";
289
+ const implicitSetup = !first || first.startsWith("-");
290
+ const action = implicitSetup ? "setup" : first;
291
+ const operands = implicitSetup ? args : rest;
292
+ let quotaProject;
293
+ let siteUrl;
294
+ const positionals = [];
295
+ for (let index = 0; index < operands.length; index++) {
296
+ const value = operands[index];
297
+ if (value === "--quota-project") {
298
+ const next = operands[++index];
299
+ if (!next || next.startsWith("-"))
300
+ fail("--quota-project requires a project ID");
301
+ quotaProject = next;
302
+ }
303
+ else if (value === "--site") {
304
+ const next = operands[++index];
305
+ if (!next || next.startsWith("-"))
306
+ fail("--site requires a Search Console site URL");
307
+ siteUrl = next;
308
+ }
309
+ else if (value?.startsWith("-")) {
310
+ fail(`unknown setup option '${value}'`);
311
+ }
312
+ else if (value)
313
+ positionals.push(value);
314
+ }
315
+ if (action === "status") {
316
+ if (positionals.length || siteUrl)
317
+ fail("usage: search-console-axi setup status [--quota-project <project>]");
318
+ return authStatus(quotaProject, providerOptions);
319
+ }
320
+ if (action === "uninstall") {
321
+ if (positionals.length || quotaProject || siteUrl)
322
+ fail("usage: search-console-axi setup uninstall");
323
+ try {
324
+ unlinkSync(configFile());
325
+ const verified = readConfig();
326
+ if (verified.serviceAccountPath || verified.quotaProjectId)
327
+ throw configError(new Error("saved registration remains after removal"), "verify removal of");
328
+ return result({ auth: { status: "removed", config: "removed" } });
329
+ }
330
+ catch (error) {
331
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
332
+ return result({ auth: { status: "not configured", config: "already absent" } });
333
+ throw error instanceof AxiError ? error : configError(error, "remove");
334
+ }
335
+ }
336
+ if (action === "service-account") {
337
+ if (siteUrl)
338
+ fail("--site is only valid with inspect");
339
+ const [path] = positionals;
340
+ if (positionals.length !== 1 || !path)
341
+ return fail("usage: search-console-axi setup service-account <key.json> [--quota-project <project>]");
342
+ const key = readServiceAccount(path, "Service-account key file");
343
+ const saved = {
344
+ ...readConfig(),
345
+ serviceAccountPath: resolve(path),
346
+ ...(quotaProject ? { quotaProjectId: quotaProject } : {}),
347
+ };
348
+ saveConfig(saved);
349
+ const verified = readConfig();
350
+ if (verified.serviceAccountPath !== saved.serviceAccountPath || verified.quotaProjectId !== saved.quotaProjectId)
351
+ throw configError(new Error("saved registration does not match requested values"), "verify saved");
352
+ return result({ auth: { status: "configured", type: "service_account", account_email: key.client_email } });
353
+ }
354
+ if (action === "check") {
355
+ if (positionals.length || siteUrl)
356
+ fail("usage: search-console-axi setup check");
357
+ return setupWithChecks({ ...providerOptions, ...(quotaProject ? { quotaProject } : {}) });
358
+ }
359
+ if (action === "inspect") {
360
+ if (positionals.length !== 1 || !positionals[0] || !siteUrl)
361
+ fail("usage: search-console-axi setup inspect <url> --site <site>");
362
+ const auth = await getAuthClient({ ...providerOptions, ...(quotaProject ? { quotaProject } : {}) });
363
+ return inspectUrl(auth, positionals[0], siteUrl);
364
+ }
365
+ if (action !== "setup")
366
+ fail(`unknown setup action '${action}'; valid actions are setup, check, status, service-account, inspect, uninstall`);
367
+ if (positionals.length || siteUrl)
368
+ fail("usage: search-console-axi setup [--quota-project <project>]");
369
+ if (quotaProject) {
370
+ saveConfig({ ...readConfig(), quotaProjectId: quotaProject });
371
+ if (readConfig().quotaProjectId !== quotaProject)
372
+ throw configError(new Error("saved quota project does not match requested value"), "verify saved");
373
+ }
374
+ return setupWithChecks({ ...providerOptions, ...(quotaProject ? { quotaProject } : {}) });
375
+ }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { runAxiCli } from "axi-sdk-js";
3
+ import { readFileSync } from "node:fs";
4
+ import { getAuthClient, setupCommand } from "./auth.js";
5
+ import { runHome } from "./setup-check.js";
6
+ const version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
7
+ const description = "Read-only Google Search Console reporting and URL inspection for agents";
8
+ const args = process.argv.slice(2);
9
+ await runAxiCli({
10
+ description,
11
+ version,
12
+ argv: args,
13
+ topLevelHelp: `${description}\n\nUsage: search-console-axi [--help] [--version]\n\nCommands:\n setup Configure, inspect, or remove authentication\n inspect Inspect a URL's index status`,
14
+ commands: {
15
+ setup: setupCommand,
16
+ inspect: (args) => setupCommand(["inspect", ...args]),
17
+ },
18
+ home: async () => {
19
+ try {
20
+ return await runHome(await getAuthClient());
21
+ }
22
+ catch {
23
+ return setupCommand(["status"]);
24
+ }
25
+ },
26
+ });
@@ -0,0 +1,237 @@
1
+ import { encode } from "@toon-format/toon";
2
+ const API = "https://searchconsole.googleapis.com/webmasters/v3/sites";
3
+ export const setupGuide = [
4
+ { step: 1, instruction: "Enable the Google Search Console API in a Google Cloud project." },
5
+ { step: 2, instruction: "Create a service account; it needs no project-level IAM roles." },
6
+ {
7
+ step: 3,
8
+ instruction: "Load its JSON key from your secret manager into SEARCH_CONSOLE_AXI_SA_KEY. Never commit the key.",
9
+ },
10
+ {
11
+ step: 4,
12
+ instruction: "In Search Console, add the service-account email under Settings > Users and permissions with Restricted access.",
13
+ },
14
+ {
15
+ step: 5,
16
+ instruction: "For personal access, use your own Desktop OAuth client and run gcloud auth application-default login --client-id-file=client.json --scopes=https://www.googleapis.com/auth/webmasters.readonly,https://www.googleapis.com/auth/cloud-platform.",
17
+ },
18
+ ];
19
+ function apiDisabledMessage(error) {
20
+ if (!error ||
21
+ typeof error !== "object" ||
22
+ !("response" in error) ||
23
+ !error.response ||
24
+ typeof error.response !== "object")
25
+ return undefined;
26
+ const response = error.response;
27
+ if (!("status" in response) || response.status !== 403 || !("data" in response))
28
+ return undefined;
29
+ const body = response.data;
30
+ if (!body || typeof body !== "object" || !("error" in body) || !body.error || typeof body.error !== "object")
31
+ return undefined;
32
+ const googleError = body.error;
33
+ const details = "details" in googleError && Array.isArray(googleError.details) ? googleError.details : [];
34
+ const legacy = "errors" in googleError && Array.isArray(googleError.errors) ? googleError.errors : [];
35
+ const reasons = [
36
+ ...details.flatMap((detail) => (detail && typeof detail === "object" && "reason" in detail ? [detail.reason] : [])),
37
+ ...legacy.flatMap((detail) => (detail && typeof detail === "object" && "reason" in detail ? [detail.reason] : [])),
38
+ ];
39
+ if (!reasons.some((reason) => reason === "SERVICE_DISABLED" || reason === "accessNotConfigured"))
40
+ return undefined;
41
+ const metadata = details.find((detail) => detail &&
42
+ typeof detail === "object" &&
43
+ "metadata" in detail &&
44
+ detail.metadata &&
45
+ typeof detail.metadata === "object");
46
+ const service = metadata && "metadata" in metadata && metadata.metadata && "service" in metadata.metadata
47
+ ? metadata.metadata.service
48
+ : undefined;
49
+ const consumer = metadata && "metadata" in metadata && metadata.metadata && "consumer" in metadata.metadata
50
+ ? metadata.metadata.consumer
51
+ : undefined;
52
+ const message = "message" in googleError && typeof googleError.message === "string" ? googleError.message : "";
53
+ const api = typeof service === "string"
54
+ ? service
55
+ : (message.match(/[\w.-]+\.googleapis\.com/)?.[0] ?? "Google Search Console API");
56
+ const project = (typeof consumer === "string" ? consumer.match(/projects\/([^/]+)/)?.[1] : undefined) ??
57
+ message.match(/project\s+([\w.-]+)/i)?.[1] ??
58
+ "your Google Cloud project";
59
+ return `Enable ${api} in ${project} to use Search Console.`;
60
+ }
61
+ const ACCESS_DENIED = "Search Console access denied. Add the authenticated account in Search Console Settings > Users and permissions.";
62
+ async function request(auth, url, method = "GET", data) {
63
+ try {
64
+ const response = await auth.client.request({ url, method, ...(data ? { data } : {}) });
65
+ return response.data;
66
+ }
67
+ catch (error) {
68
+ if (error instanceof Error && "response" in error && error.response && typeof error.response === "object") {
69
+ const response = error.response;
70
+ if ("status" in response && response.status === 403)
71
+ error.message = apiDisabledMessage(error) ?? ACCESS_DENIED;
72
+ }
73
+ throw error;
74
+ }
75
+ }
76
+ function searchDateRange() {
77
+ const parts = new Intl.DateTimeFormat("en-US", {
78
+ timeZone: "America/Los_Angeles",
79
+ year: "numeric",
80
+ month: "2-digit",
81
+ day: "2-digit",
82
+ }).formatToParts(new Date());
83
+ const date = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
84
+ const today = Date.UTC(Number(date.year), Number(date.month) - 1, Number(date.day));
85
+ const format = (offset) => new Date(today + offset * 86_400_000).toISOString().slice(0, 10);
86
+ return { startDate: format(-7), endDate: format(-1) };
87
+ }
88
+ async function sites(auth) {
89
+ const data = await request(auth, API);
90
+ if (!data || typeof data !== "object" || !("siteEntry" in data) || !Array.isArray(data.siteEntry))
91
+ return [];
92
+ return data.siteEntry.flatMap((site) => site && typeof site === "object" && "siteUrl" in site && typeof site.siteUrl === "string"
93
+ ? [
94
+ {
95
+ siteUrl: site.siteUrl,
96
+ ...("permissionLevel" in site && typeof site.permissionLevel === "string"
97
+ ? { permissionLevel: site.permissionLevel }
98
+ : {}),
99
+ },
100
+ ]
101
+ : []);
102
+ }
103
+ export async function runSetupCheck(auth) {
104
+ try {
105
+ const accessible = await sites(auth);
106
+ const reportable = accessible.filter((site) => site.permissionLevel !== "siteUnverifiedUser");
107
+ const missing = reportable.length
108
+ ? []
109
+ : ["No verified Search Console sites visible to this account - grant access as in step 4, or none exist."];
110
+ return encode({
111
+ auth: { type: auth.type, source: auth.source, ...(auth.email ? { account_email: auth.email } : {}) },
112
+ setup: { status: missing.length ? "incomplete" : "ready", missing, guide: setupGuide },
113
+ sites: accessible
114
+ .slice(0, 100)
115
+ .map(({ siteUrl, permissionLevel }) => ({ site_url: siteUrl, permission: permissionLevel ?? "" })),
116
+ truncated: accessible.length > 100,
117
+ });
118
+ }
119
+ catch (error) {
120
+ const status = error &&
121
+ typeof error === "object" &&
122
+ "response" in error &&
123
+ error.response &&
124
+ typeof error.response === "object" &&
125
+ "status" in error.response
126
+ ? error.response.status
127
+ : undefined;
128
+ const message = error instanceof Error && error.message.startsWith("Enable ")
129
+ ? error.message
130
+ : status === 403
131
+ ? ACCESS_DENIED
132
+ : "Search Console API request failed. Check API access and network connectivity.";
133
+ return encode({
134
+ auth: { type: auth.type, source: auth.source },
135
+ setup: { status: "incomplete", missing: [message], guide: setupGuide },
136
+ });
137
+ }
138
+ }
139
+ export async function runHome(auth) {
140
+ try {
141
+ const accessible = await sites(auth);
142
+ if (!accessible.length)
143
+ return encode({
144
+ tool: "search-console-axi",
145
+ sites: "No Search Console sites visible to this account - grant access as in step 4, or none exist.",
146
+ help: ["Run search-console-axi setup for access instructions."],
147
+ });
148
+ const reportable = accessible.filter((entry) => entry.permissionLevel !== "siteUnverifiedUser");
149
+ const site = reportable[0]?.siteUrl;
150
+ if (!site)
151
+ return encode({
152
+ tool: "search-console-axi",
153
+ sites: "No verified Search Console sites visible to this account - grant access as in step 4, or none exist.",
154
+ help: ["Run search-console-axi setup for access instructions."],
155
+ });
156
+ const dateRange = searchDateRange();
157
+ const query = async (dimension, orderBy) => {
158
+ const result = await request(auth, `${API}/${encodeURIComponent(site)}/searchAnalytics/query`, "POST", {
159
+ ...dateRange,
160
+ dimensions: [dimension],
161
+ rowLimit: 10,
162
+ orderBy: [{ field: orderBy, direction: "descending" }],
163
+ });
164
+ return result && typeof result === "object" && "rows" in result && Array.isArray(result.rows) ? result.rows : [];
165
+ };
166
+ const [summaryRows, queries, pages] = await Promise.all([
167
+ request(auth, `${API}/${encodeURIComponent(site)}/searchAnalytics/query`, "POST", {
168
+ ...dateRange,
169
+ }).then((result) => result && typeof result === "object" && "rows" in result && Array.isArray(result.rows) ? result.rows : []),
170
+ query("query", "clicks"),
171
+ query("page", "clicks"),
172
+ ]);
173
+ const opportunityRows = await request(auth, `${API}/${encodeURIComponent(site)}/searchAnalytics/query`, "POST", {
174
+ ...dateRange,
175
+ dimensions: ["page"],
176
+ rowLimit: 1000,
177
+ orderBy: [{ field: "impressions", direction: "descending" }],
178
+ });
179
+ const rows = opportunityRows &&
180
+ typeof opportunityRows === "object" &&
181
+ "rows" in opportunityRows &&
182
+ Array.isArray(opportunityRows.rows)
183
+ ? opportunityRows.rows
184
+ : [];
185
+ const opportunities = rows
186
+ .filter((row) => row &&
187
+ typeof row === "object" &&
188
+ "ctr" in row &&
189
+ typeof row.ctr === "number" &&
190
+ row.ctr < 0.02 &&
191
+ "impressions" in row &&
192
+ typeof row.impressions === "number" &&
193
+ row.impressions > 100)
194
+ .slice(0, 10);
195
+ const formatRows = (items) => items.map((item) => item && typeof item === "object"
196
+ ? {
197
+ ...item,
198
+ ...("ctr" in item && typeof item.ctr === "number" ? { ctr: `${(item.ctr * 100).toFixed(1)}%` } : {}),
199
+ ...("position" in item && typeof item.position === "number"
200
+ ? { position: Number(item.position.toFixed(1)) }
201
+ : {}),
202
+ }
203
+ : item);
204
+ return encode({
205
+ tool: "search-console-axi",
206
+ site,
207
+ sites: reportable.length,
208
+ period: "last 7 complete days",
209
+ totals: formatRows([summaryRows[0] ?? { clicks: 0, impressions: 0, ctr: 0, position: 0 }])[0],
210
+ top_queries: formatRows(queries),
211
+ top_pages: formatRows(pages),
212
+ low_ctr_opportunities: formatRows(opportunities),
213
+ help: [
214
+ "Run search-console-axi setup check to verify access.",
215
+ "Run search-console-axi inspect <url> --site <site> to check indexing.",
216
+ ],
217
+ });
218
+ }
219
+ catch (error) {
220
+ return encode({
221
+ tool: "search-console-axi",
222
+ status: "error",
223
+ ...(error instanceof Error && (error.message.startsWith("Enable ") || error.message === ACCESS_DENIED)
224
+ ? { error: error.message }
225
+ : {}),
226
+ help: ["Run search-console-axi setup check for access guidance."],
227
+ });
228
+ }
229
+ }
230
+ export async function inspectUrl(auth, url, siteUrl) {
231
+ const data = await request(auth, "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect", "POST", {
232
+ inspectionUrl: url,
233
+ siteUrl,
234
+ languageCode: "en-US",
235
+ });
236
+ return encode(data && typeof data === "object" && "inspectionResult" in data ? data.inspectionResult : data);
237
+ }
package/package.json CHANGED
@@ -1 +1,50 @@
1
- {"name":"search-console-axi","version":"0.0.0","description":"Placeholder that reserves the name; the first real release follows.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/Dematom1/search-console-axi.git"}}
1
+ {
2
+ "name": "search-console-axi",
3
+ "version": "0.1.0",
4
+ "description": "Read-only Google Search Console CLI for agents",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": "git+https://github.com/Dematom1/search-console-axi.git",
8
+ "homepage": "https://github.com/Dematom1/search-console-axi#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/Dematom1/search-console-axi/issues"
11
+ },
12
+ "bin": {
13
+ "search-console-axi": "./dist/bin/search-console-axi.js"
14
+ },
15
+ "files": [
16
+ "dist/bin",
17
+ "dist/src",
18
+ "skills/search-console-axi",
19
+ "LICENSE",
20
+ "README.md"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": ">=22.12.0"
27
+ },
28
+ "scripts": {
29
+ "build": "tsc -p tsconfig.json",
30
+ "typecheck": "tsc -p tsconfig.json --noEmit",
31
+ "lint": "eslint .",
32
+ "format:check": "prettier --check .",
33
+ "test": "npm run build && node --test test/cli.test.js",
34
+ "prepack": "npm run build"
35
+ },
36
+ "dependencies": {
37
+ "@toon-format/toon": "2.3.1",
38
+ "axi-sdk-js": "0.1.13",
39
+ "google-auth-library": "^11.3.2"
40
+ },
41
+ "devDependencies": {
42
+ "@eslint/js": "9.39.5",
43
+ "@types/node": "22.20.5",
44
+ "eslint": "9.39.5",
45
+ "prettier": "3.9.10",
46
+ "typescript": "5.9.3",
47
+ "typescript-eslint": "8.69.0"
48
+ },
49
+ "gitHead": "e5f66b7ae003ea7a44f2c84e3453bfcc929136fa"
50
+ }
@@ -0,0 +1,12 @@
1
+ ---
2
+ name: search-console-axi
3
+ description: Read Google Search Console performance and inspect URL indexing.
4
+ ---
5
+
6
+ # search-console-axi
7
+
8
+ Use `search-console-axi` for read-only Google Search Console reporting and URL inspection. Output is compact TOON. See the [README](../../README.md#authentication) for authentication setup.
9
+
10
+ Run `search-console-axi` for the default site's clicks, impressions, CTR, average position, top queries/pages, and low-CTR opportunities. Run `search-console-axi setup` to check access. Run `search-console-axi inspect <url> --site <site-url>` to inspect index status.
11
+
12
+ See the [README authentication guide](../../README.md#authentication) for credential setup and security guidance.