@happyvertical/smrt-app-mcp 0.51.37 → 0.51.39

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/errors.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_descriptor.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_algorithms.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_verify.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/verify.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/local.js","../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/remote.js","../src/auth.ts"],"sourcesContent":["const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), MAX_INT32 = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32)\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / MAX_INT32), low = value % MAX_INT32, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n","class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n","import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n","import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nfunction encodeBase64url(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch {\n throw new ErrorClass(`The ${label} is not a valid base64url string`);\n }\n}\nfunction parseJoseHeader(b64, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(b64)));\n } catch {\n throw new ErrorClass(message);\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeBase64url,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n","import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, privateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (privateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${privateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : privateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n","function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(bits) {\n const subtle = { name: `ML-DSA-${bits}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n","import { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from \"../util/errors.js\";\nimport { concat, decoder, encoder, encode } from \"./buffer_utils.js\";\nimport { decodeBase64url, encodeBase64url, parseJoseHeader, isDisjoint, isObject, validateB64, validateCrit, validateAlgorithms, JWS_RECOGNIZED } from \"./validate.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nfunction snapshotJws(jws, sharedPayload) {\n const encodedProtected = jws.protected, inputHeader = jws.header, header = isObject(inputHeader) ? { ...inputHeader } : inputHeader;\n let payload = sharedPayload ? sharedPayload[0] : jws.payload;\n !sharedPayload && payload instanceof Uint8Array && (payload = new Uint8Array(payload));\n const signature = jws.signature, snapshot = { payload, signature };\n if (encodedProtected !== void 0 && (snapshot.protected = encodedProtected), inputHeader !== void 0 && (snapshot.header = header), encodedProtected === void 0 && header === void 0)\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n if (encodedProtected !== void 0 && typeof encodedProtected != \"string\")\n throw new JWSInvalid(\"JWS Protected Header incorrect type\");\n if (payload === void 0)\n throw new JWSInvalid(\"JWS Payload missing\");\n if (typeof signature != \"string\")\n throw new JWSInvalid(\"JWS Signature missing or incorrect type\");\n if (header !== void 0 && !isObject(header))\n throw new JWSInvalid(\"JWS Unprotected Header incorrect type\");\n return snapshot;\n}\nfunction prepareVerify(options) {\n return [options && validateAlgorithms(\"algorithms\", options.algorithms), options?.crit];\n}\nfunction parseProtectedHeader(encodedProtected) {\n return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, \"JWS Protected Header is invalid\");\n}\nfunction encodeJsonUnencodedPayload(payload) {\n const invalid = /[\\p{Cs}\\p{Cn}]/u.exec(payload)?.[0];\n if (invalid !== void 0)\n throw new JWSInvalid(/\\p{Cs}/u.test(invalid) ? \"JWS Payload must be a well-formed Unicode string\" : \"JWS Payload must not contain unassigned Unicode code points\");\n return encoder.encode(payload);\n}\nfunction encodeCompactUnencodedPayload(payload) {\n try {\n return encode(payload);\n } catch {\n throw new JWSInvalid(\"JWS Compact Serialization payload must use only ASCII characters\");\n }\n}\nasync function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {\n const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected);\n if (!isDisjoint(parsedProt, header))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...parsedProt, ...header }, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n if (shared[0] && !shared[0].has(alg))\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n if (b64) {\n if (typeof inputPayload != \"string\")\n throw new JWSInvalid(\"JWS Payload must be a string\");\n } else if (typeof inputPayload != \"string\" && !(inputPayload instanceof Uint8Array))\n throw new JWSInvalid(\"JWS Payload must be a string or an Uint8Array instance\");\n const signingPayload = b64 || typeof inputPayload != \"string\" ? inputPayload : encodeUnencodedPayload(inputPayload);\n let resolvedKey = !1;\n typeof key == \"function\" && (key = await key(parsedProt, jws), resolvedKey = !0);\n const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode(encodedProtected) : new Uint8Array(), encode(\".\"), typeof signingPayload == \"string\" ? shared[2] ??= encodeBase64url(signingPayload, \"payload\", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, \"signature\", JWSInvalid), k = await prepareKey(entry, key, \"verify\"), cryptoKey = await rawKey(k, entry.subtle, \"verify\");\n entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);\n let verified = !1;\n try {\n verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);\n } catch {\n }\n if (!verified)\n throw new JWSSignatureVerificationFailed();\n const result = { payload: typeof signingPayload == \"string\" ? decodeBase64url(signingPayload, \"payload\", JWSInvalid) : signingPayload };\n return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: k }, b64] : [result, b64];\n}\nasync function verifyCompact(jws, shared, key) {\n if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != \"string\")\n throw new JWSInvalid(\"Compact JWS must be a string or Uint8Array\");\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(\".\");\n if (length !== 3)\n throw new JWSInvalid(\"Invalid Compact JWS\");\n return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);\n}\nexport {\n encodeJsonUnencodedPayload,\n parseProtectedHeader,\n prepareVerify,\n snapshotJws,\n verifyCompact,\n verifySignature\n};\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from \"../util/errors.js\";\nimport { encoder, strictDecoder } from \"./buffer_utils.js\";\nimport { isObject } from \"./validate.js\";\nconst epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {\n s: 1,\n m: 60,\n h: 3600,\n d: 86400,\n w: 604800,\n y: 31557600\n}, REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = \"check_failed\";\nfunction invalidDuration() {\n throw new TypeError(\"Invalid time period format\");\n}\nfunction secs(str) {\n typeof str != \"string\" && invalidDuration();\n const matched = REGEX.exec(str);\n (!matched || matched[4] && matched[1]) && invalidDuration();\n const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);\n return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === \"-\" || matched[4] === \"ago\" ? -numericDate2 : numericDate2;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input))\n throw new TypeError(`Invalid ${label} input`);\n return input;\n}\nfunction validateStringClaim(claim, value) {\n if (typeof value != \"string\")\n throw new TypeError(`\"${claim}\" claim must be a string`);\n}\nfunction validateAudienceClaim(value) {\n if (typeof value != \"string\" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != \"string\")))\n throw new TypeError('\"aud\" claim must be a string or an array of strings');\n}\nfunction numericDate(value, label) {\n return typeof value == \"number\" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);\n}\nconst normalizeTyp = (value) => {\n const normalized = value.toLowerCase();\n return value.includes(\"/\") ? normalized : `application/${normalized}`;\n}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == \"string\" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;\nfunction validateNumericDate(payload, claim, required = !1) {\n const value = payload[claim];\n if (!(value === void 0 && !required)) {\n if (typeof value != \"number\")\n throw new JWTClaimValidationFailed(`\"${claim}\" claim must be a number`, payload, claim, \"invalid\");\n return value;\n }\n}\nfunction unexpectedClaim(payload, claim) {\n throw new JWTClaimValidationFailed(`unexpected \"${claim}\" claim value`, payload, claim, checkFailed);\n}\nfunction validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(strictDecoder.decode(encodedPayload));\n } catch {\n }\n if (!isObject(payload))\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\");\n const { typ } = options;\n if (typ !== void 0 && (typeof protectedHeader.typ != \"string\" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, \"typ\", checkFailed);\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];\n maxTokenAge !== void 0 && presenceCheck.push(\"iat\"), audience !== void 0 && presenceCheck.push(\"aud\"), subject !== void 0 && presenceCheck.push(\"sub\"), issuer !== void 0 && presenceCheck.push(\"iss\");\n for (const claim of new Set(presenceCheck.reverse()))\n if (!Object.hasOwn(payload, claim))\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, \"missing\");\n issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, \"iss\"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, \"sub\"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == \"string\" ? [audience] : audience) && unexpectedClaim(payload, \"aud\");\n const { clockTolerance } = options;\n let tolerance = 0;\n if (typeof clockTolerance == \"string\")\n tolerance = secs(clockTolerance);\n else if (clockTolerance !== void 0) {\n if (typeof clockTolerance != \"number\")\n throw new TypeError(\"Invalid clockTolerance option type\");\n tolerance = clockTolerance;\n }\n validateInput(\"clockTolerance option\", tolerance);\n const { currentDate } = options, now = validateInput(\"currentDate option\", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, \"iat\", maxTokenAge !== void 0), nbf = validateNumericDate(payload, \"nbf\");\n if (nbf !== void 0 && nbf > now + tolerance)\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, \"nbf\", checkFailed);\n const exp = validateNumericDate(payload, \"exp\");\n if (exp !== void 0 && exp <= now - tolerance)\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, \"exp\", checkFailed);\n if (maxTokenAge !== void 0) {\n const age = now - iat, max = validateInput(\"maxTokenAge option\", typeof maxTokenAge == \"number\" ? maxTokenAge : secs(maxTokenAge));\n if (age - tolerance > max)\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, \"iat\", checkFailed);\n if (age < -tolerance)\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, \"iat\", checkFailed);\n }\n return payload;\n}\nlet producerPayloads;\nfunction producerPayload(producer) {\n return producerPayloads.get(producer);\n}\nfunction jwtData(producer) {\n const payload = producerPayload(producer);\n for (const claim of [\"iat\", \"nbf\", \"exp\"]) {\n const value = payload[claim];\n if (typeof value == \"number\" && !Number.isFinite(value))\n throw new TypeError(`\"${claim}\" claim must be a finite number`);\n }\n return encoder.encode(JSON.stringify(payload));\n}\nfunction jwtClaim(producer, claim) {\n return producerPayload(producer)[claim];\n}\nclass JWTClaimsBuilder {\n constructor(payload = {}) {\n if (!isObject(payload))\n throw new TypeError(\"JWT Claims Set MUST be an object\");\n (producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload));\n }\n setIssuer(value) {\n return validateStringClaim(\"iss\", value), producerPayload(this).iss = value, this;\n }\n setSubject(value) {\n return validateStringClaim(\"sub\", value), producerPayload(this).sub = value, this;\n }\n setAudience(value) {\n return validateAudienceClaim(value), producerPayload(this).aud = value, this;\n }\n setJti(value) {\n return validateStringClaim(\"jti\", value), producerPayload(this).jti = value, this;\n }\n setNotBefore(value) {\n return producerPayload(this).nbf = numericDate(value, \"setNotBefore\"), this;\n }\n setExpirationTime(value) {\n return producerPayload(this).exp = numericDate(value, \"setExpirationTime\"), this;\n }\n setIssuedAt(value) {\n const payload = producerPayload(this);\n return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == \"string\" ? payload.iat = validateInput(\"setIssuedAt\", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, \"setIssuedAt\"), this;\n }\n}\nexport {\n JWTClaimsBuilder,\n jwtClaim,\n jwtData,\n secs,\n validateClaimsSet\n};\n","import { prepareVerify, verifyCompact } from \"../lib/jws_verify.js\";\nimport { validateClaimsSet } from \"../lib/jwt_claims_set.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nasync function jwtVerify(jwt, key, options) {\n const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);\n if (!b64)\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n return { ...verified, payload };\n}\nexport {\n jwtVerify\n};\n","import { jwkToKey, snapshotJwk } from \"../lib/key.js\";\nimport { JWS } from \"../lib/jws_algorithms.js\";\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys } from \"../util/errors.js\";\nimport { isJwkSet } from \"../lib/validate.js\";\nfunction isUsableJWK(jwk, entry, alg, kid) {\n const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;\n return (ext === void 0 || typeof ext == \"boolean\") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == \"string\" && keyOps.indexOf(operation) === index) && keyOps.includes(\"verify\")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == \"string\" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== \"AKP\" : alg === jwkAlg) && (use === void 0 || use === \"sig\") && (!entry.crv || crv === entry.crv);\n}\nasync function importWithAlgCache(cache, jwk, entry) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk), { alg } = entry;\n if (cached[alg] === void 0) {\n const pending = jwkToKey(entry, jwk, !0).then((key) => {\n if (key.type !== \"public\")\n throw new JWKSInvalid(\"JSON Web Key Set members must be public keys\");\n return cached[alg] = key, key;\n }).catch((error) => {\n throw cached[alg] === pending && delete cached[alg], error;\n });\n cached[alg] = pending;\n }\n return cached[alg];\n}\nfunction createLocalJWKSet(jwks) {\n let snapshot;\n try {\n snapshot = structuredClone(jwks);\n } catch {\n }\n if (!isJwkSet(snapshot))\n throw new JWKSInvalid(\"JSON Web Key Set malformed\");\n const metadata = snapshot.keys.map((jwk) => {\n const normalized = snapshotJwk(jwk);\n return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;\n }), cached = /* @__PURE__ */ new WeakMap();\n return Object.defineProperty(async (protectedHeader, token) => {\n const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry || entry.secret)\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;\n if (!length)\n throw new JWKSNoMatchingKey();\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n throw error[Symbol.asyncIterator] = async function* () {\n for (const jwk2 of candidates)\n try {\n yield await importWithAlgCache(cached, jwk2, entry);\n } catch {\n }\n }, error;\n }\n return importWithAlgCache(cached, jwk, entry);\n }, \"jwks\", {\n value: () => structuredClone(snapshot)\n });\n}\nexport {\n createLocalJWKSet\n};\n","import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from \"../util/errors.js\";\nimport { createLocalJWKSet } from \"./local.js\";\nimport { isJwkSet } from \"../lib/validate.js\";\nfunction isCloudflareWorkers() {\n return typeof WebSocketPair < \"u\" || typeof navigator < \"u\" && navigator.userAgent === \"Cloudflare-Workers\" || typeof EdgeRuntime < \"u\" && EdgeRuntime === \"vercel\";\n}\nlet USER_AGENT;\n(typeof navigator > \"u\" || !navigator.userAgent?.startsWith?.(\"Mozilla/5.0 \")) && (USER_AGENT = \"jose/v6.2.12\");\nconst customFetch = /* @__PURE__ */ Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n const response = await fetchImpl(url, {\n method: \"GET\",\n signal,\n redirect: \"manual\",\n headers\n }).catch((err) => {\n throw err.name === \"TimeoutError\" ? new JWKSTimeout() : err;\n });\n if (response.status !== 200)\n throw new JOSEError(\"Expected 200 OK from the JSON Web Key Set HTTP response\");\n try {\n return await response.json();\n } catch {\n throw new JOSEError(\"Failed to parse the JSON Web Key Set HTTP response as JSON\");\n }\n}\nconst jwksCache = /* @__PURE__ */ Symbol();\nfunction isFreshFor(timestamp, duration) {\n return Number.isFinite(timestamp) && Date.now() < timestamp + duration;\n}\nfunction validateDuration(value, fallback, option) {\n if (Number.isNaN(value))\n throw new TypeError(`\"${option}\" option must not be NaN`);\n return typeof value == \"number\" ? value : fallback;\n}\nfunction createRemoteJWKSet(url, options) {\n if (!(url instanceof URL))\n throw new TypeError(\"url must be an instance of URL\");\n const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;\n if (typeof timeoutOption == \"number\" && (!Number.isInteger(timeoutOption) || timeoutOption < 0))\n throw new TypeError('\"timeoutDuration\" option must be a non-negative integer');\n const timeoutDuration = typeof timeoutOption == \"number\" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, \"cooldownDuration\"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, \"cacheMaxAge\"), headers = new Headers(opts.headers);\n USER_AGENT && !headers.has(\"User-Agent\") && headers.set(\"User-Agent\", USER_AGENT), headers.has(\"accept\") || headers.set(\"accept\", \"application/json, application/jwk-set+json\");\n const fetchImpl = opts[customFetch], cache = opts[jwksCache];\n let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;\n if (cache && typeof cache == \"object\") {\n const { uat, jwks } = cache;\n isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));\n }\n const reload = async () => {\n if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {\n const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {\n const next = createLocalJWKSet(json);\n if (sequence <= appliedSequence)\n return;\n local = next;\n const updatedAt = Date.now();\n cache && (cache.uat = updatedAt, cache.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;\n }).finally(() => {\n pendingFetch === current && (pendingFetch = void 0);\n });\n }\n await pendingFetch;\n };\n return Object.defineProperties(async (protectedHeader, token) => {\n (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();\n try {\n return await local(protectedHeader, token);\n } catch (err) {\n if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))\n return await reload(), local(protectedHeader, token);\n throw err;\n }\n }, {\n coolingDown: {\n get: () => isFreshFor(jwksTimestamp, cooldownDuration),\n enumerable: !0\n },\n fresh: {\n get: () => isFreshFor(jwksTimestamp, cacheMaxAge),\n enumerable: !0\n },\n reload: {\n value: reload,\n enumerable: !0\n },\n reloading: {\n get: () => !!pendingFetch,\n enumerable: !0\n },\n jwks: {\n value: () => local?.jwks(),\n enumerable: !0\n }\n });\n}\nexport {\n createRemoteJWKSet,\n customFetch,\n jwksCache\n};\n","/** Server-only OAuth protected-resource boundary. This is not an issuer. */\nimport { createRemoteJWKSet, type JWTPayload, jwtVerify } from 'jose';\nimport type { McpAppPrincipal } from './server.js';\n\nexport type McpDeploymentProfile = 'local' | 'self-hosted' | 'cloud';\nexport interface McpVerifiedIdentity {\n readonly issuer: string;\n readonly subject: string;\n readonly scopes: readonly string[];\n readonly claims: Readonly<JWTPayload>;\n}\nexport interface McpPrincipalMapping {\n id: string;\n tenantId?: string;\n kind?: string;\n roles?: string[];\n}\nexport interface McpResourceAuthOptions {\n profile: McpDeploymentProfile;\n /** Exact public resource identifier; also the required token audience. */\n resource: string;\n /** Exact issuer identifier, including any trailing slash. */\n issuer: string;\n /** Operator-configured signing keys. Never derived from an untrusted token. */\n jwksUri: string;\n scopes: readonly string[];\n algorithms: readonly ('RS256' | 'ES256')[];\n /** Default at+jwt. Select JWT only for a provider that uses it for access tokens. */\n tokenType?: 'at+jwt' | 'JWT';\n /** Default true. Set false only for an explicitly single-tenant application. */\n requireTenant?: boolean;\n /** Re-run for every request; return null for revoked/disabled/unmapped users.\n * Resolve active tenant/membership in trusted application state, never request\n * arguments. Provider JWT revocation is NOT detected by offline validation.\n */\n resolvePrincipal(\n identity: McpVerifiedIdentity,\n ): Promise<McpPrincipalMapping | null>;\n}\n\nconst scopePattern = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/u;\nfunction validateUrl(value: string, profile: McpDeploymentProfile): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error('Invalid MCP authorization URL.');\n }\n const loopback = ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname);\n if (\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n /[\\s\"\\\\]/u.test(value) ||\n (profile === 'local'\n ? !loopback || !['http:', 'https:'].includes(url.protocol)\n : url.protocol !== 'https:')\n )\n throw new Error('Invalid MCP authorization URL for deployment profile.');\n return url;\n}\nfunction validString(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n value.length <= 1024 &&\n value.trim() === value &&\n [...value].every(\n (character) =>\n character.charCodeAt(0) > 31 && character.charCodeAt(0) !== 127,\n )\n );\n}\n\nexport interface McpResourceAuth {\n /** Mount GET at this URL. Paths use RFC 9728's well-known path insertion. */\n readonly metadataUrl: string;\n metadataResponse(): Response;\n /** A failure response contains no token, claims or upstream error details. */\n authenticate(\n request: Request,\n ): Promise<\n | { ok: true; principal: McpAppPrincipal & { id: string } }\n | { ok: false; response: Response }\n >;\n}\n\nexport function createMcpResourceAuth(\n options: McpResourceAuthOptions,\n): McpResourceAuth {\n if (!['local', 'self-hosted', 'cloud'].includes(options.profile)) {\n throw new Error('Unknown MCP deployment profile.');\n }\n const resourceUrl = validateUrl(options.resource, options.profile);\n validateUrl(options.issuer, options.profile);\n validateUrl(options.jwksUri, options.profile);\n if (\n !options.algorithms.length ||\n options.algorithms.some((alg) => !['RS256', 'ES256'].includes(alg))\n ) {\n throw new Error('Explicit asymmetric MCP token algorithms are required.');\n }\n if (options.scopes.some((scope) => !scopePattern.test(scope))) {\n throw new Error('Invalid MCP OAuth scope.');\n }\n if (\n options.tokenType !== undefined &&\n !['at+jwt', 'JWT'].includes(options.tokenType)\n ) {\n throw new Error('Unsupported MCP access-token type.');\n }\n // Snapshot configuration so later caller mutation cannot broaden authority.\n const issuer = options.issuer;\n const resource = options.resource;\n const scopes = [...new Set(options.scopes)];\n const algorithms = [...options.algorithms];\n const tokenType = options.tokenType ?? 'at+jwt';\n const requireTenant = options.requireTenant !== false;\n const resolvePrincipal = options.resolvePrincipal;\n const keys = createRemoteJWKSet(new URL(options.jwksUri), {\n timeoutDuration: 5000,\n });\n const metadataUrl = `${resourceUrl.origin}/.well-known/oauth-protected-resource${resourceUrl.pathname === '/' ? '' : resourceUrl.pathname}`;\n function deny(error?: 'invalid_token' | 'insufficient_scope'): {\n ok: false;\n response: Response;\n } {\n const challenge = [\n `Bearer resource_metadata=\"${metadataUrl}\"`,\n ...(scopes.length ? [`scope=\"${scopes.join(' ')}\"`] : []),\n ...(error ? [`error=\"${error}\"`] : []),\n ].join(', ');\n return {\n ok: false,\n response: new Response(null, {\n status: error === 'insufficient_scope' ? 403 : 401,\n headers: { 'WWW-Authenticate': challenge, 'Cache-Control': 'no-store' },\n }),\n };\n }\n return {\n metadataUrl,\n metadataResponse: () =>\n Response.json(\n {\n resource,\n authorization_servers: [issuer],\n scopes_supported: scopes,\n bearer_methods_supported: ['header'],\n },\n { headers: { 'Cache-Control': 'no-store' } },\n ),\n async authenticate(request) {\n const authorization = request.headers.get('authorization');\n if (!authorization) return deny();\n const match =\n /^Bearer +([A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)$/iu.exec(\n authorization,\n );\n if (!match) return deny('invalid_token');\n try {\n const { payload } = await jwtVerify(match[1], keys, {\n issuer,\n audience: resource,\n algorithms,\n typ: tokenType,\n requiredClaims: ['iss', 'aud', 'sub', 'exp'],\n clockTolerance: 0,\n });\n if (!validString(payload.sub) || typeof payload.scope !== 'string')\n return deny('invalid_token');\n const granted = payload.scope === '' ? [] : payload.scope.split(' ');\n if (granted.some((scope) => !scopePattern.test(scope)))\n return deny('invalid_token');\n if (scopes.some((scope) => !granted.includes(scope)))\n return deny('insufficient_scope');\n const mapping = await resolvePrincipal(\n Object.freeze({\n issuer,\n subject: payload.sub,\n scopes: Object.freeze([...granted]),\n claims: Object.freeze(payload),\n }),\n );\n if (\n !mapping ||\n !validString(mapping.id) ||\n (requireTenant && !validString(mapping.tenantId)) ||\n (mapping.tenantId !== undefined && !validString(mapping.tenantId)) ||\n (mapping.kind !== undefined && !validString(mapping.kind)) ||\n (mapping.roles !== undefined &&\n (!Array.isArray(mapping.roles) ||\n !mapping.roles.every(validString)))\n ) {\n return deny('invalid_token');\n }\n return {\n ok: true,\n principal: {\n id: mapping.id,\n tenantId: mapping.tenantId,\n kind: mapping.kind,\n roles: mapping.roles ? [...mapping.roles] : undefined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MACZ,UAAU,QAAQ;MAClB,MAAM,QAAQ;MACd,OAAO,QAAQ,QAAQ,CAAC,GAAG,QAAQ,KAAK,IAAI,KAAA;MAC5C,QAAQ,CAAC,GAAG,OAAO;KACrB;IACF;GACF,QAAQ;IACN,OAAO,KAAK,eAAe;GAC7B;EACF;CACF;AACF"}
@@ -0,0 +1,184 @@
1
+ import { ProtocolError, ProtocolErrorCode, Server } from "@modelcontextprotocol/server";
2
+ //#region src/errors.ts
3
+ var MCP_TOOL_ACCESS_DENIED_CODE = "mcp_tool_access_denied";
4
+ var McpAccessError = class extends Error {
5
+ constructor(status, message, metadata = {}) {
6
+ super(message);
7
+ this.status = status;
8
+ this.metadata = metadata;
9
+ this.name = "McpAccessError";
10
+ }
11
+ status;
12
+ metadata;
13
+ };
14
+ //#endregion
15
+ //#region src/tools.ts
16
+ function matchesToolPattern(toolName, pattern) {
17
+ if (!pattern) return false;
18
+ if (pattern === "*") return true;
19
+ const parts = pattern.split("*");
20
+ if (parts.length === 1) return toolName === pattern;
21
+ let cursor = 0;
22
+ if (parts[0] && !toolName.startsWith(parts[0])) return false;
23
+ for (const part of parts) {
24
+ if (!part) continue;
25
+ const index = toolName.indexOf(part, cursor);
26
+ if (index < 0) return false;
27
+ cursor = index + part.length;
28
+ }
29
+ const last = parts.at(-1);
30
+ return !last || toolName.endsWith(last);
31
+ }
32
+ function isReadOnlyToolName(toolName) {
33
+ return toolName.endsWith("_list") || toolName.endsWith("_get");
34
+ }
35
+ function isPublicToolName(toolName, patterns) {
36
+ return isReadOnlyToolName(toolName) && patterns.some((pattern) => matchesToolPattern(toolName, pattern));
37
+ }
38
+ function isPublicMcpTool(tool, patterns) {
39
+ return (tool.annotations?.readOnlyHint ?? isReadOnlyToolName(tool.name)) && patterns.some((pattern) => matchesToolPattern(tool.name, pattern));
40
+ }
41
+ function classNamePrefixes(classNames) {
42
+ return new Set(classNames.map((className) => `${className.toLowerCase()}_`));
43
+ }
44
+ function isAllowedCoreTool(toolName, prefixes) {
45
+ for (const prefix of prefixes) if (toolName.startsWith(prefix)) return true;
46
+ return false;
47
+ }
48
+ function compareMcpToolNames(left, right) {
49
+ return left < right ? -1 : left > right ? 1 : 0;
50
+ }
51
+ //#endregion
52
+ //#region src/protocol.ts
53
+ var MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
54
+ var DEFAULT_TOOL_LIST_CACHE_HINT = {
55
+ ttlMs: 864e5,
56
+ cacheScope: "private"
57
+ };
58
+ async function createMcpProtocolServerForRequest(appServer, options = {}) {
59
+ const principal = options.principal ?? null;
60
+ let extensions = {};
61
+ if (options.extensions) try {
62
+ const tools = await appServer.listTools({ principal });
63
+ const projected = await options.extensions({
64
+ principal,
65
+ tools
66
+ });
67
+ assertExtensionMetadata(projected);
68
+ if (Object.hasOwn(projected, "io.modelcontextprotocol/tasks")) throw new TypeError("Reserved extension.");
69
+ extensions = structuredClone(projected);
70
+ } catch {
71
+ throw new ProtocolError(ProtocolErrorCode.InternalError, "Extension discovery unavailable.");
72
+ }
73
+ return protocolServer(appServer, { principal }, extensions);
74
+ }
75
+ async function resolvePrincipal(option, context) {
76
+ if (typeof option === "function") return await option(context) ?? null;
77
+ return option ?? null;
78
+ }
79
+ function createMcpProtocolServer(appServer, options = {}) {
80
+ if ("extensions" in options) throw new TypeError("Extension discovery requires createMcpProtocolServerForRequest.");
81
+ return protocolServer(appServer, options, {});
82
+ }
83
+ function protocolServer(appServer, options, extensions) {
84
+ const tasksEnabled = appServer.tasksEnabled && typeof options.principal !== "function" && Boolean(options.principal?.id);
85
+ const server = new Server(appServer.serverInfo, {
86
+ capabilities: {
87
+ tools: {},
88
+ ...appServer.listResources && appServer.readResource ? { resources: {} } : {},
89
+ ...tasksEnabled || Object.keys(extensions).length ? { extensions: {
90
+ ...extensions,
91
+ ...tasksEnabled ? { [MCP_TASKS_EXTENSION]: {} } : {}
92
+ } } : {}
93
+ },
94
+ cacheHints: { "tools/list": DEFAULT_TOOL_LIST_CACHE_HINT }
95
+ });
96
+ server.setRequestHandler("tools/list", async (_request, context) => {
97
+ const principal = await resolvePrincipal(options.principal, context);
98
+ const cacheHint = await appServer.getToolsListCacheHint?.() ?? DEFAULT_TOOL_LIST_CACHE_HINT;
99
+ return {
100
+ tools: [...await appServer.listTools({ principal })].sort((left, right) => compareMcpToolNames(left.name, right.name)),
101
+ ...cacheHint
102
+ };
103
+ });
104
+ if (appServer.listResources && appServer.readResource) {
105
+ server.setRequestHandler("resources/list", async (_request, context) => ({
106
+ resources: await appServer.listResources({ principal: await resolvePrincipal(options.principal, context) }),
107
+ ttlMs: 0,
108
+ cacheScope: "private"
109
+ }));
110
+ server.setRequestHandler("resources/read", async (request, context) => {
111
+ try {
112
+ return {
113
+ contents: [await appServer.readResource({
114
+ uri: request.params.uri,
115
+ principal: await resolvePrincipal(options.principal, context)
116
+ })],
117
+ ttlMs: 0,
118
+ cacheScope: "private"
119
+ };
120
+ } catch (error) {
121
+ if (error instanceof McpAccessError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "MCP resource is not available.");
122
+ throw error;
123
+ }
124
+ });
125
+ }
126
+ server.setRequestHandler("tools/call", async (request, context) => {
127
+ try {
128
+ return await appServer.callTool({
129
+ name: request.params.name,
130
+ arguments: request.params.arguments,
131
+ principal: await resolvePrincipal(options.principal, context)
132
+ });
133
+ } catch (error) {
134
+ if (error instanceof McpAccessError) {
135
+ const { code, retryable } = error.metadata;
136
+ throw new ProtocolError(error.status === 404 ? ProtocolErrorCode.InvalidParams : ProtocolErrorCode.InvalidRequest, error.message, {
137
+ ...typeof code === "string" ? { code } : {},
138
+ ...typeof retryable === "boolean" ? { retryable } : {}
139
+ });
140
+ }
141
+ throw error;
142
+ }
143
+ });
144
+ return server;
145
+ }
146
+ function assertExtensionMetadata(value) {
147
+ let budget = 65536;
148
+ const visit = (v, depth) => {
149
+ if (--budget < 0 || depth > 16) throw new TypeError("Extension metadata exceeds limits.");
150
+ if (v === null || typeof v === "boolean") return;
151
+ if (typeof v === "number" && Number.isFinite(v)) return;
152
+ if (typeof v === "string") {
153
+ budget -= new TextEncoder().encode(v).length;
154
+ if (budget < 0) throw new TypeError("Extension metadata exceeds limits.");
155
+ return;
156
+ }
157
+ if (Array.isArray(v)) {
158
+ if (v.length > 1024) throw new TypeError("Extension array exceeds limits.");
159
+ for (const item of v) visit(item, depth + 1);
160
+ return;
161
+ }
162
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) throw new TypeError("Expected plain extension object.");
163
+ const names = Object.keys(v);
164
+ if (names.length > 256) throw new TypeError("Extension object exceeds limits.");
165
+ for (const name of names) {
166
+ if ([
167
+ "__proto__",
168
+ "constructor",
169
+ "prototype"
170
+ ].includes(name)) throw new TypeError("Unsafe extension key.");
171
+ const descriptor = Object.getOwnPropertyDescriptor(v, name);
172
+ if (!descriptor || !("value" in descriptor)) throw new TypeError("Expected inert extension metadata.");
173
+ visit(name, depth + 1);
174
+ visit(descriptor.value, depth + 1);
175
+ }
176
+ };
177
+ visit(value, 0);
178
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Expected extension map.");
179
+ for (const [name, entry] of Object.entries(value)) if (!name.trim() || !entry || typeof entry !== "object" || Array.isArray(entry)) throw new TypeError("Expected named extension object.");
180
+ }
181
+ //#endregion
182
+ export { compareMcpToolNames as a, isPublicToolName as c, MCP_TOOL_ACCESS_DENIED_CODE as d, McpAccessError as f, classNamePrefixes as i, isReadOnlyToolName as l, createMcpProtocolServer as n, isAllowedCoreTool as o, createMcpProtocolServerForRequest as r, isPublicMcpTool as s, MCP_TASKS_EXTENSION as t, matchesToolPattern as u };
183
+
184
+ //# sourceMappingURL=protocol-Ce0U_XSp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol-Ce0U_XSp.js","names":[],"sources":["../../src/errors.ts","../../src/tools.ts","../../src/protocol.ts"],"sourcesContent":["/** Machine-readable code for a principal policy denial. */\nexport const MCP_TOOL_ACCESS_DENIED_CODE = 'mcp_tool_access_denied';\n\n/**\n * Metadata that is safe to expose for an app-MCP access failure. Policy\n * implementations must not place principal, scope, tool, or internal-error\n * details here.\n */\nexport interface McpAccessErrorMetadata {\n code?: string;\n retryable?: boolean;\n}\n\n/**\n * Error returned by the MCP app server when a caller tries to use a tool\n * they are not allowed to access. The HTTP layer should map `status` onto\n * the response status code.\n */\nexport class McpAccessError extends Error {\n constructor(\n readonly status: number,\n message: string,\n readonly metadata: McpAccessErrorMetadata = {},\n ) {\n super(message);\n this.name = 'McpAccessError';\n }\n}\n","/**\n * Tool-name policy helpers — used by `McpAppServer` to filter the full set\n * of generated tools down to what the calling principal is allowed to see,\n * and to decide whether an unauthenticated tool call should be permitted.\n *\n * @packageDocumentation\n */\n\n/**\n * Match a tool name against a glob-ish pattern with `*` wildcards.\n *\n * - Empty pattern → never matches.\n * - `*` → matches everything.\n * - `prefix_*` → matches anything starting with `prefix_`.\n * - `*_suffix` → matches anything ending with `_suffix`.\n * - `a_*_b` → matches any name containing `a_`, then any text, then `_b`.\n *\n * No regex characters are special besides `*` — the input is treated as a\n * literal string with star wildcards.\n */\nexport function matchesToolPattern(toolName: string, pattern: string): boolean {\n if (!pattern) return false;\n if (pattern === '*') return true;\n\n const parts = pattern.split('*');\n if (parts.length === 1) return toolName === pattern;\n\n let cursor = 0;\n if (parts[0] && !toolName.startsWith(parts[0])) return false;\n for (const part of parts) {\n if (!part) continue;\n const index = toolName.indexOf(part, cursor);\n if (index < 0) return false;\n cursor = index + part.length;\n }\n\n const last = parts.at(-1);\n return !last || toolName.endsWith(last);\n}\n\n/**\n * Read-only tool detection. Generated SMRT MCP tools follow the naming\n * convention `<class>_<verb>`; we treat `_list` and `_get` as read-only.\n */\nexport function isReadOnlyToolName(toolName: string): boolean {\n return toolName.endsWith('_list') || toolName.endsWith('_get');\n}\n\n/**\n * Check whether a tool name is currently allowed for unauthenticated callers\n * given the configured public-tool patterns. Only read-only tools may ever\n * be public, regardless of pattern.\n */\nexport function isPublicToolName(\n toolName: string,\n patterns: readonly string[],\n): boolean {\n return (\n isReadOnlyToolName(toolName) &&\n patterns.some((pattern) => matchesToolPattern(toolName, pattern))\n );\n}\n\n/**\n * Check public eligibility using a descriptor's canonical read annotation when\n * available. The legacy name rule remains for generated catalogs predating\n * canonical annotations.\n */\nexport function isPublicMcpTool(\n tool: {\n name: string;\n annotations?: { readOnlyHint?: boolean };\n },\n patterns: readonly string[],\n): boolean {\n const readOnly =\n tool.annotations?.readOnlyHint ?? isReadOnlyToolName(tool.name);\n return (\n readOnly &&\n patterns.some((pattern) => matchesToolPattern(tool.name, pattern))\n );\n}\n\n/**\n * Lower-case `<class>_` prefixes the app considers \"allowed core tools\"\n * given a list of SMRT class names. Used to build the allow-list for\n * `McpAppServer.listTools`.\n */\nexport function classNamePrefixes(\n classNames: readonly string[],\n): ReadonlySet<string> {\n return new Set(classNames.map((className) => `${className.toLowerCase()}_`));\n}\n\n/**\n * Whether a given tool name starts with any of the configured class\n * prefixes.\n */\nexport function isAllowedCoreTool(\n toolName: string,\n prefixes: ReadonlySet<string>,\n): boolean {\n for (const prefix of prefixes) {\n if (toolName.startsWith(prefix)) return true;\n }\n return false;\n}\n\n/**\n * Compare tool names by Unicode code unit, rather than the host locale, so a\n * catalog has one byte-stable order across every runtime.\n */\nexport function compareMcpToolNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n","/** MCP SDK v2 protocol adapter for the framework-neutral app server core. */\n\nimport type { MCPTool } from '@happyvertical/smrt-core/generators/mcp';\nimport {\n type CallToolResult,\n type JSONObject,\n ProtocolError,\n ProtocolErrorCode,\n Server,\n type ServerContext,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport { McpAccessError } from './errors.js';\nimport type { McpAppPrincipal, McpAppServer } from './server.js';\nimport { compareMcpToolNames } from './tools.js';\n\nexport const MCP_TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';\n\nconst DEFAULT_TOOL_LIST_CACHE_HINT = {\n ttlMs: 86_400_000,\n cacheScope: 'private' as const,\n};\n\nexport interface McpProtocolServerOptions {\n /** Resolve the authenticated application principal for each MCP request. */\n principal?:\n | McpAppPrincipal\n | null\n | ((\n context: ServerContext,\n ) => McpAppPrincipal | null | Promise<McpAppPrincipal | null>);\n}\n\n/** Request-bound options for asynchronous catalog extension projection. */\nexport interface McpProtocolRequestOptions {\n principal?: McpAppPrincipal | null;\n /** Optional inert extension metadata, recomputed from this request's authorized catalog. */\n extensions?: (context: {\n principal: McpAppPrincipal | null;\n tools: readonly MCPTool[];\n }) =>\n | Record<string, Record<string, unknown>>\n | Promise<Record<string, Record<string, unknown>>>;\n}\n\n/** Prepare native capabilities before the SDK HTTP factory installs discovery handlers. */\nexport async function createMcpProtocolServerForRequest(\n appServer: McpAppServer,\n options: McpProtocolRequestOptions = {},\n): Promise<Server> {\n const principal = options.principal ?? null;\n let extensions: Record<string, JSONObject> = {};\n if (options.extensions) {\n try {\n const tools = await appServer.listTools({ principal });\n const projected = await options.extensions({ principal, tools });\n assertExtensionMetadata(projected);\n if (Object.hasOwn(projected, MCP_TASKS_EXTENSION))\n throw new TypeError('Reserved extension.');\n extensions = structuredClone(projected);\n } catch {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n 'Extension discovery unavailable.',\n );\n }\n }\n return protocolServer(appServer, { principal }, extensions);\n}\n\nasync function resolvePrincipal(\n option: McpProtocolServerOptions['principal'],\n context: ServerContext,\n): Promise<McpAppPrincipal | null> {\n if (typeof option === 'function') return (await option(context)) ?? null;\n return option ?? null;\n}\n\n/**\n * Adapt an app MCP core to the SDK v2 low-level server protocol.\n *\n * Transport ownership remains with the caller. In particular, this does not\n * add a production HTTP endpoint; it is safe to compose with `serveStdio` or\n * `createMcpHandler` in a deployment that supplies its own authentication.\n */\nexport function createMcpProtocolServer(\n appServer: McpAppServer,\n options: McpProtocolServerOptions = {},\n): Server {\n if ('extensions' in options) {\n throw new TypeError(\n 'Extension discovery requires createMcpProtocolServerForRequest.',\n );\n }\n return protocolServer(appServer, options, {});\n}\n\nfunction protocolServer(\n appServer: McpAppServer,\n options: McpProtocolServerOptions,\n extensions: Record<string, JSONObject>,\n): Server {\n // Task lifecycle records are owner-scoped. Unlike ordinary public read-only\n // tools, they cannot be safely exposed without a stable principal id.\n const tasksEnabled =\n appServer.tasksEnabled &&\n typeof options.principal !== 'function' &&\n Boolean(options.principal?.id);\n const server = new Server(appServer.serverInfo, {\n capabilities: {\n tools: {},\n ...(appServer.listResources && appServer.readResource\n ? { resources: {} }\n : {}),\n ...(tasksEnabled || Object.keys(extensions).length\n ? {\n extensions: {\n ...extensions,\n ...(tasksEnabled ? { [MCP_TASKS_EXTENSION]: {} } : {}),\n },\n }\n : {}),\n } as never,\n cacheHints: { 'tools/list': DEFAULT_TOOL_LIST_CACHE_HINT },\n });\n\n server.setRequestHandler('tools/list', async (_request, context) => {\n const principal = await resolvePrincipal(options.principal, context);\n const cacheHint =\n (await appServer.getToolsListCacheHint?.()) ??\n DEFAULT_TOOL_LIST_CACHE_HINT;\n return {\n tools: [...(await appServer.listTools({ principal }))].sort(\n (left, right) => compareMcpToolNames(left.name, right.name),\n ) as Tool[],\n ...cacheHint,\n };\n });\n\n if (appServer.listResources && appServer.readResource) {\n server.setRequestHandler('resources/list', async (_request, context) => ({\n resources: await appServer.listResources!({\n principal: await resolvePrincipal(options.principal, context),\n }),\n ttlMs: 0,\n cacheScope: 'private',\n }));\n server.setRequestHandler('resources/read', async (request, context) => {\n try {\n return {\n contents: [\n await appServer.readResource!({\n uri: request.params.uri,\n principal: await resolvePrincipal(options.principal, context),\n }),\n ],\n ttlMs: 0,\n cacheScope: 'private',\n };\n } catch (error) {\n if (error instanceof McpAccessError)\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'MCP resource is not available.',\n );\n throw error;\n }\n });\n }\n\n server.setRequestHandler('tools/call', async (request, context) => {\n try {\n return (await appServer.callTool({\n name: request.params.name,\n arguments: request.params.arguments,\n principal: await resolvePrincipal(options.principal, context),\n })) as CallToolResult;\n } catch (error) {\n if (error instanceof McpAccessError) {\n const { code, retryable } = error.metadata;\n throw new ProtocolError(\n error.status === 404\n ? ProtocolErrorCode.InvalidParams\n : ProtocolErrorCode.InvalidRequest,\n error.message,\n {\n ...(typeof code === 'string' ? { code } : {}),\n ...(typeof retryable === 'boolean' ? { retryable } : {}),\n },\n );\n }\n throw error;\n }\n });\n\n return server;\n}\n\n/** Bound plugin discovery metadata without allowing executable values or provider-specific types. */\nfunction assertExtensionMetadata(\n value: unknown,\n): asserts value is Record<string, JSONObject> {\n let budget = 65536;\n const visit = (v: unknown, depth: number): void => {\n if (--budget < 0 || depth > 16)\n throw new TypeError('Extension metadata exceeds limits.');\n if (v === null || typeof v === 'boolean') return;\n if (typeof v === 'number' && Number.isFinite(v)) return;\n if (typeof v === 'string') {\n budget -= new TextEncoder().encode(v).length;\n if (budget < 0) throw new TypeError('Extension metadata exceeds limits.');\n return;\n }\n if (Array.isArray(v)) {\n if (v.length > 1024)\n throw new TypeError('Extension array exceeds limits.');\n for (const item of v) visit(item, depth + 1);\n return;\n }\n if (\n !v ||\n typeof v !== 'object' ||\n ![Object.prototype, null].includes(Object.getPrototypeOf(v))\n )\n throw new TypeError('Expected plain extension object.');\n const names = Object.keys(v);\n if (names.length > 256)\n throw new TypeError('Extension object exceeds limits.');\n for (const name of names) {\n if (['__proto__', 'constructor', 'prototype'].includes(name))\n throw new TypeError('Unsafe extension key.');\n const descriptor = Object.getOwnPropertyDescriptor(v, name);\n if (!descriptor || !('value' in descriptor))\n throw new TypeError('Expected inert extension metadata.');\n visit(name, depth + 1);\n visit(descriptor.value, depth + 1);\n }\n };\n visit(value, 0);\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError('Expected extension map.');\n for (const [name, entry] of Object.entries(value)) {\n if (\n !name.trim() ||\n !entry ||\n typeof entry !== 'object' ||\n Array.isArray(entry)\n )\n throw new TypeError('Expected named extension object.');\n }\n}\n"],"mappings":";;AACO,IAAM,8BAA8B;AAiBp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AO,yBAAyB,GAAG,IAAI;GAC1D,IAAI,CAAC,cAAc,EAAE,WAAW,aAC9B,MAAM,IAAI,UAAU,oCAAoC;GAC1D,MAAM,MAAM,QAAQ,CAAC;GACrB,MAAM,WAAW,OAAO,QAAQ,CAAC;EACnC;CACF;CACA,MAAM,OAAO,CAAC;CACd,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,MAAM,IAAI,UAAU,yBAAyB;CAC/C,KAAA,MAAW,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,GAC9C,IACE,CAAC,KAAK,KAAK,KACX,CAAC,SACD,OAAO,UAAU,YACjB,MAAM,QAAQ,KAAK,GAEnB,MAAM,IAAI,UAAU,kCAAkC;AAE5D"}
@@ -0,0 +1,30 @@
1
+ import { type McpTaskContinuation, type McpTaskStore } from '@happyvertical/smrt-jobs';
2
+ import type { McpAppPrincipal } from './server.js';
3
+ import { type McpWorkflowToolDefinition } from './workflow-tools.js';
4
+ /** Server-owned immutable review reference; contains no permission snapshot. */
5
+ export interface McpWorkflowContinuation extends McpTaskContinuation {
6
+ /** Application review page, including the application's own authentication. */
7
+ reviewUrl: string;
8
+ }
9
+ /**
10
+ * Compose a durable job with its owning workflow. The host answer is only an
11
+ * input hint. `applyReviewed` must call the owning immutable review/revision and
12
+ * idempotency API, rechecking domain approval inside that transaction.
13
+ * No host callback or server session survives suspension.
14
+ */
15
+ export declare function continueMcpWorkflow<T>(options: {
16
+ binding: McpWorkflowContinuation;
17
+ inputSchema: Record<string, unknown>;
18
+ applyReviewed: (input: unknown, binding: Readonly<McpTaskContinuation>) => Promise<T>;
19
+ }): Promise<T>;
20
+ /**
21
+ * Declare the ordinary tool fallback for hosts without elicitation. `storeFor`
22
+ * must return a store bound to the supplied verified actor and active tenant;
23
+ * the application policy callback resolves current read authority.
24
+ */
25
+ export declare function createMcpContinuationTool(options: {
26
+ name: string;
27
+ storeFor: (principal: McpAppPrincipal) => Promise<Pick<McpTaskStore, 'getContinuation'>>;
28
+ authorize: (principal: McpAppPrincipal, taskId: string) => Promise<boolean>;
29
+ }): McpWorkflowToolDefinition;
30
+ //# sourceMappingURL=continuation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"continuation.d.ts","sourceRoot":"","sources":["../src/continuation.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,YAAY,EAClB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAEL,KAAK,yBAAyB,EAC/B,MAAM,qBAAqB,CAAC;AAE7B,gFAAgF;AAChF,MAAM,WAAW,uBAAwB,SAAQ,mBAAmB;IAClE,+EAA+E;IAC/E,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE;IACpD,OAAO,EAAE,uBAAuB,CAAC;IACjC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,aAAa,EAAE,CACb,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,QAAQ,CAAC,mBAAmB,CAAC,KACnC,OAAO,CAAC,CAAC,CAAC,CAAC;CACjB,GAAG,OAAO,CAAC,CAAC,CAAC,CA4Bb;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE;IACjD,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,CACR,SAAS,EAAE,eAAe,KACvB,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,iBAAiB,CAAC,CAAC,CAAC;IACpD,SAAS,EAAE,CAAC,SAAS,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC7E,GAAG,yBAAyB,CA+C5B"}
package/dist/index.d.ts CHANGED
@@ -21,8 +21,11 @@
21
21
  *
22
22
  * @packageDocumentation
23
23
  */
24
+ export { continueMcpWorkflow, createMcpContinuationTool, type McpWorkflowContinuation, } from './continuation.js';
24
25
  export { MCP_TOOL_ACCESS_DENIED_CODE, McpAccessError, type McpAccessErrorMetadata, } from './errors.js';
25
- export { createMcpProtocolServer, type McpProtocolServerOptions, } from './protocol.js';
26
+ export { createMcpProtocolServer, createMcpProtocolServerForRequest, type McpProtocolRequestOptions, type McpProtocolServerOptions, } from './protocol.js';
27
+ export { MCP_APP_RESOURCE_MAX_BYTES, MCP_APP_RESOURCE_MIME, type McpAppResource, type McpAppResourceContent, type McpAppResourceCsp, type McpAppResourceDefinition, type McpResourcePolicy, prepareMcpAppResource, } from './resources.js';
26
28
  export { type CallToolInput, type CreateMcpAppServerOptions, createMcpAppServer, type ListToolsInput, type McpAppPrincipal, type McpAppServer, type McpAppUser, type McpPublicToolPatternsThunk, type McpSmrtOptionsThunk, type McpToolListCacheHint, type McpToolListCacheOptions, type McpToolPolicy, type McpToolPolicyContext, type McpWorkflowAssertion, } from './server.js';
27
- export { classNamePrefixes, isAllowedCoreTool, isPublicToolName, isReadOnlyToolName, matchesToolPattern, } from './tools.js';
29
+ export { classNamePrefixes, isAllowedCoreTool, isPublicMcpTool, isPublicToolName, isReadOnlyToolName, matchesToolPattern, } from './tools.js';
30
+ export { createMcpWorkflowTool, type McpWorkflowTool, type McpWorkflowToolContext, type McpWorkflowToolDefinition, type McpWorkflowToolVisibility, } from './workflow-tools.js';
28
31
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EACL,2BAA2B,EAC3B,cAAc,EACd,KAAK,sBAAsB,GAC5B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,uBAAuB,EACvB,KAAK,wBAAwB,GAC9B,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,KAAK,aAAa,EAClB,KAAK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