tiny-http-mcp-server 0.1.25 → 0.1.27

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.
@@ -279,8 +279,8 @@ function receivedType(value) {
279
279
  }
280
280
  return typeof value;
281
281
  }
282
- function issue(path3, expected, value, message, keyword = keywordFor(expected)) {
283
- return { path: path3, expected, received: receivedType(value), message, keyword };
282
+ function issue(path5, expected, value, message, keyword = keywordFor(expected)) {
283
+ return { path: path5, expected, received: receivedType(value), message, keyword };
284
284
  }
285
285
  function keywordFor(expected) {
286
286
  if (["null", "boolean", "object", "array", "number", "integer", "string"].includes(expected)) {
@@ -997,113 +997,113 @@ function evaluateArrayApplicators(graph, node, schema, value, context) {
997
997
  }
998
998
  return results;
999
999
  }
1000
- function evaluateValidationKeywords(node, schema, value, path3) {
1000
+ function evaluateValidationKeywords(node, schema, value, path5) {
1001
1001
  const results = [];
1002
1002
  const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
1003
1003
  if (types.length > 0 && !types.some((type) => typeof type === "string" && typeMatches(type, value))) {
1004
- results.push(invalidResult(issue(path3, types.join(","), value, `must be ${types.join(",")}`)));
1004
+ results.push(invalidResult(issue(path5, types.join(","), value, `must be ${types.join(",")}`)));
1005
1005
  return results;
1006
1006
  }
1007
1007
  if (schema.const !== void 0 && !deepEqual(schema.const, value)) {
1008
- results.push(invalidResult(issue(path3, "const", value, "must be equal to constant")));
1008
+ results.push(invalidResult(issue(path5, "const", value, "must be equal to constant")));
1009
1009
  }
1010
1010
  if (Array.isArray(schema.enum) && !schema.enum.some((entry) => deepEqual(entry, value))) {
1011
- results.push(invalidResult(issue(path3, "enum", value, "must be equal to one of the allowed values")));
1011
+ results.push(invalidResult(issue(path5, "enum", value, "must be equal to one of the allowed values")));
1012
1012
  }
1013
1013
  if (typeof value === "number" && Number.isFinite(value)) {
1014
- evaluateNumberKeywords(schema, value, path3, results);
1014
+ evaluateNumberKeywords(schema, value, path5, results);
1015
1015
  }
1016
1016
  if (typeof value === "string") {
1017
- evaluateStringKeywords(schema, value, path3, results);
1017
+ evaluateStringKeywords(schema, value, path5, results);
1018
1018
  }
1019
1019
  if (Array.isArray(value)) {
1020
- evaluateArrayKeywords(schema, value, path3, results);
1020
+ evaluateArrayKeywords(schema, value, path5, results);
1021
1021
  }
1022
1022
  if (isObject(value)) {
1023
- evaluateObjectKeywords(node, schema, value, path3, results);
1023
+ evaluateObjectKeywords(node, schema, value, path5, results);
1024
1024
  }
1025
1025
  return results;
1026
1026
  }
1027
- function evaluateNumberKeywords(schema, value, path3, results) {
1027
+ function evaluateNumberKeywords(schema, value, path5, results) {
1028
1028
  if (typeof schema.multipleOf === "number" && !isMultipleOf(value, schema.multipleOf)) {
1029
- results.push(invalidResult(issue(path3, `multiple of ${schema.multipleOf}`, value, `must be multiple of ${schema.multipleOf}`)));
1029
+ results.push(invalidResult(issue(path5, `multiple of ${schema.multipleOf}`, value, `must be multiple of ${schema.multipleOf}`)));
1030
1030
  }
1031
1031
  if (typeof schema.maximum === "number" && value > schema.maximum) {
1032
- results.push(invalidResult(issue(path3, `<= ${schema.maximum}`, value, `must be <= ${schema.maximum}`)));
1032
+ results.push(invalidResult(issue(path5, `<= ${schema.maximum}`, value, `must be <= ${schema.maximum}`)));
1033
1033
  }
1034
1034
  if (typeof schema.minimum === "number" && value < schema.minimum) {
1035
- results.push(invalidResult(issue(path3, `>= ${schema.minimum}`, value, `must be >= ${schema.minimum}`)));
1035
+ results.push(invalidResult(issue(path5, `>= ${schema.minimum}`, value, `must be >= ${schema.minimum}`)));
1036
1036
  }
1037
1037
  if (typeof schema.exclusiveMaximum === "number" && value >= schema.exclusiveMaximum) {
1038
- results.push(invalidResult(issue(path3, `< ${schema.exclusiveMaximum}`, value, `must be < ${schema.exclusiveMaximum}`)));
1038
+ results.push(invalidResult(issue(path5, `< ${schema.exclusiveMaximum}`, value, `must be < ${schema.exclusiveMaximum}`)));
1039
1039
  }
1040
1040
  if (typeof schema.exclusiveMinimum === "number" && value <= schema.exclusiveMinimum) {
1041
- results.push(invalidResult(issue(path3, `> ${schema.exclusiveMinimum}`, value, `must be > ${schema.exclusiveMinimum}`)));
1041
+ results.push(invalidResult(issue(path5, `> ${schema.exclusiveMinimum}`, value, `must be > ${schema.exclusiveMinimum}`)));
1042
1042
  }
1043
1043
  }
1044
- function evaluateStringKeywords(schema, value, path3, results) {
1044
+ function evaluateStringKeywords(schema, value, path5, results) {
1045
1045
  const length = unicodeLength(value);
1046
1046
  if (typeof schema.maxLength === "number" && length > schema.maxLength) {
1047
- results.push(invalidResult(issue(path3, `length <= ${schema.maxLength}`, value, `must NOT have more than ${schema.maxLength} characters`)));
1047
+ results.push(invalidResult(issue(path5, `length <= ${schema.maxLength}`, value, `must NOT have more than ${schema.maxLength} characters`)));
1048
1048
  }
1049
1049
  if (typeof schema.minLength === "number" && length < schema.minLength) {
1050
- results.push(invalidResult(issue(path3, `length >= ${schema.minLength}`, value, `must NOT have fewer than ${schema.minLength} characters`)));
1050
+ results.push(invalidResult(issue(path5, `length >= ${schema.minLength}`, value, `must NOT have fewer than ${schema.minLength} characters`)));
1051
1051
  }
1052
1052
  if (typeof schema.pattern === "string" && !new RegExp(schema.pattern, "u").test(value)) {
1053
- results.push(invalidResult(issue(path3, `pattern ${schema.pattern}`, value, `must match pattern ${schema.pattern}`)));
1053
+ results.push(invalidResult(issue(path5, `pattern ${schema.pattern}`, value, `must match pattern ${schema.pattern}`)));
1054
1054
  }
1055
1055
  }
1056
- function evaluateArrayKeywords(schema, value, path3, results) {
1056
+ function evaluateArrayKeywords(schema, value, path5, results) {
1057
1057
  if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
1058
- results.push(invalidResult(issue(path3, `items <= ${schema.maxItems}`, value, `must NOT have more than ${schema.maxItems} items`)));
1058
+ results.push(invalidResult(issue(path5, `items <= ${schema.maxItems}`, value, `must NOT have more than ${schema.maxItems} items`)));
1059
1059
  }
1060
1060
  if (typeof schema.minItems === "number" && value.length < schema.minItems) {
1061
- results.push(invalidResult(issue(path3, `items >= ${schema.minItems}`, value, `must NOT have fewer than ${schema.minItems} items`)));
1061
+ results.push(invalidResult(issue(path5, `items >= ${schema.minItems}`, value, `must NOT have fewer than ${schema.minItems} items`)));
1062
1062
  }
1063
1063
  if (schema.uniqueItems === true) {
1064
1064
  for (let left = 0; left < value.length; left += 1) {
1065
1065
  for (let right = left + 1; right < value.length; right += 1) {
1066
1066
  if (deepEqual(value[left], value[right])) {
1067
- results.push(invalidResult(issue(path3, "unique items", value, "must NOT have duplicate items")));
1067
+ results.push(invalidResult(issue(path5, "unique items", value, "must NOT have duplicate items")));
1068
1068
  return;
1069
1069
  }
1070
1070
  }
1071
1071
  }
1072
1072
  }
1073
1073
  }
1074
- function evaluateObjectKeywords(node, schema, value, path3, results) {
1074
+ function evaluateObjectKeywords(node, schema, value, path5, results) {
1075
1075
  const keys = Object.keys(value);
1076
1076
  if (typeof schema.maxProperties === "number" && keys.length > schema.maxProperties) {
1077
- results.push(invalidResult(issue(path3, `properties <= ${schema.maxProperties}`, value, `must NOT have more than ${schema.maxProperties} properties`)));
1077
+ results.push(invalidResult(issue(path5, `properties <= ${schema.maxProperties}`, value, `must NOT have more than ${schema.maxProperties} properties`)));
1078
1078
  }
1079
1079
  if (typeof schema.minProperties === "number" && keys.length < schema.minProperties) {
1080
- results.push(invalidResult(issue(path3, `properties >= ${schema.minProperties}`, value, `must NOT have fewer than ${schema.minProperties} properties`)));
1080
+ results.push(invalidResult(issue(path5, `properties >= ${schema.minProperties}`, value, `must NOT have fewer than ${schema.minProperties} properties`)));
1081
1081
  }
1082
1082
  if (Array.isArray(schema.required)) {
1083
1083
  for (const key2 of schema.required) {
1084
1084
  if (typeof key2 === "string" && !Object.prototype.hasOwnProperty.call(value, key2)) {
1085
- results.push(invalidResult(issue([...path3, key2], "required", void 0, `must have required property '${key2}'`)));
1085
+ results.push(invalidResult(issue([...path5, key2], "required", void 0, `must have required property '${key2}'`)));
1086
1086
  }
1087
1087
  }
1088
1088
  }
1089
1089
  const dependentRequired = isObject(schema.dependentRequired) ? schema.dependentRequired : {};
1090
1090
  for (const [key2, dependencies] of Object.entries(dependentRequired)) {
1091
1091
  if (Object.prototype.hasOwnProperty.call(value, key2) && Array.isArray(dependencies)) {
1092
- addMissingDependencies(value, dependencies, path3, results);
1092
+ addMissingDependencies(value, dependencies, path5, results);
1093
1093
  }
1094
1094
  }
1095
1095
  if (node.dialect === "draft7" && isObject(schema.dependencies)) {
1096
1096
  for (const [key2, dependencies] of Object.entries(schema.dependencies)) {
1097
1097
  if (Object.prototype.hasOwnProperty.call(value, key2) && Array.isArray(dependencies)) {
1098
- addMissingDependencies(value, dependencies, path3, results);
1098
+ addMissingDependencies(value, dependencies, path5, results);
1099
1099
  }
1100
1100
  }
1101
1101
  }
1102
1102
  }
1103
- function addMissingDependencies(value, dependencies, path3, results) {
1103
+ function addMissingDependencies(value, dependencies, path5, results) {
1104
1104
  for (const dependency of dependencies) {
1105
1105
  if (typeof dependency === "string" && !Object.prototype.hasOwnProperty.call(value, dependency)) {
1106
- results.push(invalidResult(issue([...path3, dependency], "dependency", void 0, `must have property '${dependency}'`)));
1106
+ results.push(invalidResult(issue([...path5, dependency], "dependency", void 0, `must have property '${dependency}'`)));
1107
1107
  }
1108
1108
  }
1109
1109
  }
@@ -3397,19 +3397,168 @@ var SubscriptionManager = class {
3397
3397
 
3398
3398
  // ../mcp-oauth/dist/client/auth-store-session-store.js
3399
3399
  import crypto from "node:crypto";
3400
- import path2 from "node:path";
3400
+ import path4 from "node:path";
3401
3401
 
3402
3402
  // ../auth-store/dist/encrypted-file-store.js
3403
- import { createCipheriv, createDecipheriv, randomBytes, randomUUID, scrypt } from "node:crypto";
3403
+ import { createCipheriv, createDecipheriv, randomBytes, randomUUID as randomUUID2, scrypt } from "node:crypto";
3404
3404
  import { promises as fs } from "node:fs";
3405
3405
  import { homedir, hostname, userInfo } from "node:os";
3406
- import path from "node:path";
3406
+ import path2 from "node:path";
3407
3407
 
3408
3408
  // ../auth-store/dist/error-codes.js
3409
3409
  function hasOwnErrorCode(error, code) {
3410
3410
  return error instanceof Error && Object.prototype.hasOwnProperty.call(error, "code") && error.code === code;
3411
3411
  }
3412
3412
 
3413
+ // ../auth-store/dist/transaction-lock.js
3414
+ import { randomUUID } from "node:crypto";
3415
+ import path from "node:path";
3416
+ async function withSecretStoreFileLock(fs2, lockDirectory, operation, options = {}) {
3417
+ const timeoutMs = options.timeoutMs ?? 3e4;
3418
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647)
3419
+ throw new Error("Invalid secret-store transaction lock timeout");
3420
+ options.signal?.throwIfAborted();
3421
+ const deadline = performance.now() + timeoutMs;
3422
+ const directory = path.resolve(lockDirectory);
3423
+ await assertLockDirectoryPath(fs2, directory);
3424
+ await fs2.mkdir(directory, { recursive: true, mode: 448 });
3425
+ await assertLockDirectoryPath(fs2, directory);
3426
+ const name = `${process.pid}-${randomUUID()}.claim`;
3427
+ const claimPath = path.join(directory, name);
3428
+ const temporaryPath = `${claimPath}.tmp`;
3429
+ let claimed = true;
3430
+ let temporaryCreated = false;
3431
+ let outcome;
3432
+ try {
3433
+ try {
3434
+ await fs2.writeFile(claimPath, JSON.stringify({ ticket: null }), { encoding: "utf8", flag: "wx", mode: 384 });
3435
+ } catch (error) {
3436
+ if (hasOwnErrorCode(error, "EEXIST"))
3437
+ claimed = false;
3438
+ throw error;
3439
+ }
3440
+ const existing = await readClaims(fs2, directory, name);
3441
+ const ticket = existing.reduce((max, claim) => Math.max(max, claim.ticket ?? 0), 0) + 1;
3442
+ if (!Number.isSafeInteger(ticket))
3443
+ throw new Error("Secret-store transaction lock ticket overflow");
3444
+ temporaryCreated = true;
3445
+ try {
3446
+ await fs2.writeFile(temporaryPath, JSON.stringify({ ticket }), { encoding: "utf8", flag: "wx", mode: 384 });
3447
+ } catch (error) {
3448
+ if (hasOwnErrorCode(error, "EEXIST"))
3449
+ temporaryCreated = false;
3450
+ throw error;
3451
+ }
3452
+ await fs2.rename(temporaryPath, claimPath);
3453
+ temporaryCreated = false;
3454
+ for (; ; ) {
3455
+ options.signal?.throwIfAborted();
3456
+ const peers = await readClaims(fs2, directory, name);
3457
+ if (!peers.some((peer) => peer.ticket === null || peer.ticket < ticket || peer.ticket === ticket && peer.name < name))
3458
+ break;
3459
+ const remaining = deadline - performance.now();
3460
+ if (remaining <= 0)
3461
+ throw new Error("Timed out waiting for secret-store transaction lock");
3462
+ await new Promise((resolve, reject) => {
3463
+ const abort = () => {
3464
+ clearTimeout(timer);
3465
+ options.signal?.removeEventListener("abort", abort);
3466
+ reject(options.signal?.reason);
3467
+ };
3468
+ const timer = setTimeout(() => {
3469
+ options.signal?.removeEventListener("abort", abort);
3470
+ resolve();
3471
+ }, Math.min(10, remaining));
3472
+ options.signal?.addEventListener("abort", abort, { once: true });
3473
+ if (options.signal?.aborted)
3474
+ abort();
3475
+ });
3476
+ }
3477
+ options.signal?.throwIfAborted();
3478
+ outcome = { result: await operation() };
3479
+ } catch (error) {
3480
+ outcome = { error };
3481
+ }
3482
+ const cleanup = [];
3483
+ for (const target of [...temporaryCreated ? [temporaryPath] : [], ...claimed ? [claimPath] : []]) {
3484
+ try {
3485
+ await fs2.unlink(target);
3486
+ } catch (error) {
3487
+ if (!hasOwnErrorCode(error, "ENOENT"))
3488
+ cleanup.push(error);
3489
+ }
3490
+ }
3491
+ if (cleanup.length)
3492
+ throw new AggregateError([..."error" in outcome ? [outcome.error] : [], ...cleanup], "Secret-store transaction lock cleanup failed");
3493
+ if ("error" in outcome)
3494
+ throw outcome.error;
3495
+ return outcome.result;
3496
+ }
3497
+ async function assertNoSymbolicLink(fs2, target) {
3498
+ try {
3499
+ if ((await fs2.lstat(target)).isSymbolicLink())
3500
+ throw new Error("Refusing secret-store transaction lock through symbolic link");
3501
+ } catch (error) {
3502
+ if (!hasOwnErrorCode(error, "ENOENT"))
3503
+ throw error;
3504
+ }
3505
+ }
3506
+ async function assertLockDirectoryPath(fs2, directory) {
3507
+ const root = path.parse(directory).root;
3508
+ const segments = directory.slice(root.length).split(path.sep).filter(Boolean);
3509
+ let current = root;
3510
+ for (const [index, segment] of segments.entries()) {
3511
+ current = path.join(current, segment);
3512
+ if (index > 0 || segments.length === 1)
3513
+ await assertNoSymbolicLink(fs2, current);
3514
+ }
3515
+ }
3516
+ async function readClaims(fs2, directory, ownName) {
3517
+ const claims = [];
3518
+ for (const name of await fs2.readdir(directory)) {
3519
+ if (name === ownName || !name.endsWith(".claim"))
3520
+ continue;
3521
+ const pidText = name.slice(0, name.indexOf("-"));
3522
+ const pid = Number(pidText);
3523
+ if (!Number.isSafeInteger(pid) || pid < 1 || String(pid) !== pidText)
3524
+ throw new Error("Malformed secret-store transaction lock owner");
3525
+ const target = path.join(directory, name);
3526
+ await assertNoSymbolicLink(fs2, target);
3527
+ let alive = true;
3528
+ try {
3529
+ process.kill(pid, 0);
3530
+ } catch (error) {
3531
+ alive = !hasOwnErrorCode(error, "ESRCH");
3532
+ }
3533
+ if (!alive) {
3534
+ try {
3535
+ await fs2.unlink(target);
3536
+ } catch (error) {
3537
+ if (!hasOwnErrorCode(error, "ENOENT"))
3538
+ throw error;
3539
+ }
3540
+ continue;
3541
+ }
3542
+ let ticket = null;
3543
+ let raw;
3544
+ try {
3545
+ raw = await fs2.readFile(target, "utf8");
3546
+ } catch (error) {
3547
+ if (hasOwnErrorCode(error, "ENOENT"))
3548
+ continue;
3549
+ throw error;
3550
+ }
3551
+ try {
3552
+ const value = JSON.parse(raw);
3553
+ if (value !== null && typeof value === "object" && "ticket" in value && typeof value.ticket === "number" && Number.isSafeInteger(value.ticket) && value.ticket > 0)
3554
+ ticket = value.ticket;
3555
+ } catch {
3556
+ }
3557
+ claims.push({ name, ticket });
3558
+ }
3559
+ return claims;
3560
+ }
3561
+
3413
3562
  // ../auth-store/dist/encrypted-file-store.js
3414
3563
  var derivedKeyCache = /* @__PURE__ */ new Map();
3415
3564
  var ENCRYPTION_ALGORITHM = "aes-256-gcm";
@@ -3435,7 +3584,7 @@ var EncryptedFileStore = class {
3435
3584
  const defaultFileName = input.defaultFileName ?? "credentials.enc";
3436
3585
  assertSafeDefaultDirectory(defaultDirectory);
3437
3586
  assertSafeDefaultFileName(defaultFileName);
3438
- this.filePath = path.join(homeDirectory, defaultDirectory, defaultFileName);
3587
+ this.filePath = path2.join(homeDirectory, defaultDirectory, defaultFileName);
3439
3588
  this.symbolicLinkCheckStartPath = resolveDefaultDirectoryCheckStart(homeDirectory, defaultDirectory);
3440
3589
  } else {
3441
3590
  this.filePath = input.filePath;
@@ -3475,6 +3624,12 @@ var EncryptedFileStore = class {
3475
3624
  return null;
3476
3625
  }
3477
3626
  }
3627
+ async withLock(operation, options = {}) {
3628
+ await this.assertCredentialPathHasNoSymbolicLinks(`${this.filePath}.lock`);
3629
+ if (this.fs.readdir === void 0)
3630
+ throw new Error("Secret-store transaction locks require filesystem readdir support");
3631
+ return withSecretStoreFileLock(this.fs, `${this.filePath}.lock`, operation, options);
3632
+ }
3478
3633
  async set(value) {
3479
3634
  await this.assertCredentialPathHasNoSymbolicLinks(this.filePath);
3480
3635
  const key2 = await this.getEncryptionKey();
@@ -3491,9 +3646,9 @@ var EncryptedFileStore = class {
3491
3646
  authTag: authTag.toString("base64"),
3492
3647
  ciphertext: ciphertext.toString("base64")
3493
3648
  };
3494
- await this.fs.mkdir(path.dirname(this.filePath), { recursive: true });
3649
+ await this.fs.mkdir(path2.dirname(this.filePath), { recursive: true });
3495
3650
  await this.assertCredentialPathHasNoSymbolicLinks(this.filePath);
3496
- const temporaryPath = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
3651
+ const temporaryPath = `${this.filePath}.${process.pid}.${randomUUID2()}.tmp`;
3497
3652
  let temporaryCreated = false;
3498
3653
  try {
3499
3654
  await this.assertCredentialPathHasNoSymbolicLinks(temporaryPath);
@@ -3523,7 +3678,7 @@ var EncryptedFileStore = class {
3523
3678
  }
3524
3679
  }
3525
3680
  async assertCredentialPathHasNoSymbolicLinks(targetPath) {
3526
- const resolvedPath = path.resolve(targetPath);
3681
+ const resolvedPath = path2.resolve(targetPath);
3527
3682
  const protectedPaths = getProtectedCredentialPaths(resolvedPath, this.symbolicLinkCheckStartPath);
3528
3683
  for (const currentPath of protectedPaths) {
3529
3684
  try {
@@ -3554,26 +3709,26 @@ var EncryptedFileStore = class {
3554
3709
  };
3555
3710
  function resolveDefaultDirectoryCheckStart(homeDirectory, defaultDirectory) {
3556
3711
  const [firstSegment] = defaultDirectory.split(/[\\/]+/).filter(Boolean);
3557
- return path.resolve(homeDirectory, firstSegment ?? ".");
3712
+ return path2.resolve(homeDirectory, firstSegment ?? ".");
3558
3713
  }
3559
3714
  function getProtectedCredentialPaths(resolvedPath, symbolicLinkCheckStartPath) {
3560
3715
  if (symbolicLinkCheckStartPath === null) {
3561
3716
  return getExplicitProtectedCredentialPaths(resolvedPath);
3562
3717
  }
3563
- const resolvedStartPath = path.resolve(symbolicLinkCheckStartPath);
3718
+ const resolvedStartPath = path2.resolve(symbolicLinkCheckStartPath);
3564
3719
  if (!isPathInsideOrEqual(resolvedPath, resolvedStartPath)) {
3565
- return [path.dirname(resolvedPath), resolvedPath];
3720
+ return [path2.dirname(resolvedPath), resolvedPath];
3566
3721
  }
3567
3722
  const protectedPaths = [resolvedStartPath];
3568
3723
  let currentPath = resolvedStartPath;
3569
- for (const segment of path.relative(resolvedStartPath, resolvedPath).split(path.sep).filter(Boolean)) {
3570
- currentPath = path.join(currentPath, segment);
3724
+ for (const segment of path2.relative(resolvedStartPath, resolvedPath).split(path2.sep).filter(Boolean)) {
3725
+ currentPath = path2.join(currentPath, segment);
3571
3726
  protectedPaths.push(currentPath);
3572
3727
  }
3573
3728
  return protectedPaths;
3574
3729
  }
3575
3730
  function assertSafeDefaultDirectory(defaultDirectory) {
3576
- if (path.isAbsolute(defaultDirectory) || path.win32.isAbsolute(defaultDirectory)) {
3731
+ if (path2.isAbsolute(defaultDirectory) || path2.win32.isAbsolute(defaultDirectory)) {
3577
3732
  throw new Error("defaultDirectory must be a relative path inside the home directory");
3578
3733
  }
3579
3734
  for (const segment of splitPathSegments(defaultDirectory)) {
@@ -3591,15 +3746,15 @@ function splitPathSegments(value) {
3591
3746
  return value.split("/").flatMap((segment) => segment.split("\\")).filter((segment) => segment.length > 0);
3592
3747
  }
3593
3748
  function getExplicitProtectedCredentialPaths(resolvedPath) {
3594
- const parsed = path.parse(resolvedPath);
3595
- const segments = resolvedPath.slice(parsed.root.length).split(path.sep).filter((segment) => segment.length > 0);
3749
+ const parsed = path2.parse(resolvedPath);
3750
+ const segments = resolvedPath.slice(parsed.root.length).split(path2.sep).filter((segment) => segment.length > 0);
3596
3751
  if (segments.length <= 1) {
3597
3752
  return [resolvedPath];
3598
3753
  }
3599
3754
  const protectedPaths = [];
3600
3755
  let currentPath = parsed.root;
3601
3756
  for (const [index, segment] of segments.entries()) {
3602
- currentPath = path.join(currentPath, segment);
3757
+ currentPath = path2.join(currentPath, segment);
3603
3758
  if (index === 0) {
3604
3759
  continue;
3605
3760
  }
@@ -3608,8 +3763,8 @@ function getExplicitProtectedCredentialPaths(resolvedPath) {
3608
3763
  return protectedPaths;
3609
3764
  }
3610
3765
  function isPathInsideOrEqual(childPath, parentPath) {
3611
- const relativePath = path.relative(parentPath, childPath);
3612
- return relativePath === "" || !relativePath.startsWith("..") && !path.isAbsolute(relativePath);
3766
+ const relativePath = path2.relative(parentPath, childPath);
3767
+ return relativePath === "" || !relativePath.startsWith("..") && !path2.isAbsolute(relativePath);
3613
3768
  }
3614
3769
  async function removeIfPresent(fileSystem, filePath) {
3615
3770
  try {
@@ -3692,16 +3847,24 @@ function isAlreadyExistsError(error) {
3692
3847
 
3693
3848
  // ../auth-store/dist/keychain-store.js
3694
3849
  import { spawn } from "node:child_process";
3850
+ import { createHash } from "node:crypto";
3851
+ import { promises as nodeFs } from "node:fs";
3852
+ import { homedir as homedir2 } from "node:os";
3853
+ import path3 from "node:path";
3695
3854
  var SECURITY_CLI = "security";
3696
3855
  var KEYCHAIN_ITEM_NOT_FOUND_EXIT_CODE = 44;
3697
3856
  var KeychainStore = class {
3698
3857
  runCommand;
3699
3858
  service;
3700
3859
  account;
3860
+ lockFs;
3861
+ lockDirectory;
3701
3862
  constructor(input) {
3702
3863
  this.runCommand = input.runCommand ?? runSecurityCommand;
3703
3864
  this.service = input.service.trim();
3704
3865
  this.account = input.account.trim();
3866
+ this.lockFs = input.lock?.fs ?? nodeFs;
3867
+ this.lockDirectory = input.lock?.directory ?? path3.join(homedir2(), ".auth-store", "keychain-locks");
3705
3868
  if (this.service.length === 0) {
3706
3869
  throw new Error("Keychain service must not be empty");
3707
3870
  }
@@ -3719,6 +3882,10 @@ var KeychainStore = class {
3719
3882
  }
3720
3883
  throw createSecurityCliFailure("read secret from macOS Keychain", result);
3721
3884
  }
3885
+ async withLock(operation, options = {}) {
3886
+ const identity = createHash("sha256").update(JSON.stringify([this.service, this.account])).digest("hex");
3887
+ return withSecretStoreFileLock(this.lockFs, path3.join(this.lockDirectory, identity), operation, options);
3888
+ }
3722
3889
  async set(value) {
3723
3890
  if (value.includes("\n") || value.includes("\r")) {
3724
3891
  throw new Error("Keychain secrets cannot contain line breaks");
@@ -3904,6 +4071,12 @@ var DEFAULT_CLIENT_KEYCHAIN_SERVICE = "poe-code-mcp-oauth-clients";
3904
4071
  var MAX_JS_DATE_MS = 864e13;
3905
4072
  function createAuthStoreSessionStore(options = {}) {
3906
4073
  return {
4074
+ async withLock(resource, operation, lockOptions) {
4075
+ const store = createResourceSecretStore(resource, options);
4076
+ if (store.withLock === void 0)
4077
+ throw new Error("OAuth secret-store backend does not support transaction locks");
4078
+ return store.withLock(operation, lockOptions);
4079
+ },
3907
4080
  async load(resource) {
3908
4081
  const store = createResourceSecretStore(resource, options);
3909
4082
  const value = await store.get();
@@ -3958,10 +4131,10 @@ function createAuthStoreClientStore(options) {
3958
4131
  function createNamedSecretStore(key2, options, defaults) {
3959
4132
  const hash = crypto.createHash("sha256").update(key2).digest("hex");
3960
4133
  const configuredFilePath = options.fileStore?.filePath;
3961
- const parsedFilePath = configuredFilePath === void 0 ? null : path2.parse(configuredFilePath);
4134
+ const parsedFilePath = configuredFilePath === void 0 ? null : path4.parse(configuredFilePath);
3962
4135
  const fileStore = {
3963
4136
  ...options.fileStore,
3964
- filePath: parsedFilePath === null ? void 0 : path2.join(parsedFilePath.dir, `${parsedFilePath.name}-${hash}${parsedFilePath.ext || ".enc"}`),
4137
+ filePath: parsedFilePath === null ? void 0 : path4.join(parsedFilePath.dir, `${parsedFilePath.name}-${hash}${parsedFilePath.ext || ".enc"}`),
3965
4138
  salt: options.fileStore?.salt ?? defaults.salt,
3966
4139
  defaultDirectory: options.fileStore?.defaultDirectory || defaults.directory,
3967
4140
  defaultFileName: parsedFilePath === null ? `${hash}.enc` : `${parsedFilePath.name}-${hash}${parsedFilePath.ext || ".enc"}`
@@ -4585,6 +4758,55 @@ function normalizeBearerTokenType(value) {
4585
4758
  return value.toLowerCase() === "bearer" ? "Bearer" : null;
4586
4759
  }
4587
4760
 
4761
+ // ../mcp-oauth/dist/client/session-transaction.js
4762
+ var queues = /* @__PURE__ */ new WeakMap();
4763
+ async function withOAuthSessionTransaction(store, resource, operation, options = {}) {
4764
+ const timeoutMs = options.timeoutMs ?? 3e4;
4765
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
4766
+ throw new Error("sessionLockTimeoutMs must be an integer from 1 to 2147483647 milliseconds");
4767
+ options.signal?.throwIfAborted();
4768
+ const started = performance.now();
4769
+ const pending = queues.get(store) ?? /* @__PURE__ */ new Map();
4770
+ queues.set(store, pending);
4771
+ const previous = pending.get(resource) ?? Promise.resolve();
4772
+ let release;
4773
+ const current = new Promise((resolve) => {
4774
+ release = resolve;
4775
+ });
4776
+ const tail = previous.then(() => current);
4777
+ pending.set(resource, tail);
4778
+ try {
4779
+ let timer;
4780
+ let rejectWait;
4781
+ const waiting = new Promise((resolve, reject) => {
4782
+ rejectWait = reject;
4783
+ previous.then(resolve, reject);
4784
+ });
4785
+ const abort = () => rejectWait(options.signal?.reason);
4786
+ try {
4787
+ timer = setTimeout(() => rejectWait(new Error("Timed out waiting for OAuth session transaction lock")), timeoutMs);
4788
+ options.signal?.addEventListener("abort", abort, { once: true });
4789
+ if (options.signal?.aborted)
4790
+ abort();
4791
+ await waiting;
4792
+ } finally {
4793
+ clearTimeout(timer);
4794
+ options.signal?.removeEventListener("abort", abort);
4795
+ }
4796
+ options.signal?.throwIfAborted();
4797
+ return store.withLock === void 0 ? await operation() : await store.withLock(resource, operation, {
4798
+ signal: options.signal,
4799
+ timeoutMs: Math.max(0, timeoutMs - (performance.now() - started))
4800
+ });
4801
+ } finally {
4802
+ release();
4803
+ void tail.then(() => {
4804
+ if (pending.get(resource) === tail)
4805
+ pending.delete(resource);
4806
+ });
4807
+ }
4808
+ }
4809
+
4588
4810
  // ../mcp-oauth/dist/client/default-oauth-client-provider.js
4589
4811
  var MAX_JS_DATE_MS3 = 864e13;
4590
4812
  function createOAuthClientProvider(options) {
@@ -4599,8 +4821,6 @@ function createDefaultOAuthClientProvider(options) {
4599
4821
  const clientStore = options.authStore === void 0 ? null : createAuthStoreClientStore(options.authStore);
4600
4822
  const now = options.now ?? Date.now;
4601
4823
  const registeredClients = /* @__PURE__ */ new Map();
4602
- const refreshPromises = /* @__PURE__ */ new Map();
4603
- const authorizationPromises = /* @__PURE__ */ new Map();
4604
4824
  if (options.initialGrant !== void 0) {
4605
4825
  let resource;
4606
4826
  try {
@@ -4687,203 +4907,182 @@ function createDefaultOAuthClientProvider(options) {
4687
4907
  async function ensureAuthorizedSession(resource, discovery, fetch2, allowInteractive, forceRefresh = false, signal, rejectedTokens) {
4688
4908
  signal?.throwIfAborted();
4689
4909
  const canonicalResource = canonicalizeResourceIndicator(resource);
4690
- let session = await loadSession(canonicalResource);
4691
- if (session !== null && initialGrant?.resource === canonicalResource)
4692
- initialGrantConsumed = true;
4693
- signal?.throwIfAborted();
4694
- if (discovery !== void 0 && getOwnString2(discovery.authorizationServerMetadata, "issuer") !== discovery.authorizationServer) {
4695
- throw new Error("OAuth discovery authorization-server issuer mismatch");
4696
- }
4697
- if (session !== null && (canonicalizeResourceIndicator(session.resource) !== canonicalResource || getOwnString2(session.discovery.authorizationServerMetadata, "issuer") !== session.authorizationServer || discovery !== void 0 && discovery.authorizationServer !== session.authorizationServer)) {
4698
- await clearSession(canonicalResource);
4699
- session = null;
4700
- }
4701
- if (session === null && discovery !== void 0 && !initialGrantConsumed && initialGrant?.resource === canonicalResource && initialGrant.tokens !== void 0 && initialGrant.client !== null) {
4702
- assertSecureOAuthFlowEndpoints(discovery.authorizationServerMetadata);
4703
- session = {
4704
- resource: canonicalResource,
4705
- authorizationServer: discovery.authorizationServer,
4706
- client: initialGrant.client,
4707
- tokens: initialGrant.tokens,
4708
- discovery: toStoredDiscovery(discovery)
4709
- };
4710
- await saveSession(canonicalResource, session);
4711
- initialGrantConsumed = true;
4910
+ return withOAuthSessionTransaction(sessionStore, canonicalResource, async () => {
4911
+ let session = await loadSession(canonicalResource);
4912
+ if (session !== null && initialGrant?.resource === canonicalResource)
4913
+ initialGrantConsumed = true;
4712
4914
  signal?.throwIfAborted();
4713
- }
4714
- if (forceRefresh && rejectedTokens !== void 0 && (rejectedTokens === null || session?.tokens === void 0 || !sameTokenGrant(session.tokens, rejectedTokens)))
4715
- forceRefresh = false;
4716
- const sessionDiscovery = resolveDiscovery(discovery, session);
4717
- if (session?.tokens !== void 0 && !forceRefresh && !isExpired(session.tokens, now)) {
4718
- return session;
4719
- }
4720
- if (session?.tokens?.refreshToken !== void 0 && sessionDiscovery !== void 0 && (forceRefresh || isExpired(session.tokens, now))) {
4721
- session = await refreshSession(canonicalResource, session, sessionDiscovery, fetch2, signal);
4722
- if (session?.tokens !== void 0 && !isExpired(session.tokens, now)) {
4915
+ if (discovery !== void 0 && getOwnString2(discovery.authorizationServerMetadata, "issuer") !== discovery.authorizationServer) {
4916
+ throw new Error("OAuth discovery authorization-server issuer mismatch");
4917
+ }
4918
+ if (session !== null && (canonicalizeResourceIndicator(session.resource) !== canonicalResource || getOwnString2(session.discovery.authorizationServerMetadata, "issuer") !== session.authorizationServer || discovery !== void 0 && discovery.authorizationServer !== session.authorizationServer)) {
4919
+ await clearSession(canonicalResource);
4920
+ session = null;
4921
+ }
4922
+ if (session === null && discovery !== void 0 && !initialGrantConsumed && initialGrant?.resource === canonicalResource && initialGrant.tokens !== void 0 && initialGrant.client !== null) {
4923
+ assertSecureOAuthFlowEndpoints(discovery.authorizationServerMetadata);
4924
+ session = {
4925
+ resource: canonicalResource,
4926
+ authorizationServer: discovery.authorizationServer,
4927
+ client: initialGrant.client,
4928
+ tokens: initialGrant.tokens,
4929
+ discovery: toStoredDiscovery(discovery)
4930
+ };
4931
+ await saveSession(canonicalResource, session);
4932
+ initialGrantConsumed = true;
4933
+ signal?.throwIfAborted();
4934
+ }
4935
+ if (forceRefresh && rejectedTokens !== void 0 && (rejectedTokens === null || session?.tokens === void 0 || !sameTokenGrant(session.tokens, rejectedTokens)))
4936
+ forceRefresh = false;
4937
+ const sessionDiscovery = resolveDiscovery(discovery, session);
4938
+ if (session?.tokens !== void 0 && !forceRefresh && !isExpired(session.tokens, now)) {
4723
4939
  return session;
4724
4940
  }
4725
- }
4726
- if (forceRefresh && session?.tokens !== void 0) {
4727
- session = clearSessionTokens(session);
4728
- await saveSession(canonicalResource, session);
4729
- }
4730
- if (!allowInteractive || sessionDiscovery === void 0) {
4731
- return session;
4732
- }
4733
- if (options.allowInteractive === false)
4734
- throw new Error("OAuth interactive authorization is disabled");
4735
- return authorizeSession(canonicalResource, session, sessionDiscovery, fetch2, signal);
4941
+ if (session?.tokens?.refreshToken !== void 0 && sessionDiscovery !== void 0 && (forceRefresh || isExpired(session.tokens, now))) {
4942
+ session = await refreshSession(canonicalResource, session, sessionDiscovery, fetch2, signal);
4943
+ if (session?.tokens !== void 0 && !isExpired(session.tokens, now)) {
4944
+ return session;
4945
+ }
4946
+ }
4947
+ if (forceRefresh && session?.tokens !== void 0) {
4948
+ session = clearSessionTokens(session);
4949
+ await saveSession(canonicalResource, session);
4950
+ }
4951
+ if (!allowInteractive || sessionDiscovery === void 0) {
4952
+ return session;
4953
+ }
4954
+ if (options.allowInteractive === false)
4955
+ throw new Error("OAuth interactive authorization is disabled");
4956
+ return authorizeSession(canonicalResource, session, sessionDiscovery, fetch2, signal);
4957
+ }, { signal, timeoutMs: options.sessionLockTimeoutMs });
4736
4958
  }
4737
4959
  async function refreshSession(resource, session, discovery, fetch2, signal) {
4738
4960
  signal?.throwIfAborted();
4739
4961
  assertSecureOAuthFlowEndpoints(discovery.authorizationServerMetadata);
4740
- const inFlight = refreshPromises.get(resource);
4741
- if (inFlight !== void 0) {
4742
- return inFlight;
4962
+ if (session.tokens?.refreshToken === void 0) {
4963
+ return session;
4743
4964
  }
4744
- const promise = (async () => {
4965
+ let refreshAttempted = false;
4966
+ let refreshedTokens;
4967
+ while (true) {
4745
4968
  try {
4746
- if (session.tokens?.refreshToken === void 0) {
4747
- return session;
4748
- }
4749
- let refreshAttempted = false;
4750
- let refreshedTokens;
4751
- while (true) {
4752
- try {
4753
- refreshedTokens = await refreshAccessToken({
4754
- tokenEndpoint: requireOwnString(discovery.authorizationServerMetadata, "token_endpoint", "Authorization server metadata"),
4755
- clientId: session.client.clientId,
4756
- clientSecret: session.client.clientSecret,
4757
- refreshToken: session.tokens.refreshToken,
4758
- resource,
4759
- fetch: fetch2,
4760
- signal,
4761
- now
4762
- });
4763
- break;
4764
- } catch (error) {
4765
- signal?.throwIfAborted();
4766
- if (error instanceof OAuthError && error.error === "invalid_grant") {
4767
- const clearedSession = clearSessionTokens(session);
4768
- await saveSession(resource, clearedSession);
4769
- return clearedSession;
4770
- }
4771
- if (shouldReRegisterStoredDynamicClient(error, await loadRegisteredClient(discovery.authorizationServer), false)) {
4772
- await clearRegisteredClient(discovery.authorizationServer);
4773
- await clearSession(resource);
4774
- return null;
4775
- }
4776
- if (!refreshAttempted && isRetryableOAuthError(error)) {
4777
- refreshAttempted = true;
4778
- continue;
4779
- }
4780
- throw error;
4781
- }
4969
+ refreshedTokens = await refreshAccessToken({
4970
+ tokenEndpoint: requireOwnString(discovery.authorizationServerMetadata, "token_endpoint", "Authorization server metadata"),
4971
+ clientId: session.client.clientId,
4972
+ clientSecret: session.client.clientSecret,
4973
+ refreshToken: session.tokens.refreshToken,
4974
+ resource,
4975
+ fetch: fetch2,
4976
+ signal,
4977
+ now
4978
+ });
4979
+ break;
4980
+ } catch (error) {
4981
+ signal?.throwIfAborted();
4982
+ if (error instanceof OAuthError && error.error === "invalid_grant") {
4983
+ const clearedSession = clearSessionTokens(session);
4984
+ await saveSession(resource, clearedSession);
4985
+ return clearedSession;
4986
+ }
4987
+ if (shouldReRegisterStoredDynamicClient(error, await loadRegisteredClient(discovery.authorizationServer), false)) {
4988
+ await clearRegisteredClient(discovery.authorizationServer);
4989
+ await clearSession(resource);
4990
+ return null;
4991
+ }
4992
+ if (!refreshAttempted && isRetryableOAuthError(error)) {
4993
+ refreshAttempted = true;
4994
+ continue;
4782
4995
  }
4783
- const updatedSession = {
4784
- ...session,
4785
- tokens: {
4786
- ...refreshedTokens,
4787
- refreshToken: refreshedTokens.refreshToken ?? session.tokens.refreshToken
4788
- },
4789
- discovery: toStoredDiscovery(discovery)
4790
- };
4791
- await saveSession(resource, updatedSession);
4792
- return updatedSession;
4793
- } finally {
4794
- refreshPromises.delete(resource);
4996
+ throw error;
4795
4997
  }
4796
- })();
4797
- refreshPromises.set(resource, promise);
4798
- return promise;
4998
+ }
4999
+ const updatedSession = {
5000
+ ...session,
5001
+ tokens: {
5002
+ ...refreshedTokens,
5003
+ refreshToken: refreshedTokens.refreshToken ?? session.tokens.refreshToken
5004
+ },
5005
+ discovery: toStoredDiscovery(discovery)
5006
+ };
5007
+ await saveSession(resource, updatedSession);
5008
+ return updatedSession;
4799
5009
  }
4800
5010
  async function authorizeSession(resource, existingSession, discovery, fetch2, signal) {
4801
5011
  signal?.throwIfAborted();
4802
- const inFlight = authorizationPromises.get(resource);
4803
- if (inFlight !== void 0) {
4804
- return inFlight;
4805
- }
4806
- const promise = (async () => {
4807
- assertS256PkceSupport(discovery.authorizationServerMetadata);
4808
- assertSecureOAuthFlowEndpoints(discovery.authorizationServerMetadata);
4809
- let currentSession = existingSession;
4810
- let transientRetryAttempted = false;
4811
- let reRegistrationAttempted = false;
4812
- while (true) {
4813
- const loopback = await createLoopbackAuthorizationSession({
4814
- openBrowser: options.browser.openBrowser,
4815
- readLine: options.browser.readLine,
4816
- createServer: options.browser.createServer,
4817
- landingPage: options.browser.landingPage,
4818
- redirectUri: options.browser.redirectUri,
4819
- signal: options.browser.signal === void 0 ? signal : signal === void 0 ? options.browser.signal : AbortSignal.any([signal, options.browser.signal]),
4820
- timeoutMs: options.browser.timeoutMs
5012
+ assertS256PkceSupport(discovery.authorizationServerMetadata);
5013
+ assertSecureOAuthFlowEndpoints(discovery.authorizationServerMetadata);
5014
+ let currentSession = existingSession;
5015
+ let transientRetryAttempted = false;
5016
+ let reRegistrationAttempted = false;
5017
+ while (true) {
5018
+ const loopback = await createLoopbackAuthorizationSession({
5019
+ openBrowser: options.browser.openBrowser,
5020
+ readLine: options.browser.readLine,
5021
+ createServer: options.browser.createServer,
5022
+ landingPage: options.browser.landingPage,
5023
+ redirectUri: options.browser.redirectUri,
5024
+ signal: options.browser.signal === void 0 ? signal : signal === void 0 ? options.browser.signal : AbortSignal.any([signal, options.browser.signal]),
5025
+ timeoutMs: options.browser.timeoutMs
5026
+ });
5027
+ let resolvedClient = null;
5028
+ try {
5029
+ resolvedClient = await resolveClient(currentSession, discovery, loopback.redirectUri, fetch2, signal);
5030
+ const sessionWithoutTokens = {
5031
+ resource,
5032
+ authorizationServer: discovery.authorizationServer,
5033
+ client: resolvedClient.client,
5034
+ discovery: toStoredDiscovery(discovery)
5035
+ };
5036
+ await saveSession(resource, sessionWithoutTokens);
5037
+ const verifier = generateCodeVerifier();
5038
+ const challenge = generateCodeChallenge(verifier);
5039
+ const authorizationUrl = buildAuthorizationUrl({
5040
+ metadata: discovery.authorizationServerMetadata,
5041
+ resource,
5042
+ clientId: resolvedClient.client.clientId,
5043
+ redirectUri: loopback.redirectUri,
5044
+ codeChallenge: challenge,
5045
+ clientMetadata: getClientMetadata(options.client)
4821
5046
  });
4822
- let resolvedClient = null;
4823
- try {
4824
- resolvedClient = await resolveClient(currentSession, discovery, loopback.redirectUri, fetch2, signal);
4825
- const sessionWithoutTokens = {
4826
- resource,
4827
- authorizationServer: discovery.authorizationServer,
4828
- client: resolvedClient.client,
4829
- discovery: toStoredDiscovery(discovery)
4830
- };
4831
- await saveSession(resource, sessionWithoutTokens);
4832
- const verifier = generateCodeVerifier();
4833
- const challenge = generateCodeChallenge(verifier);
4834
- const authorizationUrl = buildAuthorizationUrl({
4835
- metadata: discovery.authorizationServerMetadata,
4836
- resource,
4837
- clientId: resolvedClient.client.clientId,
4838
- redirectUri: loopback.redirectUri,
4839
- codeChallenge: challenge,
4840
- clientMetadata: getClientMetadata(options.client)
4841
- });
4842
- const code = await loopback.waitForCode(authorizationUrl);
4843
- const tokens = await exchangeAuthorizationCode({
4844
- tokenEndpoint: requireOwnString(discovery.authorizationServerMetadata, "token_endpoint", "Authorization server metadata"),
4845
- clientId: resolvedClient.client.clientId,
4846
- clientSecret: resolvedClient.client.clientSecret,
4847
- code,
4848
- codeVerifier: verifier,
4849
- redirectUri: loopback.redirectUri,
4850
- resource,
4851
- fetch: fetch2,
4852
- signal,
4853
- now
4854
- });
4855
- const session = {
4856
- ...sessionWithoutTokens,
4857
- tokens
4858
- };
4859
- await saveSession(resource, session);
4860
- return session;
4861
- } catch (error) {
4862
- signal?.throwIfAborted();
4863
- if (shouldReRegisterStoredDynamicClient(error, resolvedClient, reRegistrationAttempted)) {
4864
- reRegistrationAttempted = true;
4865
- await clearRegisteredClient(discovery.authorizationServer);
4866
- await clearSession(resource);
4867
- currentSession = null;
4868
- continue;
4869
- }
4870
- if (!transientRetryAttempted && isRetryableOAuthError(error)) {
4871
- transientRetryAttempted = true;
4872
- await clearSession(resource);
4873
- currentSession = null;
4874
- continue;
4875
- }
4876
- throw error;
4877
- } finally {
4878
- loopback.close();
5047
+ const code = await loopback.waitForCode(authorizationUrl);
5048
+ const tokens = await exchangeAuthorizationCode({
5049
+ tokenEndpoint: requireOwnString(discovery.authorizationServerMetadata, "token_endpoint", "Authorization server metadata"),
5050
+ clientId: resolvedClient.client.clientId,
5051
+ clientSecret: resolvedClient.client.clientSecret,
5052
+ code,
5053
+ codeVerifier: verifier,
5054
+ redirectUri: loopback.redirectUri,
5055
+ resource,
5056
+ fetch: fetch2,
5057
+ signal,
5058
+ now
5059
+ });
5060
+ const session = {
5061
+ ...sessionWithoutTokens,
5062
+ tokens
5063
+ };
5064
+ await saveSession(resource, session);
5065
+ return session;
5066
+ } catch (error) {
5067
+ signal?.throwIfAborted();
5068
+ if (shouldReRegisterStoredDynamicClient(error, resolvedClient, reRegistrationAttempted)) {
5069
+ reRegistrationAttempted = true;
5070
+ await clearRegisteredClient(discovery.authorizationServer);
5071
+ await clearSession(resource);
5072
+ currentSession = null;
5073
+ continue;
4879
5074
  }
5075
+ if (!transientRetryAttempted && isRetryableOAuthError(error)) {
5076
+ transientRetryAttempted = true;
5077
+ await clearSession(resource);
5078
+ currentSession = null;
5079
+ continue;
5080
+ }
5081
+ throw error;
5082
+ } finally {
5083
+ loopback.close();
4880
5084
  }
4881
- })();
4882
- const finalPromise = promise.finally(() => {
4883
- authorizationPromises.delete(resource);
4884
- });
4885
- authorizationPromises.set(resource, finalPromise);
4886
- return finalPromise;
5085
+ }
4887
5086
  }
4888
5087
  async function resolveClient(existingSession, discovery, redirectUri, fetch2, parentSignal) {
4889
5088
  parentSignal?.throwIfAborted();
@@ -5321,7 +5520,7 @@ function getParameterHeaders(schema) {
5321
5520
  const names = /* @__PURE__ */ new Set();
5322
5521
  const ancestors = /* @__PURE__ */ new Set();
5323
5522
  let nodes = 0;
5324
- const visit = (value, path3, reachable, depth) => {
5523
+ const visit = (value, path5, reachable, depth) => {
5325
5524
  if (++nodes > 1e4 || depth > 64)
5326
5525
  throw new Error("MCP header schema traversal limit exceeded");
5327
5526
  if (typeof value === "boolean")
@@ -5332,7 +5531,7 @@ function getParameterHeaders(schema) {
5332
5531
  try {
5333
5532
  if (Object.prototype.hasOwnProperty.call(value, "x-mcp-header")) {
5334
5533
  const name = value["x-mcp-header"];
5335
- if (!reachable || path3.length === 0 || typeof name !== "string" || name.length === 0 || [...name].some((character) => {
5534
+ if (!reachable || path5.length === 0 || typeof name !== "string" || name.length === 0 || [...name].some((character) => {
5336
5535
  const code = character.charCodeAt(0);
5337
5536
  return !tokenPunctuation.has(character) && !(code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122);
5338
5537
  }))
@@ -5343,25 +5542,25 @@ function getParameterHeaders(schema) {
5343
5542
  if (names.has(key2))
5344
5543
  throw new Error("Duplicate x-mcp-header name");
5345
5544
  names.add(key2);
5346
- headers.push({ name: `Mcp-Param-${name}`, path: [...path3], type: value.type });
5545
+ headers.push({ name: `Mcp-Param-${name}`, path: [...path5], type: value.type });
5347
5546
  }
5348
5547
  for (const [keyword, child] of Object.entries(value)) {
5349
5548
  if (schemaMaps.has(keyword)) {
5350
5549
  if (!isRecord3(child))
5351
5550
  throw new Error("Invalid schema map");
5352
5551
  for (const [key2, nested] of Object.entries(child))
5353
- visit(nested, keyword === "properties" ? [...path3, key2] : path3, reachable && keyword === "properties", depth + 1);
5552
+ visit(nested, keyword === "properties" ? [...path5, key2] : path5, reachable && keyword === "properties", depth + 1);
5354
5553
  } else if (schemaArrays.has(keyword)) {
5355
5554
  if (!Array.isArray(child))
5356
5555
  throw new Error("Invalid schema array");
5357
5556
  for (const nested of child)
5358
- visit(nested, path3, false, depth + 1);
5557
+ visit(nested, path5, false, depth + 1);
5359
5558
  } else if (schemaChildren.has(keyword)) {
5360
5559
  if (Array.isArray(child))
5361
5560
  for (const nested of child)
5362
- visit(nested, path3, false, depth + 1);
5561
+ visit(nested, path5, false, depth + 1);
5363
5562
  else
5364
- visit(child, path3, false, depth + 1);
5563
+ visit(child, path5, false, depth + 1);
5365
5564
  }
5366
5565
  }
5367
5566
  } finally {
@@ -5559,8 +5758,8 @@ function authorizationServerMetadataLocations(issuer) {
5559
5758
  ];
5560
5759
  const issuerUrl = new URL(issuer);
5561
5760
  if (issuerUrl.pathname !== "/") {
5562
- const path3 = issuerUrl.pathname.endsWith("/") ? issuerUrl.pathname.slice(0, -1) : issuerUrl.pathname;
5563
- issuerUrl.pathname = `${path3}/.well-known/openid-configuration`;
5761
+ const path5 = issuerUrl.pathname.endsWith("/") ? issuerUrl.pathname.slice(0, -1) : issuerUrl.pathname;
5762
+ issuerUrl.pathname = `${path5}/.well-known/openid-configuration`;
5564
5763
  locations.push(issuerUrl.toString());
5565
5764
  }
5566
5765
  return locations;