gogcli-mcp 2.20.0 → 2.21.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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/dist/index.js +434 -66
- package/dist/lib.js +396 -47
- package/manifest.json +1 -1
- package/package.json +3 -3
- package/server.json +2 -2
- package/src/auth-log.ts +147 -0
- package/src/connector-runtime.ts +585 -80
- package/src/google-token.ts +391 -0
- package/src/remote-runner.ts +8 -1
- package/src/runner.ts +67 -2
- package/src/tools/auth.ts +6 -1
- package/src/tools/utils.ts +94 -7
- package/src/worker.ts +12 -1
- package/tests/auth-log.test.ts +508 -0
- package/tests/connector-runtime.test.ts +675 -2
- package/tests/google-token.test.ts +425 -0
- package/tests/runner.test.ts +21 -1
- package/tests/sdk-single-copy.test.ts +48 -0
- package/tests/tools/auth-401-context.test.ts +42 -0
- package/tests/tools/auth-401-shapes.test.ts +50 -0
- package/tests/tools/auth.test.ts +21 -0
- package/tests/tools/utils.test.ts +99 -2
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
},
|
|
8
8
|
"metadata": {
|
|
9
9
|
"description": "Google Sheets (and more) for Claude via gogcli — read, write, and manage spreadsheets",
|
|
10
|
-
"version": "2.
|
|
10
|
+
"version": "2.21.1"
|
|
11
11
|
},
|
|
12
12
|
"plugins": [
|
|
13
13
|
{
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"displayName": "gogcli",
|
|
16
16
|
"source": "./",
|
|
17
17
|
"description": "Google Sheets (and more) for Claude via gogcli — read, write, and manage spreadsheets",
|
|
18
|
-
"version": "2.
|
|
18
|
+
"version": "2.21.1",
|
|
19
19
|
"author": {
|
|
20
20
|
"name": "Chris Hall"
|
|
21
21
|
},
|
package/dist/index.js
CHANGED
|
@@ -4264,8 +4264,8 @@ var require_core = __commonJS({
|
|
|
4264
4264
|
return this;
|
|
4265
4265
|
}
|
|
4266
4266
|
case "object": {
|
|
4267
|
-
const
|
|
4268
|
-
this._cache.delete(
|
|
4267
|
+
const cacheKey2 = schemaKeyRef;
|
|
4268
|
+
this._cache.delete(cacheKey2);
|
|
4269
4269
|
let id = schemaKeyRef[this.opts.schemaId];
|
|
4270
4270
|
if (id) {
|
|
4271
4271
|
id = (0, resolve_1.normalizeId)(id);
|
|
@@ -23068,17 +23068,33 @@ function normalizeObjectSchema(schema) {
|
|
|
23068
23068
|
}
|
|
23069
23069
|
return void 0;
|
|
23070
23070
|
}
|
|
23071
|
+
function getDotPath(path) {
|
|
23072
|
+
if (path.length === 0) {
|
|
23073
|
+
return "object root";
|
|
23074
|
+
}
|
|
23075
|
+
return path.reduce((acc, seg, index) => {
|
|
23076
|
+
if (index === 0) {
|
|
23077
|
+
return String(seg);
|
|
23078
|
+
}
|
|
23079
|
+
if (typeof seg === "number") {
|
|
23080
|
+
return `${acc}[${seg}]`;
|
|
23081
|
+
}
|
|
23082
|
+
return `${acc}.${seg}`;
|
|
23083
|
+
}, "");
|
|
23084
|
+
}
|
|
23071
23085
|
function getParseErrorMessage(error51) {
|
|
23072
23086
|
if (error51 && typeof error51 === "object") {
|
|
23087
|
+
if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
|
|
23088
|
+
return error51.issues.map((i) => {
|
|
23089
|
+
if (!i.path?.length) {
|
|
23090
|
+
return i.message;
|
|
23091
|
+
}
|
|
23092
|
+
return `${i.message} at ${getDotPath(i.path)}`;
|
|
23093
|
+
}).join("\n");
|
|
23094
|
+
}
|
|
23073
23095
|
if ("message" in error51 && typeof error51.message === "string") {
|
|
23074
23096
|
return error51.message;
|
|
23075
23097
|
}
|
|
23076
|
-
if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
|
|
23077
|
-
const firstIssue = error51.issues[0];
|
|
23078
|
-
if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
|
|
23079
|
-
return String(firstIssue.message);
|
|
23080
|
-
}
|
|
23081
|
-
}
|
|
23082
23098
|
try {
|
|
23083
23099
|
return JSON.stringify(error51);
|
|
23084
23100
|
} catch {
|
|
@@ -29693,16 +29709,7 @@ var Server = class extends Protocol {
|
|
|
29693
29709
|
if (!methodSchema) {
|
|
29694
29710
|
throw new Error("Schema is missing a method literal");
|
|
29695
29711
|
}
|
|
29696
|
-
|
|
29697
|
-
if (isZ4Schema(methodSchema)) {
|
|
29698
|
-
const v4Schema = methodSchema;
|
|
29699
|
-
const v4Def = v4Schema._zod?.def;
|
|
29700
|
-
methodValue = v4Def?.value ?? v4Schema.value;
|
|
29701
|
-
} else {
|
|
29702
|
-
const v3Schema = methodSchema;
|
|
29703
|
-
const legacyDef = v3Schema._def;
|
|
29704
|
-
methodValue = legacyDef?.value ?? v3Schema.value;
|
|
29705
|
-
}
|
|
29712
|
+
const methodValue = getLiteralValue(methodSchema);
|
|
29706
29713
|
if (typeof methodValue !== "string") {
|
|
29707
29714
|
throw new Error("Schema method literal must be a string");
|
|
29708
29715
|
}
|
|
@@ -30890,8 +30897,17 @@ var EMPTY_COMPLETION_RESULT = {
|
|
|
30890
30897
|
import process3 from "node:process";
|
|
30891
30898
|
|
|
30892
30899
|
// ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
|
|
30900
|
+
var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
30893
30901
|
var ReadBuffer = class {
|
|
30902
|
+
constructor(options) {
|
|
30903
|
+
this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
|
|
30904
|
+
}
|
|
30894
30905
|
append(chunk) {
|
|
30906
|
+
const newSize = (this._buffer?.length ?? 0) + chunk.length;
|
|
30907
|
+
if (newSize > this._maxBufferSize) {
|
|
30908
|
+
this.clear();
|
|
30909
|
+
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
30910
|
+
}
|
|
30895
30911
|
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
30896
30912
|
}
|
|
30897
30913
|
readMessage() {
|
|
@@ -30919,18 +30935,24 @@ function serializeMessage(message) {
|
|
|
30919
30935
|
|
|
30920
30936
|
// ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
30921
30937
|
var StdioServerTransport = class {
|
|
30922
|
-
constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
|
|
30938
|
+
constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
|
|
30923
30939
|
this._stdin = _stdin;
|
|
30924
30940
|
this._stdout = _stdout;
|
|
30925
|
-
this._readBuffer = new ReadBuffer();
|
|
30926
30941
|
this._started = false;
|
|
30927
30942
|
this._ondata = (chunk) => {
|
|
30928
|
-
|
|
30929
|
-
|
|
30943
|
+
try {
|
|
30944
|
+
this._readBuffer.append(chunk);
|
|
30945
|
+
this.processReadBuffer();
|
|
30946
|
+
} catch (error51) {
|
|
30947
|
+
this.onerror?.(error51);
|
|
30948
|
+
this.close().catch(() => {
|
|
30949
|
+
});
|
|
30950
|
+
}
|
|
30930
30951
|
};
|
|
30931
30952
|
this._onerror = (error51) => {
|
|
30932
30953
|
this.onerror?.(error51);
|
|
30933
30954
|
};
|
|
30955
|
+
this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
|
|
30934
30956
|
}
|
|
30935
30957
|
/**
|
|
30936
30958
|
* Starts listening for messages on stdin.
|
|
@@ -31118,6 +31140,21 @@ import { delimiter, join } from "node:path";
|
|
|
31118
31140
|
function isGogFileArg(arg) {
|
|
31119
31141
|
return typeof arg !== "string";
|
|
31120
31142
|
}
|
|
31143
|
+
var RUNNER_TRANSPORT_BRAND = /* @__PURE__ */ Symbol.for("gogcli.RunnerTransportError");
|
|
31144
|
+
var RunnerTransportError = class extends Error {
|
|
31145
|
+
kind;
|
|
31146
|
+
status;
|
|
31147
|
+
constructor(message, kind, status) {
|
|
31148
|
+
super(message);
|
|
31149
|
+
this.name = "RunnerTransportError";
|
|
31150
|
+
this.kind = kind;
|
|
31151
|
+
this.status = status;
|
|
31152
|
+
Object.defineProperty(this, RUNNER_TRANSPORT_BRAND, { value: true });
|
|
31153
|
+
}
|
|
31154
|
+
};
|
|
31155
|
+
function isRunnerTransportError(err) {
|
|
31156
|
+
return err instanceof Error && err[RUNNER_TRANSPORT_BRAND] === true;
|
|
31157
|
+
}
|
|
31121
31158
|
var runExecutor = new AsyncLocalStorage();
|
|
31122
31159
|
var defaultExecutor;
|
|
31123
31160
|
function setDefaultGogExecutor(executor) {
|
|
@@ -31298,7 +31335,11 @@ async function run(args, options = {}) {
|
|
|
31298
31335
|
}
|
|
31299
31336
|
return redact(output);
|
|
31300
31337
|
} catch (err) {
|
|
31301
|
-
|
|
31338
|
+
const message = redact(err instanceof Error ? err.message : String(err));
|
|
31339
|
+
if (isRunnerTransportError(err)) {
|
|
31340
|
+
throw new RunnerTransportError(message, err.kind, err.status);
|
|
31341
|
+
}
|
|
31342
|
+
throw new Error(message);
|
|
31302
31343
|
}
|
|
31303
31344
|
}
|
|
31304
31345
|
async function runBinary(args, options = {}) {
|
|
@@ -31567,7 +31608,9 @@ function registerRunTool(server, options) {
|
|
|
31567
31608
|
function errorText(err) {
|
|
31568
31609
|
return err instanceof Error ? `Error: ${err.message}` : String(err);
|
|
31569
31610
|
}
|
|
31570
|
-
var
|
|
31611
|
+
var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
|
|
31612
|
+
var STALE_TOKEN_PATTERN = /\b(?:access[ _-]?)?token\b[^.;\n]{0,40}\b(?:has\s+)?(?:been\s+)?(?:expired|revoked)\b|\b(?:expired|revoked)\s+(?:access[ _-]?)?token\b/i;
|
|
31613
|
+
var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
|
|
31571
31614
|
var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
|
|
31572
31615
|
var TRANSIENT_ERROR_PATTERN = /\b429\b|\b5\d\d\b|\bquota\b|rateLimit|\bDEADLINE_EXCEEDED\b/i;
|
|
31573
31616
|
var GRID_LIMIT_ERROR_PATTERN = /exceeds grid limits/i;
|
|
@@ -31575,6 +31618,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
|
|
|
31575
31618
|
var INVALID_GRANT_HINT = '\n\nThe stored refresh token was rejected (invalid_grant): it has expired or been revoked, so the whole account is signed out and re-authorization is required. The most common cause is the 7-day refresh-token limit Google applies to OAuth apps whose consent screen is still in "Testing" mode. Re-authorize with gog_auth_add (opens a browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless). To stop this recurring, publish the OAuth consent screen to "In production" in the Google Cloud project that owns the OAuth client. Ask the user if they would like to re-authenticate.';
|
|
31576
31619
|
var TRANSIENT_HINT = "\n\nThis error is often transient. Retry the same call before trying a different approach (do not fall back to smaller writes or row-by-row operations).";
|
|
31577
31620
|
var GRID_LIMIT_HINT = "\n\nThe target range is outside the sheet's current grid. Add the missing rows or columns first with gog_sheets_insert (dimension: rows or cols), then retry the write.";
|
|
31621
|
+
var RUNNER_TRANSPORT_AUTH_HINT = "\n\nThis is the CONNECTOR's own transport auth failing, not your Google sign-in. The gog-runner backend rejected the bearer token this server sent, so the request never reached gog and no Google credential was checked \u2014 the Google account is not the problem and re-authorizing it cannot fix this. An operator must make the Worker secret GOG_RUNNER_KEY equal RUNNER_KEY on the Fly app (wrangler secret put GOG_RUNNER_KEY / fly secrets set RUNNER_KEY), then retry.";
|
|
31622
|
+
var RUNNER_TRANSPORT_HINTS = {
|
|
31623
|
+
"transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
|
|
31624
|
+
// The request itself was malformed, so the runner will refuse it identically
|
|
31625
|
+
// every time. Nothing to advise beyond the message the runner already gave.
|
|
31626
|
+
"transport-request": "",
|
|
31627
|
+
"transport-retryable": TRANSIENT_HINT
|
|
31628
|
+
};
|
|
31578
31629
|
function formatAccountList(raw) {
|
|
31579
31630
|
try {
|
|
31580
31631
|
const parsed = JSON.parse(raw);
|
|
@@ -31587,11 +31638,12 @@ function formatAccountList(raw) {
|
|
|
31587
31638
|
}
|
|
31588
31639
|
async function diagnose(err) {
|
|
31589
31640
|
const errText = errorText(err);
|
|
31641
|
+
const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
|
|
31590
31642
|
const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
|
|
31591
|
-
const
|
|
31592
|
-
const
|
|
31643
|
+
const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
|
|
31644
|
+
const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
|
|
31593
31645
|
const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
|
|
31594
|
-
const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
|
|
31646
|
+
const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
|
|
31595
31647
|
try {
|
|
31596
31648
|
const accounts = formatAccountList(await run(["auth", "list"]));
|
|
31597
31649
|
return errorResult(`${errText}
|
|
@@ -31710,7 +31762,7 @@ function registerApiTools(server) {
|
|
|
31710
31762
|
function registerAuthToolsWith(server, defaultServices) {
|
|
31711
31763
|
const servicesDescribe = `Services to authorize: "all" or comma-separated list (e.g. "sheets,gmail,calendar"). Default: "${defaultServices}". Prefer the narrowest set you need \u2014 requesting a service whose Google API is not enabled on the OAuth client's project makes Google reject the WHOLE request with invalid_scope.`;
|
|
31712
31764
|
server.registerTool("gog_auth_list", {
|
|
31713
|
-
description: "List
|
|
31765
|
+
description: "List the Google accounts stored in gogcli, with their scopes. This reads local configuration only \u2014 it does not contact Google and does NOT tell you whether an account still works: a signed-out account whose refresh token expired or was revoked is listed here exactly like a healthy one, scopes and all. Use gog_auth_health to check whether an account can actually authenticate.",
|
|
31714
31766
|
annotations: { readOnlyHint: true },
|
|
31715
31767
|
inputSchema: {}
|
|
31716
31768
|
}, async () => {
|
|
@@ -33079,7 +33131,7 @@ function registerTasksTools(server) {
|
|
|
33079
33131
|
}
|
|
33080
33132
|
|
|
33081
33133
|
// src/server.ts
|
|
33082
|
-
var VERSION = true ? "2.
|
|
33134
|
+
var VERSION = true ? "2.21.1" : "0.0.0";
|
|
33083
33135
|
var BASE_TOOL_REGISTRARS = [
|
|
33084
33136
|
registerApiTools,
|
|
33085
33137
|
registerAuthTools,
|
|
@@ -33094,57 +33146,373 @@ var BASE_TOOL_REGISTRARS = [
|
|
|
33094
33146
|
registerTasksTools
|
|
33095
33147
|
];
|
|
33096
33148
|
|
|
33149
|
+
// src/auth-log.ts
|
|
33150
|
+
var FAILURES = /* @__PURE__ */ new Set([
|
|
33151
|
+
"token.mint-failed",
|
|
33152
|
+
"grant.dead",
|
|
33153
|
+
"replay.failed",
|
|
33154
|
+
"runner.auth-failed"
|
|
33155
|
+
]);
|
|
33156
|
+
var PREFIX = "gog-auth ";
|
|
33157
|
+
var TAG_CHARS = 12;
|
|
33158
|
+
function credentialTag(cacheKeyHash) {
|
|
33159
|
+
return cacheKeyHash.slice(0, TAG_CHARS);
|
|
33160
|
+
}
|
|
33161
|
+
function logAuthTransition(event, context) {
|
|
33162
|
+
const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
|
|
33163
|
+
const write = FAILURES.has(event) ? console.error : console.warn;
|
|
33164
|
+
write(PREFIX + redactSecrets2(record2));
|
|
33165
|
+
}
|
|
33166
|
+
|
|
33167
|
+
// src/google-token.ts
|
|
33168
|
+
var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
|
|
33169
|
+
var EXPIRY_MARGIN_MS = 12e4;
|
|
33170
|
+
var cache = /* @__PURE__ */ new Map();
|
|
33171
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
33172
|
+
async function cacheKey(refreshToken, clientId) {
|
|
33173
|
+
const data = new TextEncoder().encode(`${clientId}\0${refreshToken}`);
|
|
33174
|
+
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
33175
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
33176
|
+
}
|
|
33177
|
+
function makeAccessTokenSource(env) {
|
|
33178
|
+
const direct = readEnvVar("GOG_ACCESS_TOKEN", { env });
|
|
33179
|
+
if (direct) return async () => direct;
|
|
33180
|
+
const refreshToken = readEnvVar("GOG_REFRESH_TOKEN", { env });
|
|
33181
|
+
if (!refreshToken) return void 0;
|
|
33182
|
+
const clientId = readEnvVar("GOG_CLIENT_ID", { env });
|
|
33183
|
+
const clientSecret = readEnvVar("GOG_CLIENT_SECRET", { env });
|
|
33184
|
+
if (!clientId || !clientSecret) {
|
|
33185
|
+
const missing = [!clientId && "GOG_CLIENT_ID", !clientSecret && "GOG_CLIENT_SECRET"].filter(Boolean).join(" and ");
|
|
33186
|
+
return async () => {
|
|
33187
|
+
throw new Error(
|
|
33188
|
+
`GOG_REFRESH_TOKEN is set but ${missing} is not, so no access token can be minted. Set the OAuth client alongside the refresh token, or unset GOG_REFRESH_TOKEN to use the backend\u2019s own identity.`
|
|
33189
|
+
);
|
|
33190
|
+
};
|
|
33191
|
+
}
|
|
33192
|
+
let keyPromise;
|
|
33193
|
+
const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
|
|
33194
|
+
const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
|
|
33195
|
+
const read = async () => {
|
|
33196
|
+
const k = await key();
|
|
33197
|
+
const hit = cache.get(k);
|
|
33198
|
+
if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
|
|
33199
|
+
if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
|
|
33200
|
+
return hit.accessToken;
|
|
33201
|
+
}
|
|
33202
|
+
let pending = inFlight.get(k);
|
|
33203
|
+
if (!pending) {
|
|
33204
|
+
pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
|
|
33205
|
+
cache.set(k, minted2);
|
|
33206
|
+
logAuthTransition("token.minted", {
|
|
33207
|
+
credential: credentialTag(k),
|
|
33208
|
+
reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
|
|
33209
|
+
});
|
|
33210
|
+
return minted2;
|
|
33211
|
+
}).catch((err) => {
|
|
33212
|
+
logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
|
|
33213
|
+
credential: credentialTag(k),
|
|
33214
|
+
reason: err.message
|
|
33215
|
+
});
|
|
33216
|
+
throw err;
|
|
33217
|
+
}).finally(() => inFlight.delete(k));
|
|
33218
|
+
inFlight.set(k, pending);
|
|
33219
|
+
}
|
|
33220
|
+
const minted = await pending;
|
|
33221
|
+
return minted.accessToken;
|
|
33222
|
+
};
|
|
33223
|
+
const invalidate = async (rejected) => {
|
|
33224
|
+
const k = await key();
|
|
33225
|
+
const hit = cache.get(k);
|
|
33226
|
+
if (!hit || hit.accessToken !== rejected) {
|
|
33227
|
+
logAuthTransition("token.evict-noop", {
|
|
33228
|
+
credential: credentialTag(k),
|
|
33229
|
+
reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
|
|
33230
|
+
});
|
|
33231
|
+
return false;
|
|
33232
|
+
}
|
|
33233
|
+
cache.delete(k);
|
|
33234
|
+
logAuthTransition("token.evicted", {
|
|
33235
|
+
credential: credentialTag(k),
|
|
33236
|
+
reason: "Google rejected this access token; the next read will mint a new one"
|
|
33237
|
+
});
|
|
33238
|
+
return true;
|
|
33239
|
+
};
|
|
33240
|
+
return Object.assign(read, {
|
|
33241
|
+
invalidate,
|
|
33242
|
+
credentialId: async () => credentialTag(await key())
|
|
33243
|
+
});
|
|
33244
|
+
}
|
|
33245
|
+
var TokenExchangeError = class extends Error {
|
|
33246
|
+
/**
|
|
33247
|
+
* The REFRESH token is dead (Google's `invalid_grant`), not merely the access
|
|
33248
|
+
* token. Carried as a flag rather than re-read from the message, because
|
|
33249
|
+
* inferring the author of a failure from prose several authors can produce is
|
|
33250
|
+
* precisely the mistake this branch exists to undo. `instanceof` is safe: the
|
|
33251
|
+
* class is thrown and caught inside this one module.
|
|
33252
|
+
*/
|
|
33253
|
+
grantDead;
|
|
33254
|
+
constructor(message, grantDead) {
|
|
33255
|
+
super(message);
|
|
33256
|
+
this.grantDead = grantDead;
|
|
33257
|
+
}
|
|
33258
|
+
};
|
|
33259
|
+
async function exchange(refreshToken, clientId, clientSecret) {
|
|
33260
|
+
let res;
|
|
33261
|
+
try {
|
|
33262
|
+
res = await fetch(TOKEN_ENDPOINT, {
|
|
33263
|
+
method: "POST",
|
|
33264
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
33265
|
+
body: new URLSearchParams({
|
|
33266
|
+
grant_type: "refresh_token",
|
|
33267
|
+
refresh_token: refreshToken,
|
|
33268
|
+
client_id: clientId,
|
|
33269
|
+
client_secret: clientSecret
|
|
33270
|
+
}).toString()
|
|
33271
|
+
});
|
|
33272
|
+
} catch (err) {
|
|
33273
|
+
throw new TokenExchangeError(
|
|
33274
|
+
`the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
|
|
33275
|
+
false
|
|
33276
|
+
);
|
|
33277
|
+
}
|
|
33278
|
+
const body = await res.json().catch(() => ({}));
|
|
33279
|
+
if (!res.ok) {
|
|
33280
|
+
if (body.error === "invalid_grant") {
|
|
33281
|
+
throw new TokenExchangeError(
|
|
33282
|
+
'the stored refresh token was rejected (invalid_grant): it has expired or been revoked, so this account must be re-authorized (commonly the 7-day limit on OAuth consent screens still in "Testing" mode). Re-enrol with gog_auth_add_url + gog_auth_add_complete and store the new refresh token.',
|
|
33283
|
+
true
|
|
33284
|
+
);
|
|
33285
|
+
}
|
|
33286
|
+
throw new TokenExchangeError(
|
|
33287
|
+
`the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
|
|
33288
|
+
false
|
|
33289
|
+
);
|
|
33290
|
+
}
|
|
33291
|
+
if (!body.access_token) {
|
|
33292
|
+
throw new TokenExchangeError(
|
|
33293
|
+
"the access token could not be refreshed: Google returned no access_token",
|
|
33294
|
+
false
|
|
33295
|
+
);
|
|
33296
|
+
}
|
|
33297
|
+
const expiresInMs = (body.expires_in ?? 3600) * 1e3;
|
|
33298
|
+
return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
|
|
33299
|
+
}
|
|
33300
|
+
|
|
33097
33301
|
// src/connector-runtime.ts
|
|
33098
33302
|
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
33099
33303
|
var DEADLINE_GRACE_MS = 5e3;
|
|
33304
|
+
var MIN_REPLAY_BUDGET_MS = 1e3;
|
|
33100
33305
|
var RUNNER_GOG_FAILED = 422;
|
|
33101
33306
|
var RUNNER_DRAINING = 503;
|
|
33307
|
+
var RUNNER_BAD_REQUEST = 400;
|
|
33308
|
+
var RUNNER_BAD_KEY = 401;
|
|
33309
|
+
var GogFailedError = class extends Error {
|
|
33310
|
+
/** gog's stderr alone, with no echoed argv mixed in. */
|
|
33311
|
+
stderr;
|
|
33312
|
+
constructor(message, stderr) {
|
|
33313
|
+
super(message);
|
|
33314
|
+
this.stderr = stderr;
|
|
33315
|
+
}
|
|
33316
|
+
};
|
|
33317
|
+
var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
|
|
33318
|
+
var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
|
|
33319
|
+
var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
|
|
33320
|
+
"cat",
|
|
33321
|
+
"describe",
|
|
33322
|
+
"get",
|
|
33323
|
+
"info",
|
|
33324
|
+
"list",
|
|
33325
|
+
"list-slides",
|
|
33326
|
+
"ls",
|
|
33327
|
+
"metadata",
|
|
33328
|
+
"read-slide",
|
|
33329
|
+
"search",
|
|
33330
|
+
"services",
|
|
33331
|
+
"status",
|
|
33332
|
+
"structure"
|
|
33333
|
+
]);
|
|
33334
|
+
function gogTarget(args) {
|
|
33335
|
+
const words = args.filter((arg) => typeof arg === "string");
|
|
33336
|
+
let service;
|
|
33337
|
+
for (let i = 0; i < words.length; i += 1) {
|
|
33338
|
+
const word = words[i];
|
|
33339
|
+
if (word.startsWith("-")) {
|
|
33340
|
+
if (word === "--account") i += 1;
|
|
33341
|
+
continue;
|
|
33342
|
+
}
|
|
33343
|
+
if (service === void 0) {
|
|
33344
|
+
service = word;
|
|
33345
|
+
continue;
|
|
33346
|
+
}
|
|
33347
|
+
return { service, subcommand: word };
|
|
33348
|
+
}
|
|
33349
|
+
return { service };
|
|
33350
|
+
}
|
|
33351
|
+
async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt) {
|
|
33352
|
+
if (!(err instanceof GogFailedError)) return void 0;
|
|
33353
|
+
const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
|
|
33354
|
+
if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
|
|
33355
|
+
const { service, subcommand } = gogTarget(args);
|
|
33356
|
+
const credential = await readAccessToken?.credentialId?.();
|
|
33357
|
+
const where = { credential, service };
|
|
33358
|
+
if (grantDead) {
|
|
33359
|
+
logAuthTransition("grant.dead", {
|
|
33360
|
+
...where,
|
|
33361
|
+
reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
|
|
33362
|
+
});
|
|
33363
|
+
return void 0;
|
|
33364
|
+
}
|
|
33365
|
+
if (!used) {
|
|
33366
|
+
logAuthTransition("replay.declined", {
|
|
33367
|
+
...where,
|
|
33368
|
+
reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
|
|
33369
|
+
});
|
|
33370
|
+
return void 0;
|
|
33371
|
+
}
|
|
33372
|
+
if (!readAccessToken?.invalidate) {
|
|
33373
|
+
logAuthTransition("replay.declined", {
|
|
33374
|
+
...where,
|
|
33375
|
+
reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
|
|
33376
|
+
});
|
|
33377
|
+
return void 0;
|
|
33378
|
+
}
|
|
33379
|
+
const evicted = await readAccessToken.invalidate(used);
|
|
33380
|
+
if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
|
|
33381
|
+
logAuthTransition("replay.declined", {
|
|
33382
|
+
...where,
|
|
33383
|
+
reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
|
|
33384
|
+
});
|
|
33385
|
+
return void 0;
|
|
33386
|
+
}
|
|
33387
|
+
if (!evicted) {
|
|
33388
|
+
logAuthTransition("replay.declined", {
|
|
33389
|
+
...where,
|
|
33390
|
+
reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
|
|
33391
|
+
});
|
|
33392
|
+
return void 0;
|
|
33393
|
+
}
|
|
33394
|
+
const fresh = await readAccessToken();
|
|
33395
|
+
if (!fresh) {
|
|
33396
|
+
logAuthTransition("replay.declined", {
|
|
33397
|
+
...where,
|
|
33398
|
+
reason: "the token source produced no token after eviction; replaying without one would act as the backend"
|
|
33399
|
+
});
|
|
33400
|
+
return void 0;
|
|
33401
|
+
}
|
|
33402
|
+
const budgetMs = deadlineAt - Date.now();
|
|
33403
|
+
if (budgetMs < MIN_REPLAY_BUDGET_MS) {
|
|
33404
|
+
logAuthTransition("replay.declined", {
|
|
33405
|
+
...where,
|
|
33406
|
+
reason: `only ${budgetMs}ms of the call\u2019s deadline remained, so a replay could only time out; the rejected token was evicted, so the next call mints a fresh one`
|
|
33407
|
+
});
|
|
33408
|
+
return void 0;
|
|
33409
|
+
}
|
|
33410
|
+
return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
|
|
33411
|
+
}
|
|
33102
33412
|
function makeFlyExecutor(endpoint, key, readAccessToken) {
|
|
33103
33413
|
return async (args, opts) => {
|
|
33104
33414
|
const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
|
|
33105
|
-
const accessToken = readAccessToken?.();
|
|
33106
|
-
|
|
33415
|
+
const accessToken = await readAccessToken?.();
|
|
33416
|
+
const deadlineAt = Date.now() + deadlineMs;
|
|
33107
33417
|
try {
|
|
33108
|
-
|
|
33109
|
-
method: "POST",
|
|
33110
|
-
headers: {
|
|
33111
|
-
Authorization: "Bearer " + key,
|
|
33112
|
-
"Content-Type": "application/json"
|
|
33113
|
-
},
|
|
33114
|
-
body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
|
|
33115
|
-
signal: AbortSignal.timeout(deadlineMs)
|
|
33116
|
-
});
|
|
33418
|
+
return await attempt(endpoint, key, args, accessToken, deadlineMs);
|
|
33117
33419
|
} catch (err) {
|
|
33118
|
-
const
|
|
33119
|
-
|
|
33120
|
-
|
|
33121
|
-
|
|
33122
|
-
|
|
33420
|
+
const replay = await remintAfterGoogleRejection(
|
|
33421
|
+
err,
|
|
33422
|
+
accessToken,
|
|
33423
|
+
args,
|
|
33424
|
+
readAccessToken,
|
|
33425
|
+
deadlineAt
|
|
33426
|
+
);
|
|
33427
|
+
if (replay === void 0) throw err;
|
|
33428
|
+
const where = { credential: replay.credential, service: replay.service, endpoint };
|
|
33429
|
+
logAuthTransition("replay.attempted", {
|
|
33430
|
+
...where,
|
|
33431
|
+
reason: "Google rejected the access token; replaying this read once with a freshly minted one"
|
|
33432
|
+
});
|
|
33433
|
+
try {
|
|
33434
|
+
const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
|
|
33435
|
+
logAuthTransition("replay.succeeded", where);
|
|
33436
|
+
return stdout;
|
|
33437
|
+
} catch (replayErr) {
|
|
33438
|
+
logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
|
|
33439
|
+
if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
|
|
33440
|
+
await replay.invalidate(replay.token);
|
|
33441
|
+
}
|
|
33442
|
+
throw replayErr;
|
|
33123
33443
|
}
|
|
33124
|
-
throw err;
|
|
33125
33444
|
}
|
|
33126
|
-
|
|
33127
|
-
|
|
33128
|
-
|
|
33445
|
+
};
|
|
33446
|
+
}
|
|
33447
|
+
async function attempt(endpoint, key, args, accessToken, deadlineMs) {
|
|
33448
|
+
let res;
|
|
33449
|
+
try {
|
|
33450
|
+
res = await fetch(endpoint + "/run", {
|
|
33451
|
+
method: "POST",
|
|
33452
|
+
headers: {
|
|
33453
|
+
Authorization: "Bearer " + key,
|
|
33454
|
+
"Content-Type": "application/json"
|
|
33455
|
+
},
|
|
33456
|
+
body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
|
|
33457
|
+
signal: AbortSignal.timeout(deadlineMs)
|
|
33458
|
+
});
|
|
33459
|
+
} catch (err) {
|
|
33460
|
+
const name = err instanceof Error ? err.name : "";
|
|
33461
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
33462
|
+
throw new RunnerTransportError(
|
|
33463
|
+
`gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
|
|
33464
|
+
"transport-retryable"
|
|
33465
|
+
);
|
|
33466
|
+
}
|
|
33467
|
+
throw err;
|
|
33468
|
+
}
|
|
33469
|
+
if (!res.ok) {
|
|
33470
|
+
const body = await res.json().catch(() => null);
|
|
33471
|
+
const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
|
|
33129
33472
|
${body.stderr}` : body.error : "";
|
|
33130
|
-
|
|
33131
|
-
|
|
33132
|
-
|
|
33133
|
-
|
|
33134
|
-
throw new Error(
|
|
33135
|
-
`gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
|
|
33136
|
-
);
|
|
33137
|
-
}
|
|
33138
|
-
if (detail) {
|
|
33139
|
-
throw new Error(detail);
|
|
33140
|
-
}
|
|
33141
|
-
throw new Error(
|
|
33142
|
-
`gog-runner HTTP ${res.status}: the response did not come from the runner, so the request never reached gog. The backend Machine was most likely starting or shutting down \u2014 this is transient, retry the same call.`
|
|
33473
|
+
if (res.status === RUNNER_GOG_FAILED) {
|
|
33474
|
+
throw new GogFailedError(
|
|
33475
|
+
detail || "gog failed on the runner (no detail supplied)",
|
|
33476
|
+
typeof body?.stderr === "string" ? body.stderr : ""
|
|
33143
33477
|
);
|
|
33144
33478
|
}
|
|
33145
|
-
|
|
33146
|
-
|
|
33147
|
-
|
|
33479
|
+
if (res.status === RUNNER_BAD_KEY) {
|
|
33480
|
+
logAuthTransition("runner.auth-failed", {
|
|
33481
|
+
service: gogTarget(args).service,
|
|
33482
|
+
endpoint,
|
|
33483
|
+
reason: "the gog-runner rejected the connector\u2019s bearer token, so gog never ran and no Google credential was read; GOG_RUNNER_KEY does not match the Fly app\u2019s RUNNER_KEY"
|
|
33484
|
+
});
|
|
33485
|
+
throw new RunnerTransportError(
|
|
33486
|
+
"gog-runner rejected the connector's bearer token, so the request never reached gog and no Google credential was involved. The Worker secret GOG_RUNNER_KEY no longer matches RUNNER_KEY on the Fly app; set them to the same value (wrangler secret put GOG_RUNNER_KEY / fly secrets set RUNNER_KEY) and retry.",
|
|
33487
|
+
"transport-auth",
|
|
33488
|
+
res.status
|
|
33489
|
+
);
|
|
33490
|
+
}
|
|
33491
|
+
if (res.status === RUNNER_BAD_REQUEST) {
|
|
33492
|
+
throw new RunnerTransportError(
|
|
33493
|
+
detail || "gog-runner rejected the request (no detail supplied)",
|
|
33494
|
+
"transport-request",
|
|
33495
|
+
res.status
|
|
33496
|
+
);
|
|
33497
|
+
}
|
|
33498
|
+
if (res.status === RUNNER_DRAINING || body?.retryable === true) {
|
|
33499
|
+
throw new RunnerTransportError(
|
|
33500
|
+
`gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
|
|
33501
|
+
"transport-retryable",
|
|
33502
|
+
res.status
|
|
33503
|
+
);
|
|
33504
|
+
}
|
|
33505
|
+
if (detail) {
|
|
33506
|
+
throw new Error(detail);
|
|
33507
|
+
}
|
|
33508
|
+
throw new RunnerTransportError(
|
|
33509
|
+
`gog-runner HTTP ${res.status}: the response did not come from the runner, so the request never reached gog. The backend Machine was most likely starting or shutting down \u2014 this is transient, retry the same call.`,
|
|
33510
|
+
"transport-retryable",
|
|
33511
|
+
res.status
|
|
33512
|
+
);
|
|
33513
|
+
}
|
|
33514
|
+
const { stdout } = await res.json();
|
|
33515
|
+
return stdout;
|
|
33148
33516
|
}
|
|
33149
33517
|
|
|
33150
33518
|
// src/remote-runner.ts
|
|
@@ -33153,7 +33521,7 @@ function useRemoteGogRunner(env = process.env) {
|
|
|
33153
33521
|
const key = readEnvVar("GOG_RUNNER_KEY", { env });
|
|
33154
33522
|
if (!endpoint || !key) return false;
|
|
33155
33523
|
setDefaultGogExecutor(
|
|
33156
|
-
makeFlyExecutor(endpoint.replace(/\/+$/, ""), key, (
|
|
33524
|
+
makeFlyExecutor(endpoint.replace(/\/+$/, ""), key, makeAccessTokenSource(env))
|
|
33157
33525
|
);
|
|
33158
33526
|
return true;
|
|
33159
33527
|
}
|