fastmcp 4.27.0 → 4.28.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.
Files changed (43) hide show
  1. package/dist/FastMCP.cjs +4 -4
  2. package/dist/FastMCP.d.cts +2 -2
  3. package/dist/FastMCP.d.ts +2 -2
  4. package/dist/FastMCP.js +3 -3
  5. package/dist/{OAuthProvider-CUfrAKTR.d.cts → OAuthProvider-DvIxa9N1.d.cts} +8 -5
  6. package/dist/{OAuthProvider-CUfrAKTR.d.ts → OAuthProvider-DvIxa9N1.d.ts} +8 -5
  7. package/dist/auth/index.cjs +2 -2
  8. package/dist/auth/index.d.cts +2 -2
  9. package/dist/auth/index.d.ts +2 -2
  10. package/dist/auth/index.js +1 -1
  11. package/dist/{chunk-SQ5JIDOQ.cjs → chunk-2ABBQFJB.cjs} +28 -13
  12. package/dist/chunk-2ABBQFJB.cjs.map +1 -0
  13. package/dist/chunk-2NZFMD6I.cjs +120 -0
  14. package/dist/chunk-2NZFMD6I.cjs.map +1 -0
  15. package/dist/{chunk-PKJVR5H3.cjs → chunk-3FM67CFK.cjs} +58 -49
  16. package/dist/chunk-3FM67CFK.cjs.map +1 -0
  17. package/dist/chunk-AM3HVK4Z.js +120 -0
  18. package/dist/chunk-AM3HVK4Z.js.map +1 -0
  19. package/dist/{chunk-TCXNF2SR.js → chunk-NRATQX66.js} +22 -7
  20. package/dist/chunk-NRATQX66.js.map +1 -0
  21. package/dist/{chunk-6L7ORLPC.js → chunk-PWSYODM5.js} +49 -40
  22. package/dist/chunk-PWSYODM5.js.map +1 -0
  23. package/dist/edge/index.cjs +114 -65
  24. package/dist/edge/index.cjs.map +1 -1
  25. package/dist/edge/index.js +90 -41
  26. package/dist/edge/index.js.map +1 -1
  27. package/dist/examples/custom-routes.cjs +4 -4
  28. package/dist/examples/custom-routes.js +3 -3
  29. package/dist/openapi/index.cjs +26 -15
  30. package/dist/openapi/index.cjs.map +1 -1
  31. package/dist/openapi/index.d.cts +4 -4
  32. package/dist/openapi/index.d.ts +4 -4
  33. package/dist/openapi/index.js +20 -9
  34. package/dist/openapi/index.js.map +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-6L7ORLPC.js.map +0 -1
  37. package/dist/chunk-6TDYSPLC.cjs +0 -44
  38. package/dist/chunk-6TDYSPLC.cjs.map +0 -1
  39. package/dist/chunk-OKKFL2M4.js +0 -44
  40. package/dist/chunk-OKKFL2M4.js.map +0 -1
  41. package/dist/chunk-PKJVR5H3.cjs.map +0 -1
  42. package/dist/chunk-SQ5JIDOQ.cjs.map +0 -1
  43. package/dist/chunk-TCXNF2SR.js.map +0 -1
