@zortexhq/indra-v2.5 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/box-level1-setup.js +1 -1
- package/dist/calcom-level1-setup.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/discord-level1-setup.js +1 -1
- package/dist/dropbox-level1-setup.js +1 -1
- package/dist/figma-level1-setup.js +1 -1
- package/dist/freshdesk-level1-setup.js +1 -1
- package/dist/freshrss-level1-setup.js +1 -1
- package/dist/front-level1-setup.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/google-chat-level1-setup.js +1 -1
- package/dist/google-contacts-level1-setup.js +1 -1
- package/dist/hubspot-level1-setup.js +1 -1
- package/dist/joplin-selection.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mattermost-level1-setup.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/measurement-context.js +1 -1
- package/dist/miniflux-level1-setup.js +1 -1
- package/dist/nextcloud-level1-setup.js +1 -1
- package/dist/operation-telemetry.js +1 -0
- package/dist/prepared-level1-setup.js +1 -0
- package/dist/product-feedback.js +2 -2
- package/dist/profile.js +1 -1
- package/dist/proton-mail-level1-setup.js +1 -1
- package/dist/recovery-launch.js +10 -0
- package/dist/recovery-support.js +1 -1
- package/dist/recovery-surface.js +1 -0
- package/dist/recovery.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +1 -1
- package/dist/resident-telemetry.js +1 -0
- package/dist/resource-telemetry.js +1 -0
- package/dist/salesforce-level1-setup.js +1 -1
- package/dist/smartsheet-level1-setup.js +1 -1
- package/dist/startup.js +2 -2
- package/dist/thunderbird-level1-setup.js +1 -1
- package/dist/wakatime-level1-setup.js +1 -1
- package/dist/wallabag-level1-setup.js +1 -1
- package/dist/web.js +2 -2
- package/dist/zendesk-level1-setup.js +1 -1
- package/dist/zoom-level1-setup.js +1 -1
- package/dist/zulip-level1-setup.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/localizer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +98 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-panel.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +13 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy.html +141 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-state.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/panels-live.js +3 -3
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/product.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +12 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/device-identity.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
- package/package.json +6 -6
- package/profiles/core.yml +1 -0
- package/release-provenance.json +26 -26
- package/update-manifest.json +419 -197
- package/dist/recovery-page.js +0 -215
|
@@ -1 +1 @@
|
|
|
1
|
-
import{matrixHomeserver,matrixIssuer,matrixLogin,matrixTokenUrl,matrixUserId,verifyMatrixDevice}from"./matrix-login.js";import{createPinnedLoopbackHttp,continueAuthorizationWithBrowser}from"@zortexhq/plugin-connector-core/api";import{exchangeZendeskCode,refreshZendeskToken,zendeskOAuthEndpoints}from"./zendesk-oauth.js";import{Client,StreamableHTTPClientTransport,checkResourceAllowed,discoverOAuthServerInfo,discoverAuthorizationServerMetadata,refreshAuthorization,registerClient,resolveClientMetadata,resourceUrlFromServerUrl}from"@modelcontextprotocol/client";import{StdioClientTransport}from"@modelcontextprotocol/client/stdio";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{completedJob,connectionState}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId,isMcpSessionAuthority,isServerSessionAuthority}from"@zortexhq/plugin-vault-sqlite/api";import{browserConnectionDiagnostic,browserFailureCause}from"@zortexhq/plugin-oauth-browser-driver/api";import{SIGNED_IN_BROWSER_CREDENTIAL,automaticError,isSignedInBrowserCredential,readSignedInPage}from"@zortexhq/plugin-auto-connect/api";import{createHash,randomUUID}from"node:crypto";import{createLocalJWKSet,decodeJwt,jwtVerify}from"jose";import{AsyncLocalStorage}from"node:async_hooks";import{readResult,validateRead,authorizationImage}from"@zortexhq/plugin-connector-core/api";import{acceptsSavedMcpScopes}from"./saved-mcp-scopes.js";import{acceptsMondayDefaultGrant,isReviewedMondayDefault}from"./monday-oauth-scopes.js";import{captureCustodied,checkCustodied,inspectCustodied,reviewedToolSchemaHash,validateCustodiedAuth}from"./custodied.js";const PROXY_VARS=["HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY","https_proxy","http_proxy","all_proxy","no_proxy"];export function proxyEnv(env=process.env){const out={};for(const key of PROXY_VARS)if(env[key])out[key]=env[key];if(Object.keys(out).some(k=>!/no_proxy/i.test(k)))out.NODE_USE_ENV_PROXY="1";if(env.NODE_EXTRA_CA_CERTS)out.NODE_EXTRA_CA_CERTS=env.NODE_EXTRA_CA_CERTS;return out}let LOGIN_POLL=5e3;export function setLoginPoll(ms){LOGIN_POLL=ms}const MAX_PENDING=32,MAX_PARAMS=65536,MAX_RESULT=1048576,CALL_TIMEOUT=12e4,LOGIN_TIMEOUT=6e5;const SOURCE=/^[a-z][a-z0-9-]{1,39}$/,TOOL=/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;const DISCOVERY_TIMEOUT=3e4;const OPENROUTER_KEY_URL="https://openrouter.ai/api/v1/key",GITLAB_TOKEN_INFO_URL="https://gitlab.com/oauth/token/info";const ATLASSIAN_ME_URL="https://api.atlassian.com/me",ATLASSIAN_RESOURCES_URL="https://api.atlassian.com/oauth/token/accessible-resources",IDENTITY_TIMEOUT=3e4,MAX_IDENTITY_BYTES=65536;const LINEAR_JWKS_URL="https://mcp.linear.app/.well-known/jwks.json";const CLICKUP_USER_URL="https://api.clickup.com/api/v2/user";const ZOOM_USERINFO_URL="https://zoom.us/v1/userinfo";class ServerLoginRequired extends Error{}export function resolveAuthorizationBudget(input){if(input===void 0)return{maxSteps:8,maxModelCalls:0};if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some(key=>!["maxSteps","maxModelCalls"].includes(key))||!Number.isInteger(input.maxSteps)||input.maxSteps<1||input.maxSteps>12||!Number.isInteger(input.maxModelCalls)||input.maxModelCalls<0||input.maxModelCalls>24)throw Error("Invalid level 1 authorization budget.");return{maxSteps:input.maxSteps,maxModelCalls:input.maxModelCalls}}function httpsUrl(value){const url=new URL(value);if(value!==value.trim()||url.protocol!=="https:"||url.username||url.password||url.search||url.hash||url.hostname.includes("*"))throw Error("Invalid reviewed OAuth URL.");return url}function validIdentityPath(path){return Array.isArray(path)&&path.length>0&&path.length<=8&&path.every(key=>typeof key==="string"&&/^[a-zA-Z0-9_-]{1,80}$/.test(key)&&!["__proto__","prototype","constructor"].includes(key))}function validIdentityReview(identity){if(!identity||typeof identity!=="object"||Array.isArray(identity))return false;if(identity.kind==="openrouter-current-key"||identity.kind==="gitlab-token-info"||identity.kind==="atlassian-current-user-sites"||identity.kind==="linear-openid-teams"||identity.kind==="asana-user-workspaces"||identity.kind==="zoom-openid-userinfo"||identity.kind==="clickup-current-user-workspaces"||identity.kind==="ticktick-inbox-self"||identity.kind==="notion-bot-owner"||identity.kind==="sentry-catalog-whoami"||identity.kind==="wordpress-user-profile")return Object.keys(identity).every(key=>key==="kind");return identity.kind===void 0&&Object.keys(identity).every(key=>["tool","subjectPath","labelPath"].includes(key))&&typeof identity.tool==="string"&&/^[a-zA-Z0-9_.-]{1,200}$/.test(identity.tool)&&validIdentityPath(identity.subjectPath)&&(identity.labelPath===void 0||validIdentityPath(identity.labelPath))}function validReview(review){try{return!!review&&typeof review==="object"&&!Array.isArray(review)&&Object.keys(review).every(key=>["issuer","scopes","allowedOrigins","identity","redirectUriPolicy","registration"].includes(key))&&Array.isArray(review.scopes)&&review.scopes.length<=32&&new Set(review.scopes).size===review.scopes.length&&review.scopes.every(scope=>typeof scope==="string"&&!!scope&&scope.length<=1024&&!/\s/u.test(scope))&&Array.isArray(review.allowedOrigins)&&review.allowedOrigins.length>0&&review.allowedOrigins.length<=8&&review.allowedOrigins.every(origin=>httpsUrl(origin).origin===origin)&&review.allowedOrigins.includes(httpsUrl(review.issuer).origin)&&(review.redirectUriPolicy===void 0||review.redirectUriPolicy==="https-only")&&(review.identity===void 0||validIdentityReview(review.identity))&&(review.registration===void 0||review.registration.kind==="dcr"&&Object.keys(review.registration).every(key=>["kind","httpsBroker","allowUnadvertisedPublicClient","discardReturnedSecretForPublicClient","tokenEndpointAuthMethod"].includes(key))&&(review.registration.httpsBroker===void 0||review.registration.httpsBroker==="calendly")&&(review.registration.allowUnadvertisedPublicClient===void 0||review.registration.allowUnadvertisedPublicClient===true)&&(review.registration.discardReturnedSecretForPublicClient===void 0||review.registration.discardReturnedSecretForPublicClient===true)&&(review.registration.tokenEndpointAuthMethod===void 0||["client_secret_basic","client_secret_post"].includes(review.registration.tokenEndpointAuthMethod)&&review.registration.allowUnadvertisedPublicClient===void 0&&review.registration.discardReturnedSecretForPublicClient===void 0)||(review.registration.kind==="pre-registered"||review.registration.kind==="cimd")&&Object.keys(review.registration).every(key=>(review.registration.kind==="pre-registered"?["kind","clientId","allowUnadvertisedPublicClient","tokenEndpointAuthMethod"]:["kind","clientId"]).includes(key))&&typeof review.registration.clientId==="string"&&review.registration.clientId.length<=2048&&!!review.registration.clientId&&(review.registration.kind!=="pre-registered"||review.registration.allowUnadvertisedPublicClient===void 0||review.registration.allowUnadvertisedPublicClient===true)&&(review.registration.kind!=="pre-registered"||review.registration.tokenEndpointAuthMethod===void 0||["client_secret_basic","client_secret_post"].includes(review.registration.tokenEndpointAuthMethod)&&review.registration.allowUnadvertisedPublicClient===void 0)&&(review.registration.kind!=="cimd"||httpsUrl(review.registration.clientId).pathname!=="/")||(review.registration.kind==="broker"||review.registration.kind==="redirect-broker")&&Object.keys(review.registration).every(key=>["kind","clientId","brokerBase","brokerPath"].includes(key))&&typeof review.registration.clientId==="string"&&/^[A-Za-z0-9_-]{1,2048}$/.test(review.registration.clientId)&&typeof review.registration.brokerPath==="string"&&/^[a-z][a-z0-9-]{1,39}$/.test(review.registration.brokerPath)&&httpsUrl(review.registration.brokerBase).href===review.registration.brokerBase+"/")}catch{return false}}function sameScopes(left,right){return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&new Set(left).size===left.length&&new Set(right).size===right.length&&left.every(scope=>typeof scope==="string"&&right.includes(scope))}function validClientAuthentication(value){return!!value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).every(key=>["method","secret","expiresAt"].includes(key))&&["client_secret_basic","client_secret_post"].includes(value.method)&&typeof value.secret==="string"&&value.secret.length>0&&value.secret.length<=4096&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value.secret)&&(value.expiresAt===void 0||Number.isSafeInteger(value.expiresAt)&&value.expiresAt>Date.now()&&value.expiresAt<=864e13)}function reviewedDcrConfidentialSource(url,review){const registration=review.registration;if(registration?.kind!=="dcr"||registration.allowUnadvertisedPublicClient!==void 0||registration.discardReturnedSecretForPublicClient!==void 0||review.identity!==void 0||review.redirectUriPolicy!==void 0)return;if(url==="https://mcp.supabase.com/mcp"&&review.issuer==="https://api.supabase.com"&&sameScopes(review.allowedOrigins,["https://api.supabase.com","https://supabase.com"])&&sameScopes(review.scopes,[])&®istration.tokenEndpointAuthMethod==="client_secret_basic")return"supabase";if(url==="https://coda.io/apis/mcp"&&review.issuer==="https://coda.io"&&sameScopes(review.allowedOrigins,["https://coda.io"])&&sameScopes(review.scopes,["mcp:all"])&®istration.tokenEndpointAuthMethod==="client_secret_post")return"coda";if(isReviewedMondayDefault(url,review))return"monday"}const formComponent=value=>new URLSearchParams({v:value}).toString().slice(2);const confidentialBasic=(clientId,secret)=>"Basic "+Buffer.from(formComponent(clientId)+":"+formComponent(secret)).toString("base64");function protectsCredential(credential,onlyClient=false){const authentication=credential.clientAuthentication;const secrets=[...onlyClient?[]:[credential.accessToken,credential.refreshToken],authentication?.secret,...authentication?.method==="client_secret_basic"?[confidentialBasic(credential.clientId,authentication.secret).slice(6)]:[]];return encoded=>secrets.some(secret=>!!secret&&(encoded.includes(secret)||encoded.includes(JSON.stringify(secret).slice(1,-1))))}function reviewedConfidentialSource(url,review){if(review.registration?.kind!=="pre-registered"||!review.registration.tokenEndpointAuthMethod||review.registration.allowUnadvertisedPublicClient!==void 0||review.identity!==void 0||review.redirectUriPolicy!==void 0)return;if((url==="https://mcp.box.com/"||url==="https://mcp.box.com")&&review.issuer==="https://api.box.com"&&sameScopes(review.allowedOrigins,["https://account.box.com","https://api.box.com"])&&review.scopes.every(scope=>["root_readwrite","ai.readwrite","docgen.readwrite"].includes(scope)))return"box";if(url==="https://mcp.frontapp.com/mcp"&&review.issuer==="https://app.frontapp.com"&&sameScopes(review.allowedOrigins,[review.issuer])&&sameScopes(review.scopes,["feature:mcp"])&&review.registration.tokenEndpointAuthMethod==="client_secret_basic")return"front";if(url==="https://mcp.hubspot.com/"&&review.issuer==="https://mcp.hubspot.com"&&sameScopes(review.allowedOrigins,[review.issuer])&&review.scopes.length===0&&review.registration.tokenEndpointAuthMethod==="client_secret_post")return"hubspot";const prefix="https://www.googleapis.com/auth/";if(review.issuer!=="https://accounts.google.com"||!sameScopes(review.allowedOrigins,["https://accounts.google.com","https://oauth2.googleapis.com"]))return;if(url==="https://people.googleapis.com/mcp/v1"&&review.scopes.every(scope=>["contacts.readonly","directory.readonly","userinfo.profile"].some(name=>scope===prefix+name)))return"google-contacts";if(url==="https://chatmcp.googleapis.com/mcp/v1"&&review.scopes.every(scope=>["spaces","spaces.readonly","memberships","memberships.readonly","messages","messages.readonly","messages.create","users.readstate"].some(name=>scope===prefix+"chat."+name)))return"google-chat"}function reviewedDropboxPublicClient(url,review){const scopes=["account_info.read","file_requests.read","file_requests.write","files.content.read","files.content.write","files.metadata.read","files.metadata.write","sharing.read","sharing.write"];return url==="https://mcp.dropbox.com/mcp"&&review.issuer==="https://www.dropbox.com"&&sameScopes(review.allowedOrigins,["https://www.dropbox.com","https://api.dropboxapi.com"])&&review.scopes.every(scope=>scopes.includes(scope))&&review.registration?.kind==="pre-registered"&&review.registration.allowUnadvertisedPublicClient!==true&&review.registration.tokenEndpointAuthMethod===void 0&&review.identity===void 0&&review.redirectUriPolicy===void 0}function reviewedRegisteredPublicSource(url,review){if(review.registration?.kind!=="pre-registered"||review.registration.allowUnadvertisedPublicClient!==true||review.identity!==void 0||review.redirectUriPolicy!==void 0)return;const zoomScopes=["meeting:write:meeting","meeting:read:search","meeting:delete:meeting","meeting:update:in_meeting_controls","meeting:update:meeting","meeting:read:assets","cloud_recording:read:list_user_recordings","cloud_recording:read:content"];if(url==="https://mcp.zoom.us/mcp/meeting/streamable"&&review.issuer==="https://zoom.us"&&sameScopes(review.allowedOrigins,["https://zoom.us"])&&review.scopes.every(scope=>zoomScopes.includes(scope)))return"zoom";for(const environment of["production","sandbox"]){const issuer=environment==="sandbox"?"https://test.salesforce.com":"https://login.salesforce.com";if(url===`https://api.salesforce.com/platform/mcp/v1/${environment==="sandbox"?"sandbox/":""}platform/sobject-all`&&review.issuer===issuer&&sameScopes(review.allowedOrigins,[issuer])&&review.scopes.includes("mcp_api")&&review.scopes.every(scope=>["mcp_api","refresh_token"].includes(scope)))return"salesforce"}}function salesforceTokenExpiry(token,requestedAt){if(typeof token.access_token!=="string"||token.access_token.length>65536)throw Error("Salesforce token expiry was not verified.");const exp=decodeJwt(token.access_token).exp;if(!(typeof exp==="number"&&Number.isInteger(exp)||typeof exp==="string"&&/^[0-9]{1,13}$/u.test(exp)))throw Error("Salesforce token expiry was not verified.");let expiresAt=Number(exp)*1e3;if(token.expires_in!==void 0){if(typeof token.expires_in!=="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw Error("Salesforce token expiry was not verified.");expiresAt=Math.min(expiresAt,requestedAt+token.expires_in*1e3)}if(!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now())throw Error("Salesforce token expiry was not verified.");return expiresAt}function matchesOAuthReview(url,review,server,refresh=false,selectedMethod){try{const metadata=server.authorizationServerMetadata;const registeredPublic=reviewedRegisteredPublicSource(url,review);const dropbox=reviewedDropboxPublicClient(url,review);const confidential=reviewedConfidentialSource(url,review),dynamicConfidential=reviewedDcrConfidentialSource(url,review),method=selectedMethod??(review.registration?.kind==="pre-registered"||review.registration?.kind==="dcr"?review.registration.tokenEndpointAuthMethod:void 0);const authorityMatches=server.authorizationServerUrl===review.issuer||review.identity?.kind==="ticktick-inbox-self"&&review.issuer==="https://ticktick.com"&&server.authorizationServerUrl==="https://ticktick.com/"||!!confidential&&server.authorizationServerUrl===review.issuer+"/";const cloudflareIncrementalScopes=url==="https://mcp.cloudflare.com/mcp"&&review.issuer==="https://mcp.cloudflare.com"&&sameScopes(server.resourceMetadata?.scopes_supported??[],["user:read","account:read"]);return!!metadata&&authorityMatches&&metadata.issuer===review.issuer&&(!dynamicConfidential||server.resourceMetadata?.resource===url&&(dynamicConfidential==="monday"?metadata.authorization_endpoint==="https://auth.monday.com/oauth2/authorize"&&metadata.token_endpoint==="https://auth.monday.com/oauth_ms/oauth/token"&&metadata.registration_endpoint==="https://auth.monday.com/oauth_ms/oauth/register":metadata.authorization_endpoint===review.issuer+(dynamicConfidential==="supabase"?"/v1/oauth/authorize":"/v4/api/oauth2/authorize")&&metadata.token_endpoint===review.issuer+(dynamicConfidential==="supabase"?"/v1/oauth/token":"/v4/api/oauth2/token")&&metadata.registration_endpoint===review.issuer+(dynamicConfidential==="supabase"?"/platform/oauth/apps/register":"/v4/api/oauth2/register")))&&(!(url==="https://mcp.miro.com/"&&review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient)||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint==="https://mcp.miro.com/authorize"&&metadata.token_endpoint==="https://mcp.miro.com/token"&&metadata.registration_endpoint==="https://mcp.miro.com/register")&&(!(url==="https://public-api.wordpress.com/wpcom/v2/mcp/v1"&&review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient)||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint===review.issuer+"/oauth2-1/authorize"&&metadata.token_endpoint===review.issuer+"/oauth2-1/token"&&metadata.registration_endpoint===review.issuer+"/oauth2-1/register")&&(!(url==="https://mcp.pipedrive.ai/mcp"&&review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient)||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint==="https://oauth.pipedrive.com/oauth/authorize"&&metadata.token_endpoint==="https://oauth.pipedrive.com/oauth/token"&&metadata.registration_endpoint==="https://oauth.pipedrive.com/oauth/register")&&(!confidential||server.resourceMetadata?.resource===(confidential==="box"?"https://mcp.box.com/":confidential==="front"?"https://mcp.frontapp.com":confidential==="hubspot"?"https://mcp.hubspot.com":url)&&metadata.authorization_endpoint===(confidential==="box"?"https://account.box.com/api/oauth2/authorize":confidential==="front"?"https://app.frontapp.com/oauth/authorize":confidential==="hubspot"?"https://mcp.hubspot.com/oauth/authorize/user":"https://accounts.google.com/o/oauth2/v2/auth")&&metadata.token_endpoint===(confidential==="box"?"https://api.box.com/oauth2/token":confidential==="front"?"https://app.frontapp.com/oauth/token":confidential==="hubspot"?"https://mcp.hubspot.com/oauth/v3/token":"https://oauth2.googleapis.com/token"))&&(!dropbox||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint==="https://www.dropbox.com/oauth2/authorize"&&metadata.token_endpoint==="https://api.dropboxapi.com/oauth2/token"&&metadata.token_endpoint_auth_methods_supported?.includes("none")===true&&metadata.code_challenge_methods_supported?.includes("S256")===true&&metadata.grant_types_supported?.includes("refresh_token")===true)&&(!registeredPublic||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint===review.issuer+(registeredPublic==="salesforce"?"/services/oauth2/authorize":"/oauth/authorize")&&metadata.token_endpoint===review.issuer+(registeredPublic==="salesforce"?"/services/oauth2/token":"/oauth/token"))&&[metadata.authorization_endpoint,metadata.token_endpoint,...metadata.registration_endpoint?[metadata.registration_endpoint]:[]].every(endpoint=>review.allowedOrigins.includes(httpsUrl(endpoint).origin))&&(!server.resourceMetadata||checkResourceAllowed({requestedResource:resourceUrlFromServerUrl(url),configuredResource:server.resourceMetadata.resource}))&&(refresh||!server.resourceMetadata?.scopes_supported||review.scopes.every(scope=>server.resourceMetadata.scopes_supported.includes(scope)||["openid","email","profile","offline_access"].includes(scope)||cloudflareIncrementalScopes&&metadata.scopes_supported?.includes(scope)))&&(refresh||!metadata.scopes_supported||review.scopes.every(scope=>metadata.scopes_supported.includes(scope)||server.resourceMetadata?.scopes_supported?.includes(scope)||scope==="offline_access"))&&metadata.response_types_supported.includes("code")&&(!metadata.code_challenge_methods_supported||metadata.code_challenge_methods_supported.includes("S256"))&&(method?(metadata.token_endpoint_auth_methods_supported??["client_secret_basic"]).includes(method):!metadata.token_endpoint_auth_methods_supported||metadata.token_endpoint_auth_methods_supported.includes("none")||review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient===true||review.registration?.kind==="broker"||!!registeredPublic)}catch{return false}}function discoveredOAuthReview(url,server){const metadata=server.authorizationServerMetadata;if(!metadata)throw Error("The MCP server did not publish OAuth metadata.");const issuer=metadata.issuer,allowedOrigins=[...new Set([issuer,metadata.authorization_endpoint,metadata.token_endpoint,...metadata.registration_endpoint?[metadata.registration_endpoint]:[]].map(value=>httpsUrl(value).origin))];const review={issuer,allowedOrigins,scopes:[...server.resourceMetadata?.scopes_supported??[]]};if(!validReview(review)||!matchesOAuthReview(url,review,server))throw Error("The MCP server published incompatible OAuth metadata.");return review}function matchesSessionAuthority(authority,url,server,clientId){try{return isMcpSessionAuthority(authority)&&authority.clientId===clientId&&server.authorizationServerMetadata?.issuer===authority.issuer&&server.authorizationServerMetadata.token_endpoint===authority.tokenEndpoint&&new URL(server.resourceMetadata?.resource??resourceUrlFromServerUrl(url).href).href===new URL(authority.resource).href&&checkResourceAllowed({requestedResource:resourceUrlFromServerUrl(url),configuredResource:authority.resource})}catch{return false}}function identityValue(value,path){for(const key of path){if(!value||typeof value!=="object"||Array.isArray(value)||!Object.hasOwn(value,key))throw Error("Provider identity was not uniquely verified.");value=value[key]}if(typeof value==="number"&&Number.isSafeInteger(value)&&value>=0)return String(value);if(typeof value!=="string"||!value||value!==value.trim()||value.length>512)throw Error("Provider identity was not uniquely verified.");return value}function loginSnapshot(login){return{...login,...login.args?{args:structuredClone(login.args)}:{},...login.ready?{ready:{...login.ready,...login.ready.args?{args:structuredClone(login.ready.args)}:{}}}:{},...login.cleanup?{cleanup:{...login.cleanup,...login.cleanup.args?{args:structuredClone(login.cleanup.args)}:{}}}:{},...login.handoff?{handoff:{...login.handoff}}:{},...login.identity?{identity:structuredClone(login.identity)}:{}}}function validateFieldsAccountBinding(auth){if(!("accountBinding"in auth))return;const descriptor=Object.getOwnPropertyDescriptor(auth,"accountBinding");if(!descriptor||!descriptor.enumerable||!("value"in descriptor)||descriptor.value!=="endpoint")throw Error("Invalid fields account binding.")}function validateFieldsTokenDelivery(source,auth,server){const invalid=()=>{throw Error("Invalid HTTP fields token delivery.")};const inert=(value,keys)=>!!value&&typeof value==="object"&&!Array.isArray(value)&&[Object.prototype,null].includes(Object.getPrototypeOf(value))&&Reflect.ownKeys(value).every(key=>typeof key==="string"&&keys.includes(key)&&Object.getOwnPropertyDescriptor(value,key).enumerable&&"value"in Object.getOwnPropertyDescriptor(value,key));if(!inert(auth,["kind","fields","account","login","tokenField","accountBinding"])||typeof auth.tokenField!=="string"||!auth.tokenField||typeof auth.account!=="function"||!Array.isArray(auth.fields)||!auth.fields.length||auth.fields.length>16||auth.fields.some(field=>!inert(field,["key","label","secret"])||typeof field.key!=="string"||!field.key)||new Set(auth.fields.map(field=>field.key)).size!==auth.fields.length||!auth.fields.some(field=>field.key===auth.tokenField&&field.secret===true))return invalid();const allowedServerKeys=["transport","url","authorization"];if(source==="wordpress")allowedServerKeys.push("loopbackPin");if(!inert(server,allowedServerKeys)||server.transport!=="http"||typeof server.url!=="string")return invalid();if(Object.hasOwn(server,"loopbackPin")&&(typeof server.loopbackPin!=="function"||server.authorization?.kind!=="basic"||httpsUrl(server.url).hostname!=="127.0.0.1"))return invalid();if(source==="wordpress"&&server.authorization?.kind==="basic"){const username=server.authorization.username;if(!inert(server.authorization,["kind","username"])||typeof username!=="string"||!username||username.length>60||/[:\u0000-\u001f\u007f]/u.test(username)||!httpsUrl(server.url).pathname.endsWith("/wp-json/indra-l1/v1/mcp")||auth.tokenField!=="applicationPassword"||auth.login?.ready?.tool!=="indra-l1-identity")return invalid();return}if(server.authorization!==void 0&&(!inert(server.authorization,["kind"])||!["bearer","raw"].includes(server.authorization.kind)))return invalid();try{httpsUrl(server.url)}catch{const loopback=/^http:\/\/127\.0\.0\.1:([1-9][0-9]{3,4})\/$/u.exec(server.url);if(!loopback||Number(loopback[1])<1024||Number(loopback[1])>65535||server.authorization?.kind==="raw")return invalid()}}function sourceSnapshot(spec){return{...spec,server:spec.server.transport==="http"?{...spec.server,...spec.server.authorization?{authorization:structuredClone(spec.server.authorization)}:{},...spec.server.metadataHeaders?{metadataHeaders:{...spec.server.metadataHeaders}}:{}}:{...spec.server,args:[...spec.server.args]},...spec.liveRead?{liveRead:{...spec.liveRead,args:structuredClone(spec.liveRead.args??{})}}:{},...spec.exposedTools?{exposedTools:[...spec.exposedTools]}:{},...spec.publicTools?{publicTools:[...spec.publicTools]}:{},...spec.allowedTools?{allowedTools:[...spec.allowedTools]}:{},...spec.excludedTools?{excludedTools:[...spec.excludedTools]}:{},...spec.reviewedReadTools?{reviewedReadTools:structuredClone(spec.reviewedReadTools)}:{},auth:spec.auth.kind==="zendesk-oauth"?{...spec.auth,config:structuredClone(spec.auth.config),login:loginSnapshot(spec.auth.login)}:spec.auth.kind==="custodied"?structuredClone(spec.auth):spec.auth.kind==="mcp-oauth"||spec.auth.kind==="oauth-device"?{...spec.auth,...spec.auth.reviewed?{reviewed:structuredClone(spec.auth.reviewed)}:{}}:spec.auth.kind==="server-login"?{...spec.auth,login:loginSnapshot(spec.auth.login)}:spec.auth.kind==="fields"?{...spec.auth,fields:spec.auth.fields.map(field=>({...field})),...spec.auth.login?{login:loginSnapshot(spec.auth.login)}:{}}:spec.auth}}export function toolRow(source,tool){return{name:`${source}.${tool.name}`,tool:tool.name,effect:tool.annotations?.readOnlyHint===true?"read":"write",description:String(tool.description??"").slice(0,1e3),inputSchema:tool.inputSchema??{type:"object"}}}function textOf(content){return Array.isArray(content)?content.map(c=>c&&typeof c==="object"&&c.type==="text"?String(c.text??""):"").filter(Boolean).join("\n"):""}export function createShallowProvider(spec,deps){if(!SOURCE.test(spec.source))throw new Error(`Invalid level 1 source id '${spec.source}'.`);if(spec.exposedTools&&(!spec.exposedTools.length||new Set(spec.exposedTools).size!==spec.exposedTools.length||spec.exposedTools.some(name=>!TOOL.test(name))))throw new Error(`Invalid exposed tools for '${spec.source}'.`);if(spec.excludedTools&&(!Array.isArray(spec.excludedTools)||new Set(spec.excludedTools).size!==spec.excludedTools.length||spec.excludedTools.some(name=>!TOOL.test(name))))throw new Error(`Invalid excluded tools for '${spec.source}'.`);const authorizationBudget=resolveAuthorizationBudget(deps.authorizationBudget);if(spec.auth.kind==="fields")validateFieldsAccountBinding(spec.auth);if(spec.auth.kind==="custodied")validateCustodiedAuth(spec.auth,spec.server);else if(spec.auth.kind==="zendesk-oauth"){zendeskOAuthEndpoints(spec.auth.config);if(spec.source!=="zendesk"||spec.server.transport!=="stdio"||spec.server.tokenEnv!=="ZENDESK_OAUTH_ACCESS_TOKEN"||spec.auth.login.identity?.tool!=="zendesk_status"||spec.auth.login.ready?.tool!=="zendesk_status")throw Error("Invalid Zendesk native OAuth route.")}else if(spec.auth.kind==="fields"&&Object.hasOwn(spec.auth,"tokenField"))validateFieldsTokenDelivery(spec.source,spec.auth,spec.server);else if(spec.server.transport==="http"?spec.server.authorization!==void 0||spec.server.metadataHeaders!==void 0:spec.server.tokenEnv!==void 0)throw Error("Protected credential delivery requires custodied authorization.");spec=sourceSnapshot(spec);if(spec.auth.kind==="custodied"&&spec.auth.credentialKind==="oauth"&&!validReview({issuer:spec.auth.issuer,scopes:spec.auth.requiredScopes,allowedOrigins:spec.auth.oauth.allowedOrigins}))throw Error("Invalid protected OAuth refresh policy.");const toolName=name=>/^[a-zA-Z0-9_.-]{1,200}$/u.test(name);if(spec.readOnly!==void 0&&spec.readOnly!==true||spec.preserveContent!==void 0&&spec.preserveContent!==true||spec.validateResult!==void 0&&typeof spec.validateResult!=="function"||spec.validateParams!==void 0&&typeof spec.validateParams!=="function"||spec.allowedTools&&(!Array.isArray(spec.allowedTools)||spec.allowedTools.length>256||new Set(spec.allowedTools).size!==spec.allowedTools.length||spec.allowedTools.some(name=>!toolName(name))))throw Error("Invalid prepared tool policy.");if(spec.reviewedReadTools&&(!spec.origin.package&&!spec.origin.artifact||Object.entries(spec.reviewedReadTools).some(([name,pin])=>!toolName(name)||!pin||Object.keys(pin).some(key=>key!=="inputSchemaSha256")||!/^[a-f0-9]{64}$/u.test(pin.inputSchemaSha256))))throw Error("Invalid pinned readonly tool contract.");if(spec.auth.kind==="server-login"&&spec.auth.login.identity){const{format,...review}=spec.auth.login.identity;if(format!==void 0&&format!=="json-text"||!validIdentityReview(review))throw Error("Invalid native server identity contract.")}if(spec.auth.kind==="server-login"){const login=spec.auth.login;if(login.tool!==void 0&&!toolName(login.tool)||!login.tool&&!login.ready||login.instructions!==void 0&&(typeof login.instructions!=="string"||!login.instructions.trim()||login.instructions.length>2048||/[\u0000-\u001f\u007f-\u009f]/u.test(login.instructions)))throw Error("Invalid upstream login instructions.");if(login.handoff&&(!login.tool||!login.ready||typeof login.handoff.instructions!=="function"||login.handoff.image!==void 0&&typeof login.handoff.image!=="function"||login.handoff.automatic!==void 0&&login.handoff.automatic!==true||login.handoff.device!==void 0&&typeof login.handoff.device!=="function"||login.handoff.openingInstructions!==void 0&&(typeof login.handoff.openingInstructions!=="string"||!login.handoff.openingInstructions.trim()||login.handoff.openingInstructions.length>2048||/[\u0000-\u001f\u007f-\u009f]/u.test(login.handoff.openingInstructions))))throw Error("Invalid upstream login handoff.");if(login.cleanup&&(!login.handoff||!toolName(login.cleanup.tool)||typeof login.cleanup.done!=="function"))throw Error("Invalid upstream login cleanup.")}const{vault,enrollment,transport=fetch}=deps;const custodySource=spec.source==="figma"&&spec.auth.kind==="fields"?"figma--pat":spec.source;const info={source:spec.source,label:spec.label,group:spec.group,auth:spec.auth.kind==="fields"||spec.auth.kind==="custodied"&&spec.auth.credentialKind!=="local-no-secret"?"api-key":spec.auth.kind==="none"||spec.auth.kind==="custodied"&&spec.auth.credentialKind==="local-no-secret"?"none":"oauth-browser"};const stop=new AbortController,pending=new Set;const wireSignals=new AsyncLocalStorage;let closed=false,session=null,closing;let checkEpoch=0;let guardedReadsInFlight=0;const guardedReadiness=()=>spec.source==="joplin"||spec.source==="wordpress"||spec.source==="basecamp"||spec.source==="coda"||spec.source==="todoist"||spec.source==="calendly"||spec.source==="monday"||spec.source==="zotero"||spec.source==="webflow"||["visual-studio","modelsim","quartus","simulink","jianying","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","windows-event-viewer","windows-task-scheduler","wsl","docker-desktop","ollama","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter"].includes(spec.source);let readiness;function clearReadiness(){readiness=void 0;checkEpoch++}const starting=new Set,cleanup=new Set;const bound=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;const fail=(code,message)=>businessError(code,message,"plugin");function fieldsGrant(fields){return{fields,...spec.auth.kind==="fields"&&spec.auth.tokenField?{token:fields[spec.auth.tokenField]}:{}}}function containsProtectedMaterial(encoded,grant2){if(grant2.protect?.(encoded))return true;if(spec.auth.kind!=="custodied"&&spec.auth.kind!=="fields")return false;const secrets=[grant2.token,...Object.values(grant2.environment??{})];if(spec.auth.kind==="fields"){for(const field of spec.auth.fields)if(field.secret===true)secrets.push(grant2.fields?.[field.key])}if(spec.server.transport==="http"&&spec.server.authorization?.kind==="basic"&&grant2.token)secrets.push(Buffer.from(spec.server.authorization.username+":"+grant2.token,"utf8").toString("base64"));return secrets.some(secret=>!!secret&&(encoded.includes(secret)||encoded.includes(JSON.stringify(secret).slice(1,-1))))}const jobs=new Map;let loginOwner;let firstRead;async function signedInPage(url,signal){const route=spec.signedIn;return readSignedInPage(deps.browserDriver?.(),{site:route.site,url,timeoutMs:6e4,settleMs:1e4},signal).catch(()=>({state:"failed",reason:"collector_error"}))}async function connectSignedIn(options){const route=spec.signedIn,signal=bound(options?.signal);const outcome=await signedInPage(route.identityUrl,signal);if(!outcome&&!signal.aborted)return void 0;const job={id:randomUUID(),source:spec.source,state:"failed",startedAt:new Date().toISOString()};jobs.set(job.id,job);const failed=(code,message)=>{job.error={code,message};return ok({...job})};if(signal.aborted){job.state="cancelled";return ok({...job})}if(/^browser_session_unavailable(?:\s|$)/.test(outcome.reason??"")){const error={...automaticError("browser_session_unavailable"),code:browserConnectionDiagnostic(outcome.reason)??"browser_session_unavailable"};return failed(error.code,error.message)}if(outcome.state==="login_required")return failed("login_required",`Sign in to ${spec.label} in Chrome on this computer, then connect again. Zortex never asks for your password.`);if(outcome.state!=="completed")return failed("site_read_failed",`${spec.label} could not be read in the background (${String(outcome.reason??outcome.state).split(" ")[0]}).`);const identity=route.identity(outcome);if(!identity)return failed("site_read_failed",`${spec.label} did not show the signed-in account.`);const saved=await vault.saveConnection({source:spec.source,provider:spec.source,account:identity.account,accountId:identity.accountId,scopes:["page.read"],state:"connected",updatedAt:new Date().toISOString()},{...SIGNED_IN_BROWSER_CREDENTIAL,scopes:["page.read"]},{signal});if(!("ok"in saved))return failed("custody_failed","The connection could not be saved on this computer.");if(!route.feedUrl)firstRead={records:route.records(spec.source,outcome),expiresAt:Date.now()+6e4};job.state="connected";job.account=identity.account;return ok({...job})}function rawWire(grant2){if(deps.wire){const{protect:_protect,...wireGrant}=grant2;return deps.wire(spec,wireGrant)}const server=spec.server;if(server.transport==="http"){const target=new URL(server.url),headers={...server.metadataHeaders};if(grant2.token){if(server.authorization?.kind==="query")target.searchParams.set(server.authorization.parameter,grant2.token);else headers.Authorization=server.authorization?.kind==="raw"?grant2.token:server.authorization?.kind==="basic"?`Basic ${Buffer.from(server.authorization.username+":"+grant2.token,"utf8").toString("base64")}`:`Bearer ${grant2.token}`;if(server.authorization?.kind==="bearer")for(const name of server.authorization.additionalHeaders??[])headers[name]=grant2.token}const fieldsToken=spec.auth.kind==="fields"&&spec.auth.tokenField!==void 0;const pin=server.loopbackPin?.();const pinned=pin===void 0?void 0:createPinnedLoopbackHttp(target.href,pin);const protectedFetch=spec.auth.kind==="custodied"||fieldsToken?async(input,init)=>{const requested=new URL(input instanceof Request?input.url:String(input));if(requested.origin!==target.origin||requested.pathname!==target.pathname||fieldsToken&&requested.href!==target.href)throw Error("Protected MCP destination changed.");const signals=[stop.signal,wireSignals.getStore(),init?.signal,input instanceof Request?input.signal:void 0].filter(value=>!!value);const signal=AbortSignal.any(signals);signal.throwIfAborted();await grant2.authorize?.(signal);signal.throwIfAborted();const options={...init,signal,redirect:"error",credentials:"omit"};return pinned?pinned.fetch(transport,input,options):transport(input,options)}:transport;const wire2=new StreamableHTTPClientTransport(target,{fetch:protectedFetch,...Object.keys(headers).length?{requestInit:{headers}}:{}});if(pinned){const close=wire2.close.bind(wire2);wire2.close=async()=>{try{await close()}finally{await pinned.close()}}}return wire2}return new StdioClientTransport({command:server.command,args:server.args,...server.cwd?{cwd:server.cwd}:{},env:{...proxyEnv(),...server.env?.(grant2.fields??{},grant2.token)??{},...grant2.environment??{},...server.tokenEnv&&grant2.token?{[server.tokenEnv]:grant2.token}:{}},stderr:"ignore"})}function wire(grant2){const transport2=rawWire(grant2);if(grant2.authorize){const send=transport2.send.bind(transport2);transport2.send=async(...args)=>{const signal=wireSignals.getStore()??stop.signal;signal.throwIfAborted();await grant2.authorize(signal);signal.throwIfAborted();return send(...args)}}return transport2}function track(set,task){set.add(task);void task.then(()=>set.delete(task),()=>set.delete(task));return task}function dropSession(s=session){if(!s)return Promise.resolve();if(readiness?.session===s)readiness=void 0;if(session===s)session=null;if(!s.closing){s.stop.abort();s.closing=track(cleanup,s.client.close().catch(()=>{}))}return s.closing}function wait(task,signal){signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>{signal.removeEventListener("abort",abort);reject(signal.reason)};signal.addEventListener("abort",abort,{once:true});void task.then(value=>{signal.removeEventListener("abort",abort);resolve(value)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}async function open(grant2,signal){signal.throwIfAborted();if(closed)throw new Error("inactive");const key=JSON.stringify(grant2);if(session?.key!==key){const previous=dropSession();const s2={key,client:new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}}),stop:new AbortController,ready:Promise.resolve([]),published:false,waiters:0};s2.client.onclose=()=>{s2.published=false;s2.stop.abort();if(readiness?.session===s2)clearReadiness();if(session===s2)session=null};session=s2;const setupSignal=bound(s2.stop.signal);s2.ready=track(starting,(async()=>{try{await previous;setupSignal.throwIfAborted();await grant2.authorize?.(setupSignal);setupSignal.throwIfAborted();await wireSignals.run(setupSignal,()=>s2.client.connect(wire(grant2),{signal:setupSignal}));const tools=[];let cursor;for(let page=0;page<10;page++){const listed2=await wireSignals.run(setupSignal,()=>s2.client.listTools(cursor?{cursor}:{},{signal:setupSignal}));if(containsProtectedMaterial(JSON.stringify(listed2),grant2))throw Error("Protected MCP discovery returned credential material.");for(const t of listed2.tools){if(grant2.public&&!spec.publicTools?.includes(t.name)||spec.allowedTools&&!spec.allowedTools.includes(t.name)||spec.exposedTools&&!spec.exposedTools.includes(t.name)||spec.excludedTools?.includes(t.name))continue;let reviewed=t;const pin=spec.reviewedReadTools?.[t.name];if(pin){if(t.annotations?.readOnlyHint===false||reviewedToolSchemaHash(t.inputSchema)!==pin.inputSchemaSha256)throw Error("Pinned readonly MCP tool contract changed.");reviewed={...t,annotations:{...t.annotations,readOnlyHint:true}}}const row=toolRow(spec.source,reviewed);if(spec.adaptSchema)row.inputSchema=spec.adaptSchema(row.tool,row.inputSchema);if(!spec.readOnly||row.effect==="read")tools.push(row)}cursor=listed2.nextCursor;if(!cursor)break}setupSignal.throwIfAborted();s2.published=true;return tools}catch(error){await dropSession(s2);throw error}})())}const s=session;s.waiters++;try{return{client:s.client,tools:await wait(s.ready,signal)}}finally{s.waiters--;if(!s.published&&s.waiters===0)await dropSession(s)}}const selectedReadinessFence=()=>spec.source==="matrix"&&spec.auth.kind==="fields"||spec.auth.kind==="zendesk-oauth"||["ticktick","airtable","gitlab","monday","linear"].includes(spec.source)||["jira","todoist","coda","webflow","wordpress"].includes(spec.source)&&spec.auth.kind!=="custodied";const nativeAccountChoice=options=>options?.selectAccount===true||options?.reauthorize!==true;async function captureAccountChoice(signal){const custody=vault.bindingCustody;if(!custody?.sourceSelection)return fail("failed_precondition",`${spec.label} needs native account selection custody.`);const selected=await wait(custody.sourceSelection(spec.source),signal);if(!("ok"in selected))return selected;const bindings=await wait(custody.bindings(spec.source),signal);if(!("ok"in bindings))return bindings;const inventory=[];for(const binding of bindings.ok){const captured=await wait(custody.bindingInventory(binding.id),signal);if(!("ok"in captured))return captured;if(!captured.ok)return fail("failed_precondition",`${spec.label} account changed before authorization.`);inventory.push(captured.ok)}return ok({revision:selected.ok?.revision??null,inventory})}function accountChoiceProof(choice,accountId,audience){if(!accountId)throw Error("Account selection requires a verified native subject.");const matches=choice.inventory.filter(row2=>row2.binding.identity.source===spec.source&&row2.binding.identity.issuer===spec.source&&row2.binding.identity.subject===accountId&&row2.binding.identity.tenant===null);if(matches.length>1)throw Error("Native account binding is ambiguous.");if(!matches.length)return{selectSource:{expectedSelectionRevision:choice.revision,expectedBindingRevision:0}};const row=matches[0],grant2=row.grants.find(g=>g.purpose==="L1"&&g.audience===audience),resource=row.resources.find(r=>r.id===oauthCredentialResourceId(row.binding.id));if(!grant2||!resource)throw Error("Existing native account needs its original resource authority.");const expectedCredential={bindingId:row.binding.id,bindingRevision:row.binding.revision,grantId:grant2.id,grantRevision:grant2.revision,resourceId:resource.id,resourceRevision:resource.revision};return{selectSource:{expectedSelectionRevision:choice.revision,expectedBindingRevision:row.binding.revision},expectedCredential}}const readinessAuthority=current=>(current.snapshot?[current.snapshot,...current.additionalSnapshots??[]]:[]).map(snapshot=>({bindingId:snapshot.binding.id,bindingRevision:snapshot.binding.revision,grantId:snapshot.grant.id,grantRevision:snapshot.grant.revision,scopeEpoch:snapshot.grant.scopeEpoch,resourceId:snapshot.resource.id,resourceRevision:snapshot.resource.revision,expiresAt:snapshot.material.kind==="oauth"?snapshot.material.credential.expiresAt:0}));function rememberReadiness(current,opened,operation,epoch,signal){if(epoch!==checkEpoch||signal.aborted||closed||!session?.published||session.stop.signal.aborted||session.client!==opened.client||opened.tools.length===0||current.grant.public)return;if(!current.snapshot&&!current.legacyRevision&¤t.pairingRevision===void 0&&spec.auth.kind!=="none")return;const authority=readinessAuthority(current);if(selectedReadinessFence()&&(!current.snapshot||current.selectionRevision===void 0))return;readiness={session,authority,...current.pairingRevision===void 0?{}:{pairingRevision:current.pairingRevision,pairingAccount:current.account},...current.legacyRevision?{legacyRevision:current.legacyRevision}:{},...selectedReadinessFence()?{selectionRevision:current.selectionRevision}:{},value:{actions:opened.tools.length,operation}}}async function currentReadiness(signal){const checked=readiness;if(!checked)return;const discard=()=>{if(readiness===checked)clearReadiness();return void 0};if(closed||signal.aborted||session!==checked.session||!checked.session.published||checked.session.stop.signal.aborted)return discard();try{if(checked.legacyRevision){if(!vault.legacyRevision)return discard();const revision=await wait(vault.legacyRevision(custodySource),signal);if(!("ok"in revision)||revision.ok!==checked.legacyRevision)return discard()}if(checked.pairingRevision!==void 0){if(!vault.joplinFencedRevision)return discard();if(!checked.pairingAccount)return discard();const revision=await wait(vault.joplinFencedRevision(checked.pairingAccount),signal);if(!("ok"in revision)||revision.ok!==checked.pairingRevision)return discard()}if(checked.authority.length){const selectionMatches=async()=>{if(!selectedReadinessFence())return true;if(checked.selectionRevision===void 0||!vault.bindingCustody.sourceSelection)return false;const selected=await wait(vault.bindingCustody.sourceSelection(spec.source),signal);return"ok"in selected&&(selected.ok?.revision??null)===checked.selectionRevision&&(!selected.ok||selected.ok.bindingId===checked.authority[0]?.bindingId)};if(!await selectionMatches())return discard();const custody=vault.bindingCustody;if(!custody?.bindingInventory)return discard();if(spec.auth.kind!=="custodied"){const selected=await wait(custody.resolve({kind:spec.auth.kind==="server-login"?"legacy-source":"selected-source",source:spec.source}),signal);if(!("ok"in selected)||selected.ok.kind!=="resolved"||selected.ok.binding.id!==checked.authority[0].bindingId)return discard()}for(const bindingId of new Set(checked.authority.map(value=>value.bindingId))){const loaded=await wait(custody.bindingInventory(bindingId),signal);if(!("ok"in loaded)||!loaded.ok)return discard();const{binding,grants,resources}=loaded.ok;for(const expected of checked.authority.filter(value=>value.bindingId===bindingId)){const grant2=grants.find(value=>value.id===expected.grantId),resource=resources.find(value=>value.id===expected.resourceId);if(binding.id!==expected.bindingId||binding.revision!==expected.bindingRevision||binding.state!=="connected"||!grant2||grant2.revision!==expected.grantRevision||grant2.scopeEpoch!==expected.scopeEpoch||grant2.state!=="active"||!resource||resource.revision!==expected.resourceRevision||expected.expiresAt>0&&expected.expiresAt<=Date.now())return discard()}}if(!await selectionMatches())return discard()}if(signal.aborted||readiness!==checked||session!==checked.session||checked.session.stop.signal.aborted)return discard();return{actions:checked.value.actions,operation:{...checked.value.operation}}}catch{return discard()}}const nativeAudience=spec.server.transport==="http"?spec.server.url:spec.source;const nativeResourceId=bindingId=>`server-login:${bindingId}`;function registeredSessionMatches(authority){const review=spec.auth.kind==="mcp-oauth"?spec.auth.reviewed:void 0,registration=review?.registration;return registration?.kind!=="pre-registered"||isMcpSessionAuthority(authority)&&spec.server.transport==="http"&&authority.issuer===review.issuer&&authority.resource===(spec.source==="front"&&spec.server.url==="https://mcp.frontapp.com/mcp"?"https://mcp.frontapp.com/":spec.server.url)&&authority.clientId===registration.clientId}function selectedResourceMatches(authority){if(!isMcpSessionAuthority(authority))return false;if(spec.source==="matrix"&&spec.auth.kind==="fields")return authority.resource===matrixHomeserver&&authority.issuer===matrixIssuer&&authority.tokenEndpoint===matrixTokenUrl;if(spec.auth.kind==="oauth-device"){const resource=spec.server.transport==="http"?spec.server.url:spec.auth.tokenUrl;return authority.resource===resource&&authority.issuer===spec.auth.reviewed.issuer&&authority.clientId===spec.auth.clientId&&authority.tokenEndpoint===spec.auth.tokenUrl}return spec.server.transport==="http"&&checkResourceAllowed({requestedResource:resourceUrlFromServerUrl(spec.server.url),configuredResource:authority.resource})}function zendeskBindingMatches(binding,auth,credential){const endpoints=zendeskOAuthEndpoints(auth.config),prefix=`zendesk:v1:${auth.config.subdomain}:`;return spec.source==="zendesk"&&spec.server.transport==="stdio"&&spec.server.tokenEnv==="ZENDESK_OAUTH_ACCESS_TOKEN"&&binding.provider==="zendesk"&&binding.identity.source==="zendesk"&&binding.identity.issuer==="zendesk"&&binding.identity.tenant===null&&!binding.authority&&typeof binding.identity.subject==="string"&&binding.identity.subject.startsWith(prefix)&&/^[1-9][0-9]{0,19}$/u.test(binding.identity.subject.slice(prefix.length))&&(!credential||credential.clientId===endpoints.clientId&&!credential.clientAuthentication&&credential.registeredRedirectUri===endpoints.redirectUri&&sameScopes(credential.scopes,endpoints.scopes))}async function refreshZendeskGrant(snapshot,auth,caller){caller.throwIfAborted();const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition","Zendesk refresh requires durable credential custody.");return custody.refreshResource(snapshot,{kind:"resident"},async current=>{const permitted=authorizedCredential(current);if(!("ok"in permitted))return permitted;if(!permitted.ok.refreshToken)return fail("failed_precondition","Zendesk needs a new authorization.");try{const token=await refreshZendeskToken(auth.config,{refreshToken:permitted.ok.refreshToken,scopes:current.grant.scopes},bound(),(url,init)=>transport(url,init));return ok({kind:"oauth",credential:{...permitted.ok,...token}})}catch{return fail("failed_precondition","Zendesk token refresh failed; reconnect this source.")}})}async function connectZendeskOAuth(auth,options){const endpoints=zendeskOAuthEndpoints(auth.config);if(spec.source!=="zendesk"||spec.server.transport!=="stdio"||spec.server.tokenEnv!=="ZENDESK_OAUTH_ACCESS_TOKEN")return fail("failed_precondition","Zendesk OAuth needs its fixed native server route.");const prior=await vault.connection(custodySource);if(!("ok"in prior))return prior;const choose=nativeAccountChoice(options),expected=choose?void 0:prior.ok?.accountId;const choice=choose?await captureAccountChoice(bound(options?.signal)):void 0;if(choice&&!("ok"in choice))return choice;return enrollment.pkce(info,{clientId:endpoints.clientId,authorizeUrl:endpoints.authorizeUrl,tokenUrl:endpoints.tokenUrl,scope:endpoints.scopes.join(" "),provider:"zendesk",loopbackPort:auth.config.loopbackPort,redirectHost:"127.0.0.1",redirectPath:"/callback",exchangeCode:async(input,signal)=>{if(input.clientId!==endpoints.clientId||input.tokenUrl!==endpoints.tokenUrl)throw Error("Zendesk authorization configuration changed.");const token=await exchangeZendeskCode(auth.config,input,signal,(url,init)=>transport(url,init));return{access_token:token.accessToken,refresh_token:token.refreshToken,expires_at:token.expiresAt,scope:token.scopes.join(" "),token_type:"bearer"}}},async(token,signal)=>{const candidate=await probe({token:token.access_token},signal,auth.login,true).catch(()=>{throw Error("Zendesk native identity verification failed.")});if(!candidate.identity||!/^[1-9][0-9]{0,19}$/u.test(candidate.identity.accountId))throw Error("Zendesk native user identity was not verified.");const accountId=`zendesk:v1:${auth.config.subdomain}:${candidate.identity.accountId}`;if(expected!==void 0&&expected!==accountId)throw Error("Zendesk user or tenant changed; explicitly choose the account again.");if(!Number.isFinite(token.expires_at)||token.expires_at<=Date.now())throw Error("Zendesk authorization expired before identity verification.");return{account:`${auth.config.subdomain}: ${candidate.identity.account}`,accountId,...choice&&"ok"in choice?accountChoiceProof(choice.ok,accountId,"zendesk"):{},credential:{accessToken:token.access_token,refreshToken:token.refresh_token,expiresAt:token.expires_at,clientId:endpoints.clientId,registeredRedirectUri:endpoints.redirectUri,scopes:[...endpoints.scopes]}}},options)}function authorizedCredential(snapshot){if(snapshot.material.kind!=="oauth"||snapshot.resource.kind!=="oauth"||snapshot.resource.owner.kind!=="resident"||snapshot.binding.identity.source!==spec.source)return fail("failed_precondition",`${spec.label} needs a resident-owned OAuth credential resource.`);const credential=snapshot.material.credential;if(spec.auth.kind==="zendesk-oauth"&&!zendeskBindingMatches(snapshot.binding,spec.auth,credential))return fail("permission_denied","Zendesk credential does not match its selected tenant and public client.");const clientAuthentication=credential.clientAuthentication,registration=spec.auth.kind==="mcp-oauth"?spec.auth.reviewed?.registration:void 0;if(clientAuthentication!==void 0&&!validClientAuthentication(clientAuthentication))return fail("failed_precondition",`${spec.label} client authentication is unreadable; reconnect this source.`);if(clientAuthentication&&spec.auth.kind==="mcp-oauth"&®istration?.kind!=="pre-registered"&&!(registration?.kind==="dcr"&&spec.server.transport==="http"&&spec.auth.reviewed&&reviewedDcrConfidentialSource(spec.server.url,spec.auth.reviewed)===spec.source))return fail("permission_denied",`${spec.label} selected OAuth mode does not authorize confidential client authentication.`);if((registration?.kind==="pre-registered"||registration?.kind==="dcr"&®istration.tokenEndpointAuthMethod)&®istration.tokenEndpointAuthMethod!==clientAuthentication?.method)return fail("permission_denied",`${spec.label} credential belongs to another selected OAuth authentication method.`);if(!registeredSessionMatches(snapshot.binding.authority))return fail("permission_denied",`${spec.label} credential belongs to another selected OAuth client or resource.`);if(snapshot.binding.authority&&(!isMcpSessionAuthority(snapshot.binding.authority)||snapshot.binding.authority.clientId!==credential.clientId||snapshot.binding.authority.resource!==snapshot.grant.audience))return fail("permission_denied",`${spec.label} credential no longer matches its selected MCP session.`);if(!sameScopes(snapshot.grant.scopes,credential.scopes))return fail("permission_denied",`${spec.label} credential scopes no longer match its selected L1 grant.`);if(spec.source==="monday"&&!acceptsMondayDefaultGrant(snapshot.grant.scopes))return fail("permission_denied",`${spec.label} saved scopes do not match its reviewed default grant; reconnect this source.`);if(typeof credential.accessToken!=="string"||!credential.accessToken||!Number.isFinite(credential.expiresAt)||credential.expiresAt<0)return fail("failed_precondition",`${spec.label} grant is unreadable; reconnect this source.`);return ok(credential)}async function inspectSelectedAuthority(signal){const custody=vault.bindingCustody;if(!custody?.bindingInventory)return fail("failed_precondition",`${spec.label} status requires its selected credential custody.`);const selected=await wait(custody.resolve({kind:spec.auth.kind==="server-login"?"legacy-source":"selected-source",source:spec.source}),signal);if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition",`${spec.label} needs one selected account or session binding.`);const loaded=await wait(custody.bindingInventory(selected.ok.binding.id),signal);if(!("ok"in loaded))return loaded;if(!loaded.ok)return fail("failed_precondition",`${spec.label} selected binding is not configured.`);const{binding,grants,resources}=loaded.ok,serverLogin=spec.auth.kind==="server-login";if(spec.auth.kind==="zendesk-oauth"&&!zendeskBindingMatches(binding,spec.auth))return fail("permission_denied","Zendesk selected tenant does not match its authorization.");if(binding.identity.source!==spec.source||binding.state!=="connected")return fail("permission_denied",`${spec.label} selected connection is no longer active.`);if(!registeredSessionMatches(binding.authority))return fail("permission_denied",`${spec.label} selected OAuth client or resource has changed.`);if(spec.auth.kind==="server-login"){const native=!!spec.auth.login.identity;if(binding.identity.issuer!==spec.source||(native?!binding.identity.subject:binding.identity.subject!==void 0||!isServerSessionAuthority(binding.authority)||binding.authority.resource!==nativeAudience))return fail("failed_precondition",`${spec.label} needs its selected upstream account or server session binding.`)}else if(binding.authority){if(!selectedResourceMatches(binding.authority))return fail("permission_denied",`${spec.label} selected MCP session belongs to another resource.`)}else if(!binding.identity.subject)return fail("failed_precondition",`${spec.label} has no selected OAuth authority.`);const audience=serverLogin?nativeAudience:binding.authority?.resource??binding.provider;const selectedGrants=grants.filter(grant2=>grant2.bindingId===binding.id&&grant2.purpose==="L1"&&grant2.audience===audience);if(selectedGrants.length!==1||selectedGrants[0].state!=="active")return fail("permission_denied",`${spec.label} selected L1 permission is not active.`);const resourceId=serverLogin?nativeResourceId(binding.id):oauthCredentialResourceId(binding.id),resource=resources.find(value=>value.id===resourceId);if(!resource||resource.bindingId!==binding.id||resource.owner.kind!=="resident"||resource.kind!==(serverLogin?"local-no-secret":"oauth"))return fail("failed_precondition",`${spec.label} selected credential resource is not configured for this source.`);signal.throwIfAborted();return ok(void 0)}function oauthFetch(signal){return async(input,init)=>{signal.throwIfAborted();const response=await transport(input,{...init,redirect:"error",credentials:"omit",signal:init?.signal?AbortSignal.any([signal,init.signal]):signal});signal.throwIfAborted();return response}}async function brokerCall(base,path,body,signal){const target=new URL(path,base+"/");if(target.origin!==new URL(base).origin||target.username||target.password||target.hash)throw Error("Invalid authorization broker request.");const response=await wait(transport(target.href,{method:body?"POST":"GET",redirect:"error",credentials:"omit",signal,headers:{Accept:"application/json",...body?{"Content-Type":"application/json"}:{}},...body?{body:JSON.stringify(body)}:{}}),signal);const size=Number(response.headers.get("content-length")??0);if(size>32768||!response.body)throw Error("Authorization broker returned an invalid response.");const reader=response.body.getReader(),chunks=[];let length=0;try{for(;;){const part=await wait(reader.read(),signal);if(part.done)break;length+=part.value.byteLength;if(length>32768)throw Error("Authorization broker returned an invalid response.");chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(length);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length}let value;try{value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch{throw Error("Authorization broker returned an invalid response.")}if(!response.ok||!value||typeof value!=="object"||Array.isArray(value)||Object.hasOwn(value,"error"))throw Error("Authorization broker refused the request.");return value}function sourceOAuthReviewMatches(review,url){if(review.registration?.kind==="dcr"&&review.registration.tokenEndpointAuthMethod)return reviewedDcrConfidentialSource(url,review)===spec.source;const unadvertised=review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient===true;if(spec.source==="miro"&&unadvertised)return url==="https://mcp.miro.com/"&&review.issuer==="https://mcp.miro.com/"&&sameScopes(review.scopes,["boards:read","boards:write","openid","email"])&&sameScopes(review.allowedOrigins,["https://mcp.miro.com"])&&review.registration?.kind==="dcr"&&!review.registration.discardReturnedSecretForPublicClient&&review.identity===void 0;if(spec.source==="pipedrive"&&unadvertised)return url==="https://mcp.pipedrive.ai/mcp"&&review.issuer==="https://oauth.pipedrive.com"&&sameScopes(review.scopes,["search:read"])&&sameScopes(review.allowedOrigins,["https://oauth.pipedrive.com"])&&review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient===true&&review.identity===void 0;if(spec.source==="wordpress")return url==="https://public-api.wordpress.com/wpcom/v2/mcp/v1"&&review.issuer==="https://public-api.wordpress.com"&&sameScopes(review.allowedOrigins,["https://public-api.wordpress.com"])&&sameScopes(review.scopes,["auth"])&&review.identity?.kind==="wordpress-user-profile"&&review.redirectUriPolicy===void 0&&review.registration?.kind==="dcr"&&Object.keys(review.registration).length===2&&review.registration.discardReturnedSecretForPublicClient===true;const confidentialSource=reviewedConfidentialSource(url,review);if(confidentialSource&&confidentialSource!==spec.source)return false;if(["box","google-contacts","google-chat","front","hubspot"].includes(spec.source)&&review.registration?.kind==="pre-registered"&&review.registration.tokenEndpointAuthMethod){const source=reviewedConfidentialSource(url,review),auth=spec.auth;return source===spec.source&&(auth.kind==="custodied"||auth.kind==="mcp-oauth"&&auth.redirectHost==="localhost"&&Number.isInteger(auth.loopbackPort)&&auth.loopbackPort>=1024&&auth.loopbackPort<=65535)}if(spec.source==="dropbox"&&review.registration?.kind==="pre-registered")return reviewedDropboxPublicClient(url,review)&&spec.auth.kind==="mcp-oauth"&&spec.auth.redirectHost==="localhost"&&Number.isInteger(spec.auth.loopbackPort)&&spec.auth.loopbackPort>=1024&&spec.auth.loopbackPort<=65535;if(review.registration?.kind==="pre-registered"&&review.registration.allowUnadvertisedPublicClient===true){const source=reviewedRegisteredPublicSource(url,review),auth=spec.auth;return source===spec.source&&auth.kind==="mcp-oauth"&&(source==="zoom"?auth.loopbackPort===0&&(auth.redirectHost===void 0||auth.redirectHost==="127.0.0.1"):auth.redirectHost==="localhost"&&Number.isInteger(auth.loopbackPort)&&auth.loopbackPort>=1024&&auth.loopbackPort<=65535)}if(spec.source==="cloudflare")return url==="https://mcp.cloudflare.com/mcp"&&review.issuer==="https://mcp.cloudflare.com"&&(sameScopes(review.scopes,["user:read","account:read","offline_access"])||sameScopes(review.scopes,["user:read","account:read","offline_access","workers-kv-storage.write"]))&&sameScopes(review.allowedOrigins,["https://mcp.cloudflare.com","https://dash.cloudflare.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind===void 0&&review.identity?.tool==="whoami"&&sameScopes(review.identity.subjectPath,["id"])&&sameScopes(review.identity.labelPath??[],["email"]);if(spec.source==="posthog")return(url==="https://mcp.posthog.com/mcp"||url==="https://mcp.posthog.com/mcp?mode=tools&tools=user-get%2Corganizations-get%2Cprojects-get%2Cdashboards-get-all%2Cinsights-list%2Cexecute-sql%2Cannotation-create%2Cannotation-retrieve%2Cannotations-list%2Cannotation-delete")&&review.issuer==="https://oauth.posthog.com"&&sameScopes(review.scopes,["user:read","organization:read","dashboard:read","insight:read","query:read","annotation:read","annotation:write"])&&sameScopes(review.allowedOrigins,["https://oauth.posthog.com","https://us.posthog.com","https://eu.posthog.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind===void 0&&review.identity?.tool==="user-get"&&sameScopes(review.identity.subjectPath,["uuid"])&&sameScopes(review.identity.labelPath??[],["email"]);if(spec.source==="notion-l1")return url==="https://mcp.notion.com/mcp"&&review.issuer==="https://mcp.notion.com"&&sameScopes(review.scopes,["default"])&&sameScopes(review.allowedOrigins,["https://mcp.notion.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind==="notion-bot-owner";if(spec.source==="sentry")return url==="https://mcp.sentry.dev/mcp"&&review.issuer==="https://mcp.sentry.dev"&&sameScopes(review.scopes,["org:read","project:write","team:write","event:write","alerts:write"])&&sameScopes(review.allowedOrigins,["https://mcp.sentry.dev","https://sentry.io"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind==="sentry-catalog-whoami";if(review.identity?.kind==="openrouter-current-key")return!unadvertised&&spec.source==="openrouter"&&url==="https://mcp.openrouter.ai/mcp"&&review.issuer==="https://mcp.openrouter.ai"&&review.allowedOrigins.includes("https://openrouter.ai");if(review.identity?.kind==="gitlab-token-info")return spec.source==="gitlab"&&url==="https://gitlab.com/api/v4/mcp"&&review.issuer==="https://gitlab.com"&&review.scopes.length===1&&review.scopes[0]==="mcp"&&review.allowedOrigins.length===1&&review.allowedOrigins[0]==="https://gitlab.com"&&unadvertised;if(review.identity?.kind==="atlassian-current-user-sites")return(spec.source==="jira"||spec.source==="confluence")&&url==="https://mcp.atlassian.com/v2/mcp"&&review.issuer==="https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3"&&sameScopes(review.scopes,spec.source==="jira"?["read:me","read:account","offline_access","email","read:jira:agent-interface","write:jira:agent-interface","search:jira:agent-interface","delete:jira:agent-interface","manage:jira:agent-interface"]:["read:me","read:account","offline_access","email","read:confluence:agent-interface","write:confluence:agent-interface","search:confluence:agent-interface"])&&sameScopes(review.allowedOrigins,["https://auth.atlassian.com","https://api.atlassian.com"])&&review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient===true&&!unadvertised;if(review.identity?.kind==="linear-openid-teams")return spec.source==="linear"&&url==="https://mcp.linear.app/mcp"&&review.issuer==="https://mcp.linear.app"&&sameScopes(review.scopes,["read","write","openid","email"])&&sameScopes(review.allowedOrigins,["https://mcp.linear.app","https://linear.app"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient;if(review.identity?.kind==="asana-user-workspaces")return spec.source==="asana"&&url==="https://mcp.asana.com/v2/mcp"&&review.issuer==="https://app.asana.com"&&review.scopes.length===0&&sameScopes(review.allowedOrigins,["https://app.asana.com"])&&review.registration?.kind==="broker"&&review.registration.clientId==="1219875673629405"&&review.registration.brokerBase==="https://zortex-auth-9sl.pages.dev"&&review.registration.brokerPath==="asana";if(review.identity?.kind==="clickup-current-user-workspaces")return spec.source==="clickup"&&url==="https://mcp.clickup.com/mcp"&&review.issuer==="https://mcp.clickup.com"&&sameScopes(review.scopes,["read","write"])&&sameScopes(review.allowedOrigins,["https://mcp.clickup.com","https://app.clickup.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient;if(review.identity?.kind==="ticktick-inbox-self")return spec.source==="ticktick"&&url==="https://mcp.ticktick.com"&&review.issuer==="https://ticktick.com"&&sameScopes(review.scopes,["tasks:read","tasks:write"])&&sameScopes(review.allowedOrigins,["https://ticktick.com","https://api.ticktick.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient;if(spec.source==="todoist")return url==="https://ai.todoist.net/mcp"&&review.issuer==="https://todoist.com"&&sameScopes(review.scopes,["data:read_write"])&&sameScopes(review.allowedOrigins,["https://todoist.com","https://app.todoist.com"])&&(!review.registration||review.registration.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient)&&review.identity?.kind===void 0&&review.identity?.tool==="user-info"&&sameScopes(review.identity.subjectPath,["userId"])&&sameScopes(review.identity.labelPath??[],["email"]);return!unadvertised&&!(review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient===true)}async function refreshGrant(snapshot,review,url,caller,issuerDiscovery=false){const custody=vault.bindingCustody,deadline=new AbortController,signal=bound(deadline.signal);const timer=setTimeout(()=>deadline.abort(Error("OAuth refresh deadline exceeded.")),DISCOVERY_TIMEOUT);try{const discoverySignal=AbortSignal.any([signal,caller]);const selected=authorizedCredential(snapshot);if(!("ok"in selected))return selected;if(spec.source==="monday"&&(!review||!isReviewedMondayDefault(url,review)||!acceptsMondayDefaultGrant(snapshot.grant.scopes)))return fail("failed_precondition",`${spec.label} saved scopes do not match its reviewed default grant.`);const issuer=review?.issuer??(isMcpSessionAuthority(snapshot.binding.authority)?snapshot.binding.authority.issuer:void 0);if(issuerDiscovery&&!issuer)return fail("failed_precondition",`${spec.label} refresh requires its original OAuth issuer.`);let server;if(issuerDiscovery){const metadata=await wait(discoverAuthorizationServerMetadata(issuer,{fetchFn:oauthFetch(discoverySignal)}),discoverySignal);if(!metadata)return fail("failed_precondition",`${spec.label} did not publish its original OAuth issuer metadata.`);server={authorizationServerUrl:issuer,authorizationServerMetadata:metadata}}else server=await wait(discoverOAuthServerInfo(url,{fetchFn:oauthFetch(discoverySignal)}),discoverySignal);const originalReview=review??discoveredOAuthReview(url,server);const actualReview={...originalReview,scopes:spec.source==="monday"?[]:[...snapshot.grant.scopes],...!originalReview.registration&&selected.ok.clientAuthentication?{registration:{kind:"pre-registered",clientId:selected.ok.clientId,tokenEndpointAuthMethod:selected.ok.clientAuthentication.method}}:{}};if(actualReview.registration?.kind==="pre-registered"&&(actualReview.registration.allowUnadvertisedPublicClient===true||spec.source==="dropbox")&&!sourceOAuthReviewMatches(actualReview,url))return fail("failed_precondition",`${spec.label} has incompatible public-client refresh settings.`);if(selected.ok.clientAuthentication&&(["box","google-contacts","google-chat","front","hubspot","supabase","coda"].includes(spec.source)||reviewedConfidentialSource(url,actualReview)||reviewedDcrConfidentialSource(url,actualReview))&&!sourceOAuthReviewMatches(actualReview,url)||!matchesOAuthReview(url,actualReview,server,true,selected.ok.clientAuthentication?.method)||snapshot.binding.authority&&(!isMcpSessionAuthority(snapshot.binding.authority)||!matchesSessionAuthority(snapshot.binding.authority,url,server,selected.ok.clientId)))return fail("failed_precondition",`${spec.label} discovery does not match its reviewed authorization policy.`);caller.throwIfAborted();const refreshed=await wait(custody.refreshResource(snapshot,{kind:"resident"},async current=>{const permitted=authorizedCredential(current);if(!("ok"in permitted))return permitted;if(!permitted.ok.refreshToken)return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);try{const requestedAt=Date.now();const clientAuthentication=permitted.ok.clientAuthentication;if(clientAuthentication?.method!==selected.ok.clientAuthentication?.method)return fail("permission_denied",`${spec.label} client authentication changed before refresh.`);const tokens=actualReview.registration?.kind==="broker"?await brokerCall(actualReview.registration.brokerBase,`/${actualReview.registration.brokerPath}/refresh`,{refreshToken:permitted.ok.refreshToken},signal):await wait(refreshAuthorization(server.authorizationServerUrl,{metadata:server.authorizationServerMetadata,clientInformation:{client_id:permitted.ok.clientId,...clientAuthentication?{client_secret:clientAuthentication.secret,token_endpoint_auth_method:clientAuthentication.method}:{}},refreshToken:permitted.ok.refreshToken,...clientAuthentication?{addClientAuthentication:async(headers,params,endpoint)=>{if(String(endpoint)!==server.authorizationServerMetadata.token_endpoint||!(server.authorizationServerMetadata.token_endpoint_auth_methods_supported??["client_secret_basic"]).includes(clientAuthentication.method))throw Error("Selected client authentication changed.");if(clientAuthentication.method==="client_secret_basic")headers.set("Authorization",confidentialBasic(permitted.ok.clientId,clientAuthentication.secret));else{params.set("client_id",permitted.ok.clientId);params.set("client_secret",clientAuthentication.secret)}}}:{},...issuerDiscovery?{}:{resource:new URL(server.resourceMetadata?.resource??resourceUrlFromServerUrl(url).href)},fetchFn:oauthFetch(signal)}),signal);if(clientAuthentication&&protectsCredential(permitted.ok,true)(JSON.stringify(tokens)))return fail("failed_precondition",`${spec.label} refresh returned protected client authentication.`);const scopes=tokens.scope===void 0?permitted.ok.scopes:tokens.scope.split(/\s+/u).filter(Boolean);const salesforce=reviewedRegisteredPublicSource(url,actualReview)==="salesforce";const expiresAt=salesforce?salesforceTokenExpiry(tokens,requestedAt):requestedAt+Number(tokens.expires_in)*1e3;if(!tokens.access_token||tokens.token_type.toLowerCase()!=="bearer"||!sameScopes(scopes,current.grant.scopes)||!salesforce&&(typeof tokens.expires_in!=="number"||!Number.isFinite(tokens.expires_in)||tokens.expires_in<=0)||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()||tokens.refresh_token!==void 0&&!tokens.refresh_token)return fail("failed_precondition",`${spec.label} refresh did not preserve a verified scope and expiry.`);signal.throwIfAborted();return ok({kind:"oauth",credential:{...permitted.ok,accessToken:tokens.access_token,...tokens.refresh_token?{refreshToken:tokens.refresh_token}:{},expiresAt}})}catch{return fail("failed_precondition",`${spec.label} token refresh failed; reconnect this source.`)}}),signal);if("ok"in refreshed||!("err"in refreshed)||refreshed.err.code!=="failed_precondition")return refreshed;const winner=await wait(custody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:snapshot.grant.audience}),signal);if(!("ok"in winner))return winner;const allowed=authorizedCredential(winner.ok);return winner.ok.resource.revision>snapshot.resource.revision&&"ok"in allowed&&(allowed.ok.expiresAt===0||allowed.ok.expiresAt>Date.now()+6e4)?winner:refreshed}catch{return fail(caller.aborted||stop.signal.aborted?"aborted":"failed_precondition",`${spec.label} token refresh did not complete; reconnect this source.`)}finally{clearTimeout(timer)}}async function refreshDeviceGrant(snapshot,auth,caller){const signal=bound(caller),custody=vault.bindingCustody;if(!custody)return fail("failed_precondition",`${spec.label} OAuth access requires durable credential custody.`);if(!validReview(auth.reviewed)||!auth.reviewed.allowedOrigins.includes(httpsUrl(auth.tokenUrl).origin)||snapshot.binding.authority&&(!isMcpSessionAuthority(snapshot.binding.authority)||snapshot.binding.authority.tokenEndpoint!==auth.tokenUrl||snapshot.binding.authority.issuer!==auth.reviewed.issuer))return fail("failed_precondition",`${spec.label} refresh does not match its reviewed authorization policy.`);return custody.refreshResource(snapshot,{kind:"resident"},async current=>{const permitted=authorizedCredential(current);if(!("ok"in permitted))return permitted;if(!permitted.ok.refreshToken)return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);try{const response=await wait(transport(auth.tokenUrl,{method:"POST",redirect:"error",credentials:"omit",signal,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:permitted.ok.clientId,grant_type:"refresh_token",refresh_token:permitted.ok.refreshToken,scope:current.grant.scopes.join(" ")})}),signal);const body=await response.json();const accessToken=typeof body.access_token==="string"?body.access_token:"",tokenType=String(body.token_type??"").toLowerCase();const scopes=body.scope===void 0?[...current.grant.scopes]:String(body.scope).split(/[\s,]+/u).filter(Boolean),seconds=Number(body.expires_in),expiresAt=Date.now()+seconds*1e3;if(!response.ok||!accessToken||tokenType!=="bearer"||!sameScopes(scopes,current.grant.scopes)||!Number.isFinite(seconds)||seconds<=0||!Number.isFinite(expiresAt)||expiresAt<=Date.now())return fail("failed_precondition",`${spec.label} refresh did not preserve a verified scope and expiry.`);if(spec.source==="matrix"){const prefix="urn:matrix:client:device:",device=scopes.find(s=>s.startsWith(prefix))?.slice(prefix.length);if(!device||!matrixUserId(current.binding.identity.subject))return fail("failed_precondition","Matrix refresh needs its original account and device.");await verifyMatrixDevice(transport,signal,accessToken,device,current.binding.identity.subject)}return ok({kind:"oauth",credential:{...permitted.ok,accessToken,...typeof body.refresh_token==="string"&&body.refresh_token?{refreshToken:body.refresh_token}:{},expiresAt}})}catch{return fail("failed_precondition",`${spec.label} token refresh failed; reconnect this source.`)}})}async function checkGrant(current,signal,opened){if(signal.aborted)return fail("aborted",`${spec.label} call was cancelled.`);if(current.pairingRevision!==void 0){if(!vault.joplinFencedRevision)return fail("failed_precondition","Joplin pairing custody is unavailable.");const revision=await wait(vault.joplinFencedRevision(current.account),signal);if(!("ok"in revision))return revision;return revision.ok===current.pairingRevision?ok(void 0):fail("failed_precondition","Joplin pairing changed while the call was pending.")}const expected=current.snapshot;if(!expected)return ok(void 0);try{if(spec.auth.kind==="custodied")return await checkCustodied(spec.source,spec.auth,vault,{snapshot:expected,additionalSnapshots:current.additionalSnapshots??[]},signal);const unchanged=async()=>{if(current.selectionRevision!==void 0){if(!vault.bindingCustody.sourceSelection)return fail("failed_precondition",`${spec.label} selected account custody is unavailable.`);const selected=await wait(vault.bindingCustody.sourceSelection(spec.source),signal);if(!("ok"in selected))return selected;if((selected.ok?.revision??null)!==current.selectionRevision||selected.ok&&selected.ok.bindingId!==expected.binding.id)return fail("failed_precondition",`${spec.label} selected account changed while the call was pending.`)}const latest=await wait(vault.bindingCustody.credentialSnapshot(expected.resource.id,{purpose:"L1",audience:expected.grant.audience}),signal);if(!("ok"in latest))return latest;if(current.selectionRevision!==void 0){const selected=await wait(vault.bindingCustody.sourceSelection(spec.source),signal);if(!("ok"in selected))return selected;if((selected.ok?.revision??null)!==current.selectionRevision||selected.ok&&selected.ok.bindingId!==expected.binding.id)return fail("failed_precondition",`${spec.label} selected account changed while the call was pending.`)}return latest.ok.binding.revision===expected.binding.revision&&latest.ok.grant.id===expected.grant.id&&latest.ok.grant.revision===expected.grant.revision&&latest.ok.grant.scopeEpoch===expected.grant.scopeEpoch&&latest.ok.resource.revision===expected.resource.revision?ok(void 0):fail("failed_precondition",`${spec.label} credential authority changed while the call was pending.`)};const authorized=await unchanged();if(!("ok"in authorized))return authorized;if(isServerSessionAuthority(expected.binding.authority)){if(!opened||spec.auth.kind!=="server-login"||!spec.auth.login.ready)return fail("failed_precondition",`${spec.label} needs its noninteractive upstream session status.`);const ready=spec.auth.login.ready;const check=await wireSignals.run(signal,()=>opened.client.callTool({name:ready.tool,arguments:ready.args??{}},{signal,timeout:IDENTITY_TIMEOUT}));if(Buffer.byteLength(JSON.stringify(check))>MAX_IDENTITY_BYTES)return fail("resource_exhausted",`${spec.label} session status exceeded its bound.`);if(check.isError)return fail("unavailable",`${spec.label} session status could not be confirmed.`);if(!ready.done(check.structuredContent,textOf(check.content)))return fail("unauthenticated",spec.auth.login.instructions??`${spec.label} needs its upstream login; use its connection instructions or QR.`);signal.throwIfAborted();const stillAuthorized=await unchanged();if(!("ok"in stillAuthorized)||!current.nativeIdentity)return stillAuthorized}if(!current.nativeIdentity)return authorized;if(!opened||spec.auth.kind!=="server-login"||!spec.auth.login.identity)return fail("failed_precondition",`${spec.label} native identity cannot be verified.`);const identity=await verifyServerIdentity(opened.client,opened.tools,spec.auth.login.identity,signal);if(identity.accountId!==current.nativeIdentity)return fail("failed_precondition",`${spec.label} signed-in account changed; reconnect the selected account.`);return unchanged()}catch(error){return failure(error,signal)}}async function grant(signal){if(signal.aborted)return fail("aborted",`${spec.label} call was cancelled.`);if(spec.auth.kind==="custodied"){const selected=spec.auth,server=spec.server;const refresh=selected.credentialKind==="oauth"&&selected.oauth?snapshot2=>wait(track(starting,refreshGrant(snapshot2,{issuer:selected.issuer,scopes:selected.requiredScopes,allowedOrigins:selected.oauth.allowedOrigins},server.transport==="http"?server.url:selected.audience,signal,server.transport==="stdio")),signal):void 0;const captured=await captureCustodied(spec.source,selected,vault,signal,refresh);if(!("ok"in captured))return captured;const value=captured.ok,auth=spec.auth;const authorize=async signal2=>{const current2=await checkCustodied(spec.source,auth,vault,value,signal2);if(!("ok"in current2))throw Error("Protected source authority changed before its MCP request.")};const authorityKey2=JSON.stringify([value.snapshot,...value.additionalSnapshots].map(s=>[s.binding.id,s.binding.revision,s.grant.id,s.grant.revision,s.grant.scopeEpoch,s.resource.id,s.resource.revision]));const credential2=value.snapshot.material.kind==="oauth"?value.snapshot.material.credential:void 0;if(credential2?.clientAuthentication&&!validClientAuthentication(credential2.clientAuthentication))return fail("failed_precondition",`${spec.label} client authentication is unreadable; reconnect this source.`);return ok({grant:{...value.token===void 0?{}:{token:value.token},environment:value.environment,authorityKey:authorityKey2,authorize,...credential2?.clientAuthentication?{protect:protectsCredential(credential2)}:{}},account:value.account,snapshot:value.snapshot,additionalSnapshots:value.additionalSnapshots})}if(spec.auth.kind==="none")return ok({grant:{},account:"local"});const matrixFields=spec.source==="matrix"&&spec.auth.kind==="fields";const oauth=spec.auth.kind==="mcp-oauth"||spec.auth.kind==="oauth-device"||spec.auth.kind==="zendesk-oauth";if(oauth&&!vault.bindingCustody?.sourceSelection)return fail("failed_precondition",`${spec.label} selected account custody is unavailable.`);const connection=await vault.connection(custodySource);if(!("ok"in connection))return connection;const nativeMatrix=matrixFields&&!!connection.ok?.authority;if(nativeMatrix&&(!matrixUserId(connection.ok?.accountId)||connection.ok.account!==connection.ok.accountId))return fail("permission_denied","Matrix selected account identity is unavailable.");if(nativeMatrix&&!vault.bindingCustody?.sourceSelection)return fail("failed_precondition","Matrix native account selection is unavailable.");const selection=oauth||nativeMatrix?await vault.bindingCustody.sourceSelection(spec.source):void 0;if(selection&&!("ok"in selection))return selection;const selectionRevision=selection&&"ok"in selection?selection.ok?.revision??null:void 0;if(!connection.ok||connection.ok.state!=="connected"){if(spec.publicTools?.length)return ok({grant:{fields:{},public:true},account:"public (not connected)"});return fail("unauthenticated",`Connect ${spec.label} first (connector.connect with source ${spec.source}).`)}if(spec.auth.kind==="server-login"){const opaque=!spec.auth.login.identity;const custody2=vault.bindingCustody;if(!custody2||(opaque?connection.ok.accountId!==void 0||!isServerSessionAuthority(connection.ok.authority):!connection.ok.accountId))return fail("failed_precondition",`${spec.label} needs its selected upstream account or server session binding.`);const resolved2=await custody2.resolve({kind:"legacy-source",source:spec.source});if(!("ok"in resolved2))return resolved2;if(resolved2.ok.kind!=="resolved")return fail("failed_precondition",`${spec.label} needs one explicit native account binding.`);const captured=await custody2.credentialSnapshot(nativeResourceId(resolved2.ok.binding.id),{purpose:"L1",audience:nativeAudience});if(!("ok"in captured))return captured;const snapshot2=captured.ok;if(snapshot2.material.kind!=="local-no-secret"||snapshot2.resource.kind!=="local-no-secret"||snapshot2.resource.owner.kind!=="resident"||snapshot2.binding.identity.issuer!==spec.source||snapshot2.binding.identity.subject!==connection.ok.accountId||opaque&&(!isServerSessionAuthority(snapshot2.binding.authority)||snapshot2.binding.authority.resource!==nativeAudience))return fail("failed_precondition",`${spec.label} native login custody does not match its selected account.`);return ok({grant:{authorityKey:JSON.stringify([snapshot2.binding.id,snapshot2.binding.revision,snapshot2.grant.revision,snapshot2.resource.revision])},account:snapshot2.binding.account,snapshot:snapshot2,...snapshot2.binding.identity.subject?{nativeIdentity:snapshot2.binding.identity.subject}:{}})}let credential;if(spec.auth.kind==="fields"&&!(matrixFields&&connection.ok.authority)||!connection.ok.accountId&&!connection.ok.authority){const legacyBefore=spec.source!=="joplin"&&spec.auth.kind==="fields"&&!connection.ok.accountId&&!connection.ok.authority&&spec.liveRead&&vault.legacyRevision?await vault.legacyRevision(custodySource):void 0;if(legacyBefore&&!("ok"in legacyBefore))return legacyBefore;let pairingRevision;if(spec.source==="joplin"){if(!vault.joplinFencedSnapshot)return fail("failed_precondition","Joplin pairing custody is unavailable.");const paired=await vault.joplinFencedSnapshot(connection.ok.account);if(!("ok"in paired))return paired;credential=paired.ok.credential;pairingRevision=paired.ok.revision;if(JSON.stringify(paired.ok.connection)!==JSON.stringify(connection.ok))return fail("failed_precondition","Joplin pairing changed; retry.")}else{const stored=await vault.credential(custodySource);if(!("ok"in stored))return stored;credential=stored.ok}if(isSignedInBrowserCredential(credential)){if(spec.publicTools?.length)return ok({grant:{fields:{},public:true},account:connection.ok.account});return fail("failed_precondition",`${spec.label} is connected through Chrome for reading. Connect it from its connection page to use its actions.`)}if(spec.auth.kind==="fields"){try{if(credential.clientId!=="mcp-fields")throw Error("Not a stored fields credential.");const fields=JSON.parse(credential.accessToken),keys=spec.auth.fields.map(field=>field.key);if(!fields||typeof fields!=="object"||Array.isArray(fields)||Object.keys(fields).length!==keys.length||Object.keys(fields).some(key=>!keys.includes(key))||keys.some(key=>{const value=fields[key];return typeof value!=="string"||!value||value.length>4096||/[\u0000-\u001f\u007f-\u009f]/u.test(value)}))throw Error("Stored fields do not match this source.");const values=fields;if((spec.auth.tokenField||spec.auth.accountBinding==="endpoint")&&connection.ok.account!==spec.auth.account(values))throw Error("Stored fields belong to another selected endpoint.");const legacyAfter=legacyBefore&&vault.legacyRevision?await vault.legacyRevision(custodySource):void 0;if(legacyAfter&&!("ok"in legacyAfter))return legacyAfter;if(legacyBefore&&(!("ok"in legacyAfter)||!legacyBefore.ok||legacyBefore.ok!==legacyAfter.ok))return fail("failed_precondition",`${spec.label} connection changed; retry the check.`);return ok({grant:{...fieldsGrant(values),...pairingRevision===void 0?{}:{authorityKey:`joplin-pairing:${pairingRevision}`}},account:connection.ok.account,...pairingRevision===void 0?{}:{pairingRevision},...legacyBefore&&"ok"in legacyBefore&&legacyBefore.ok?{legacyRevision:legacyBefore.ok}:{}})}catch{return fail("failed_precondition",`${spec.label} grant is unreadable; reconnect this source.`)}}}const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition",`${spec.label} OAuth access requires durable credential custody.`);const resolved=await custody.resolve({kind:"selected-source",source:spec.source});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved")return fail("failed_precondition",`${spec.label} needs one explicit account binding.`);let current;try{current=await wait(custody.credentialSnapshot(oauthCredentialResourceId(resolved.ok.binding.id),{purpose:"L1",audience:connection.ok.authority?.resource??connection.ok.provider}),signal)}catch(error){return failure(error,signal)}if(!("ok"in current))return current;const allowed=authorizedCredential(current.ok);if(!("ok"in allowed))return allowed;let snapshot=current.ok;credential=allowed.ok;const selectedBeforeRefresh=await checkGrant({grant:{},account:snapshot.binding.account,snapshot,...selectionRevision===void 0?{}:{selectionRevision}},signal);if(!("ok"in selectedBeforeRefresh))return selectedBeforeRefresh;if(matrixFields&&(snapshot.binding.identity.subject!==connection.ok.accountId||!matrixUserId(snapshot.binding.identity.subject)||!selectedResourceMatches(snapshot.binding.authority)||credential.clientAuthentication||credential.scopes.length!==2||!credential.scopes.includes("urn:matrix:client:api:*")||!credential.scopes.some(scope=>/^urn:matrix:client:device:[a-f0-9]{32}$/u.test(scope))))return fail("permission_denied","Matrix selected account or device permission changed.");if(snapshot.binding.authority&&!selectedResourceMatches(snapshot.binding.authority))return fail("permission_denied",`${spec.label} selected MCP session belongs to another resource.`);if(credential.expiresAt>0&&credential.expiresAt<=Date.now()+6e4){if(spec.auth.kind==="mcp-oauth"&&spec.auth.reviewed?.identity?.kind==="openrouter-current-key")return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);if(!credential.refreshToken)return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);const review=spec.auth.kind==="fields"||spec.auth.kind==="zendesk-oauth"?void 0:spec.auth.reviewed;if(spec.auth.kind!=="zendesk-oauth"&&(review&&!validReview(review)||!review&&!snapshot.binding.authority))return fail("failed_precondition",`${spec.label} refresh requires its original OAuth authority.`);let refreshed;try{refreshed=await wait(track(starting,nativeMatrix?refreshDeviceGrant(snapshot,{tokenUrl:matrixTokenUrl,reviewed:{issuer:matrixIssuer,scopes:credential.scopes,allowedOrigins:[new URL(matrixIssuer).origin]}},signal):spec.auth.kind==="zendesk-oauth"?refreshZendeskGrant(snapshot,spec.auth,signal):spec.auth.kind==="oauth-device"?refreshDeviceGrant(snapshot,spec.auth,signal):spec.server.transport==="http"?refreshGrant(snapshot,review,spec.server.url,signal):Promise.resolve(fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`))),signal)}catch(error){return failure(error,signal)}if(!("ok"in refreshed))return refreshed;const allowed2=authorizedCredential(refreshed.ok);if(!("ok"in allowed2))return allowed2;snapshot=refreshed.ok;credential=allowed2.ok}const authorityKey=JSON.stringify([snapshot.binding.id,snapshot.binding.revision,snapshot.grant.revision,snapshot.resource.revision,...selectionRevision===void 0?[]:[selectionRevision]]);const access={grant:{token:credential.accessToken,authorityKey,...credential.clientAuthentication||spec.auth.kind==="zendesk-oauth"?{protect:protectsCredential(credential)}:{}},account:snapshot.binding.account,snapshot,...selectionRevision===void 0?{}:{selectionRevision}};const selectedAfterRefresh=await checkGrant(access,signal);if(!("ok"in selectedAfterRefresh))return selectedAfterRefresh;access.grant.authorize=async selectedSignal=>{const checked=await checkGrant(access,selectedSignal);if(!("ok"in checked))throw Error("MCP session authority changed before dispatch.")};return ok(access)}function failure(error,signal){if(signal.aborted)return fail("aborted",`${spec.label} call was cancelled.`);if(spec.auth.kind==="custodied")return fail("unavailable",`${spec.label} did not complete the request.`);const message=String(error?.message??error).slice(0,300);const status=error?.status;if(status===401||status===403||/unauthori[sz]ed|invalid_token|401/i.test(message))return fail("failed_precondition",`${spec.label} refused the grant; reconnect this source.`);if(status===429||/\b429\b|rate limit/i.test(message))return fail("resource_exhausted",`${spec.label} rate limit reached; retry later.`);return fail("unavailable",`${spec.label} did not complete the request.`)}async function listed(){if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);const signal=bound();const g=await grant(signal);if(!("ok"in g))return g;try{const opened=await open(g.ok.grant,signal),current=await checkGrant(g.ok,signal,opened);return"ok"in current?ok(opened.tools):current}catch(error){return failure(error,signal)}}const actions={reportsActionAccess:true,async catalog(input={}){const limit=input.limit??50,cursor=input.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid.");const base={source:spec.source,level:1,label:spec.label,auth:info.auth,origin:spec.origin};const tools=await listed();if(!("ok"in tools))return tools;const query=typeof input.query==="string"?input.query.toLowerCase():"";const rows=tools.ok.filter(a=>!query||a.name.toLowerCase().includes(query)||a.description.toLowerCase().includes(query)).map(({tool:_,...row})=>row);return ok({...base,actions:rows.slice(cursor,cursor+limit),total:rows.length,...cursor+limit<rows.length?{nextCursor:cursor+limit}:{}})},async method(name){const tools=await listed();if(!("ok"in tools))return tools;const found=tools.ok.find(a=>a.name===name);if(!found)return fail(spec.publicTools?.length&&!await vault.connection(custodySource).then(c=>"ok"in c&&c.ok?.state==="connected")?"unauthenticated":"not_found",`${spec.label} has no action '${name}'${spec.publicTools?.length?" available without a connection; connect with connector.connect source "+spec.source:""}.`);const{tool:_,...row}=found;return ok({...row,source:spec.source,level:1})},invoke(name,input,options={}){return invokeAction(name,input,options)}};function invokeAction(name,input,options={},readOnly=false){if(pending.size>=MAX_PENDING)return Promise.resolve(fail("resource_exhausted",`${spec.label} has reached its active call bound.`));const task=(async()=>{if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);if(input===null||typeof input!=="object"||input.body!==void 0||input.media!==void 0)return fail("invalid_argument","Level 1 actions take params only.");const params=input.params??{};if(params===null||typeof params!=="object"||Array.isArray(params))return fail("invalid_argument","params must be an object");if(JSON.stringify(params).length>MAX_PARAMS)return fail("invalid_argument","params are too large");const signal=bound(options.signal);const publicLogin=spec.auth.kind==="server-login"&&spec.publicTools?.some(tool=>name===`${spec.source}.${tool}`);const g=publicLogin?ok({grant:{fields:{},public:true},account:"public (not connected)"}):await grant(signal);if(!("ok"in g))return g;const actionGrant=g.ok;let actionEpoch;let guardedReadStarted=false;let used;const matchesAction=()=>actionEpoch!==void 0&&actionEpoch===checkEpoch&&session?.client===used&&(!selectedReadinessFence()||!!readiness&&readiness.session.client===used&&readiness.selectionRevision===actionGrant.selectionRevision&&JSON.stringify(readiness.authority)===JSON.stringify(readinessAuthority(actionGrant)));const isCurrent=!actionGrant.grant.public&&(!!actionGrant.snapshot||actionGrant.pairingRevision!==void 0)?async()=>{if(!matchesAction()||!actionGrant.snapshot&&actionGrant.pairingRevision===void 0)return false;const checked=await checkGrant(actionGrant,signal);return"ok"in checked&&matchesAction()}:void 0;const publicCatalog=(spec.source==="appstore"||spec.group==="Connector / Public data")&&spec.auth.kind==="none"&&name.startsWith(spec.source+".")&&Object.hasOwn(spec.reviewedReadTools??{},name.slice(spec.source.length+1));try{options.onActionAccess?.(actionGrant.grant.public||publicCatalog?"public":"account",publicCatalog?void 0:isCurrent)}catch{}try{const{client,tools}=await open(g.ok.grant,signal);used=client;let epoch=checkEpoch;actionEpoch=epoch;const row=tools.find(a=>a.name===name);if(readOnly&&(tools.filter(a=>a.name===name).length!==1||row?.effect!=="read"))return fail("failed_precondition",`${spec.label} live-read tool is not uniquely declared readonly.`);if(!row)return g.ok.grant.public?fail("unauthenticated",`${spec.label}: '${name}' needs a connection; without one only ${spec.publicTools.map(t=>`${spec.source}.${t}`).join(", ")} work. Connect with connector.connect source ${spec.source}.`):fail("not_found",`${spec.label} has no action '${name}'.`);const current=await checkGrant(g.ok,signal,{client,tools});if(!("ok"in current))return current;const requestParams=structuredClone(params);const wpProfile=spec.source==="wordpress"&&row.tool==="execute"&&Object.keys(requestParams).length===2&&requestParams.name==="wpcom/user-profile"&&!!requestParams.input&&typeof requestParams.input==="object"&&!Array.isArray(requestParams.input)&&Object.keys(requestParams.input).length===0;const readinessRead=row.effect==="read"||wpProfile;if(spec.validateParams){const valid=spec.validateParams(row.tool,Object.freeze(structuredClone(requestParams)));if(!("ok"in valid))return valid}const validationParams=spec.validateResult?Object.freeze(structuredClone(requestParams)):void 0;if(guardedReadiness()&&readinessRead&&row.tool!=="tool_guide"&&!g.ok.grant.public){const zoteroProbe=spec.source==="zotero"&&row.tool==="zotero_get_recent"&&validationParams?.limit===1&&(validationParams.collection_key===void 0||validationParams.collection_key===null);if(spec.source==="zotero"&&!zoteroProbe)checkEpoch++;else clearReadiness();epoch=checkEpoch;actionEpoch=epoch;guardedReadStarted=true;guardedReadsInFlight++}const adapted=await spec.adaptInvoke?.(row.tool,requestParams,g.ok.grant,{signal,fetch:transport});const result=adapted?{content:[{type:"text",text:JSON.stringify(adapted.structured)}],structuredContent:adapted.structured}:await wireSignals.run(signal,()=>client.callTool({name:row.tool,arguments:requestParams},{signal,timeout:CALL_TIMEOUT}));if(closed)return fail("unavailable",`${spec.label} source was disabled before its reply.`);const completed=await checkGrant(g.ok,signal,{client,tools});if(!("ok"in completed))return completed;const text=textOf(result.content);if(result.isError){if(guardedReadiness()&&readinessRead&&row.tool!=="tool_guide"&&epoch===checkEpoch&&session?.client===client)clearReadiness();if(spec.source==="matrix"){if(text==="ZORTEX_MATRIX_READ_FAILURE:auth")return fail("failed_precondition","Matrix rejected authorization; check the grant.");if(text==="ZORTEX_MATRIX_READ_FAILURE:rate")return fail("resource_exhausted","Matrix reported a rate limit; retry later.");if(text==="ZORTEX_MATRIX_READ_FAILURE:upstream")return fail("unavailable","Matrix reported a server error.");if(text==="ZORTEX_MATRIX_READ_FAILURE:network")return fail("unavailable","Matrix could not be reached.")}if(spec.source==="coda"){const prefix=text.trimStart().slice(0,128);if(/^rate limit(?: exceeded| reached)?(?:[.:\s]|$)/i.test(prefix))return fail("resource_exhausted",`${spec.label} reported a rate limit; retry later.`);if(/^unauthori[sz]ed(?:[.:\s]|$)/i.test(prefix))return fail("failed_precondition",`${spec.label} reported an authorization error; check the grant.`)}if(spec.source==="coda"&&process.env.ZORTEX_CODA_ERROR_SHAPE_DIAGNOSTICS==="1"){const hasText=result.content.some(block=>block.type==="text"&&block.text.length>0);const hasStructured=result.structuredContent!==void 0;const shape=hasText?hasStructured?"text+structured":"text":hasStructured?"structured":"empty";const first=hasText?text.trimStart().charAt(0):"";const format=!hasText?"empty":first==="{"?"object-like":first==="["?"array-like":"other";return fail("unavailable",`${spec.label} reported a tool error. Diagnostic shape=${shape}; text-format=${format}.`)}return fail("unavailable",`${spec.label} reported a tool error.`)}const out={text,...result.structuredContent?{structured:result.structuredContent}:{},...spec.preserveContent?{content:structuredClone(result.content)}:{}};const encoded=JSON.stringify(out);const invalidateZoteroFailure=()=>{if(spec.source==="zotero"&&guardedReadStarted&&epoch===checkEpoch&&session?.client===client)clearReadiness()};if(Buffer.byteLength(encoded)>MAX_RESULT){invalidateZoteroFailure();return fail("resource_exhausted",`${spec.label} reply exceeds ${MAX_RESULT} bytes.`)}if(containsProtectedMaterial(encoded,g.ok.grant)){invalidateZoteroFailure();return fail("data_loss",`${spec.label} returned protected credential material instead of a usable record.`)}if(spec.validateResult){const valid=spec.validateResult(row.tool,out,validationParams);if(!("ok"in valid)){invalidateZoteroFailure();return valid}}if(spec.source==="zotero"&&row.effect==="read"&&row.tool==="zotero_get_recent"&&validationParams?.limit===1&&(validationParams.collection_key===void 0||validationParams.collection_key===null)&&!g.ok.grant.public){const records=spec.liveRead?.records(spec.source,out.structured,out.text);if(records)rememberReadiness(g.ok,{client,tools},{state:"succeeded",returned:records.length},epoch,signal)}if((spec.source==="ticktick"||spec.source==="airtable"||spec.source==="gitlab"||spec.source==="monday"||spec.source==="linear"||spec.source==="jira"||spec.source==="github"||spec.source==="confluence"||spec.source==="miro"||guardedReadiness()&&spec.source!=="zotero"&&row.tool!=="tool_guide"&&(spec.source!=="wordpress"||row.tool==="zortex_read_profile"||wpProfile))&&readinessRead&&!g.ok.grant.public){let returned,replyError=false;if(spec.source==="monday"&&row.tool==="list_workspaces"){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0;if(!replyError&&Array.isArray(v.data))returned=v.data.length}}catch{}}if(spec.source==="plecs"||spec.source==="solidworks"||spec.source==="lattics"||spec.source==="jetbrains"||spec.source==="eclipse"||spec.source==="multisim"||spec.source==="stm32cubemx")returned=spec.liveRead?.records(spec.source,out.structured,out.text)?.length;if(spec.source==="confluence"&&row.tool==="searchConfluence"){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0}if(value&&typeof value==="object"&&!Array.isArray(value)&&!replyError){const data=value.data;if(data&&typeof data==="object"&&!Array.isArray(data)&&Array.isArray(data.results))returned=data.results.length}}catch{}}if(spec.source==="wordpress"&&(row.tool==="zortex_read_profile"||wpProfile)){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0;const profile=v.profile;const id=profile&&typeof profile==="object"&&!Array.isArray(profile)?profile.id:void 0;if(!replyError&&(typeof id==="string"&&id.trim()||typeof id==="number"&&Number.isSafeInteger(id)&&id>0))returned=1}}catch{}}if(spec.source==="calendly"&&row.tool==="users-get_current_user"){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0;const resource=v.resource;const uri=resource&&typeof resource==="object"&&!Array.isArray(resource)?resource.uri:void 0;if(!replyError&&typeof uri==="string"&&uri.trim())returned=1}}catch{}}if(replyError){if(epoch===checkEpoch&&session?.client===client)clearReadiness();return fail("unavailable",`${spec.label} reported a read error.`)}if(spec.source==="wordpress"&&returned===void 0){if(epoch===checkEpoch&&session?.client===client)clearReadiness()}else rememberReadiness(g.ok,{client,tools},{state:"succeeded",...returned===void 0?{}:{returned}},epoch,signal)}return ok({source:spec.source,action:name,effect:row.effect,account:g.ok.account,...g.ok.grant.public?{access:"public"}:{},result:out})}catch(error){if(!signal.aborted&&used&&session?.client===used&&(!guardedReadiness()||actionEpoch===checkEpoch))await dropSession();return failure(error,signal)}finally{if(guardedReadStarted)guardedReadsInFlight--}})();return track(pending,task)}async function probe(candidate,signal,login,savedAccessOnly=false,onHandoff,deadline,closeOwned){signal.throwIfAborted();const client=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});let interactiveStarted=false,cleaned=false;const close=async()=>{if(interactiveStarted&&login?.cleanup&&!cleaned){const cleanupSignal=AbortSignal.timeout(CALL_TIMEOUT);const result=await wireSignals.run(cleanupSignal,()=>client.callTool({name:login.cleanup.tool,arguments:login.cleanup.args??{}},{signal:cleanupSignal,timeout:CALL_TIMEOUT}));if(result.isError||Buffer.byteLength(JSON.stringify(result))>MAX_IDENTITY_BYTES||!login.cleanup.done(result.structuredContent,textOf(result.content)))throw Error("Upstream login cleanup was not confirmed.");cleaned=true}await client.close()};try{await candidate.authorize?.(signal);signal.throwIfAborted();await wireSignals.run(signal,()=>client.connect(wire(candidate),{signal}));if(login){const started=Date.now();const authenticated=async()=>{const check=await client.callTool({name:login.ready.tool,arguments:login.ready.args??{}},{signal,timeout:CALL_TIMEOUT});if(Buffer.byteLength(JSON.stringify(check))>MAX_IDENTITY_BYTES)throw Error("Server login status exceeded its bound.");return!check.isError&&login.ready.done(check.structuredContent,textOf(check.content))};let done=login.ready?await authenticated():false;if(!done){if(savedAccessOnly||!login.tool)throw new ServerLoginRequired(login.instructions);interactiveStarted=true;if(login.handoff?.openingInstructions){if(!onHandoff)throw Error("Server login requires an owned handoff.");onHandoff(login.handoff.openingInstructions)}const r=await client.callTool({name:login.tool,arguments:login.args??{}},{signal,timeout:LOGIN_TIMEOUT});if(r.isError)throw new Error(textOf(r.content).slice(0,300)||"login did not complete");if(login.handoff?.openingInstructions&&r.structuredContent?.success===false)throw new Error("The upstream browser login failed or was cancelled.");done=!login.ready;if(login.handoff){if(Buffer.byteLength(JSON.stringify(r))>MAX_IDENTITY_BYTES)throw Error("Server login challenge exceeded its bound.");done=await authenticated();if(!done){const instructions=login.handoff.instructions(r.structuredContent,textOf(r.content));if(typeof instructions!=="string"||!instructions.trim()||Buffer.byteLength(instructions)>2048||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(instructions))throw Error("Server login did not provide valid bounded instructions.");if(!onHandoff)throw Error("Server login requires an owned handoff.");const image=login.handoff.image?authorizationImage(login.handoff.image(r.content)):void 0;if(login.handoff.image&&!image)throw Error("Server login did not provide a valid bounded PNG challenge.");const device=login.handoff.device?.(r.structuredContent,textOf(r.content));if(login.handoff.device){if(!device||typeof device.authorizationUrl!=="string"||device.authorizationUrl.length>2048||typeof device.userCode!=="string"||!/^[A-Z0-9-]{4,32}$/i.test(device.userCode))throw Error("Server login did not provide a supported device challenge.");const url=new URL(device.authorizationUrl);if(url.protocol!=="https:"||url.username||url.password||url.search||url.hash)throw Error("Server login did not provide a supported device challenge.")}onHandoff(instructions,image,device)}}}while(!done){if(Date.now()>=(deadline??started+LOGIN_TIMEOUT))throw new Error(`${spec.label} login was not completed within 10 minutes.`);done=await authenticated();if(!done)await new Promise((resolve,reject)=>{const abort=()=>{clearTimeout(timer);reject(new Error("aborted"))},timer=setTimeout(()=>{signal.removeEventListener("abort",abort);resolve()},LOGIN_POLL);signal.addEventListener("abort",abort,{once:true});if(signal.aborted)abort()})}}const listed2=await wireSignals.run(signal,()=>client.listTools({},{signal}));const identity=login?.identity?await verifyServerIdentity(client,listed2.tools.map(tool=>toolRow(spec.source,tool)),login.identity,signal):void 0;return{count:listed2.tools.length,...identity?{identity}:{}}}finally{if(closeOwned)await closeOwned(close);else await close().catch(()=>{})}}function retryLoginCleanup(owner){if(!owner.finished||!owner.cleanup&&!owner.browserCleanupPending||owner.cleaning)return;const release=async()=>{if(owner.cleanup)try{await owner.cleanup();delete owner.cleanup}catch{}if(owner.browserCleanup)try{await owner.browserCleanup();delete owner.browserCleanup;owner.browserCleanupPending=false}catch{}owner.settled=!owner.cleanup&&!owner.browserCleanupPending};owner.cleaning=track(cleanup,release().finally(()=>{delete owner.cleaning}))}async function connectServerHandoff(login,options){if(options.expectedBinding!==void 0)return fail("failed_precondition","This upstream session requires its existing unambiguous source binding.");const caller=bound(options.signal);if(loginOwner&&!loginOwner.settled){if(loginOwner.job.state!=="waiting-user")return fail("failed_precondition",`${spec.label} is still closing its previous login.`);if(!loginOwner.job.automationActive&&!loginOwner.job.browserContinuation)loginOwner.resume?.();await wait(loginOwner.ready,caller);return ok({...loginOwner.job})}const job={id:randomUUID(),source:spec.source,state:"waiting-user",automationActive:true,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+LOGIN_TIMEOUT).toISOString()};let publish;const ready=new Promise(resolve=>{publish=resolve}),owner={job,stop:new AbortController,settled:false,finished:false,ready,publish:()=>publish(ok({...job}))};loginOwner=owner;jobs.set(job.id,job);const clear=()=>{delete job.automationActive;delete job.browserContinuation;delete job.instructions;delete job.authorizationUrl;delete job.authorizationOrigin;delete job.authorizationImage;delete job.devicePrompt};const cancel=()=>{if(job.state==="waiting-user")job.state="cancelled";clear();owner.stop.abort();owner.publish()};const expire=()=>{if(job.state!=="waiting-user")return;job.state="failed";job.error={code:"authorization_timeout",message:"Upstream login timed out. Start a new connection."};clear();owner.stop.abort();owner.publish()};const timer=setTimeout(expire,LOGIN_TIMEOUT);timer.unref();options.signal?.addEventListener("abort",cancel,{once:true});const signal=bound(owner.stop.signal);void track(starting,(async()=>{try{signal.throwIfAborted();const previous=await vault.connection(custodySource);signal.throwIfAborted();const selected="ok"in previous&&previous.ok&&options.automatic!==false?await inspectSelectedAuthority(signal):previous;if(!("ok"in selected)){job.state="failed";job.error="err"in selected?{code:selected.err.code,message:selected.err.message}:{code:"failed_precondition",message:"The selected upstream session is unavailable."};return}await dropSession();signal.throwIfAborted();const native=await probe({},signal,login,options.savedAccessOnly===true,(instructions,image,device)=>{signal.throwIfAborted();job.instructions=instructions;if(image)job.authorizationImage=image;if(instructions!==login.handoff?.openingInstructions)delete job.automationActive;job.error={code:"login_required",message:"Continue the active upstream transaction with the available tools."};if(device){job.authorizationUrl=device.authorizationUrl;job.authorizationOrigin=new URL(device.authorizationUrl).origin;job.devicePrompt={kind:"device-code",userCode:device.userCode};owner.resume=()=>{if(job.state!=="waiting-user"||signal.aborted||job.automationActive||job.browserContinuation)return;delete job.error;void track(starting,continueAuthorizationWithBrowser(job,device.authorizationUrl,[new URL(device.authorizationUrl).origin],signal,deps.actions,{code:device.userCode}).then(async result=>{if(result?.cleanup){if(result.close)owner.browserCleanup=result.close;owner.browserCleanupPending=true}if(job.state==="waiting-user"&&!signal.aborted){if(result?.code==="authorization_callback_missing"){job.automationActive=true;delete job.error}else job.error=result?{code:result.code,message:result.message}:automaticError("browser_driver_unavailable");owner.publish()}if(result?.cleanup)try{await result.cleanup;owner.browserCleanupPending=false;delete owner.browserCleanup;if(owner.finished&&!owner.cleanup)owner.settled=true}catch{}}))};owner.resume()}owner.publish()},Date.parse(job.expiresAt),async close=>{owner.cleanup=close;await owner.cleanup();delete owner.cleanup});signal.throwIfAborted();const identity=native.identity??{account:`${spec.label} session`},saved=await saveServerIdentity(identity,signal,options.automatic!==false);if(!("ok"in saved)){job.state="failed";job.error="err"in saved?{code:saved.err.code,message:saved.err.message}:{code:"failed_precondition",message:"The upstream session could not be saved."};return}signal.throwIfAborted();job.state="connected";job.account=identity.account;delete job.error}catch(error){if(job.state==="waiting-user"){if(Date.now()>=Date.parse(job.expiresAt))expire();else if(signal.aborted)job.state="cancelled";else{job.state="failed";const failed=failure(error,signal);job.error=error instanceof ServerLoginRequired?{code:"login_required",message:error.message||"Sign in through the upstream application."}:"err"in failed?{code:failed.err.code,message:failed.err.message}:{code:"unavailable",message:"Upstream login did not complete."}}}}finally{clearTimeout(timer);options.signal?.removeEventListener("abort",cancel);if(job.state!=="waiting-user"){clear();owner.stop.abort()}owner.finished=true;owner.settled=!owner.cleanup&&!owner.browserCleanupPending;owner.publish()}})());if(options.signal?.aborted)cancel();return wait(ready,caller)}async function verifyServerIdentity(client,tools,review,signal){const matches=tools.filter(tool=>tool.tool===review.tool);if(matches.length!==1||matches[0].effect!=="read")throw Error("Native identity tool is not uniquely declared readonly.");const result=await wireSignals.run(signal,()=>client.callTool({name:review.tool,arguments:{}},{signal,timeout:IDENTITY_TIMEOUT}));if(result.isError)throw Error("Native identity verification failed.");let value=result.structuredContent;if(review.format==="json-text"){const content=result.content;if(content.length!==1||content[0]?.type!=="text"||typeof content[0].text!=="string"||Buffer.byteLength(content[0].text)>MAX_IDENTITY_BYTES)throw Error("Native identity response is invalid or exceeds its limit.");try{value=JSON.parse(content[0].text)}catch{throw Error("Native identity response is not JSON.")}}else if(Buffer.byteLength(JSON.stringify(value)??"")>MAX_IDENTITY_BYTES)throw Error("Native identity response exceeds its limit.");const accountId=identityValue(value,review.subjectPath),account=review.labelPath?identityValue(value,review.labelPath):accountId;if(/[\u0000-\u001f\u007f]/u.test(accountId+account))throw Error("Native identity fields are invalid.");signal.throwIfAborted();return{account,accountId}}async function saveServerIdentity(identity,signal,automatic=false){const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition",`${spec.label} upstream login requires durable credential custody.`);const previous=await vault.connection(custodySource);if(!("ok"in previous))return previous;if(previous.ok&&previous.ok.accountId===void 0&&!isServerSessionAuthority(previous.ok.authority))return fail("failed_precondition",`${spec.label} has an unattributed legacy account; select its verified binding first.`);const selected=await custody.bindings(spec.source);if(!("ok"in selected))return selected;if(selected.ok.length>1)return fail("failed_precondition",`${spec.label} needs one explicit account or session binding.`);let binding=selected.ok[0];if(binding&&(binding.identity.issuer!==spec.source||binding.identity.subject!==identity.accountId||binding.identity.tenant!==null||identity.accountId===void 0&&(!isServerSessionAuthority(binding.authority)||binding.authority.resource!==nativeAudience)))return fail("failed_precondition",`${spec.label} upstream login does not match the selected account or session.`);const stamp=new Date().toISOString();signal.throwIfAborted();if(!binding){const created=await custody.compareAndSwapBinding({id:randomUUID(),revision:0,identity:{source:spec.source,issuer:spec.source,...identity.accountId?{subject:identity.accountId}:{},tenant:null},...identity.accountId?{}:{authority:{kind:"server-session",id:randomUUID(),resource:nativeAudience}},provider:spec.source,account:identity.account,state:"disconnected",verifiedAt:stamp,updatedAt:stamp},0);if(!("ok"in created))return created;binding=created.ok}const granted=await custody.grantForBinding(binding.id,"L1",nativeAudience);if(!("ok"in granted))return granted;if(granted.ok?.state==="revoked"&&automatic)return fail("permission_denied",`${spec.label} upstream login permission was revoked; reconnect this source explicitly.`);if(!granted.ok||granted.ok.state!=="active"){signal.throwIfAborted();const saved2=await custody.compareAndSwapGrant({id:granted.ok?.id??randomUUID(),revision:granted.ok?.revision??0,bindingId:binding.id,purpose:"L1",audience:nativeAudience,scopes:[],scopeEpoch:(granted.ok?.scopeEpoch??-1)+1,state:"active",updatedAt:stamp},granted.ok?.revision??0);if(!("ok"in saved2))return saved2}const resourceId=nativeResourceId(binding.id),resource=await custody.resource(resourceId);if(!("ok"in resource))return resource;if(resource.ok&&(resource.ok.kind!=="local-no-secret"||resource.ok.owner.kind!=="resident"))return fail("failed_precondition",`${spec.label} native login resource has a different owner or credential kind.`);if(!resource.ok){signal.throwIfAborted();const saved2=await custody.compareAndSwapResource({id:resourceId,revision:0,bindingId:binding.id,kind:"local-no-secret",owner:{kind:"resident"},encryptedRef:null,updatedAt:stamp},{kind:"local-no-secret"},0);if(!("ok"in saved2))return saved2}signal.throwIfAborted();const saved=await custody.compareAndSwapBinding({...binding,account:identity.account,state:"connected",verifiedAt:stamp,updatedAt:stamp},binding.revision);return"ok"in saved?ok(void 0):saved}function blockedAuthorization(code,message){const job={id:randomUUID(),source:spec.source,state:"failed",startedAt:new Date().toISOString(),error:{code,message}};jobs.set(job.id,job);return ok({...job})}async function verifyOpenRouterIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const request=transport(OPENROUTER_KEY_URL,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}).then(response2=>{if(signal.aborted){void response2.body?.cancel().catch(()=>{});signal.throwIfAborted()}return response2});const response=await wait(request,signal);if(response.status!==200||response.redirected||response.url&&response.url!==OPENROUTER_KEY_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part2=await wait(reader.read(),signal);if(part2.done)break;bytes+=part2.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part2.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();const body=JSON.parse(text);if(!body||typeof body!=="object"||Array.isArray(body)||Object.hasOwn(body,"error")||!Object.hasOwn(body,"data"))throw Error("Provider identity was not uniquely verified.");const data=body.data;if(!data||typeof data!=="object"||Array.isArray(data))throw Error("Provider identity was not uniquely verified.");const fields=data;const part=key=>{const value=fields[key];if(!Object.hasOwn(fields,key)||typeof value!=="string"||!value||value.length>128||/[\s\u0000-\u001f\u007f]/u.test(value))throw Error("Provider identity was not uniquely verified.");return value};const creator=part("creator_user_id"),workspace=part("workspace_id");const organization=Object.hasOwn(fields,"organization_id")&&fields.organization_id===null?null:part("organization_id");const accountId=`openrouter:v1:${JSON.stringify([creator,organization,workspace])}`;if(accountId.length>512)throw Error("Provider identity was not uniquely verified.");let expiresAt;if(Object.hasOwn(fields,"expires_at")){if(fields.expires_at===null)expiresAt=0;else{const stamp=typeof fields.expires_at==="string"?fields.expires_at.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(?:Z|\+00:00)$/):null;expiresAt=stamp?Date.parse(fields.expires_at):NaN;if(!stamp||!Number.isFinite(expiresAt)||expiresAt<=Date.now()||new Date(expiresAt).toISOString()!==`${stamp[1]}.${(stamp[2]??"").padEnd(3,"0").slice(0,3)}Z`)throw Error("Provider key expiry was not verified.")}}signal.throwIfAborted();return{account:accountId,accountId,...expiresAt===void 0?{}:{expiresAt}}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyGitLabIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const request=transport(GITLAB_TOKEN_INFO_URL,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}).then(response2=>{if(signal.aborted){void response2.body?.cancel().catch(()=>{});signal.throwIfAborted()}return response2});const response=await wait(request,signal);if(response.status!==200||response.redirected||response.url&&response.url!==GITLAB_TOKEN_INFO_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();const body=JSON.parse(text);if(!body||typeof body!=="object"||Array.isArray(body)||Object.hasOwn(body,"error"))throw Error("Provider identity was not uniquely verified.");const fields=body;if(!Array.isArray(fields.scope)||fields.scope.length!==1||fields.scope[0]!=="mcp")throw Error("Provider credential scope does not match the authorized grant.");const accountId=identityValue(fields,["resource_owner_id"]);signal.throwIfAborted();return{account:`GitLab user ${accountId}`,accountId}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyAtlassianIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);const read=async url=>{let reader;try{signal.throwIfAborted();const response=await wait(transport(url,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==url||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();return JSON.parse(text)}finally{if(reader)void reader.cancel().catch(()=>{})}};try{const me=await read(ATLASSIAN_ME_URL);if(!me||typeof me!=="object"||Array.isArray(me)||Object.hasOwn(me,"error"))throw Error("Provider identity was not uniquely verified.");const fields=me,userId=identityValue(fields,["account_id"]);if(userId.length>128||/[\u0000-\u001f\u007f]/u.test(userId))throw Error("Provider identity was not uniquely verified.");const sites=await read(ATLASSIAN_RESOURCES_URL);if(!Array.isArray(sites)||sites.length<1||sites.length>256)throw Error("Provider identity sites were not uniquely verified.");const siteIds=sites.map(site=>{if(!site||typeof site!=="object"||Array.isArray(site))throw Error("Provider identity sites were not uniquely verified.");const row=site,id=identityValue(row,["id"]),siteUrl=identityValue(row,["url"]);if(id.length>128||/[\s\u0000-\u001f\u007f]/u.test(id)||httpsUrl(siteUrl).origin!==siteUrl)throw Error("Provider identity sites were not uniquely verified.");return id}).sort();if(new Set(siteIds).size!==siteIds.length)throw Error("Provider identity sites were not uniquely verified.");const label=typeof fields.name==="string"&&fields.name===fields.name.trim()&&fields.name.length<=200&&!/[\u0000-\u001f\u007f]/u.test(fields.name)?fields.name:userId;const siteHash=createHash("sha256").update(JSON.stringify(siteIds),"utf8").digest("hex");signal.throwIfAborted();return{account:`${label} (${siteIds.length} Atlassian site${siteIds.length===1?"":"s"})`,accountId:`atlassian:v1:${userId}:${siteHash}`}}finally{clearTimeout(timer);deadline.abort()}}async function verifyLinearIdentity(_token,idToken,clientId,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const response=await wait(transport(LINEAR_JWKS_URL,{method:"GET",headers:{Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==LINEAR_JWKS_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();reader=void 0;const jwks=JSON.parse(text);const verified=await jwtVerify(idToken,createLocalJWKSet(jwks),{issuer:"https://mcp.linear.app",audience:clientId,algorithms:["RS256"],requiredClaims:["sub","email","email_verified"]});const sub=identityValue(verified.payload,["sub"]),email=identityValue(verified.payload,["email"]);if(verified.payload.email_verified!==true||sub.length>200||email.length>320||!email.includes("@")||/[\s\u0000-\u001f\u007f]/u.test(sub+email))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:email,accountId:`linear:v2:${sub}`}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyAsanaIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let client;try{client=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="get_me");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("Provider identity tool is not uniquely declared readonly.");const result=await client.callTool({name:"get_me",arguments:{}},{signal,timeout:CALL_TIMEOUT});if(result.isError||!result.structuredContent||typeof result.structuredContent!=="object"||Array.isArray(result.structuredContent))throw Error("Provider identity verification failed.");const root=result.structuredContent,data=root.data;const me=data&&typeof data==="object"&&!Array.isArray(data)?data:root;const userId=identityValue(me,["gid"]),name=typeof me.email==="string"&&me.email.trim()?me.email.trim():identityValue(me,["name"]);if(userId.length>200||name.length>320||/[\u0000-\u001f\u007f]/u.test(userId+name))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:name,accountId:`asana:v2:${userId}`}}finally{clearTimeout(timer);deadline.abort();if(client)await client.close().catch(()=>{})}}async function verifyZoomIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const response=await wait(transport(ZOOM_USERINFO_URL,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==ZOOM_USERINFO_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();reader=void 0;const body=JSON.parse(text);if(!body||typeof body!=="object"||Array.isArray(body)||Object.hasOwn(body,"error"))throw Error("Provider identity was not uniquely verified.");const profile=body,subject=identityValue(profile,["sub"]),email=identityValue(profile,["email"]);if(profile.email_verified!==true||subject.length>200||email.length>320||!email.includes("@")||/[\s\u0000-\u001f\u007f]/u.test(subject+email))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:email,accountId:`zoom:v1:${subject}`}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyClickUpIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);const read=async url=>{let reader;try{signal.throwIfAborted();const response=await wait(transport(url,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==url||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();return JSON.parse(text)}finally{if(reader)void reader.cancel().catch(()=>{})}};try{const userBody=await read(CLICKUP_USER_URL);if(!userBody||typeof userBody!=="object"||Array.isArray(userBody)||Object.hasOwn(userBody,"error"))throw Error("Provider identity was not uniquely verified.");const root=userBody,rawUser=root.user;const user=rawUser&&typeof rawUser==="object"&&!Array.isArray(rawUser)?rawUser:root;const userId=identityValue(user,["id"]),label=typeof user.email==="string"&&user.email.trim()?user.email.trim():identityValue(user,["username"]);if(userId.length>200||label.length>320||/[\s\u0000-\u001f\u007f]/u.test(userId)||/[\u0000-\u001f\u007f]/u.test(label))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:label,accountId:`clickup:v2:${userId}`}}finally{clearTimeout(timer);deadline.abort()}}async function verifyTickTickIdentity(token,signal){const client=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});try{await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="list_project_members");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("TickTick identity tool is not uniquely readonly.");const result=await client.callTool({name:"list_project_members",arguments:{project_id:"inbox"}},{signal,timeout:CALL_TIMEOUT});const body=result.structuredContent;if(result.isError||!Array.isArray(body?.result))throw Error("TickTick identity response is invalid.");const selves=body.result.filter(member=>member&&typeof member==="object"&&member.self===true);if(selves.length!==1)throw Error("TickTick current member is not unique.");const username=identityValue(selves[0],["username"]);if(username.length>320||/[\s\u0000-\u001f\u007f]/u.test(username))throw Error("TickTick account username is invalid.");signal.throwIfAborted();return{account:username,accountId:username}}finally{await client.close().catch(()=>{})}}async function verifyWordPressIdentity(token,caller){const auth=spec.auth;if(spec.source!=="wordpress"||spec.server.transport!=="http"||spec.server.url!=="https://public-api.wordpress.com/wpcom/v2/mcp/v1"||auth.kind!=="mcp-oauth"||auth.reviewed?.issuer!=="https://public-api.wordpress.com")throw Error("WordPress identity authority is invalid.");const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);const client=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);try{await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),describers=tools.tools.filter(tool=>tool.name==="describe"),executors=tools.tools.filter(tool=>tool.name==="execute");if(describers.length!==1||describers[0].annotations?.readOnlyHint!==true||executors.length!==1||executors[0].annotations?.readOnlyHint!==false)throw Error("WordPress identity catalog contract changed.");const described=await client.callTool({name:"describe",arguments:{names:["wpcom/user-profile"],include_output_schema:true}},{signal,timeout:CALL_TIMEOUT});const description=described.structuredContent;if(described.isError||!object(description)||!Array.isArray(description.results)||description.results.length!==1)throw Error("WordPress identity description is invalid.");const ability=description.results[0];if(!object(ability)||ability.name!=="wpcom/user-profile"||!object(ability.annotations)||ability.annotations.readonly!==true||ability.annotations.destructive!==false||ability.requires_confirmation!==false)throw Error("WordPress current-user ability is not explicitly readonly.");const result=await client.callTool({name:"execute",arguments:{name:"wpcom/user-profile",input:{fields:["id","username","email","display_name"]}}},{signal,timeout:CALL_TIMEOUT});const body=result.structuredContent;if(result.isError||!object(body)||!object(body.profile))throw Error("WordPress identity response is invalid.");const{id,email}=body.profile;if(typeof id!=="number"||!Number.isSafeInteger(id)||id<=0||typeof email!=="string"||email.length>320||!/^[^\s@]+@[^\s@]+$/u.test(email)||/[\u0000-\u001f\u007f-\u009f]/u.test(email))throw Error("WordPress current-user identity is invalid.");signal.throwIfAborted();return{account:email,accountId:`wordpress:v1:${id}`}}finally{clearTimeout(timer);deadline.abort();await client.close().catch(()=>{})}}async function verifyOAuthIdentity(token,review,signal,oidc){if(review.kind==="wordpress-user-profile")return verifyWordPressIdentity(token,signal);if(review.kind==="openrouter-current-key")return verifyOpenRouterIdentity(token,signal);if(review.kind==="gitlab-token-info")return verifyGitLabIdentity(token,signal);if(review.kind==="atlassian-current-user-sites")return verifyAtlassianIdentity(token,signal);if(review.kind==="linear-openid-teams")return verifyLinearIdentity(token,String(oidc?.idToken??""),String(oidc?.clientId??""),signal);if(review.kind==="asana-user-workspaces")return verifyAsanaIdentity(token,signal);if(review.kind==="zoom-openid-userinfo")return verifyZoomIdentity(token,signal);if(review.kind==="clickup-current-user-workspaces")return verifyClickUpIdentity(token,signal);if(review.kind==="ticktick-inbox-self")return verifyTickTickIdentity(token,signal);if(review.kind==="notion-bot-owner"){const client2=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});try{await client2.connect(wire({token}),{signal});const tools=await client2.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="notion-get-self");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("Notion identity tool is not uniquely readonly.");const result=await client2.callTool({name:"notion-get-self",arguments:{}},{signal,timeout:CALL_TIMEOUT});if(result.isError||!Array.isArray(result.content)||result.content.length!==1||result.content[0]?.type!=="text")throw Error("Notion identity response is invalid.");let body;try{body=JSON.parse(result.content[0].text)}catch{throw Error("Notion identity response is invalid.")}if(!body||typeof body!=="object"||Array.isArray(body))throw Error("Notion identity response is invalid.");const userType=identityValue(body,["user","type"]),userId=identityValue(body,["user","id"]);const account=identityValue(body,["user","email"]),workspaceId=identityValue(body,["workspace","id"]);if(userType!=="person"||userId.length>200||workspaceId.length>200||account.length>320||/[\s\u0000-\u001f\u007f]/u.test(userId)||/[\s\u0000-\u001f\u007f]/u.test(workspaceId)||/[\s\u0000-\u001f\u007f]/u.test(account))throw Error("Notion identity response is invalid.");signal.throwIfAborted();return{account,accountId:`notion:v1:${userId}:${workspaceId}`}}finally{await client2.close().catch(()=>{})}}if(review.kind==="sentry-catalog-whoami"){const client2=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});try{await client2.connect(wire({token}),{signal});const tools=await client2.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="execute_sentry_tool");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==false||matches[0].annotations?.destructiveHint!==true)throw Error("Sentry catalog executor contract changed.");const result=await client2.callTool({name:"execute_sentry_tool",arguments:{name:"whoami",arguments:{}}},{signal,timeout:CALL_TIMEOUT});if(result.isError)throw Error("Sentry identity verification failed.");const accountId=identityValue(result.structuredContent,["user","id"]),account=identityValue(result.structuredContent,["user","email"]);signal.throwIfAborted();return{account,accountId}}finally{await client2.close().catch(()=>{})}}const client=new Client({name:"Zortex level 1",version:"0.2.0"},{capabilities:{}});try{await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name===review.tool);if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("Provider identity tool is not uniquely declared readonly.");const result=await client.callTool({name:review.tool,arguments:{}},{signal,timeout:CALL_TIMEOUT});if(result.isError)throw Error("Provider identity verification failed.");const accountId=identityValue(result.structuredContent,review.subjectPath),account=review.labelPath?identityValue(result.structuredContent,review.labelPath):accountId;signal.throwIfAborted();return{account,accountId}}finally{await client.close().catch(()=>{})}}async function optionalOAuthIdentity(token,review,signal,expected,oidc){if(!review){if(expected!==void 0)throw Error("The selected native account requires its identity contract.");return{account:`${spec.label} connection`}}let identity;try{identity=await verifyOAuthIdentity(token,review,signal,oidc)}catch(error){signal.throwIfAborted();if(review.kind==="wordpress-user-profile"||expected!==void 0||error instanceof Error&&["Provider key expiry was not verified.","Provider credential scope does not match the authorized grant."].includes(error.message))throw error;return{account:`${spec.label} connection`}}if(expected!==void 0&&identity.accountId!==expected){const stable=/^(linear|asana|clickup):v2:(.+)$/u.exec(identity.accountId);const prefix=stable&&stable[1]===spec.source?`${stable[1]}:v1:${stable[2]}:`:void 0;if(!prefix||!expected.startsWith(prefix)||!/^[a-f0-9]{64}$/u.test(expected.slice(prefix.length)))throw Error("Provider account does not match the existing verified identity.");identity={...identity,accountId:expected}}return identity}async function connectOAuth(url,auth,options){const declaredReview=auth.reviewed?structuredClone(auth.reviewed):void 0;const readwiseMcpWrite=options?.readwiseMcpWrite===true;if(readwiseMcpWrite){if(spec.source!=="readwise"||url!=="https://mcp2.readwise.io/mcp"||declaredReview?.issuer!=="https://readwise.io/o/"||declaredReview.registration?.kind!=="dcr")return blockedAuthorization("invalid_authorization_policy","Readwise write access requires the Readwise OAuth source.");declaredReview.scopes=["openid","read","write"]}if(auth.redirectHost!==void 0&&!["127.0.0.1","localhost"].includes(auth.redirectHost))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has invalid OAuth callback settings.`);if(declaredReview&&!validReview(declaredReview))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has invalid OAuth settings.`);if(declaredReview&&!sourceOAuthReviewMatches(declaredReview,url))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has an identity or registration adapter outside its reviewed source and origins.`);const caller=bound(options?.signal),deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("OAuth discovery deadline exceeded.")),DISCOVERY_TIMEOUT);const fetchFn=oauthFetch(signal);try{const prior=await vault.connection(custodySource);signal.throwIfAborted();if(!("ok"in prior)&&!nativeAccountChoice(options))return prior;const server=await wait(discoverOAuthServerInfo(url,{fetchFn}),signal);const metadata=server.authorizationServerMetadata;if(!metadata)return fail("unavailable",`${spec.label} did not publish OAuth metadata.`);if(!declaredReview&&metadata.token_endpoint_auth_methods_supported&&!metadata.token_endpoint_auth_methods_supported.includes("none"))return blockedAuthorization("authorization_client_configuration_required",`${spec.label} requires a supported OAuth client configuration before sign-in can start.`);const review=declaredReview??discoveredOAuthReview(url,server);const chooseNative=nativeAccountChoice(options)&&!!review.identity;if(!("ok"in prior)&&!chooseNative)return prior;const previous="ok"in prior?prior.ok:null;const expectedAccountId=chooseNative?void 0:previous?.accountId;const choice=chooseNative?await captureAccountChoice(signal):void 0;if(choice&&!("ok"in choice))return choice;const registration=review.registration??{kind:"dcr"};const confidentialMethod=registration.kind==="pre-registered"||registration.kind==="dcr"?registration.tokenEndpointAuthMethod:void 0;const calendlyDcr=registration.kind==="dcr"&®istration.httpsBroker==="calendly"&&spec.source==="calendly"&&review.issuer==="https://calendly.com/"&&url==="https://mcp.calendly.com";if(registration.kind==="dcr"&®istration.httpsBroker&&!calendlyDcr)return blockedAuthorization("authorization_policy_mismatch",`${spec.label} has an invalid HTTPS broker configuration.`);if(review.redirectUriPolicy==="https-only"&®istration.kind!=="redirect-broker"&&!calendlyDcr)return blockedAuthorization("authorization_https_redirect_required",`${spec.label} requires a registered HTTPS callback; configure its provider client.`);if(expectedAccountId!==void 0&&!review.identity)return blockedAuthorization("authorization_identity_contract_required",`${spec.label} already has a selected native account; retain its identity contract when reconnecting that account.`);const resourceUrl=resourceUrlFromServerUrl(url);if(!matchesOAuthReview(url,review,server))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} discovery does not match its reviewed authorization policy.`);const supportedGrants=metadata.grant_types_supported??["authorization_code"];if(!supportedGrants.includes("authorization_code"))return fail("failed_precondition",`${spec.label} does not support authorization-code login.`);const grantTypes=["authorization_code",...supportedGrants.includes("refresh_token")?["refresh_token"]:[]];const scope=review.scopes.join(" ");if(registration.kind==="cimd"&&metadata.client_id_metadata_document_supported!==true)return blockedAuthorization("authorization_registration_unavailable",`${spec.label} did not advertise Client ID Metadata Document support.`);if(registration.kind==="dcr"&&!metadata.registration_endpoint)return blockedAuthorization("authorization_registration_unavailable",`${spec.label} has no compatible dynamic registration endpoint.`);const resource=httpsUrl(server.resourceMetadata?.resource??resourceUrl.href).href;const previousAuthority=chooseNative?void 0:previous?.authority;if(previousAuthority&&!registeredSessionMatches(previousAuthority))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} already has a different selected OAuth client or resource.`);if(previousAuthority&&!isMcpSessionAuthority(previousAuthority))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} selected a different kind of session; configure that connection before authorizing again.`);if(previousAuthority&&!matchesSessionAuthority(previousAuthority,url,server,previousAuthority.clientId))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} changed its original OAuth destination; configure that connection before authorizing again.`);let savedClient;let replacementSnapshot;if(registration.kind==="dcr"&&(previousAuthority||confidentialMethod&&previous&&!chooseNative)){const unsupported=()=>blockedAuthorization("authorization_client_registration_required",`${spec.label} cannot reuse its existing client without its original registered callback. The current connection is preserved; open zortex help to inspect it.`);if(confidentialMethod&&reviewedDcrConfidentialSource(url,review)!==spec.source||!previousAuthority||!vault.bindingCustody)return unsupported();const selected=await wait(vault.bindingCustody.resolve({kind:"selected-source",source:spec.source}),signal);if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return unsupported();const captured=await wait(vault.bindingCustody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:resource}),signal);if(!("ok"in captured))return captured;const allowed=authorizedCredential(captured.ok);if(!("ok"in allowed))return allowed;const credential=allowed.ok,authority=captured.ok.binding.authority,redirectUri=credential.registeredRedirectUri;const callback=typeof redirectUri==="string"?/^http:\/\/127\.0\.0\.1:([1-9]\d{0,4})\/callback$/u.exec(redirectUri):null;if(captured.ok.binding.id!==selected.ok.binding.id||captured.ok.binding.revision!==selected.ok.binding.revision||!isMcpSessionAuthority(authority)||authority.id!==previousAuthority.id||!matchesSessionAuthority(authority,url,server,credential.clientId)||credential.clientId!==previousAuthority.clientId||typeof credential.clientId!=="string"||!credential.clientId||credential.clientId.length>2048||/[\u0000-\u0020\u007f-\u009f]/u.test(credential.clientId)||(confidentialMethod?credential.clientAuthentication?.method!==confidentialMethod:credential.clientAuthentication!==void 0)||!(declaredReview?acceptsSavedMcpScopes(spec,credential.scopes):credential.scopes.every(scope2=>review.scopes.includes(scope2))))return unsupported();const migrateMissingCallback=!confidentialMethod&&redirectUri===void 0&&typeof expectedAccountId==="string"&&!!expectedAccountId&&!!review.identity&&captured.ok.binding.identity.subject===expectedAccountId;if(!callback||Number(callback[1])>65535){if(!migrateMissingCallback)return unsupported()}else savedClient={snapshot:captured.ok,credential:structuredClone(credential),redirectUri,port:Number(callback[1])};replacementSnapshot=captured.ok}const authorization={issuer:review.issuer,authorizationEndpoint:metadata.authorization_endpoint,resource,scopes:[...review.scopes],allowedOrigins:[...review.allowedOrigins],...authorizationBudget};let clientId=registration.kind==="dcr"?previousAuthority?.clientId??"":registration.clientId;let registeredRedirectUri=savedClient?.redirectUri;let brokerConfig;if(registration.kind==="broker"||registration.kind==="redirect-broker"){brokerConfig=await brokerCall(registration.brokerBase,`/${registration.brokerPath}/config`,void 0,signal);const redirectBroker=registration.kind==="redirect-broker",authorizationEndpoint=`${registration.brokerBase}/${registration.brokerPath}/authorize`;if(brokerConfig.clientId!==registration.clientId||brokerConfig.resource!==resource||redirectBroker&&(brokerConfig.authorizationEndpoint!==authorizationEndpoint||brokerConfig.redirectUri!==`${registration.brokerBase}/${registration.brokerPath}/callback`)||!redirectBroker&&brokerConfig.redirectUri!==`http://127.0.0.1:${auth.loopbackPort}/callback`)throw Error("Authorization broker configuration does not match the reviewed client.")}if(calendlyDcr){brokerConfig=await brokerCall("https://zortex-calendly-auth.pages.dev","/calendly/dcr/config",void 0,signal);if(brokerConfig.resource!==resource||brokerConfig.authorizationEndpoint!=="https://zortex-calendly-auth.pages.dev/calendly/dcr/authorize"||brokerConfig.redirectUri!=="https://zortex-calendly-auth.pages.dev/calendly/dcr/callback")throw Error("Calendly authorization broker configuration does not match the reviewed client.")}const clientSettings=registration.kind==="dcr"&&confidentialMethod?{authorization,async resolveClient(redirectUri,registrationSignal){try{if(savedClient){registrationSignal.throwIfAborted();if(redirectUri!==savedClient.redirectUri||!validClientAuthentication(savedClient.credential.clientAuthentication))throw Error("The registered client callback or secret changed.");const unchanged=await checkGrant({grant:{},account:savedClient.snapshot.binding.account,snapshot:savedClient.snapshot},registrationSignal);if(!("ok"in unchanged))throw Error("The selected client changed before authorization.");clientId=savedClient.credential.clientId;return{clientId,clientAuthentication:structuredClone(savedClient.credential.clientAuthentication)}}const registered=await registerClient(server.authorizationServerUrl,{metadata,fetchFn:oauthFetch(registrationSignal),...scope?{scope}:{},clientMetadata:resolveClientMetadata({redirectUrl:redirectUri,clientMetadata:{client_name:"Zortex",redirect_uris:[redirectUri],grant_types:grantTypes,response_types:["code"],token_endpoint_auth_method:confidentialMethod}})});registrationSignal.throwIfAborted();const dynamic=registered;const method=dynamic.token_endpoint_auth_method??(spec.source==="supabase"?"client_secret_basic":void 0),expiry=dynamic.client_secret_expires_at;if(method!==confidentialMethod||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri||expiry!==void 0&&(!Number.isSafeInteger(expiry)||expiry<0||expiry>864e10))throw Error("Provider did not confirm the reviewed client, callback and secret expiry.");const clientAuthentication={method:confidentialMethod,secret:dynamic.client_secret,...expiry?{expiresAt:expiry*1e3}:{}};if(!validClientAuthentication(clientAuthentication))throw Error("Provider did not return valid client authentication.");clientId=registered.client_id;return{clientId,clientAuthentication}}catch{registrationSignal.throwIfAborted();throw Error("Provider did not confirm the reviewed confidential client, callback and valid secret.")}finally{clearTimeout(timer)}}}:registration.kind==="dcr"?{authorization:{...authorization,...calendlyDcr?{authorizationEndpoint:brokerConfig.authorizationEndpoint}:{}},...calendlyDcr?{async exchangeCode(input,exchangeSignal){if(input.clientId!==clientId||!/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}\/callback$/u.test(input.redirectUri)||input.tokenUrl!==metadata.token_endpoint||input.tokenParams.resource!==resource)throw Error("Calendly authorization broker exchange does not match the reviewed request.");return brokerCall("https://zortex-calendly-auth.pages.dev","/calendly/dcr/exchange",{code:input.code,redirectUri:input.redirectUri,verifier:input.verifier},exchangeSignal)}}:{},async resolveClientId(redirectUri,registrationSignal){try{if(savedClient){registrationSignal.throwIfAborted();if(redirectUri!==savedClient.redirectUri)throw Error("The registered client callback changed.");const unchanged=await checkGrant({grant:{},account:savedClient.snapshot.binding.account,snapshot:savedClient.snapshot},registrationSignal);if(!("ok"in unchanged))throw Error("The selected client changed before authorization.");clientId=savedClient.credential.clientId;return clientId}if(replacementSnapshot){const unchanged=await checkGrant({grant:{},account:replacementSnapshot.binding.account,snapshot:replacementSnapshot},registrationSignal);if(!("ok"in unchanged))throw Error("The selected client changed before authorization.")}const providerRedirect=calendlyDcr?String(brokerConfig.redirectUri):redirectUri;if(calendlyDcr&&!/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}\/callback$/u.test(redirectUri))throw Error("Calendly requires a loopback callback.");const registered=await registerClient(server.authorizationServerUrl,{metadata,fetchFn:oauthFetch(registrationSignal),scope,clientMetadata:resolveClientMetadata({redirectUrl:providerRedirect,clientMetadata:{client_name:"Zortex",redirect_uris:[providerRedirect],grant_types:grantTypes,response_types:["code"],token_endpoint_auth_method:"none"}})});if(calendlyDcr&&(registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==providerRedirect))throw Error("Calendly did not confirm the HTTPS callback.");registrationSignal.throwIfAborted();const dynamic=registered;if(spec.source==="miro"&®istration.allowUnadvertisedPublicClient&&(dynamic.token_endpoint_auth_method!=="none"||dynamic.client_secret!==void 0||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri))throw Error("Miro did not confirm the requested public client and callback.");if(spec.source==="wordpress"&&dynamic.client_secret!==void 0&&(dynamic.token_endpoint_auth_method!=="none"||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri))throw Error("WordPress.com did not confirm the requested public client and callback.");if(spec.source==="pipedrive"&®istration.allowUnadvertisedPublicClient&&(dynamic.token_endpoint_auth_method!=="none"||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri))throw Error("Pipedrive did not confirm the requested public client and callback.");if(dynamic.token_endpoint_auth_method&&dynamic.token_endpoint_auth_method!=="none"||dynamic.client_secret&&!registration.discardReturnedSecretForPublicClient)throw Error("Unsupported confidential client registration.");if(dynamic.client_secret&&dynamic.token_endpoint_auth_method!=="none")throw Error("Unsupported confidential client registration.");clientId=registered.client_id;registeredRedirectUri=redirectUri;return clientId}finally{clearTimeout(timer)}}}:{clientId,...confidentialMethod?{clientAuthentication:{method:confidentialMethod}}:{},authorization:{...authorization,...registration.kind==="redirect-broker"?{authorizationEndpoint:brokerConfig.authorizationEndpoint}:{},clientId},...registration.kind==="broker"||registration.kind==="redirect-broker"?{async exchangeCode(input,exchangeSignal){const expectedRedirect=registration.kind==="redirect-broker"?`http://127.0.0.1:${auth.loopbackPort}/callback`:brokerConfig.redirectUri;if(input.clientId!==registration.clientId||input.redirectUri!==expectedRedirect||input.tokenUrl!==metadata.token_endpoint||input.tokenParams.resource!==resource)throw Error("Authorization broker exchange does not match the reviewed request.");return brokerCall(registration.brokerBase,`/${registration.brokerPath}/exchange`,{code:input.code,redirectUri:input.redirectUri,verifier:input.verifier},exchangeSignal)}}:{}};if(registration.kind!=="dcr")clearTimeout(timer);signal.throwIfAborted();const dropbox=spec.source==="dropbox"&&reviewedDropboxPublicClient(url,review)&®istration.kind==="pre-registered"&®istration.clientId===clientId;const google=confidentialMethod&&["google-contacts","google-chat"].includes(spec.source)&&reviewedConfidentialSource(url,review)===spec.source&®istration.kind==="pre-registered"&®istration.clientId===clientId;const result=await enrollment.pkce(info,{...clientSettings,authorizeUrl:registration.kind==="redirect-broker"||calendlyDcr?brokerConfig.authorizationEndpoint:metadata.authorization_endpoint,tokenUrl:metadata.token_endpoint,scope,loopbackPort:savedClient?.port??(replacementSnapshot?0:auth.loopbackPort),redirectHost:replacementSnapshot?"127.0.0.1":auth.redirectHost??"127.0.0.1",authorizeParams:{resource,...dropbox?{token_access_type:"offline"}:{},...google?{access_type:"offline",prompt:"consent"}:{}},tokenParams:{resource},driver:"oauth",issuerResponseRequired:metadata.authorization_response_iss_parameter_supported===true},async(token,signal2)=>{if(replacementSnapshot){const unchanged=await checkGrant({grant:{},account:replacementSnapshot.binding.account,snapshot:replacementSnapshot},signal2);if(!("ok"in unchanged)||confidentialMethod&&!validClientAuthentication(savedClient.credential.clientAuthentication))throw Error("The selected client changed while authorization was pending.")}const accessToken=String(token.access_token??"");if(!accessToken)throw new Error(`${spec.label} returned no access token.`);const scopes=String(token.scope??scope).split(/\s+/u).filter(Boolean);if(spec.source==="monday"&&isReviewedMondayDefault(url,review)?!acceptsMondayDefaultGrant(scopes):new Set(scopes).size!==scopes.length||scopes.some(granted=>!review.scopes.includes(granted)))throw Error("Provider granted scopes outside the requested authorization.");if(readwiseMcpWrite&&!scopes.includes("write"))throw Error("Readwise did not grant the explicitly requested MCP permission.");if((spec.source==="readwise"||spec.source==="raindrop")&&!scopes.includes("read"))throw Error(spec.label+" did not grant read access.");if(spec.source==="cloudflare"&&!["user:read","account:read"].every(scope2=>scopes.includes(scope2)))throw Error("Cloudflare did not grant both reader permissions.");if(reviewedRegisteredPublicSource(url,review)==="salesforce"&&!scopes.includes("mcp_api"))throw Error("Provider did not grant its required MCP permission.");const currentKey=review.identity?.kind==="openrouter-current-key";if(currentKey&&token.expires_in!==void 0&&(typeof token.expires_in!=="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0))throw Error("Provider token expiry was not verified.");let expiresAt=reviewedRegisteredPublicSource(url,review)==="salesforce"?salesforceTokenExpiry(token,Date.now()):token.expires_in?Date.now()+Number(token.expires_in)*1e3:0;if(dropbox&&(typeof token.access_token!=="string"||typeof token.token_type!=="string"||token.token_type.toLowerCase()!=="bearer"||typeof token.refresh_token!=="string"||!token.refresh_token||!Number.isSafeInteger(token.expires_in)||token.expires_in<=0||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()))throw Error("Dropbox did not return a verified offline grant and expiry.");if(confidentialMethod&&(typeof token.access_token!=="string"||!token.access_token||typeof token.token_type!=="string"||token.token_type.toLowerCase()!=="bearer"||token.refresh_token!==void 0&&(typeof token.refresh_token!=="string"||!token.refresh_token)||token.expires_in!==void 0&&(typeof token.expires_in!=="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt!==0&&expiresAt<=Date.now()))throw Error("The provider did not return a verified confidential grant.");if(currentKey&&(!Number.isFinite(expiresAt)||expiresAt>864e13))throw Error("Provider token expiry was not verified.");const identity=await optionalOAuthIdentity(accessToken,review.identity,signal2,expectedAccountId,{...typeof token.id_token==="string"?{idToken:token.id_token}:{},clientId});if(currentKey){if(identity.expiresAt===void 0&&!expiresAt)throw Error("Provider key expiry was not verified.");if(identity.expiresAt&&(!expiresAt||identity.expiresAt<expiresAt))expiresAt=identity.expiresAt;if(!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt!==0&&expiresAt<=Date.now())throw Error("Provider key expiry was not verified.")}if(chooseNative&&!identity.accountId&&(previous?.accountId||choice&&"ok"in choice&&choice.ok.inventory.some(row=>row.binding.identity.subject)))throw Error("Choosing another account requires verified provider identity.");return{account:identity.account,...identity.accountId===void 0?{}:{accountId:identity.accountId},...choice&&"ok"in choice&&identity.accountId?accountChoiceProof(choice.ok,identity.accountId,resource):{},...replacementSnapshot?{expectedCredential:{bindingId:replacementSnapshot.binding.id,bindingRevision:replacementSnapshot.binding.revision,grantId:replacementSnapshot.grant.id,grantRevision:replacementSnapshot.grant.revision,resourceId:replacementSnapshot.resource.id,resourceRevision:replacementSnapshot.resource.revision}}:{},authority:{kind:"mcp-session",id:(identity.accountId?previousAuthority:previous?.authority)?.id??randomUUID(),issuer:review.issuer,resource,clientId,tokenEndpoint:metadata.token_endpoint},credential:{accessToken,...token.refresh_token?{refreshToken:String(token.refresh_token)}:{},expiresAt,clientId,scopes,...!confidentialMethod&®isteredRedirectUri?{registeredRedirectUri}:{}}}},{...options,...readwiseMcpWrite?{reauthorize:true}:{},signal});if(deadline.signal.aborted&&!caller.aborted)return blockedAuthorization("authorization_discovery_timeout",`${spec.label} OAuth discovery or registration exceeded its 30-second deadline.`);return result}catch(error){if(deadline.signal.aborted&&!caller.aborted)return blockedAuthorization("authorization_discovery_timeout",`${spec.label} OAuth discovery or registration exceeded its 30-second deadline.`);throw error}finally{clearTimeout(timer)}}async function connectDeviceOAuth(_url,auth,options){const review=structuredClone(auth.reviewed);if(!validReview(review))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has invalid reviewed OAuth settings.`);if(review.identity?.kind!==void 0)return blockedAuthorization("invalid_authorization_policy",`${spec.label} device authorization has an incompatible identity adapter.`);const identityReview=review.identity;const chooseNative=nativeAccountChoice(options)&&!!identityReview;const prior=await vault.connection(custodySource);if(!("ok"in prior)&&!chooseNative)return prior;const previous="ok"in prior?prior.ok:null;const expectedAccountId=chooseNative?void 0:previous?.accountId;const choice=chooseNative?await captureAccountChoice(bound(options?.signal)):void 0;if(choice&&!("ok"in choice))return choice;if(expectedAccountId!==void 0&&!identityReview)return blockedAuthorization("authorization_identity_contract_required",`${spec.label} already has a selected native account; retain its identity contract when reconnecting that account.`);const requested=[...review.scopes],scope=requested.join(" ");const browserRead=spec.source==="microsoft-todo"&&spec.readOnly===true&&options?.automatic===false&&options.manualPresentation==="return-url"&&auth.clientId==="2a0c47ae-6035-459e-a544-f8c2008a9d78"&&auth.tokenUrl==="https://login.microsoftonline.com/common/oauth2/v2.0/token"&&requested.length===6&&["openid","profile","email","Tasks.Read","User.Read","offline_access"].every(permission=>requested.includes(permission));const validate=async(token,signal)=>{const accessToken=String(token.access_token??"");if(!accessToken)throw Error(`${spec.label} returned no access token.`);const scopes=String(token.scope??"").split(/[,\s]+/u).filter(Boolean);if(!scopes.length||new Set(scopes).size!==scopes.length||scopes.some(granted=>!requested.includes(granted)))throw Error("Provider granted scopes outside the reviewed request.");if(spec.source==="microsoft-todo"&&!scopes.includes(requested.includes("Tasks.ReadWrite")?"Tasks.ReadWrite":"Tasks.Read"))throw Error("Microsoft did not grant the requested task permission.");const expiresAt=token.expires_in===void 0?0:Date.now()+Number(token.expires_in)*1e3;if(!Number.isFinite(expiresAt)||expiresAt<0||expiresAt>864e13)throw Error("Provider token expiry was invalid.");const identity=await optionalOAuthIdentity(accessToken,identityReview,signal,expectedAccountId);if(browserRead&&!identity.accountId)throw Error("Microsoft To Do profile could not be verified.");if(chooseNative&&!identity.accountId&&(previous?.accountId||choice&&"ok"in choice&&choice.ok.inventory.some(row=>row.binding.identity.subject)))throw Error("Choosing another account requires verified provider identity.");return{account:identity.account,...identity.accountId===void 0?{}:{accountId:identity.accountId},...choice&&"ok"in choice&&identity.accountId?accountChoiceProof(choice.ok,identity.accountId,_url):{},authority:{kind:"mcp-session",id:chooseNative&&identity.accountId?randomUUID():previous?.authority?.id??randomUUID(),issuer:review.issuer,resource:_url,clientId:auth.clientId,tokenEndpoint:auth.tokenUrl},credential:{accessToken,...token.refresh_token?{refreshToken:String(token.refresh_token)}:{},expiresAt,clientId:auth.clientId,scopes}}};if(browserRead)return enrollment.pkce(info,{clientId:auth.clientId,authorizeUrl:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?prompt=select_account",tokenUrl:auth.tokenUrl,scope,redirectPath:"/",provider:spec.source,driver:"microsoft"},validate,options);return enrollment.device(info,{clientId:auth.clientId,deviceCodeUrl:auth.deviceCodeUrl,tokenUrl:auth.tokenUrl,scope,allowedOrigins:[...review.allowedOrigins],provider:spec.source},validate,options)}const provider={info,spec:sourceSnapshot(spec),actions,async check(options){if(guardedReadiness()&&guardedReadsInFlight)return fail("unavailable",`${spec.label} read is in progress; retry the check.`);const previousReadiness=readiness;clearReadiness();const epoch=checkEpoch;if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);const signal=bound(options?.signal);try{if(spec.signedIn){const credential=await vault.credential(custodySource);if("ok"in credential&&isSignedInBrowserCredential(credential.ok)){const read=await provider.read({limit:1},{...options,signal});if(!("ok"in read))return read;return ok({source:spec.source,basis:"read",operation:{state:"succeeded",returned:read.ok.returned,...read.ok.evidence?{evidence:read.ok.evidence}:{}}})}}const current=await grant(signal);if(!("ok"in current))return current;if(current.ok.grant.public&&spec.auth.kind==="server-login")return fail("unauthenticated",spec.auth.login.instructions??`${spec.label} needs its upstream session before private Actions are available.`);const opened=await open(current.ok.grant,signal),authorized=await checkGrant(current.ok,signal,opened);if(!("ok"in authorized))return authorized;if(spec.liveRead){const read=await provider.read({limit:1},{...options,signal});if(!("ok"in read))return read;if(current.ok.legacyRevision){const revision=await vault.legacyRevision(custodySource);if(!("ok"in revision)||revision.ok!==current.ok.legacyRevision)return fail("failed_precondition",`${spec.label} connection changed during the read.`)}rememberReadiness(current.ok,opened,{state:"succeeded",returned:read.ok.returned},epoch,signal);return ok({source:spec.source,basis:"actions",actions:opened.tools.length,operation:{state:"succeeded",returned:read.ok.returned,...read.ok.evidence?{evidence:read.ok.evidence}:{}}})}if(guardedReadiness()&&(epoch!==checkEpoch||session?.client!==opened.client))return fail("unavailable",`${spec.label} check was superseded by a newer operation.`);const operation=(spec.source==="ticktick"||spec.source==="airtable"||spec.source==="gitlab"||spec.source==="monday"||spec.source==="linear"||spec.source==="jira"||spec.source==="confluence"||spec.source==="miro"||guardedReadiness())&&previousReadiness?.session===session&&previousReadiness.value.operation.state==="succeeded"&&JSON.stringify(previousReadiness.authority)===JSON.stringify(readinessAuthority(current.ok))&&(!selectedReadinessFence()||previousReadiness.selectionRevision===current.ok.selectionRevision)?previousReadiness.value.operation:{state:"not-run"};rememberReadiness(current.ok,opened,operation,epoch,signal);return ok({source:spec.source,basis:"actions",actions:opened.tools.length,operation})}catch(error){return failure(error,signal)}},async status(options){if(closed){clearReadiness();return fail("unavailable",`${spec.label} source is inactive.`)}const reason=spec.unavailable?.();if(reason){clearReadiness();return ok({...info,state:"unavailable",actions:true,message:reason})}const signal=bound(options?.signal);if(spec.auth.kind==="none"){const checked2=await currentReadiness(signal);return ok({...info,state:session?.published&&!session.stop.signal.aborted?"connected":"not-connected",actions:true,...checked2?{readiness:checked2}:{}})}if(spec.auth.kind==="custodied"){const current=await inspectCustodied(spec.source,spec.auth,vault);if(!("ok"in current)){clearReadiness();return current}const checked2=await currentReadiness(signal);return ok({...info,state:"connected",...checked2?{readiness:checked2}:{verification:"configuration-only"},account:current.ok.account,actions:true})}const state=await connectionState(vault,{...info,source:custodySource});if("ok"in state)state.ok.source=info.source;if(!("ok"in state)||state.ok.state!=="connected"){clearReadiness();return"ok"in state?ok({...state.ok,actions:true}):state}if("ok"in state&&state.ok.state==="connected"&&(spec.auth.kind==="mcp-oauth"||spec.auth.kind==="oauth-device"||spec.auth.kind==="zendesk-oauth"||spec.auth.kind==="server-login"||spec.source==="matrix"&&matrixUserId(state.ok.account??""))){try{const selected=await inspectSelectedAuthority(signal);if(!("ok"in selected)){clearReadiness();return selected}}catch(error){clearReadiness();return failure(error,signal)}}const checked=await currentReadiness(signal);return ok({...state.ok,actions:true,...checked?{readiness:checked}:{}})},supportsSavedReconnect:true,async connect(options){clearReadiness();options={...options,automatic:options?.automatic!==false};if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const enrollmentReason=spec.enrollmentUnavailable?.();if(enrollmentReason)return fail("unavailable",enrollmentReason);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);const auth=spec.auth,server=spec.server;if(options.readwiseMcpWrite&&(spec.source!=="readwise"||auth.kind!=="mcp-oauth"||options.savedAccessOnly))return blockedAuthorization("invalid_authorization_policy","Readwise MCP write access requires the Readwise OAuth source and a fresh provider authorization.");try{const signal=bound(options?.signal);signal.throwIfAborted();if(options.savedAccessOnly){if(!options.automatic||auth.kind==="none"||auth.kind==="server-login"||auth.kind==="fields"&&auth.login?.handoff?.automatic)return fail("failed_precondition","This source cannot reconnect using saved access.")}if(auth.kind==="server-login"&&auth.login.handoff)return await connectServerHandoff(auth.login,options);if(auth.kind==="custodied"){const current=await grant(signal);if(!("ok"in current))return current;const opened=await open(current.ok.grant,signal);const checked=await checkGrant(current.ok,signal);if(!("ok"in checked))return checked;if(opened.tools.length===0)return fail("failed_precondition",`${spec.label} exposed no tools admitted by its reviewed source policy.`);const job2={...completedJob(spec.source,randomUUID()),account:current.ok.account};jobs.set(job2.id,job2);return ok({...job2})}if(options?.automatic&&!options.reauthorize&&!options.selectAccount&&!options.readwiseMcpWrite&&(auth.kind==="mcp-oauth"||auth.kind==="oauth-device"||auth.kind==="zendesk-oauth"||auth.kind==="fields")){const connection=await vault.connection(custodySource);if(!("ok"in connection))return connection;if(auth.kind==="fields"&&connection.ok?.state==="disconnected")return blockedAuthorization("login_required",`Reconnect ${spec.label} through its connection page.`);if(connection.ok?.state==="connected"){const stored=auth.kind!=="fields"&&(connection.ok.accountId||connection.ok.authority)?ok(null):await vault.credential(custodySource);if("err"in stored&&stored.err.code!=="not_found")return stored;if("ok"in stored&&(stored.ok===null||stored.ok.accessToken&&!isSignedInBrowserCredential(stored.ok))){const current=await grant(signal);if(!("ok"in current))return current;if(!current.ok.grant.token&&!current.ok.grant.fields||current.ok.grant.public)return fail("failed_precondition",`${spec.label} has no MCP authorization grant; reconnect this source.`);await probe(current.ok.grant,signal,auth.kind==="fields"?auth.login:void 0,options.savedAccessOnly===true);signal.throwIfAborted();if(auth.kind==="fields"){const latest=await grant(signal);if(!("ok"in latest))return latest;if(latest.ok.account!==current.ok.account||JSON.stringify(latest.ok.grant.fields)!==JSON.stringify(current.ok.grant.fields))return fail("failed_precondition",`${spec.label} selected credential changed while reconnecting.`)}const authorized=await checkGrant(current.ok,signal);if(!("ok"in authorized))return authorized;const job2={...completedJob(spec.source,randomUUID()),account:current.ok.account};jobs.set(job2.id,job2);return ok({...job2})}}}if(options.savedAccessOnly)return blockedAuthorization("login_required",`Saved access is unavailable for ${spec.label}.`);if(auth.kind!=="none")await dropSession();if(options?.automatic&&spec.signedIn&&auth.kind!=="none"){firstRead=void 0;const signedIn=await connectSignedIn(options);if(signedIn)return signedIn}if(auth.kind==="none"){const opened=await open({},signal);signal.throwIfAborted();if(deps.rememberPublicConnection){if(!opened.tools.some(row=>row.tool==="lookup"&&row.effect==="read")){await dropSession();return fail("failed_precondition","The public lookup tool is unavailable.")}await deps.rememberPublicConnection()}return ok(completedJob(spec.source,"local"))}if(auth.kind==="zendesk-oauth")return await track(starting,connectZendeskOAuth(auth,options));if(auth.kind==="mcp-oauth"){if(server.transport!=="http")return fail("failed_precondition",`${spec.label}: MCP OAuth needs a remote server.`);return await track(starting,connectOAuth(server.url,auth,options))}if(auth.kind==="oauth-device"){return await track(starting,connectDeviceOAuth(server.transport==="http"?server.url:auth.tokenUrl,auth,options))}if(spec.source==="matrix"&&auth.kind==="fields"){const prior=await vault.connection(spec.source);if(!("ok"in prior))return prior;const previous=prior.ok;if(previous&&(previous.accountId&&matrixUserId(previous.accountId)||[matrixHomeserver,"https://matrix.org"].includes(previous.account))){const choice=await captureAccountChoice(signal);if(!("ok"in choice))return choice;const latest=await vault.connection(spec.source);if(!("ok"in latest))return latest;if(latest.ok?.account!==previous.account||latest.ok?.accountId!==previous.accountId)return fail("failed_precondition","The selected Matrix account changed. Start the connection again.");const login=await matrixLogin(transport,signal,previous.accountId);return enrollment.pkce(info,login.settings,async(token,verificationSignal)=>{const verified=await login.validate(token,verificationSignal);return{...verified,...accountChoiceProof(choice.ok,verified.accountId,matrixHomeserver),authority:{kind:"mcp-session",id:randomUUID(),issuer:matrixIssuer,resource:matrixHomeserver,clientId:verified.credential.clientId,tokenEndpoint:matrixTokenUrl}}},options)}}if(auth.kind==="fields")return await enrollment.form(info,auth.fields,async(fields,signal2)=>{await probe(fieldsGrant(fields),signal2,auth.login,options?.savedAccessOnly);return{account:auth.account(fields),credential:{accessToken:JSON.stringify(fields),expiresAt:0,clientId:"mcp-fields",scopes:[]},...custodySource==="figma--pat"?{custodySource:"figma--pat"}:{}}},options);const native=await probe({},signal,auth.login,options?.savedAccessOnly);signal.throwIfAborted();if(!native.identity&&!auth.login.ready)return fail("failed_precondition",`${spec.label} needs a noninteractive login status contract before its session can be saved.`);const identity=native.identity??{account:`${spec.label} session`},saved=await saveServerIdentity(identity,signal,options?.automatic);if(!("ok"in saved))return saved;const job={...completedJob(spec.source,randomUUID()),account:identity.account};jobs.set(job.id,job);return ok({...job})}catch(error){const signal=bound(options?.signal);if(error instanceof ServerLoginRequired&&!signal.aborted){const blocked=automaticError("login_required");return blockedAuthorization(blocked.code,error.message||`Sign in to ${spec.label} through its app, then retry this connection.`)}return failure(error,signal)}},job:id=>{const job=jobs.get(id);return job?ok({...job}):enrollment.job(id)},cancelJob(id){const job=jobs.get(id);if(job){if(loginOwner?.job.id===id&&!loginOwner.settled){if(job.state==="waiting-user")job.state="cancelled";delete job.automationActive;delete job.browserContinuation;delete job.instructions;delete job.authorizationUrl;delete job.authorizationOrigin;delete job.authorizationImage;delete job.devicePrompt;loginOwner.stop.abort();loginOwner.publish();retryLoginCleanup(loginOwner);return ok({id,cleanup:"pending"})}return ok({id,cleanup:"confirmed"})}const owned=enrollment.job?.(id);return owned&&"ok"in owned&&owned.ok.source!==spec.source?fail("not_found","Unknown connector connection job."):enrollment.cancelJob?enrollment.cancelJob(id):ok({id,cleanup:"confirmed"})},async read(request,options){const route=spec.signedIn;const fallback=()=>fail("failed_precondition",`${spec.label} is a level 1 connector: it acts through actions and stores nothing in the Vault.`);if(spec.liveRead){if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const invalid2=validateRead(request);if(invalid2)return invalid2;if(request.fileId!==void 0||request.since!==void 0||request.until!==void 0)return fail("invalid_argument",`${spec.label} metadata reads support limit and query only.`);const result=await invokeAction(`${spec.source}.${spec.liveRead.tool}`,{params:spec.liveRead.args??{}},options??{},true);if(!("ok"in result))return result;const value=result.ok.result;let records2;try{records2=spec.liveRead.records(spec.source,value.structured,value.text)}catch{return fail("unavailable",`${spec.label} did not return a valid live-read response.`)}if(!records2)return fail("unavailable",`${spec.label} did not return a valid live-read response.`);if(closed||options?.signal?.aborted)return fail(closed?"unavailable":"aborted",`${spec.label} live read did not complete.`);const query2=request.query?.toLowerCase(),reply=readResult(spec.source,records2.filter(row=>!query2||String(row.body??"").toLowerCase().includes(query2)).slice(0,request.limit??1));if("ok"in reply)reply.ok.evidence={origin:"live",observedAt:new Date().toISOString(),stage:"read-page"};return reply}if(!route)return fallback();if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const invalid=validateRead(request);if(invalid)return invalid;const stored=await vault.credential(custodySource);if(!("ok"in stored)||!isSignedInBrowserCredential(stored.ok))return fallback();const identity=await vault.connection(custodySource);if(!("ok"in identity))return identity;const signal=bound(options?.signal),pending2=firstRead;firstRead=void 0;let records;if(pending2&&pending2.expiresAt>Date.now())records=pending2.records;else{const outcome=await signedInPage(route.feedUrl??route.identityUrl,signal);if(signal.aborted)return fail("aborted",`${spec.label} read cancelled.`);if(!outcome)return fail("unavailable",`The ${spec.label} browser session could not be read on this computer.`);if(/^browser_session_unavailable(?:\s|$)/.test(outcome.reason??""))return{err:{...fail("unavailable",automaticError("browser_session_unavailable").message).err,...browserFailureCause(outcome.reason)}};if(outcome.state==="login_required")return fail("unauthenticated",`Sign in to ${spec.label} in Chrome, then read again.`);if(outcome.state!=="completed")return fail("unavailable",`${spec.label} could not be read live.`);if(!route.feedUrl&&route.identity(outcome)?.accountId!==identity.ok?.accountId)return fail("unauthenticated",`The signed-in ${spec.label} account changed. Connect again before reading.`);records=route.records(spec.source,outcome)}const query=request.query?.toLowerCase();return closed?fail("unavailable",`${spec.label} source was disabled.`):readResult(spec.source,records.filter(row=>!query||String(row.body).toLowerCase().includes(query)).slice(0,request.limit??1))},close(){if(!closing){clearReadiness();closed=true;stop.abort();firstRead=void 0;enrollment.cancelSource?.(spec.source);const dropped=dropSession();closing=Promise.allSettled([dropped,...pending,...starting,...cleanup]).then(async()=>{if(loginOwner){retryLoginCleanup(loginOwner);await loginOwner.cleaning}})}return closing}};return provider}
|
|
1
|
+
import{matrixHomeserver,matrixIssuer,matrixLogin,matrixTokenUrl,matrixUserId,verifyMatrixDevice}from"./matrix-login.js";import{createPinnedLoopbackHttp,continueAuthorizationWithBrowser}from"@zortexhq/plugin-connector-core/api";import{exchangeZendeskCode,refreshZendeskToken,zendeskOAuthEndpoints}from"./zendesk-oauth.js";import{StreamableHTTPClientTransport,checkResourceAllowed,discoverOAuthServerInfo,discoverAuthorizationServerMetadata,refreshAuthorization,registerClient,resolveClientMetadata,resourceUrlFromServerUrl}from"@modelcontextprotocol/client";import{StdioClientTransport}from"@modelcontextprotocol/client/stdio";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{completedJob,connectionState}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId,isMcpSessionAuthority,isServerSessionAuthority}from"@zortexhq/plugin-vault-sqlite/api";import{browserConnectionDiagnostic,browserFailureCause}from"@zortexhq/plugin-oauth-browser-driver/api";import{SIGNED_IN_BROWSER_CREDENTIAL,automaticError,isSignedInBrowserCredential,readSignedInPage}from"@zortexhq/plugin-auto-connect/api";import{createHash,randomUUID}from"node:crypto";import{createLocalJWKSet,decodeJwt,jwtVerify}from"jose";import{AsyncLocalStorage}from"node:async_hooks";import{readResult,validateRead,authorizationImage}from"@zortexhq/plugin-connector-core/api";import{acceptsSavedMcpScopes}from"./saved-mcp-scopes.js";import{acceptsMondayDefaultGrant,isReviewedMondayDefault}from"./monday-oauth-scopes.js";import{captureCustodied,checkCustodied,inspectCustodied,reviewedToolSchemaHash,validateCustodiedAuth}from"./custodied.js";import{operationalReason,startOperationalStep}from"@zortexhq/plugin-telemetry/api";import{startOwnedProcessResourceSampler}from"@zortexhq/plugin-process-local/api/resources";import{createOperationalClient}from"./operational-client.js";const PROXY_VARS=["HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY","https_proxy","http_proxy","all_proxy","no_proxy"];export function proxyEnv(env=process.env){const out={};for(const key of PROXY_VARS)if(env[key])out[key]=env[key];if(Object.keys(out).some(k=>!/no_proxy/i.test(k)))out.NODE_USE_ENV_PROXY="1";if(env.NODE_EXTRA_CA_CERTS)out.NODE_EXTRA_CA_CERTS=env.NODE_EXTRA_CA_CERTS;return out}let LOGIN_POLL=5e3;export function setLoginPoll(ms){LOGIN_POLL=ms}const MAX_PENDING=32,MAX_PARAMS=65536,MAX_RESULT=1048576,CALL_TIMEOUT=12e4,LOGIN_TIMEOUT=6e5;const SOURCE=/^[a-z][a-z0-9-]{1,39}$/,TOOL=/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;const DISCOVERY_TIMEOUT=3e4;const OPENROUTER_KEY_URL="https://openrouter.ai/api/v1/key",GITLAB_TOKEN_INFO_URL="https://gitlab.com/oauth/token/info";const ATLASSIAN_ME_URL="https://api.atlassian.com/me",ATLASSIAN_RESOURCES_URL="https://api.atlassian.com/oauth/token/accessible-resources",IDENTITY_TIMEOUT=3e4,MAX_IDENTITY_BYTES=65536;const LINEAR_JWKS_URL="https://mcp.linear.app/.well-known/jwks.json";const CLICKUP_USER_URL="https://api.clickup.com/api/v2/user";const ZOOM_USERINFO_URL="https://zoom.us/v1/userinfo";class ServerLoginRequired extends Error{}export function resolveAuthorizationBudget(input){if(input===void 0)return{maxSteps:8,maxModelCalls:0};if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some(key=>!["maxSteps","maxModelCalls"].includes(key))||!Number.isInteger(input.maxSteps)||input.maxSteps<1||input.maxSteps>12||!Number.isInteger(input.maxModelCalls)||input.maxModelCalls<0||input.maxModelCalls>24)throw Error("Invalid level 1 authorization budget.");return{maxSteps:input.maxSteps,maxModelCalls:input.maxModelCalls}}function httpsUrl(value){const url=new URL(value);if(value!==value.trim()||url.protocol!=="https:"||url.username||url.password||url.search||url.hash||url.hostname.includes("*"))throw Error("Invalid reviewed OAuth URL.");return url}function validIdentityPath(path){return Array.isArray(path)&&path.length>0&&path.length<=8&&path.every(key=>typeof key==="string"&&/^[a-zA-Z0-9_-]{1,80}$/.test(key)&&!["__proto__","prototype","constructor"].includes(key))}function validIdentityReview(identity){if(!identity||typeof identity!=="object"||Array.isArray(identity))return false;if(identity.kind==="openrouter-current-key"||identity.kind==="gitlab-token-info"||identity.kind==="atlassian-current-user-sites"||identity.kind==="linear-openid-teams"||identity.kind==="asana-user-workspaces"||identity.kind==="zoom-openid-userinfo"||identity.kind==="clickup-current-user-workspaces"||identity.kind==="ticktick-inbox-self"||identity.kind==="notion-bot-owner"||identity.kind==="sentry-catalog-whoami"||identity.kind==="wordpress-user-profile")return Object.keys(identity).every(key=>key==="kind");return identity.kind===void 0&&Object.keys(identity).every(key=>["tool","subjectPath","labelPath"].includes(key))&&typeof identity.tool==="string"&&/^[a-zA-Z0-9_.-]{1,200}$/.test(identity.tool)&&validIdentityPath(identity.subjectPath)&&(identity.labelPath===void 0||validIdentityPath(identity.labelPath))}function validReview(review){try{return!!review&&typeof review==="object"&&!Array.isArray(review)&&Object.keys(review).every(key=>["issuer","scopes","allowedOrigins","identity","redirectUriPolicy","registration"].includes(key))&&Array.isArray(review.scopes)&&review.scopes.length<=32&&new Set(review.scopes).size===review.scopes.length&&review.scopes.every(scope=>typeof scope==="string"&&!!scope&&scope.length<=1024&&!/\s/u.test(scope))&&Array.isArray(review.allowedOrigins)&&review.allowedOrigins.length>0&&review.allowedOrigins.length<=8&&review.allowedOrigins.every(origin=>httpsUrl(origin).origin===origin)&&review.allowedOrigins.includes(httpsUrl(review.issuer).origin)&&(review.redirectUriPolicy===void 0||review.redirectUriPolicy==="https-only")&&(review.identity===void 0||validIdentityReview(review.identity))&&(review.registration===void 0||review.registration.kind==="dcr"&&Object.keys(review.registration).every(key=>["kind","httpsBroker","allowUnadvertisedPublicClient","discardReturnedSecretForPublicClient","tokenEndpointAuthMethod"].includes(key))&&(review.registration.httpsBroker===void 0||review.registration.httpsBroker==="calendly")&&(review.registration.allowUnadvertisedPublicClient===void 0||review.registration.allowUnadvertisedPublicClient===true)&&(review.registration.discardReturnedSecretForPublicClient===void 0||review.registration.discardReturnedSecretForPublicClient===true)&&(review.registration.tokenEndpointAuthMethod===void 0||["client_secret_basic","client_secret_post"].includes(review.registration.tokenEndpointAuthMethod)&&review.registration.allowUnadvertisedPublicClient===void 0&&review.registration.discardReturnedSecretForPublicClient===void 0)||(review.registration.kind==="pre-registered"||review.registration.kind==="cimd")&&Object.keys(review.registration).every(key=>(review.registration.kind==="pre-registered"?["kind","clientId","allowUnadvertisedPublicClient","tokenEndpointAuthMethod"]:["kind","clientId"]).includes(key))&&typeof review.registration.clientId==="string"&&review.registration.clientId.length<=2048&&!!review.registration.clientId&&(review.registration.kind!=="pre-registered"||review.registration.allowUnadvertisedPublicClient===void 0||review.registration.allowUnadvertisedPublicClient===true)&&(review.registration.kind!=="pre-registered"||review.registration.tokenEndpointAuthMethod===void 0||["client_secret_basic","client_secret_post"].includes(review.registration.tokenEndpointAuthMethod)&&review.registration.allowUnadvertisedPublicClient===void 0)&&(review.registration.kind!=="cimd"||httpsUrl(review.registration.clientId).pathname!=="/")||(review.registration.kind==="broker"||review.registration.kind==="redirect-broker")&&Object.keys(review.registration).every(key=>["kind","clientId","brokerBase","brokerPath"].includes(key))&&typeof review.registration.clientId==="string"&&/^[A-Za-z0-9_-]{1,2048}$/.test(review.registration.clientId)&&typeof review.registration.brokerPath==="string"&&/^[a-z][a-z0-9-]{1,39}$/.test(review.registration.brokerPath)&&httpsUrl(review.registration.brokerBase).href===review.registration.brokerBase+"/")}catch{return false}}function sameScopes(left,right){return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&new Set(left).size===left.length&&new Set(right).size===right.length&&left.every(scope=>typeof scope==="string"&&right.includes(scope))}function validClientAuthentication(value){return!!value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).every(key=>["method","secret","expiresAt"].includes(key))&&["client_secret_basic","client_secret_post"].includes(value.method)&&typeof value.secret==="string"&&value.secret.length>0&&value.secret.length<=4096&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value.secret)&&(value.expiresAt===void 0||Number.isSafeInteger(value.expiresAt)&&value.expiresAt>Date.now()&&value.expiresAt<=864e13)}function reviewedDcrConfidentialSource(url,review){const registration=review.registration;if(registration?.kind!=="dcr"||registration.allowUnadvertisedPublicClient!==void 0||registration.discardReturnedSecretForPublicClient!==void 0||review.identity!==void 0||review.redirectUriPolicy!==void 0)return;if(url==="https://mcp.supabase.com/mcp"&&review.issuer==="https://api.supabase.com"&&sameScopes(review.allowedOrigins,["https://api.supabase.com","https://supabase.com"])&&sameScopes(review.scopes,[])&®istration.tokenEndpointAuthMethod==="client_secret_basic")return"supabase";if(url==="https://coda.io/apis/mcp"&&review.issuer==="https://coda.io"&&sameScopes(review.allowedOrigins,["https://coda.io"])&&sameScopes(review.scopes,["mcp:all"])&®istration.tokenEndpointAuthMethod==="client_secret_post")return"coda";if(isReviewedMondayDefault(url,review))return"monday"}const formComponent=value=>new URLSearchParams({v:value}).toString().slice(2);const confidentialBasic=(clientId,secret)=>"Basic "+Buffer.from(formComponent(clientId)+":"+formComponent(secret)).toString("base64");function protectsCredential(credential,onlyClient=false){const authentication=credential.clientAuthentication;const secrets=[...onlyClient?[]:[credential.accessToken,credential.refreshToken],authentication?.secret,...authentication?.method==="client_secret_basic"?[confidentialBasic(credential.clientId,authentication.secret).slice(6)]:[]];return encoded=>secrets.some(secret=>!!secret&&(encoded.includes(secret)||encoded.includes(JSON.stringify(secret).slice(1,-1))))}function reviewedConfidentialSource(url,review){if(review.registration?.kind!=="pre-registered"||!review.registration.tokenEndpointAuthMethod||review.registration.allowUnadvertisedPublicClient!==void 0||review.identity!==void 0||review.redirectUriPolicy!==void 0)return;if((url==="https://mcp.box.com/"||url==="https://mcp.box.com")&&review.issuer==="https://api.box.com"&&sameScopes(review.allowedOrigins,["https://account.box.com","https://api.box.com"])&&review.scopes.every(scope=>["root_readwrite","ai.readwrite","docgen.readwrite"].includes(scope)))return"box";if(url==="https://mcp.frontapp.com/mcp"&&review.issuer==="https://app.frontapp.com"&&sameScopes(review.allowedOrigins,[review.issuer])&&sameScopes(review.scopes,["feature:mcp"])&&review.registration.tokenEndpointAuthMethod==="client_secret_basic")return"front";if(url==="https://mcp.hubspot.com/"&&review.issuer==="https://mcp.hubspot.com"&&sameScopes(review.allowedOrigins,[review.issuer])&&review.scopes.length===0&&review.registration.tokenEndpointAuthMethod==="client_secret_post")return"hubspot";const prefix="https://www.googleapis.com/auth/";if(review.issuer!=="https://accounts.google.com"||!sameScopes(review.allowedOrigins,["https://accounts.google.com","https://oauth2.googleapis.com"]))return;if(url==="https://people.googleapis.com/mcp/v1"&&review.scopes.every(scope=>["contacts.readonly","directory.readonly","userinfo.profile"].some(name=>scope===prefix+name)))return"google-contacts";if(url==="https://chatmcp.googleapis.com/mcp/v1"&&review.scopes.every(scope=>["spaces","spaces.readonly","memberships","memberships.readonly","messages","messages.readonly","messages.create","users.readstate"].some(name=>scope===prefix+"chat."+name)))return"google-chat"}function reviewedDropboxPublicClient(url,review){const scopes=["account_info.read","file_requests.read","file_requests.write","files.content.read","files.content.write","files.metadata.read","files.metadata.write","sharing.read","sharing.write"];return url==="https://mcp.dropbox.com/mcp"&&review.issuer==="https://www.dropbox.com"&&sameScopes(review.allowedOrigins,["https://www.dropbox.com","https://api.dropboxapi.com"])&&review.scopes.every(scope=>scopes.includes(scope))&&review.registration?.kind==="pre-registered"&&review.registration.allowUnadvertisedPublicClient!==true&&review.registration.tokenEndpointAuthMethod===void 0&&review.identity===void 0&&review.redirectUriPolicy===void 0}function reviewedRegisteredPublicSource(url,review){if(review.registration?.kind!=="pre-registered"||review.registration.allowUnadvertisedPublicClient!==true||review.identity!==void 0||review.redirectUriPolicy!==void 0)return;const zoomScopes=["meeting:write:meeting","meeting:read:search","meeting:delete:meeting","meeting:update:in_meeting_controls","meeting:update:meeting","meeting:read:assets","cloud_recording:read:list_user_recordings","cloud_recording:read:content"];if(url==="https://mcp.zoom.us/mcp/meeting/streamable"&&review.issuer==="https://zoom.us"&&sameScopes(review.allowedOrigins,["https://zoom.us"])&&review.scopes.every(scope=>zoomScopes.includes(scope)))return"zoom";for(const environment of["production","sandbox"]){const issuer=environment==="sandbox"?"https://test.salesforce.com":"https://login.salesforce.com";if(url===`https://api.salesforce.com/platform/mcp/v1/${environment==="sandbox"?"sandbox/":""}platform/sobject-all`&&review.issuer===issuer&&sameScopes(review.allowedOrigins,[issuer])&&review.scopes.includes("mcp_api")&&review.scopes.every(scope=>["mcp_api","refresh_token"].includes(scope)))return"salesforce"}}function salesforceTokenExpiry(token,requestedAt){if(typeof token.access_token!=="string"||token.access_token.length>65536)throw Error("Salesforce token expiry was not verified.");const exp=decodeJwt(token.access_token).exp;if(!(typeof exp==="number"&&Number.isInteger(exp)||typeof exp==="string"&&/^[0-9]{1,13}$/u.test(exp)))throw Error("Salesforce token expiry was not verified.");let expiresAt=Number(exp)*1e3;if(token.expires_in!==void 0){if(typeof token.expires_in!=="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw Error("Salesforce token expiry was not verified.");expiresAt=Math.min(expiresAt,requestedAt+token.expires_in*1e3)}if(!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now())throw Error("Salesforce token expiry was not verified.");return expiresAt}function matchesOAuthReview(url,review,server,refresh=false,selectedMethod){try{const metadata=server.authorizationServerMetadata;const registeredPublic=reviewedRegisteredPublicSource(url,review);const dropbox=reviewedDropboxPublicClient(url,review);const confidential=reviewedConfidentialSource(url,review),dynamicConfidential=reviewedDcrConfidentialSource(url,review),method=selectedMethod??(review.registration?.kind==="pre-registered"||review.registration?.kind==="dcr"?review.registration.tokenEndpointAuthMethod:void 0);const authorityMatches=server.authorizationServerUrl===review.issuer||review.identity?.kind==="ticktick-inbox-self"&&review.issuer==="https://ticktick.com"&&server.authorizationServerUrl==="https://ticktick.com/"||!!confidential&&server.authorizationServerUrl===review.issuer+"/";const cloudflareIncrementalScopes=url==="https://mcp.cloudflare.com/mcp"&&review.issuer==="https://mcp.cloudflare.com"&&sameScopes(server.resourceMetadata?.scopes_supported??[],["user:read","account:read"]);return!!metadata&&authorityMatches&&metadata.issuer===review.issuer&&(!dynamicConfidential||server.resourceMetadata?.resource===url&&(dynamicConfidential==="monday"?metadata.authorization_endpoint==="https://auth.monday.com/oauth2/authorize"&&metadata.token_endpoint==="https://auth.monday.com/oauth_ms/oauth/token"&&metadata.registration_endpoint==="https://auth.monday.com/oauth_ms/oauth/register":metadata.authorization_endpoint===review.issuer+(dynamicConfidential==="supabase"?"/v1/oauth/authorize":"/v4/api/oauth2/authorize")&&metadata.token_endpoint===review.issuer+(dynamicConfidential==="supabase"?"/v1/oauth/token":"/v4/api/oauth2/token")&&metadata.registration_endpoint===review.issuer+(dynamicConfidential==="supabase"?"/platform/oauth/apps/register":"/v4/api/oauth2/register")))&&(!(url==="https://mcp.miro.com/"&&review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient)||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint==="https://mcp.miro.com/authorize"&&metadata.token_endpoint==="https://mcp.miro.com/token"&&metadata.registration_endpoint==="https://mcp.miro.com/register")&&(!(url==="https://public-api.wordpress.com/wpcom/v2/mcp/v1"&&review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient)||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint===review.issuer+"/oauth2-1/authorize"&&metadata.token_endpoint===review.issuer+"/oauth2-1/token"&&metadata.registration_endpoint===review.issuer+"/oauth2-1/register")&&(!(url==="https://mcp.pipedrive.ai/mcp"&&review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient)||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint==="https://oauth.pipedrive.com/oauth/authorize"&&metadata.token_endpoint==="https://oauth.pipedrive.com/oauth/token"&&metadata.registration_endpoint==="https://oauth.pipedrive.com/oauth/register")&&(!confidential||server.resourceMetadata?.resource===(confidential==="box"?"https://mcp.box.com/":confidential==="front"?"https://mcp.frontapp.com":confidential==="hubspot"?"https://mcp.hubspot.com":url)&&metadata.authorization_endpoint===(confidential==="box"?"https://account.box.com/api/oauth2/authorize":confidential==="front"?"https://app.frontapp.com/oauth/authorize":confidential==="hubspot"?"https://mcp.hubspot.com/oauth/authorize/user":"https://accounts.google.com/o/oauth2/v2/auth")&&metadata.token_endpoint===(confidential==="box"?"https://api.box.com/oauth2/token":confidential==="front"?"https://app.frontapp.com/oauth/token":confidential==="hubspot"?"https://mcp.hubspot.com/oauth/v3/token":"https://oauth2.googleapis.com/token"))&&(!dropbox||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint==="https://www.dropbox.com/oauth2/authorize"&&metadata.token_endpoint==="https://api.dropboxapi.com/oauth2/token"&&metadata.token_endpoint_auth_methods_supported?.includes("none")===true&&metadata.code_challenge_methods_supported?.includes("S256")===true&&metadata.grant_types_supported?.includes("refresh_token")===true)&&(!registeredPublic||server.resourceMetadata?.resource===url&&metadata.authorization_endpoint===review.issuer+(registeredPublic==="salesforce"?"/services/oauth2/authorize":"/oauth/authorize")&&metadata.token_endpoint===review.issuer+(registeredPublic==="salesforce"?"/services/oauth2/token":"/oauth/token"))&&[metadata.authorization_endpoint,metadata.token_endpoint,...metadata.registration_endpoint?[metadata.registration_endpoint]:[]].every(endpoint=>review.allowedOrigins.includes(httpsUrl(endpoint).origin))&&(!server.resourceMetadata||checkResourceAllowed({requestedResource:resourceUrlFromServerUrl(url),configuredResource:server.resourceMetadata.resource}))&&(refresh||!server.resourceMetadata?.scopes_supported||review.scopes.every(scope=>server.resourceMetadata.scopes_supported.includes(scope)||["openid","email","profile","offline_access"].includes(scope)||cloudflareIncrementalScopes&&metadata.scopes_supported?.includes(scope)))&&(refresh||!metadata.scopes_supported||review.scopes.every(scope=>metadata.scopes_supported.includes(scope)||server.resourceMetadata?.scopes_supported?.includes(scope)||scope==="offline_access"))&&metadata.response_types_supported.includes("code")&&(!metadata.code_challenge_methods_supported||metadata.code_challenge_methods_supported.includes("S256"))&&(method?(metadata.token_endpoint_auth_methods_supported??["client_secret_basic"]).includes(method):!metadata.token_endpoint_auth_methods_supported||metadata.token_endpoint_auth_methods_supported.includes("none")||review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient===true||review.registration?.kind==="broker"||!!registeredPublic)}catch{return false}}function discoveredOAuthReview(url,server){const metadata=server.authorizationServerMetadata;if(!metadata)throw Error("The MCP server did not publish OAuth metadata.");const issuer=metadata.issuer,allowedOrigins=[...new Set([issuer,metadata.authorization_endpoint,metadata.token_endpoint,...metadata.registration_endpoint?[metadata.registration_endpoint]:[]].map(value=>httpsUrl(value).origin))];const review={issuer,allowedOrigins,scopes:[...server.resourceMetadata?.scopes_supported??[]]};if(!validReview(review)||!matchesOAuthReview(url,review,server))throw Error("The MCP server published incompatible OAuth metadata.");return review}function matchesSessionAuthority(authority,url,server,clientId){try{return isMcpSessionAuthority(authority)&&authority.clientId===clientId&&server.authorizationServerMetadata?.issuer===authority.issuer&&server.authorizationServerMetadata.token_endpoint===authority.tokenEndpoint&&new URL(server.resourceMetadata?.resource??resourceUrlFromServerUrl(url).href).href===new URL(authority.resource).href&&checkResourceAllowed({requestedResource:resourceUrlFromServerUrl(url),configuredResource:authority.resource})}catch{return false}}function identityValue(value,path){for(const key of path){if(!value||typeof value!=="object"||Array.isArray(value)||!Object.hasOwn(value,key))throw Error("Provider identity was not uniquely verified.");value=value[key]}if(typeof value==="number"&&Number.isSafeInteger(value)&&value>=0)return String(value);if(typeof value!=="string"||!value||value!==value.trim()||value.length>512)throw Error("Provider identity was not uniquely verified.");return value}function loginSnapshot(login){return{...login,...login.args?{args:structuredClone(login.args)}:{},...login.ready?{ready:{...login.ready,...login.ready.args?{args:structuredClone(login.ready.args)}:{}}}:{},...login.cleanup?{cleanup:{...login.cleanup,...login.cleanup.args?{args:structuredClone(login.cleanup.args)}:{}}}:{},...login.handoff?{handoff:{...login.handoff}}:{},...login.identity?{identity:structuredClone(login.identity)}:{}}}function validateFieldsAccountBinding(auth){if(!("accountBinding"in auth))return;const descriptor=Object.getOwnPropertyDescriptor(auth,"accountBinding");if(!descriptor||!descriptor.enumerable||!("value"in descriptor)||descriptor.value!=="endpoint")throw Error("Invalid fields account binding.")}function validateFieldsTokenDelivery(source,auth,server){const invalid=()=>{throw Error("Invalid HTTP fields token delivery.")};const inert=(value,keys)=>!!value&&typeof value==="object"&&!Array.isArray(value)&&[Object.prototype,null].includes(Object.getPrototypeOf(value))&&Reflect.ownKeys(value).every(key=>typeof key==="string"&&keys.includes(key)&&Object.getOwnPropertyDescriptor(value,key).enumerable&&"value"in Object.getOwnPropertyDescriptor(value,key));if(!inert(auth,["kind","fields","account","login","tokenField","accountBinding"])||typeof auth.tokenField!=="string"||!auth.tokenField||typeof auth.account!=="function"||!Array.isArray(auth.fields)||!auth.fields.length||auth.fields.length>16||auth.fields.some(field=>!inert(field,["key","label","secret"])||typeof field.key!=="string"||!field.key)||new Set(auth.fields.map(field=>field.key)).size!==auth.fields.length||!auth.fields.some(field=>field.key===auth.tokenField&&field.secret===true))return invalid();const allowedServerKeys=["transport","url","authorization"];if(source==="wordpress")allowedServerKeys.push("loopbackPin");if(!inert(server,allowedServerKeys)||server.transport!=="http"||typeof server.url!=="string")return invalid();if(Object.hasOwn(server,"loopbackPin")&&(typeof server.loopbackPin!=="function"||server.authorization?.kind!=="basic"||httpsUrl(server.url).hostname!=="127.0.0.1"))return invalid();if(source==="wordpress"&&server.authorization?.kind==="basic"){const username=server.authorization.username;if(!inert(server.authorization,["kind","username"])||typeof username!=="string"||!username||username.length>60||/[:\u0000-\u001f\u007f]/u.test(username)||!httpsUrl(server.url).pathname.endsWith("/wp-json/indra-l1/v1/mcp")||auth.tokenField!=="applicationPassword"||auth.login?.ready?.tool!=="indra-l1-identity")return invalid();return}if(server.authorization!==void 0&&(!inert(server.authorization,["kind"])||!["bearer","raw"].includes(server.authorization.kind)))return invalid();try{httpsUrl(server.url)}catch{const loopback=/^http:\/\/127\.0\.0\.1:([1-9][0-9]{3,4})\/$/u.exec(server.url);if(!loopback||Number(loopback[1])<1024||Number(loopback[1])>65535||server.authorization?.kind==="raw")return invalid()}}function sourceSnapshot(spec){return{...spec,server:spec.server.transport==="http"?{...spec.server,...spec.server.authorization?{authorization:structuredClone(spec.server.authorization)}:{},...spec.server.metadataHeaders?{metadataHeaders:{...spec.server.metadataHeaders}}:{}}:{...spec.server,args:[...spec.server.args]},...spec.liveRead?{liveRead:{...spec.liveRead,args:structuredClone(spec.liveRead.args??{})}}:{},...spec.exposedTools?{exposedTools:[...spec.exposedTools]}:{},...spec.publicTools?{publicTools:[...spec.publicTools]}:{},...spec.allowedTools?{allowedTools:[...spec.allowedTools]}:{},...spec.excludedTools?{excludedTools:[...spec.excludedTools]}:{},...spec.reviewedReadTools?{reviewedReadTools:structuredClone(spec.reviewedReadTools)}:{},auth:spec.auth.kind==="zendesk-oauth"?{...spec.auth,config:structuredClone(spec.auth.config),login:loginSnapshot(spec.auth.login)}:spec.auth.kind==="custodied"?structuredClone(spec.auth):spec.auth.kind==="mcp-oauth"||spec.auth.kind==="oauth-device"?{...spec.auth,...spec.auth.reviewed?{reviewed:structuredClone(spec.auth.reviewed)}:{}}:spec.auth.kind==="server-login"?{...spec.auth,login:loginSnapshot(spec.auth.login)}:spec.auth.kind==="fields"?{...spec.auth,fields:spec.auth.fields.map(field=>({...field})),...spec.auth.login?{login:loginSnapshot(spec.auth.login)}:{}}:spec.auth}}export function toolRow(source,tool){return{name:`${source}.${tool.name}`,tool:tool.name,effect:tool.annotations?.readOnlyHint===true?"read":"write",description:String(tool.description??"").slice(0,1e3),inputSchema:tool.inputSchema??{type:"object"}}}function textOf(content){return Array.isArray(content)?content.map(c=>c&&typeof c==="object"&&c.type==="text"?String(c.text??""):"").filter(Boolean).join("\n"):""}export function createShallowProvider(spec,deps){if(!SOURCE.test(spec.source))throw new Error(`Invalid level 1 source id '${spec.source}'.`);const createClient=()=>createOperationalClient(deps.metrics,spec.source,spec.server.transport==="stdio"?"mcp_stdio":"mcp_http");if(spec.exposedTools&&(!spec.exposedTools.length||new Set(spec.exposedTools).size!==spec.exposedTools.length||spec.exposedTools.some(name=>!TOOL.test(name))))throw new Error(`Invalid exposed tools for '${spec.source}'.`);if(spec.excludedTools&&(!Array.isArray(spec.excludedTools)||new Set(spec.excludedTools).size!==spec.excludedTools.length||spec.excludedTools.some(name=>!TOOL.test(name))))throw new Error(`Invalid excluded tools for '${spec.source}'.`);const authorizationBudget=resolveAuthorizationBudget(deps.authorizationBudget);if(spec.auth.kind==="fields")validateFieldsAccountBinding(spec.auth);if(spec.auth.kind==="custodied")validateCustodiedAuth(spec.auth,spec.server);else if(spec.auth.kind==="zendesk-oauth"){zendeskOAuthEndpoints(spec.auth.config);if(spec.source!=="zendesk"||spec.server.transport!=="stdio"||spec.server.tokenEnv!=="ZENDESK_OAUTH_ACCESS_TOKEN"||spec.auth.login.identity?.tool!=="zendesk_status"||spec.auth.login.ready?.tool!=="zendesk_status")throw Error("Invalid Zendesk native OAuth route.")}else if(spec.auth.kind==="fields"&&Object.hasOwn(spec.auth,"tokenField"))validateFieldsTokenDelivery(spec.source,spec.auth,spec.server);else if(spec.server.transport==="http"?spec.server.authorization!==void 0||spec.server.metadataHeaders!==void 0:spec.server.tokenEnv!==void 0)throw Error("Protected credential delivery requires custodied authorization.");spec=sourceSnapshot(spec);if(spec.auth.kind==="custodied"&&spec.auth.credentialKind==="oauth"&&!validReview({issuer:spec.auth.issuer,scopes:spec.auth.requiredScopes,allowedOrigins:spec.auth.oauth.allowedOrigins}))throw Error("Invalid protected OAuth refresh policy.");const toolName=name=>/^[a-zA-Z0-9_.-]{1,200}$/u.test(name);if(spec.readOnly!==void 0&&spec.readOnly!==true||spec.preserveContent!==void 0&&spec.preserveContent!==true||spec.validateResult!==void 0&&typeof spec.validateResult!=="function"||spec.validateParams!==void 0&&typeof spec.validateParams!=="function"||spec.allowedTools&&(!Array.isArray(spec.allowedTools)||spec.allowedTools.length>256||new Set(spec.allowedTools).size!==spec.allowedTools.length||spec.allowedTools.some(name=>!toolName(name))))throw Error("Invalid prepared tool policy.");if(spec.reviewedReadTools&&(!spec.origin.package&&!spec.origin.artifact||Object.entries(spec.reviewedReadTools).some(([name,pin])=>!toolName(name)||!pin||Object.keys(pin).some(key=>key!=="inputSchemaSha256")||!/^[a-f0-9]{64}$/u.test(pin.inputSchemaSha256))))throw Error("Invalid pinned readonly tool contract.");if(spec.auth.kind==="server-login"&&spec.auth.login.identity){const{format,...review}=spec.auth.login.identity;if(format!==void 0&&format!=="json-text"||!validIdentityReview(review))throw Error("Invalid native server identity contract.")}if(spec.auth.kind==="server-login"){const login=spec.auth.login;if(login.browserProfile!==void 0&&!["dedicated","existing","temporary"].includes(login.browserProfile))throw Error("Invalid upstream browser ownership.");if(login.tool!==void 0&&!toolName(login.tool)||!login.tool&&!login.ready||login.instructions!==void 0&&(typeof login.instructions!=="string"||!login.instructions.trim()||login.instructions.length>2048||/[\u0000-\u001f\u007f-\u009f]/u.test(login.instructions)))throw Error("Invalid upstream login instructions.");if(login.handoff&&(!login.tool||!login.ready||typeof login.handoff.instructions!=="function"||login.handoff.image!==void 0&&typeof login.handoff.image!=="function"||login.handoff.automatic!==void 0&&login.handoff.automatic!==true||login.handoff.device!==void 0&&typeof login.handoff.device!=="function"||login.handoff.openingInstructions!==void 0&&(typeof login.handoff.openingInstructions!=="string"||!login.handoff.openingInstructions.trim()||login.handoff.openingInstructions.length>2048||/[\u0000-\u001f\u007f-\u009f]/u.test(login.handoff.openingInstructions))))throw Error("Invalid upstream login handoff.");if(login.cleanup&&(!login.handoff||!toolName(login.cleanup.tool)||typeof login.cleanup.done!=="function"))throw Error("Invalid upstream login cleanup.")}const{vault,enrollment,transport=fetch}=deps;const custodySource=spec.source==="figma"&&spec.auth.kind==="fields"?"figma--pat":spec.source;const info={source:spec.source,label:spec.label,group:spec.group,auth:spec.auth.kind==="fields"||spec.auth.kind==="custodied"&&spec.auth.credentialKind!=="local-no-secret"?"api-key":spec.auth.kind==="none"||spec.auth.kind==="custodied"&&spec.auth.credentialKind==="local-no-secret"?"none":"oauth-browser"};const stop=new AbortController,pending=new Set;const wireSignals=new AsyncLocalStorage;let closed=false,session=null,closing;let checkEpoch=0;let guardedReadsInFlight=0;const guardedReadiness=()=>spec.source==="joplin"||spec.source==="wordpress"||spec.source==="basecamp"||spec.source==="coda"||spec.source==="todoist"||spec.source==="calendly"||spec.source==="monday"||spec.source==="zotero"||spec.source==="webflow"||["visual-studio","modelsim","quartus","simulink","jianying","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","windows-event-viewer","windows-task-scheduler","wsl","docker-desktop","ollama","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter"].includes(spec.source);let readiness;function clearReadiness(){readiness=void 0;checkEpoch++}const starting=new Set,cleanup=new Set;const bound=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;const fail=(code,message)=>businessError(code,message,"plugin");function fieldsGrant(fields){return{fields,...spec.auth.kind==="fields"&&spec.auth.tokenField?{token:fields[spec.auth.tokenField]}:{}}}function containsProtectedMaterial(encoded,grant2){if(grant2.protect?.(encoded))return true;if(spec.auth.kind!=="custodied"&&spec.auth.kind!=="fields")return false;const secrets=[grant2.token,...Object.values(grant2.environment??{})];if(spec.auth.kind==="fields"){for(const field of spec.auth.fields)if(field.secret===true)secrets.push(grant2.fields?.[field.key])}if(spec.server.transport==="http"&&spec.server.authorization?.kind==="basic"&&grant2.token)secrets.push(Buffer.from(spec.server.authorization.username+":"+grant2.token,"utf8").toString("base64"));return secrets.some(secret=>!!secret&&(encoded.includes(secret)||encoded.includes(JSON.stringify(secret).slice(1,-1))))}const jobs=new Map;let loginOwner;let firstRead;async function signedInPage(url,signal){const route=spec.signedIn;return readSignedInPage(deps.browserDriver?.(),{site:route.site,url,timeoutMs:6e4,settleMs:1e4},signal).catch(()=>({state:"failed",reason:"collector_error"}))}async function connectSignedIn(options){const route=spec.signedIn,signal=bound(options?.signal);const outcome=await signedInPage(route.identityUrl,signal);if(!outcome&&!signal.aborted)return void 0;const job={id:randomUUID(),source:spec.source,state:"failed",startedAt:new Date().toISOString()};jobs.set(job.id,job);const failed=(code,message)=>{job.error={code,message};return ok({...job})};if(signal.aborted){job.state="cancelled";return ok({...job})}if(/^browser_session_unavailable(?:\s|$)/.test(outcome.reason??"")){const error={...automaticError("browser_session_unavailable"),code:browserConnectionDiagnostic(outcome.reason)??"browser_session_unavailable"};return failed(error.code,error.message)}if(outcome.state==="login_required")return failed("login_required",`Sign in to ${spec.label} in Chrome on this computer, then connect again. Zortex never asks for your password.`);if(outcome.state!=="completed")return failed("site_read_failed",`${spec.label} could not be read in the background (${String(outcome.reason??outcome.state).split(" ")[0]}).`);const identity=route.identity(outcome);if(!identity)return failed("site_read_failed",`${spec.label} did not show the signed-in account.`);const saved=await vault.saveConnection({source:spec.source,provider:spec.source,account:identity.account,accountId:identity.accountId,scopes:["page.read"],state:"connected",updatedAt:new Date().toISOString()},{...SIGNED_IN_BROWSER_CREDENTIAL,scopes:["page.read"]},{signal});if(!("ok"in saved))return failed("custody_failed","The connection could not be saved on this computer.");if(!route.feedUrl)firstRead={records:route.records(spec.source,outcome),expiresAt:Date.now()+6e4};job.state="connected";job.account=identity.account;return ok({...job})}function rawWire(grant2){if(deps.wire){const{protect:_protect,...wireGrant}=grant2;return deps.wire(spec,wireGrant)}const server=spec.server;if(server.transport==="http"){const target=new URL(server.url),headers={...server.metadataHeaders};if(grant2.token){if(server.authorization?.kind==="query")target.searchParams.set(server.authorization.parameter,grant2.token);else headers.Authorization=server.authorization?.kind==="raw"?grant2.token:server.authorization?.kind==="basic"?`Basic ${Buffer.from(server.authorization.username+":"+grant2.token,"utf8").toString("base64")}`:`Bearer ${grant2.token}`;if(server.authorization?.kind==="bearer")for(const name of server.authorization.additionalHeaders??[])headers[name]=grant2.token}const fieldsToken=spec.auth.kind==="fields"&&spec.auth.tokenField!==void 0;const pin=server.loopbackPin?.();const pinned=pin===void 0?void 0:createPinnedLoopbackHttp(target.href,pin);const protectedFetch=spec.auth.kind==="custodied"||fieldsToken?async(input,init)=>{const requested=new URL(input instanceof Request?input.url:String(input));if(requested.origin!==target.origin||requested.pathname!==target.pathname||fieldsToken&&requested.href!==target.href)throw Error("Protected MCP destination changed.");const signals=[stop.signal,wireSignals.getStore(),init?.signal,input instanceof Request?input.signal:void 0].filter(value=>!!value);const signal=AbortSignal.any(signals);signal.throwIfAborted();await grant2.authorize?.(signal);signal.throwIfAborted();const options={...init,signal,redirect:"error",credentials:"omit"};return pinned?pinned.fetch(transport,input,options):transport(input,options)}:transport;const wire2=new StreamableHTTPClientTransport(target,{fetch:protectedFetch,...Object.keys(headers).length?{requestInit:{headers}}:{}});if(pinned){const close=wire2.close.bind(wire2);wire2.close=async()=>{try{await close()}finally{await pinned.close()}}}return wire2}return new StdioClientTransport({command:server.command,args:server.args,...server.cwd?{cwd:server.cwd}:{},env:{...proxyEnv(),...server.env?.(grant2.fields??{},grant2.token)??{},...grant2.environment??{},...server.tokenEnv&&grant2.token?{[server.tokenEnv]:grant2.token}:{}},stderr:"ignore"})}function wire(grant2){const transport2=rawWire(grant2);let processRef,resources;const facts={route:spec.server.transport==="stdio"?"mcp_stdio":"mcp_http",...spec.server.transport==="stdio"?{artifactFamily:"connector_runtime"}:{}};const lifecycle=startOperationalStep(deps.metrics,()=>{if(spec.server.transport==="stdio")processRef=randomUUID();return{source:spec.source,phase:"runtime",action:"execute",...facts,...processRef?{processRef}:{}}});const start=transport2.start.bind(transport2),close=transport2.close.bind(transport2);transport2.start=async()=>{const step=lifecycle.run(()=>startOperationalStep(deps.metrics,{source:spec.source,phase:"runtime",action:"connect",...facts}));try{await step.run(start);step.finish({state:"completed"});if(transport2 instanceof StdioClientTransport&&transport2.pid!==null&&deps.metrics)try{const pid=transport2.pid;resources=lifecycle.run(()=>startOwnedProcessResourceSampler({pid,parentPid:process.pid,role:"connector_runtime",metrics:deps.metrics,...processRef?{processRef}:{},isAlive:()=>transport2.pid===pid}))}catch{}}catch(error){const reason=operationalReason(error instanceof Error?error.message:void 0);step.finish({state:"failed",reason});lifecycle.finish({state:"failed",reason});throw error}};transport2.close=async()=>{const step=lifecycle.run(()=>startOperationalStep(deps.metrics,{source:spec.source,phase:"runtime",action:"cleanup",...facts,...processRef?{processRef}:{}}));try{await step.run(close);resources?.close();step.finish({state:"completed"});lifecycle.finish({state:"completed"})}catch(error){step.finish({state:"failed",reason:"provider_failure"});lifecycle.mark({state:"unknown",reason:"provider_failure"});throw error}};if(grant2.authorize){const send=transport2.send.bind(transport2);transport2.send=async(...args)=>{const signal=wireSignals.getStore()??stop.signal;signal.throwIfAborted();await grant2.authorize(signal);signal.throwIfAborted();return send(...args)}}return transport2}function track(set,task){set.add(task);void task.then(()=>set.delete(task),()=>set.delete(task));return task}function dropSession(s=session){if(!s)return Promise.resolve();if(readiness?.session===s)readiness=void 0;if(session===s)session=null;if(!s.closing){s.stop.abort();s.closing=track(cleanup,s.client.close().catch(()=>{}))}return s.closing}function wait(task,signal){signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>{signal.removeEventListener("abort",abort);reject(signal.reason)};signal.addEventListener("abort",abort,{once:true});void task.then(value=>{signal.removeEventListener("abort",abort);resolve(value)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}async function open(grant2,signal){signal.throwIfAborted();if(closed)throw new Error("inactive");const key=JSON.stringify(grant2);if(session?.key!==key){const previous=dropSession();const s2={key,client:createClient(),stop:new AbortController,ready:Promise.resolve([]),published:false,waiters:0};s2.client.onclose=()=>{s2.published=false;s2.stop.abort();if(readiness?.session===s2)clearReadiness();if(session===s2)session=null};session=s2;const setupSignal=bound(s2.stop.signal);s2.ready=track(starting,(async()=>{try{await previous;setupSignal.throwIfAborted();await grant2.authorize?.(setupSignal);setupSignal.throwIfAborted();await wireSignals.run(setupSignal,()=>s2.client.connect(wire(grant2),{signal:setupSignal}));const tools=[];let cursor;for(let page=0;page<10;page++){const listed2=await wireSignals.run(setupSignal,()=>s2.client.listTools(cursor?{cursor}:{},{signal:setupSignal}));if(containsProtectedMaterial(JSON.stringify(listed2),grant2))throw Error("Protected MCP discovery returned credential material.");for(const t of listed2.tools){if(grant2.public&&!spec.publicTools?.includes(t.name)||spec.allowedTools&&!spec.allowedTools.includes(t.name)||spec.exposedTools&&!spec.exposedTools.includes(t.name)||spec.excludedTools?.includes(t.name))continue;let reviewed=t;const pin=spec.reviewedReadTools?.[t.name];if(pin){if(t.annotations?.readOnlyHint===false||reviewedToolSchemaHash(t.inputSchema)!==pin.inputSchemaSha256)throw Error("Pinned readonly MCP tool contract changed.");reviewed={...t,annotations:{...t.annotations,readOnlyHint:true}}}const row=toolRow(spec.source,reviewed);if(spec.adaptSchema)row.inputSchema=spec.adaptSchema(row.tool,row.inputSchema);if(!spec.readOnly||row.effect==="read")tools.push(row)}cursor=listed2.nextCursor;if(!cursor)break}setupSignal.throwIfAborted();s2.published=true;return tools}catch(error){await dropSession(s2);throw error}})())}const s=session;s.waiters++;try{return{client:s.client,tools:await wait(s.ready,signal)}}finally{s.waiters--;if(!s.published&&s.waiters===0)await dropSession(s)}}const selectedReadinessFence=()=>spec.source==="matrix"&&spec.auth.kind==="fields"||spec.auth.kind==="zendesk-oauth"||["ticktick","airtable","gitlab","monday","linear"].includes(spec.source)||["jira","todoist","coda","webflow","wordpress"].includes(spec.source)&&spec.auth.kind!=="custodied";const nativeAccountChoice=options=>options?.selectAccount===true||options?.reauthorize!==true;async function captureAccountChoice(signal){const custody=vault.bindingCustody;if(!custody?.sourceSelection)return fail("failed_precondition",`${spec.label} needs native account selection custody.`);const selected=await wait(custody.sourceSelection(spec.source),signal);if(!("ok"in selected))return selected;const bindings=await wait(custody.bindings(spec.source),signal);if(!("ok"in bindings))return bindings;const inventory=[];for(const binding of bindings.ok){const captured=await wait(custody.bindingInventory(binding.id),signal);if(!("ok"in captured))return captured;if(!captured.ok)return fail("failed_precondition",`${spec.label} account changed before authorization.`);inventory.push(captured.ok)}return ok({revision:selected.ok?.revision??null,inventory})}function accountChoiceProof(choice,accountId,audience){if(!accountId)throw Error("Account selection requires a verified native subject.");const matches=choice.inventory.filter(row2=>row2.binding.identity.source===spec.source&&row2.binding.identity.issuer===spec.source&&row2.binding.identity.subject===accountId&&row2.binding.identity.tenant===null);if(matches.length>1)throw Error("Native account binding is ambiguous.");if(!matches.length)return{selectSource:{expectedSelectionRevision:choice.revision,expectedBindingRevision:0}};const row=matches[0],grant2=row.grants.find(g=>g.purpose==="L1"&&g.audience===audience),resource=row.resources.find(r=>r.id===oauthCredentialResourceId(row.binding.id));if(!grant2||!resource)throw Error("Existing native account needs its original resource authority.");const expectedCredential={bindingId:row.binding.id,bindingRevision:row.binding.revision,grantId:grant2.id,grantRevision:grant2.revision,resourceId:resource.id,resourceRevision:resource.revision};return{selectSource:{expectedSelectionRevision:choice.revision,expectedBindingRevision:row.binding.revision},expectedCredential}}const readinessAuthority=current=>(current.snapshot?[current.snapshot,...current.additionalSnapshots??[]]:[]).map(snapshot=>({bindingId:snapshot.binding.id,bindingRevision:snapshot.binding.revision,grantId:snapshot.grant.id,grantRevision:snapshot.grant.revision,scopeEpoch:snapshot.grant.scopeEpoch,resourceId:snapshot.resource.id,resourceRevision:snapshot.resource.revision,expiresAt:snapshot.material.kind==="oauth"?snapshot.material.credential.expiresAt:0}));function rememberReadiness(current,opened,operation,epoch,signal){if(epoch!==checkEpoch||signal.aborted||closed||!session?.published||session.stop.signal.aborted||session.client!==opened.client||opened.tools.length===0||current.grant.public)return;if(!current.snapshot&&!current.legacyRevision&¤t.pairingRevision===void 0&&spec.auth.kind!=="none")return;const authority=readinessAuthority(current);if(selectedReadinessFence()&&(!current.snapshot||current.selectionRevision===void 0))return;readiness={session,authority,...current.pairingRevision===void 0?{}:{pairingRevision:current.pairingRevision,pairingAccount:current.account},...current.legacyRevision?{legacyRevision:current.legacyRevision}:{},...selectedReadinessFence()?{selectionRevision:current.selectionRevision}:{},value:{actions:opened.tools.length,operation}}}async function currentReadiness(signal){const checked=readiness;if(!checked)return;const discard=()=>{if(readiness===checked)clearReadiness();return void 0};if(closed||signal.aborted||session!==checked.session||!checked.session.published||checked.session.stop.signal.aborted)return discard();try{if(checked.legacyRevision){if(!vault.legacyRevision)return discard();const revision=await wait(vault.legacyRevision(custodySource),signal);if(!("ok"in revision)||revision.ok!==checked.legacyRevision)return discard()}if(checked.pairingRevision!==void 0){if(!vault.joplinFencedRevision)return discard();if(!checked.pairingAccount)return discard();const revision=await wait(vault.joplinFencedRevision(checked.pairingAccount),signal);if(!("ok"in revision)||revision.ok!==checked.pairingRevision)return discard()}if(checked.authority.length){const selectionMatches=async()=>{if(!selectedReadinessFence())return true;if(checked.selectionRevision===void 0||!vault.bindingCustody.sourceSelection)return false;const selected=await wait(vault.bindingCustody.sourceSelection(spec.source),signal);return"ok"in selected&&(selected.ok?.revision??null)===checked.selectionRevision&&(!selected.ok||selected.ok.bindingId===checked.authority[0]?.bindingId)};if(!await selectionMatches())return discard();const custody=vault.bindingCustody;if(!custody?.bindingInventory)return discard();if(spec.auth.kind!=="custodied"){const selected=await wait(custody.resolve({kind:spec.auth.kind==="server-login"?"legacy-source":"selected-source",source:spec.source}),signal);if(!("ok"in selected)||selected.ok.kind!=="resolved"||selected.ok.binding.id!==checked.authority[0].bindingId)return discard()}for(const bindingId of new Set(checked.authority.map(value=>value.bindingId))){const loaded=await wait(custody.bindingInventory(bindingId),signal);if(!("ok"in loaded)||!loaded.ok)return discard();const{binding,grants,resources}=loaded.ok;for(const expected of checked.authority.filter(value=>value.bindingId===bindingId)){const grant2=grants.find(value=>value.id===expected.grantId),resource=resources.find(value=>value.id===expected.resourceId);if(binding.id!==expected.bindingId||binding.revision!==expected.bindingRevision||binding.state!=="connected"||!grant2||grant2.revision!==expected.grantRevision||grant2.scopeEpoch!==expected.scopeEpoch||grant2.state!=="active"||!resource||resource.revision!==expected.resourceRevision||expected.expiresAt>0&&expected.expiresAt<=Date.now())return discard()}}if(!await selectionMatches())return discard()}if(signal.aborted||readiness!==checked||session!==checked.session||checked.session.stop.signal.aborted)return discard();return{actions:checked.value.actions,operation:{...checked.value.operation}}}catch{return discard()}}const nativeAudience=spec.server.transport==="http"?spec.server.url:spec.source;const nativeResourceId=bindingId=>`server-login:${bindingId}`;function registeredSessionMatches(authority){const review=spec.auth.kind==="mcp-oauth"?spec.auth.reviewed:void 0,registration=review?.registration;return registration?.kind!=="pre-registered"||isMcpSessionAuthority(authority)&&spec.server.transport==="http"&&authority.issuer===review.issuer&&authority.resource===(spec.source==="front"&&spec.server.url==="https://mcp.frontapp.com/mcp"?"https://mcp.frontapp.com/":spec.server.url)&&authority.clientId===registration.clientId}function selectedResourceMatches(authority){if(!isMcpSessionAuthority(authority))return false;if(spec.source==="matrix"&&spec.auth.kind==="fields")return authority.resource===matrixHomeserver&&authority.issuer===matrixIssuer&&authority.tokenEndpoint===matrixTokenUrl;if(spec.auth.kind==="oauth-device"){const resource=spec.server.transport==="http"?spec.server.url:spec.auth.tokenUrl;return authority.resource===resource&&authority.issuer===spec.auth.reviewed.issuer&&authority.clientId===spec.auth.clientId&&authority.tokenEndpoint===spec.auth.tokenUrl}return spec.server.transport==="http"&&checkResourceAllowed({requestedResource:resourceUrlFromServerUrl(spec.server.url),configuredResource:authority.resource})}function zendeskBindingMatches(binding,auth,credential){const endpoints=zendeskOAuthEndpoints(auth.config),prefix=`zendesk:v1:${auth.config.subdomain}:`;return spec.source==="zendesk"&&spec.server.transport==="stdio"&&spec.server.tokenEnv==="ZENDESK_OAUTH_ACCESS_TOKEN"&&binding.provider==="zendesk"&&binding.identity.source==="zendesk"&&binding.identity.issuer==="zendesk"&&binding.identity.tenant===null&&!binding.authority&&typeof binding.identity.subject==="string"&&binding.identity.subject.startsWith(prefix)&&/^[1-9][0-9]{0,19}$/u.test(binding.identity.subject.slice(prefix.length))&&(!credential||credential.clientId===endpoints.clientId&&!credential.clientAuthentication&&credential.registeredRedirectUri===endpoints.redirectUri&&sameScopes(credential.scopes,endpoints.scopes))}async function refreshZendeskGrant(snapshot,auth,caller){caller.throwIfAborted();const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition","Zendesk refresh requires durable credential custody.");return custody.refreshResource(snapshot,{kind:"resident"},async current=>{const permitted=authorizedCredential(current);if(!("ok"in permitted))return permitted;if(!permitted.ok.refreshToken)return fail("failed_precondition","Zendesk needs a new authorization.");try{const token=await refreshZendeskToken(auth.config,{refreshToken:permitted.ok.refreshToken,scopes:current.grant.scopes},bound(),(url,init)=>transport(url,init));return ok({kind:"oauth",credential:{...permitted.ok,...token}})}catch{return fail("failed_precondition","Zendesk token refresh failed; reconnect this source.")}})}async function connectZendeskOAuth(auth,options){const endpoints=zendeskOAuthEndpoints(auth.config);if(spec.source!=="zendesk"||spec.server.transport!=="stdio"||spec.server.tokenEnv!=="ZENDESK_OAUTH_ACCESS_TOKEN")return fail("failed_precondition","Zendesk OAuth needs its fixed native server route.");const prior=await vault.connection(custodySource);if(!("ok"in prior))return prior;const choose=nativeAccountChoice(options),expected=choose?void 0:prior.ok?.accountId;const choice=choose?await captureAccountChoice(bound(options?.signal)):void 0;if(choice&&!("ok"in choice))return choice;return enrollment.pkce(info,{clientId:endpoints.clientId,authorizeUrl:endpoints.authorizeUrl,tokenUrl:endpoints.tokenUrl,scope:endpoints.scopes.join(" "),provider:"zendesk",loopbackPort:auth.config.loopbackPort,redirectHost:"127.0.0.1",redirectPath:"/callback",exchangeCode:async(input,signal)=>{if(input.clientId!==endpoints.clientId||input.tokenUrl!==endpoints.tokenUrl)throw Error("Zendesk authorization configuration changed.");const token=await exchangeZendeskCode(auth.config,input,signal,(url,init)=>transport(url,init));return{access_token:token.accessToken,refresh_token:token.refreshToken,expires_at:token.expiresAt,scope:token.scopes.join(" "),token_type:"bearer"}}},async(token,signal)=>{const candidate=await probe({token:token.access_token},signal,auth.login,true).catch(()=>{throw Error("Zendesk native identity verification failed.")});if(!candidate.identity||!/^[1-9][0-9]{0,19}$/u.test(candidate.identity.accountId))throw Error("Zendesk native user identity was not verified.");const accountId=`zendesk:v1:${auth.config.subdomain}:${candidate.identity.accountId}`;if(expected!==void 0&&expected!==accountId)throw Error("Zendesk user or tenant changed; explicitly choose the account again.");if(!Number.isFinite(token.expires_at)||token.expires_at<=Date.now())throw Error("Zendesk authorization expired before identity verification.");return{account:`${auth.config.subdomain}: ${candidate.identity.account}`,accountId,...choice&&"ok"in choice?accountChoiceProof(choice.ok,accountId,"zendesk"):{},credential:{accessToken:token.access_token,refreshToken:token.refresh_token,expiresAt:token.expires_at,clientId:endpoints.clientId,registeredRedirectUri:endpoints.redirectUri,scopes:[...endpoints.scopes]}}},options)}function authorizedCredential(snapshot){if(snapshot.material.kind!=="oauth"||snapshot.resource.kind!=="oauth"||snapshot.resource.owner.kind!=="resident"||snapshot.binding.identity.source!==spec.source)return fail("failed_precondition",`${spec.label} needs a resident-owned OAuth credential resource.`);const credential=snapshot.material.credential;if(spec.auth.kind==="zendesk-oauth"&&!zendeskBindingMatches(snapshot.binding,spec.auth,credential))return fail("permission_denied","Zendesk credential does not match its selected tenant and public client.");const clientAuthentication=credential.clientAuthentication,registration=spec.auth.kind==="mcp-oauth"?spec.auth.reviewed?.registration:void 0;if(clientAuthentication!==void 0&&!validClientAuthentication(clientAuthentication))return fail("failed_precondition",`${spec.label} client authentication is unreadable; reconnect this source.`);if(clientAuthentication&&spec.auth.kind==="mcp-oauth"&®istration?.kind!=="pre-registered"&&!(registration?.kind==="dcr"&&spec.server.transport==="http"&&spec.auth.reviewed&&reviewedDcrConfidentialSource(spec.server.url,spec.auth.reviewed)===spec.source))return fail("permission_denied",`${spec.label} selected OAuth mode does not authorize confidential client authentication.`);if((registration?.kind==="pre-registered"||registration?.kind==="dcr"&®istration.tokenEndpointAuthMethod)&®istration.tokenEndpointAuthMethod!==clientAuthentication?.method)return fail("permission_denied",`${spec.label} credential belongs to another selected OAuth authentication method.`);if(!registeredSessionMatches(snapshot.binding.authority))return fail("permission_denied",`${spec.label} credential belongs to another selected OAuth client or resource.`);if(snapshot.binding.authority&&(!isMcpSessionAuthority(snapshot.binding.authority)||snapshot.binding.authority.clientId!==credential.clientId||snapshot.binding.authority.resource!==snapshot.grant.audience))return fail("permission_denied",`${spec.label} credential no longer matches its selected MCP session.`);if(!sameScopes(snapshot.grant.scopes,credential.scopes))return fail("permission_denied",`${spec.label} credential scopes no longer match its selected L1 grant.`);if(spec.source==="monday"&&!acceptsMondayDefaultGrant(snapshot.grant.scopes))return fail("permission_denied",`${spec.label} saved scopes do not match its reviewed default grant; reconnect this source.`);if(typeof credential.accessToken!=="string"||!credential.accessToken||!Number.isFinite(credential.expiresAt)||credential.expiresAt<0)return fail("failed_precondition",`${spec.label} grant is unreadable; reconnect this source.`);return ok(credential)}async function inspectSelectedAuthority(signal){const custody=vault.bindingCustody;if(!custody?.bindingInventory)return fail("failed_precondition",`${spec.label} status requires its selected credential custody.`);const selected=await wait(custody.resolve({kind:spec.auth.kind==="server-login"?"legacy-source":"selected-source",source:spec.source}),signal);if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition",`${spec.label} needs one selected account or session binding.`);const loaded=await wait(custody.bindingInventory(selected.ok.binding.id),signal);if(!("ok"in loaded))return loaded;if(!loaded.ok)return fail("failed_precondition",`${spec.label} selected binding is not configured.`);const{binding,grants,resources}=loaded.ok,serverLogin=spec.auth.kind==="server-login";if(spec.auth.kind==="zendesk-oauth"&&!zendeskBindingMatches(binding,spec.auth))return fail("permission_denied","Zendesk selected tenant does not match its authorization.");if(binding.identity.source!==spec.source||binding.state!=="connected")return fail("permission_denied",`${spec.label} selected connection is no longer active.`);if(!registeredSessionMatches(binding.authority))return fail("permission_denied",`${spec.label} selected OAuth client or resource has changed.`);if(spec.auth.kind==="server-login"){const native=!!spec.auth.login.identity;if(binding.identity.issuer!==spec.source||(native?!binding.identity.subject:binding.identity.subject!==void 0||!isServerSessionAuthority(binding.authority)||binding.authority.resource!==nativeAudience))return fail("failed_precondition",`${spec.label} needs its selected upstream account or server session binding.`)}else if(binding.authority){if(!selectedResourceMatches(binding.authority))return fail("permission_denied",`${spec.label} selected MCP session belongs to another resource.`)}else if(!binding.identity.subject)return fail("failed_precondition",`${spec.label} has no selected OAuth authority.`);const audience=serverLogin?nativeAudience:binding.authority?.resource??binding.provider;const selectedGrants=grants.filter(grant2=>grant2.bindingId===binding.id&&grant2.purpose==="L1"&&grant2.audience===audience);if(selectedGrants.length!==1||selectedGrants[0].state!=="active")return fail("permission_denied",`${spec.label} selected L1 permission is not active.`);const resourceId=serverLogin?nativeResourceId(binding.id):oauthCredentialResourceId(binding.id),resource=resources.find(value=>value.id===resourceId);if(!resource||resource.bindingId!==binding.id||resource.owner.kind!=="resident"||resource.kind!==(serverLogin?"local-no-secret":"oauth"))return fail("failed_precondition",`${spec.label} selected credential resource is not configured for this source.`);signal.throwIfAborted();return ok(void 0)}function oauthFetch(signal){return async(input,init)=>{signal.throwIfAborted();const response=await transport(input,{...init,redirect:"error",credentials:"omit",signal:init?.signal?AbortSignal.any([signal,init.signal]):signal});signal.throwIfAborted();return response}}async function brokerCall(base,path,body,signal){const target=new URL(path,base+"/");if(target.origin!==new URL(base).origin||target.username||target.password||target.hash)throw Error("Invalid authorization broker request.");const response=await wait(transport(target.href,{method:body?"POST":"GET",redirect:"error",credentials:"omit",signal,headers:{Accept:"application/json",...body?{"Content-Type":"application/json"}:{}},...body?{body:JSON.stringify(body)}:{}}),signal);const size=Number(response.headers.get("content-length")??0);if(size>32768||!response.body)throw Error("Authorization broker returned an invalid response.");const reader=response.body.getReader(),chunks=[];let length=0;try{for(;;){const part=await wait(reader.read(),signal);if(part.done)break;length+=part.value.byteLength;if(length>32768)throw Error("Authorization broker returned an invalid response.");chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(length);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length}let value;try{value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch{throw Error("Authorization broker returned an invalid response.")}if(!response.ok||!value||typeof value!=="object"||Array.isArray(value)||Object.hasOwn(value,"error"))throw Error("Authorization broker refused the request.");return value}function sourceOAuthReviewMatches(review,url){if(review.registration?.kind==="dcr"&&review.registration.tokenEndpointAuthMethod)return reviewedDcrConfidentialSource(url,review)===spec.source;const unadvertised=review.registration?.kind==="dcr"&&review.registration.allowUnadvertisedPublicClient===true;if(spec.source==="miro"&&unadvertised)return url==="https://mcp.miro.com/"&&review.issuer==="https://mcp.miro.com/"&&sameScopes(review.scopes,["boards:read","boards:write","openid","email"])&&sameScopes(review.allowedOrigins,["https://mcp.miro.com"])&&review.registration?.kind==="dcr"&&!review.registration.discardReturnedSecretForPublicClient&&review.identity===void 0;if(spec.source==="pipedrive"&&unadvertised)return url==="https://mcp.pipedrive.ai/mcp"&&review.issuer==="https://oauth.pipedrive.com"&&sameScopes(review.scopes,["search:read"])&&sameScopes(review.allowedOrigins,["https://oauth.pipedrive.com"])&&review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient===true&&review.identity===void 0;if(spec.source==="wordpress")return url==="https://public-api.wordpress.com/wpcom/v2/mcp/v1"&&review.issuer==="https://public-api.wordpress.com"&&sameScopes(review.allowedOrigins,["https://public-api.wordpress.com"])&&sameScopes(review.scopes,["auth"])&&review.identity?.kind==="wordpress-user-profile"&&review.redirectUriPolicy===void 0&&review.registration?.kind==="dcr"&&Object.keys(review.registration).length===2&&review.registration.discardReturnedSecretForPublicClient===true;const confidentialSource=reviewedConfidentialSource(url,review);if(confidentialSource&&confidentialSource!==spec.source)return false;if(["box","google-contacts","google-chat","front","hubspot"].includes(spec.source)&&review.registration?.kind==="pre-registered"&&review.registration.tokenEndpointAuthMethod){const source=reviewedConfidentialSource(url,review),auth=spec.auth;return source===spec.source&&(auth.kind==="custodied"||auth.kind==="mcp-oauth"&&auth.redirectHost==="localhost"&&Number.isInteger(auth.loopbackPort)&&auth.loopbackPort>=1024&&auth.loopbackPort<=65535)}if(spec.source==="dropbox"&&review.registration?.kind==="pre-registered")return reviewedDropboxPublicClient(url,review)&&spec.auth.kind==="mcp-oauth"&&spec.auth.redirectHost==="localhost"&&Number.isInteger(spec.auth.loopbackPort)&&spec.auth.loopbackPort>=1024&&spec.auth.loopbackPort<=65535;if(review.registration?.kind==="pre-registered"&&review.registration.allowUnadvertisedPublicClient===true){const source=reviewedRegisteredPublicSource(url,review),auth=spec.auth;return source===spec.source&&auth.kind==="mcp-oauth"&&(source==="zoom"?auth.loopbackPort===0&&(auth.redirectHost===void 0||auth.redirectHost==="127.0.0.1"):auth.redirectHost==="localhost"&&Number.isInteger(auth.loopbackPort)&&auth.loopbackPort>=1024&&auth.loopbackPort<=65535)}if(spec.source==="cloudflare")return url==="https://mcp.cloudflare.com/mcp"&&review.issuer==="https://mcp.cloudflare.com"&&(sameScopes(review.scopes,["user:read","account:read","offline_access"])||sameScopes(review.scopes,["user:read","account:read","offline_access","workers-kv-storage.write"]))&&sameScopes(review.allowedOrigins,["https://mcp.cloudflare.com","https://dash.cloudflare.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind===void 0&&review.identity?.tool==="whoami"&&sameScopes(review.identity.subjectPath,["id"])&&sameScopes(review.identity.labelPath??[],["email"]);if(spec.source==="posthog")return(url==="https://mcp.posthog.com/mcp"||url==="https://mcp.posthog.com/mcp?mode=tools&tools=user-get%2Corganizations-get%2Cprojects-get%2Cdashboards-get-all%2Cinsights-list%2Cexecute-sql%2Cannotation-create%2Cannotation-retrieve%2Cannotations-list%2Cannotation-delete")&&review.issuer==="https://oauth.posthog.com"&&sameScopes(review.scopes,["user:read","organization:read","dashboard:read","insight:read","query:read","annotation:read","annotation:write"])&&sameScopes(review.allowedOrigins,["https://oauth.posthog.com","https://us.posthog.com","https://eu.posthog.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind===void 0&&review.identity?.tool==="user-get"&&sameScopes(review.identity.subjectPath,["uuid"])&&sameScopes(review.identity.labelPath??[],["email"]);if(spec.source==="notion-l1")return url==="https://mcp.notion.com/mcp"&&review.issuer==="https://mcp.notion.com"&&sameScopes(review.scopes,["default"])&&sameScopes(review.allowedOrigins,["https://mcp.notion.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind==="notion-bot-owner";if(spec.source==="sentry")return url==="https://mcp.sentry.dev/mcp"&&review.issuer==="https://mcp.sentry.dev"&&sameScopes(review.scopes,["org:read","project:write","team:write","event:write","alerts:write"])&&sameScopes(review.allowedOrigins,["https://mcp.sentry.dev","https://sentry.io"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient&&review.identity?.kind==="sentry-catalog-whoami";if(review.identity?.kind==="openrouter-current-key")return!unadvertised&&spec.source==="openrouter"&&url==="https://mcp.openrouter.ai/mcp"&&review.issuer==="https://mcp.openrouter.ai"&&review.allowedOrigins.includes("https://openrouter.ai");if(review.identity?.kind==="gitlab-token-info")return spec.source==="gitlab"&&url==="https://gitlab.com/api/v4/mcp"&&review.issuer==="https://gitlab.com"&&review.scopes.length===1&&review.scopes[0]==="mcp"&&review.allowedOrigins.length===1&&review.allowedOrigins[0]==="https://gitlab.com"&&unadvertised;if(review.identity?.kind==="atlassian-current-user-sites")return(spec.source==="jira"||spec.source==="confluence")&&url==="https://mcp.atlassian.com/v2/mcp"&&review.issuer==="https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3"&&sameScopes(review.scopes,spec.source==="jira"?["read:me","read:account","offline_access","email","read:jira:agent-interface","write:jira:agent-interface","search:jira:agent-interface","delete:jira:agent-interface","manage:jira:agent-interface"]:["read:me","read:account","offline_access","email","read:confluence:agent-interface","write:confluence:agent-interface","search:confluence:agent-interface"])&&sameScopes(review.allowedOrigins,["https://auth.atlassian.com","https://api.atlassian.com"])&&review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient===true&&!unadvertised;if(review.identity?.kind==="linear-openid-teams")return spec.source==="linear"&&url==="https://mcp.linear.app/mcp"&&review.issuer==="https://mcp.linear.app"&&sameScopes(review.scopes,["read","write","openid","email"])&&sameScopes(review.allowedOrigins,["https://mcp.linear.app","https://linear.app"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient;if(review.identity?.kind==="asana-user-workspaces")return spec.source==="asana"&&url==="https://mcp.asana.com/v2/mcp"&&review.issuer==="https://app.asana.com"&&review.scopes.length===0&&sameScopes(review.allowedOrigins,["https://app.asana.com"])&&review.registration?.kind==="broker"&&review.registration.clientId==="1219875673629405"&&review.registration.brokerBase==="https://zortex-auth-9sl.pages.dev"&&review.registration.brokerPath==="asana";if(review.identity?.kind==="clickup-current-user-workspaces")return spec.source==="clickup"&&url==="https://mcp.clickup.com/mcp"&&review.issuer==="https://mcp.clickup.com"&&sameScopes(review.scopes,["read","write"])&&sameScopes(review.allowedOrigins,["https://mcp.clickup.com","https://app.clickup.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient;if(review.identity?.kind==="ticktick-inbox-self")return spec.source==="ticktick"&&url==="https://mcp.ticktick.com"&&review.issuer==="https://ticktick.com"&&sameScopes(review.scopes,["tasks:read","tasks:write"])&&sameScopes(review.allowedOrigins,["https://ticktick.com","https://api.ticktick.com"])&&review.registration?.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient;if(spec.source==="todoist")return url==="https://ai.todoist.net/mcp"&&review.issuer==="https://todoist.com"&&sameScopes(review.scopes,["data:read_write"])&&sameScopes(review.allowedOrigins,["https://todoist.com","https://app.todoist.com"])&&(!review.registration||review.registration.kind==="dcr"&&!unadvertised&&!review.registration.discardReturnedSecretForPublicClient)&&review.identity?.kind===void 0&&review.identity?.tool==="user-info"&&sameScopes(review.identity.subjectPath,["userId"])&&sameScopes(review.identity.labelPath??[],["email"]);return!unadvertised&&!(review.registration?.kind==="dcr"&&review.registration.discardReturnedSecretForPublicClient===true)}async function refreshGrant(snapshot,review,url,caller,issuerDiscovery=false){const custody=vault.bindingCustody,deadline=new AbortController,signal=bound(deadline.signal);const timer=setTimeout(()=>deadline.abort(Error("OAuth refresh deadline exceeded.")),DISCOVERY_TIMEOUT);try{const discoverySignal=AbortSignal.any([signal,caller]);const selected=authorizedCredential(snapshot);if(!("ok"in selected))return selected;if(spec.source==="monday"&&(!review||!isReviewedMondayDefault(url,review)||!acceptsMondayDefaultGrant(snapshot.grant.scopes)))return fail("failed_precondition",`${spec.label} saved scopes do not match its reviewed default grant.`);const issuer=review?.issuer??(isMcpSessionAuthority(snapshot.binding.authority)?snapshot.binding.authority.issuer:void 0);if(issuerDiscovery&&!issuer)return fail("failed_precondition",`${spec.label} refresh requires its original OAuth issuer.`);let server;if(issuerDiscovery){const metadata=await wait(discoverAuthorizationServerMetadata(issuer,{fetchFn:oauthFetch(discoverySignal)}),discoverySignal);if(!metadata)return fail("failed_precondition",`${spec.label} did not publish its original OAuth issuer metadata.`);server={authorizationServerUrl:issuer,authorizationServerMetadata:metadata}}else server=await wait(discoverOAuthServerInfo(url,{fetchFn:oauthFetch(discoverySignal)}),discoverySignal);const originalReview=review??discoveredOAuthReview(url,server);const actualReview={...originalReview,scopes:spec.source==="monday"?[]:[...snapshot.grant.scopes],...!originalReview.registration&&selected.ok.clientAuthentication?{registration:{kind:"pre-registered",clientId:selected.ok.clientId,tokenEndpointAuthMethod:selected.ok.clientAuthentication.method}}:{}};if(actualReview.registration?.kind==="pre-registered"&&(actualReview.registration.allowUnadvertisedPublicClient===true||spec.source==="dropbox")&&!sourceOAuthReviewMatches(actualReview,url))return fail("failed_precondition",`${spec.label} has incompatible public-client refresh settings.`);if(selected.ok.clientAuthentication&&(["box","google-contacts","google-chat","front","hubspot","supabase","coda"].includes(spec.source)||reviewedConfidentialSource(url,actualReview)||reviewedDcrConfidentialSource(url,actualReview))&&!sourceOAuthReviewMatches(actualReview,url)||!matchesOAuthReview(url,actualReview,server,true,selected.ok.clientAuthentication?.method)||snapshot.binding.authority&&(!isMcpSessionAuthority(snapshot.binding.authority)||!matchesSessionAuthority(snapshot.binding.authority,url,server,selected.ok.clientId)))return fail("failed_precondition",`${spec.label} discovery does not match its reviewed authorization policy.`);caller.throwIfAborted();const refreshed=await wait(custody.refreshResource(snapshot,{kind:"resident"},async current=>{const permitted=authorizedCredential(current);if(!("ok"in permitted))return permitted;if(!permitted.ok.refreshToken)return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);try{const requestedAt=Date.now();const clientAuthentication=permitted.ok.clientAuthentication;if(clientAuthentication?.method!==selected.ok.clientAuthentication?.method)return fail("permission_denied",`${spec.label} client authentication changed before refresh.`);const tokens=actualReview.registration?.kind==="broker"?await brokerCall(actualReview.registration.brokerBase,`/${actualReview.registration.brokerPath}/refresh`,{refreshToken:permitted.ok.refreshToken},signal):await wait(refreshAuthorization(server.authorizationServerUrl,{metadata:server.authorizationServerMetadata,clientInformation:{client_id:permitted.ok.clientId,...clientAuthentication?{client_secret:clientAuthentication.secret,token_endpoint_auth_method:clientAuthentication.method}:{}},refreshToken:permitted.ok.refreshToken,...clientAuthentication?{addClientAuthentication:async(headers,params,endpoint)=>{if(String(endpoint)!==server.authorizationServerMetadata.token_endpoint||!(server.authorizationServerMetadata.token_endpoint_auth_methods_supported??["client_secret_basic"]).includes(clientAuthentication.method))throw Error("Selected client authentication changed.");if(clientAuthentication.method==="client_secret_basic")headers.set("Authorization",confidentialBasic(permitted.ok.clientId,clientAuthentication.secret));else{params.set("client_id",permitted.ok.clientId);params.set("client_secret",clientAuthentication.secret)}}}:{},...issuerDiscovery?{}:{resource:new URL(server.resourceMetadata?.resource??resourceUrlFromServerUrl(url).href)},fetchFn:oauthFetch(signal)}),signal);if(clientAuthentication&&protectsCredential(permitted.ok,true)(JSON.stringify(tokens)))return fail("failed_precondition",`${spec.label} refresh returned protected client authentication.`);const scopes=tokens.scope===void 0?permitted.ok.scopes:tokens.scope.split(/\s+/u).filter(Boolean);const salesforce=reviewedRegisteredPublicSource(url,actualReview)==="salesforce";const expiresAt=salesforce?salesforceTokenExpiry(tokens,requestedAt):requestedAt+Number(tokens.expires_in)*1e3;if(!tokens.access_token||tokens.token_type.toLowerCase()!=="bearer"||!sameScopes(scopes,current.grant.scopes)||!salesforce&&(typeof tokens.expires_in!=="number"||!Number.isFinite(tokens.expires_in)||tokens.expires_in<=0)||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()||tokens.refresh_token!==void 0&&!tokens.refresh_token)return fail("failed_precondition",`${spec.label} refresh did not preserve a verified scope and expiry.`);signal.throwIfAborted();return ok({kind:"oauth",credential:{...permitted.ok,accessToken:tokens.access_token,...tokens.refresh_token?{refreshToken:tokens.refresh_token}:{},expiresAt}})}catch{return fail("failed_precondition",`${spec.label} token refresh failed; reconnect this source.`)}}),signal);if("ok"in refreshed||!("err"in refreshed)||refreshed.err.code!=="failed_precondition")return refreshed;const winner=await wait(custody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:snapshot.grant.audience}),signal);if(!("ok"in winner))return winner;const allowed=authorizedCredential(winner.ok);return winner.ok.resource.revision>snapshot.resource.revision&&"ok"in allowed&&(allowed.ok.expiresAt===0||allowed.ok.expiresAt>Date.now()+6e4)?winner:refreshed}catch{return fail(caller.aborted||stop.signal.aborted?"aborted":"failed_precondition",`${spec.label} token refresh did not complete; reconnect this source.`)}finally{clearTimeout(timer)}}async function refreshDeviceGrant(snapshot,auth,caller){const signal=bound(caller),custody=vault.bindingCustody;if(!custody)return fail("failed_precondition",`${spec.label} OAuth access requires durable credential custody.`);if(!validReview(auth.reviewed)||!auth.reviewed.allowedOrigins.includes(httpsUrl(auth.tokenUrl).origin)||snapshot.binding.authority&&(!isMcpSessionAuthority(snapshot.binding.authority)||snapshot.binding.authority.tokenEndpoint!==auth.tokenUrl||snapshot.binding.authority.issuer!==auth.reviewed.issuer))return fail("failed_precondition",`${spec.label} refresh does not match its reviewed authorization policy.`);return custody.refreshResource(snapshot,{kind:"resident"},async current=>{const permitted=authorizedCredential(current);if(!("ok"in permitted))return permitted;if(!permitted.ok.refreshToken)return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);try{const response=await wait(transport(auth.tokenUrl,{method:"POST",redirect:"error",credentials:"omit",signal,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:permitted.ok.clientId,grant_type:"refresh_token",refresh_token:permitted.ok.refreshToken,scope:current.grant.scopes.join(" ")})}),signal);const body=await response.json();const accessToken=typeof body.access_token==="string"?body.access_token:"",tokenType=String(body.token_type??"").toLowerCase();const scopes=body.scope===void 0?[...current.grant.scopes]:String(body.scope).split(/[\s,]+/u).filter(Boolean),seconds=Number(body.expires_in),expiresAt=Date.now()+seconds*1e3;if(!response.ok||!accessToken||tokenType!=="bearer"||!sameScopes(scopes,current.grant.scopes)||!Number.isFinite(seconds)||seconds<=0||!Number.isFinite(expiresAt)||expiresAt<=Date.now())return fail("failed_precondition",`${spec.label} refresh did not preserve a verified scope and expiry.`);if(spec.source==="matrix"){const prefix="urn:matrix:client:device:",device=scopes.find(s=>s.startsWith(prefix))?.slice(prefix.length);if(!device||!matrixUserId(current.binding.identity.subject))return fail("failed_precondition","Matrix refresh needs its original account and device.");await verifyMatrixDevice(transport,signal,accessToken,device,current.binding.identity.subject)}return ok({kind:"oauth",credential:{...permitted.ok,accessToken,...typeof body.refresh_token==="string"&&body.refresh_token?{refreshToken:body.refresh_token}:{},expiresAt}})}catch{return fail("failed_precondition",`${spec.label} token refresh failed; reconnect this source.`)}})}async function checkGrant(current,signal,opened){if(signal.aborted)return fail("aborted",`${spec.label} call was cancelled.`);if(current.pairingRevision!==void 0){if(!vault.joplinFencedRevision)return fail("failed_precondition","Joplin pairing custody is unavailable.");const revision=await wait(vault.joplinFencedRevision(current.account),signal);if(!("ok"in revision))return revision;return revision.ok===current.pairingRevision?ok(void 0):fail("failed_precondition","Joplin pairing changed while the call was pending.")}const expected=current.snapshot;if(!expected)return ok(void 0);try{if(spec.auth.kind==="custodied")return await checkCustodied(spec.source,spec.auth,vault,{snapshot:expected,additionalSnapshots:current.additionalSnapshots??[]},signal);const unchanged=async()=>{if(current.selectionRevision!==void 0){if(!vault.bindingCustody.sourceSelection)return fail("failed_precondition",`${spec.label} selected account custody is unavailable.`);const selected=await wait(vault.bindingCustody.sourceSelection(spec.source),signal);if(!("ok"in selected))return selected;if((selected.ok?.revision??null)!==current.selectionRevision||selected.ok&&selected.ok.bindingId!==expected.binding.id)return fail("failed_precondition",`${spec.label} selected account changed while the call was pending.`)}const latest=await wait(vault.bindingCustody.credentialSnapshot(expected.resource.id,{purpose:"L1",audience:expected.grant.audience}),signal);if(!("ok"in latest))return latest;if(current.selectionRevision!==void 0){const selected=await wait(vault.bindingCustody.sourceSelection(spec.source),signal);if(!("ok"in selected))return selected;if((selected.ok?.revision??null)!==current.selectionRevision||selected.ok&&selected.ok.bindingId!==expected.binding.id)return fail("failed_precondition",`${spec.label} selected account changed while the call was pending.`)}return latest.ok.binding.revision===expected.binding.revision&&latest.ok.grant.id===expected.grant.id&&latest.ok.grant.revision===expected.grant.revision&&latest.ok.grant.scopeEpoch===expected.grant.scopeEpoch&&latest.ok.resource.revision===expected.resource.revision?ok(void 0):fail("failed_precondition",`${spec.label} credential authority changed while the call was pending.`)};const authorized=await unchanged();if(!("ok"in authorized))return authorized;if(isServerSessionAuthority(expected.binding.authority)){if(!opened||spec.auth.kind!=="server-login"||!spec.auth.login.ready)return fail("failed_precondition",`${spec.label} needs its noninteractive upstream session status.`);const ready=spec.auth.login.ready;const check=await wireSignals.run(signal,()=>opened.client.callTool({name:ready.tool,arguments:ready.args??{}},{signal,timeout:IDENTITY_TIMEOUT}));if(Buffer.byteLength(JSON.stringify(check))>MAX_IDENTITY_BYTES)return fail("resource_exhausted",`${spec.label} session status exceeded its bound.`);if(check.isError)return fail("unavailable",`${spec.label} session status could not be confirmed.`);if(!ready.done(check.structuredContent,textOf(check.content)))return fail("unauthenticated",spec.auth.login.instructions??`${spec.label} needs its upstream login; use its connection instructions or QR.`);signal.throwIfAborted();const stillAuthorized=await unchanged();if(!("ok"in stillAuthorized)||!current.nativeIdentity)return stillAuthorized}if(!current.nativeIdentity)return authorized;if(!opened||spec.auth.kind!=="server-login"||!spec.auth.login.identity)return fail("failed_precondition",`${spec.label} native identity cannot be verified.`);const identity=await verifyServerIdentity(opened.client,opened.tools,spec.auth.login.identity,signal);if(identity.accountId!==current.nativeIdentity)return fail("failed_precondition",`${spec.label} signed-in account changed; reconnect the selected account.`);return unchanged()}catch(error){return failure(error,signal)}}async function grant(signal){if(signal.aborted)return fail("aborted",`${spec.label} call was cancelled.`);if(spec.auth.kind==="custodied"){const selected=spec.auth,server=spec.server;const refresh=selected.credentialKind==="oauth"&&selected.oauth?snapshot2=>wait(track(starting,refreshGrant(snapshot2,{issuer:selected.issuer,scopes:selected.requiredScopes,allowedOrigins:selected.oauth.allowedOrigins},server.transport==="http"?server.url:selected.audience,signal,server.transport==="stdio")),signal):void 0;const captured=await captureCustodied(spec.source,selected,vault,signal,refresh);if(!("ok"in captured))return captured;const value=captured.ok,auth=spec.auth;const authorize=async signal2=>{const current2=await checkCustodied(spec.source,auth,vault,value,signal2);if(!("ok"in current2))throw Error("Protected source authority changed before its MCP request.")};const authorityKey2=JSON.stringify([value.snapshot,...value.additionalSnapshots].map(s=>[s.binding.id,s.binding.revision,s.grant.id,s.grant.revision,s.grant.scopeEpoch,s.resource.id,s.resource.revision]));const credential2=value.snapshot.material.kind==="oauth"?value.snapshot.material.credential:void 0;if(credential2?.clientAuthentication&&!validClientAuthentication(credential2.clientAuthentication))return fail("failed_precondition",`${spec.label} client authentication is unreadable; reconnect this source.`);return ok({grant:{...value.token===void 0?{}:{token:value.token},environment:value.environment,authorityKey:authorityKey2,authorize,...credential2?.clientAuthentication?{protect:protectsCredential(credential2)}:{}},account:value.account,snapshot:value.snapshot,additionalSnapshots:value.additionalSnapshots})}if(spec.auth.kind==="none")return ok({grant:{},account:"local"});const matrixFields=spec.source==="matrix"&&spec.auth.kind==="fields";const oauth=spec.auth.kind==="mcp-oauth"||spec.auth.kind==="oauth-device"||spec.auth.kind==="zendesk-oauth";if(oauth&&!vault.bindingCustody?.sourceSelection)return fail("failed_precondition",`${spec.label} selected account custody is unavailable.`);const connection=await vault.connection(custodySource);if(!("ok"in connection))return connection;const nativeMatrix=matrixFields&&!!connection.ok?.authority;if(nativeMatrix&&(!matrixUserId(connection.ok?.accountId)||connection.ok.account!==connection.ok.accountId))return fail("permission_denied","Matrix selected account identity is unavailable.");if(nativeMatrix&&!vault.bindingCustody?.sourceSelection)return fail("failed_precondition","Matrix native account selection is unavailable.");const selection=oauth||nativeMatrix?await vault.bindingCustody.sourceSelection(spec.source):void 0;if(selection&&!("ok"in selection))return selection;const selectionRevision=selection&&"ok"in selection?selection.ok?.revision??null:void 0;if(!connection.ok||connection.ok.state!=="connected"){if(spec.publicTools?.length)return ok({grant:{fields:{},public:true},account:"public (not connected)"});return fail("unauthenticated",`Connect ${spec.label} first (connector.connect with source ${spec.source}).`)}if(spec.auth.kind==="server-login"){const opaque=!spec.auth.login.identity;const custody2=vault.bindingCustody;if(!custody2||(opaque?connection.ok.accountId!==void 0||!isServerSessionAuthority(connection.ok.authority):!connection.ok.accountId))return fail("failed_precondition",`${spec.label} needs its selected upstream account or server session binding.`);const resolved2=await custody2.resolve({kind:"legacy-source",source:spec.source});if(!("ok"in resolved2))return resolved2;if(resolved2.ok.kind!=="resolved")return fail("failed_precondition",`${spec.label} needs one explicit native account binding.`);const captured=await custody2.credentialSnapshot(nativeResourceId(resolved2.ok.binding.id),{purpose:"L1",audience:nativeAudience});if(!("ok"in captured))return captured;const snapshot2=captured.ok;if(snapshot2.material.kind!=="local-no-secret"||snapshot2.resource.kind!=="local-no-secret"||snapshot2.resource.owner.kind!=="resident"||snapshot2.binding.identity.issuer!==spec.source||snapshot2.binding.identity.subject!==connection.ok.accountId||opaque&&(!isServerSessionAuthority(snapshot2.binding.authority)||snapshot2.binding.authority.resource!==nativeAudience))return fail("failed_precondition",`${spec.label} native login custody does not match its selected account.`);return ok({grant:{authorityKey:JSON.stringify([snapshot2.binding.id,snapshot2.binding.revision,snapshot2.grant.revision,snapshot2.resource.revision])},account:snapshot2.binding.account,snapshot:snapshot2,...snapshot2.binding.identity.subject?{nativeIdentity:snapshot2.binding.identity.subject}:{}})}let credential;if(spec.auth.kind==="fields"&&!(matrixFields&&connection.ok.authority)||!connection.ok.accountId&&!connection.ok.authority){const legacyBefore=spec.source!=="joplin"&&spec.auth.kind==="fields"&&!connection.ok.accountId&&!connection.ok.authority&&spec.liveRead&&vault.legacyRevision?await vault.legacyRevision(custodySource):void 0;if(legacyBefore&&!("ok"in legacyBefore))return legacyBefore;let pairingRevision;if(spec.source==="joplin"){if(!vault.joplinFencedSnapshot)return fail("failed_precondition","Joplin pairing custody is unavailable.");const paired=await vault.joplinFencedSnapshot(connection.ok.account);if(!("ok"in paired))return paired;credential=paired.ok.credential;pairingRevision=paired.ok.revision;if(JSON.stringify(paired.ok.connection)!==JSON.stringify(connection.ok))return fail("failed_precondition","Joplin pairing changed; retry.")}else{const stored=await vault.credential(custodySource);if(!("ok"in stored))return stored;credential=stored.ok}if(isSignedInBrowserCredential(credential)){if(spec.publicTools?.length)return ok({grant:{fields:{},public:true},account:connection.ok.account});return fail("failed_precondition",`${spec.label} is connected through Chrome for reading. Connect it from its connection page to use its actions.`)}if(spec.auth.kind==="fields"){try{if(credential.clientId!=="mcp-fields")throw Error("Not a stored fields credential.");const fields=JSON.parse(credential.accessToken),keys=spec.auth.fields.map(field=>field.key);if(!fields||typeof fields!=="object"||Array.isArray(fields)||Object.keys(fields).length!==keys.length||Object.keys(fields).some(key=>!keys.includes(key))||keys.some(key=>{const value=fields[key];return typeof value!=="string"||!value||value.length>4096||/[\u0000-\u001f\u007f-\u009f]/u.test(value)}))throw Error("Stored fields do not match this source.");const values=fields;if((spec.auth.tokenField||spec.auth.accountBinding==="endpoint")&&connection.ok.account!==spec.auth.account(values))throw Error("Stored fields belong to another selected endpoint.");const legacyAfter=legacyBefore&&vault.legacyRevision?await vault.legacyRevision(custodySource):void 0;if(legacyAfter&&!("ok"in legacyAfter))return legacyAfter;if(legacyBefore&&(!("ok"in legacyAfter)||!legacyBefore.ok||legacyBefore.ok!==legacyAfter.ok))return fail("failed_precondition",`${spec.label} connection changed; retry the check.`);return ok({grant:{...fieldsGrant(values),...pairingRevision===void 0?{}:{authorityKey:`joplin-pairing:${pairingRevision}`}},account:connection.ok.account,...pairingRevision===void 0?{}:{pairingRevision},...legacyBefore&&"ok"in legacyBefore&&legacyBefore.ok?{legacyRevision:legacyBefore.ok}:{}})}catch{return fail("failed_precondition",`${spec.label} grant is unreadable; reconnect this source.`)}}}const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition",`${spec.label} OAuth access requires durable credential custody.`);const resolved=await custody.resolve({kind:"selected-source",source:spec.source});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved")return fail("failed_precondition",`${spec.label} needs one explicit account binding.`);let current;try{current=await wait(custody.credentialSnapshot(oauthCredentialResourceId(resolved.ok.binding.id),{purpose:"L1",audience:connection.ok.authority?.resource??connection.ok.provider}),signal)}catch(error){return failure(error,signal)}if(!("ok"in current))return current;const allowed=authorizedCredential(current.ok);if(!("ok"in allowed))return allowed;let snapshot=current.ok;credential=allowed.ok;const selectedBeforeRefresh=await checkGrant({grant:{},account:snapshot.binding.account,snapshot,...selectionRevision===void 0?{}:{selectionRevision}},signal);if(!("ok"in selectedBeforeRefresh))return selectedBeforeRefresh;if(matrixFields&&(snapshot.binding.identity.subject!==connection.ok.accountId||!matrixUserId(snapshot.binding.identity.subject)||!selectedResourceMatches(snapshot.binding.authority)||credential.clientAuthentication||credential.scopes.length!==2||!credential.scopes.includes("urn:matrix:client:api:*")||!credential.scopes.some(scope=>/^urn:matrix:client:device:[a-f0-9]{32}$/u.test(scope))))return fail("permission_denied","Matrix selected account or device permission changed.");if(snapshot.binding.authority&&!selectedResourceMatches(snapshot.binding.authority))return fail("permission_denied",`${spec.label} selected MCP session belongs to another resource.`);if(credential.expiresAt>0&&credential.expiresAt<=Date.now()+6e4){if(spec.auth.kind==="mcp-oauth"&&spec.auth.reviewed?.identity?.kind==="openrouter-current-key")return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);if(!credential.refreshToken)return fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`);const review=spec.auth.kind==="fields"||spec.auth.kind==="zendesk-oauth"?void 0:spec.auth.reviewed;if(spec.auth.kind!=="zendesk-oauth"&&(review&&!validReview(review)||!review&&!snapshot.binding.authority))return fail("failed_precondition",`${spec.label} refresh requires its original OAuth authority.`);let refreshed;try{refreshed=await wait(track(starting,nativeMatrix?refreshDeviceGrant(snapshot,{tokenUrl:matrixTokenUrl,reviewed:{issuer:matrixIssuer,scopes:credential.scopes,allowedOrigins:[new URL(matrixIssuer).origin]}},signal):spec.auth.kind==="zendesk-oauth"?refreshZendeskGrant(snapshot,spec.auth,signal):spec.auth.kind==="oauth-device"?refreshDeviceGrant(snapshot,spec.auth,signal):spec.server.transport==="http"?refreshGrant(snapshot,review,spec.server.url,signal):Promise.resolve(fail("failed_precondition",`${spec.label} grant expired; reconnect this source.`))),signal)}catch(error){return failure(error,signal)}if(!("ok"in refreshed))return refreshed;const allowed2=authorizedCredential(refreshed.ok);if(!("ok"in allowed2))return allowed2;snapshot=refreshed.ok;credential=allowed2.ok}const authorityKey=JSON.stringify([snapshot.binding.id,snapshot.binding.revision,snapshot.grant.revision,snapshot.resource.revision,...selectionRevision===void 0?[]:[selectionRevision]]);const access={grant:{token:credential.accessToken,authorityKey,...credential.clientAuthentication||spec.auth.kind==="zendesk-oauth"?{protect:protectsCredential(credential)}:{}},account:snapshot.binding.account,snapshot,...selectionRevision===void 0?{}:{selectionRevision}};const selectedAfterRefresh=await checkGrant(access,signal);if(!("ok"in selectedAfterRefresh))return selectedAfterRefresh;access.grant.authorize=async selectedSignal=>{const checked=await checkGrant(access,selectedSignal);if(!("ok"in checked))throw Error("MCP session authority changed before dispatch.")};return ok(access)}function failure(error,signal){if(signal.aborted)return fail("aborted",`${spec.label} call was cancelled.`);if(spec.auth.kind==="custodied")return fail("unavailable",`${spec.label} did not complete the request.`);const message=String(error?.message??error).slice(0,300);const status=error?.status;if(status===401||status===403||/unauthori[sz]ed|invalid_token|401/i.test(message))return fail("failed_precondition",`${spec.label} refused the grant; reconnect this source.`);if(status===429||/\b429\b|rate limit/i.test(message))return fail("resource_exhausted",`${spec.label} rate limit reached; retry later.`);return fail("unavailable",`${spec.label} did not complete the request.`)}async function listed(){if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);const signal=bound();const g=await grant(signal);if(!("ok"in g))return g;try{const opened=await open(g.ok.grant,signal),current=await checkGrant(g.ok,signal,opened);return"ok"in current?ok(opened.tools):current}catch(error){return failure(error,signal)}}const actions={reportsActionAccess:true,async catalog(input={}){const limit=input.limit??50,cursor=input.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid.");const base={source:spec.source,level:1,label:spec.label,auth:info.auth,origin:spec.origin};const tools=await listed();if(!("ok"in tools))return tools;const query=typeof input.query==="string"?input.query.toLowerCase():"";const rows=tools.ok.filter(a=>!query||a.name.toLowerCase().includes(query)||a.description.toLowerCase().includes(query)).map(({tool:_,...row})=>row);return ok({...base,actions:rows.slice(cursor,cursor+limit),total:rows.length,...cursor+limit<rows.length?{nextCursor:cursor+limit}:{}})},async method(name){const tools=await listed();if(!("ok"in tools))return tools;const found=tools.ok.find(a=>a.name===name);if(!found)return fail(spec.publicTools?.length&&!await vault.connection(custodySource).then(c=>"ok"in c&&c.ok?.state==="connected")?"unauthenticated":"not_found",`${spec.label} has no action '${name}'${spec.publicTools?.length?" available without a connection; connect with connector.connect source "+spec.source:""}.`);const{tool:_,...row}=found;return ok({...row,source:spec.source,level:1})},invoke(name,input,options={}){return invokeAction(name,input,options)}};function invokeAction(name,input,options={},readOnly=false){const operation=startOperationalStep(deps.metrics,{source:spec.source,phase:spec.source==="cua"?"computer":"connector",action:"execute"});if(pending.size>=MAX_PENDING){operation.finish({state:"failed",reason:"not_available"});return Promise.resolve(fail("resource_exhausted",`${spec.label} has reached its active call bound.`))}const task=operation.run(async()=>{if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);if(input===null||typeof input!=="object"||input.body!==void 0||input.media!==void 0)return fail("invalid_argument","Level 1 actions take params only.");const params=input.params??{};if(params===null||typeof params!=="object"||Array.isArray(params))return fail("invalid_argument","params must be an object");if(JSON.stringify(params).length>MAX_PARAMS)return fail("invalid_argument","params are too large");const signal=bound(options.signal);const publicLogin=spec.auth.kind==="server-login"&&spec.publicTools?.some(tool=>name===`${spec.source}.${tool}`);const g=publicLogin?ok({grant:{fields:{},public:true},account:"public (not connected)"}):await grant(signal);if(!("ok"in g))return g;const actionGrant=g.ok;let actionEpoch;let guardedReadStarted=false;let used;const matchesAction=()=>actionEpoch!==void 0&&actionEpoch===checkEpoch&&session?.client===used&&(!selectedReadinessFence()||!!readiness&&readiness.session.client===used&&readiness.selectionRevision===actionGrant.selectionRevision&&JSON.stringify(readiness.authority)===JSON.stringify(readinessAuthority(actionGrant)));const isCurrent=!actionGrant.grant.public&&(!!actionGrant.snapshot||actionGrant.pairingRevision!==void 0)?async()=>{if(!matchesAction()||!actionGrant.snapshot&&actionGrant.pairingRevision===void 0)return false;const checked=await checkGrant(actionGrant,signal);return"ok"in checked&&matchesAction()}:void 0;const publicCatalog=(spec.source==="appstore"||spec.group==="Connector / Public data")&&spec.auth.kind==="none"&&name.startsWith(spec.source+".")&&Object.hasOwn(spec.reviewedReadTools??{},name.slice(spec.source.length+1));try{options.onActionAccess?.(actionGrant.grant.public||publicCatalog?"public":"account",publicCatalog?void 0:isCurrent)}catch{}try{const{client,tools}=await open(g.ok.grant,signal);used=client;let epoch=checkEpoch;actionEpoch=epoch;const row=tools.find(a=>a.name===name);if(readOnly&&(tools.filter(a=>a.name===name).length!==1||row?.effect!=="read"))return fail("failed_precondition",`${spec.label} live-read tool is not uniquely declared readonly.`);if(!row)return g.ok.grant.public?fail("unauthenticated",`${spec.label}: '${name}' needs a connection; without one only ${spec.publicTools.map(t=>`${spec.source}.${t}`).join(", ")} work. Connect with connector.connect source ${spec.source}.`):fail("not_found",`${spec.label} has no action '${name}'.`);const current=await checkGrant(g.ok,signal,{client,tools});if(!("ok"in current))return current;const requestParams=structuredClone(params);const wpProfile=spec.source==="wordpress"&&row.tool==="execute"&&Object.keys(requestParams).length===2&&requestParams.name==="wpcom/user-profile"&&!!requestParams.input&&typeof requestParams.input==="object"&&!Array.isArray(requestParams.input)&&Object.keys(requestParams.input).length===0;const readinessRead=row.effect==="read"||wpProfile;if(spec.validateParams){const valid=spec.validateParams(row.tool,Object.freeze(structuredClone(requestParams)));if(!("ok"in valid))return valid}const validationParams=spec.validateResult?Object.freeze(structuredClone(requestParams)):void 0;if(guardedReadiness()&&readinessRead&&row.tool!=="tool_guide"&&!g.ok.grant.public){const zoteroProbe=spec.source==="zotero"&&row.tool==="zotero_get_recent"&&validationParams?.limit===1&&(validationParams.collection_key===void 0||validationParams.collection_key===null);if(spec.source==="zotero"&&!zoteroProbe)checkEpoch++;else clearReadiness();epoch=checkEpoch;actionEpoch=epoch;guardedReadStarted=true;guardedReadsInFlight++}const adapted=await spec.adaptInvoke?.(row.tool,requestParams,g.ok.grant,{signal,fetch:transport});const result=adapted?{content:[{type:"text",text:JSON.stringify(adapted.structured)}],structuredContent:adapted.structured}:await wireSignals.run(signal,()=>client.callTool({name:row.tool,arguments:requestParams},{signal,timeout:CALL_TIMEOUT}));if(closed)return fail("unavailable",`${spec.label} source was disabled before its reply.`);const completed=await checkGrant(g.ok,signal,{client,tools});if(!("ok"in completed))return completed;const text=textOf(result.content);if(result.isError){if(guardedReadiness()&&readinessRead&&row.tool!=="tool_guide"&&epoch===checkEpoch&&session?.client===client)clearReadiness();if(spec.source==="matrix"){if(text==="ZORTEX_MATRIX_READ_FAILURE:auth")return fail("failed_precondition","Matrix rejected authorization; check the grant.");if(text==="ZORTEX_MATRIX_READ_FAILURE:rate")return fail("resource_exhausted","Matrix reported a rate limit; retry later.");if(text==="ZORTEX_MATRIX_READ_FAILURE:upstream")return fail("unavailable","Matrix reported a server error.");if(text==="ZORTEX_MATRIX_READ_FAILURE:network")return fail("unavailable","Matrix could not be reached.")}if(spec.source==="coda"){const prefix=text.trimStart().slice(0,128);if(/^rate limit(?: exceeded| reached)?(?:[.:\s]|$)/i.test(prefix))return fail("resource_exhausted",`${spec.label} reported a rate limit; retry later.`);if(/^unauthori[sz]ed(?:[.:\s]|$)/i.test(prefix))return fail("failed_precondition",`${spec.label} reported an authorization error; check the grant.`)}if(spec.source==="coda"&&process.env.ZORTEX_CODA_ERROR_SHAPE_DIAGNOSTICS==="1"){const hasText=result.content.some(block=>block.type==="text"&&block.text.length>0);const hasStructured=result.structuredContent!==void 0;const shape=hasText?hasStructured?"text+structured":"text":hasStructured?"structured":"empty";const first=hasText?text.trimStart().charAt(0):"";const format=!hasText?"empty":first==="{"?"object-like":first==="["?"array-like":"other";return fail("unavailable",`${spec.label} reported a tool error. Diagnostic shape=${shape}; text-format=${format}.`)}return fail("unavailable",`${spec.label} reported a tool error.`)}const out={text,...result.structuredContent?{structured:result.structuredContent}:{},...spec.preserveContent?{content:structuredClone(result.content)}:{}};const encoded=JSON.stringify(out);const invalidateZoteroFailure=()=>{if(spec.source==="zotero"&&guardedReadStarted&&epoch===checkEpoch&&session?.client===client)clearReadiness()};if(Buffer.byteLength(encoded)>MAX_RESULT){invalidateZoteroFailure();return fail("resource_exhausted",`${spec.label} reply exceeds ${MAX_RESULT} bytes.`)}if(containsProtectedMaterial(encoded,g.ok.grant)){invalidateZoteroFailure();return fail("data_loss",`${spec.label} returned protected credential material instead of a usable record.`)}if(spec.validateResult){const valid=spec.validateResult(row.tool,out,validationParams);if(!("ok"in valid)){invalidateZoteroFailure();return valid}}if(spec.source==="zotero"&&row.effect==="read"&&row.tool==="zotero_get_recent"&&validationParams?.limit===1&&(validationParams.collection_key===void 0||validationParams.collection_key===null)&&!g.ok.grant.public){const records=spec.liveRead?.records(spec.source,out.structured,out.text);if(records)rememberReadiness(g.ok,{client,tools},{state:"succeeded",returned:records.length},epoch,signal)}if((spec.source==="ticktick"||spec.source==="airtable"||spec.source==="gitlab"||spec.source==="monday"||spec.source==="linear"||spec.source==="jira"||spec.source==="github"||spec.source==="confluence"||spec.source==="miro"||guardedReadiness()&&spec.source!=="zotero"&&row.tool!=="tool_guide"&&(spec.source!=="wordpress"||row.tool==="zortex_read_profile"||wpProfile))&&readinessRead&&!g.ok.grant.public){let returned,replyError=false;if(spec.source==="monday"&&row.tool==="list_workspaces"){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0;if(!replyError&&Array.isArray(v.data))returned=v.data.length}}catch{}}if(spec.source==="plecs"||spec.source==="solidworks"||spec.source==="lattics"||spec.source==="jetbrains"||spec.source==="eclipse"||spec.source==="multisim"||spec.source==="stm32cubemx")returned=spec.liveRead?.records(spec.source,out.structured,out.text)?.length;if(spec.source==="confluence"&&row.tool==="searchConfluence"){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0}if(value&&typeof value==="object"&&!Array.isArray(value)&&!replyError){const data=value.data;if(data&&typeof data==="object"&&!Array.isArray(data)&&Array.isArray(data.results))returned=data.results.length}}catch{}}if(spec.source==="wordpress"&&(row.tool==="zortex_read_profile"||wpProfile)){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0;const profile=v.profile;const id=profile&&typeof profile==="object"&&!Array.isArray(profile)?profile.id:void 0;if(!replyError&&(typeof id==="string"&&id.trim()||typeof id==="number"&&Number.isSafeInteger(id)&&id>0))returned=1}}catch{}}if(spec.source==="calendly"&&row.tool==="users-get_current_user"){try{const value=out.structured??JSON.parse(out.text);if(value&&typeof value==="object"&&!Array.isArray(value)){const v=value;replyError=Boolean(v.error)||Array.isArray(v.errors)&&v.errors.length>0;const resource=v.resource;const uri=resource&&typeof resource==="object"&&!Array.isArray(resource)?resource.uri:void 0;if(!replyError&&typeof uri==="string"&&uri.trim())returned=1}}catch{}}if(replyError){if(epoch===checkEpoch&&session?.client===client)clearReadiness();return fail("unavailable",`${spec.label} reported a read error.`)}if(spec.source==="wordpress"&&returned===void 0){if(epoch===checkEpoch&&session?.client===client)clearReadiness()}else rememberReadiness(g.ok,{client,tools},{state:"succeeded",...returned===void 0?{}:{returned}},epoch,signal)}return ok({source:spec.source,action:name,effect:row.effect,account:g.ok.account,...g.ok.grant.public?{access:"public"}:{},result:out})}catch(error){if(!signal.aborted&&used&&session?.client===used&&(!guardedReadiness()||actionEpoch===checkEpoch))await dropSession();return failure(error,signal)}finally{if(guardedReadStarted)guardedReadsInFlight--}});return track(pending,task.then(result=>{operation.finish("err"in result?{state:options.signal?.aborted||result.err.code==="aborted"?"cancelled":"failed",reason:operationalReason(result.err.code)}:{state:"completed"});return result},error=>{operation.finish({state:options.signal?.aborted?"cancelled":"failed",reason:operationalReason(error instanceof Error?error.message:void 0)});throw error}))}async function probe(candidate,signal,login,savedAccessOnly=false,onHandoff,deadline,closeOwned){signal.throwIfAborted();const client=createClient();let interactiveStarted=false,cleaned=false,loginStep,readinessAttempt=0;const browserFacts=login?.browserProfile?{route:"upstream_browser",profile:login.browserProfile,downloadObservation:"unavailable"}:{};const close=async()=>{if(interactiveStarted&&login?.cleanup&&!cleaned){const cleanupSignal=AbortSignal.timeout(CALL_TIMEOUT);const step=startOperationalStep(deps.metrics,{source:spec.source,phase:"connector",action:"cleanup",...browserFacts});try{const result=await step.run(()=>wireSignals.run(cleanupSignal,()=>client.callTool({name:login.cleanup.tool,arguments:login.cleanup.args??{}},{signal:cleanupSignal,timeout:CALL_TIMEOUT})));if(result.isError||Buffer.byteLength(JSON.stringify(result))>MAX_IDENTITY_BYTES||!login.cleanup.done(result.structuredContent,textOf(result.content)))throw Error("Upstream login cleanup was not confirmed.");cleaned=true;step.finish({state:"completed"})}catch(error){step.finish({state:"failed",reason:"browser_cleanup_failed"});throw error}}await client.close()};try{await candidate.authorize?.(signal);signal.throwIfAborted();await wireSignals.run(signal,()=>client.connect(wire(candidate),{signal}));if(login){const started=Date.now();const authenticated=async()=>{const step=startOperationalStep(deps.metrics,{source:spec.source,phase:"connector",action:"readiness",attempt:++readinessAttempt,...browserFacts});try{const check=await step.run(()=>client.callTool({name:login.ready.tool,arguments:login.ready.args??{}},{signal,timeout:CALL_TIMEOUT}));if(Buffer.byteLength(JSON.stringify(check))>MAX_IDENTITY_BYTES)throw Error("Server login status exceeded its bound.");const ready=!check.isError&&login.ready.done(check.structuredContent,textOf(check.content));const decision=interactiveStarted?{}:{loginDecision:ready?"reuse":savedAccessOnly||!login.tool?"not_available":"start_login"};step.finish({state:"completed",...decision});return ready}catch(error){step.finish({state:signal.aborted?"cancelled":"failed",reason:operationalReason(error instanceof Error?error.message:void 0)});throw error}};let done=login.ready?await authenticated():false;if(!done){if(savedAccessOnly||!login.tool)throw new ServerLoginRequired(login.instructions);interactiveStarted=true;loginStep=startOperationalStep(deps.metrics,{source:spec.source,phase:"connector",action:"login",loginDecision:"start_login",...browserFacts});if(login.handoff?.openingInstructions){if(!onHandoff)throw Error("Server login requires an owned handoff.");onHandoff(login.handoff.openingInstructions)}const r=await loginStep.run(()=>client.callTool({name:login.tool,arguments:login.args??{}},{signal,timeout:LOGIN_TIMEOUT}));if(r.isError)throw new Error(textOf(r.content).slice(0,300)||"login did not complete");if(login.handoff?.openingInstructions&&r.structuredContent?.success===false)throw new Error("The upstream browser login failed or was cancelled.");done=!login.ready;if(login.handoff){if(Buffer.byteLength(JSON.stringify(r))>MAX_IDENTITY_BYTES)throw Error("Server login challenge exceeded its bound.");done=await authenticated();if(!done){const instructions=login.handoff.instructions(r.structuredContent,textOf(r.content));if(typeof instructions!=="string"||!instructions.trim()||Buffer.byteLength(instructions)>2048||/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(instructions))throw Error("Server login did not provide valid bounded instructions.");if(!onHandoff)throw Error("Server login requires an owned handoff.");const image=login.handoff.image?authorizationImage(login.handoff.image(r.content)):void 0;if(login.handoff.image&&!image)throw Error("Server login did not provide a valid bounded PNG challenge.");const device=login.handoff.device?.(r.structuredContent,textOf(r.content));if(login.handoff.device){if(!device||typeof device.authorizationUrl!=="string"||device.authorizationUrl.length>2048||typeof device.userCode!=="string"||!/^[A-Z0-9-]{4,32}$/i.test(device.userCode))throw Error("Server login did not provide a supported device challenge.");const url=new URL(device.authorizationUrl);if(url.protocol!=="https:"||url.username||url.password||url.search||url.hash)throw Error("Server login did not provide a supported device challenge.")}onHandoff(instructions,image,device);loginStep.mark({state:"waiting",reason:"login_required"})}}}while(!done){if(Date.now()>=(deadline??started+LOGIN_TIMEOUT))throw new Error(`${spec.label} login was not completed within 10 minutes.`);done=await authenticated();if(!done)await new Promise((resolve,reject)=>{const abort=()=>{clearTimeout(timer);reject(new Error("aborted"))},timer=setTimeout(()=>{signal.removeEventListener("abort",abort);resolve()},LOGIN_POLL);signal.addEventListener("abort",abort,{once:true});if(signal.aborted)abort()})}}const listed2=await wireSignals.run(signal,()=>client.listTools({},{signal}));const identity=login?.identity?await verifyServerIdentity(client,listed2.tools.map(tool=>toolRow(spec.source,tool)),login.identity,signal):void 0;loginStep?.finish({state:"completed"});return{count:listed2.tools.length,...identity?{identity}:{}}}catch(error){loginStep?.finish({state:signal.aborted?"cancelled":"failed",reason:operationalReason(error instanceof Error?error.message:void 0)});throw error}finally{if(closeOwned)await closeOwned(close);else await close().catch(()=>{})}}function observeLoginOwner(owner){if(!owner.settled){owner.operation.mark({state:"unknown",reason:"browser_cleanup_failed"});return}owner.operation.finish({state:owner.job.state==="connected"?"completed":owner.job.state==="cancelled"?"cancelled":"failed",...owner.job.state==="connected"?{}:{reason:operationalReason(owner.job.error?.code)}})}function retryLoginCleanup(owner){if(!owner.finished||!owner.cleanup&&!owner.browserCleanupPending||owner.cleaning)return;const release=async()=>{if(owner.cleanup)try{await owner.cleanup();delete owner.cleanup}catch{}if(owner.browserCleanup)try{await owner.browserCleanup();delete owner.browserCleanup;owner.browserCleanupPending=false}catch{}owner.settled=!owner.cleanup&&!owner.browserCleanupPending;observeLoginOwner(owner)};owner.cleaning=track(cleanup,owner.operation.run(release).finally(()=>{delete owner.cleaning}))}async function connectServerHandoff(login,options){if(options.expectedBinding!==void 0)return fail("failed_precondition","This upstream session requires its existing unambiguous source binding.");const caller=bound(options.signal);if(loginOwner&&!loginOwner.settled){if(loginOwner.job.state!=="waiting-user")return fail("failed_precondition",`${spec.label} is still closing its previous login.`);const reused=loginOwner.operation.run(()=>startOperationalStep(deps.metrics,{source:spec.source,phase:"connector",action:"reuse",loginDecision:"reuse"}));reused.finish({state:"completed"});if(!loginOwner.job.automationActive&&!loginOwner.job.browserContinuation)loginOwner.resume?.();await wait(loginOwner.ready,caller);return ok({...loginOwner.job})}const job={id:randomUUID(),source:spec.source,state:"waiting-user",automationActive:true,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+LOGIN_TIMEOUT).toISOString()};const operation=startOperationalStep(deps.metrics,{source:spec.source,phase:"connector",action:"connect",...login.browserProfile?{route:"upstream_browser",profile:login.browserProfile,downloadObservation:"unavailable"}:{}});let publish;const ready=new Promise(resolve=>{publish=resolve}),owner={job,operation,stop:new AbortController,settled:false,finished:false,ready,publish:()=>publish(ok({...job}))};loginOwner=owner;jobs.set(job.id,job);const clear=()=>{delete job.automationActive;delete job.browserContinuation;delete job.instructions;delete job.authorizationUrl;delete job.authorizationOrigin;delete job.authorizationImage;delete job.devicePrompt};const cancel=()=>{if(job.state==="waiting-user")job.state="cancelled";clear();owner.stop.abort();owner.publish()};const expire=()=>{if(job.state!=="waiting-user")return;job.state="failed";job.error={code:"authorization_timeout",message:"Upstream login timed out. Start a new connection."};clear();owner.stop.abort();owner.publish()};const timer=setTimeout(expire,LOGIN_TIMEOUT);timer.unref();options.signal?.addEventListener("abort",cancel,{once:true});const signal=bound(owner.stop.signal);void track(starting,operation.run(async()=>{try{signal.throwIfAborted();const previous=await vault.connection(custodySource);signal.throwIfAborted();const selected="ok"in previous&&previous.ok&&options.automatic!==false?await inspectSelectedAuthority(signal):previous;if(!("ok"in selected)){job.state="failed";job.error="err"in selected?{code:selected.err.code,message:selected.err.message}:{code:"failed_precondition",message:"The selected upstream session is unavailable."};return}await dropSession();signal.throwIfAborted();const native=await probe({},signal,login,options.savedAccessOnly===true,(instructions,image,device)=>{signal.throwIfAborted();job.instructions=instructions;if(image)job.authorizationImage=image;if(instructions!==login.handoff?.openingInstructions)delete job.automationActive;job.error={code:"login_required",message:"Continue the active upstream transaction with the available tools."};operation.mark({state:"waiting",reason:"login_required"});if(device){job.authorizationUrl=device.authorizationUrl;job.authorizationOrigin=new URL(device.authorizationUrl).origin;job.devicePrompt={kind:"device-code",userCode:device.userCode};owner.resume=()=>{if(job.state!=="waiting-user"||signal.aborted||job.automationActive||job.browserContinuation)return;delete job.error;void track(starting,owner.operation.run(()=>continueAuthorizationWithBrowser(job,device.authorizationUrl,[new URL(device.authorizationUrl).origin],signal,deps.actions,{code:device.userCode})).then(async result=>{if(result?.cleanup){if(result.close)owner.browserCleanup=result.close;owner.browserCleanupPending=true}if(job.state==="waiting-user"&&!signal.aborted){if(result?.code==="authorization_callback_missing"){job.automationActive=true;delete job.error}else job.error=result?{code:result.code,message:result.message}:automaticError("browser_driver_unavailable");owner.publish()}if(result?.cleanup)try{await result.cleanup;owner.browserCleanupPending=false;delete owner.browserCleanup;if(owner.finished&&!owner.cleanup){owner.settled=true;observeLoginOwner(owner)}}catch{}}))};owner.resume()}owner.publish()},Date.parse(job.expiresAt),async close=>{owner.cleanup=close;await owner.cleanup();delete owner.cleanup});signal.throwIfAborted();const identity=native.identity??{account:`${spec.label} session`},saved=await saveServerIdentity(identity,signal,options.automatic!==false);if(!("ok"in saved)){job.state="failed";job.error="err"in saved?{code:saved.err.code,message:saved.err.message}:{code:"failed_precondition",message:"The upstream session could not be saved."};return}signal.throwIfAborted();job.state="connected";job.account=identity.account;delete job.error}catch(error){if(job.state==="waiting-user"){if(Date.now()>=Date.parse(job.expiresAt))expire();else if(signal.aborted)job.state="cancelled";else{job.state="failed";const failed=failure(error,signal);job.error=error instanceof ServerLoginRequired?{code:"login_required",message:error.message||"Sign in through the upstream application."}:"err"in failed?{code:failed.err.code,message:failed.err.message}:{code:"unavailable",message:"Upstream login did not complete."}}}}finally{clearTimeout(timer);options.signal?.removeEventListener("abort",cancel);if(job.state!=="waiting-user"){clear();owner.stop.abort()}owner.finished=true;owner.settled=!owner.cleanup&&!owner.browserCleanupPending;observeLoginOwner(owner);owner.publish()}}));if(options.signal?.aborted)cancel();return wait(ready,caller)}async function verifyServerIdentity(client,tools,review,signal){const matches=tools.filter(tool=>tool.tool===review.tool);if(matches.length!==1||matches[0].effect!=="read")throw Error("Native identity tool is not uniquely declared readonly.");const result=await wireSignals.run(signal,()=>client.callTool({name:review.tool,arguments:{}},{signal,timeout:IDENTITY_TIMEOUT}));if(result.isError)throw Error("Native identity verification failed.");let value=result.structuredContent;if(review.format==="json-text"){const content=result.content;if(content.length!==1||content[0]?.type!=="text"||typeof content[0].text!=="string"||Buffer.byteLength(content[0].text)>MAX_IDENTITY_BYTES)throw Error("Native identity response is invalid or exceeds its limit.");try{value=JSON.parse(content[0].text)}catch{throw Error("Native identity response is not JSON.")}}else if(Buffer.byteLength(JSON.stringify(value)??"")>MAX_IDENTITY_BYTES)throw Error("Native identity response exceeds its limit.");const accountId=identityValue(value,review.subjectPath),account=review.labelPath?identityValue(value,review.labelPath):accountId;if(/[\u0000-\u001f\u007f]/u.test(accountId+account))throw Error("Native identity fields are invalid.");signal.throwIfAborted();return{account,accountId}}async function saveServerIdentity(identity,signal,automatic=false){const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition",`${spec.label} upstream login requires durable credential custody.`);const previous=await vault.connection(custodySource);if(!("ok"in previous))return previous;if(previous.ok&&previous.ok.accountId===void 0&&!isServerSessionAuthority(previous.ok.authority))return fail("failed_precondition",`${spec.label} has an unattributed legacy account; select its verified binding first.`);const selected=await custody.bindings(spec.source);if(!("ok"in selected))return selected;if(selected.ok.length>1)return fail("failed_precondition",`${spec.label} needs one explicit account or session binding.`);let binding=selected.ok[0];if(binding&&(binding.identity.issuer!==spec.source||binding.identity.subject!==identity.accountId||binding.identity.tenant!==null||identity.accountId===void 0&&(!isServerSessionAuthority(binding.authority)||binding.authority.resource!==nativeAudience)))return fail("failed_precondition",`${spec.label} upstream login does not match the selected account or session.`);const stamp=new Date().toISOString();signal.throwIfAborted();if(!binding){const created=await custody.compareAndSwapBinding({id:randomUUID(),revision:0,identity:{source:spec.source,issuer:spec.source,...identity.accountId?{subject:identity.accountId}:{},tenant:null},...identity.accountId?{}:{authority:{kind:"server-session",id:randomUUID(),resource:nativeAudience}},provider:spec.source,account:identity.account,state:"disconnected",verifiedAt:stamp,updatedAt:stamp},0);if(!("ok"in created))return created;binding=created.ok}const granted=await custody.grantForBinding(binding.id,"L1",nativeAudience);if(!("ok"in granted))return granted;if(granted.ok?.state==="revoked"&&automatic)return fail("permission_denied",`${spec.label} upstream login permission was revoked; reconnect this source explicitly.`);if(!granted.ok||granted.ok.state!=="active"){signal.throwIfAborted();const saved2=await custody.compareAndSwapGrant({id:granted.ok?.id??randomUUID(),revision:granted.ok?.revision??0,bindingId:binding.id,purpose:"L1",audience:nativeAudience,scopes:[],scopeEpoch:(granted.ok?.scopeEpoch??-1)+1,state:"active",updatedAt:stamp},granted.ok?.revision??0);if(!("ok"in saved2))return saved2}const resourceId=nativeResourceId(binding.id),resource=await custody.resource(resourceId);if(!("ok"in resource))return resource;if(resource.ok&&(resource.ok.kind!=="local-no-secret"||resource.ok.owner.kind!=="resident"))return fail("failed_precondition",`${spec.label} native login resource has a different owner or credential kind.`);if(!resource.ok){signal.throwIfAborted();const saved2=await custody.compareAndSwapResource({id:resourceId,revision:0,bindingId:binding.id,kind:"local-no-secret",owner:{kind:"resident"},encryptedRef:null,updatedAt:stamp},{kind:"local-no-secret"},0);if(!("ok"in saved2))return saved2}signal.throwIfAborted();const saved=await custody.compareAndSwapBinding({...binding,account:identity.account,state:"connected",verifiedAt:stamp,updatedAt:stamp},binding.revision);return"ok"in saved?ok(void 0):saved}function blockedAuthorization(code,message){const job={id:randomUUID(),source:spec.source,state:"failed",startedAt:new Date().toISOString(),error:{code,message}};jobs.set(job.id,job);return ok({...job})}async function verifyOpenRouterIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const request=transport(OPENROUTER_KEY_URL,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}).then(response2=>{if(signal.aborted){void response2.body?.cancel().catch(()=>{});signal.throwIfAborted()}return response2});const response=await wait(request,signal);if(response.status!==200||response.redirected||response.url&&response.url!==OPENROUTER_KEY_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part2=await wait(reader.read(),signal);if(part2.done)break;bytes+=part2.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part2.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();const body=JSON.parse(text);if(!body||typeof body!=="object"||Array.isArray(body)||Object.hasOwn(body,"error")||!Object.hasOwn(body,"data"))throw Error("Provider identity was not uniquely verified.");const data=body.data;if(!data||typeof data!=="object"||Array.isArray(data))throw Error("Provider identity was not uniquely verified.");const fields=data;const part=key=>{const value=fields[key];if(!Object.hasOwn(fields,key)||typeof value!=="string"||!value||value.length>128||/[\s\u0000-\u001f\u007f]/u.test(value))throw Error("Provider identity was not uniquely verified.");return value};const creator=part("creator_user_id"),workspace=part("workspace_id");const organization=Object.hasOwn(fields,"organization_id")&&fields.organization_id===null?null:part("organization_id");const accountId=`openrouter:v1:${JSON.stringify([creator,organization,workspace])}`;if(accountId.length>512)throw Error("Provider identity was not uniquely verified.");let expiresAt;if(Object.hasOwn(fields,"expires_at")){if(fields.expires_at===null)expiresAt=0;else{const stamp=typeof fields.expires_at==="string"?fields.expires_at.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(?:Z|\+00:00)$/):null;expiresAt=stamp?Date.parse(fields.expires_at):NaN;if(!stamp||!Number.isFinite(expiresAt)||expiresAt<=Date.now()||new Date(expiresAt).toISOString()!==`${stamp[1]}.${(stamp[2]??"").padEnd(3,"0").slice(0,3)}Z`)throw Error("Provider key expiry was not verified.")}}signal.throwIfAborted();return{account:accountId,accountId,...expiresAt===void 0?{}:{expiresAt}}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyGitLabIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const request=transport(GITLAB_TOKEN_INFO_URL,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}).then(response2=>{if(signal.aborted){void response2.body?.cancel().catch(()=>{});signal.throwIfAborted()}return response2});const response=await wait(request,signal);if(response.status!==200||response.redirected||response.url&&response.url!==GITLAB_TOKEN_INFO_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();const body=JSON.parse(text);if(!body||typeof body!=="object"||Array.isArray(body)||Object.hasOwn(body,"error"))throw Error("Provider identity was not uniquely verified.");const fields=body;if(!Array.isArray(fields.scope)||fields.scope.length!==1||fields.scope[0]!=="mcp")throw Error("Provider credential scope does not match the authorized grant.");const accountId=identityValue(fields,["resource_owner_id"]);signal.throwIfAborted();return{account:`GitLab user ${accountId}`,accountId}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyAtlassianIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);const read=async url=>{let reader;try{signal.throwIfAborted();const response=await wait(transport(url,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==url||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();return JSON.parse(text)}finally{if(reader)void reader.cancel().catch(()=>{})}};try{const me=await read(ATLASSIAN_ME_URL);if(!me||typeof me!=="object"||Array.isArray(me)||Object.hasOwn(me,"error"))throw Error("Provider identity was not uniquely verified.");const fields=me,userId=identityValue(fields,["account_id"]);if(userId.length>128||/[\u0000-\u001f\u007f]/u.test(userId))throw Error("Provider identity was not uniquely verified.");const sites=await read(ATLASSIAN_RESOURCES_URL);if(!Array.isArray(sites)||sites.length<1||sites.length>256)throw Error("Provider identity sites were not uniquely verified.");const siteIds=sites.map(site=>{if(!site||typeof site!=="object"||Array.isArray(site))throw Error("Provider identity sites were not uniquely verified.");const row=site,id=identityValue(row,["id"]),siteUrl=identityValue(row,["url"]);if(id.length>128||/[\s\u0000-\u001f\u007f]/u.test(id)||httpsUrl(siteUrl).origin!==siteUrl)throw Error("Provider identity sites were not uniquely verified.");return id}).sort();if(new Set(siteIds).size!==siteIds.length)throw Error("Provider identity sites were not uniquely verified.");const label=typeof fields.name==="string"&&fields.name===fields.name.trim()&&fields.name.length<=200&&!/[\u0000-\u001f\u007f]/u.test(fields.name)?fields.name:userId;const siteHash=createHash("sha256").update(JSON.stringify(siteIds),"utf8").digest("hex");signal.throwIfAborted();return{account:`${label} (${siteIds.length} Atlassian site${siteIds.length===1?"":"s"})`,accountId:`atlassian:v1:${userId}:${siteHash}`}}finally{clearTimeout(timer);deadline.abort()}}async function verifyLinearIdentity(_token,idToken,clientId,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const response=await wait(transport(LINEAR_JWKS_URL,{method:"GET",headers:{Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==LINEAR_JWKS_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();reader=void 0;const jwks=JSON.parse(text);const verified=await jwtVerify(idToken,createLocalJWKSet(jwks),{issuer:"https://mcp.linear.app",audience:clientId,algorithms:["RS256"],requiredClaims:["sub","email","email_verified"]});const sub=identityValue(verified.payload,["sub"]),email=identityValue(verified.payload,["email"]);if(verified.payload.email_verified!==true||sub.length>200||email.length>320||!email.includes("@")||/[\s\u0000-\u001f\u007f]/u.test(sub+email))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:email,accountId:`linear:v2:${sub}`}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyAsanaIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let client;try{client=createClient();await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="get_me");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("Provider identity tool is not uniquely declared readonly.");const result=await client.callTool({name:"get_me",arguments:{}},{signal,timeout:CALL_TIMEOUT});if(result.isError||!result.structuredContent||typeof result.structuredContent!=="object"||Array.isArray(result.structuredContent))throw Error("Provider identity verification failed.");const root=result.structuredContent,data=root.data;const me=data&&typeof data==="object"&&!Array.isArray(data)?data:root;const userId=identityValue(me,["gid"]),name=typeof me.email==="string"&&me.email.trim()?me.email.trim():identityValue(me,["name"]);if(userId.length>200||name.length>320||/[\u0000-\u001f\u007f]/u.test(userId+name))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:name,accountId:`asana:v2:${userId}`}}finally{clearTimeout(timer);deadline.abort();if(client)await client.close().catch(()=>{})}}async function verifyZoomIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);let reader;try{signal.throwIfAborted();const response=await wait(transport(ZOOM_USERINFO_URL,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==ZOOM_USERINFO_URL||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();reader=void 0;const body=JSON.parse(text);if(!body||typeof body!=="object"||Array.isArray(body)||Object.hasOwn(body,"error"))throw Error("Provider identity was not uniquely verified.");const profile=body,subject=identityValue(profile,["sub"]),email=identityValue(profile,["email"]);if(profile.email_verified!==true||subject.length>200||email.length>320||!email.includes("@")||/[\s\u0000-\u001f\u007f]/u.test(subject+email))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:email,accountId:`zoom:v1:${subject}`}}finally{clearTimeout(timer);deadline.abort();if(reader)void reader.cancel().catch(()=>{})}}async function verifyClickUpIdentity(token,caller){const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);const read=async url=>{let reader;try{signal.throwIfAborted();const response=await wait(transport(url,{method:"GET",headers:{Authorization:`Bearer ${token}`,Accept:"application/json"},redirect:"error",credentials:"omit",signal}),signal);if(response.status!==200||response.redirected||response.url&&response.url!==url||!response.body){void response.body?.cancel().catch(()=>{});throw Error("Provider identity verification failed.")}reader=response.body.getReader();const decoder=new TextDecoder("utf-8",{fatal:true});let bytes=0,text="";while(true){const part=await wait(reader.read(),signal);if(part.done)break;bytes+=part.value.byteLength;if(bytes>MAX_IDENTITY_BYTES)throw Error("Provider identity response exceeded its limit.");text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode();signal.throwIfAborted();return JSON.parse(text)}finally{if(reader)void reader.cancel().catch(()=>{})}};try{const userBody=await read(CLICKUP_USER_URL);if(!userBody||typeof userBody!=="object"||Array.isArray(userBody)||Object.hasOwn(userBody,"error"))throw Error("Provider identity was not uniquely verified.");const root=userBody,rawUser=root.user;const user=rawUser&&typeof rawUser==="object"&&!Array.isArray(rawUser)?rawUser:root;const userId=identityValue(user,["id"]),label=typeof user.email==="string"&&user.email.trim()?user.email.trim():identityValue(user,["username"]);if(userId.length>200||label.length>320||/[\s\u0000-\u001f\u007f]/u.test(userId)||/[\u0000-\u001f\u007f]/u.test(label))throw Error("Provider identity was not uniquely verified.");signal.throwIfAborted();return{account:label,accountId:`clickup:v2:${userId}`}}finally{clearTimeout(timer);deadline.abort()}}async function verifyTickTickIdentity(token,signal){const client=createClient();try{await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="list_project_members");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("TickTick identity tool is not uniquely readonly.");const result=await client.callTool({name:"list_project_members",arguments:{project_id:"inbox"}},{signal,timeout:CALL_TIMEOUT});const body=result.structuredContent;if(result.isError||!Array.isArray(body?.result))throw Error("TickTick identity response is invalid.");const selves=body.result.filter(member=>member&&typeof member==="object"&&member.self===true);if(selves.length!==1)throw Error("TickTick current member is not unique.");const username=identityValue(selves[0],["username"]);if(username.length>320||/[\s\u0000-\u001f\u007f]/u.test(username))throw Error("TickTick account username is invalid.");signal.throwIfAborted();return{account:username,accountId:username}}finally{await client.close().catch(()=>{})}}async function verifyWordPressIdentity(token,caller){const auth=spec.auth;if(spec.source!=="wordpress"||spec.server.transport!=="http"||spec.server.url!=="https://public-api.wordpress.com/wpcom/v2/mcp/v1"||auth.kind!=="mcp-oauth"||auth.reviewed?.issuer!=="https://public-api.wordpress.com")throw Error("WordPress identity authority is invalid.");const deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("Provider identity deadline exceeded.")),IDENTITY_TIMEOUT);const client=createClient();const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);try{await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),describers=tools.tools.filter(tool=>tool.name==="describe"),executors=tools.tools.filter(tool=>tool.name==="execute");if(describers.length!==1||describers[0].annotations?.readOnlyHint!==true||executors.length!==1||executors[0].annotations?.readOnlyHint!==false)throw Error("WordPress identity catalog contract changed.");const described=await client.callTool({name:"describe",arguments:{names:["wpcom/user-profile"],include_output_schema:true}},{signal,timeout:CALL_TIMEOUT});const description=described.structuredContent;if(described.isError||!object(description)||!Array.isArray(description.results)||description.results.length!==1)throw Error("WordPress identity description is invalid.");const ability=description.results[0];if(!object(ability)||ability.name!=="wpcom/user-profile"||!object(ability.annotations)||ability.annotations.readonly!==true||ability.annotations.destructive!==false||ability.requires_confirmation!==false)throw Error("WordPress current-user ability is not explicitly readonly.");const result=await client.callTool({name:"execute",arguments:{name:"wpcom/user-profile",input:{fields:["id","username","email","display_name"]}}},{signal,timeout:CALL_TIMEOUT});const body=result.structuredContent;if(result.isError||!object(body)||!object(body.profile))throw Error("WordPress identity response is invalid.");const{id,email}=body.profile;if(typeof id!=="number"||!Number.isSafeInteger(id)||id<=0||typeof email!=="string"||email.length>320||!/^[^\s@]+@[^\s@]+$/u.test(email)||/[\u0000-\u001f\u007f-\u009f]/u.test(email))throw Error("WordPress current-user identity is invalid.");signal.throwIfAborted();return{account:email,accountId:`wordpress:v1:${id}`}}finally{clearTimeout(timer);deadline.abort();await client.close().catch(()=>{})}}async function verifyOAuthIdentity(token,review,signal,oidc){if(review.kind==="wordpress-user-profile")return verifyWordPressIdentity(token,signal);if(review.kind==="openrouter-current-key")return verifyOpenRouterIdentity(token,signal);if(review.kind==="gitlab-token-info")return verifyGitLabIdentity(token,signal);if(review.kind==="atlassian-current-user-sites")return verifyAtlassianIdentity(token,signal);if(review.kind==="linear-openid-teams")return verifyLinearIdentity(token,String(oidc?.idToken??""),String(oidc?.clientId??""),signal);if(review.kind==="asana-user-workspaces")return verifyAsanaIdentity(token,signal);if(review.kind==="zoom-openid-userinfo")return verifyZoomIdentity(token,signal);if(review.kind==="clickup-current-user-workspaces")return verifyClickUpIdentity(token,signal);if(review.kind==="ticktick-inbox-self")return verifyTickTickIdentity(token,signal);if(review.kind==="notion-bot-owner"){const client2=createClient();try{await client2.connect(wire({token}),{signal});const tools=await client2.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="notion-get-self");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("Notion identity tool is not uniquely readonly.");const result=await client2.callTool({name:"notion-get-self",arguments:{}},{signal,timeout:CALL_TIMEOUT});if(result.isError||!Array.isArray(result.content)||result.content.length!==1||result.content[0]?.type!=="text")throw Error("Notion identity response is invalid.");let body;try{body=JSON.parse(result.content[0].text)}catch{throw Error("Notion identity response is invalid.")}if(!body||typeof body!=="object"||Array.isArray(body))throw Error("Notion identity response is invalid.");const userType=identityValue(body,["user","type"]),userId=identityValue(body,["user","id"]);const account=identityValue(body,["user","email"]),workspaceId=identityValue(body,["workspace","id"]);if(userType!=="person"||userId.length>200||workspaceId.length>200||account.length>320||/[\s\u0000-\u001f\u007f]/u.test(userId)||/[\s\u0000-\u001f\u007f]/u.test(workspaceId)||/[\s\u0000-\u001f\u007f]/u.test(account))throw Error("Notion identity response is invalid.");signal.throwIfAborted();return{account,accountId:`notion:v1:${userId}:${workspaceId}`}}finally{await client2.close().catch(()=>{})}}if(review.kind==="sentry-catalog-whoami"){const client2=createClient();try{await client2.connect(wire({token}),{signal});const tools=await client2.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name==="execute_sentry_tool");if(matches.length!==1||matches[0].annotations?.readOnlyHint!==false||matches[0].annotations?.destructiveHint!==true)throw Error("Sentry catalog executor contract changed.");const result=await client2.callTool({name:"execute_sentry_tool",arguments:{name:"whoami",arguments:{}}},{signal,timeout:CALL_TIMEOUT});if(result.isError)throw Error("Sentry identity verification failed.");const accountId=identityValue(result.structuredContent,["user","id"]),account=identityValue(result.structuredContent,["user","email"]);signal.throwIfAborted();return{account,accountId}}finally{await client2.close().catch(()=>{})}}const client=createClient();try{await client.connect(wire({token}),{signal});const tools=await client.listTools({},{signal}),matches=tools.tools.filter(tool=>tool.name===review.tool);if(matches.length!==1||matches[0].annotations?.readOnlyHint!==true)throw Error("Provider identity tool is not uniquely declared readonly.");const result=await client.callTool({name:review.tool,arguments:{}},{signal,timeout:CALL_TIMEOUT});if(result.isError)throw Error("Provider identity verification failed.");const accountId=identityValue(result.structuredContent,review.subjectPath),account=review.labelPath?identityValue(result.structuredContent,review.labelPath):accountId;signal.throwIfAborted();return{account,accountId}}finally{await client.close().catch(()=>{})}}async function optionalOAuthIdentity(token,review,signal,expected,oidc){if(!review){if(expected!==void 0)throw Error("The selected native account requires its identity contract.");return{account:`${spec.label} connection`}}let identity;try{identity=await verifyOAuthIdentity(token,review,signal,oidc)}catch(error){signal.throwIfAborted();if(review.kind==="wordpress-user-profile"||expected!==void 0||error instanceof Error&&["Provider key expiry was not verified.","Provider credential scope does not match the authorized grant."].includes(error.message))throw error;return{account:`${spec.label} connection`}}if(expected!==void 0&&identity.accountId!==expected){const stable=/^(linear|asana|clickup):v2:(.+)$/u.exec(identity.accountId);const prefix=stable&&stable[1]===spec.source?`${stable[1]}:v1:${stable[2]}:`:void 0;if(!prefix||!expected.startsWith(prefix)||!/^[a-f0-9]{64}$/u.test(expected.slice(prefix.length)))throw Error("Provider account does not match the existing verified identity.");identity={...identity,accountId:expected}}return identity}async function connectOAuth(url,auth,options){const declaredReview=auth.reviewed?structuredClone(auth.reviewed):void 0;const readwiseMcpWrite=options?.readwiseMcpWrite===true;if(readwiseMcpWrite){if(spec.source!=="readwise"||url!=="https://mcp2.readwise.io/mcp"||declaredReview?.issuer!=="https://readwise.io/o/"||declaredReview.registration?.kind!=="dcr")return blockedAuthorization("invalid_authorization_policy","Readwise write access requires the Readwise OAuth source.");declaredReview.scopes=["openid","read","write"]}if(auth.redirectHost!==void 0&&!["127.0.0.1","localhost"].includes(auth.redirectHost))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has invalid OAuth callback settings.`);if(declaredReview&&!validReview(declaredReview))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has invalid OAuth settings.`);if(declaredReview&&!sourceOAuthReviewMatches(declaredReview,url))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has an identity or registration adapter outside its reviewed source and origins.`);const caller=bound(options?.signal),deadline=new AbortController,signal=AbortSignal.any([caller,deadline.signal]);const timer=setTimeout(()=>deadline.abort(Error("OAuth discovery deadline exceeded.")),DISCOVERY_TIMEOUT);const fetchFn=oauthFetch(signal);try{const prior=await vault.connection(custodySource);signal.throwIfAborted();if(!("ok"in prior)&&!nativeAccountChoice(options))return prior;const server=await wait(discoverOAuthServerInfo(url,{fetchFn}),signal);const metadata=server.authorizationServerMetadata;if(!metadata)return fail("unavailable",`${spec.label} did not publish OAuth metadata.`);if(!declaredReview&&metadata.token_endpoint_auth_methods_supported&&!metadata.token_endpoint_auth_methods_supported.includes("none"))return blockedAuthorization("authorization_client_configuration_required",`${spec.label} requires a supported OAuth client configuration before sign-in can start.`);const review=declaredReview??discoveredOAuthReview(url,server);const chooseNative=nativeAccountChoice(options)&&!!review.identity;if(!("ok"in prior)&&!chooseNative)return prior;const previous="ok"in prior?prior.ok:null;const expectedAccountId=chooseNative?void 0:previous?.accountId;const choice=chooseNative?await captureAccountChoice(signal):void 0;if(choice&&!("ok"in choice))return choice;const registration=review.registration??{kind:"dcr"};const confidentialMethod=registration.kind==="pre-registered"||registration.kind==="dcr"?registration.tokenEndpointAuthMethod:void 0;const calendlyDcr=registration.kind==="dcr"&®istration.httpsBroker==="calendly"&&spec.source==="calendly"&&review.issuer==="https://calendly.com/"&&url==="https://mcp.calendly.com";if(registration.kind==="dcr"&®istration.httpsBroker&&!calendlyDcr)return blockedAuthorization("authorization_policy_mismatch",`${spec.label} has an invalid HTTPS broker configuration.`);if(review.redirectUriPolicy==="https-only"&®istration.kind!=="redirect-broker"&&!calendlyDcr)return blockedAuthorization("authorization_https_redirect_required",`${spec.label} requires a registered HTTPS callback; configure its provider client.`);if(expectedAccountId!==void 0&&!review.identity)return blockedAuthorization("authorization_identity_contract_required",`${spec.label} already has a selected native account; retain its identity contract when reconnecting that account.`);const resourceUrl=resourceUrlFromServerUrl(url);if(!matchesOAuthReview(url,review,server))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} discovery does not match its reviewed authorization policy.`);const supportedGrants=metadata.grant_types_supported??["authorization_code"];if(!supportedGrants.includes("authorization_code"))return fail("failed_precondition",`${spec.label} does not support authorization-code login.`);const grantTypes=["authorization_code",...supportedGrants.includes("refresh_token")?["refresh_token"]:[]];const scope=review.scopes.join(" ");if(registration.kind==="cimd"&&metadata.client_id_metadata_document_supported!==true)return blockedAuthorization("authorization_registration_unavailable",`${spec.label} did not advertise Client ID Metadata Document support.`);if(registration.kind==="dcr"&&!metadata.registration_endpoint)return blockedAuthorization("authorization_registration_unavailable",`${spec.label} has no compatible dynamic registration endpoint.`);const resource=httpsUrl(server.resourceMetadata?.resource??resourceUrl.href).href;const previousAuthority=chooseNative?void 0:previous?.authority;if(previousAuthority&&!registeredSessionMatches(previousAuthority))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} already has a different selected OAuth client or resource.`);if(previousAuthority&&!isMcpSessionAuthority(previousAuthority))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} selected a different kind of session; configure that connection before authorizing again.`);if(previousAuthority&&!matchesSessionAuthority(previousAuthority,url,server,previousAuthority.clientId))return blockedAuthorization("authorization_policy_mismatch",`${spec.label} changed its original OAuth destination; configure that connection before authorizing again.`);let savedClient;let replacementSnapshot;if(registration.kind==="dcr"&&(previousAuthority||confidentialMethod&&previous&&!chooseNative)){const unsupported=()=>blockedAuthorization("authorization_client_registration_required",`${spec.label} cannot reuse its existing client without its original registered callback. The current connection is preserved; open zortex help to inspect it.`);if(confidentialMethod&&reviewedDcrConfidentialSource(url,review)!==spec.source||!previousAuthority||!vault.bindingCustody)return unsupported();const selected=await wait(vault.bindingCustody.resolve({kind:"selected-source",source:spec.source}),signal);if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return unsupported();const captured=await wait(vault.bindingCustody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:resource}),signal);if(!("ok"in captured))return captured;const allowed=authorizedCredential(captured.ok);if(!("ok"in allowed))return allowed;const credential=allowed.ok,authority=captured.ok.binding.authority,redirectUri=credential.registeredRedirectUri;const callback=typeof redirectUri==="string"?/^http:\/\/127\.0\.0\.1:([1-9]\d{0,4})\/callback$/u.exec(redirectUri):null;if(captured.ok.binding.id!==selected.ok.binding.id||captured.ok.binding.revision!==selected.ok.binding.revision||!isMcpSessionAuthority(authority)||authority.id!==previousAuthority.id||!matchesSessionAuthority(authority,url,server,credential.clientId)||credential.clientId!==previousAuthority.clientId||typeof credential.clientId!=="string"||!credential.clientId||credential.clientId.length>2048||/[\u0000-\u0020\u007f-\u009f]/u.test(credential.clientId)||(confidentialMethod?credential.clientAuthentication?.method!==confidentialMethod:credential.clientAuthentication!==void 0)||!(declaredReview?acceptsSavedMcpScopes(spec,credential.scopes):credential.scopes.every(scope2=>review.scopes.includes(scope2))))return unsupported();const migrateMissingCallback=!confidentialMethod&&redirectUri===void 0&&typeof expectedAccountId==="string"&&!!expectedAccountId&&!!review.identity&&captured.ok.binding.identity.subject===expectedAccountId;if(!callback||Number(callback[1])>65535){if(!migrateMissingCallback)return unsupported()}else savedClient={snapshot:captured.ok,credential:structuredClone(credential),redirectUri,port:Number(callback[1])};replacementSnapshot=captured.ok}const authorization={issuer:review.issuer,authorizationEndpoint:metadata.authorization_endpoint,resource,scopes:[...review.scopes],allowedOrigins:[...review.allowedOrigins],...authorizationBudget};let clientId=registration.kind==="dcr"?previousAuthority?.clientId??"":registration.clientId;let registeredRedirectUri=savedClient?.redirectUri;let brokerConfig;if(registration.kind==="broker"||registration.kind==="redirect-broker"){brokerConfig=await brokerCall(registration.brokerBase,`/${registration.brokerPath}/config`,void 0,signal);const redirectBroker=registration.kind==="redirect-broker",authorizationEndpoint=`${registration.brokerBase}/${registration.brokerPath}/authorize`;if(brokerConfig.clientId!==registration.clientId||brokerConfig.resource!==resource||redirectBroker&&(brokerConfig.authorizationEndpoint!==authorizationEndpoint||brokerConfig.redirectUri!==`${registration.brokerBase}/${registration.brokerPath}/callback`)||!redirectBroker&&brokerConfig.redirectUri!==`http://127.0.0.1:${auth.loopbackPort}/callback`)throw Error("Authorization broker configuration does not match the reviewed client.")}if(calendlyDcr){brokerConfig=await brokerCall("https://zortex-calendly-auth.pages.dev","/calendly/dcr/config",void 0,signal);if(brokerConfig.resource!==resource||brokerConfig.authorizationEndpoint!=="https://zortex-calendly-auth.pages.dev/calendly/dcr/authorize"||brokerConfig.redirectUri!=="https://zortex-calendly-auth.pages.dev/calendly/dcr/callback")throw Error("Calendly authorization broker configuration does not match the reviewed client.")}const clientSettings=registration.kind==="dcr"&&confidentialMethod?{authorization,async resolveClient(redirectUri,registrationSignal){try{if(savedClient){registrationSignal.throwIfAborted();if(redirectUri!==savedClient.redirectUri||!validClientAuthentication(savedClient.credential.clientAuthentication))throw Error("The registered client callback or secret changed.");const unchanged=await checkGrant({grant:{},account:savedClient.snapshot.binding.account,snapshot:savedClient.snapshot},registrationSignal);if(!("ok"in unchanged))throw Error("The selected client changed before authorization.");clientId=savedClient.credential.clientId;return{clientId,clientAuthentication:structuredClone(savedClient.credential.clientAuthentication)}}const registered=await registerClient(server.authorizationServerUrl,{metadata,fetchFn:oauthFetch(registrationSignal),...scope?{scope}:{},clientMetadata:resolveClientMetadata({redirectUrl:redirectUri,clientMetadata:{client_name:"Zortex",redirect_uris:[redirectUri],grant_types:grantTypes,response_types:["code"],token_endpoint_auth_method:confidentialMethod}})});registrationSignal.throwIfAborted();const dynamic=registered;const method=dynamic.token_endpoint_auth_method??(spec.source==="supabase"?"client_secret_basic":void 0),expiry=dynamic.client_secret_expires_at;if(method!==confidentialMethod||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri||expiry!==void 0&&(!Number.isSafeInteger(expiry)||expiry<0||expiry>864e10))throw Error("Provider did not confirm the reviewed client, callback and secret expiry.");const clientAuthentication={method:confidentialMethod,secret:dynamic.client_secret,...expiry?{expiresAt:expiry*1e3}:{}};if(!validClientAuthentication(clientAuthentication))throw Error("Provider did not return valid client authentication.");clientId=registered.client_id;return{clientId,clientAuthentication}}catch{registrationSignal.throwIfAborted();throw Error("Provider did not confirm the reviewed confidential client, callback and valid secret.")}finally{clearTimeout(timer)}}}:registration.kind==="dcr"?{authorization:{...authorization,...calendlyDcr?{authorizationEndpoint:brokerConfig.authorizationEndpoint}:{}},...calendlyDcr?{async exchangeCode(input,exchangeSignal){if(input.clientId!==clientId||!/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}\/callback$/u.test(input.redirectUri)||input.tokenUrl!==metadata.token_endpoint||input.tokenParams.resource!==resource)throw Error("Calendly authorization broker exchange does not match the reviewed request.");return brokerCall("https://zortex-calendly-auth.pages.dev","/calendly/dcr/exchange",{code:input.code,redirectUri:input.redirectUri,verifier:input.verifier},exchangeSignal)}}:{},async resolveClientId(redirectUri,registrationSignal){try{if(savedClient){registrationSignal.throwIfAborted();if(redirectUri!==savedClient.redirectUri)throw Error("The registered client callback changed.");const unchanged=await checkGrant({grant:{},account:savedClient.snapshot.binding.account,snapshot:savedClient.snapshot},registrationSignal);if(!("ok"in unchanged))throw Error("The selected client changed before authorization.");clientId=savedClient.credential.clientId;return clientId}if(replacementSnapshot){const unchanged=await checkGrant({grant:{},account:replacementSnapshot.binding.account,snapshot:replacementSnapshot},registrationSignal);if(!("ok"in unchanged))throw Error("The selected client changed before authorization.")}const providerRedirect=calendlyDcr?String(brokerConfig.redirectUri):redirectUri;if(calendlyDcr&&!/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}\/callback$/u.test(redirectUri))throw Error("Calendly requires a loopback callback.");const registered=await registerClient(server.authorizationServerUrl,{metadata,fetchFn:oauthFetch(registrationSignal),scope,clientMetadata:resolveClientMetadata({redirectUrl:providerRedirect,clientMetadata:{client_name:"Zortex",redirect_uris:[providerRedirect],grant_types:grantTypes,response_types:["code"],token_endpoint_auth_method:"none"}})});if(calendlyDcr&&(registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==providerRedirect))throw Error("Calendly did not confirm the HTTPS callback.");registrationSignal.throwIfAborted();const dynamic=registered;if(spec.source==="miro"&®istration.allowUnadvertisedPublicClient&&(dynamic.token_endpoint_auth_method!=="none"||dynamic.client_secret!==void 0||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri))throw Error("Miro did not confirm the requested public client and callback.");if(spec.source==="wordpress"&&dynamic.client_secret!==void 0&&(dynamic.token_endpoint_auth_method!=="none"||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri))throw Error("WordPress.com did not confirm the requested public client and callback.");if(spec.source==="pipedrive"&®istration.allowUnadvertisedPublicClient&&(dynamic.token_endpoint_auth_method!=="none"||registered.redirect_uris?.length!==1||registered.redirect_uris[0]!==redirectUri))throw Error("Pipedrive did not confirm the requested public client and callback.");if(dynamic.token_endpoint_auth_method&&dynamic.token_endpoint_auth_method!=="none"||dynamic.client_secret&&!registration.discardReturnedSecretForPublicClient)throw Error("Unsupported confidential client registration.");if(dynamic.client_secret&&dynamic.token_endpoint_auth_method!=="none")throw Error("Unsupported confidential client registration.");clientId=registered.client_id;registeredRedirectUri=redirectUri;return clientId}finally{clearTimeout(timer)}}}:{clientId,...confidentialMethod?{clientAuthentication:{method:confidentialMethod}}:{},authorization:{...authorization,...registration.kind==="redirect-broker"?{authorizationEndpoint:brokerConfig.authorizationEndpoint}:{},clientId},...registration.kind==="broker"||registration.kind==="redirect-broker"?{async exchangeCode(input,exchangeSignal){const expectedRedirect=registration.kind==="redirect-broker"?`http://127.0.0.1:${auth.loopbackPort}/callback`:brokerConfig.redirectUri;if(input.clientId!==registration.clientId||input.redirectUri!==expectedRedirect||input.tokenUrl!==metadata.token_endpoint||input.tokenParams.resource!==resource)throw Error("Authorization broker exchange does not match the reviewed request.");return brokerCall(registration.brokerBase,`/${registration.brokerPath}/exchange`,{code:input.code,redirectUri:input.redirectUri,verifier:input.verifier},exchangeSignal)}}:{}};if(registration.kind!=="dcr")clearTimeout(timer);signal.throwIfAborted();const dropbox=spec.source==="dropbox"&&reviewedDropboxPublicClient(url,review)&®istration.kind==="pre-registered"&®istration.clientId===clientId;const google=confidentialMethod&&["google-contacts","google-chat"].includes(spec.source)&&reviewedConfidentialSource(url,review)===spec.source&®istration.kind==="pre-registered"&®istration.clientId===clientId;const result=await enrollment.pkce(info,{...clientSettings,authorizeUrl:registration.kind==="redirect-broker"||calendlyDcr?brokerConfig.authorizationEndpoint:metadata.authorization_endpoint,tokenUrl:metadata.token_endpoint,scope,loopbackPort:savedClient?.port??(replacementSnapshot?0:auth.loopbackPort),redirectHost:replacementSnapshot?"127.0.0.1":auth.redirectHost??"127.0.0.1",authorizeParams:{resource,...dropbox?{token_access_type:"offline"}:{},...google?{access_type:"offline",prompt:"consent"}:{}},tokenParams:{resource},driver:"oauth",issuerResponseRequired:metadata.authorization_response_iss_parameter_supported===true},async(token,signal2)=>{if(replacementSnapshot){const unchanged=await checkGrant({grant:{},account:replacementSnapshot.binding.account,snapshot:replacementSnapshot},signal2);if(!("ok"in unchanged)||confidentialMethod&&!validClientAuthentication(savedClient.credential.clientAuthentication))throw Error("The selected client changed while authorization was pending.")}const accessToken=String(token.access_token??"");if(!accessToken)throw new Error(`${spec.label} returned no access token.`);const scopes=String(token.scope??scope).split(/\s+/u).filter(Boolean);if(spec.source==="monday"&&isReviewedMondayDefault(url,review)?!acceptsMondayDefaultGrant(scopes):new Set(scopes).size!==scopes.length||scopes.some(granted=>!review.scopes.includes(granted)))throw Error("Provider granted scopes outside the requested authorization.");if(readwiseMcpWrite&&!scopes.includes("write"))throw Error("Readwise did not grant the explicitly requested MCP permission.");if((spec.source==="readwise"||spec.source==="raindrop")&&!scopes.includes("read"))throw Error(spec.label+" did not grant read access.");if(spec.source==="cloudflare"&&!["user:read","account:read"].every(scope2=>scopes.includes(scope2)))throw Error("Cloudflare did not grant both reader permissions.");if(reviewedRegisteredPublicSource(url,review)==="salesforce"&&!scopes.includes("mcp_api"))throw Error("Provider did not grant its required MCP permission.");const currentKey=review.identity?.kind==="openrouter-current-key";if(currentKey&&token.expires_in!==void 0&&(typeof token.expires_in!=="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0))throw Error("Provider token expiry was not verified.");let expiresAt=reviewedRegisteredPublicSource(url,review)==="salesforce"?salesforceTokenExpiry(token,Date.now()):token.expires_in?Date.now()+Number(token.expires_in)*1e3:0;if(dropbox&&(typeof token.access_token!=="string"||typeof token.token_type!=="string"||token.token_type.toLowerCase()!=="bearer"||typeof token.refresh_token!=="string"||!token.refresh_token||!Number.isSafeInteger(token.expires_in)||token.expires_in<=0||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()))throw Error("Dropbox did not return a verified offline grant and expiry.");if(confidentialMethod&&(typeof token.access_token!=="string"||!token.access_token||typeof token.token_type!=="string"||token.token_type.toLowerCase()!=="bearer"||token.refresh_token!==void 0&&(typeof token.refresh_token!=="string"||!token.refresh_token)||token.expires_in!==void 0&&(typeof token.expires_in!=="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt!==0&&expiresAt<=Date.now()))throw Error("The provider did not return a verified confidential grant.");if(currentKey&&(!Number.isFinite(expiresAt)||expiresAt>864e13))throw Error("Provider token expiry was not verified.");const identity=await optionalOAuthIdentity(accessToken,review.identity,signal2,expectedAccountId,{...typeof token.id_token==="string"?{idToken:token.id_token}:{},clientId});if(currentKey){if(identity.expiresAt===void 0&&!expiresAt)throw Error("Provider key expiry was not verified.");if(identity.expiresAt&&(!expiresAt||identity.expiresAt<expiresAt))expiresAt=identity.expiresAt;if(!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt!==0&&expiresAt<=Date.now())throw Error("Provider key expiry was not verified.")}if(chooseNative&&!identity.accountId&&(previous?.accountId||choice&&"ok"in choice&&choice.ok.inventory.some(row=>row.binding.identity.subject)))throw Error("Choosing another account requires verified provider identity.");return{account:identity.account,...identity.accountId===void 0?{}:{accountId:identity.accountId},...choice&&"ok"in choice&&identity.accountId?accountChoiceProof(choice.ok,identity.accountId,resource):{},...replacementSnapshot?{expectedCredential:{bindingId:replacementSnapshot.binding.id,bindingRevision:replacementSnapshot.binding.revision,grantId:replacementSnapshot.grant.id,grantRevision:replacementSnapshot.grant.revision,resourceId:replacementSnapshot.resource.id,resourceRevision:replacementSnapshot.resource.revision}}:{},authority:{kind:"mcp-session",id:(identity.accountId?previousAuthority:previous?.authority)?.id??randomUUID(),issuer:review.issuer,resource,clientId,tokenEndpoint:metadata.token_endpoint},credential:{accessToken,...token.refresh_token?{refreshToken:String(token.refresh_token)}:{},expiresAt,clientId,scopes,...!confidentialMethod&®isteredRedirectUri?{registeredRedirectUri}:{}}}},{...options,...readwiseMcpWrite?{reauthorize:true}:{},signal});if(deadline.signal.aborted&&!caller.aborted)return blockedAuthorization("authorization_discovery_timeout",`${spec.label} OAuth discovery or registration exceeded its 30-second deadline.`);return result}catch(error){if(deadline.signal.aborted&&!caller.aborted)return blockedAuthorization("authorization_discovery_timeout",`${spec.label} OAuth discovery or registration exceeded its 30-second deadline.`);throw error}finally{clearTimeout(timer)}}async function connectDeviceOAuth(_url,auth,options){const review=structuredClone(auth.reviewed);if(!validReview(review))return blockedAuthorization("invalid_authorization_policy",`${spec.label} has invalid reviewed OAuth settings.`);if(review.identity?.kind!==void 0)return blockedAuthorization("invalid_authorization_policy",`${spec.label} device authorization has an incompatible identity adapter.`);const identityReview=review.identity;const chooseNative=nativeAccountChoice(options)&&!!identityReview;const prior=await vault.connection(custodySource);if(!("ok"in prior)&&!chooseNative)return prior;const previous="ok"in prior?prior.ok:null;const expectedAccountId=chooseNative?void 0:previous?.accountId;const choice=chooseNative?await captureAccountChoice(bound(options?.signal)):void 0;if(choice&&!("ok"in choice))return choice;if(expectedAccountId!==void 0&&!identityReview)return blockedAuthorization("authorization_identity_contract_required",`${spec.label} already has a selected native account; retain its identity contract when reconnecting that account.`);const requested=[...review.scopes],scope=requested.join(" ");const browserRead=spec.source==="microsoft-todo"&&spec.readOnly===true&&options?.automatic===false&&options.manualPresentation==="return-url"&&auth.clientId==="2a0c47ae-6035-459e-a544-f8c2008a9d78"&&auth.tokenUrl==="https://login.microsoftonline.com/common/oauth2/v2.0/token"&&requested.length===6&&["openid","profile","email","Tasks.Read","User.Read","offline_access"].every(permission=>requested.includes(permission));const validate=async(token,signal)=>{const accessToken=String(token.access_token??"");if(!accessToken)throw Error(`${spec.label} returned no access token.`);const scopes=String(token.scope??"").split(/[,\s]+/u).filter(Boolean);if(!scopes.length||new Set(scopes).size!==scopes.length||scopes.some(granted=>!requested.includes(granted)))throw Error("Provider granted scopes outside the reviewed request.");if(spec.source==="microsoft-todo"&&!scopes.includes(requested.includes("Tasks.ReadWrite")?"Tasks.ReadWrite":"Tasks.Read"))throw Error("Microsoft did not grant the requested task permission.");const expiresAt=token.expires_in===void 0?0:Date.now()+Number(token.expires_in)*1e3;if(!Number.isFinite(expiresAt)||expiresAt<0||expiresAt>864e13)throw Error("Provider token expiry was invalid.");const identity=await optionalOAuthIdentity(accessToken,identityReview,signal,expectedAccountId);if(browserRead&&!identity.accountId)throw Error("Microsoft To Do profile could not be verified.");if(chooseNative&&!identity.accountId&&(previous?.accountId||choice&&"ok"in choice&&choice.ok.inventory.some(row=>row.binding.identity.subject)))throw Error("Choosing another account requires verified provider identity.");return{account:identity.account,...identity.accountId===void 0?{}:{accountId:identity.accountId},...choice&&"ok"in choice&&identity.accountId?accountChoiceProof(choice.ok,identity.accountId,_url):{},authority:{kind:"mcp-session",id:chooseNative&&identity.accountId?randomUUID():previous?.authority?.id??randomUUID(),issuer:review.issuer,resource:_url,clientId:auth.clientId,tokenEndpoint:auth.tokenUrl},credential:{accessToken,...token.refresh_token?{refreshToken:String(token.refresh_token)}:{},expiresAt,clientId:auth.clientId,scopes}}};if(browserRead)return enrollment.pkce(info,{clientId:auth.clientId,authorizeUrl:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?prompt=select_account",tokenUrl:auth.tokenUrl,scope,redirectPath:"/",provider:spec.source,driver:"microsoft"},validate,options);return enrollment.device(info,{clientId:auth.clientId,deviceCodeUrl:auth.deviceCodeUrl,tokenUrl:auth.tokenUrl,scope,allowedOrigins:[...review.allowedOrigins],provider:spec.source},validate,options)}const provider={info,spec:sourceSnapshot(spec),actions,async check(options){if(guardedReadiness()&&guardedReadsInFlight)return fail("unavailable",`${spec.label} read is in progress; retry the check.`);const previousReadiness=readiness;clearReadiness();const epoch=checkEpoch;if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);const signal=bound(options?.signal);try{if(spec.signedIn){const credential=await vault.credential(custodySource);if("ok"in credential&&isSignedInBrowserCredential(credential.ok)){const read=await provider.read({limit:1},{...options,signal});if(!("ok"in read))return read;return ok({source:spec.source,basis:"read",operation:{state:"succeeded",returned:read.ok.returned,...read.ok.evidence?{evidence:read.ok.evidence}:{}}})}}const current=await grant(signal);if(!("ok"in current))return current;if(current.ok.grant.public&&spec.auth.kind==="server-login")return fail("unauthenticated",spec.auth.login.instructions??`${spec.label} needs its upstream session before private Actions are available.`);const opened=await open(current.ok.grant,signal),authorized=await checkGrant(current.ok,signal,opened);if(!("ok"in authorized))return authorized;if(spec.liveRead){const read=await provider.read({limit:1},{...options,signal});if(!("ok"in read))return read;if(current.ok.legacyRevision){const revision=await vault.legacyRevision(custodySource);if(!("ok"in revision)||revision.ok!==current.ok.legacyRevision)return fail("failed_precondition",`${spec.label} connection changed during the read.`)}rememberReadiness(current.ok,opened,{state:"succeeded",returned:read.ok.returned},epoch,signal);return ok({source:spec.source,basis:"actions",actions:opened.tools.length,operation:{state:"succeeded",returned:read.ok.returned,...read.ok.evidence?{evidence:read.ok.evidence}:{}}})}if(guardedReadiness()&&(epoch!==checkEpoch||session?.client!==opened.client))return fail("unavailable",`${spec.label} check was superseded by a newer operation.`);const operation=(spec.source==="ticktick"||spec.source==="airtable"||spec.source==="gitlab"||spec.source==="monday"||spec.source==="linear"||spec.source==="jira"||spec.source==="confluence"||spec.source==="miro"||guardedReadiness())&&previousReadiness?.session===session&&previousReadiness.value.operation.state==="succeeded"&&JSON.stringify(previousReadiness.authority)===JSON.stringify(readinessAuthority(current.ok))&&(!selectedReadinessFence()||previousReadiness.selectionRevision===current.ok.selectionRevision)?previousReadiness.value.operation:{state:"not-run"};rememberReadiness(current.ok,opened,operation,epoch,signal);return ok({source:spec.source,basis:"actions",actions:opened.tools.length,operation})}catch(error){return failure(error,signal)}},async status(options){if(closed){clearReadiness();return fail("unavailable",`${spec.label} source is inactive.`)}const reason=spec.unavailable?.();if(reason){clearReadiness();return ok({...info,state:"unavailable",actions:true,message:reason})}const signal=bound(options?.signal);if(spec.auth.kind==="none"){const checked2=await currentReadiness(signal);return ok({...info,state:session?.published&&!session.stop.signal.aborted?"connected":"not-connected",actions:true,...checked2?{readiness:checked2}:{}})}if(spec.auth.kind==="custodied"){const current=await inspectCustodied(spec.source,spec.auth,vault);if(!("ok"in current)){clearReadiness();return current}const checked2=await currentReadiness(signal);return ok({...info,state:"connected",...checked2?{readiness:checked2}:{verification:"configuration-only"},account:current.ok.account,actions:true})}const state=await connectionState(vault,{...info,source:custodySource});if("ok"in state)state.ok.source=info.source;if(!("ok"in state)||state.ok.state!=="connected"){clearReadiness();return"ok"in state?ok({...state.ok,actions:true}):state}if("ok"in state&&state.ok.state==="connected"&&(spec.auth.kind==="mcp-oauth"||spec.auth.kind==="oauth-device"||spec.auth.kind==="zendesk-oauth"||spec.auth.kind==="server-login"||spec.source==="matrix"&&matrixUserId(state.ok.account??""))){try{const selected=await inspectSelectedAuthority(signal);if(!("ok"in selected)){clearReadiness();return selected}}catch(error){clearReadiness();return failure(error,signal)}}const checked=await currentReadiness(signal);return ok({...state.ok,actions:true,...checked?{readiness:checked}:{}})},supportsSavedReconnect:true,async connect(options){clearReadiness();options={...options,automatic:options?.automatic!==false};if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const enrollmentReason=spec.enrollmentUnavailable?.();if(enrollmentReason)return fail("unavailable",enrollmentReason);const reason=spec.unavailable?.();if(reason)return fail("unavailable",reason);const auth=spec.auth,server=spec.server;if(options.readwiseMcpWrite&&(spec.source!=="readwise"||auth.kind!=="mcp-oauth"||options.savedAccessOnly))return blockedAuthorization("invalid_authorization_policy","Readwise MCP write access requires the Readwise OAuth source and a fresh provider authorization.");try{const signal=bound(options?.signal);signal.throwIfAborted();if(options.savedAccessOnly){if(!options.automatic||auth.kind==="none"||auth.kind==="server-login"||auth.kind==="fields"&&auth.login?.handoff?.automatic){const decision=startOperationalStep(deps.metrics,{source:spec.source,phase:"connector",action:"connect",selection:"saved",loginDecision:"not_available"});decision.finish({state:"failed",reason:"not_available"});return fail("failed_precondition","This source cannot reconnect using saved access.")}}if(auth.kind==="server-login"&&auth.login.handoff)return await connectServerHandoff(auth.login,options);if(auth.kind==="custodied"){const current=await grant(signal);if(!("ok"in current))return current;const opened=await open(current.ok.grant,signal);const checked=await checkGrant(current.ok,signal);if(!("ok"in checked))return checked;if(opened.tools.length===0)return fail("failed_precondition",`${spec.label} exposed no tools admitted by its reviewed source policy.`);const job2={...completedJob(spec.source,randomUUID()),account:current.ok.account};jobs.set(job2.id,job2);return ok({...job2})}if(options?.automatic&&!options.reauthorize&&!options.selectAccount&&!options.readwiseMcpWrite&&(auth.kind==="mcp-oauth"||auth.kind==="oauth-device"||auth.kind==="zendesk-oauth"||auth.kind==="fields")){const connection=await vault.connection(custodySource);if(!("ok"in connection))return connection;if(auth.kind==="fields"&&connection.ok?.state==="disconnected")return blockedAuthorization("login_required",`Reconnect ${spec.label} through its connection page.`);if(connection.ok?.state==="connected"){const stored=auth.kind!=="fields"&&(connection.ok.accountId||connection.ok.authority)?ok(null):await vault.credential(custodySource);if("err"in stored&&stored.err.code!=="not_found")return stored;if("ok"in stored&&(stored.ok===null||stored.ok.accessToken&&!isSignedInBrowserCredential(stored.ok))){const current=await grant(signal);if(!("ok"in current))return current;if(!current.ok.grant.token&&!current.ok.grant.fields||current.ok.grant.public)return fail("failed_precondition",`${spec.label} has no MCP authorization grant; reconnect this source.`);await probe(current.ok.grant,signal,auth.kind==="fields"?auth.login:void 0,options.savedAccessOnly===true);signal.throwIfAborted();if(auth.kind==="fields"){const latest=await grant(signal);if(!("ok"in latest))return latest;if(latest.ok.account!==current.ok.account||JSON.stringify(latest.ok.grant.fields)!==JSON.stringify(current.ok.grant.fields))return fail("failed_precondition",`${spec.label} selected credential changed while reconnecting.`)}const authorized=await checkGrant(current.ok,signal);if(!("ok"in authorized))return authorized;const job2={...completedJob(spec.source,randomUUID()),account:current.ok.account};jobs.set(job2.id,job2);return ok({...job2})}}}if(options.savedAccessOnly)return blockedAuthorization("login_required",`Saved access is unavailable for ${spec.label}.`);if(auth.kind!=="none")await dropSession();if(options?.automatic&&spec.signedIn&&auth.kind!=="none"){firstRead=void 0;const signedIn=await connectSignedIn(options);if(signedIn)return signedIn}if(auth.kind==="none"){const opened=await open({},signal);signal.throwIfAborted();if(deps.rememberPublicConnection){if(!opened.tools.some(row=>row.tool==="lookup"&&row.effect==="read")){await dropSession();return fail("failed_precondition","The public lookup tool is unavailable.")}await deps.rememberPublicConnection()}return ok(completedJob(spec.source,"local"))}if(auth.kind==="zendesk-oauth")return await track(starting,connectZendeskOAuth(auth,options));if(auth.kind==="mcp-oauth"){if(server.transport!=="http")return fail("failed_precondition",`${spec.label}: MCP OAuth needs a remote server.`);return await track(starting,connectOAuth(server.url,auth,options))}if(auth.kind==="oauth-device"){return await track(starting,connectDeviceOAuth(server.transport==="http"?server.url:auth.tokenUrl,auth,options))}if(spec.source==="matrix"&&auth.kind==="fields"){const prior=await vault.connection(spec.source);if(!("ok"in prior))return prior;const previous=prior.ok;if(previous&&(previous.accountId&&matrixUserId(previous.accountId)||[matrixHomeserver,"https://matrix.org"].includes(previous.account))){const choice=await captureAccountChoice(signal);if(!("ok"in choice))return choice;const latest=await vault.connection(spec.source);if(!("ok"in latest))return latest;if(latest.ok?.account!==previous.account||latest.ok?.accountId!==previous.accountId)return fail("failed_precondition","The selected Matrix account changed. Start the connection again.");const login=await matrixLogin(transport,signal,previous.accountId);return enrollment.pkce(info,login.settings,async(token,verificationSignal)=>{const verified=await login.validate(token,verificationSignal);return{...verified,...accountChoiceProof(choice.ok,verified.accountId,matrixHomeserver),authority:{kind:"mcp-session",id:randomUUID(),issuer:matrixIssuer,resource:matrixHomeserver,clientId:verified.credential.clientId,tokenEndpoint:matrixTokenUrl}}},options)}}if(auth.kind==="fields")return await enrollment.form(info,auth.fields,async(fields,signal2)=>{await probe(fieldsGrant(fields),signal2,auth.login,options?.savedAccessOnly);return{account:auth.account(fields),credential:{accessToken:JSON.stringify(fields),expiresAt:0,clientId:"mcp-fields",scopes:[]},...custodySource==="figma--pat"?{custodySource:"figma--pat"}:{}}},options);const native=await probe({},signal,auth.login,options?.savedAccessOnly);signal.throwIfAborted();if(!native.identity&&!auth.login.ready)return fail("failed_precondition",`${spec.label} needs a noninteractive login status contract before its session can be saved.`);const identity=native.identity??{account:`${spec.label} session`},saved=await saveServerIdentity(identity,signal,options?.automatic);if(!("ok"in saved))return saved;const job={...completedJob(spec.source,randomUUID()),account:identity.account};jobs.set(job.id,job);return ok({...job})}catch(error){const signal=bound(options?.signal);if(error instanceof ServerLoginRequired&&!signal.aborted){const blocked=automaticError("login_required");return blockedAuthorization(blocked.code,error.message||`Sign in to ${spec.label} through its app, then retry this connection.`)}return failure(error,signal)}},job:id=>{const job=jobs.get(id);return job?ok({...job}):enrollment.job(id)},cancelJob(id){const job=jobs.get(id);if(job){if(loginOwner?.job.id===id&&!loginOwner.settled){if(job.state==="waiting-user")job.state="cancelled";delete job.automationActive;delete job.browserContinuation;delete job.instructions;delete job.authorizationUrl;delete job.authorizationOrigin;delete job.authorizationImage;delete job.devicePrompt;loginOwner.stop.abort();loginOwner.publish();retryLoginCleanup(loginOwner);return ok({id,cleanup:"pending"})}return ok({id,cleanup:"confirmed"})}const owned=enrollment.job?.(id);return owned&&"ok"in owned&&owned.ok.source!==spec.source?fail("not_found","Unknown connector connection job."):enrollment.cancelJob?enrollment.cancelJob(id):ok({id,cleanup:"confirmed"})},async read(request,options){const route=spec.signedIn;const fallback=()=>fail("failed_precondition",`${spec.label} is a level 1 connector: it acts through actions and stores nothing in the Vault.`);if(spec.liveRead){if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const invalid2=validateRead(request);if(invalid2)return invalid2;if(request.fileId!==void 0||request.since!==void 0||request.until!==void 0)return fail("invalid_argument",`${spec.label} metadata reads support limit and query only.`);const result=await invokeAction(`${spec.source}.${spec.liveRead.tool}`,{params:spec.liveRead.args??{}},options??{},true);if(!("ok"in result))return result;const value=result.ok.result;let records2;try{records2=spec.liveRead.records(spec.source,value.structured,value.text)}catch{return fail("unavailable",`${spec.label} did not return a valid live-read response.`)}if(!records2)return fail("unavailable",`${spec.label} did not return a valid live-read response.`);if(closed||options?.signal?.aborted)return fail(closed?"unavailable":"aborted",`${spec.label} live read did not complete.`);const query2=request.query?.toLowerCase(),reply=readResult(spec.source,records2.filter(row=>!query2||String(row.body??"").toLowerCase().includes(query2)).slice(0,request.limit??1));if("ok"in reply)reply.ok.evidence={origin:"live",observedAt:new Date().toISOString(),stage:"read-page"};return reply}if(!route)return fallback();if(closed)return fail("unavailable",`${spec.label} source is inactive.`);const invalid=validateRead(request);if(invalid)return invalid;const stored=await vault.credential(custodySource);if(!("ok"in stored)||!isSignedInBrowserCredential(stored.ok))return fallback();const identity=await vault.connection(custodySource);if(!("ok"in identity))return identity;const signal=bound(options?.signal),pending2=firstRead;firstRead=void 0;let records;if(pending2&&pending2.expiresAt>Date.now())records=pending2.records;else{const outcome=await signedInPage(route.feedUrl??route.identityUrl,signal);if(signal.aborted)return fail("aborted",`${spec.label} read cancelled.`);if(!outcome)return fail("unavailable",`The ${spec.label} browser session could not be read on this computer.`);if(/^browser_session_unavailable(?:\s|$)/.test(outcome.reason??""))return{err:{...fail("unavailable",automaticError("browser_session_unavailable").message).err,...browserFailureCause(outcome.reason)}};if(outcome.state==="login_required")return fail("unauthenticated",`Sign in to ${spec.label} in Chrome, then read again.`);if(outcome.state!=="completed")return fail("unavailable",`${spec.label} could not be read live.`);if(!route.feedUrl&&route.identity(outcome)?.accountId!==identity.ok?.accountId)return fail("unauthenticated",`The signed-in ${spec.label} account changed. Connect again before reading.`);records=route.records(spec.source,outcome)}const query=request.query?.toLowerCase();return closed?fail("unavailable",`${spec.label} source was disabled.`):readResult(spec.source,records.filter(row=>!query||String(row.body).toLowerCase().includes(query)).slice(0,request.limit??1))},close(){if(!closing){clearReadiness();closed=true;stop.abort();firstRead=void 0;enrollment.cancelSource?.(spec.source);const dropped=dropSession();closing=Promise.allSettled([dropped,...pending,...starting,...cleanup]).then(async()=>{if(loginOwner){retryLoginCleanup(loginOwner);await loginOwner.cleaning}})}return closing}};return provider}
|