@chrischall/microsoft-teams-mcp 0.2.0 → 0.2.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/dist/bundle.js CHANGED
@@ -2279,7 +2279,7 @@ var require_websocket = __commonJS({
2279
2279
  var http = __require("http");
2280
2280
  var net = __require("net");
2281
2281
  var tls = __require("tls");
2282
- var { randomBytes: randomBytes2, createHash } = __require("crypto");
2282
+ var { randomBytes: randomBytes3, createHash } = __require("crypto");
2283
2283
  var { Duplex, Readable } = __require("stream");
2284
2284
  var { URL: URL2 } = __require("url");
2285
2285
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2817,7 +2817,7 @@ var require_websocket = __commonJS({
2817
2817
  }
2818
2818
  }
2819
2819
  const defaultPort = isSecure ? 443 : 80;
2820
- const key = randomBytes2(16).toString("base64");
2820
+ const key = randomBytes3(16).toString("base64");
2821
2821
  const request = isSecure ? https.request : http.request;
2822
2822
  const protocolSet = /* @__PURE__ */ new Set();
2823
2823
  let perMessageDeflate;
@@ -38066,13 +38066,28 @@ var API_KEY_RE = new RegExp([
38066
38066
  "whsec_[A-Za-z0-9]{16,}\\b"
38067
38067
  // webhook signing secret (Stripe-style)
38068
38068
  ].map((p) => `\\b${p}`).join("|"), "g");
38069
- var QUERY_SECRET_RE = /([?&](?:access_token|refresh_token|client_secret|api_?key|signature|token|key|sig)=)[^&#\s"'<>`]+/gi;
38069
+ var QUERY_SECRET_RE = /([?&](?:(?:access|refresh|id|auth|session|csrf|xsrf)[_-]?token|client[_-]?secret|api[_-]?secret|api[_-]?key|password|passwd|signature|token|key|sig)=)[^&#\s"'<>`]+/gi;
38070
+ var OAUTH_CODE_RE = /([?&]code=)(?=[^&#\s"'<>`]{16,})[^&#\s"'<>`]+/gi;
38071
+ var FORM_PASSWORD_RE = /((?:^|[\s,;:"'(\[{])(?:password|passwd)=)[^&#\s"'<>`]+/gim;
38072
+ var HEADER_SECRET_RE = /(\b(?:x[-_][a-z0-9_-]*?(?:api[-_]?key|token|secret|auth)[a-z0-9_-]*|api[-_]?key)\s*:\s*)[^\s,;"'<>`]+/gi;
38070
38073
  var AWS_SIGV4_RE = /([?&]X-Amz-(?:Signature|Security-Token|Credential)=)[^&#\s"'<>`]+/gi;
38071
- var JSON_SECRET_KEYS = "access_token|refresh_token|client_secret|api_?key|password|passwd|secret|token";
38072
- var JSON_SECRET_DQ_RE = new RegExp(`("(?:${JSON_SECRET_KEYS})"\\s*:\\s*")[^"]*(")`, "gi");
38073
- var JSON_SECRET_SQ_RE = new RegExp(`('(?:${JSON_SECRET_KEYS})'\\s*:\\s*')[^']*(')`, "gi");
38074
+ var JSON_SECRET_KEYS = [
38075
+ "(?:access|refresh|id|auth|session|bearer|csrf|xsrf)[_-]?token",
38076
+ "client[_-]?secret",
38077
+ "api[_-]?secret",
38078
+ "(?:x[_-])?api[_-]?key",
38079
+ "private[_-]?key",
38080
+ "x[_-][a-z0-9_-]*?(?:api[_-]?key|token|secret|auth)[a-z0-9_-]*",
38081
+ "(?:proxy-)?authorization",
38082
+ "password",
38083
+ "passwd",
38084
+ "secret",
38085
+ "token"
38086
+ ].join("|");
38087
+ var JSON_SECRET_DQ_RE = new RegExp(`("(?:${JSON_SECRET_KEYS})"\\s*:\\s*")(?:[^"\\\\]|\\\\.)*(")`, "gi");
38088
+ var JSON_SECRET_SQ_RE = new RegExp(`('(?:${JSON_SECRET_KEYS})'\\s*:\\s*')(?:[^'\\\\]|\\\\.)*(')`, "gi");
38074
38089
  function redactSecrets(text) {
38075
- return text.replace(BEARER_RE, "$1[REDACTED]").replace(BASIC_AUTH_RE, "$1[REDACTED]").replace(SET_COOKIE_RE, "$1$2=[REDACTED]").replace(COOKIE_HEADER_RE, (_m, prefix, pairs) => `${prefix}${pairs.replace(/=[^;,\s]*/g, "=[REDACTED]")}`).replace(API_KEY_RE, "[REDACTED]").replace(QUERY_SECRET_RE, "$1[REDACTED]").replace(AWS_SIGV4_RE, "$1[REDACTED]").replace(JSON_SECRET_DQ_RE, "$1[REDACTED]$2").replace(JSON_SECRET_SQ_RE, "$1[REDACTED]$2").replace(JWT_RE, "[REDACTED]");
38090
+ return text.replace(BEARER_RE, "$1[REDACTED]").replace(BASIC_AUTH_RE, "$1[REDACTED]").replace(SET_COOKIE_RE, "$1$2=[REDACTED]").replace(COOKIE_HEADER_RE, (_m, prefix, pairs) => `${prefix}${pairs.replace(/=[^;,\s]*/g, "=[REDACTED]")}`).replace(API_KEY_RE, "[REDACTED]").replace(HEADER_SECRET_RE, "$1[REDACTED]").replace(QUERY_SECRET_RE, "$1[REDACTED]").replace(OAUTH_CODE_RE, "$1[REDACTED]").replace(FORM_PASSWORD_RE, "$1[REDACTED]").replace(AWS_SIGV4_RE, "$1[REDACTED]").replace(JSON_SECRET_DQ_RE, "$1[REDACTED]$2").replace(JSON_SECRET_SQ_RE, "$1[REDACTED]$2").replace(JWT_RE, "[REDACTED]");
38076
38091
  }
38077
38092
  function truncateErrorMessage(text, max = DEFAULT_ERROR_MESSAGE_MAX) {
38078
38093
  const str = text === null || text === void 0 ? "" : String(text);
@@ -38199,13 +38214,47 @@ async function createMcpServer(opts) {
38199
38214
  }
38200
38215
  return server;
38201
38216
  }
38217
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
38218
+ var DEFAULT_REPEAT_SIGNAL_GRACE_MS = 500;
38202
38219
  function withGracefulShutdown(target, opts = {}) {
38203
38220
  const shouldExit = opts.exit ?? true;
38221
+ if (opts.timeoutMs !== void 0 && !(Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0)) {
38222
+ throw new RangeError("withGracefulShutdown: timeoutMs must be a finite number greater than 0.");
38223
+ }
38224
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
38225
+ if (opts.repeatSignalGraceMs !== void 0 && !(Number.isFinite(opts.repeatSignalGraceMs) && opts.repeatSignalGraceMs >= 0)) {
38226
+ throw new RangeError("withGracefulShutdown: repeatSignalGraceMs must be a finite number >= 0.");
38227
+ }
38228
+ const repeatGraceMs = opts.repeatSignalGraceMs ?? DEFAULT_REPEAT_SIGNAL_GRACE_MS;
38204
38229
  let shuttingDown = false;
38230
+ let firstSignalAt = 0;
38231
+ let exited = false;
38232
+ const exitOnce = () => {
38233
+ if (exited)
38234
+ return;
38235
+ exited = true;
38236
+ process.exit(0);
38237
+ };
38205
38238
  const handler = (signal) => {
38206
- if (shuttingDown)
38239
+ if (shuttingDown) {
38240
+ if (Date.now() - firstSignalAt < repeatGraceMs)
38241
+ return;
38242
+ if (shouldExit) {
38243
+ console.error(`[mcp-utils] second ${signal} during shutdown \u2014 exiting now`);
38244
+ exitOnce();
38245
+ }
38207
38246
  return;
38247
+ }
38208
38248
  shuttingDown = true;
38249
+ firstSignalAt = Date.now();
38250
+ let timer;
38251
+ if (shouldExit) {
38252
+ timer = setTimeout(() => {
38253
+ console.error(`[mcp-utils] graceful shutdown on ${signal} did not finish in ${timeoutMs}ms \u2014 exiting`);
38254
+ exitOnce();
38255
+ }, timeoutMs);
38256
+ timer.unref?.();
38257
+ }
38209
38258
  void (async () => {
38210
38259
  try {
38211
38260
  if (opts.onSignal)
@@ -38214,8 +38263,10 @@ function withGracefulShutdown(target, opts = {}) {
38214
38263
  } catch (err) {
38215
38264
  console.error(`[mcp-utils] error during graceful shutdown on ${signal}: ${err instanceof Error ? err.message : String(err)}`);
38216
38265
  } finally {
38266
+ if (timer !== void 0)
38267
+ clearTimeout(timer);
38217
38268
  if (shouldExit)
38218
- process.exit(0);
38269
+ exitOnce();
38219
38270
  }
38220
38271
  })();
38221
38272
  };
@@ -38304,9 +38355,12 @@ var pageSchema = {
38304
38355
  page_size: external_exports.number().int().min(1).max(200).default(50).describe("Number of items per page (1-200).")
38305
38356
  };
38306
38357
  function toolAnnotations(opts = {}) {
38358
+ if (opts.readOnly === true && opts.destructive === true) {
38359
+ throw new Error("toolAnnotations: readOnly: true contradicts destructive: true \u2014 a destructive tool is not read-only.");
38360
+ }
38307
38361
  return {
38308
38362
  ...opts.title !== void 0 ? { title: opts.title } : {},
38309
- readOnlyHint: opts.readOnly ?? true,
38363
+ readOnlyHint: opts.readOnly ?? opts.destructive === void 0,
38310
38364
  ...opts.idempotent !== void 0 ? { idempotentHint: opts.idempotent } : {},
38311
38365
  ...opts.destructive !== void 0 ? { destructiveHint: opts.destructive } : {},
38312
38366
  ...opts.openWorld !== void 0 ? { openWorldHint: opts.openWorld } : {}
@@ -38315,7 +38369,7 @@ function toolAnnotations(opts = {}) {
38315
38369
 
38316
38370
  // src/version.ts
38317
38371
  var PACKAGE_NAME = "microsoft-teams-mcp";
38318
- var VERSION = "0.2.0";
38372
+ var VERSION = "0.2.1";
38319
38373
 
38320
38374
  // node_modules/@fetchproxy/protocol/dist/crypto.js
38321
38375
  var subtle = globalThis.crypto.subtle;
@@ -39134,6 +39188,8 @@ function validateFrame(raw) {
39134
39188
  return validateHelloRejected(raw);
39135
39189
  if (t === "extension-disconnected")
39136
39190
  return { type: "extension-disconnected" };
39191
+ if (t === "peer-gone")
39192
+ return validatePeerGone(raw);
39137
39193
  throw new ProtocolError3(`unknown frame type: ${String(t)}`);
39138
39194
  }
39139
39195
  function validateHello(raw) {
@@ -39207,16 +39263,8 @@ function validateHello(raw) {
39207
39263
  if (raw.domListSelectors !== void 0) {
39208
39264
  assertDomListSelectorsArray(raw.domListSelectors, "hello.domListSelectors");
39209
39265
  }
39210
- if (raw.accepts !== void 0) {
39211
- if (!Array.isArray(raw.accepts)) {
39212
- throw new ProtocolError3("hello.accepts: expected array");
39213
- }
39214
- for (const a of raw.accepts) {
39215
- if (typeof a !== "string") {
39216
- throw new ProtocolError3(`hello.accepts: entry must be string, got ${typeof a}`);
39217
- }
39218
- }
39219
- }
39266
+ if (raw.accepts !== void 0)
39267
+ assertAcceptsList(raw.accepts);
39220
39268
  if (raw.graphqlOps !== void 0) {
39221
39269
  assertGraphqlOpsArray(raw.graphqlOps, "hello.graphqlOps");
39222
39270
  }
@@ -39238,6 +39286,8 @@ function validateHello(raw) {
39238
39286
  assertBase64(raw.identityX25519Pub, "hello.identityX25519Pub");
39239
39287
  assertBase64(raw.identityEd25519Pub, "hello.identityEd25519Pub");
39240
39288
  assertBase64(raw.sessionNonce, "hello.sessionNonce");
39289
+ if (raw.accepts !== void 0)
39290
+ assertAcceptsList(raw.accepts);
39241
39291
  return raw;
39242
39292
  }
39243
39293
  throw new ProtocolError3(`hello.role: must be 'server' or 'extension', got ${String(role)}`);
@@ -39293,6 +39343,27 @@ function validatePairPending(raw) {
39293
39343
  }
39294
39344
  return { type: "pair-pending", mcpId: raw.mcpId, pairCode: raw.pairCode };
39295
39345
  }
39346
+ function assertAcceptsList(accepts) {
39347
+ if (!Array.isArray(accepts)) {
39348
+ throw new ProtocolError3("hello.accepts: expected array");
39349
+ }
39350
+ for (const a of accepts) {
39351
+ if (typeof a !== "string") {
39352
+ throw new ProtocolError3(`hello.accepts: entry must be string, got ${typeof a}`);
39353
+ }
39354
+ }
39355
+ }
39356
+ function validatePeerGone(raw) {
39357
+ assertString(raw.mcpId, "peer-gone.mcpId");
39358
+ if (!isValidMcpId(raw.mcpId))
39359
+ throw new ProtocolError3("peer-gone.mcpId: invalid format");
39360
+ for (const k of Object.keys(raw)) {
39361
+ if (k !== "type" && k !== "mcpId") {
39362
+ throw new ProtocolError3(`peer-gone: unexpected field ${JSON.stringify(k)}`);
39363
+ }
39364
+ }
39365
+ return { type: "peer-gone", mcpId: raw.mcpId };
39366
+ }
39296
39367
  function validateHelloRejected(raw) {
39297
39368
  assertString(raw.mcpId, "hello-rejected.mcpId");
39298
39369
  if (!isValidMcpId(raw.mcpId))
@@ -39828,12 +39899,6 @@ async function sealInnerFrame(sessionKey, mcpId, seq, inner, direction) {
39828
39899
  ciphertext: toB64(ct)
39829
39900
  };
39830
39901
  }
39831
- async function openEncryptedFrame(sessionKey, frame, direction) {
39832
- const result = await openEncryptedFrameDetailed(sessionKey, frame, direction);
39833
- if (result.stage === "ok")
39834
- return result.inner;
39835
- throw result.error instanceof Error ? result.error : new Error(String(result.error));
39836
- }
39837
39902
  async function openEncryptedFrameDetailed(sessionKey, frame, direction) {
39838
39903
  let pt;
39839
39904
  try {
@@ -40165,11 +40230,12 @@ async function awaitSessionReady(ready, opts) {
40165
40230
  }
40166
40231
 
40167
40232
  // node_modules/@fetchproxy/server/dist/extension-trust.js
40168
- import { readFile as readFile2, writeFile as writeFile2, rename as rename2, unlink as unlink2, mkdir as mkdir2, chmod as chmod2 } from "node:fs/promises";
40233
+ import { readFile as readFile2, writeFile as writeFile2, rename as rename2, unlink as unlink2, mkdir as mkdir2, chmod as chmod2, rm as rm2 } from "node:fs/promises";
40234
+ import { randomBytes as randomBytes2 } from "node:crypto";
40169
40235
  import { isAbsolute as isAbsolute2, join as join2 } from "node:path";
40170
40236
 
40171
40237
  // node_modules/@fetchproxy/server/dist/identity.js
40172
- import { readFile, readdir, writeFile, mkdir, chmod, rename, rm, unlink } from "node:fs/promises";
40238
+ import { readFile, readdir, writeFile, mkdir, chmod, rename, rm, unlink, link, lstat } from "node:fs/promises";
40173
40239
  import { randomBytes } from "node:crypto";
40174
40240
  import { isAbsolute, join } from "node:path";
40175
40241
  import { homedir } from "node:os";
@@ -40237,7 +40303,7 @@ async function openIdentityDir(dir) {
40237
40303
  }
40238
40304
  }
40239
40305
  var STAGING_BYTES = 6;
40240
- async function sweepStagingFiles(dir, serverName) {
40306
+ async function sweepStagingFiles(dir, serverName, opts = {}) {
40241
40307
  const base = safeIdentityFileBase(serverName).replace(/[.]/g, "\\.");
40242
40308
  const staging = new RegExp(`^${base}\\.json\\.[0-9a-f]{${STAGING_BYTES * 2}}\\.tmp$`);
40243
40309
  let names;
@@ -40246,35 +40312,80 @@ async function sweepStagingFiles(dir, serverName) {
40246
40312
  } catch {
40247
40313
  return;
40248
40314
  }
40249
- await Promise.all(names.filter((name) => staging.test(name)).map((name) => unlink(join(dir, name)).catch(() => void 0)));
40315
+ const cutoff = opts.olderThanMs === void 0 ? null : Date.now() - opts.olderThanMs;
40316
+ await Promise.all(names.filter((name) => staging.test(name)).map(async (name) => {
40317
+ const path = join(dir, name);
40318
+ if (cutoff !== null) {
40319
+ const st = await lstat(path).catch(() => null);
40320
+ if (st === null || st.mtimeMs > cutoff)
40321
+ return;
40322
+ }
40323
+ await unlink(path).catch(() => void 0);
40324
+ }));
40250
40325
  }
40251
- async function writeIdentityFile(dir, serverName, id) {
40326
+ async function loadOrCreateIdentity(serverName, dir = defaultIdentityDir()) {
40252
40327
  const path = identityFilePath(dir, serverName);
40253
40328
  await openIdentityDir(dir);
40254
- await sweepStagingFiles(dir, serverName);
40255
- const tmp = `${path}.${randomBytes(STAGING_BYTES).toString("hex")}.tmp`;
40256
40329
  try {
40257
- await writeFile(tmp, serializeIdentity(id), { mode: 384, flag: "wx" });
40258
- await chmod(tmp, 384);
40259
- await rename(tmp, path);
40330
+ return parseIdentity(await readFile(path, "utf8"));
40260
40331
  } catch (e) {
40261
- await rm(tmp, { force: true });
40262
- throw e;
40332
+ if (e.code !== "ENOENT" && !(e instanceof SyntaxError))
40333
+ throw e;
40334
+ }
40335
+ let unreadable = null;
40336
+ for (let attempt = 0; attempt < 5; attempt++) {
40337
+ const id = await generateIdentity();
40338
+ if (await publishIdentityIfAbsent(dir, serverName, id))
40339
+ return id;
40340
+ try {
40341
+ return parseIdentity(await readFile(path, "utf8"));
40342
+ } catch (e) {
40343
+ if (e.code === "ENOENT") {
40344
+ continue;
40345
+ }
40346
+ if (!(e instanceof SyntaxError))
40347
+ throw e;
40348
+ unreadable = e;
40349
+ await new Promise((r) => setTimeout(r, 20 * (attempt + 1)));
40350
+ }
40263
40351
  }
40264
- return path;
40352
+ if (unreadable !== null)
40353
+ throw unreadable;
40354
+ throw new Error(`fetchproxy: could not create an identity for ${JSON.stringify(serverName)} in ${dir}`);
40265
40355
  }
40266
- async function loadOrCreateIdentity(serverName, dir = defaultIdentityDir()) {
40356
+ var NO_HARD_LINKS = /* @__PURE__ */ new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS"]);
40357
+ async function publishIdentityIfAbsent(dir, serverName, id) {
40267
40358
  const path = identityFilePath(dir, serverName);
40268
- await openIdentityDir(dir);
40359
+ await sweepStagingFiles(dir, serverName, { olderThanMs: 6e4 });
40360
+ const tmp = `${path}.${randomBytes(STAGING_BYTES).toString("hex")}.tmp`;
40269
40361
  try {
40270
- return parseIdentity(await readFile(path, "utf8"));
40362
+ await writeFile(tmp, serializeIdentity(id), { mode: 384, flag: "wx" });
40363
+ await chmod(tmp, 384);
40364
+ try {
40365
+ await link(tmp, path);
40366
+ } catch (e) {
40367
+ const code = e.code;
40368
+ if (code === void 0 || !NO_HARD_LINKS.has(code))
40369
+ throw e;
40370
+ try {
40371
+ await writeFile(path, serializeIdentity(id), { mode: 384, flag: "wx" });
40372
+ } catch (writeErr) {
40373
+ if (writeErr.code !== "EEXIST") {
40374
+ await rm(path, { force: true }).catch(() => void 0);
40375
+ }
40376
+ throw writeErr;
40377
+ }
40378
+ await chmod(path, 384);
40379
+ }
40380
+ return true;
40271
40381
  } catch (e) {
40272
- if (e.code !== "ENOENT")
40273
- throw e;
40382
+ const code = e.code;
40383
+ if (code === "EEXIST" || code === "ENOENT")
40384
+ return false;
40385
+ throw e;
40386
+ } finally {
40387
+ await rm(tmp, { force: true });
40274
40388
  }
40275
- const id = await generateIdentity();
40276
- await writeIdentityFile(dir, serverName, id);
40277
- return id;
40278
40389
  }
40279
40390
 
40280
40391
  // node_modules/@fetchproxy/server/dist/extension-trust.js
@@ -40375,10 +40486,15 @@ async function readExtensionPin(serverName, dir = defaultTrustDir()) {
40375
40486
  async function writeExtensionPin(serverName, pin, dir = defaultTrustDir()) {
40376
40487
  const path = extensionTrustPath(serverName, dir);
40377
40488
  await mkdir2(dir, { recursive: true, mode: 448 });
40378
- const tmp = `${path}.tmp`;
40379
- await writeFile2(tmp, JSON.stringify(pin, null, 2), { mode: 384 });
40380
- await chmod2(tmp, 384);
40381
- await rename2(tmp, path);
40489
+ const tmp = `${path}.${randomBytes2(6).toString("hex")}.tmp`;
40490
+ try {
40491
+ await writeFile2(tmp, JSON.stringify(pin, null, 2), { mode: 384, flag: "wx" });
40492
+ await chmod2(tmp, 384);
40493
+ await rename2(tmp, path);
40494
+ } catch (e) {
40495
+ await rm2(tmp, { force: true });
40496
+ throw e;
40497
+ }
40382
40498
  }
40383
40499
 
40384
40500
  // node_modules/@fetchproxy/server/dist/host.js
@@ -40415,6 +40531,7 @@ function originVerdict(origin, allowLocal) {
40415
40531
  var HANDSHAKE_TIMEOUT_MS = 15e3;
40416
40532
  var MAX_PAYLOAD_BYTES = MAX_FRAME_BYTES;
40417
40533
  var enc4 = new TextEncoder();
40534
+ var OWN_DECRYPT_FAILURES_BEFORE_REHANDSHAKE = 3;
40418
40535
  async function startHost(opts) {
40419
40536
  const allowLocalOrigins = envAllowsLocalOrigins();
40420
40537
  if (allowLocalOrigins) {
@@ -40529,6 +40646,31 @@ async function startHost(opts) {
40529
40646
  return null;
40530
40647
  }
40531
40648
  };
40649
+ let ownDecryptFailures = 0;
40650
+ const rehandshakeOwnSession = async (ws) => {
40651
+ const hello = extensionHello;
40652
+ if (extensionWs !== ws || !hello)
40653
+ return;
40654
+ console.warn(`[fetchproxy] ${opts.ownServerName}: ${OWN_DECRYPT_FAILURES_BEFORE_REHANDSHAKE} frames in a row from the extension failed authentication under this MCP's session key \u2014 re-handshaking this MCP's session (the extension stays connected).`);
40655
+ ownSession = dropOwnSessionAndEphemeral();
40656
+ resetSessionPromise();
40657
+ const mintedKeypair = await generateSessionKeypair();
40658
+ const mintedHello = await buildServerHello({
40659
+ ...ownHelloBase,
40660
+ sessionPub: mintedKeypair.publicKey,
40661
+ answersExtNonce: fromB64(hello.sessionNonce)
40662
+ });
40663
+ if (extensionWs !== ws || extensionHello !== hello || ownSession !== null) {
40664
+ mintedKeypair.privateKey.fill(0);
40665
+ return;
40666
+ }
40667
+ installOwnEphemeral({
40668
+ nonce: fromB64(mintedHello.sessionNonce),
40669
+ pub: mintedKeypair.publicKey,
40670
+ priv: mintedKeypair.privateKey
40671
+ });
40672
+ ws.send(JSON.stringify(mintedHello));
40673
+ };
40532
40674
  wss.on("connection", (ws) => {
40533
40675
  let identified = null;
40534
40676
  let peerMcpId = null;
@@ -40719,6 +40861,7 @@ async function startHost(opts) {
40719
40861
  if (extensionWs !== ws)
40720
40862
  return;
40721
40863
  ownSession = new SessionState(key);
40864
+ ownDecryptFailures = 0;
40722
40865
  ownPendingPairCode = null;
40723
40866
  resolveOwnSession(ownSession);
40724
40867
  } else {
@@ -40740,15 +40883,42 @@ async function startHost(opts) {
40740
40883
  }
40741
40884
  if (claim2 !== "ok")
40742
40885
  return;
40743
- let inner;
40886
+ let result;
40744
40887
  try {
40745
- inner = await openEncryptedFrame(session.sessionKey, frame, "e2s");
40888
+ result = await openEncryptedFrameDetailed(session.sessionKey, frame, "e2s");
40746
40889
  } catch (e) {
40747
40890
  session.releaseInboundSeq(frame.seq);
40748
40891
  throw e;
40749
40892
  }
40893
+ if (result.stage === "decrypt-failed") {
40894
+ session.releaseInboundSeq(frame.seq);
40895
+ console.warn(`[fetchproxy] ${opts.ownServerName}: dropped an inbound frame (seq ${frame.seq}) that failed authentication \u2014 most likely a straggler from a previous session.`);
40896
+ if (session === ownSession) {
40897
+ ownDecryptFailures += 1;
40898
+ if (ownDecryptFailures >= OWN_DECRYPT_FAILURES_BEFORE_REHANDSHAKE) {
40899
+ ownDecryptFailures = 0;
40900
+ void rehandshakeOwnSession(ws).catch((e) => console.error(`[fetchproxy] ${opts.ownServerName}: re-handshake failed:`, e));
40901
+ }
40902
+ }
40903
+ return;
40904
+ }
40905
+ if (session === ownSession)
40906
+ ownDecryptFailures = 0;
40750
40907
  session.commitInboundSeq(frame.seq);
40751
- ownInnerListeners.forEach((cb) => cb(inner));
40908
+ if (result.stage === "ok") {
40909
+ ownInnerListeners.forEach((cb) => cb(result.inner));
40910
+ } else {
40911
+ console.error("[fetchproxy] host: received a frame that decrypted OK but failed validation:", result.error);
40912
+ const recoveredId = result.recoveredId;
40913
+ if (recoveredId !== void 0) {
40914
+ ownInnerListeners.forEach((cb) => cb({
40915
+ type: "response",
40916
+ id: recoveredId,
40917
+ ok: false,
40918
+ error: `malformed response failed protocol validation: ${String(result.error)}`
40919
+ }));
40920
+ }
40921
+ }
40752
40922
  } else {
40753
40923
  const slot = peers.get(frame.mcpId);
40754
40924
  if (slot)
@@ -40807,6 +40977,7 @@ async function startHost(opts) {
40807
40977
  rejectOwnSession(new Error("extension disconnected before ready"));
40808
40978
  }
40809
40979
  ownSession = dropOwnSessionAndEphemeral();
40980
+ ownDecryptFailures = 0;
40810
40981
  ownPendingPairCode = null;
40811
40982
  resetSessionPromise();
40812
40983
  disconnectListeners.forEach((cb) => cb());
@@ -40821,8 +40992,15 @@ async function startHost(opts) {
40821
40992
  }
40822
40993
  }
40823
40994
  if (identified === "peer" && peerMcpId) {
40824
- if (peers.get(peerMcpId)?.ws === ws)
40995
+ if (peers.get(peerMcpId)?.ws === ws) {
40825
40996
  peers.delete(peerMcpId);
40997
+ if (extensionWs && extensionHello?.accepts?.includes("peer-gone")) {
40998
+ try {
40999
+ extensionWs.send(JSON.stringify({ type: "peer-gone", mcpId: peerMcpId }));
41000
+ } catch {
41001
+ }
41002
+ }
41003
+ }
40826
41004
  }
40827
41005
  });
40828
41006
  });
@@ -40865,12 +41043,18 @@ async function startHost(opts) {
40865
41043
  }
40866
41044
 
40867
41045
  // node_modules/@fetchproxy/server/dist/peer.js
41046
+ var PEER_DIAL_TIMEOUT_MS = 5e3;
40868
41047
  var enc5 = new TextEncoder();
41048
+ function notSentError() {
41049
+ return new Error("fetchproxy: request not sent \u2014 the connection to the bridge host closed before it went out, so nothing reached the browser. It is safe to retry.");
41050
+ }
40869
41051
  async function startPeer(opts) {
40870
41052
  const ws = new import_websocket.default(`ws://${opts.host}:${opts.port}`, {
40871
41053
  maxPayload: opts.maxPayloadBytes ?? MAX_PAYLOAD_BYTES
40872
41054
  });
41055
+ const dialTimeoutMs = opts.dialTimeoutMs ?? PEER_DIAL_TIMEOUT_MS;
40873
41056
  await new Promise((resolve, reject) => {
41057
+ let timer;
40874
41058
  const onOpen = () => {
40875
41059
  cleanup();
40876
41060
  resolve();
@@ -40880,11 +41064,21 @@ async function startPeer(opts) {
40880
41064
  reject(e);
40881
41065
  };
40882
41066
  const cleanup = () => {
41067
+ if (timer !== void 0)
41068
+ clearTimeout(timer);
40883
41069
  ws.off("open", onOpen);
40884
41070
  ws.off("error", onError);
40885
41071
  };
40886
41072
  ws.once("open", onOpen);
40887
41073
  ws.once("error", onError);
41074
+ if (dialTimeoutMs > 0) {
41075
+ timer = setTimeout(() => {
41076
+ cleanup();
41077
+ ws.on("error", () => void 0);
41078
+ ws.terminate();
41079
+ reject(new Error(`fetchproxy: the process holding ${opts.host}:${opts.port} did not answer the WebSocket upgrade within ${dialTimeoutMs}ms \u2014 it may be wedged or not a fetchproxy host. Restart the MCP that owns the port (or free it) and retry.`));
41080
+ }, dialTimeoutMs);
41081
+ }
40888
41082
  });
40889
41083
  ws.on("error", (e) => {
40890
41084
  console.warn(`[fetchproxy] peer: socket error: ${String(e)}`);
@@ -40927,6 +41121,7 @@ async function startPeer(opts) {
40927
41121
  const renegotiateListeners = [];
40928
41122
  const pendingPairListeners = [];
40929
41123
  const closeListeners = [];
41124
+ const extensionDisconnectListeners = [];
40930
41125
  let session = null;
40931
41126
  let sessionEphemeral = null;
40932
41127
  function dropSessionEphemeral() {
@@ -40946,10 +41141,24 @@ async function startPeer(opts) {
40946
41141
  let warnedUnverifiablePairCode = false;
40947
41142
  let resolveFirstReady;
40948
41143
  let rejectFirstReady;
40949
- const sessionPromise = new Promise((resolve, reject) => {
40950
- resolveFirstReady = resolve;
40951
- rejectFirstReady = reject;
40952
- });
41144
+ let sessionPromise;
41145
+ let sessionPromiseSettled = false;
41146
+ function resetSessionPromise() {
41147
+ sessionPromiseSettled = false;
41148
+ sessionPromise = new Promise((resolve, reject) => {
41149
+ resolveFirstReady = (st) => {
41150
+ sessionPromiseSettled = true;
41151
+ resolve(st);
41152
+ };
41153
+ rejectFirstReady = (e) => {
41154
+ sessionPromiseSettled = true;
41155
+ reject(e);
41156
+ };
41157
+ });
41158
+ sessionPromise.catch(() => {
41159
+ });
41160
+ }
41161
+ resetSessionPromise();
40953
41162
  let extensionHello = null;
40954
41163
  let extensionGone = false;
40955
41164
  let cachedPin = void 0;
@@ -41046,6 +41255,12 @@ async function startPeer(opts) {
41046
41255
  extensionGone = true;
41047
41256
  dropSessionEphemeral();
41048
41257
  pendingPairCode = null;
41258
+ if (session !== null) {
41259
+ session = null;
41260
+ if (sessionPromiseSettled)
41261
+ resetSessionPromise();
41262
+ }
41263
+ extensionDisconnectListeners.forEach((cb) => cb());
41049
41264
  return;
41050
41265
  }
41051
41266
  if (frame.type === "ready" && frame.mcpId === opts.mcpId) {
@@ -41162,19 +41377,30 @@ async function startPeer(opts) {
41162
41377
  }
41163
41378
  closeListeners.forEach((cb) => cb());
41164
41379
  });
41165
- sessionPromise.catch(() => {
41166
- });
41167
41380
  const handle = {
41168
41381
  ws,
41169
- session: sessionPromise,
41382
+ // A getter: `extension-disconnected` replaces the promise (B-BUG-5).
41383
+ get session() {
41384
+ return sessionPromise;
41385
+ },
41170
41386
  sendInner: async (inner) => {
41171
- await awaitSessionReady(sessionPromise, {
41172
- mcpId: opts.mcpId,
41173
- pendingPairCode: () => pendingPairCode
41174
- });
41387
+ try {
41388
+ await awaitSessionReady(sessionPromise, {
41389
+ mcpId: opts.mcpId,
41390
+ pendingPairCode: () => pendingPairCode
41391
+ });
41392
+ } catch (e) {
41393
+ if (ws.readyState !== import_websocket.default.OPEN)
41394
+ throw notSentError();
41395
+ throw e;
41396
+ }
41175
41397
  const s = session;
41398
+ if (s === null)
41399
+ throw new Error("peer: extension disconnected");
41176
41400
  const plaintext = encodeOutboundInnerFrame(opts.mcpId, inner);
41177
41401
  const sealed = await sealInnerFrame(s.sessionKey, opts.mcpId, s.nextOutboundSeq(), plaintext, "s2e");
41402
+ if (ws.readyState !== import_websocket.default.OPEN)
41403
+ throw notSentError();
41178
41404
  ws.send(JSON.stringify(sealed));
41179
41405
  },
41180
41406
  onInner: (cb) => {
@@ -41192,6 +41418,9 @@ async function startPeer(opts) {
41192
41418
  onClose: (cb) => {
41193
41419
  closeListeners.push(cb);
41194
41420
  },
41421
+ onExtensionDisconnect: (cb) => {
41422
+ extensionDisconnectListeners.push(cb);
41423
+ },
41195
41424
  close: () => ws.close()
41196
41425
  };
41197
41426
  return handle;
@@ -41199,15 +41428,15 @@ async function startPeer(opts) {
41199
41428
 
41200
41429
  // node_modules/@fetchproxy/server/dist/error-kind.js
41201
41430
  function classifyFetchError(error62) {
41431
+ if (/^(in-page )?fetch threw:/.test(error62)) {
41432
+ return "tab_fetch_failed";
41433
+ }
41202
41434
  if (/Could not establish connection/i.test(error62) || /Receiving end does not exist/i.test(error62)) {
41203
41435
  return "content_script_unreachable";
41204
41436
  }
41205
41437
  if (/^tab fetch failed:/.test(error62)) {
41206
41438
  return "tab_fetch_failed";
41207
41439
  }
41208
- if (/^(in-page )?fetch threw:/.test(error62)) {
41209
- return "tab_fetch_failed";
41210
- }
41211
41440
  if (/^no tab matching /.test(error62)) {
41212
41441
  return "no_tab";
41213
41442
  }
@@ -41399,6 +41628,17 @@ var FetchproxyTimeoutError = class extends FetchproxyProtocolError {
41399
41628
  * the message says which number that was and where it came from.
41400
41629
  */
41401
41630
  requestedTimeoutMs;
41631
+ /**
41632
+ * B-BUG-1: whether re-sending this request is safe. A timeout only means
41633
+ * the reply did not arrive in time — the extension may already have run the
41634
+ * request in the tab — so this is `false` for a non-idempotent `fetch`
41635
+ * (anything but GET/HEAD/OPTIONS) the caller did not mark `retryOnTimeout`,
41636
+ * for `download` and `writeCookies`, and for `graphqlQuery` unless the
41637
+ * caller marked it `retryOnTimeout` (a declared operation may be a
41638
+ * mutation). `retryOnceOnTimeout` honours it. Defaults to `true` (the read
41639
+ * verbs).
41640
+ */
41641
+ retrySafe;
41402
41642
  constructor(args) {
41403
41643
  const graceMs = args.graceMs ?? VERB_DEADLINE_GRACE_MS;
41404
41644
  const callerChose = args.requestedTimeoutMs !== void 0 && args.timeoutMs === args.requestedTimeoutMs + graceMs;
@@ -41411,6 +41651,7 @@ var FetchproxyTimeoutError = class extends FetchproxyProtocolError {
41411
41651
  this.elapsedMs = args.elapsedMs ?? args.timeoutMs;
41412
41652
  this.retryAttempted = args.retryAttempted ?? false;
41413
41653
  this.requestedTimeoutMs = args.requestedTimeoutMs ?? null;
41654
+ this.retrySafe = args.retrySafe ?? true;
41414
41655
  }
41415
41656
  };
41416
41657
  var SUBDOMAIN_LABEL_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
@@ -41450,6 +41691,32 @@ function assertUrlInDomains(field, url2, domains) {
41450
41691
  throw new Error(`FetchproxyServer: ${field} host "${host}" is outside declared domains [${declared}] \u2014 must be one of them or a subdomain`);
41451
41692
  }
41452
41693
  var DEFAULT_JSON_OK_STATUSES = [200, 201, 202, 204];
41694
+ function parseJsonBody(response) {
41695
+ if (response.status === 204 || response.body.trim() === "")
41696
+ return null;
41697
+ return JSON.parse(response.body);
41698
+ }
41699
+ var TIMEOUT_RETRY_SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
41700
+ function isRetrySafeOnTimeout(method, retryOnTimeout) {
41701
+ if (retryOnTimeout !== void 0)
41702
+ return retryOnTimeout;
41703
+ return TIMEOUT_RETRY_SAFE_METHODS.has(method.toUpperCase());
41704
+ }
41705
+ function isResendableRequest(inner) {
41706
+ switch (inner.op) {
41707
+ case "fetch":
41708
+ return isRetrySafeOnTimeout(inner.init.method);
41709
+ case "write_cookies":
41710
+ case "download":
41711
+ // A declared GraphQL operation may be a mutation; the server holds only
41712
+ // its name, so it cannot tell. `graphqlQuery({ retryOnTimeout: true })`
41713
+ // passes `resendable` explicitly for a known query.
41714
+ case "graphql_query":
41715
+ return false;
41716
+ default:
41717
+ return true;
41718
+ }
41719
+ }
41453
41720
  var FetchproxyServer = class {
41454
41721
  /**
41455
41722
  * Bridge role. `null` until the first verb call (or an explicit
@@ -41507,6 +41774,13 @@ var FetchproxyServer = class {
41507
41774
  // shape is operation-specific, so the awaiter resolves `unknown` and the
41508
41775
  // caller narrows.
41509
41776
  pendingGraphql = /* @__PURE__ */ new Map();
41777
+ /**
41778
+ * B-BUG-6: the frames of in-flight requests that are safe to send again
41779
+ * if the host that relayed them exits before replying (see
41780
+ * `recoverFromHostLoss`). Keyed by request id; an entry outlives its
41781
+ * request only until the next prune or response.
41782
+ */
41783
+ resendable = /* @__PURE__ */ new Map();
41510
41784
  mcpId = null;
41511
41785
  identity = null;
41512
41786
  // 0.5.3+: in-flight role-election / handle-start promise. Set the
@@ -41552,7 +41826,7 @@ var FetchproxyServer = class {
41552
41826
  }
41553
41827
  for (const c of opts.capabilities) {
41554
41828
  if (!KNOWN_CAPABILITIES.has(c)) {
41555
- throw new Error(`FetchproxyServer: unknown capability ${JSON.stringify(c)} \u2014 known values: ["fetch", "read_cookies"]`);
41829
+ throw new Error(`FetchproxyServer: unknown capability ${JSON.stringify(c)} \u2014 known values: ${JSON.stringify([...KNOWN_CAPABILITIES])}`);
41556
41830
  }
41557
41831
  }
41558
41832
  capabilities = [...opts.capabilities];
@@ -41780,6 +42054,10 @@ var FetchproxyServer = class {
41780
42054
  this.stopKeepalive();
41781
42055
  this.rejectAllPending();
41782
42056
  });
42057
+ this.peerHandle.onExtensionDisconnect(() => {
42058
+ this.stopKeepalive();
42059
+ this.rejectAllPending();
42060
+ });
41783
42061
  this.peerHandle.onPendingPair((code) => {
41784
42062
  this.rejectAllPending(this.pairingErrorMessage(code));
41785
42063
  });
@@ -41791,9 +42069,9 @@ var FetchproxyServer = class {
41791
42069
  if (this.closing || this.peerHandle === null)
41792
42070
  return;
41793
42071
  this.stopKeepalive();
41794
- this.rejectAllPending();
41795
42072
  this.peerHandle = null;
41796
42073
  this.role = null;
42074
+ void this.recoverFromHostLoss();
41797
42075
  });
41798
42076
  }
41799
42077
  }
@@ -41814,7 +42092,7 @@ var FetchproxyServer = class {
41814
42092
  * only when the bridge itself failed (no signed-in tab, extension
41815
42093
  * offline, etc.).
41816
42094
  */
41817
- async fetch(init) {
42095
+ async fetch(init, fetchOpts = {}) {
41818
42096
  await this.ensureConnected();
41819
42097
  const pendingCode = this.currentPendingPairCode();
41820
42098
  if (pendingCode !== null) {
@@ -41826,16 +42104,17 @@ var FetchproxyServer = class {
41826
42104
  retryAttempted: false
41827
42105
  };
41828
42106
  }
41829
- const first = await this._fetchOnceWithTimeout(init);
42107
+ const first = await this._fetchOnceWithTimeout(init, fetchOpts);
41830
42108
  const reviveMs = this.opts.bridgeReviveDelayMs;
41831
42109
  const isColdStartSymptom = !first.ok && (first.kind === "content_script_unreachable" || first.kind === "timeout");
41832
42110
  if (isColdStartSymptom) {
41833
42111
  this.lastEvictionDetectedAt = Date.now();
41834
42112
  }
41835
- if (isColdStartSymptom && reviveMs !== void 0 && reviveMs > 0) {
42113
+ const retryable = isColdStartSymptom && (first.kind === "content_script_unreachable" || isRetrySafeOnTimeout(init.method, fetchOpts.retryOnTimeout));
42114
+ if (retryable && reviveMs !== void 0 && reviveMs > 0) {
41836
42115
  this.lazyReviveAttempts += 1;
41837
42116
  await new Promise((r) => setTimeout(r, reviveMs));
41838
- const second = await this._fetchOnceWithTimeout(init);
42117
+ const second = await this._fetchOnceWithTimeout(init, fetchOpts);
41839
42118
  if (second.ok) {
41840
42119
  this.lazyReviveSuccesses += 1;
41841
42120
  this.recordSuccess();
@@ -41984,13 +42263,16 @@ var FetchproxyServer = class {
41984
42263
  * one of the op maps — request ids are unique) so it doesn't leak until the
41985
42264
  * server closes, then rethrow.
41986
42265
  */
41987
- async sendInnerFrame(inner) {
42266
+ async sendInnerFrame(inner, opts = {}) {
41988
42267
  try {
41989
42268
  if (this.hostHandle) {
41990
42269
  await this.hostHandle.sendOwnInner(inner);
41991
42270
  } else if (this.peerHandle) {
41992
42271
  await this.peerHandle.sendInner(inner);
41993
42272
  }
42273
+ if (inner.type === "request" && (opts.resendable ?? isResendableRequest(inner))) {
42274
+ this.noteResendable(inner);
42275
+ }
41994
42276
  } catch (err) {
41995
42277
  if ("id" in inner && typeof inner.id === "number") {
41996
42278
  const { id } = inner;
@@ -42013,13 +42295,25 @@ var FetchproxyServer = class {
42013
42295
  * On timeout returns the `{ok:false, kind:'timeout'}` envelope —
42014
42296
  * the throwing surface is the convenience methods.
42015
42297
  */
42016
- async _fetchOnceWithTimeout(init) {
42298
+ async _fetchOnceWithTimeout(init, fetchOpts = {}) {
42017
42299
  const id = this.nextRequestId++;
42018
42300
  const inner = { type: "request", id, op: "fetch", init };
42019
42301
  const pending = this.guardPending(new Promise((resolve) => {
42020
42302
  this.pending.set(id, resolve);
42021
42303
  }));
42022
- await this.sendInnerFrame(inner);
42304
+ try {
42305
+ await this.sendInnerFrame(inner, {
42306
+ resendable: isRetrySafeOnTimeout(init.method, fetchOpts.retryOnTimeout)
42307
+ });
42308
+ } catch (err) {
42309
+ return {
42310
+ ok: false,
42311
+ error: err instanceof Error ? err.message : String(err),
42312
+ kind: "session_not_ready",
42313
+ retryAttempted: false,
42314
+ cause: err
42315
+ };
42316
+ }
42023
42317
  const timeoutMs = this.opts.fetchTimeoutMs;
42024
42318
  if (timeoutMs === void 0 || timeoutMs <= 0)
42025
42319
  return pending;
@@ -42093,7 +42387,7 @@ var FetchproxyServer = class {
42093
42387
  });
42094
42388
  return pending;
42095
42389
  }
42096
- async _withVerbTimeout(pending, pendingMap, id, url2, requestedTimeoutMs) {
42390
+ async _withVerbTimeout(pending, pendingMap, id, url2, requestedTimeoutMs, retrySafe = true) {
42097
42391
  const transportMs = this.opts.fetchTimeoutMs;
42098
42392
  if (transportMs === void 0 || transportMs <= 0)
42099
42393
  return pending;
@@ -42114,6 +42408,7 @@ var FetchproxyServer = class {
42114
42408
  port: this.opts.port,
42115
42409
  elapsedMs: Date.now() - start,
42116
42410
  retryAttempted: false,
42411
+ retrySafe,
42117
42412
  graceMs,
42118
42413
  ...requestedTimeoutMs !== void 0 ? { requestedTimeoutMs } : {}
42119
42414
  }));
@@ -42131,7 +42426,7 @@ var FetchproxyServer = class {
42131
42426
  * logic re-implemented inline) `captureRequestHeader()` agree on what
42132
42427
  * to throw.
42133
42428
  */
42134
- _typedErrorFor(result, url2, op, retryAttempted) {
42429
+ _typedErrorFor(result, url2, op, retryAttempted, retrySafe = true) {
42135
42430
  if (result.kind === "timeout") {
42136
42431
  return new FetchproxyTimeoutError({
42137
42432
  url: url2,
@@ -42139,7 +42434,8 @@ var FetchproxyServer = class {
42139
42434
  role: this.role,
42140
42435
  port: this.opts.port,
42141
42436
  elapsedMs: result.elapsedMs,
42142
- retryAttempted
42437
+ retryAttempted,
42438
+ retrySafe
42143
42439
  });
42144
42440
  }
42145
42441
  if (result.kind === "content_script_unreachable") {
@@ -42213,9 +42509,12 @@ var FetchproxyServer = class {
42213
42509
  // every version before this option existed.
42214
42510
  ...opts.credentials === "omit" ? { credentials: "omit" } : {}
42215
42511
  };
42216
- const result = await this.fetch(init);
42512
+ const result = await this.fetch(init, opts.retryOnTimeout !== void 0 ? { retryOnTimeout: opts.retryOnTimeout } : {});
42217
42513
  if (!result.ok) {
42218
- throw this._typedErrorFor(result, init.url, "fetch", result.retryAttempted ?? false);
42514
+ if (result.kind === "session_not_ready" && result.cause instanceof Error) {
42515
+ throw result.cause;
42516
+ }
42517
+ throw this._typedErrorFor(result, init.url, "fetch", result.retryAttempted ?? false, isRetrySafeOnTimeout(method, opts.retryOnTimeout));
42219
42518
  }
42220
42519
  const response = {
42221
42520
  status: result.status,
@@ -42255,17 +42554,21 @@ var FetchproxyServer = class {
42255
42554
  * GET a path and parse the response body as JSON. Throws
42256
42555
  * `FetchproxyHttpError` if the status is outside the default 2xx
42257
42556
  * happy-path set (`[200, 201, 202, 204]`); pass a custom
42258
- * `expectStatus` to override.
42557
+ * `expectStatus` to override. A 204 or an empty/whitespace body
42558
+ * resolves to `null` (the declared `T` does not say so, to keep
42559
+ * existing call sites compiling — include `| null` in `T` if the
42560
+ * endpoint can answer empty).
42259
42561
  */
42260
42562
  async getJson(path, opts = {}) {
42261
42563
  const response = await this.get(path, this.applyJsonDefaults(opts));
42262
- return JSON.parse(response.body);
42564
+ return parseJsonBody(response);
42263
42565
  }
42264
42566
  /**
42265
42567
  * POST a JSON body and parse the response body as JSON. The body is
42266
42568
  * `JSON.stringify`'d; `Content-Type: application/json` is set unless
42267
42569
  * the caller already provided one. Defaults `expectStatus` to the 2xx
42268
- * happy-path set.
42570
+ * happy-path set. A 204 or an empty/whitespace body resolves to `null`
42571
+ * rather than throwing after the write already happened (see `getJson`).
42269
42572
  */
42270
42573
  async postJson(path, body, opts = {}) {
42271
42574
  const headers = { ...opts.headers ?? {} };
@@ -42277,7 +42580,7 @@ var FetchproxyServer = class {
42277
42580
  headers,
42278
42581
  body: body === void 0 ? void 0 : JSON.stringify(body)
42279
42582
  });
42280
- return JSON.parse(response.body);
42583
+ return parseJsonBody(response);
42281
42584
  }
42282
42585
  /**
42283
42586
  * GET a path and return the response body as a string. Throws
@@ -42298,7 +42601,8 @@ var FetchproxyServer = class {
42298
42601
  * - adds `Content-Type: application/json` only for a non-GET request
42299
42602
  * that carries a `body` (and only if the caller didn't set one);
42300
42603
  * - `JSON.stringify`s the body (GET / no-body sends nothing);
42301
- * - treats a `204` or an empty body as `data: null` (no parse);
42604
+ * - treats a `204`, an empty body, or a whitespace-only body as
42605
+ * `data: null` (no parse), the same rule as getJson/postJson;
42302
42606
  * - otherwise `JSON.parse`s the body.
42303
42607
  *
42304
42608
  * Scope is serialization + header defaults + 204-handling +
@@ -42312,6 +42616,11 @@ var FetchproxyServer = class {
42312
42616
  * Bridge-level failures (no signed-in tab, SW down, timeout) still
42313
42617
  * throw the typed errors via `request()`, exactly like the verb
42314
42618
  * helpers — only successful round-trips (any HTTP status) return.
42619
+ *
42620
+ * `retryOnTimeout` is `RequestOpts.retryOnTimeout`: a timed-out POST is
42621
+ * NOT re-sent unless the caller says it is safe to repeat. A read-only POST
42622
+ * (a search, a GraphQL query) should pass `true` to keep the cold-start
42623
+ * timeout retry (#90).
42315
42624
  */
42316
42625
  async requestJson(method, path, opts = {}) {
42317
42626
  const isGet = method.toUpperCase() === "GET";
@@ -42325,7 +42634,8 @@ var FetchproxyServer = class {
42325
42634
  headers,
42326
42635
  body: sendBody ? JSON.stringify(opts.body) : void 0,
42327
42636
  ...opts.subdomain !== void 0 ? { subdomain: opts.subdomain } : {},
42328
- ...opts.domain !== void 0 ? { domain: opts.domain } : {}
42637
+ ...opts.domain !== void 0 ? { domain: opts.domain } : {},
42638
+ ...opts.retryOnTimeout !== void 0 ? { retryOnTimeout: opts.retryOnTimeout } : {}
42329
42639
  });
42330
42640
  const result = {
42331
42641
  ok: true,
@@ -42333,12 +42643,9 @@ var FetchproxyServer = class {
42333
42643
  url: response.url,
42334
42644
  body: response.body
42335
42645
  };
42336
- if (response.status === 204 || response.body === "") {
42337
- return { data: null, result };
42338
- }
42339
42646
  let data;
42340
42647
  try {
42341
- data = JSON.parse(response.body);
42648
+ data = parseJsonBody(response);
42342
42649
  } catch (e) {
42343
42650
  throw new Error(`fetchproxy ${method} ${path} \u2014 response was not JSON: ${e instanceof Error ? e.message : String(e)}`);
42344
42651
  }
@@ -42395,18 +42702,19 @@ var FetchproxyServer = class {
42395
42702
  };
42396
42703
  }
42397
42704
  /**
42398
- * Snapshot the user's non-HttpOnly cookies for the chosen domain.
42705
+ * Read the user's cookies for the chosen domain.
42399
42706
  *
42400
42707
  * Requires `'read_cookies'` in `FetchproxyServerOpts.capabilities`.
42401
42708
  * Throws a developer-facing `Error` at the call site if the MCP did
42402
42709
  * not declare the capability — this is a programming mistake, not a
42403
42710
  * runtime condition.
42404
42711
  *
42405
- * The returned string is the raw `document.cookie` value (semicolon-
42406
- * separated `k=v` pairs). HttpOnly cookies are NOT visible to page JS
42407
- * and are therefore not included; the underlying threat model assumes
42408
- * the cookies that matter for the auth bootstrap (session tokens, csrf
42409
- * cookies that the page itself reads) are non-HttpOnly.
42712
+ * The returned string is semicolon-separated `k=v` pairs. With `keys`
42713
+ * (each in the declared `cookieKeys`), the extension reads each name via
42714
+ * `chrome.cookies.get`, which INCLUDES HttpOnly cookies — the login
42715
+ * session cookie among them; that is what cookie-session MCPs use it
42716
+ * for. Without `keys` (legacy), it is the tab's `document.cookie`, which
42717
+ * omits HttpOnly cookies. See docs/SECURITY.md §T-cookie-exfil.
42410
42718
  *
42411
42719
  * Throws `FetchproxyProtocolError` if the bridge could not deliver
42412
42720
  * the request (no signed-in tab, extension offline, etc.).
@@ -42502,7 +42810,15 @@ var FetchproxyServer = class {
42502
42810
  this.pendingWriteCookies.set(id, { resolve, reject });
42503
42811
  }));
42504
42812
  await this.sendInnerFrame(inner);
42505
- return this._withVerbTimeout(pending, this.pendingWriteCookies, id, `https://${host}`);
42813
+ return this._withVerbTimeout(
42814
+ pending,
42815
+ this.pendingWriteCookies,
42816
+ id,
42817
+ `https://${host}`,
42818
+ void 0,
42819
+ // A write: never re-sent after an ambiguous timeout.
42820
+ false
42821
+ );
42506
42822
  }
42507
42823
  /**
42508
42824
  * 0.3.0+: read declared localStorage keys from the user's signed-in
@@ -42605,53 +42921,7 @@ var FetchproxyServer = class {
42605
42921
  throw new Error("FetchproxyServer.captureRequestHeader: pass both host AND headerName, or neither (which defaults to the single declared entry)");
42606
42922
  }
42607
42923
  const callOpts = { ...resolved, ...opts?.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {} };
42608
- try {
42609
- const result = await this._captureRequestHeaderOnce(callOpts);
42610
- this.recordSuccess();
42611
- return result;
42612
- } catch (err) {
42613
- const swDown = err instanceof FetchproxyProtocolError && classifyFetchError(err.message) === "content_script_unreachable";
42614
- if (!swDown) {
42615
- this.recordFailure(`capture_request_header: ${err.message ?? String(err)}`);
42616
- throw err;
42617
- }
42618
- this.lastEvictionDetectedAt = Date.now();
42619
- const reviveMs = this.opts.bridgeReviveDelayMs ?? 0;
42620
- if (reviveMs > 0) {
42621
- this.lazyReviveAttempts += 1;
42622
- await new Promise((r) => setTimeout(r, reviveMs));
42623
- try {
42624
- const result = await this._captureRequestHeaderOnce(callOpts);
42625
- this.lazyReviveSuccesses += 1;
42626
- this.recordSuccess();
42627
- return result;
42628
- } catch (retryErr) {
42629
- const stillDown = retryErr instanceof FetchproxyProtocolError && classifyFetchError(retryErr.message) === "content_script_unreachable";
42630
- if (!stillDown) {
42631
- this.recordFailure(`capture_request_header: ${retryErr.message ?? String(retryErr)}`);
42632
- throw retryErr;
42633
- }
42634
- this.recordFailure(`capture_request_header bridge-down: ${retryErr.message}`);
42635
- throw new FetchproxyBridgeDownError({
42636
- originalError: retryErr.message,
42637
- retryAttempted: true,
42638
- op: "capture_request_header",
42639
- url: `https://${resolved.host}${resolved.path ?? "/*"}`,
42640
- role: this.role,
42641
- port: this.opts.port
42642
- });
42643
- }
42644
- }
42645
- this.recordFailure(`capture_request_header bridge-down: ${err.message}`);
42646
- throw new FetchproxyBridgeDownError({
42647
- originalError: err.message,
42648
- retryAttempted: false,
42649
- op: "capture_request_header",
42650
- url: `https://${resolved.host}${resolved.path ?? "/*"}`,
42651
- role: this.role,
42652
- port: this.opts.port
42653
- });
42654
- }
42924
+ return this.withLazyRevive("capture_request_header", `https://${resolved.host}${resolved.path ?? "/*"}`, () => this._captureRequestHeaderOnce(callOpts));
42655
42925
  }
42656
42926
  async _captureRequestHeaderOnce(opts) {
42657
42927
  const id = this.nextRequestId++;
@@ -42700,53 +42970,7 @@ var FetchproxyServer = class {
42700
42970
  }
42701
42971
  await this.ensureConnected();
42702
42972
  this.throwIfPendingPair();
42703
- try {
42704
- const result = await this._captureRedirectOnce(opts);
42705
- this.recordSuccess();
42706
- return result;
42707
- } catch (err) {
42708
- const swDown = err instanceof FetchproxyProtocolError && classifyFetchError(err.message) === "content_script_unreachable";
42709
- if (!swDown) {
42710
- this.recordFailure(`capture_redirect: ${err.message ?? String(err)}`);
42711
- throw err;
42712
- }
42713
- this.lastEvictionDetectedAt = Date.now();
42714
- const reviveMs = this.opts.bridgeReviveDelayMs ?? 0;
42715
- if (reviveMs > 0) {
42716
- this.lazyReviveAttempts += 1;
42717
- await new Promise((r) => setTimeout(r, reviveMs));
42718
- try {
42719
- const result = await this._captureRedirectOnce(opts);
42720
- this.lazyReviveSuccesses += 1;
42721
- this.recordSuccess();
42722
- return result;
42723
- } catch (retryErr) {
42724
- const stillDown = retryErr instanceof FetchproxyProtocolError && classifyFetchError(retryErr.message) === "content_script_unreachable";
42725
- if (!stillDown) {
42726
- this.recordFailure(`capture_redirect: ${retryErr.message ?? String(retryErr)}`);
42727
- throw retryErr;
42728
- }
42729
- this.recordFailure(`capture_redirect bridge-down: ${retryErr.message}`);
42730
- throw new FetchproxyBridgeDownError({
42731
- originalError: retryErr.message,
42732
- retryAttempted: true,
42733
- op: "capture_redirect",
42734
- url: `https://${opts.host}${opts.path ?? "/*"}`,
42735
- role: this.role,
42736
- port: this.opts.port
42737
- });
42738
- }
42739
- }
42740
- this.recordFailure(`capture_redirect bridge-down: ${err.message}`);
42741
- throw new FetchproxyBridgeDownError({
42742
- originalError: err.message,
42743
- retryAttempted: false,
42744
- op: "capture_redirect",
42745
- url: `https://${opts.host}${opts.path ?? "/*"}`,
42746
- role: this.role,
42747
- port: this.opts.port
42748
- });
42749
- }
42973
+ return this.withLazyRevive("capture_redirect", `https://${opts.host}${opts.path ?? "/*"}`, () => this._captureRedirectOnce(opts));
42750
42974
  }
42751
42975
  async _captureRedirectOnce(opts) {
42752
42976
  const id = this.nextRequestId++;
@@ -42791,52 +43015,57 @@ var FetchproxyServer = class {
42791
43015
  assertUrlInDomains("download url", opts.url, this.opts.domains);
42792
43016
  await this.ensureConnected();
42793
43017
  this.throwIfPendingPair();
43018
+ return this.withLazyRevive("download", opts.url, () => this._downloadOnce(opts));
43019
+ }
43020
+ /**
43021
+ * B-QUAL-1: the lazy-revive policy for the throwing verbs
43022
+ * (`capture_request_header`, `capture_redirect`, `download`), in one place.
43023
+ * Runs `once`; on the SW-eviction symptom (`content_script_unreachable` —
43024
+ * the request provably never reached a tab, so re-sending is safe) stamps
43025
+ * the eviction counter, waits `bridgeReviveDelayMs` and retries once, then
43026
+ * surfaces a `FetchproxyBridgeDownError`. Every other error is recorded and
43027
+ * rethrown untouched. `fetch()` keeps its own envelope-shaped variant.
43028
+ */
43029
+ async withLazyRevive(op, url2, once) {
43030
+ const isSwDown = (e) => e instanceof FetchproxyProtocolError && classifyFetchError(e.message) === "content_script_unreachable";
43031
+ const bridgeDown = (e, retryAttempted) => {
43032
+ this.recordFailure(`${op} bridge-down: ${e.message}`);
43033
+ return new FetchproxyBridgeDownError({
43034
+ originalError: e.message,
43035
+ retryAttempted,
43036
+ op,
43037
+ url: url2,
43038
+ role: this.role,
43039
+ port: this.opts.port
43040
+ });
43041
+ };
42794
43042
  try {
42795
- const result = await this._downloadOnce(opts);
43043
+ const result = await once();
42796
43044
  this.recordSuccess();
42797
43045
  return result;
42798
43046
  } catch (err) {
42799
- const swDown = err instanceof FetchproxyProtocolError && classifyFetchError(err.message) === "content_script_unreachable";
42800
- if (!swDown) {
42801
- this.recordFailure(`download: ${err.message ?? String(err)}`);
43047
+ if (!isSwDown(err)) {
43048
+ this.recordFailure(`${op}: ${err.message ?? String(err)}`);
42802
43049
  throw err;
42803
43050
  }
42804
43051
  this.lastEvictionDetectedAt = Date.now();
42805
43052
  const reviveMs = this.opts.bridgeReviveDelayMs ?? 0;
42806
- if (reviveMs > 0) {
42807
- this.lazyReviveAttempts += 1;
42808
- await new Promise((r) => setTimeout(r, reviveMs));
42809
- try {
42810
- const result = await this._downloadOnce(opts);
42811
- this.lazyReviveSuccesses += 1;
42812
- this.recordSuccess();
42813
- return result;
42814
- } catch (retryErr) {
42815
- const stillDown = retryErr instanceof FetchproxyProtocolError && classifyFetchError(retryErr.message) === "content_script_unreachable";
42816
- if (!stillDown) {
42817
- this.recordFailure(`download: ${retryErr.message ?? String(retryErr)}`);
42818
- throw retryErr;
42819
- }
42820
- this.recordFailure(`download bridge-down: ${retryErr.message}`);
42821
- throw new FetchproxyBridgeDownError({
42822
- originalError: retryErr.message,
42823
- retryAttempted: true,
42824
- op: "download",
42825
- url: opts.url,
42826
- role: this.role,
42827
- port: this.opts.port
42828
- });
43053
+ if (reviveMs <= 0)
43054
+ throw bridgeDown(err, false);
43055
+ this.lazyReviveAttempts += 1;
43056
+ await new Promise((r) => setTimeout(r, reviveMs));
43057
+ try {
43058
+ const result = await once();
43059
+ this.lazyReviveSuccesses += 1;
43060
+ this.recordSuccess();
43061
+ return result;
43062
+ } catch (retryErr) {
43063
+ if (!isSwDown(retryErr)) {
43064
+ this.recordFailure(`${op}: ${retryErr.message ?? String(retryErr)}`);
43065
+ throw retryErr;
42829
43066
  }
43067
+ throw bridgeDown(retryErr, true);
42830
43068
  }
42831
- this.recordFailure(`download bridge-down: ${err.message}`);
42832
- throw new FetchproxyBridgeDownError({
42833
- originalError: err.message,
42834
- retryAttempted: false,
42835
- op: "download",
42836
- url: opts.url,
42837
- role: this.role,
42838
- port: this.opts.port
42839
- });
42840
43069
  }
42841
43070
  }
42842
43071
  async _downloadOnce(opts) {
@@ -42865,7 +43094,9 @@ var FetchproxyServer = class {
42865
43094
  // CAP and need the identical explanation; missing it then was the point
42866
43095
  // of #279 — "both verbs" was counted off the two call sites in view
42867
43096
  // rather than off the type. Three is still the number.
42868
- opts.timeoutMs
43097
+ opts.timeoutMs,
43098
+ // A second download saves a duplicate "file (1)".
43099
+ false
42869
43100
  );
42870
43101
  }
42871
43102
  /**
@@ -43045,8 +43276,9 @@ var FetchproxyServer = class {
43045
43276
  const pending = this.guardPending(new Promise((resolve, reject) => {
43046
43277
  this.pendingGraphql.set(id, { resolve, reject });
43047
43278
  }));
43048
- await this.sendInnerFrame(inner);
43049
- return this._withVerbTimeout(pending, this.pendingGraphql, id, opts.name);
43279
+ const retrySafe = opts.retryOnTimeout === true;
43280
+ await this.sendInnerFrame(inner, { resendable: retrySafe });
43281
+ return this._withVerbTimeout(pending, this.pendingGraphql, id, opts.name, void 0, retrySafe);
43050
43282
  }
43051
43283
  assertScopeSubset(requested, declared, label) {
43052
43284
  const undeclared = undeclaredKeys(requested, declared);
@@ -43083,6 +43315,7 @@ var FetchproxyServer = class {
43083
43315
  onInner(inner) {
43084
43316
  if (inner.type !== "response")
43085
43317
  return;
43318
+ this.resendable.delete(inner.id);
43086
43319
  this.lastExtensionMessageAt = Date.now();
43087
43320
  const fetchCb = this.pending.get(inner.id);
43088
43321
  if (fetchCb) {
@@ -43244,45 +43477,133 @@ var FetchproxyServer = class {
43244
43477
  }
43245
43478
  }
43246
43479
  }
43247
- rejectAllPending(reason = "extension disconnected") {
43480
+ rejectAllPending(reason = "extension disconnected", keep = /* @__PURE__ */ new Set()) {
43481
+ for (const id of this.allPendingIds()) {
43482
+ if (!keep.has(id))
43483
+ this.rejectPendingId(id, reason);
43484
+ }
43485
+ if (keep.size === 0)
43486
+ this.resendable.clear();
43487
+ }
43488
+ /** Every request id with a live awaiter, across all op maps. */
43489
+ allPendingIds() {
43490
+ const ids = [];
43491
+ for (const map2 of this.pendingMaps())
43492
+ for (const id of map2.keys())
43493
+ ids.push(id);
43494
+ return ids;
43495
+ }
43496
+ pendingMaps() {
43497
+ return [
43498
+ this.pending,
43499
+ this.pendingReadCookies,
43500
+ this.pendingStorage,
43501
+ this.pendingWriteCookies,
43502
+ this.pendingCapture,
43503
+ this.pendingRedirect,
43504
+ this.pendingIdb,
43505
+ this.pendingDomList,
43506
+ this.pendingDownload,
43507
+ this.pendingGraphql
43508
+ ];
43509
+ }
43510
+ isPendingId(id) {
43511
+ return this.pendingMaps().some((m) => m.has(id));
43512
+ }
43513
+ /** Fail the one awaiter registered under `id`, in its own map's shape. */
43514
+ rejectPendingId(id, reason) {
43248
43515
  const err = new FetchproxyProtocolError(reason);
43249
- for (const cb of this.pending.values()) {
43250
- cb({
43516
+ this.resendable.delete(id);
43517
+ const fetchCb = this.pending.get(id);
43518
+ if (fetchCb) {
43519
+ this.pending.delete(id);
43520
+ fetchCb({
43251
43521
  ok: false,
43252
43522
  error: err.message,
43253
43523
  kind: classifyFetchError(err.message),
43254
43524
  retryAttempted: false
43255
43525
  });
43526
+ return;
43527
+ }
43528
+ const cookieCb = this.pendingReadCookies.get(id);
43529
+ if (cookieCb) {
43530
+ this.pendingReadCookies.delete(id);
43531
+ cookieCb({ ok: false, error: err.message });
43532
+ return;
43533
+ }
43534
+ for (const map2 of [
43535
+ this.pendingStorage,
43536
+ this.pendingWriteCookies,
43537
+ this.pendingCapture,
43538
+ this.pendingRedirect,
43539
+ this.pendingIdb,
43540
+ this.pendingDomList,
43541
+ this.pendingDownload,
43542
+ this.pendingGraphql
43543
+ ]) {
43544
+ const entry = map2.get(id);
43545
+ if (entry) {
43546
+ map2.delete(id);
43547
+ entry.reject(err);
43548
+ return;
43549
+ }
43550
+ }
43551
+ }
43552
+ noteResendable(inner) {
43553
+ this.resendable.set(inner.id, inner);
43554
+ if (this.resendable.size > 256) {
43555
+ for (const id of [...this.resendable.keys()]) {
43556
+ if (!this.isPendingId(id))
43557
+ this.resendable.delete(id);
43558
+ }
43256
43559
  }
43257
- this.pending.clear();
43258
- for (const cb of this.pendingReadCookies.values()) {
43259
- cb({ ok: false, error: err.message });
43260
- }
43261
- this.pendingReadCookies.clear();
43262
- for (const { reject } of this.pendingStorage.values())
43263
- reject(err);
43264
- this.pendingStorage.clear();
43265
- for (const { reject } of this.pendingWriteCookies.values())
43266
- reject(err);
43267
- this.pendingWriteCookies.clear();
43268
- for (const { reject } of this.pendingCapture.values())
43269
- reject(err);
43270
- this.pendingCapture.clear();
43271
- for (const { reject } of this.pendingRedirect.values())
43272
- reject(err);
43273
- this.pendingRedirect.clear();
43274
- for (const { reject } of this.pendingIdb.values())
43275
- reject(err);
43276
- this.pendingIdb.clear();
43277
- for (const { reject } of this.pendingDomList.values())
43278
- reject(err);
43279
- this.pendingDomList.clear();
43280
- for (const { reject } of this.pendingDownload.values())
43281
- reject(err);
43282
- this.pendingDownload.clear();
43283
- for (const { reject } of this.pendingGraphql.values())
43284
- reject(err);
43285
- this.pendingGraphql.clear();
43560
+ }
43561
+ /**
43562
+ * B-BUG-6: the host this peer relayed through has gone — most often a
43563
+ * short-lived process (a bootstrap lift, an `fpx` call) that won the
43564
+ * election and then closed. Fail only the in-flight requests that may
43565
+ * already have run (a non-idempotent fetch, a cookie write, a download);
43566
+ * re-elect and send the rest again. The replies to the originals died with
43567
+ * the old host, and each re-sent request keeps its awaiter and its
43568
+ * original deadline.
43569
+ */
43570
+ async recoverFromHostLoss() {
43571
+ const toResend = /* @__PURE__ */ new Map();
43572
+ for (const [id, inner] of this.resendable) {
43573
+ if (this.isPendingId(id))
43574
+ toResend.set(id, inner);
43575
+ }
43576
+ this.resendable.clear();
43577
+ this.rejectAllPending("fetchproxy: the MCP process holding the bridge port exited while this request was in flight. It was not re-sent because it may already have run in the browser \u2014 check before retrying.", new Set(toResend.keys()));
43578
+ if (toResend.size === 0)
43579
+ return;
43580
+ const lost = (id, e) => this.rejectPendingId(id, `fetchproxy: the bridge host exited and reconnecting failed: ${e instanceof Error ? e.message : String(e)}`);
43581
+ try {
43582
+ await this.ensureConnected();
43583
+ } catch (e) {
43584
+ for (const id of toResend.keys())
43585
+ lost(id, e);
43586
+ return;
43587
+ }
43588
+ for (const [id, inner] of toResend) {
43589
+ if (!this.isPendingId(id))
43590
+ continue;
43591
+ try {
43592
+ await this.resendInnerFrame(inner);
43593
+ } catch (e) {
43594
+ lost(id, e);
43595
+ }
43596
+ }
43597
+ }
43598
+ /** Send an already-registered request again, keeping its awaiter on failure. */
43599
+ async resendInnerFrame(inner) {
43600
+ if (this.hostHandle)
43601
+ await this.hostHandle.sendOwnInner(inner);
43602
+ else if (this.peerHandle)
43603
+ await this.peerHandle.sendInner(inner);
43604
+ else
43605
+ throw new Error("no bridge handle after re-election");
43606
+ this.noteResendable(inner);
43286
43607
  }
43287
43608
  /**
43288
43609
  * 0.5.2+: read the current pair-pending pair code from whichever handle
@@ -43428,7 +43749,8 @@ function createFetchproxyTransport(opts) {
43428
43749
  ...init.headers !== void 0 ? { headers: init.headers } : {},
43429
43750
  ...init.body !== void 0 ? { body: init.body } : {},
43430
43751
  ...init.subdomain !== void 0 ? { subdomain: init.subdomain } : {},
43431
- ...init.domain !== void 0 ? { domain: init.domain } : {}
43752
+ ...init.domain !== void 0 ? { domain: init.domain } : {},
43753
+ ...init.retryOnTimeout !== void 0 ? { retryOnTimeout: init.retryOnTimeout } : {}
43432
43754
  }));
43433
43755
  return { status: response.status, body: response.body, url: response.url };
43434
43756
  },
@@ -43437,7 +43759,8 @@ function createFetchproxyTransport(opts) {
43437
43759
  ...init.headers !== void 0 ? { headers: init.headers } : {},
43438
43760
  ...init.body !== void 0 ? { body: init.body } : {},
43439
43761
  ...init.subdomain !== void 0 ? { subdomain: init.subdomain } : {},
43440
- ...init.domain !== void 0 ? { domain: init.domain } : {}
43762
+ ...init.domain !== void 0 ? { domain: init.domain } : {},
43763
+ ...init.retryOnTimeout !== void 0 ? { retryOnTimeout: init.retryOnTimeout } : {}
43441
43764
  }));
43442
43765
  return {
43443
43766
  data,
@@ -43487,6 +43810,9 @@ function healthcheckHint(args) {
43487
43810
  }
43488
43811
  return `Unexpected error \u2014 see the error.message field for details.`;
43489
43812
  }
43813
+ function redactReason(reason) {
43814
+ return typeof reason === "string" ? truncateErrorMessage(reason) : reason;
43815
+ }
43490
43816
  function projectBridgeStatus(health) {
43491
43817
  const session = health.session;
43492
43818
  return {
@@ -43496,7 +43822,7 @@ function projectBridgeStatus(health) {
43496
43822
  fetch_timeout_ms: health.fetchTimeoutMs,
43497
43823
  last_success_at: health.lastSuccessAt,
43498
43824
  last_failure_at: health.lastFailureAt,
43499
- last_failure_reason: health.lastFailureReason,
43825
+ last_failure_reason: redactReason(health.lastFailureReason),
43500
43826
  consecutive_failures: health.consecutiveFailures,
43501
43827
  last_extension_message_at: health.lastExtensionMessageAt,
43502
43828
  ...session ? {
@@ -43555,9 +43881,10 @@ async function runBridgeHealthcheck(args) {
43555
43881
  elapsedMs = probeResult.elapsed_ms;
43556
43882
  bridge = {
43557
43883
  ...probeResult.bridge,
43884
+ last_failure_reason: redactReason(probeResult.bridge.last_failure_reason),
43558
43885
  last_extension_message_at: transport.status().lastExtensionMessageAt
43559
43886
  };
43560
- rawError = probeResult.error;
43887
+ rawError = probeResult.error ? { ...probeResult.error, message: truncateErrorMessage(probeResult.error.message) } : void 0;
43561
43888
  }
43562
43889
  const probe = ok ? { url: probeUrl, elapsed_ms: elapsedMs, status: 200, body_length: probeBody.length } : { url: probeUrl, elapsed_ms: elapsedMs };
43563
43890
  let error62;