@@ -0,0 +1,120 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/strictInputSchema.ts
2
+ var _zod = require('zod');
3
+ function objectRootSchema(schema) {
4
+ return schema.type === void 0 ? { ...schema, type: "object" } : schema;
5
+ }
6
+ function strictInputSchema(schema, nested = false) {
7
+ const { $ref, additionalProperties, allOf, anyOf, oneOf, properties } = schema;
8
+ if (!nested && ($ref || allOf || anyOf || oneOf)) {
9
+ return objectRootSchema(schema);
10
+ }
11
+ const keepsAdditionalProperties = Object.keys(_nullishCoalesce(properties, () => ( {}))).length === 0 && (typeof additionalProperties === "object" || additionalProperties === true || nested && additionalProperties === void 0 && !properties);
12
+ const strict = {
13
+ ...schema,
14
+ ...keepsAdditionalProperties ? {} : { additionalProperties: false },
15
+ ...properties && {
16
+ properties: Object.fromEntries(
17
+ Object.entries(properties).map(([key, value]) => [
18
+ key,
19
+ typeof value === "object" && value.type === "object" ? strictInputSchema(value, true) : value
20
+ ])
21
+ )
22
+ }
23
+ };
24
+ return nested ? strict : objectRootSchema(strict);
25
+ }
26
+ function zodInputSchema(schema, target) {
27
+ const jsonSchema = _zod.z.toJSONSchema(schema, {
28
+ io: "input",
29
+ target
30
+ });
31
+ const definitionsKey = target === "draft-7" ? "definitions" : "$defs";
32
+ const definitions = {};
33
+ const operands = /* @__PURE__ */ new Map();
34
+ const closeObjects = (value, operand = false) => {
35
+ if (!value || typeof value !== "object") return value;
36
+ const result = { ...value };
37
+ if (operand && typeof result.$ref === "string" && (result.$ref === "#" || result.$ref.startsWith("#/"))) {
38
+ const reference = result.$ref;
39
+ let name = operands.get(reference);
40
+ if (!name) {
41
+ const path = decodeURIComponent(reference.slice(1)).split("/").slice(1);
42
+ const referenced = path.reduce(
43
+ (node, key) => node && typeof node === "object" ? node[key.replace(/~1/g, "/").replace(/~0/g, "~")] : void 0,
44
+ jsonSchema
45
+ );
46
+ if (referenced && typeof referenced === "object") {
47
+ name = `__fastmcp_operand_${operands.size}`;
48
+ const existing = jsonSchema[definitionsKey];
49
+ while (Object.hasOwn(_nullishCoalesce(existing, () => ( {})), name) || Object.hasOwn(definitions, name))
50
+ name += "_";
51
+ operands.set(reference, name);
52
+ const copy = { ...referenced };
53
+ delete copy.$schema;
54
+ delete copy.$defs;
55
+ delete copy.definitions;
56
+ definitions[name] = closeObjects(copy, true);
57
+ }
58
+ }
59
+ if (name) result.$ref = `#/${definitionsKey}/${name}`;
60
+ }
61
+ if (!operand && result.type === "object" && result.properties !== void 0 && result.additionalProperties === void 0) {
62
+ result.additionalProperties = false;
63
+ }
64
+ for (const keyword of ["allOf", "anyOf", "oneOf"]) {
65
+ const branches = result[keyword];
66
+ if (Array.isArray(branches)) {
67
+ result[keyword] = branches.map(
68
+ (branch) => closeObjects(
69
+ branch,
70
+ operand || keyword === "allOf" && branches.length > 1
71
+ )
72
+ );
73
+ }
74
+ }
75
+ for (const keyword of [
76
+ "$defs",
77
+ "definitions",
78
+ "patternProperties",
79
+ "properties"
80
+ ]) {
81
+ const children = result[keyword];
82
+ if (children && typeof children === "object") {
83
+ result[keyword] = Object.fromEntries(
84
+ Object.entries(children).map(([key, child]) => [
85
+ key,
86
+ closeObjects(child)
87
+ ])
88
+ );
89
+ }
90
+ }
91
+ for (const keyword of [
92
+ "additionalItems",
93
+ "additionalProperties",
94
+ "items",
95
+ "prefixItems",
96
+ "propertyNames"
97
+ ]) {
98
+ const child = result[keyword];
99
+ if (child !== void 0) {
100
+ result[keyword] = Array.isArray(child) ? child.map((item) => closeObjects(item)) : closeObjects(child);
101
+ }
102
+ }
103
+ return result;
104
+ };
105
+ const closed = closeObjects(jsonSchema);
106
+ if (operands.size > 0) {
107
+ closed[definitionsKey] = {
108
+ ...closed[definitionsKey],
109
+ ...definitions
110
+ };
111
+ }
112
+ return closed;
113
+ }
114
+
115
+
116
+
117
+
118
+
119
+ exports.objectRootSchema = objectRootSchema; exports.strictInputSchema = strictInputSchema; exports.zodInputSchema = zodInputSchema;
120
+ //# sourceMappingURL=chunk-2NZFMD6I.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/fastmcp/fastmcp/dist/chunk-2NZFMD6I.cjs","../src/strictInputSchema.ts"],"names":[],"mappings":"AAAA;ACEA,0BAAkB;AAUX,SAAS,gBAAA,CAAiB,MAAA,EAAgC;AAC/D,EAAA,OAAO,MAAA,CAAO,KAAA,IAAS,KAAA,EAAA,EAAY,EAAE,GAAG,MAAA,EAAQ,IAAA,EAAM,SAAS,EAAA,EAAI,MAAA;AACrE;AA2BO,SAAS,iBAAA,CACd,MAAA,EACA,OAAA,EAAS,KAAA,EACG;AACZ,EAAA,MAAM,EAAE,IAAA,EAAM,oBAAA,EAAsB,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,WAAW,EAAA,EAClE,MAAA;AAEF,EAAA,GAAA,CAAI,CAAC,OAAA,GAAA,CAAW,KAAA,GAAQ,MAAA,GAAS,MAAA,GAAS,KAAA,CAAA,EAAQ;AAChD,IAAA,OAAO,gBAAA,CAAiB,MAAM,CAAA;AAAA,EAChC;AAEA,EAAA,MAAM,0BAAA,EACJ,MAAA,CAAO,IAAA,kBAAK,UAAA,UAAc,CAAC,GAAC,CAAA,CAAE,OAAA,IAAW,EAAA,G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,UAAA;AACE,YAAA;AACmC,YAAA;AACrC,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AAEsB,IAAA;AACpB,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACC,IAAA;AAC8B,MAAA;AACe,MAAA;AACnB,QAAA;AACkB,UAAA;AACvC,YAAA;AACkB,YAAA;AACnB,UAAA;AACH,QAAA;AACF,MAAA;AACF,IAAA;AACsB,IAAA;AACpB,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACC,IAAA;AAC2B,MAAA;AACH,MAAA;AAEnB,QAAA;AAEN,MAAA;AACF,IAAA;AACO,IAAA;AACT,EAAA;AAEsC,EAAA;AACf,EAAA;AACI,IAAA;AACE,MAAA;AACtB,MAAA;AACL,IAAA;AACF,EAAA;AACO,EAAA;AACT;ADxFoD;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fastmcp/fastmcp/dist/chunk-2NZFMD6I.cjs","sourcesContent":[null,"import type { JsonSchema } from \"xsschema\";\n\nimport { z } from \"zod\";\n\n/**\n * Gives a tool's input or output schema the `type: \"object\"` MCP requires at\n * its root, unless it states a type of its own. A union of objects converts to\n * a bare `anyOf` or `oneOf`, and the SDK client rejects a whole `tools/list`\n * that contains one, so a single such tool would hide every other. Arguments\n * and structured content are always objects, so this only rules out values a\n * tool can never be sent or return.\n */\nexport function objectRootSchema(schema: JsonSchema): JsonSchema {\n return schema.type === undefined ? { ...schema, type: \"object\" } : schema;\n}\n\n/**\n * Closes tool input objects to undeclared keys, like xsschema's\n * `strictJsonSchema`, except for objects made only of additional properties.\n * Closing one of those advertises an object that accepts nothing but `{}`,\n * while the tool's own validation still takes any key, so it keeps whatever\n * `additionalProperties` it declared — or none:\n *\n * - a dictionary, whose `additionalProperties` is a schema (`z.record()`, an\n * OpenAPI map), keeps its value schema;\n * - a free-form object, which declares `additionalProperties: true`, or, as an\n * argument, is a bare `{ type: \"object\" }` (OpenAPI's usual spelling), stays\n * open.\n *\n * A plain object that declares an empty `properties`, or a bare one at the\n * top of the input, is still closed: that is how a schema says \"no keys\" —\n * `z.object({})`, or a tool without arguments. Root schemas with `allOf`,\n * `anyOf`, `oneOf`, or `$ref` are left as declared, even with their own\n * `properties`: `additionalProperties` only sees adjacent properties, so\n * adding it would reject keys declared by a branch or reference target.\n *\n * The root is given an object type (see `objectRootSchema`).\n *\n * Shared by both runtimes, so a tool's advertised input schema does not depend\n * on whether it is served by `FastMCP` or `EdgeFastMCP`.\n */\nexport function strictInputSchema(\n schema: JsonSchema,\n nested = false,\n): JsonSchema {\n const { $ref, additionalProperties, allOf, anyOf, oneOf, properties } =\n schema;\n\n if (!nested && ($ref || allOf || anyOf || oneOf)) {\n return objectRootSchema(schema);\n }\n\n const keepsAdditionalProperties =\n Object.keys(properties ?? {}).length === 0 &&\n (typeof additionalProperties === \"object\" ||\n additionalProperties === true ||\n (nested && additionalProperties === undefined && !properties));\n\n const strict = {\n ...schema,\n ...(keepsAdditionalProperties ? {} : { additionalProperties: false }),\n ...(properties && {\n properties: Object.fromEntries(\n Object.entries(properties).map(([key, value]) => [\n key,\n typeof value === \"object\" && value.type === \"object\"\n ? strictInputSchema(value, true)\n : value,\n ]),\n ),\n }),\n };\n\n return nested ? strict : objectRootSchema(strict);\n}\n\n/**\n * Converts Zod 4 tool parameters by what a call may send (`io: \"input\"`), so a\n * transformed field advertises the type it parses and a defaulted one is\n * optional. Close ordinary object occurrences after conversion, but leave\n * intersection operands open to each other's keys. Child values start a new\n * closure context; explicit catchalls, including .strict(), stay as declared.\n */\nexport function zodInputSchema(\n schema: z.ZodType,\n target?: \"draft-7\",\n): JsonSchema {\n const jsonSchema = z.toJSONSchema(schema, {\n io: \"input\",\n target,\n }) as Record<string, unknown>;\n const definitionsKey = target === \"draft-7\" ? \"definitions\" : \"$defs\";\n const definitions: Record<string, unknown> = {};\n const operands = new Map<string, string>();\n\n const closeObjects = (value: unknown, operand = false): unknown => {\n if (!value || typeof value !== \"object\") return value;\n const result = { ...(value as Record<string, unknown>) };\n\n if (\n operand &&\n typeof result.$ref === \"string\" &&\n (result.$ref === \"#\" || result.$ref.startsWith(\"#/\"))\n ) {\n const reference = result.$ref;\n let name = operands.get(reference);\n if (!name) {\n const path = decodeURIComponent(reference.slice(1)).split(\"/\").slice(1);\n const referenced = path.reduce<unknown>(\n (node, key) =>\n node && typeof node === \"object\"\n ? (node as Record<string, unknown>)[\n key.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n ]\n : undefined,\n jsonSchema,\n );\n if (referenced && typeof referenced === \"object\") {\n name = `__fastmcp_operand_${operands.size}`;\n const existing = jsonSchema[definitionsKey] as object | undefined;\n while (\n Object.hasOwn(existing ?? {}, name) ||\n Object.hasOwn(definitions, name)\n )\n name += \"_\";\n // Reserve the reference before descending, including through child values.\n operands.set(reference, name);\n const copy = { ...(referenced as Record<string, unknown>) };\n delete copy.$schema;\n delete copy.$defs;\n delete copy.definitions;\n definitions[name] = closeObjects(copy, true);\n }\n }\n if (name) result.$ref = `#/${definitionsKey}/${name}`;\n }\n\n if (\n !operand &&\n result.type === \"object\" &&\n result.properties !== undefined &&\n result.additionalProperties === undefined\n ) {\n result.additionalProperties = false;\n }\n\n for (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"]) {\n const branches = result[keyword];\n if (Array.isArray(branches)) {\n // A single allOf branch is Zod's draft-7 reference wrapper, not\n // an intersection. Only intersections introduce a new exemption.\n result[keyword] = branches.map((branch) =>\n closeObjects(\n branch,\n operand || (keyword === \"allOf\" && branches.length > 1),\n ),\n );\n }\n }\n\n for (const keyword of [\n \"$defs\",\n \"definitions\",\n \"patternProperties\",\n \"properties\",\n ]) {\n const children = result[keyword];\n if (children && typeof children === \"object\") {\n result[keyword] = Object.fromEntries(\n Object.entries(children).map(([key, child]) => [\n key,\n closeObjects(child),\n ]),\n );\n }\n }\n for (const keyword of [\n \"additionalItems\",\n \"additionalProperties\",\n \"items\",\n \"prefixItems\",\n \"propertyNames\",\n ]) {\n const child = result[keyword];\n if (child !== undefined) {\n result[keyword] = Array.isArray(child)\n ? child.map((item) => closeObjects(item))\n : closeObjects(child);\n }\n }\n return result;\n };\n\n const closed = closeObjects(jsonSchema) as Record<string, unknown>;\n if (operands.size > 0) {\n closed[definitionsKey] = {\n ...(closed[definitionsKey] as Record<string, unknown>),\n ...definitions,\n };\n }\n return closed as JsonSchema;\n}\n"]}
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/auth/helpers.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/auth/helpers.ts
2
2
  function getAuthSession(session) {
3
3
  if (!session) {
4
4
  throw new Error("Session is not authenticated");
@@ -1322,6 +1322,7 @@ var MemoryTokenStorage = (_class3 = class {
1322
1322
  () => void this.cleanup(),
1323
1323
  cleanupIntervalMs
1324
1324
  );
1325
+ _optionalChain([this, 'access', _9 => _9.cleanupInterval, 'access', _10 => _10.unref, 'optionalCall', _11 => _11()]);
1325
1326
  }
1326
1327
  async cleanup() {
1327
1328
  const now = Date.now();
@@ -1394,7 +1395,8 @@ var DEFAULT_PORTS = {
1394
1395
  "ws:": "80",
1395
1396
  "wss:": "443"
1396
1397
  };
1397
- var CONSENT_COOKIE_VALUE = /^[\w-]{43}$/;
1398
+ var GENERATED_ID = /^[\w-]{43}$/;
1399
+ var OAUTH_ERROR_TEXT = /^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/;
1398
1400
  var MAX_CLIENT_REGISTRATION_BYTES = 32 * 1024;
1399
1401
  var RESERVED_AUTHORIZATION_PARAMS = /* @__PURE__ */ new Set([
1400
1402
  "client_id",
@@ -1416,11 +1418,9 @@ var OAuthProxy = (_class4 = class {
1416
1418
 
1417
1419
 
1418
1420
  /**
1419
- * The fallback storage this proxy created for itself, if any. It runs a
1420
- * cleanup timer that keeps the event loop alive, so `destroy()` has to stop
1421
- * it — and once the storage is wrapped for encryption it is reachable
1422
- * through nothing else. A caller-supplied storage is deliberately not
1423
- * recorded here: its lifetime belongs to the caller.
1421
+ * The fallback storage this proxy created for itself, if any. Keep a
1422
+ * reference so `destroy()` can stop its cleanup timer even when the storage
1423
+ * is wrapped for encryption. Caller-supplied storage has its own lifetime.
1424
1424
  */
1425
1425
  __init7() {this.ownedTokenStorage = null}
1426
1426
  /**
@@ -1556,7 +1556,7 @@ var OAuthProxy = (_class4 = class {
1556
1556
  const consentBinding = this.config.consentRequired ? _nullishCoalesce((request && this.consentCookieValue(request)), () => ( this.generateId())) : void 0;
1557
1557
  const transaction = await this.createTransaction(params, consentBinding);
1558
1558
  if (consentBinding && !transaction.consentGiven) {
1559
- const clientName = _optionalChain([registeredClient, 'access', _9 => _9.metadata, 'optionalAccess', _10 => _10.client_name]);
1559
+ const clientName = _optionalChain([registeredClient, 'access', _12 => _12.metadata, 'optionalAccess', _13 => _13.client_name]);
1560
1560
  return this.consentManager.createConsentResponse(
1561
1561
  transaction,
1562
1562
  this.getProviderName(),
@@ -1576,7 +1576,7 @@ var OAuthProxy = (_class4 = class {
1576
1576
  clearInterval(this.cleanupInterval);
1577
1577
  this.cleanupInterval = null;
1578
1578
  }
1579
- _optionalChain([this, 'access', _11 => _11.ownedTokenStorage, 'optionalAccess', _12 => _12.destroy, 'call', _13 => _13()]);
1579
+ _optionalChain([this, 'access', _14 => _14.ownedTokenStorage, 'optionalAccess', _15 => _15.destroy, 'call', _16 => _16()]);
1580
1580
  this.registeredClientsByClientId.clear();
1581
1581
  }
1582
1582
  /**
@@ -1728,25 +1728,35 @@ var OAuthProxy = (_class4 = class {
1728
1728
  ]
1729
1729
  };
1730
1730
  }
1731
+ /**
1732
+ * Get the configured OAuth callback path, including the default.
1733
+ */
1734
+ getRedirectPath() {
1735
+ return this.config.redirectPath;
1736
+ }
1731
1737
  /**
1732
1738
  * Handle OAuth callback from upstream provider
1733
1739
  */
1734
1740
  async handleCallback(request) {
1735
1741
  const url = new URL(request.url);
1736
- const code = url.searchParams.get("code");
1742
+ const code = _nullishCoalesce(url.searchParams.get("code"), () => ( ""));
1737
1743
  const state = url.searchParams.get("state");
1738
1744
  const error = url.searchParams.get("error");
1745
+ const description = url.searchParams.get("error_description") || void 0;
1739
1746
  if (error) {
1740
- const errorDescription = url.searchParams.get("error_description");
1741
- throw new OAuthProxyError(error, errorDescription || void 0);
1742
- }
1743
- if (!code || !state) {
1747
+ if (!state || url.searchParams.getAll("state").length !== 1 || !GENERATED_ID.test(state) || !OAUTH_ERROR_TEXT.test(error) || description && !OAUTH_ERROR_TEXT.test(description) || await _asyncOptionalChain([(await this.stateStore.getTransaction(state)), 'optionalAccess', async _17 => _17.id]) !== state) {
1748
+ throw new OAuthProxyError(error, description);
1749
+ }
1750
+ } else if (!code || !state) {
1744
1751
  throw new OAuthProxyError(
1745
1752
  "invalid_request",
1746
1753
  "Missing code or state parameter"
1747
1754
  );
1748
1755
  }
1749
1756
  const transaction = await this.stateStore.consumeTransaction(state);
1757
+ if (error && (_optionalChain([transaction, 'optionalAccess', _18 => _18.id]) !== state || transaction.expiresAt.getTime() <= Date.now())) {
1758
+ throw new OAuthProxyError(error, description);
1759
+ }
1750
1760
  if (!transaction) {
1751
1761
  throw new OAuthProxyError("invalid_request", "Invalid or expired state");
1752
1762
  }
@@ -1762,23 +1772,18 @@ var OAuthProxy = (_class4 = class {
1762
1772
  "Transaction callback URL is not registered"
1763
1773
  );
1764
1774
  }
1775
+ if (error) {
1776
+ return this.redirectToClient(transaction, {
1777
+ error,
1778
+ error_description: description
1779
+ });
1780
+ }
1765
1781
  const upstreamTokens = await this.exchangeUpstreamCode(code, transaction);
1766
1782
  const clientCode = await this.generateAuthorizationCode(
1767
1783
  transaction,
1768
1784
  upstreamTokens
1769
1785
  );
1770
- const redirectUrl = new URL(transaction.clientCallbackUrl);
1771
- redirectUrl.searchParams.set("code", clientCode);
1772
- redirectUrl.searchParams.set("state", transaction.state);
1773
- if (this.config.authorizationResponseIss) {
1774
- redirectUrl.searchParams.set("iss", this.config.baseUrl);
1775
- }
1776
- return new Response(null, {
1777
- headers: {
1778
- Location: redirectUrl.toString()
1779
- },
1780
- status: 302
1781
- });
1786
+ return this.redirectToClient(transaction, { code: clientCode });
1782
1787
  }
1783
1788
  /**
1784
1789
  * Handle consent form submission
@@ -1817,21 +1822,9 @@ var OAuthProxy = (_class4 = class {
1817
1822
  "Transaction callback URL is not registered"
1818
1823
  );
1819
1824
  }
1820
- const redirectUrl = new URL(transaction.clientCallbackUrl);
1821
- redirectUrl.searchParams.set("error", "access_denied");
1822
- redirectUrl.searchParams.set(
1823
- "error_description",
1824
- "User denied authorization"
1825
- );
1826
- redirectUrl.searchParams.set("state", transaction.state);
1827
- if (this.config.authorizationResponseIss) {
1828
- redirectUrl.searchParams.set("iss", this.config.baseUrl);
1829
- }
1830
- return new Response(null, {
1831
- headers: {
1832
- Location: redirectUrl.toString()
1833
- },
1834
- status: 302
1825
+ return this.redirectToClient(transaction, {
1826
+ error: "access_denied",
1827
+ error_description: "User denied authorization"
1835
1828
  });
1836
1829
  }
1837
1830
  const approvedTransaction = {
@@ -1849,7 +1842,7 @@ var OAuthProxy = (_class4 = class {
1849
1842
  return null;
1850
1843
  }
1851
1844
  const result = await this.jwtIssuer.verify(fastmcpToken);
1852
- if (!result.valid || !_optionalChain([result, 'access', _14 => _14.claims, 'optionalAccess', _15 => _15.jti])) {
1845
+ if (!result.valid || !_optionalChain([result, 'access', _19 => _19.claims, 'optionalAccess', _20 => _20.jti])) {
1853
1846
  return null;
1854
1847
  }
1855
1848
  if (result.claims.token_use !== "access") {
@@ -2059,7 +2052,7 @@ var OAuthProxy = (_class4 = class {
2059
2052
  const separator = pair.indexOf("=");
2060
2053
  if (separator !== -1 && withoutOptionalWhitespace(pair.slice(0, separator)) === name) {
2061
2054
  const value = withoutOptionalWhitespace(pair.slice(separator + 1));
2062
- return CONSENT_COOKIE_VALUE.test(value) ? value : void 0;
2055
+ return GENERATED_ID.test(value) ? value : void 0;
2063
2056
  }
2064
2057
  }
2065
2058
  return void 0;
@@ -2143,7 +2136,7 @@ var OAuthProxy = (_class4 = class {
2143
2136
  throw new Error("JWT issuer not initialized");
2144
2137
  }
2145
2138
  const result = await this.jwtIssuer.verify(token);
2146
- if (!result.valid || !_optionalChain([result, 'access', _16 => _16.claims, 'optionalAccess', _17 => _17.jti])) {
2139
+ if (!result.valid || !_optionalChain([result, 'access', _21 => _21.claims, 'optionalAccess', _22 => _22.jti])) {
2147
2140
  throw new Error("Failed to extract JTI from token");
2148
2141
  }
2149
2142
  return result.claims.jti;
@@ -2405,7 +2398,7 @@ var OAuthProxy = (_class4 = class {
2405
2398
  refreshedUpstreamTokens.scope = upstreamTokens.scope;
2406
2399
  }
2407
2400
  const requestedScope = [
2408
- ...new Set(_optionalChain([request, 'access', _18 => _18.scope, 'optionalAccess', _19 => _19.split, 'call', _20 => _20(" "), 'access', _21 => _21.filter, 'call', _22 => _22(Boolean)]))
2401
+ ...new Set(_optionalChain([request, 'access', _23 => _23.scope, 'optionalAccess', _24 => _24.split, 'call', _25 => _25(" "), 'access', _26 => _26.filter, 'call', _27 => _27(Boolean)]))
2409
2402
  ];
2410
2403
  const accessTokenScope = requestedScope.length > 0 && requestedScope.every(
2411
2404
  (scope) => refreshedUpstreamTokens.scope.includes(scope)
@@ -2604,7 +2597,7 @@ var OAuthProxy = (_class4 = class {
2604
2597
  transaction.clientId,
2605
2598
  transaction.clientCallbackUrl
2606
2599
  );
2607
- return _nullishCoalesce(_optionalChain([registeredClient, 'optionalAccess', _23 => _23.redirectUris, 'access', _24 => _24.includes, 'call', _25 => _25(transaction.clientCallbackUrl)]), () => ( false));
2600
+ return _nullishCoalesce(_optionalChain([registeredClient, 'optionalAccess', _28 => _28.redirectUris, 'access', _29 => _29.includes, 'call', _30 => _30(transaction.clientCallbackUrl)]), () => ( false));
2608
2601
  }
2609
2602
  /**
2610
2603
  * Whether a redirect URI matches a pattern.
@@ -2690,6 +2683,20 @@ var OAuthProxy = (_class4 = class {
2690
2683
  passthroughRefreshKey(refreshToken) {
2691
2684
  return `passthrough-refresh:${sha256(refreshToken)}`;
2692
2685
  }
2686
+ redirectToClient(transaction, params) {
2687
+ const url = new URL(transaction.clientCallbackUrl);
2688
+ for (const [name, value] of Object.entries(params)) {
2689
+ if (value !== void 0) url.searchParams.set(name, value);
2690
+ }
2691
+ url.searchParams.set("state", transaction.state);
2692
+ if (this.config.authorizationResponseIss) {
2693
+ url.searchParams.set("iss", this.config.baseUrl);
2694
+ }
2695
+ return new Response(null, {
2696
+ headers: { Location: url.toString() },
2697
+ status: 302
2698
+ });
2699
+ }
2693
2700
  /**
2694
2701
  * Redirect to upstream OAuth provider
2695
2702
  */
@@ -2867,6 +2874,7 @@ var OAuthProxy = (_class4 = class {
2867
2874
  this.cleanupInterval = setInterval(() => {
2868
2875
  this.cleanup();
2869
2876
  }, 6e4);
2877
+ _optionalChain([this, 'access', _31 => _31.cleanupInterval, 'access', _32 => _32.unref, 'optionalCall', _33 => _33()]);
2870
2878
  }
2871
2879
  /**
2872
2880
  * Atomically claim a token mapping, mirroring `OAuthProxyStateStore`: at most
@@ -3035,7 +3043,7 @@ var AuthProvider = class {
3035
3043
  if (!request) {
3036
3044
  return void 0;
3037
3045
  }
3038
- const authHeader = _optionalChain([request, 'access', _26 => _26.headers, 'optionalAccess', _27 => _27.authorization]);
3046
+ const authHeader = _optionalChain([request, 'access', _34 => _34.headers, 'optionalAccess', _35 => _35.authorization]);
3039
3047
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
3040
3048
  return void 0;
3041
3049
  }
@@ -3253,6 +3261,7 @@ var DiskStore = (_class5 = class {
3253
3261
  this.cleanupInterval = setInterval(() => {
3254
3262
  void this.cleanup();
3255
3263
  }, cleanupIntervalMs);
3264
+ _optionalChain([this, 'access', _36 => _36.cleanupInterval, 'access', _37 => _37.unref, 'optionalCall', _38 => _38()]);
3256
3265
  }
3257
3266
  /**
3258
3267
  * Clean up expired entries
@@ -3429,7 +3438,7 @@ var DiskStore = (_class5 = class {
3429
3438
  await _promises.rename.call(void 0, source, destination);
3430
3439
  return;
3431
3440
  } catch (error) {
3432
- const code = _optionalChain([error, 'optionalAccess', _28 => _28.code]);
3441
+ const code = _optionalChain([error, 'optionalAccess', _39 => _39.code]);
3433
3442
  if (process.platform !== "win32" || attempt >= 5 || !["EACCES", "EBUSY", "EPERM"].includes(_nullishCoalesce(code, () => ( "")))) {
3434
3443
  throw error;
3435
3444
  }
@@ -3605,4 +3614,4 @@ Original error: ${error.message}`
3605
3614
 
3606
3615
 
3607
3616
  exports.cancelResponseBody = cancelResponseBody; exports.getAuthSession = getAuthSession; exports.requireAll = requireAll; exports.requireAny = requireAny; exports.requireAuth = requireAuth; exports.requireRole = requireRole; exports.requireScopes = requireScopes; exports.DEFAULT_ACCESS_TOKEN_TTL = DEFAULT_ACCESS_TOKEN_TTL; exports.DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH = DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH; exports.DEFAULT_REFRESH_TOKEN_TTL = DEFAULT_REFRESH_TOKEN_TTL; exports.TOKEN_ENDPOINT_AUTH_METHODS = TOKEN_ENDPOINT_AUTH_METHODS; exports.DEFAULT_AUTHORIZATION_CODE_TTL = DEFAULT_AUTHORIZATION_CODE_TTL; exports.DEFAULT_TRANSACTION_TTL = DEFAULT_TRANSACTION_TTL; exports.ConsentManager = ConsentManager; exports.JWTIssuer = JWTIssuer; exports.PKCEUtils = PKCEUtils; exports.EncryptedTokenStorage = EncryptedTokenStorage; exports.MemoryTokenStorage = MemoryTokenStorage; exports.OAuthProxy = OAuthProxy; exports.OAuthProxyError = OAuthProxyError; exports.AuthProvider = AuthProvider; exports.AzureProvider = AzureProvider; exports.GitHubProvider = GitHubProvider; exports.GoogleProvider = GoogleProvider; exports.OAuthProvider = OAuthProvider; exports.DiskStore = DiskStore; exports.JWKSVerifier = JWKSVerifier;
3608
- //# sourceMappingURL=chunk-PKJVR5H3.cjs.map
3617
+ //# sourceMappingURL=chunk-3FM67CFK.cjs.map