UNPKG

@kya-os/mcp-i

Version:

The TypeScript MCP framework with identity features built-in

1 lines 11.9 kB
"use strict";exports.id=784,exports.ids=[784],exports.modules={6721:(e,t,n)=>{n.d(t,{Y:()=>o});var r=n(64549);const o=async e=>{const t=await(0,r.p)(e);return((...e)=>{const t={};for(const n of e)for(const[e,r]of Object.entries(n))void 0!==t[e]?Object.assign(t[e],r):t[e]=r;return t})(t.configFile,t.credentialsFile)}},85784:(e,t,n)=>{n.d(t,{fromIni:()=>k});var r=n(6721),o=n(76682),s=n(84122),i=n(53243),a=n(76896);const c=e=>(0,i.g)(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p"),l=e=>!e.role_arn&&!!e.credential_source;var g=n(86880),d=n(71078),f=n(77598),u=n(73024),p=n(48161),h=n(76760);class _{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=3e5;constructor(e,t,n){this.profileData=e,this.init=t,this.callerClientConfig=n}async loadCredentials(){const e=await this.loadToken();if(!e)throw new s.C(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});const t=e.accessToken,n=Date.now();return new Date(t.expiresAt).getTime()-n<=_.REFRESH_THRESHOLD?this.refresh(e):{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,sessionToken:t.sessionToken,accountId:t.accountId,expiration:new Date(t.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){const{SigninClient:t,CreateOAuth2TokenCommand:r}=await Promise.all([n.e(478),n.e(743)]).then(n.bind(n,17743)),{logger:o,userAgentAppId:i}=this.callerClientConfig??{},a=(e=>"h2"===e?.metadata?.handlerProtocol)(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,c=new t({credentials:{accessKeyId:"",secretAccessKey:""},region:this.profileData.region??await(this.callerClientConfig?.region?.())??process.env.AWS_REGION,requestHandler:a,logger:o,userAgentAppId:i,...this.init?.clientConfig});this.createDPoPInterceptor(c.middlewareStack);const l={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{const t=await c.send(new r(l)),{accessKeyId:n,secretAccessKey:o,sessionToken:i}=t.tokenOutput?.accessToken??{},{refreshToken:a,expiresIn:g}=t.tokenOutput??{};if(!(n&&o&&i&&a))throw new s.C("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});const d=1e3*(g??900),f=new Date(Date.now()+d),u={...e,accessToken:{...e.accessToken,accessKeyId:n,secretAccessKey:o,sessionToken:i,expiresAt:f.toISOString()},refreshToken:a};await this.saveToken(u);const p=u.accessToken;return{accessKeyId:p.accessKeyId,secretAccessKey:p.secretAccessKey,sessionToken:p.sessionToken,accountId:p.accountId,expiration:f}}catch(e){if("AccessDeniedException"===e.name){let t;switch(e.error){case"TOKEN_EXPIRED":t="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":t="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":t="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:t=`Failed to refresh token: ${String(e)}. Please re-authenticate using \`aws login\``}throw new s.C(t,{logger:this.logger,tryNextLink:!1})}throw new s.C(`Failed to refresh token: ${String(e)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){const e=this.getTokenFilePath();try{let t;try{t=await(0,d.TA)(e,{ignoreCache:this.init?.ignoreCache})}catch{t=await u.promises.readFile(e,"utf8")}const n=JSON.parse(t),r=["accessToken","clientId","refreshToken","dpopKey"].filter(e=>!n[e]);if(n.accessToken?.accountId||r.push("accountId"),r.length>0)throw new s.C(`Token validation failed, missing fields: ${r.join(", ")}`,{logger:this.logger,tryNextLink:!1});return n}catch(t){throw new s.C(`Failed to load token from ${e}: ${String(t)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){const t=this.getTokenFilePath(),n=(0,h.dirname)(t);try{await u.promises.mkdir(n,{recursive:!0})}catch(e){}await u.promises.writeFile(t,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){const e=process.env.AWS_LOGIN_CACHE_DIRECTORY??(0,h.join)((0,p.homedir)(),".aws","login","cache"),t=Buffer.from(this.loginSession,"utf8"),n=(0,f.createHash)("sha256").update(t).digest("hex");return(0,h.join)(e,`${n}.json`)}derToRawSignature(e){let t=2;if(2!==e[t])throw new Error("Invalid DER signature");t++;const n=e[t++];let r=e.subarray(t,t+n);if(t+=n,2!==e[t])throw new Error("Invalid DER signature");t++;const o=e[t++];let s=e.subarray(t,t+o);r=0===r[0]?r.subarray(1):r,s=0===s[0]?s.subarray(1):s;const i=Buffer.concat([Buffer.alloc(32-r.length),r]),a=Buffer.concat([Buffer.alloc(32-s.length),s]);return Buffer.concat([i,a])}createDPoPInterceptor(e){e.add(e=>async t=>{if(g.K.isInstance(t.request)){const e=t.request,n=`${e.protocol}//${e.hostname}${e.port?`:${e.port}`:""}${e.path}`,r=await this.generateDpop(e.method,n);e.headers={...e.headers,DPoP:r}}return e(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",t){const n=await this.loadToken();try{const r=(0,f.createPrivateKey)({key:n.dpopKey,format:"pem",type:"sec1"}),o=(0,f.createPublicKey)(r).export({format:"der",type:"spki"});let s=-1;for(let e=0;e<o.length;e++)if(4===o[e]){s=e;break}const i=o.slice(s+1,s+33),a=o.slice(s+33,s+65),c={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:i.toString("base64url"),y:a.toString("base64url")}},l={jti:crypto.randomUUID(),htm:e,htu:t,iat:Math.floor(Date.now()/1e3)},g=`${Buffer.from(JSON.stringify(c)).toString("base64url")}.${Buffer.from(JSON.stringify(l)).toString("base64url")}`,d=(0,f.sign)("sha256",Buffer.from(g),r);return`${g}.${this.derToRawSignature(d).toString("base64url")}`}catch(e){throw new s.C(`Failed to generate Dpop proof: ${e instanceof Error?e.message:String(e)}`,{logger:this.logger,tryNextLink:!1})}}}const y=e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.aws_access_key_id&&"string"==typeof e.aws_secret_access_key&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,w=async(e,t)=>{t?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");const n={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return(0,i.g)(n,"CREDENTIALS_PROFILE","n")},C=async(e,t,g,d={},f=!1)=>{const u=t[e];if(Object.keys(d).length>0&&y(u))return w(u,g);if(f||((e,{profile:t="default",logger:n}={})=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.role_arn&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(((e,{profile:t,logger:n})=>{const r="string"==typeof e.source_profile&&void 0===e.credential_source;return r&&n?.debug?.(` ${t} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`),r})(e,{profile:t,logger:n})||((e,{profile:t,logger:n})=>{const r="string"==typeof e.credential_source&&void 0===e.source_profile;return r&&n?.debug?.(` ${t} isCredentialSourceProfile credential_source=${e.credential_source}`),r})(e,{profile:t,logger:n})))(u,{profile:e,logger:g.logger}))return(async(e,t,r,g={},d)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");const f=t[e],{source_profile:u,region:p}=f;if(!r.roleAssumer){const{getDefaultRoleAssumer:e}=await n.e(482).then(n.bind(n,84482));r.roleAssumer=e({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...r?.parentClientConfig,region:p??r?.parentClientConfig?.region}},r.clientPlugins)}if(u&&u in g)throw new s.C(`Detected a cycle attempting to resolve credentials for profile ${(0,o.Bz)(r)}. Profiles visited: `+Object.keys(g).join(", "),{logger:r.logger});r.logger?.debug("@aws-sdk/credential-provider-ini - finding credential resolver using "+(u?`source_profile=[${u}]`:`profile=[${e}]`));const h=u?d(u,t,r,{...g,[u]:!0},l(t[u]??{})):(await((e,t,r)=>{const o={EcsContainer:async e=>{const{fromHttp:t}=await n.e(866).then(n.bind(n,57866)),{fromContainerMetadata:o}=await n.e(387).then(n.bind(n,35387));return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>(0,a.c)(t(e??{}),o(e))().then(c)},Ec2InstanceMetadata:async e=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");const{fromInstanceMetadata:t}=await n.e(387).then(n.bind(n,35387));return async()=>t(e)().then(c)},Environment:async e=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");const{fromEnv:t}=await n.e(844).then(n.bind(n,84844));return async()=>t(e)().then(c)}};if(e in o)return o[e];throw new s.C(`Unsupported credential source in profile ${t}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})})(f.credential_source,e,r.logger)(r))();if(l(f))return h.then(e=>(0,i.g)(e,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));{const t={RoleArn:f.role_arn,RoleSessionName:f.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:f.external_id,DurationSeconds:parseInt(f.duration_seconds||"3600",10)},{mfa_serial:n}=f;if(n){if(!r.mfaCodeProvider)throw new s.C(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:r.logger,tryNextLink:!1});t.SerialNumber=n,t.TokenCode=await r.mfaCodeProvider(n)}const o=await h;return r.roleAssumer(o,t).then(e=>(0,i.g)(e,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}})(e,t,g,d,C);if(y(u))return w(u,g);if(p=u,Boolean(p)&&"object"==typeof p&&"string"==typeof p.web_identity_token_file&&"string"==typeof p.role_arn&&["undefined","string"].indexOf(typeof p.role_session_name)>-1)return(async(e,t)=>n.e(988).then(n.bind(n,48988)).then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:t.roleAssumerWithWebIdentity,logger:t.logger,parentClientConfig:t.parentClientConfig})().then(e=>(0,i.g)(e,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q"))))(u,g);var p;if((e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.credential_process)(u))return(async(e,t)=>n.e(67).then(n.bind(n,68448)).then(({fromProcess:n})=>n({...e,profile:t})().then(e=>(0,i.g)(e,"CREDENTIALS_PROFILE_PROCESS","v"))))(g,e);if((e=>e&&("string"==typeof e.sso_start_url||"string"==typeof e.sso_account_id||"string"==typeof e.sso_session||"string"==typeof e.sso_region||"string"==typeof e.sso_role_name))(u))return await(async(e,t,r={})=>{const{fromSSO:o}=await n.e(25).then(n.bind(n,49406));return o({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})().then(e=>t.sso_session?(0,i.g)(e,"CREDENTIALS_PROFILE_SSO","r"):(0,i.g)(e,"CREDENTIALS_PROFILE_SSO_LEGACY","t"))})(e,u,g);if((e=>Boolean(e&&e.login_session))(u))return(async(e,t)=>{const n=await(a={...t,profile:e},async({callerClientConfig:e}={})=>{a?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");const t=await(0,r.Y)(a||{}),n=(0,o.Bz)({profile:a?.profile??e?.profile}),c=t[n];if(!c?.login_session)throw new s.C(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:a?.logger});const l=new _(c,a,e),g=await l.loadCredentials();return(0,i.g)(g,"CREDENTIALS_LOGIN","AD")})();var a;return(0,i.g)(n,"CREDENTIALS_PROFILE_LOGIN","AC")})(e,g);throw new s.C(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:g.logger})},k=(e={})=>async({callerClientConfig:t}={})=>{const n={...e,parentClientConfig:{...t,...e.parentClientConfig}};n.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");const s=await(0,r.Y)(n);return C((0,o.Bz)({profile:e.profile??t?.profile}),s,n)}}};