@kya-os/mcp-i 1.10.0 → 1.11.0
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/317.js +1 -0
- package/dist/354.js +1 -1
- package/dist/839.js +1 -0
- package/dist/95.js +1 -1
- package/dist/cli-adapter/index.js +1 -1
- package/dist/runtime/102.js +1 -0
- package/dist/runtime/adapter-express.js +3 -3
- package/dist/runtime/adapter-nextjs.js +5 -5
- package/dist/runtime/audit.d.ts +1 -1
- package/dist/runtime/debug.d.ts +1 -1
- package/dist/runtime/debug.js +3 -2
- package/dist/runtime/delegation-hooks.d.ts +1 -1
- package/dist/runtime/http.js +3 -3
- package/dist/runtime/identity.d.ts +4 -4
- package/dist/runtime/identity.js +4 -4
- package/dist/runtime/index.d.ts +6 -2
- package/dist/runtime/index.js +10 -2
- package/dist/runtime/mcpi-runtime.d.ts +9 -1
- package/dist/runtime/mcpi-runtime.js +20 -3
- package/dist/runtime/outbound-delegation.d.ts +5 -3
- package/dist/runtime/outbound-delegation.js +14 -8
- package/dist/runtime/outbound-identity-bridge.d.ts +40 -0
- package/dist/runtime/outbound-identity-bridge.js +114 -0
- package/dist/runtime/proof-batch-queue.d.ts +1 -1
- package/dist/runtime/request-context.d.ts +10 -0
- package/dist/runtime/request-context.js +4 -0
- package/dist/runtime/resume-token-store-kv.d.ts +44 -0
- package/dist/runtime/resume-token-store-kv.js +93 -0
- package/dist/runtime/resume-token-store.d.ts +30 -0
- package/dist/runtime/resume-token-store.js +46 -0
- package/dist/runtime/session.js +6 -0
- package/dist/runtime/stdio.js +3 -3
- package/dist/runtime/utils/tools.d.ts +1 -1
- package/dist/runtime/utils/tools.js +29 -7
- package/dist/runtime/well-known.d.ts +12 -1
- package/dist/runtime/well-known.js +13 -2
- package/package.json +4 -2
- package/dist/225.js +0 -1
- package/dist/runtime/verifier-middleware.d.ts +0 -99
- package/dist/runtime/verifier-middleware.js +0 -416
package/dist/317.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=317,exports.ids=[317],exports.modules={2445:e=>{e.exports={rE:"3.993.0"}},2840:(e,t,n)=>{n.d(t,{k:()=>S});var r=n(50469),i=n(69700);const s="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",o="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",a="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",c="(\\d?\\d)",l="(\\d{4})",d=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),p=new RegExp(`^${s}, ${c} ${o} ${l} ${a} GMT$`),h=new RegExp(`^${s}, ${c}-${o}-(\\d\\d) ${a} GMT$`),u=new RegExp(`^${s} ${o} ( [1-9]|\\d\\d) ${a} ${l}$`),g=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function m(e,t,n){const r=Number(e);if(r<t||r>n)throw new Error(`Value ${r} out of range [${t}, ${n}]`)}var f=n(84651),x=n(70764),y=n(12544),b=n(2914),E=n(63282),w=n(26144);class S extends E.f{settings;constructor(e){super(),this.settings=e}read(e,t){const n=r.l.of(e);if(n.isListSchema())return(0,i.G)(t).map(e=>this.read(n.getValueSchema(),e));if(n.isBlobSchema())return(this.serdeContext?.base64Decoder??y.E)(t);if(n.isTimestampSchema())switch((0,w.V)(n,this.settings)){case 5:return(e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC3339 timestamps must be strings");const t=d.exec(e);if(!t)throw new TypeError(`Invalid RFC3339 timestamp format ${e}`);const[,n,r,i,s,o,a,,c,l]=t;m(r,1,12),m(i,1,31),m(s,0,23),m(o,0,59),m(a,0,60);const p=new Date(Date.UTC(Number(n),Number(r)-1,Number(i),Number(s),Number(o),Number(a),Number(c)?Math.round(1e3*parseFloat(`0.${c}`)):0));if(p.setUTCFullYear(Number(n)),"Z"!=l.toUpperCase()){const[,e,t,n]=/([+-])(\d\d):(\d\d)/.exec(l)||[void 0,"+",0,0],r="-"===e?1:-1;p.setTime(p.getTime()+r*(60*Number(t)*60*1e3+60*Number(n)*1e3))}return p})(t);case 6:return(e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC7231 timestamps must be strings.");let t,n,r,i,s,o,a,c;if((c=p.exec(e))?[,t,n,r,i,s,o,a]=c:(c=h.exec(e))?([,t,n,r,i,s,o,a]=c,r=(Number(r)+1900).toString()):(c=u.exec(e))&&([,n,t,i,s,o,a,r]=c),r&&o){const e=Date.UTC(Number(r),g.indexOf(n),Number(t),Number(i),Number(s),Number(o),a?Math.round(1e3*parseFloat(`0.${a}`)):0);m(t,1,31),m(i,0,23),m(s,0,59),m(o,0,60);const c=new Date(e);return c.setUTCFullYear(Number(r)),c}throw new TypeError(`Invalid RFC7231 date-time value ${e}.`)})(t);case 7:return(e=>{if(null==e)return;let t=NaN;if("number"==typeof e)t=e;else if("string"==typeof e){if(!/^-?\d*\.?\d+$/.test(e))throw new TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(e)}else"object"==typeof e&&1===e.tag&&(t=e.value);if(isNaN(t)||Math.abs(t)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(1e3*t))})(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(n.isStringSchema()){const e=n.getMergedTraits().mediaType;let r=t;if(e)return n.getMergedTraits().httpHeader&&(r=this.base64ToUtf8(r)),("application/json"===e||e.endsWith("+json"))&&(r=f.A.from(r)),r}return n.isNumericSchema()?Number(t):n.isBigIntegerSchema()?BigInt(t):n.isBigDecimalSchema()?new x.D(t,"bigDecimal"):n.isBooleanSchema()?"true"===String(t).toLowerCase():t}base64ToUtf8(e){return(this.serdeContext?.utf8Encoder??b.P)((this.serdeContext?.base64Decoder??y.E)(e))}}},14433:(e,t,n)=>{n.d(t,{m:()=>r});class r{async sign(e,t,n){return e}}},30259:(e,t,n)=>{function r(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}n.d(t,{$:()=>r})},69700:(e,t,n)=>{n.d(t,{G:()=>r});const r=e=>{const t=e.length,n=[];let r,i=!1,s=0;for(let o=0;o<t;++o){const t=e[o];switch(t){case'"':"\\"!==r&&(i=!i);break;case",":i||(n.push(e.slice(s,o)),s=o+1)}r=t}return n.push(e.slice(s)),n.map(e=>{const t=(e=e.trim()).length;return t<2?e:('"'===e[0]&&'"'===e[t-1]&&(e=e.slice(1,t-1)),e.replace(/\\"/g,'"'))})}},79317:(e,t,n)=>{n.d(t,{getDefaultRoleAssumer:()=>ai,getDefaultRoleAssumerWithWebIdentity:()=>ci});var r=n(53347),i=n(96901),s=n(7387);const o=!1;var a=n(66686),c=n(22869);const l={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var d=n(51453),p=n(6723);class h extends p.T{constructor(e){super(e),Object.setPrototypeOf(this,h.prototype)}}class u extends h{name="ExpiredTokenException";$fault="client";constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,u.prototype)}}class g extends h{name="MalformedPolicyDocumentException";$fault="client";constructor(e){super({name:"MalformedPolicyDocumentException",$fault:"client",...e}),Object.setPrototypeOf(this,g.prototype)}}class m extends h{name="PackedPolicyTooLargeException";$fault="client";constructor(e){super({name:"PackedPolicyTooLargeException",$fault:"client",...e}),Object.setPrototypeOf(this,m.prototype)}}class f extends h{name="RegionDisabledException";$fault="client";constructor(e){super({name:"RegionDisabledException",$fault:"client",...e}),Object.setPrototypeOf(this,f.prototype)}}class x extends h{name="IDPRejectedClaimException";$fault="client";constructor(e){super({name:"IDPRejectedClaimException",$fault:"client",...e}),Object.setPrototypeOf(this,x.prototype)}}class y extends h{name="InvalidIdentityTokenException";$fault="client";constructor(e){super({name:"InvalidIdentityTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,y.prototype)}}class b extends h{name="IDPCommunicationErrorException";$fault="client";constructor(e){super({name:"IDPCommunicationErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,b.prototype)}}const E="AssumedRoleUser",w="Credentials",S="DurationSeconds",v="Policy",N="PolicyArns",T="PackedPolicySize",A="RoleArn",C="RoleSessionName",I="SourceIdentity",$="awsQueryError",_="client",P="error",k="httpError",D="message",R="smithy.ts.sdk.synthetic.com.amazonaws.sts",O="com.amazonaws.sts",j=d.O.for(R);var M=[-3,R,"STSServiceException",0,[],[]];j.registerError(M,h);const L=d.O.for(O);var V=[-3,O,"ExpiredTokenException",{[$]:["ExpiredTokenException",400],[P]:_,[k]:400},[D],[0]];L.registerError(V,u);var U=[-3,O,"IDPCommunicationErrorException",{[$]:["IDPCommunicationError",400],[P]:_,[k]:400},[D],[0]];L.registerError(U,b);var q=[-3,O,"IDPRejectedClaimException",{[$]:["IDPRejectedClaim",403],[P]:_,[k]:403},[D],[0]];L.registerError(q,x);var F=[-3,O,"InvalidIdentityTokenException",{[$]:["InvalidIdentityToken",400],[P]:_,[k]:400},[D],[0]];L.registerError(F,y);var W=[-3,O,"MalformedPolicyDocumentException",{[$]:["MalformedPolicyDocument",400],[P]:_,[k]:400},[D],[0]];L.registerError(W,g);var z=[-3,O,"PackedPolicyTooLargeException",{[$]:["PackedPolicyTooLarge",400],[P]:_,[k]:400},[D],[0]];L.registerError(z,m);var B=[-3,O,"RegionDisabledException",{[$]:["RegionDisabledException",403],[P]:_,[k]:403},[D],[0]];L.registerError(B,f);const K=[j,L];var G=[0,O,"accessKeySecretType",8,0],H=[0,O,"clientTokenType",8,0],X=[3,O,E,0,["AssumedRoleId","Arn"],[0,0],2],Q=[3,O,"AssumeRoleRequest",0,[A,C,N,v,S,"Tags","TransitiveTagKeys","ExternalId","SerialNumber","TokenCode",I,"ProvidedContexts"],[0,0,()=>ie,0,1,()=>oe,64,0,0,0,0,()=>se],2],Y=[3,O,"AssumeRoleResponse",0,[w,E,T,I],[[()=>ee,0],()=>X,1,0]],Z=[3,O,"AssumeRoleWithWebIdentityRequest",0,[A,C,"WebIdentityToken","ProviderId",N,v,S],[0,0,[()=>H,0],0,()=>ie,0,1],3],J=[3,O,"AssumeRoleWithWebIdentityResponse",0,[w,"SubjectFromWebIdentityToken",E,T,"Provider","Audience",I],[[()=>ee,0],0,()=>X,1,0,0,0]],ee=[3,O,w,0,["AccessKeyId","SecretAccessKey","SessionToken","Expiration"],[0,[()=>G,0],0,4],4],te=[3,O,"PolicyDescriptorType",0,["arn"],[0]],ne=[3,O,"ProvidedContext",0,["ProviderArn","ContextAssertion"],[0,0]],re=[3,O,"Tag",0,["Key","Value"],[0,0],2],ie=[1,O,"policyDescriptorListType",0,()=>te],se=[1,O,"ProvidedContextsListType",0,()=>ne],oe=[1,O,"tagListType",0,()=>re],ae=[9,O,"AssumeRole",0,()=>Q,()=>Y],ce=[9,O,"AssumeRoleWithWebIdentity",0,()=>Z,()=>J];class le extends(c.u.classBuilder().ep(l).m(function(e,t,n,r){return[(0,a.r)(n,e.getEndpointParameterInstructions())]}).s("AWSSecurityTokenServiceV20110615","AssumeRole",{}).n("STSClient","AssumeRoleCommand").sc(ae).build()){}class de extends(c.u.classBuilder().ep(l).m(function(e,t,n,r){return[(0,a.r)(n,e.getEndpointParameterInstructions())]}).s("AWSSecurityTokenServiceV20110615","AssumeRoleWithWebIdentity",{}).n("STSClient","AssumeRoleWithWebIdentityCommand").sc(ce).build()){}const pe=e=>{if("string"==typeof e?.Arn){const t=e.Arn.split(":");if(t.length>4&&""!==t[4])return t[4]}},he=async(e,t,n,r={})=>{const a="function"==typeof e?await e():e,c="function"==typeof t?await t():t;let l="";const d=a??c??(l=await function(e={}){return(0,s.Z)({...i.GG,default:async()=>(o||console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."),"us-east-1")},{...i.zH,...e})}(r)());return n?.debug?.("@aws-sdk/client-sts::resolveRegion","accepting first of:",`${a} (credential provider clientConfig)`,`${c} (contextual client)`,`${l} (STS default: AWS_REGION, profile region, or us-east-1)`),d},ue=e=>"h2"===e?.metadata?.handlerProtocol;var ge=n(97040),me=n(74534),fe=n(70775),xe=n(5572),ye=n(61019),be=n(94615),Ee=n(45326),we=n(9575),Se=n(68249),ve=n(75279),Ne=n(10860),Te=n(39412),Ae=n(72084),Ce=n(10773),Ie=n(9942),$e=n(23870),_e=n(45547),Pe=n(81974);const ke=async(e,t,n)=>({operation:(0,_e.u)(t).operation,region:await(0,Pe.t)(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),De=e=>{const t=[];return"AssumeRoleWithWebIdentity"===e.operation?t.push({schemeId:"smithy.api#noAuth"}):t.push(function(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}(e)),t};var Re=n(2445),Oe=n(17479),je=n(96965),Me=n(17357),Le=n(17914),Ve=n(5882),Ue=n(24661),qe=n(46109),Fe=n(14433),We=n(5012),ze=n(24176),Be=n(64327),Ke=n(34338),Ge=n(57815),He=n(55425),Xe=n(99816),Qe=n(48828),Ye=n(63139),Ze=n(78607),Je=n(59772),et=n(50469),tt=n(28075);const nt=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",rt=new RegExp("^["+nt+"]["+nt+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function it(e,t){const n=[];let r=t.exec(e);for(;r;){const i=[];i.startIndex=t.lastIndex-r[0].length;const s=r.length;for(let e=0;e<s;e++)i.push(r[e]);n.push(i),r=t.exec(e)}return n}const st=function(e){return!(null==rt.exec(e))},ot=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],at=["__proto__","constructor","prototype"],ct=e=>ot.includes(e)?"__"+e:e,lt={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0,unicode:!1},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,n){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:ct};function dt(e,t){if("string"!=typeof e)return;const n=e.toLowerCase();if(ot.some(e=>n===e.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);if(at.some(e=>n===e.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}function pt(e,t){return"boolean"==typeof e?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof e&&null!==e?{enabled:!1!==e.enabled,maxEntitySize:Math.max(1,e.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,e.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,e.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,e.maxExpandedLength??1e5),maxEntityCount:Math.max(1,e.maxEntityCount??1e3),allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null,appliesTo:e.appliesTo??"all"}:pt(!0)}const ht=function(e){const t=Object.assign({},lt,e),n=[{value:t.attributeNamePrefix,name:"attributeNamePrefix"},{value:t.attributesGroupName,name:"attributesGroupName"},{value:t.textNodeName,name:"textNodeName"},{value:t.cdataPropName,name:"cdataPropName"},{value:t.commentPropName,name:"commentPropName"}];for(const{value:e,name:t}of n)e&&dt(e,t);return null===t.onDangerousProperty&&(t.onDangerousProperty=ct),t.processEntities=pt(t.processEntities,t.htmlEntities),t.unpairedTagsSet=new Set(t.unpairedTags),t.stopNodes&&Array.isArray(t.stopNodes)&&(t.stopNodes=t.stopNodes.map(e=>"string"==typeof e&&e.startsWith("*.")?".."+e.substring(2):e)),t};let ut;ut="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class gt{constructor(e){this.tagname=e,this.child=[],this[":@"]=Object.create(null)}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e,t){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==t&&(this.child[this.child.length-1][ut]={startIndex:t})}static getMetaDataSymbol(){return ut}}const mt=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�",ft=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-",xt=ft+"\\-\\.\\d·̀-ͯ҇‿-⁀",yt=(e,t,n="")=>{const r=`[${e.replace(":","")}][${t.replace(":","")}]*`;return{name:new RegExp(`^[${e}][${t}]*$`,n),ncName:new RegExp(`^${r}$`,n),qName:new RegExp(`^${r}(?::${r})?$`,n),nmToken:new RegExp(`^[${t}]+$`,n),nmTokens:new RegExp(`^[${t}]+(?:\\s+[${t}]+)*$`,n)}},bt=yt(mt,mt+"\\-\\.\\d·̀-ͯ‿-⁀"),Et=yt(ft,xt,"u"),wt=(e,{xmlVersion:t="1.0"}={})=>((e="1.0")=>"1.1"===e?Et:bt)(t).qName.test(e);class St{constructor(e,t){this.suppressValidationErr=!e,this.options=e,this.xmlVersion=t||1}setXmlVersion(e=1){this.xmlVersion=e}readDocType(e,t){const n=Object.create(null);let r=0;if("O"!==e[t+3]||"C"!==e[t+4]||"T"!==e[t+5]||"Y"!==e[t+6]||"P"!==e[t+7]||"E"!==e[t+8])throw new Error("Invalid Tag instead of DOCTYPE");{t+=9;let i=1,s=!1,o=!1,a="";for(;t<e.length;t++)if("<"!==e[t]||o)if(">"===e[t]){if(o?"-"===e[t-1]&&"-"===e[t-2]&&(o=!1,i--):i--,0===i)break}else"["===e[t]?s=!0:a+=e[t];else{if(s&&Nt(e,"!ENTITY",t)){let i,s;if(t+=7,[i,s,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),-1===s.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw new Error(`Entity count (${r+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);n[i]=s,r++}}else if(s&&Nt(e,"!ELEMENT",t)){t+=8;const{index:n}=this.readElementExp(e,t+1);t=n}else if(s&&Nt(e,"!ATTLIST",t))t+=8;else if(s&&Nt(e,"!NOTATION",t)){t+=9;const{index:n}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=n}else{if(!Nt(e,"!--",t))throw new Error("Invalid DOCTYPE");o=!0}i++,a=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:t}}readEntityExp(e,t){const n=t=vt(e,t);for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)t++;let r=e.substring(n,t);if(Tt(r,{xmlVersion:this.xmlVersion}),t=vt(e,t),!this.suppressValidationErr){if("SYSTEM"===e.substring(t,t+6).toUpperCase())throw new Error("External entities are not supported");if("%"===e[t])throw new Error("Parameter entities are not supported")}let i="";if([t,i]=this.readIdentifierVal(e,t,"entity"),!1!==this.options.enabled&&null!=this.options.maxEntitySize&&i.length>this.options.maxEntitySize)throw new Error(`Entity "${r}" size (${i.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[r,i,--t]}readNotationExp(e,t){const n=t=vt(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let r=e.substring(n,t);!this.suppressValidationErr&&Tt(r,{xmlVersion:this.xmlVersion}),t=vt(e,t);const i=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==i&&"PUBLIC"!==i)throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);t+=i.length,t=vt(e,t);let s=null,o=null;if("PUBLIC"===i)[t,s]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=vt(e,t)]&&"'"!==e[t]||([t,o]=this.readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===i&&([t,o]=this.readIdentifierVal(e,t,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:r,publicIdentifier:s,systemIdentifier:o,index:--t}}readIdentifierVal(e,t,n){let r="";const i=e[t];if('"'!==i&&"'"!==i)throw new Error(`Expected quoted string, found "${i}"`);const s=++t;for(;t<e.length&&e[t]!==i;)t++;if(r=e.substring(s,t),e[t]!==i)throw new Error(`Unterminated ${n} value`);return[++t,r]}readElementExp(e,t){const n=t=vt(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let r=e.substring(n,t);if(!this.suppressValidationErr&&!wt(r,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid element name: "${r}"`);let i="";if("E"===e[t=vt(e,t)]&&Nt(e,"MPTY",t))t+=4;else if("A"===e[t]&&Nt(e,"NY",t))t+=2;else if("("===e[t]){const n=++t;for(;t<e.length&&")"!==e[t];)t++;if(i=e.substring(n,t),")"!==e[t])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:r,contentModel:i.trim(),index:t}}readAttlistExp(e,t){let n=t=vt(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let r=e.substring(n,t);for(Tt(r,{xmlVersion:this.xmlVersion}),n=t=vt(e,t);t<e.length&&!/\s/.test(e[t]);)t++;let i=e.substring(n,t);if(!Tt(i,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid attribute name: "${i}"`);t=vt(e,t);let s="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(s="NOTATION","("!==e[t=vt(e,t+=8)])throw new Error(`Expected '(', found "${e[t]}"`);t++;let n=[];for(;t<e.length&&")"!==e[t];){const r=t;for(;t<e.length&&"|"!==e[t]&&")"!==e[t];)t++;let i=e.substring(r,t);if(i=i.trim(),!Tt(i,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid notation name: "${i}"`);n.push(i),"|"===e[t]&&(t++,t=vt(e,t))}if(")"!==e[t])throw new Error("Unterminated list of notations");t++,s+=" ("+n.join("|")+")"}else{const n=t;for(;t<e.length&&!/\s/.test(e[t]);)t++;s+=e.substring(n,t);const r=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!r.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}t=vt(e,t);let o="";return"#REQUIRED"===e.substring(t,t+8).toUpperCase()?(o="#REQUIRED",t+=8):"#IMPLIED"===e.substring(t,t+7).toUpperCase()?(o="#IMPLIED",t+=7):[t,o]=this.readIdentifierVal(e,t,"ATTLIST"),{elementName:r,attributeName:i,attributeType:s,defaultValue:o,index:t}}}const vt=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function Nt(e,t,n){for(let r=0;r<t.length;r++)if(t[r]!==e[n+r+1])return!1;return!0}function Tt(e,t){if(wt(e,{xmlVersion:t}))return e;throw new Error(`Invalid entity name ${e}`)}const At=[48,1632,1776,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,65296,120782,120792,120802,120812,120822,66720,68912,69734,69872,69942,70096,70384,70736,70864,71248,71360,71472,71904,72016,72688,72784,73040,73120,73552,92768,92864,93008,123200,123632,124144,125264,130032],Ct=new Map,It=1632,$t=new Uint8Array(63904).fill(255);for(const e of At)for(let t=0;t<10;t++){const n=e+t;n<=65535?$t[n-It]=t:Ct.set(n,t)}const _t=new Set([8722,65293,65123]),Pt=/^[-+]?0x[a-fA-F0-9]+$/,kt=/^0b[01]+$/,Dt=/^0o[0-7]+$/,Rt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ot={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function jt(e,t={}){if(t=Object.assign({},Ot,t),!e||"string"!=typeof e)return e;let n=e.trim();if(0===n.length)return e;if(void 0!==t.skipLike&&t.skipLike.test(n))return e;if("0"===n)return 0;if(t.unicode&&(n=function(e){if("string"!=typeof e)return e;const t=e.length;if(0===t)return e;let n=-1;for(let r=0;r<t;r++){const i=e.charCodeAt(r);if(!(i>=48&&i<=57||45===i))if(i<It){if(_t.has(i)){n=r;break}}else if(i>=55296&&i<=56319){if(r+1<t){const t=e.charCodeAt(r+1);if(t>=56320&&t<=57343){const e=65536+(i-55296<<10)+(t-56320);if(Ct.has(e)){n=r;break}}}}else if(255!==$t[i-It]||_t.has(i)){n=r;break}}if(-1===n)return e;const r=[];n>0&&r.push(e.slice(0,n));for(let i=n;i<t;i++){const n=e.charCodeAt(i);if(n>=48&&n<=57||45===n){r.push(e[i]);continue}if(n<It){r.push(_t.has(n)?"-":e[i]);continue}if(n>=55296&&n<=56319){if(i+1<t){const t=e.charCodeAt(i+1);if(t>=56320&&t<=57343){const e=65536+(n-55296<<10)+(t-56320),s=Ct.get(e);if(void 0!==s){r.push(String.fromCharCode(s+48)),i++;continue}}}r.push(e[i]);continue}if(_t.has(n)){r.push("-");continue}const s=$t[n-It];r.push(255!==s?String.fromCharCode(s+48):e[i])}return r.join("")}(n),"0"===n))return 0;if(t.hex&&Pt.test(n))return Lt(n,16);if(t.binary&&kt.test(n))return Lt(n,2);if(t.octal&&Dt.test(n))return Lt(n,8);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return function(e,t,n){if(!n.eNotation)return e;const r=t.match(Mt);if(r){let i=r[1]||"";const s=-1===r[3].indexOf("e")?"E":"e",o=r[2],a=i?e[o.length+1]===s:e[o.length]===s;return o.length>1&&a?e:(1!==o.length||!r[3].startsWith(`.${s}`)&&r[3][0]!==s)&&o.length>0?n.leadingZeros&&!a?(t=(r[1]||"")+r[3],Number(t)):e:Number(t)}return e}(e,n,t);{const i=Rt.exec(n);if(i){const s=i[1]||"",o=i[2];let a=(r=i[3])&&-1!==r.indexOf(".")?("."===(r=r.replace(/0+$/,""))?r="0":"."===r[0]?r="0"+r:"."===r[r.length-1]&&(r=r.substring(0,r.length-1)),r):r;const c=s?"."===e[o.length+1]:"."===e[o.length];if(!t.leadingZeros&&(o.length>1||1===o.length&&!c))return e;{const r=Number(n),i=String(r);if(0===r)return r;if(-1!==i.search(/[eE]/))return t.eNotation?r:e;if(-1!==n.indexOf("."))return"0"===i||i===a||i===`${s}${a}`?r:e;let c=o?a:n;return o?c===i||s+c===i?r:e:c===i||c===s+i?r:e}}return e}}var r;return function(e,t,n){const r=t===1/0;switch(n.infinity.toLowerCase()){case"null":return null;case"infinity":return t;case"string":return r?"Infinity":"-Infinity";default:return e}}(e,Number(n),t)}const Mt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Lt(e,t){const n=e.trim();if(2!==t&&8!==t||(e=n.substring(2)),parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}class Vt{constructor(e){this._matcher=e}get separator(){return this._matcher.separator}getCurrentTag(){const e=this._matcher.path;return e.length>0?e[e.length-1].tag:void 0}getCurrentNamespace(){const e=this._matcher.path;return e.length>0?e[e.length-1].namespace:void 0}getAttrValue(e){const t=this._matcher.path;if(0!==t.length)return t[t.length-1].values?.[e]}hasAttr(e){const t=this._matcher.path;if(0===t.length)return!1;const n=t[t.length-1];return void 0!==n.values&&e in n.values}getPosition(){const e=this._matcher.path;return 0===e.length?-1:e[e.length-1].position??0}getCounter(){const e=this._matcher.path;return 0===e.length?-1:e[e.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(e,t=!0){return this._matcher.toString(e,t)}toArray(){return this._matcher.path.map(e=>e.tag)}matches(e){return this._matcher.matches(e)}matchesAny(e){return e.matchesAny(this._matcher)}}class Ut{constructor(e={}){this.separator=e.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new Vt(this)}push(e,t=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);const i=this.siblingStacks[r],s=n?`${n}:${e}`:e,o=i.get(s)||0;let a=0;for(const e of i.values())a+=e;i.set(s,o+1);const c={tag:e,position:a,counter:o};null!=n&&(c.namespace=n),null!=t&&(c.values=t),this.path.push(c)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const e=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),e}updateCurrent(e){if(this.path.length>0){const t=this.path[this.path.length-1];null!=e&&(t.values=e)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(e){if(0!==this.path.length)return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(0===this.path.length)return!1;const t=this.path[this.path.length-1];return void 0!==t.values&&e in t.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(e,t=!0){const n=e||this.separator;if(n===this.separator&&!0===t){if(null!==this._pathStringCache)return this._pathStringCache;const e=this.path.map(e=>e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(n);return this._pathStringCache=e,e}return this.path.map(e=>t&&e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(n)}toArray(){return this.path.map(e=>e.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(e){const t=e.segments;return 0!==t.length&&(e.hasDeepWildcard()?this._matchWithDeepWildcard(t):this._matchSimple(t))}_matchSimple(e){if(this.path.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(!this._matchSegment(e[t],this.path[t],t===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(e){let t=this.path.length-1,n=e.length-1;for(;n>=0&&t>=0;){const r=e[n];if("deep-wildcard"===r.type){if(n--,n<0)return!0;const r=e[n];let i=!1;for(let e=t;e>=0;e--)if(this._matchSegment(r,this.path[e],e===this.path.length-1)){t=e-1,n--,i=!0;break}if(!i)return!1}else{if(!this._matchSegment(r,this.path[t],t===this.path.length-1))return!1;t--,n--}}return n<0}_matchSegment(e,t,n){if("*"!==e.tag&&e.tag!==t.tag)return!1;if(void 0!==e.namespace&&"*"!==e.namespace&&e.namespace!==t.namespace)return!1;if(void 0!==e.attrName){if(!n)return!1;if(!t.values||!(e.attrName in t.values))return!1;if(void 0!==e.attrValue&&String(t.values[e.attrName])!==String(e.attrValue))return!1}if(void 0!==e.position){if(!n)return!1;const r=t.counter??0;if("first"===e.position&&0!==r)return!1;if("odd"===e.position&&r%2!=1)return!1;if("even"===e.position&&r%2!=0)return!1;if("nth"===e.position&&r!==e.positionValue)return!1}return!0}matchesAny(e){return e.matchesAny(this)}snapshot(){return{path:this.path.map(e=>({...e})),siblingStacks:this.siblingStacks.map(e=>new Map(e))}}restore(e){this._pathStringCache=null,this.path=e.path.map(e=>({...e})),this.siblingStacks=e.siblingStacks.map(e=>new Map(e))}readOnly(){return this._view}}class qt{constructor(e,t={},n){this.pattern=e,this.separator=t.separator||".",this.segments=this._parse(e),this.data=n,this._hasDeepWildcard=this.segments.some(e=>"deep-wildcard"===e.type),this._hasAttributeCondition=this.segments.some(e=>void 0!==e.attrName),this._hasPositionSelector=this.segments.some(e=>void 0!==e.position)}_parse(e){const t=[];let n=0,r="";for(;n<e.length;)e[n]===this.separator?n+1<e.length&&e[n+1]===this.separator?(r.trim()&&(t.push(this._parseSegment(r.trim())),r=""),t.push({type:"deep-wildcard"}),n+=2):(r.trim()&&t.push(this._parseSegment(r.trim())),r="",n++):(r+=e[n],n++);return r.trim()&&t.push(this._parseSegment(r.trim())),t}_parseSegment(e){const t={type:"tag"};let n=null,r=e;const i=e.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(i&&(r=i[1]+i[3],i[2])){const e=i[2].slice(1,-1);e&&(n=e)}let s,o,a=r;if(r.includes("::")){const t=r.indexOf("::");if(s=r.substring(0,t).trim(),a=r.substring(t+2).trim(),!s)throw new Error(`Invalid namespace in pattern: ${e}`)}let c=null;if(a.includes(":")){const e=a.lastIndexOf(":"),t=a.substring(0,e).trim(),n=a.substring(e+1).trim();["first","last","odd","even"].includes(n)||/^nth\(\d+\)$/.test(n)?(o=t,c=n):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${e}`);if(t.tag=o,s&&(t.namespace=s),n)if(n.includes("=")){const e=n.indexOf("=");t.attrName=n.substring(0,e).trim(),t.attrValue=n.substring(e+1).trim()}else t.attrName=n.trim();if(c){const e=c.match(/^nth\((\d+)\)$/);e?(t.position="nth",t.positionValue=parseInt(e[1],10)):t.position=c}return t}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class Ft{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(e){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(e.pattern))return this;if(this._patterns.add(e.pattern),e.hasDeepWildcard())return this._deepWildcards.push(e),this;const t=e.length,n=e.segments[e.segments.length-1],r=n?.tag;if(r&&"*"!==r){const n=`${t}:${r}`;this._byDepthAndTag.has(n)||this._byDepthAndTag.set(n,[]),this._byDepthAndTag.get(n).push(e)}else this._wildcardByDepth.has(t)||this._wildcardByDepth.set(t,[]),this._wildcardByDepth.get(t).push(e);return this}addAll(e){for(const t of e)this.add(t);return this}has(e){return this._patterns.has(e.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(e){return null!==this.findMatch(e)}findMatch(e){const t=e.getDepth(),n=`${t}:${e.getCurrentTag()}`,r=this._byDepthAndTag.get(n);if(r)for(let t=0;t<r.length;t++)if(e.matches(r[t]))return r[t];const i=this._wildcardByDepth.get(t);if(i)for(let t=0;t<i.length;t++)if(e.matches(i[t]))return i[t];for(let t=0;t<this._deepWildcards.length;t++)if(e.matches(this._deepWildcards[t]))return this._deepWildcards[t];return null}}const Wt={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},zt={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},Bt={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Kt=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),Gt=new Set("!?\\\\/[]$%{}^&*()<>|+");function Ht(e){if("#"===e[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`);for(const t of e)if(Gt.has(t))throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`);return e}function Xt(...e){const t=Object.create(null);for(const n of e)if(n)for(const e of Object.keys(n)){const r=n[e];if("string"==typeof r)t[e]=r;else if(r&&"object"==typeof r&&void 0!==r.val){const n=r.val;"string"==typeof n&&(t[e]=n)}}return t}const Qt="external",Yt="base",Zt="all",Jt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),en=new Set([9,10,13]);class tn{constructor(e={}){var t;this._limit=e.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof e.postCheck?e.postCheck:e=>e,this._limitTiers=(t=this._limit.applyLimitsTo??Qt)&&t!==Qt?t===Zt?new Set([Zt]):t===Yt?new Set([Yt]):Array.isArray(t)?new Set(t):new Set([Qt]):new Set([Qt]),this._numericAllowed=e.numericAllowed??!0,this._baseMap=Xt(zt,e.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(e.remove&&Array.isArray(e.remove)?e.remove:[]),this._leaveSet=new Set(e.leave&&Array.isArray(e.leave)?e.leave:[]);const n=function(e){if(!e)return{xmlVersion:1,onLevel:Jt.allow,nullLevel:Jt.remove};const t=1.1===e.xmlVersion?1.1:1,n=Jt[e.onNCR]??Jt.allow,r=Jt[e.nullNCR]??Jt.remove;return{xmlVersion:t,onLevel:n,nullLevel:Math.max(r,Jt.remove)}}(e.ncr);this._ncrXmlVersion=n.xmlVersion,this._ncrOnLevel=n.onLevel,this._ncrNullLevel=n.nullLevel,this._onExternalEntity="function"==typeof e.onExternalEntity?e.onExternalEntity:null,this._onInputEntity="function"==typeof e.onInputEntity?e.onInputEntity:null}_applyRegistrationHook(e,t,n,r){if(!e)return!0;const i=e(t,n);if(i===Kt.BLOCK)return!1;if(i===Kt.THROW)throw new Error(`[EntityDecoder] Registration of ${r} entity "&${t};" was rejected by hook`);return!0}setExternalEntities(e){if(e)for(const t of Object.keys(e))Ht(t);if(!this._onExternalEntity)return void(this._externalMap=Xt(e));const t=Xt(e),n=Object.create(null);for(const[e,r]of Object.entries(t))this._applyRegistrationHook(this._onExternalEntity,e,r,"external")&&(n[e]=r);this._externalMap=n}addExternalEntity(e,t){Ht(e),"string"==typeof t&&-1===t.indexOf("&")&&this._applyRegistrationHook(this._onExternalEntity,e,t,"external")&&(this._externalMap[e]=t)}addInputEntities(e){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity)return void(this._inputMap=Xt(e));const t=Xt(e),n=Object.create(null);for(const[e,r]of Object.entries(t))this._applyRegistrationHook(this._onInputEntity,e,r,"input")&&(n[e]=r);this._inputMap=n}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(e){this._ncrXmlVersion=1.1===e?1.1:1}decode(e){if("string"!=typeof e||0===e.length)return e;if(-1===e.indexOf("&"))return e;const t=e,n=[],r=e.length;let i=0,s=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,c=o||a;for(;s<r;){if(38!==e.charCodeAt(s)){s++;continue}let t=s+1;for(;t<r&&59!==e.charCodeAt(t)&&t-s<=32;)t++;if(t>=r||59!==e.charCodeAt(t)){s++;continue}const l=e.slice(s+1,t);if(0===l.length){s++;continue}let d,p;if(this._removeSet.has(l))d="",void 0===p&&(p=Qt);else{if(this._leaveSet.has(l)){s++;continue}if(35===l.charCodeAt(0)){const e=this._resolveNCR(l);if(void 0===e){s++;continue}d=e,p=Yt}else{const e=this._resolveName(l);d=e?.value,p=e?.tier}}if(void 0!==d){if(s>i&&n.push(e.slice(i,s)),n.push(d),i=t+1,s=i,c&&this._tierCounts(p)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const e=d.length-(l.length+2);if(e>0&&(this._expandedLength+=e,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else s++}i<r&&n.push(e.slice(i));const l=0===n.length?e:n.join("");return this._postCheck(l,t)}_tierCounts(e){return!!this._limitTiers.has(Zt)||this._limitTiers.has(e)}_resolveName(e){return e in this._inputMap?{value:this._inputMap[e],tier:Qt}:e in this._externalMap?{value:this._externalMap[e],tier:Qt}:e in this._baseMap?{value:this._baseMap[e],tier:Yt}:void 0}_classifyNCR(e){return 0===e?this._ncrNullLevel:e>=55296&&e<=57343||1===this._ncrXmlVersion&&e>=1&&e<=31&&!en.has(e)?Jt.remove:-1}_applyNCRAction(e,t,n){switch(e){case Jt.allow:return String.fromCodePoint(n);case Jt.remove:return"";case Jt.leave:return;case Jt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${t}; (U+${n.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(n)}}_resolveNCR(e){const t=e.charCodeAt(1);let n;if(n=120===t||88===t?parseInt(e.slice(2),16):parseInt(e.slice(1),10),Number.isNaN(n)||n<0||n>1114111)return;const r=this._classifyNCR(n);if(!this._numericAllowed&&r<Jt.remove)return;const i=-1===r?this._ncrOnLevel:Math.max(this._ncrOnLevel,r);return this._applyNCRAction(i,e,n)}}const nn=[{id:"sql-block-comment-open",description:"SQL block comment open: /* ... */ — unusual in legitimate user text",pattern:/\/\*/},{id:"sql-union-select",description:"UNION SELECT — most common SQL injection aggregation attack",pattern:/\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i},{id:"sql-drop-table",description:"DROP TABLE — destructive DDL injection",pattern:/\bDROP\s{1,20}TABLE\b/i},{id:"sql-drop-database",description:"DROP DATABASE — destructive DDL injection",pattern:/\bDROP\s{1,20}DATABASE\b/i},{id:"sql-insert-into",description:"INSERT INTO — data injection",pattern:/\bINSERT\s{1,20}INTO\b/i},{id:"sql-delete-from",description:"DELETE FROM — data deletion injection",pattern:/\bDELETE\s{1,20}FROM\b/i},{id:"sql-update-set",description:"UPDATE ... SET — data modification injection",pattern:/\bUPDATE\b[\s\S]{1,60}\bSET\b/i},{id:"sql-exec-xp",description:"EXEC xp_ — MSSQL extended stored procedure execution",pattern:/\bEXEC(?:UTE)?\s{1,20}xp_/i},{id:"sql-tautology-string",description:'Classic string tautology: \' OR \'1\'=\'1 or " OR "1"="1"',pattern:/'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i},{id:"sql-tautology-numeric",description:"Numeric tautology: OR 1=1",pattern:/\bOR\s{1,10}1\s*=\s*1\b/i},{id:"sql-always-true-zero",description:"Numeric tautology: OR 0=0",pattern:/\bOR\s{1,10}0\s*=\s*0\b/i},{id:"sql-sleep-benchmark",description:"Time-based blind injection: SLEEP() or BENCHMARK()",pattern:/\b(?:SLEEP|BENCHMARK)\s*\(/i},{id:"sql-waitfor-delay",description:"MSSQL time-based blind injection: WAITFOR DELAY",pattern:/\bWAITFOR\s{1,20}DELAY\b/i},{id:"sql-char-function",description:"CHAR() function — used to obfuscate injected strings",pattern:/\bCHAR\s*\(\s*\d{1,3}/i},{id:"sql-information-schema",description:"INFORMATION_SCHEMA — reconnaissance query for table/column enumeration",pattern:/\bINFORMATION_SCHEMA\b/i}],rn="[\"'\\s]*:",sn={HTML:[{id:"html-script-open",description:"<script opening tag",pattern:/<script[\s>/]/i},{id:"html-script-close",description:"<\/script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI — can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI — can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded <script (e.g. <script or <script)",pattern:/(?:�*3[Cc];?|�*60;?|<)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial — catches common j or j for "j")',pattern:/(?:�*6[Aa];?|�*106;?)\s*(?:�*61;?|a)[\s\S]{0,80}script\s*:/i},{id:"html-style-expression",description:"CSS expression() — IE-era code execution in style attributes",pattern:/style[\s\S]{0,20}expression\s*\(/i},{id:"html-object-embed",description:"<object or <embed tags that can load active content",pattern:/<(?:object|embed)[\s>/]/i},{id:"html-base-tag",description:"<base href= — can hijack all relative URLs on a page",pattern:/<base[\s>]/i},{id:"html-meta-refresh",description:'<meta http-equiv="refresh" — can redirect users',pattern:/<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i},{id:"html-srcdoc",description:"srcdoc= attribute on iframes — embeds HTML that can run scripts",pattern:/srcdoc\s*=/i},{id:"html-iframe",description:"<iframe tag",pattern:/<iframe[\s>/]/i},{id:"html-form",description:"<form tag — can be used for phishing / credential harvesting injection",pattern:/<form[\s>/]/i}],XML:[{id:"xml-cdata-injection",description:"CDATA section injection: <![CDATA[ breaks out of text node context",pattern:/<!\[CDATA\[/i},{id:"xml-cdata-close",description:"CDATA close sequence: ]]> can terminate an enclosing CDATA section",pattern:/\]\]>/},{id:"xml-processing-instruction",description:"XML processing instruction: <?xml-stylesheet or <?php etc.",pattern:/<\?(?:xml[\- ]|php|asp)/i},{id:"xml-doctype-injection",description:"DOCTYPE declaration embedded in content — can define entities",pattern:/<!DOCTYPE(?:[\s[]|$)/i},{id:"xml-entity-system",description:"SYSTEM keyword — used in external entity declarations (XXE)",pattern:/\bSYSTEM\s+["']/i},{id:"xml-entity-public",description:"PUBLIC keyword — used in external entity declarations (XXE)",pattern:/\bPUBLIC\s+["']/i},{id:"xml-entity-declaration",description:"<!ENTITY declaration — defines entities, potential XXE or entity expansion",pattern:/<!ENTITY[\s%]/i},{id:"xml-billion-laughs",description:"Entity reference chaining / billion laughs: repeated &eX; style references",pattern:/(?:&\w{1,20};){3,}/},{id:"xml-namespace-confusion",description:"xmlns: attribute injection — can redefine namespaces to confuse parsers",pattern:/\bxmlns\s*(?::\w{1,40})?\s*=/i},{id:"xml-comment-injection",description:"\x3c!-- comment injection — can hide content from some parsers",pattern:/<!--/},{id:"xml-comment-close",description:"--\x3e closes an enclosing XML comment",pattern:/-->/},{id:"xml-pi-close",description:"?> closes an enclosing processing instruction",pattern:/\?>/}],SVG:[{id:"svg-script-element",description:"<script element inside SVG executes JavaScript",pattern:/<script[\s>/]/i},{id:"svg-xlink-href-javascript",description:"xlink:href with javascript: — classic SVG XSS via <a> or <use>",pattern:/xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-href-javascript",description:"href= with javascript: in SVG context (<a>, <animate>, etc.)",pattern:/href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-foreignobject",description:"<foreignObject embeds HTML inside SVG — can execute scripts",pattern:/<foreignObject[\s>/]/i},{id:"svg-use-external",description:"<use xlink:href or href pointing to external resource (non-fragment URL)",pattern:/<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i},{id:"svg-animate-href",description:'<animate attributeName="href" — can dynamically change href to javascript:',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i},{id:"svg-animate-xlinkhref",description:'<animate attributeName="xlink:href"',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i},{id:"svg-set-javascript",description:'<set to="javascript:..." — sets an attribute to a javascript: URI',pattern:/<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-event-handler",description:"SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",pattern:/\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i},{id:"svg-handler-generic",description:"Generic on* handler catch-all for SVG attributes",pattern:/\bon\w{1,30}\s*=/i},{id:"svg-filter-feimage",description:"<feImage href= — filter primitive that can load external resources",pattern:/<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i},{id:"svg-image-external",description:"<image xlink:href with http/https or javascript protocol",pattern:/<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i},{id:"svg-style-javascript",description:"style= attribute containing javascript: (e.g. background:url(javascript:...))",pattern:/style\s*=[\s\S]{0,60}javascript\s*:/i}],SQL:nn,"SQL-STRICT":[...nn,{id:"sql-line-comment",description:"SQL line comment: -- followed by whitespace or end of string",pattern:/--(?:\s|$)/},{id:"sql-stacked-query",description:"Stacked queries: semicolon immediately followed by a SQL keyword",pattern:/;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i},{id:"sql-hex-encoding",description:"Hex-encoded string injection: 0x41414141 style (MySQL)",pattern:/\b0x[0-9a-f]{4,}/i}],SHELL:[{id:"shell-path-traversal-unix",description:"Unix path traversal: ../ — climbing the directory tree",pattern:/\.\.\//},{id:"shell-path-traversal-windows",description:"Windows path traversal: ..\\ — climbing the directory tree",pattern:/\.\.\\/},{id:"shell-path-traversal-encoded",description:"URL-encoded path traversal: %2e%2e or %2f variants",pattern:/%2e%2e|%2f\.\.|\.\.%2f/i},{id:"shell-null-byte",description:"Null byte injection: \\x00 or %00 — truncates strings in C-backed functions",pattern:/\x00|%00/},{id:"shell-semicolon",description:"Semicolon command separator: cmd1; cmd2",pattern:/;/},{id:"shell-pipe",description:"Pipe operator: cmd1 | cmd2",pattern:/\|/},{id:"shell-and-operator",description:"AND operator: cmd1 && cmd2",pattern:/&&/},{id:"shell-or-operator",description:"OR operator: cmd1 || cmd2",pattern:/\|\|/},{id:"shell-backtick",description:"Backtick command substitution: `cmd`",pattern:/`/},{id:"shell-dollar-paren",description:"Dollar-paren command substitution: $(cmd)",pattern:/\$\(/},{id:"shell-dollar-brace",description:"Dollar-brace variable expansion: ${var} — can be abused for injection",pattern:/\$\{/},{id:"shell-redirect-out",description:"Output redirection: cmd > file or cmd >> file",pattern:/>{1,2}/},{id:"shell-redirect-in",description:"Input redirection: cmd < file",pattern:/</},{id:"shell-newline-injection",description:"Newline injection: \\n or \\r — can inject new shell commands",pattern:/[\n\r]/},{id:"shell-glob-star",description:"Glob expansion: * or ? — can expand to unintended files",pattern:/[/\\][*?]/},{id:"shell-absolute-root",description:"Absolute root path injection: string starting with / or \\ (Windows UNC)",pattern:/^(?:\/|\\\\)/},{id:"shell-windows-drive",description:"Windows drive letter path injection: C:\\ or D:/",pattern:/^[a-zA-Z]:[/\\]/},{id:"shell-curl-wget",description:"curl/wget with URL or flags — can exfiltrate data or download payloads",pattern:/\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i}],REDOS:[{id:"redos-nested-quantifier-plus",description:"Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",pattern:/\([^)]*\+[^)]*\)[+*]/},{id:"redos-nested-quantifier-star",description:"Nested * quantifier: (a*)* or (a*)+ — catastrophic backtracking",pattern:/\([^)]*\*[^)]*\)[*+]/},{id:"redos-nested-groups",description:"Doubly nested quantified groups: ((a+)+) — guaranteed catastrophic",pattern:/\(\([^)]{0,40}\)[+*]\)[+*]/},{id:"redos-alternation-overlap",description:"Overlapping alternation under quantifier: (a|a)+ — ambiguous NFA paths",pattern:/\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/},{id:"redos-star-plus-concat",description:"(x*x)+ pattern — triggers super-linear backtracking",pattern:/\([^)]{0,10}\*[^)]{0,10}\)[+*]/},{id:"redos-dot-star-greedy",description:"(.*){n,} or (.+){n,} — repeated greedy dot quantifiers",pattern:/\(\.[*+]\)\{?\d/},{id:"redos-large-repetition",description:"Very large fixed or range repetition count {1000,} or {1000,n} — denial of service via backtracking",pattern:/\{\d{4,}(?:,\d*)?\}/},{id:"redos-catastrophic-alternation",description:"Long alternation with many similar branches — polynomial backtracking risk",pattern:/\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/}],NOSQL:[{id:"nosql-where-operator",description:"$where — executes arbitrary JavaScript server-side in MongoDB",pattern:new RegExp(`\\$where${rn}`,"i")},{id:"nosql-ne-operator",description:'$ne — "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${rn}`,"i")},{id:"nosql-gt-operator",description:'$gt — "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${rn}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte — "less than" bypass variants',pattern:new RegExp(`\\$lte?${rn}`,"i")},{id:"nosql-regex-operator",description:"$regex — can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${rn}`,"i")},{id:"nosql-or-operator",description:"$or — logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${rn}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and — logical AND operator injection",pattern:new RegExp(`\\$and${rn}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor — logical NOR operator injection",pattern:new RegExp(`\\$nor${rn}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists — can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${rn}`,"i")},{id:"nosql-in-operator",description:"$in — matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${rn}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr — allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${rn}`,"i")},{id:"nosql-function-operator",description:"$function — executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${rn}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator — custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${rn}`,"i")},{id:"nosql-proto-pollution",description:"__proto__ — prototype pollution via object key injection",pattern:/__proto__/},{id:"nosql-constructor-prototype",description:"constructor.prototype — alternative prototype pollution vector (dot notation or JSON key)",pattern:/constructor[\s"':.,{\[]*prototype/i},{id:"nosql-proto-bracket",description:'["__proto__"] — bracket-notation prototype pollution',pattern:/\[["']__proto__["']\]/}],LOG:[{id:"log-crlf-injection",description:"CRLF injection: literal \\r or \\n embeds fake log lines",pattern:/[\r\n]/},{id:"log-url-encoded-crlf",description:"URL-encoded CRLF: %0d, %0a, %0D, %0A — decoded by some log parsers",pattern:/%0[dDaA]/},{id:"log-unicode-newline",description:"Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",pattern:/[\u2028\u2029]/},{id:"log-log4shell-jndi",description:"Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",pattern:/\$\{jndi\s*:/i},{id:"log-log4shell-obfuscated",description:"Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",pattern:/\$\{::-/},{id:"log-log4j-lookup",description:"Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} — data exfiltration",pattern:/\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i},{id:"log-ssti-double-brace",description:"SSTI double-brace: {{expression}} — Jinja2, Twig, Handlebars, etc.",pattern:/\{\{[\s\S]{0,80}\}\}/},{id:"log-ssti-hash-brace",description:"SSTI hash-brace: #{expression} — Thymeleaf, Velocity, Ruby ERB",pattern:/#\{[\s\S]{0,80}\}/},{id:"log-ssti-dollar-brace",description:"SSTI/EL injection: ${expression with operators or method calls} — JSP EL, Freemarker, SpEL",pattern:/\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i},{id:"log-ssti-percent-tag",description:"SSTI ERB/ASP tag: <%= expression %> — Ruby ERB, ASP",pattern:/<%=[\s\S]{0,80}%>/},{id:"log-null-byte",description:"Null byte: \\x00 or %00 — can truncate log entries in C-backed loggers",pattern:/\x00|%00/},{id:"log-ansi-escape",description:"ANSI escape sequence: ESC[ — can manipulate terminal output when logs are tailed",pattern:/\x1b\[/}]},on=sn,an=Object.freeze(Object.fromEntries(Object.keys(sn).map(e=>[e,e])));function cn(e,t){const n=on[t];for(const r of n)if(r.pattern.test(e))return{context:t,id:r.id,description:r.description,pattern:r.pattern};return null}function ln(e,t){if(function(e){if("string"!=typeof e)throw new TypeError("is-unsafe: first argument must be a string, got "+typeof e)}(e),function(e){if(!(e instanceof RegExp))if("string"!=typeof e){if(!Array.isArray(e))throw new TypeError("is-unsafe: second argument must be a context string, array of context strings, or RegExp. Got: "+typeof e);if(0===e.length)throw new TypeError("is-unsafe: context array must not be empty");for(const t of e)if("string"!=typeof t||!on[t])throw new TypeError(`is-unsafe: unknown context "${t}" in array. Valid contexts: ${Object.keys(an).join(", ")}`)}else if(!on[e])throw new TypeError(`is-unsafe: unknown context "${e}". Valid contexts: ${Object.keys(an).join(", ")}`)}(t),t instanceof RegExp)return t.test(e);if("string"==typeof t)return null!==cn(e,t);for(const n of t)if(null!==cn(e,n))return!0;return!1}function dn(e,t){if(!e)return{};const n=t.attributesGroupName?e[t.attributesGroupName]:e;if(!n)return{};const r={};for(const e in n)e.startsWith(t.attributeNamePrefix)?r[e.substring(t.attributeNamePrefix.length)]=n[e]:r[e]=n[e];return r}function pn(e){if(!e||"string"!=typeof e)return;const t=e.indexOf(":");if(-1!==t&&t>0){const n=e.substring(0,t);if("xmlns"!==n)return n}}class hn{constructor(e,t){var n;this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=xn,this.parseTextData=un,this.resolveNameSpace=gn,this.buildAttributesMap=fn,this.isItStopNode=wn,this.replaceEntitiesValue=bn,this.readStopNodeData=Tn,this.saveTextToParentTag=En,this.addChild=yn,this.ignoreAttributesFn="function"==typeof(n=this.options.ignoreAttributes)?n:Array.isArray(n)?e=>{for(const t of n){if("string"==typeof t&&e===t)return!0;if(t instanceof RegExp&&t.test(e))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let r={...zt};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?r=this.options.htmlEntities:!0===this.options.htmlEntities&&(r={...Bt,...Wt}),this.entityDecoder=new tn({namedEntities:{...r,...t},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo},onInputEntity:(e,t)=>ln(t,[an.HTML,an.XML])?Kt.BLOCK:Kt.ALLOW})),this.matcher=new Ut,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new Ft;const i=this.options.stopNodes;if(i&&i.length>0){for(let e=0;e<i.length;e++){const t=i[e];"string"==typeof t?this.stopNodeExpressionsSet.add(new qt(t)):t instanceof qt&&this.stopNodeExpressionsSet.add(t)}this.stopNodeExpressionsSet.seal()}}}function un(e,t,n,r,i,s,o){const a=this.options;if(void 0!==e&&(a.trimValues&&!r&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,n));const r=a.jPath?n.toString():n,c=a.tagValueProcessor(t,e,r,i,s);return null==c?e:typeof c!=typeof e||c!==e?c:a.trimValues||e.trim()===e?An(e,a.parseTagValue,a.numberParseOptions):e}}function gn(e){if(this.options.removeNSPrefix){const t=e.split(":"),n="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=n+t[1])}return e}const mn=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function fn(e,t,n,r=!1){const i=this.options;if(!0===r||!0!==i.ignoreAttributes&&"string"==typeof e){const r=it(e,mn),s=r.length,o={},a=new Array(s);let c=!1;const l={};for(let e=0;e<s;e++){const t=this.resolveNameSpace(r[e][1]),s=r[e][4];if(t.length&&void 0!==s){let r=s;i.trimValues&&(r=r.trim()),r=this.replaceEntitiesValue(r,n,this.readonlyMatcher),a[e]=r,l[t]=r,c=!0}}c&&"object"==typeof t&&t.updateCurrent&&t.updateCurrent(l);const d=i.jPath?t.toString():this.readonlyMatcher;let p=!1;for(let e=0;e<s;e++){const t=this.resolveNameSpace(r[e][1]);if(this.ignoreAttributesFn(t,d))continue;let n=i.attributeNamePrefix+t;if(t.length)if(i.transformAttributeName&&(n=i.transformAttributeName(n)),n=In(n,i),void 0!==r[e][4]){const r=a[e],s=i.attributeValueProcessor(t,r,d);o[n]=null==s?r:typeof s!=typeof r||s!==r?s:An(r,i.parseAttributeValue,i.numberParseOptions),p=!0}else i.allowBooleanAttributes&&(o[n]=!0,p=!0)}if(!p)return;if(i.attributesGroupName&&!i.preserveOrder){const e={};return e[i.attributesGroupName]=o,e}return o}}const xn=function(e){e=e.replace(/\r\n?/g,"\n");const t=new gt("!xml");let n=t,r="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const i=this.options,s=new St(i.processEntities),o=e.length;for(let a=0;a<o;a++)if("<"===e[a]){const c=e.charCodeAt(a+1);if(47===c){const t=Sn(e,">",a,"Closing Tag is not closed.");let s=e.substring(a+2,t).trim();if(i.removeNSPrefix){const e=s.indexOf(":");-1!==e&&(s=s.substr(e+1))}s=Cn(i.transformTagName,s,"",i).tagName,n&&(r=this.saveTextToParentTag(r,n,this.readonlyMatcher));const o=this.matcher.getCurrentTag();if(s&&i.unpairedTagsSet.has(s))throw new Error(`Unpaired tag can not be used as closing tag: </${s}>`);o&&i.unpairedTagsSet.has(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,n=this.tagsNodeStack.pop(),r="",a=t}else if(63===c){let t=Nn(e,a,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");r=this.saveTextToParentTag(r,n,this.readonlyMatcher);const o=this.buildAttributesMap(t.tagExp,this.matcher,t.tagName,!0);if(o){const e=o[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(e)||1),s.setXmlVersion(Number(e)||1)}if(i.ignoreDeclaration&&"?xml"===t.tagName||i.ignorePiTags);else{const e=new gt(t.tagName);e.add(i.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&!0!==i.ignoreAttributes&&(e[":@"]=o),this.addChild(n,e,this.readonlyMatcher,a)}a=t.closeIndex+1}else if(33===c&&45===e.charCodeAt(a+2)&&45===e.charCodeAt(a+3)){const t=Sn(e,"--\x3e",a+4,"Comment is not closed.");if(i.commentPropName){const s=e.substring(a+4,t-2);r=this.saveTextToParentTag(r,n,this.readonlyMatcher),n.add(i.commentPropName,[{[i.textNodeName]:s}])}a=t}else if(33===c&&68===e.charCodeAt(a+2)){const t=s.readDocType(e,a);this.entityDecoder.addInputEntities(t.entities),a=t.i}else if(33===c&&91===e.charCodeAt(a+2)){const t=Sn(e,"]]>",a,"CDATA is not closed.")-2,s=e.substring(a+9,t);r=this.saveTextToParentTag(r,n,this.readonlyMatcher);let o=this.parseTextData(s,n.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==o&&(o=""),i.cdataPropName?n.add(i.cdataPropName,[{[i.textNodeName]:s}]):n.add(i.textNodeName,o),a=t+2}else{let s=Nn(e,a,i.removeNSPrefix);if(!s){const t=e.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${t}"`)}let c=s.tagName;const l=s.rawTagName;let d=s.tagExp,p=s.attrExpPresent,h=s.closeIndex;if(({tagName:c,tagExp:d}=Cn(i.transformTagName,c,d,i)),i.strictReservedNames&&(c===i.commentPropName||c===i.cdataPropName||c===i.textNodeName||c===i.attributesGroupName))throw new Error(`Invalid tag name: ${c}`);n&&r&&"!xml"!==n.tagname&&(r=this.saveTextToParentTag(r,n,this.readonlyMatcher,!1));const u=n;u&&i.unpairedTagsSet.has(u.tagname)&&(n=this.tagsNodeStack.pop(),this.matcher.pop());let g=!1;d.length>0&&d.lastIndexOf("/")===d.length-1&&(g=!0,"/"===c[c.length-1]?(c=c.substr(0,c.length-1),d=c):d=d.substr(0,d.length-1),p=c!==d);let m,f=null,x={};m=pn(l),c!==t.tagname&&this.matcher.push(c,{},m),c!==d&&p&&(f=this.buildAttributesMap(d,this.matcher,c),f&&(x=dn(f,i))),c!==t.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const y=a;if(this.isCurrentNodeStopNode){let t="";if(g)a=s.closeIndex;else if(i.unpairedTagsSet.has(c))a=s.closeIndex;else{const n=this.readStopNodeData(e,l,h+1);if(!n)throw new Error(`Unexpected end of ${l}`);a=n.i,t=n.tagContent}const r=new gt(c);f&&(r[":@"]=f),r.add(i.textNodeName,t),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(n,r,this.readonlyMatcher,y)}else{if(g){({tagName:c,tagExp:d}=Cn(i.transformTagName,c,d,i));const e=new gt(c);f&&(e[":@"]=f),this.addChild(n,e,this.readonlyMatcher,y),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(i.unpairedTagsSet.has(c)){const e=new gt(c);f&&(e[":@"]=f),this.addChild(n,e,this.readonlyMatcher,y),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=s.closeIndex;continue}{const e=new gt(c);if(this.tagsNodeStack.length>i.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),f&&(e[":@"]=f),this.addChild(n,e,this.readonlyMatcher,y),n=e}}r="",a=h}}}else r+=e[a];return t.child};function yn(e,t,n,r){this.options.captureMetaData||(r=void 0);const i=this.options.jPath?n.toString():n,s=this.options.updateTag(t.tagname,i,t[":@"]);!1===s||("string"==typeof s?(t.tagname=s,e.addChild(t,r)):e.addChild(t,r))}function bn(e,t,n){const r=this.options.processEntities;if(!r||!r.enabled)return e;if(r.allowedTags){const i=this.options.jPath?n.toString():n;if(!(Array.isArray(r.allowedTags)?r.allowedTags.includes(t):r.allowedTags(t,i)))return e}if(r.tagFilter){const i=this.options.jPath?n.toString():n;if(!r.tagFilter(t,i))return e}return this.entityDecoder.decode(e)}function En(e,t,n,r){return e&&(void 0===r&&(r=0===t.child.length),void 0!==(e=this.parseTextData(e,t.tagname,n,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,r))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function wn(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Sn(e,t,n,r){const i=e.indexOf(t,n);if(-1===i)throw new Error(r);return i+t.length-1}function vn(e,t,n,r){const i=e.indexOf(t,n);if(-1===i)throw new Error(r);return i}function Nn(e,t,n,r=">"){const i=function(e,t,n=">"){let r=0;const i=e.length,s=n.charCodeAt(0),o=n.length>1?n.charCodeAt(1):-1;let a="",c=t;for(let n=t;n<i;n++){const t=e.charCodeAt(n);if(r)t===r&&(r=0);else if(34===t||39===t)r=t;else if(t===s){if(-1===o)return a+=e.substring(c,n),{data:a,index:n};if(e.charCodeAt(n+1)===o)return a+=e.substring(c,n),{data:a,index:n}}else 9!==t||r||(a+=e.substring(c,n)+" ",c=n+1)}}(e,t+1,r);if(!i)return;let s=i.data;const o=i.index,a=s.search(/\s/);let c=s,l=!0;-1!==a&&(c=s.substring(0,a),s=s.substring(a+1).trimStart());const d=c;if(n){const e=c.indexOf(":");-1!==e&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:s,closeIndex:o,attrExpPresent:l,rawTagName:d}}function Tn(e,t,n){const r=n;let i=1;const s=e.length;for(;n<s;n++)if("<"===e[n]){const s=e.charCodeAt(n+1);if(47===s){const s=vn(e,">",n,`${t} is not closed`);if(e.substring(n+2,s).trim()===t&&(i--,0===i))return{tagContent:e.substring(r,n),i:s};n=s}else if(63===s)n=Sn(e,"?>",n+1,"StopNode is not closed.");else if(33===s&&45===e.charCodeAt(n+2)&&45===e.charCodeAt(n+3))n=Sn(e,"--\x3e",n+3,"StopNode is not closed.");else if(33===s&&91===e.charCodeAt(n+2))n=Sn(e,"]]>",n,"StopNode is not closed.")-2;else{const r=Nn(e,n,!1);r&&((r&&r.tagName)===t&&"/"!==r.tagExp[r.tagExp.length-1]&&i++,n=r.closeIndex)}}}function An(e,t,n){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&jt(e,n)}return function(e){return void 0!==e}(e)?e:""}function Cn(e,t,n,r){if(e){const r=e(t);n===t&&(n=r),t=r}return{tagName:t=In(t,r),tagExp:n}}function In(e,t){if(at.includes(e))throw new Error(`[SECURITY] Invalid name: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);return ot.includes(e)?t.onDangerousProperty(e):e}const $n=gt.getMetaDataSymbol();function _n(e,t){if(!e||"object"!=typeof e)return{};if(!t)return e;const n={};for(const r in e)r.startsWith(t)?n[r.substring(t.length)]=e[r]:n[r]=e[r];return n}function Pn(e,t,n,r){return kn(e,t,n,r)}function kn(e,t,n,r){let i;const s={};for(let o=0;o<e.length;o++){const a=e[o],c=Dn(a);if(void 0!==c&&c!==t.textNodeName){const e=_n(a[":@"]||{},t.attributeNamePrefix);n.push(c,e)}if(c===t.textNodeName)void 0===i?i=a[c]:i+=""+a[c];else{if(void 0===c)continue;if(a[c]){let e=kn(a[c],t,n,r);const i=On(e,t);if(0===Object.keys(e).length&&t.alwaysCreateTextNode&&(e[t.textNodeName]=""),a[":@"]?Rn(e,a[":@"],r,t):1!==Object.keys(e).length||void 0===e[t.textNodeName]||t.alwaysCreateTextNode?0===Object.keys(e).length&&(t.alwaysCreateTextNode?e[t.textNodeName]="":e=""):e=e[t.textNodeName],void 0!==a[$n]&&"object"==typeof e&&null!==e&&(e[$n]=a[$n]),void 0!==s[c]&&Object.prototype.hasOwnProperty.call(s,c))Array.isArray(s[c])||(s[c]=[s[c]]),s[c].push(e);else{const n=t.jPath?r.toString():r;t.isArray(c,n,i)?s[c]=[e]:s[c]=e}void 0!==c&&c!==t.textNodeName&&n.pop()}}}return"string"==typeof i?i.length>0&&(s[t.textNodeName]=i):void 0!==i&&(s[t.textNodeName]=i),s}function Dn(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const n=t[e];if(":@"!==n)return n}}function Rn(e,t,n,r){if(t){const i=Object.keys(t),s=i.length;for(let o=0;o<s;o++){const s=i[o],a=s.startsWith(r.attributeNamePrefix)?s.substring(r.attributeNamePrefix.length):s,c=r.jPath?n.toString()+"."+a:n;r.isArray(s,c,!0,!0)?e[s]=[t[s]]:e[s]=t[s]}}}function On(e,t){const{textNodeName:n}=t,r=Object.keys(e).length;return 0===r||!(1!==r||!e[n]&&"boolean"!=typeof e[n]&&0!==e[n])}const jn={allowBooleanAttributes:!1,unpairedTags:[]};function Mn(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function Ln(e,t){const n=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const r=e.substr(n,t-n);if(t>5&&"xml"===r)return zn("InvalidXml","XML declaration allowed only at the start of the document.",Gn(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function Vn(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t<e.length;t++)if("-"===e[t]&&"-"===e[t+1]&&">"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let n=1;for(t+=8;t<e.length;t++)if("<"===e[t])n++;else if(">"===e[t]&&(n--,0===n))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t<e.length;t++)if("]"===e[t]&&"]"===e[t+1]&&">"===e[t+2]){t+=2;break}return t}function Un(e,t){let n="",r="",i=!1;for(;t<e.length;t++){if('"'===e[t]||"'"===e[t])""===r?r=e[t]:r!==e[t]||(r="");else if(">"===e[t]&&""===r){i=!0;break}n+=e[t]}return""===r&&{value:n,index:t,tagClosed:i}}const qn=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Fn(e,t){const n=it(e,qn),r={};for(let e=0;e<n.length;e++){if(0===n[e][1].length)return zn("InvalidAttr","Attribute '"+n[e][2]+"' has no space in starting.",Hn(n[e]));if(void 0!==n[e][3]&&void 0===n[e][4])return zn("InvalidAttr","Attribute '"+n[e][2]+"' is without value.",Hn(n[e]));if(void 0===n[e][3]&&!t.allowBooleanAttributes)return zn("InvalidAttr","boolean attribute '"+n[e][2]+"' is not allowed.",Hn(n[e]));const i=n[e][2];if(!Bn(i))return zn("InvalidAttr","Attribute '"+i+"' is an invalid name.",Hn(n[e]));if(Object.prototype.hasOwnProperty.call(r,i))return zn("InvalidAttr","Attribute '"+i+"' is repeated.",Hn(n[e]));r[i]=1}return!0}function Wn(e,t){if(";"===e[++t])return-1;if("#"===e[t])return function(e,t){let n=/\d/;for("x"===e[t]&&(t++,n=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(n))break}return-1}(e,++t);let n=0;for(;t<e.length;t++,n++)if(!(e[t].match(/\w/)&&n<20)){if(";"===e[t])break;return-1}return t}function zn(e,t,n){return{err:{code:e,msg:t,line:n.line||n,col:n.col}}}function Bn(e){return st(e)}function Kn(e){return st(e)}function Gn(e,t){const n=e.substring(0,t).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Hn(e){return e.startIndex+e[1].length}const Xn=new class{constructor(e){this.externalEntities={},this.options=ht(e)}parse(e,t){if("string"!=typeof e&&e.toString)e=e.toString();else if("string"!=typeof e)throw new Error("XML data is accepted in String or Bytes[] form.");if(t){!0===t&&(t={});const n=function(e,t){t=Object.assign({},jn,t);const n=[];let r=!1,i=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let s=0;s<e.length;s++)if("<"===e[s]&&"?"===e[s+1]){if(s+=2,s=Ln(e,s),s.err)return s}else{if("<"!==e[s]){if(Mn(e[s]))continue;return zn("InvalidChar","char '"+e[s]+"' is not expected.",Gn(e,s))}{let o=s;if(s++,"!"===e[s]){s=Vn(e,s);continue}{let a=!1;"/"===e[s]&&(a=!0,s++);let c="";for(;s<e.length&&">"!==e[s]&&" "!==e[s]&&"\t"!==e[s]&&"\n"!==e[s]&&"\r"!==e[s];s++)c+=e[s];if(c=c.trim(),"/"===c[c.length-1]&&(c=c.substring(0,c.length-1),s--),!Kn(c)){let t;return t=0===c.trim().length?"Invalid space after '<'.":"Tag '"+c+"' is an invalid name.",zn("InvalidTag",t,Gn(e,s))}const l=Un(e,s);if(!1===l)return zn("InvalidAttr","Attributes for '"+c+"' have open quote.",Gn(e,s));let d=l.value;if(s=l.index,"/"===d[d.length-1]){const n=s-d.length;d=d.substring(0,d.length-1);const i=Fn(d,t);if(!0!==i)return zn(i.err.code,i.err.msg,Gn(e,n+i.err.line));r=!0}else if(a){if(!l.tagClosed)return zn("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",Gn(e,s));if(d.trim().length>0)return zn("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",Gn(e,o));if(0===n.length)return zn("InvalidTag","Closing tag '"+c+"' has not been opened.",Gn(e,o));{const t=n.pop();if(c!==t.tagName){let n=Gn(e,t.tagStartPos);return zn("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+c+"'.",Gn(e,o))}0==n.length&&(i=!0)}}else{const a=Fn(d,t);if(!0!==a)return zn(a.err.code,a.err.msg,Gn(e,s-d.length+a.err.line));if(!0===i)return zn("InvalidXml","Multiple possible root nodes found.",Gn(e,s));-1!==t.unpairedTags.indexOf(c)||n.push({tagName:c,tagStartPos:o}),r=!0}for(s++;s<e.length;s++)if("<"===e[s]){if("!"===e[s+1]){s++,s=Vn(e,s);continue}if("?"!==e[s+1])break;if(s=Ln(e,++s),s.err)return s}else if("&"===e[s]){const t=Wn(e,s);if(-1==t)return zn("InvalidChar","char '&' is not expected.",Gn(e,s));s=t}else if(!0===i&&!Mn(e[s]))return zn("InvalidXml","Extra text at the end",Gn(e,s));"<"===e[s]&&s--}}}return r?1==n.length?zn("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",Gn(e,n[0].tagStartPos)):!(n.length>0)||zn("InvalidXml","Invalid '"+JSON.stringify(n.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):zn("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}const n=new hn(this.options,this.externalEntities),r=n.parseXml(e);return this.options.preserveOrder||void 0===r?r:Pn(r,this.options,n.matcher,n.readonlyMatcher)}addEntity(e,t){if(-1!==t.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return gt.getMetaDataSymbol()}}({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(e,t)=>""===t.trim()&&t.includes("\n")?"":void 0});Xn.addEntity("#xD","\r"),Xn.addEntity("#10","\n");var Qn=n(2840);const Yn=e=>{const t="#text";for(const n in e)e.hasOwnProperty(n)&&void 0!==e[n][t]?e[n]=e[n][t]:"object"==typeof e[n]&&null!==e[n]&&(e[n]=Yn(e[n]));return e};var Zn=n(2914),Jn=n(88791),er=n(89946);class tr extends Jn.B{settings;stringDeserializer;constructor(e){super(),this.settings=e,this.stringDeserializer=new Qn.k(e)}setSerdeContext(e){this.serdeContext=e,this.stringDeserializer.setSerdeContext(e)}read(e,t,n){const r=et.l.of(e),i=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&Object.values(i).find(e=>!!e.getMemberTraits().eventPayload)){const e={},n=Object.keys(i)[0];return i[n].isBlobSchema()?e[n]=t:e[n]=this.read(i[n],t),e}const s=(this.serdeContext?.utf8Encoder??Zn.P)(t),o=this.parseXml(s);return this.readSchema(e,n?o[n]:o)}readSchema(e,t){const n=et.l.of(e);if(n.isUnitSchema())return;const r=n.getMergedTraits();if(n.isListSchema()&&!Array.isArray(t))return this.readSchema(n,[t]);if(null==t)return t;if("object"==typeof t){const e=!!r.sparse,i=!!r.xmlFlattened;if(n.isListSchema()){const r=n.getValueSchema(),s=[],o=r.getMergedTraits().xmlName??"member",a=i?t:(t[0]??t)[o],c=Array.isArray(a)?a:[a];for(const t of c)(null!=t||e)&&s.push(this.readSchema(r,t));return s}const s={};if(n.isMapSchema()){const r=n.getKeySchema(),o=n.getValueSchema();let a;a=i?Array.isArray(t)?t:[t]:Array.isArray(t.entry)?t.entry:[t.entry];const c=r.getMergedTraits().xmlName??"key",l=o.getMergedTraits().xmlName??"value";for(const t of a){const n=t[c],r=t[l];(null!=r||e)&&(s[n]=this.readSchema(o,r))}return s}if(n.isStructSchema()){const e=n.isUnionSchema();let r;e&&(r=new er.F(t,s));for(const[i,o]of n.structIterator()){const n=o.getMergedTraits(),a=n.httpPayload?n.xmlName??o.getName():o.getMemberTraits().xmlName??i;e&&r.mark(a),null!=t[a]&&(s[i]=this.readSchema(o,t[a]))}return e&&r.writeUnknown(),s}if(n.isDocumentSchema())return t;throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${n.getName(!0)}`)}return n.isListSchema()?[]:n.isMapSchema()||n.isStructSchema()?{}:this.stringDeserializer.read(n,t)}parseXml(e){if(e.length){let n;try{t=e,n=Xn.parse(t,!0)}catch(t){throw t&&"object"==typeof t&&Object.defineProperty(t,"$responseBodyText",{value:e}),t}const r="#text",i=Object.keys(n)[0],s=n[i];return s[r]&&(s[i]=s[r],delete s[r]),Yn(s)}var t;return{}}}var nr=n(26144),rr=n(30259),ir=n(34708),sr=n(70764),or=n(10015),ar=n(39181);class cr extends Jn.B{settings;buffer;constructor(e){super(),this.settings=e}write(e,t,n=""){void 0===this.buffer&&(this.buffer="");const r=et.l.of(e);if(n&&!n.endsWith(".")&&(n+="."),r.isBlobSchema())("string"==typeof t||t instanceof Uint8Array)&&(this.writeKey(n),this.writeValue((this.serdeContext?.base64Encoder??ar.n)(t)));else if(r.isBooleanSchema()||r.isNumericSchema()||r.isStringSchema())null!=t?(this.writeKey(n),this.writeValue(String(t))):r.isIdempotencyToken()&&(this.writeKey(n),this.writeValue((0,ir.v4)()));else if(r.isBigIntegerSchema())null!=t&&(this.writeKey(n),this.writeValue(String(t)));else if(r.isBigDecimalSchema())null!=t&&(this.writeKey(n),this.writeValue(t instanceof sr.D?t.string:String(t)));else if(r.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(n),(0,nr.V)(r,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue((0,or.JV)(t));break;case 7:this.writeValue(String(t.getTime()/1e3))}}else if(r.isDocumentSchema())Array.isArray(t)?this.write(79,t,n):t instanceof Date?this.write(4,t,n):t instanceof Uint8Array?this.write(21,t,n):t&&"object"==typeof t?this.write(143,t,n):(this.writeKey(n),this.writeValue(String(t)));else if(r.isListSchema()){if(Array.isArray(t))if(0===t.length)this.settings.serializeEmptyLists&&(this.writeKey(n),this.writeValue(""));else{const e=r.getValueSchema(),i=this.settings.flattenLists||r.getMergedTraits().xmlFlattened;let s=1;for(const r of t){if(null==r)continue;const t=e.getMergedTraits(),o=this.getKey("member",t.xmlName,t.ec2QueryName),a=i?`${n}${s}`:`${n}${o}.${s}`;this.write(e,r,a),++s}}}else if(r.isMapSchema()){if(t&&"object"==typeof t){const e=r.getKeySchema(),i=r.getValueSchema(),s=r.getMergedTraits().xmlFlattened;let o=1;for(const[r,a]of Object.entries(t)){if(null==a)continue;const t=e.getMergedTraits(),c=this.getKey("key",t.xmlName,t.ec2QueryName),l=s?`${n}${o}.${c}`:`${n}entry.${o}.${c}`,d=i.getMergedTraits(),p=this.getKey("value",d.xmlName,d.ec2QueryName),h=s?`${n}${o}.${p}`:`${n}entry.${o}.${p}`;this.write(e,r,l),this.write(i,a,h),++o}}}else if(r.isStructSchema()){if(t&&"object"==typeof t){let e=!1;for(const[i,s]of r.structIterator()){if(null==t[i]&&!s.isIdempotencyToken())continue;const r=s.getMergedTraits(),o=`${n}${this.getKey(i,r.xmlName,r.ec2QueryName,"struct")}`;this.write(s,t[i],o),e=!0}if(!e&&r.isUnionSchema()){const{$unknown:e}=t;if(Array.isArray(e)){const[t,r]=e,i=`${n}${t}`;this.write(15,r,i)}}}}else if(!r.isUnitSchema())throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${r.getName(!0)}`)}flush(){if(void 0===this.buffer)throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");const e=this.buffer;return delete this.buffer,e}getKey(e,t,n,r){const{ec2:i,capitalizeKeys:s}=this.settings;if(i&&n)return n;const o=t??e;return s&&"struct"===r?o[0].toUpperCase()+o.slice(1):o}writeKey(e){e.endsWith(".")&&(e=e.slice(0,e.length-1)),this.buffer+=`&${(0,rr.$)(e)}=`}writeValue(e){this.buffer+=(0,rr.$)(e)}}class lr extends Ye.M{options;serializer;deserializer;mixin=new tt.U;constructor(e){super({defaultNamespace:e.defaultNamespace}),this.options=e;const t={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace,serializeEmptyLists:!0};this.serializer=new cr(t),this.deserializer=new tr(t)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(e){this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e)}getPayloadCodec(){throw new Error("AWSQuery protocol has no payload codec.")}async serializeRequest(e,t,n){const r=await super.serializeRequest(e,t,n);r.path.endsWith("/")||(r.path+="/"),Object.assign(r.headers,{"content-type":"application/x-www-form-urlencoded"}),"unit"!==(0,Je.L)(e.input)&&r.body||(r.body="");const i=e.name.split("#")[1]??e.name;return r.body=`Action=${i}&Version=${this.options.version}`+r.body,r.body.endsWith("&")&&(r.body=r.body.slice(-1)),r}async deserializeResponse(e,t,n){const r=this.deserializer,i=et.l.of(e.output),s={};if(n.statusCode>=300){const i=await(0,Ze.P)(n.body,t);i.byteLength>0&&Object.assign(s,await r.read(15,i)),await this.handleError(e,t,n,s,this.deserializeMetadata(n))}for(const e in n.headers){const t=n.headers[e];delete n.headers[e],n.headers[e.toLowerCase()]=t}const o=e.name.split("#")[1]??e.name,a=i.isStructSchema()&&this.useNestedResult()?o+"Result":void 0,c=await(0,Ze.P)(n.body,t);return c.byteLength>0&&Object.assign(s,await r.read(i,c,a)),{$metadata:this.deserializeMetadata(n),...s}}useNestedResult(){return!0}async handleError(e,t,n,r,i){const s=this.loadQueryErrorCode(n,r)??"Unknown",o=this.loadQueryError(r),a=this.loadQueryErrorMessage(r);o.message=a,o.Error={Type:o.Type,Code:o.Code,Message:a};const{errorSchema:c,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,n,o,i,this.mixin.findQueryCompatibleError),p=et.l.of(c),h=new(d.O.for(c[1]).getErrorCtor(c)??Error)(a),u={Type:o.Error.Type,Code:o.Error.Code,Error:o.Error};for(const[e,t]of p.structIterator()){const n=t.getMergedTraits().xmlName??e,i=o[n]??r[n];u[e]=this.deserializer.readSchema(t,i)}throw this.mixin.decorateServiceException(Object.assign(h,l,{$fault:p.getMergedTraits().error,message:a},u),r)}loadQueryErrorCode(e,t){const n=(t.Errors?.[0]?.Error??t.Errors?.Error??t.Error)?.Code;return void 0!==n?n:404==e.statusCode?"NotFound":void 0}loadQueryError(e){return e.Errors?.[0]?.Error??e.Errors?.Error??e.Error}loadQueryErrorMessage(e){const t=this.loadQueryError(e);return t?.message??t?.Message??e.message??e.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}var dr=n(3761),pr=n(67933),hr=n(12544),ur=n(40935),gr=n(2456),mr=n(48105),fr=n(1034),xr=n(7856);const yr="required",br="type",Er="fn",wr="argv",Sr="ref",vr=!1,Nr=!0,Tr="booleanEquals",Ar="stringEquals",Cr="sigv4",Ir="us-east-1",$r="endpoint",_r="https://sts.{Region}.{PartitionResult#dnsSuffix}",Pr="tree",kr="error",Dr="getAttr",Rr={[yr]:!1,[br]:"string"},Or={[yr]:!0,default:!1,[br]:"boolean"},jr={[Sr]:"Endpoint"},Mr={[Er]:"isSet",[wr]:[{[Sr]:"Region"}]},Lr={[Sr]:"Region"},Vr={[Er]:"aws.partition",[wr]:[Lr],assign:"PartitionResult"},Ur={[Sr]:"UseFIPS"},qr={[Sr]:"UseDualStack"},Fr={url:"https://sts.amazonaws.com",properties:{authSchemes:[{name:Cr,signingName:"sts",signingRegion:Ir}]},headers:{}},Wr={},zr={conditions:[{[Er]:Ar,[wr]:[Lr,"aws-global"]}],[$r]:Fr,[br]:$r},Br={[Er]:Tr,[wr]:[Ur,!0]},Kr={[Er]:Tr,[wr]:[qr,!0]},Gr={[Er]:Dr,[wr]:[{[Sr]:"PartitionResult"},"supportsFIPS"]},Hr={[Sr]:"PartitionResult"},Xr={[Er]:Tr,[wr]:[!0,{[Er]:Dr,[wr]:[Hr,"supportsDualStack"]}]},Qr=[{[Er]:"isSet",[wr]:[jr]}],Yr=[Br],Zr=[Kr],Jr={version:"1.0",parameters:{Region:Rr,UseDualStack:Or,UseFIPS:Or,Endpoint:Rr,UseGlobalEndpoint:Or},rules:[{conditions:[{[Er]:Tr,[wr]:[{[Sr]:"UseGlobalEndpoint"},Nr]},{[Er]:"not",[wr]:Qr},Mr,Vr,{[Er]:Tr,[wr]:[Ur,vr]},{[Er]:Tr,[wr]:[qr,vr]}],rules:[{conditions:[{[Er]:Ar,[wr]:[Lr,"ap-northeast-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"ap-south-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"ap-southeast-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"ap-southeast-2"]}],endpoint:Fr,[br]:$r},zr,{conditions:[{[Er]:Ar,[wr]:[Lr,"ca-central-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"eu-central-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"eu-north-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"eu-west-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"eu-west-2"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"eu-west-3"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"sa-east-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,Ir]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"us-east-2"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"us-west-1"]}],endpoint:Fr,[br]:$r},{conditions:[{[Er]:Ar,[wr]:[Lr,"us-west-2"]}],endpoint:Fr,[br]:$r},{endpoint:{url:_r,properties:{authSchemes:[{name:Cr,signingName:"sts",signingRegion:"{Region}"}]},headers:Wr},[br]:$r}],[br]:Pr},{conditions:Qr,rules:[{conditions:Yr,error:"Invalid Configuration: FIPS and custom endpoint are not supported",[br]:kr},{conditions:Zr,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",[br]:kr},{endpoint:{url:jr,properties:Wr,headers:Wr},[br]:$r}],[br]:Pr},{conditions:[Mr],rules:[{conditions:[Vr],rules:[{conditions:[Br,Kr],rules:[{conditions:[{[Er]:Tr,[wr]:[Nr,Gr]},Xr],rules:[{endpoint:{url:"https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Wr,headers:Wr},[br]:$r}],[br]:Pr},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",[br]:kr}],[br]:Pr},{conditions:Yr,rules:[{conditions:[{[Er]:Tr,[wr]:[Gr,Nr]}],rules:[{conditions:[{[Er]:Ar,[wr]:[{[Er]:Dr,[wr]:[Hr,"name"]},"aws-us-gov"]}],endpoint:{url:"https://sts.{Region}.amazonaws.com",properties:Wr,headers:Wr},[br]:$r},{endpoint:{url:"https://sts-fips.{Region}.{PartitionResult#dnsSuffix}",properties:Wr,headers:Wr},[br]:$r}],[br]:Pr},{error:"FIPS is enabled but this partition does not support FIPS",[br]:kr}],[br]:Pr},{conditions:Zr,rules:[{conditions:[Xr],rules:[{endpoint:{url:"https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Wr,headers:Wr},[br]:$r}],[br]:Pr},{error:"DualStack is enabled but this partition does not support DualStack",[br]:kr}],[br]:Pr},zr,{endpoint:{url:_r,properties:Wr,headers:Wr},[br]:$r}],[br]:Pr}],[br]:Pr},{error:"Invalid Configuration: Missing Region",[br]:kr}]},ei=new mr.k({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS","UseGlobalEndpoint"]}),ti=(e,t={})=>ei.get(e,()=>(0,fr.s)(Jr,{endpointParams:e,logger:t.logger}));xr.m.aws=gr.UF;var ni=n(93673),ri=n(78646),ii=n(18081);class si extends Ie.K{config;constructor(...[e]){const t=(e=>{(0,Ke.I)(process.version);const t=(0,Xe.I)(e),n=()=>t().then(Ge.l),r=(e=>({apiVersion:"2011-06-15",base64Decoder:e?.base64Decoder??hr.E,base64Encoder:e?.base64Encoder??ar.n,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??ti,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??De,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Me.f2},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Fe.m}],logger:e?.logger??new dr.N,protocol:e?.protocol??lr,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.sts",errorTypeRegistries:K,xmlNamespace:"https://sts.amazonaws.com/doc/2011-06-15/",version:"2011-06-15",serviceTarget:"AWSSecurityTokenServiceV20110615"},serviceId:e?.serviceId??"STS",urlParser:e?.urlParser??pr.D,utf8Decoder:e?.utf8Decoder??ur.a,utf8Encoder:e?.utf8Encoder??Zn.P}))(e);(0,Oe.I)(process.version);const o={profile:e?.profile,logger:r.logger};return{...r,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??(0,s.Z)(je.$,o),bodyLengthChecker:e?.bodyLengthChecker??He.n,defaultUserAgentProvider:e?.defaultUserAgentProvider??(0,Le.pf)({serviceId:r.serviceId,clientVersion:Re.rE}),httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:t=>t.getIdentityProvider("aws.auth#sigv4")||(async t=>await e.credentialDefaultProvider(t?.__config||{})()),signer:new Me.f2},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Fe.m}],maxAttempts:e?.maxAttempts??(0,s.Z)(Ae.qs,e),region:e?.region??(0,s.Z)(i.GG,{...i.zH,...o}),requestHandler:ze.$.create(e?.requestHandler??n),retryMode:e?.retryMode??(0,s.Z)({...Ae.kN,default:async()=>(await n()).retryMode||Qe.L0},e),sha256:e?.sha256??We.V.bind(null,"sha256"),streamCollector:e?.streamCollector??Be.k,useDualstackEndpoint:e?.useDualstackEndpoint??(0,s.Z)(Ue.e$,o),useFipsEndpoint:e?.useFipsEndpoint??(0,s.Z)(qe.Ko,o),userAgentAppId:e?.userAgentAppId??(0,s.Z)(Ve.hV,o)}})(e||{});super(t),this.initConfig=t;const n=(r=t,Object.assign(r,{useDualstackEndpoint:r.useDualstackEndpoint??!1,useFipsEndpoint:r.useFipsEndpoint??!1,useGlobalEndpoint:r.useGlobalEndpoint??!1,defaultSigningName:"sts"}));var r;const o=(0,xe.D)(n),a=(0,Ae.$z)(o),c=(0,be.T)(a),l=(0,ge.OV)(c),d=((e,t)=>{const n=Object.assign((0,ni.R)(e),(0,ii.xA)(e),(0,ri.e)(e),(e=>{const t=e.httpAuthSchemes;let n=e.httpAuthSchemeProvider,r=e.credentials;return{setHttpAuthScheme(e){const n=t.findIndex(t=>t.schemeId===e.schemeId);-1===n?t.push(e):t.splice(n,1,e)},httpAuthSchemes:()=>t,setHttpAuthSchemeProvider(e){n=e},httpAuthSchemeProvider:()=>n,setCredentials(e){r=e},credentials:()=>r}})(e));return t.forEach(e=>e.configure(n)),Object.assign(e,(0,ni.$)(n),(0,ii.uv)(n),(0,ri.j)(n),{httpAuthSchemes:(r=n).httpAuthSchemes(),httpAuthSchemeProvider:r.httpAuthSchemeProvider(),credentials:r.credentials()});var r})((e=>{const t=(n=e,Object.assign(n,{stsClientCtor:si}));var n;const r=(0,$e.h)(t);return Object.assign(r,{authSchemePreference:(0,Pe.t)(e.authSchemePreference??[])})})((0,Te.C)(l)),e?.extensions||[]);this.config=d,this.middlewareStack.use((0,ve.wq)(this.config)),this.middlewareStack.use((0,ye.sM)(this.config)),this.middlewareStack.use((0,Ce.ey)(this.config)),this.middlewareStack.use((0,Ne.vK)(this.config)),this.middlewareStack.use((0,ge.TC)(this.config)),this.middlewareStack.use((0,me.Y7)(this.config)),this.middlewareStack.use((0,fe.n)(this.config)),this.middlewareStack.use((0,Ee.w)(this.config,{httpAuthSchemeParametersProvider:ke,identityProviderConfigProvider:async e=>new we.h({"aws.auth#sigv4":e.credentials})})),this.middlewareStack.use((0,Se.l)(this.config))}destroy(){super.destroy()}}const oi=(e,t)=>t?class extends e{constructor(e){super(e);for(const e of t)this.middlewareStack.use(e)}}:e,ai=(e={},t)=>((e,t)=>{let n,i;return async(s,o)=>{if(i=s,!n){const{logger:r=e?.parentClientConfig?.logger,profile:s=e?.parentClientConfig?.profile,region:o,requestHandler:a=e?.parentClientConfig?.requestHandler,credentialProviderLogger:c,userAgentAppId:l=e?.parentClientConfig?.userAgentAppId}=e,d=await he(o,e?.parentClientConfig?.region,c,{logger:r,profile:s}),p=!ue(a);n=new t({...e,userAgentAppId:l,profile:s,credentialDefaultProvider:()=>async()=>i,region:d,requestHandler:p?a:void 0,logger:r})}const{Credentials:a,AssumedRoleUser:c}=await n.send(new le(o));if(!a||!a.AccessKeyId||!a.SecretAccessKey)throw new Error(`Invalid response from STS.assumeRole call with role ${o.RoleArn}`);const l=pe(c),d={accessKeyId:a.AccessKeyId,secretAccessKey:a.SecretAccessKey,sessionToken:a.SessionToken,expiration:a.Expiration,...a.CredentialScope&&{credentialScope:a.CredentialScope},...l&&{accountId:l}};return(0,r.g)(d,"CREDENTIALS_STS_ASSUME_ROLE","i"),d}})(e,oi(si,t)),ci=(e={},t)=>((e,t)=>{let n;return async i=>{if(!n){const{logger:r=e?.parentClientConfig?.logger,profile:i=e?.parentClientConfig?.profile,region:s,requestHandler:o=e?.parentClientConfig?.requestHandler,credentialProviderLogger:a,userAgentAppId:c=e?.parentClientConfig?.userAgentAppId}=e,l=await he(s,e?.parentClientConfig?.region,a,{logger:r,profile:i}),d=!ue(o);n=new t({...e,userAgentAppId:c,profile:i,region:l,requestHandler:d?o:void 0,logger:r})}const{Credentials:s,AssumedRoleUser:o}=await n.send(new de(i));if(!s||!s.AccessKeyId||!s.SecretAccessKey)throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${i.RoleArn}`);const a=pe(o),c={accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken,expiration:s.Expiration,...s.CredentialScope&&{credentialScope:s.CredentialScope},...a&&{accountId:a}};return a&&(0,r.g)(c,"RESOLVED_ACCOUNT_ID","T"),(0,r.g)(c,"CREDENTIALS_STS_ASSUME_ROLE_WEB_ID","k"),c}})(e,oi(si,t))}};
|
package/dist/354.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=354,exports.ids=[354],exports.modules={28226:(e,n,o)=>{o.d(n,{C:()=>s});var r=o(76982),t=o(16928),i=o(14581);const s=e=>{const n=(0,r.createHash)("sha1").update(e).digest("hex");return(0,t.join)((0,i.R)(),".aws","sso","cache",`${n}.json`)}},70737:(e,n,o)=>{o.d(n,{Z:()=>i});var r=o(78405),t=o(35789);const i={getFileRecord:()=>t.Jj,interceptFile(e,n){t.Jj[e]=Promise.resolve(n)},getTokenRecord:()=>r.a,interceptToken(e,n){r.a[e]=n}}},78405:(e,n,o)=>{o.d(n,{a:()=>i,v:()=>s});var r=o(91943),t=o(28226);const i={},s=async e=>{if(i[e])return i[e];const n=(0,t.C)(e),o=await(0,r.readFile)(n,"utf8");return JSON.parse(o)}},83354:(e,n,o)=>{o.d(n,{fromTokenFile:()=>d});var r=o(53347),t=o(43281),i=o(70737),s=o(79896);const a="AWS_WEB_IDENTITY_TOKEN_FILE",d=(e={})=>async n=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");const d=e?.webIdentityTokenFile??process.env[a],c=e?.roleArn??process.env.AWS_ROLE_ARN,l=e?.roleSessionName??process.env.AWS_ROLE_SESSION_NAME;if(!d||!c)throw new t.C("Web identity configuration not specified",{logger:e.logger});const g=await(e=>async n=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");const{roleArn:r,roleSessionName:t,webIdentityToken:i,providerId:s,policyArns:a,policy:d,durationSeconds:c}=e;let{roleAssumerWithWebIdentity:l}=e;if(!l){const{getDefaultRoleAssumerWithWebIdentity:r}=await o.e(
|
|
1
|
+
"use strict";exports.id=354,exports.ids=[354],exports.modules={28226:(e,n,o)=>{o.d(n,{C:()=>s});var r=o(76982),t=o(16928),i=o(14581);const s=e=>{const n=(0,r.createHash)("sha1").update(e).digest("hex");return(0,t.join)((0,i.R)(),".aws","sso","cache",`${n}.json`)}},70737:(e,n,o)=>{o.d(n,{Z:()=>i});var r=o(78405),t=o(35789);const i={getFileRecord:()=>t.Jj,interceptFile(e,n){t.Jj[e]=Promise.resolve(n)},getTokenRecord:()=>r.a,interceptToken(e,n){r.a[e]=n}}},78405:(e,n,o)=>{o.d(n,{a:()=>i,v:()=>s});var r=o(91943),t=o(28226);const i={},s=async e=>{if(i[e])return i[e];const n=(0,t.C)(e),o=await(0,r.readFile)(n,"utf8");return JSON.parse(o)}},83354:(e,n,o)=>{o.d(n,{fromTokenFile:()=>d});var r=o(53347),t=o(43281),i=o(70737),s=o(79896);const a="AWS_WEB_IDENTITY_TOKEN_FILE",d=(e={})=>async n=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");const d=e?.webIdentityTokenFile??process.env[a],c=e?.roleArn??process.env.AWS_ROLE_ARN,l=e?.roleSessionName??process.env.AWS_ROLE_SESSION_NAME;if(!d||!c)throw new t.C("Web identity configuration not specified",{logger:e.logger});const g=await(e=>async n=>{e.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");const{roleArn:r,roleSessionName:t,webIdentityToken:i,providerId:s,policyArns:a,policy:d,durationSeconds:c}=e;let{roleAssumerWithWebIdentity:l}=e;if(!l){const{getDefaultRoleAssumerWithWebIdentity:r}=await o.e(317).then(o.bind(o,79317));l=r({...e.clientConfig,credentialProviderLogger:e.logger,parentClientConfig:{...n?.callerClientConfig,...e.parentClientConfig}},e.clientPlugins)}return l({RoleArn:r,RoleSessionName:t??`aws-sdk-js-session-${Date.now()}`,WebIdentityToken:i,ProviderId:s,PolicyArns:a,Policy:d,DurationSeconds:c})})({...e,webIdentityToken:i.Z?.getTokenRecord?.()[d]??(0,s.readFileSync)(d,{encoding:"ascii"}),roleArn:c,roleSessionName:l})(n);return d===process.env[a]&&(0,r.g)(g,"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN","h"),g}}};
|
package/dist/839.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=839,exports.ids=[839],exports.modules={13839:(e,t,r)=>{r.r(t),r.d(t,{ANON_NONCE_TTL_MS:()=>D,AUTH_NONCE_TTL_MS:()=>b,AuditLogProvider:()=>cr,BitstringManager:()=>W,CascadingRevocationManager:()=>z,ClockProvider:()=>Bt,CryptoProvider:()=>Vt,DEFAULT_CLOCK_SKEW_SECONDS:()=>Kt,DEFAULT_SESSION_TTL_MINUTES:()=>v,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>w,DELEGATION_CREDENTIAL_CONTEXT:()=>h,DefaultPolicyEngine:()=>Ir,DelegationCredentialIssuer:()=>M,DelegationCredentialVerifier:()=>L,DelegationGraphManager:()=>j,DidWebResolver:()=>Et,ED25519_KEY_SIZE:()=>at,ED25519_PKCS8_DER_HEADER:()=>st,ED25519_SPKI_DER_HEADER_LENGTH:()=>ot,FetchProvider:()=>Jt,HOLDER_BINDING_ERROR:()=>yt,IdentityProvider:()=>Ft,KYA_OS_ERROR_CODES:()=>n,MAX_CLOCK_SKEW_SECONDS:()=>Ht,MIN_CLOCK_SKEW_SECONDS:()=>Lt,MemoryAuditLogProvider:()=>dr,MemoryDelegationGraphStorage:()=>St,MemoryIdentityProvider:()=>Xt,MemoryNonceCacheProvider:()=>Gt,MemoryResumeTokenStore:()=>Pt,MemoryStatusListStorage:()=>wt,MemoryStorageProvider:()=>Yt,NONCE_LENGTH_BYTES:()=>S,NodeCryptoProvider:()=>nr,NonceCacheProvider:()=>qt,NoopAuditLogProvider:()=>ur,NoopFetchProvider:()=>or,OUTBOUND_HEADER_NAMES:()=>rt,PROOF_VERIFICATION_ERROR_CODES:()=>Ot,ProofGenerator:()=>dt,ProofVerificationError:()=>Mt,ProofVerifier:()=>jt,RiskClassifier:()=>Sr,RuntimeFetchProvider:()=>sr,SENSITIVE_VERBS:()=>vr,SessionManager:()=>Qt,StatusList2021Manager:()=>B,StorageProvider:()=>zt,SystemClockProvider:()=>ir,assertHolderBinding:()=>vt,base58Decode:()=>Re,base58Encode:()=>Ne,base64ToBytes:()=>u,base64urlDecodeToBytes:()=>o,base64urlEncodeFromBytes:()=>c,buildAuditRecord:()=>ar,buildChainString:()=>Te,buildDelegationProofJWT:()=>Ce,buildDidWebDocument:()=>Tt,buildOutboundDelegationHeaders:()=>nt,buildPolicyRequest:()=>Er,bytesToBase64:()=>d,canonicalizeJSON:()=>P,compareDids:()=>Le,completeVCJWT:()=>R,createCascadingRevocationManager:()=>q,createDefaultConsoleLogger:()=>qe,createDelegationGraph:()=>U,createDelegationIssuer:()=>x,createDelegationVerifier:()=>H,createDidKeyResolver:()=>et,createDidWebResolver:()=>_t,createHandshakeRequest:()=>Zt,createKyaOsError:()=>i,createKyaOsMiddleware:()=>Cr,createNeedsApprovalError:()=>E,createNeedsAuthorizationError:()=>I,createProofResponse:()=>ut,createProofVerificationError:()=>xt,createStatusListManager:()=>J,createUnsignedVCJWT:()=>N,didKeyFragment:()=>Je,didWebToUrl:()=>kt,extractAgentId:()=>je,extractAgentSlug:()=>Ue,extractCanonicalData:()=>lt,extractDelegationFromVC:()=>p,extractProofFromMeta:()=>Wt,extractPublicKeyFromDidKey:()=>Qe,generateDidKeyFromBase64:()=>Be,generateDidKeyFromBytes:()=>Ve,generateIdentity:()=>Pr,generateRequestProof:()=>gt,getDidMethod:()=>xe,getServerDid:()=>He,hasSensitiveScopes:()=>Rt,isDelegationCredentialExpired:()=>g,isDelegationCredentialNotYetValid:()=>y,isDidWeb:()=>Dt,isEd25519DidKey:()=>Xe,isHolderBindingApplicable:()=>mt,isIndexSet:()=>V,isKyaOsControlArg:()=>ft,isNeedsApprovalError:()=>_,isNeedsAuthorizationError:()=>k,isValidBase58:()=>Oe,isValidDid:()=>Me,logger:()=>Fe,matchScope:()=>pr,normalizeDid:()=>Ke,parseDidWeb:()=>It,parseVCJWT:()=>O,publicKeyToJwk:()=>Ze,resolveDidKeySync:()=>tt,scopeSatisfies:()=>gr,toHolderBindingRequest:()=>pt,validateDelegationCredential:()=>m,validateDetachedProof:()=>C,validateHandshakeFormat:()=>er,validateMetaStructure:()=>Ut,verifyApprovalQuorum:()=>kr,verifyDelegationAudience:()=>F,verifyOrHints:()=>$t,withKyaOs:()=>$r,wrapDelegationAsVC:()=>f});const n={invalid_proof:"invalid_proof",invalid_jws:"invalid_jws",nonce_replay:"nonce_replay",timestamp_skew:"timestamp_skew",did_not_found:"did_not_found",invalid_public_key:"invalid_public_key",handshake_failed:"handshake_failed",session_expired:"session_expired",invalid_request:"invalid_request",needs_authorization:"needs_authorization",insufficient_scope:"insufficient_scope",policy_denied:"policy_denied",delegation_expired:"delegation_expired",delegation_not_yet_valid:"delegation_not_yet_valid",delegation_revoked:"delegation_revoked",delegation_invalid:"delegation_invalid",holder_binding_failed:"holder_binding_failed",budget_exceeded:"budget_exceeded",rate_limit_exceeded:"rate_limit_exceeded",invalid_token:"invalid_token",token_expired:"token_expired",mirror_pending:"mirror_pending",claim_failed:"claim_failed",configuration_error:"configuration_error",runtime_error:"runtime_error"};function i(e,t,r){return r?{code:e,message:t,details:r}:{code:e,message:t}}function s(e){const t=l(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof Buffer){if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");return Buffer.from(t,"base64").toString("utf-8")}if("undefined"!=typeof atob){const e=atob(t);if("undefined"!=typeof TextDecoder){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return(new TextDecoder).decode(t)}return e}throw new Error("Neither Buffer nor atob is available")}function o(e){const t=l(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return new Uint8Array(Buffer.from(t,"base64"))}function a(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");if("undefined"!=typeof btoa){const t=(new TextEncoder).encode(e),r=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}throw new Error("Neither Buffer nor btoa is available")}function c(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function d(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")}function u(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;if(t+="=".repeat(r),"undefined"!=typeof atob){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return new Uint8Array(Buffer.from(t,"base64"))}function l(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}const h="https://schema.kya-os.org/v1/protocol/delegation/context/v1.0.0";function f(e,t){const r=(new Date).toISOString(),n=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let i=t?.issuanceDate||r;!t?.issuanceDate&&e.createdAt&&(i=new Date(e.createdAt).toISOString());const s=t?.scopes||e.constraints.scopes;return{"@context":["https://www.w3.org/2018/credentials/v1",h],id:t?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:i,...void 0!==n&&{expirationDate:n},credentialSubject:{id:e.subjectDid,delegation:{id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,...t?.userDid&&{userDid:t.userDid},...t?.userIdentifier&&{userIdentifier:t.userIdentifier},...t?.sessionId&&{sessionId:t.sessionId},...s&&s.length>0&&{scopes:s},...void 0!==e.controller&&{controller:e.controller},...void 0!==e.parentId&&{parentId:e.parentId},constraints:e.constraints,status:e.status,...void 0!==e.createdAt&&{createdAt:e.createdAt},...void 0!==e.metadata&&{metadata:e.metadata}}},...void 0!==t?.credentialStatus&&{credentialStatus:t.credentialStatus}}}function p(e){const t=e?.credentialSubject?.delegation;if(!t||"object"!=typeof t)throw new Error("extractDelegationFromVC: credential is missing credentialSubject.delegation");let r="";if(e.proof){const t=e.proof;r=t.proofValue||t.jws||t.signatureValue||""}return{id:t.id,issuerDid:t.issuerDid,subjectDid:t.subjectDid,controller:t.controller,vcId:e.id||`vc:${t.id}`,parentId:t.parentId,constraints:t.constraints,signature:r,status:t.status,createdAt:t.createdAt,revokedAt:void 0,revokedReason:void 0,metadata:t.metadata}}function g(e){if(e.expirationDate&&new Date(e.expirationDate)<new Date)return!0;const t=e.credentialSubject.delegation;return!!(t.constraints.notAfter&&Math.floor(Date.now()/1e3)>t.constraints.notAfter)}function y(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)}function m(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if(!Array.isArray(t["@context"])||0===t["@context"].length)return{success:!1,error:{message:"Missing or invalid @context"}};if("https://www.w3.org/2018/credentials/v1"!==t["@context"][0])return{success:!1,error:{message:"First @context must be W3C VC context"}};if(!Array.isArray(t.type))return{success:!1,error:{message:"Missing type array"}};if(!t.type.includes("VerifiableCredential")||!t.type.includes("DelegationCredential"))return{success:!1,error:{message:"type must include VerifiableCredential and DelegationCredential"}};if(!t.issuer||"string"!=typeof t.issuer&&"object"!=typeof t.issuer)return{success:!1,error:{message:"Missing or invalid issuer"}};if(!t.issuanceDate||"string"!=typeof t.issuanceDate)return{success:!1,error:{message:"Missing issuanceDate"}};const r=t.credentialSubject;if(!r||"object"!=typeof r)return{success:!1,error:{message:"Missing credentialSubject"}};if(!r.id||"string"!=typeof r.id)return{success:!1,error:{message:"credentialSubject.id missing"}};const n=r.delegation;return n&&"object"==typeof n?n.id&&n.issuerDid&&n.subjectDid&&n.constraints?{success:!0,data:e}:{success:!1,error:{message:"delegation fields missing"}}:{success:!1,error:{message:"credentialSubject.delegation missing"}}}const v=30,w=120,S=16,b=12e4,D=6e4;function I(e){return{error:"needs_authorization",...e}}function k(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function E(e){return{error:"needs_approval",...e}}function _(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const A=/^sha256:[a-f0-9]{64}$/;function C(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if("string"!=typeof t.jws||t.jws.length<1)return{success:!1,error:{message:"jws must be a non-empty string"}};const r=t.meta;if(!r||"object"!=typeof r)return{success:!1,error:{message:"meta must be an object"}};const n=r,i=["did","kid","nonce","audience","sessionId"];for(const e of i)if("string"!=typeof n[e]||n[e].length<1)return{success:!1,error:{message:`meta.${e} must be a non-empty string`}};if("number"!=typeof n.ts||!Number.isInteger(n.ts)||n.ts<=0)return{success:!1,error:{message:"meta.ts must be a positive integer"}};if("string"!=typeof n.requestHash||!A.test(n.requestHash))return{success:!1,error:{message:"meta.requestHash must match sha256:<64 hex chars>"}};if(void 0!==n.responseHash&&("string"!=typeof n.responseHash||!A.test(n.responseHash)))return{success:!1,error:{message:"meta.responseHash must match sha256:<64 hex chars> when present"}};const s=["scopeId","delegationRef","clientDid","reason"];for(const e of s)if(void 0!==n[e]&&"string"!=typeof n[e])return{success:!1,error:{message:`meta.${e} must be a string if present`}};return void 0===n.outcome||["allowed","denied","step_up_required","needs_authorization"].includes(n.outcome)?{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var T=r(77753);function P(e){return $(e),(0,T.d)(e)}function $(e,t="$"){if(null!==e&&"boolean"!=typeof e&&"string"!=typeof e)if("number"!=typeof e){if(void 0===e)throw new TypeError(`Cannot canonicalize undefined at ${t}`);if("function"==typeof e)throw new TypeError(`Cannot canonicalize function at ${t}`);if("symbol"==typeof e)throw new TypeError(`Cannot canonicalize symbol at ${t}`);if("bigint"==typeof e)throw new TypeError(`Cannot canonicalize bigint at ${t}`);if(Array.isArray(e))for(let r=0;r<e.length;r++)$(e[r],`${t}[${r}]`);else if("object"!=typeof e);else for(const[r,n]of Object.entries(e))$(n,`${t}.${r}`)}else if(!Number.isFinite(e))throw new TypeError(`Cannot canonicalize non-finite number at ${t}: ${e}`)}function N(e,t={}){const r={alg:"EdDSA",typ:"JWT"};t.keyId&&(r.kid=t.keyId);const n="string"==typeof e.issuer?e.issuer:e.issuer?.id,i=e.credentialSubject?.id;let s,o;e.expirationDate&&"string"==typeof e.expirationDate&&(s=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(o=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const c={...e};delete c.proof;const d={iss:n,vc:c};i&&(d.sub=i),s&&(d.exp=s),o&&(d.iat=o),e.id&&"string"==typeof e.id&&(d.jti=e.id);const u=a(JSON.stringify(r)),l=a(JSON.stringify(d));return{header:r,payload:d,encodedHeader:u,encodedPayload:l,signingInput:`${u}.${l}`}}function R(e,t){return`${e}.${t}`}function O(e){const t=e.split(".");if(3!==t.length)return null;try{const e=s(t[0]),r=s(t[1]);return{header:JSON.parse(e),payload:JSON.parse(r),signature:t[2],signingInput:`${t[0]}.${t[1]}`}}catch{return null}}class M{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=f(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=r["@context"];r={...r,"@context":[...e,...t.additionalContexts]}}const n=this.canonicalizeVC(r),i=await this.signingFunction(n,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:i}}async createAndIssueDelegation(e,t={}){const r=Date.now(),n={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:r,metadata:e.metadata};return this.issueDelegationCredential(n,t)}canonicalizeVC(e){return P(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function x(e,t){return new M(e,t)}const K=["id","delegation"];class L{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheInsertionOrder=[];cacheTtl;maxCacheSize;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4,this.maxCacheSize=e?.maxCacheSize??1e3}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const n=Date.now(),i=this.validateBasicProperties(e),s=Date.now()-n;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:s,totalMs:Date.now()-r},checks:{basicValid:!1}};const o=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),a=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,d]=await Promise.all([o,a]),u=c.durationMs||0,l=d.durationMs||0,h=i.valid&&c.valid&&d.valid,f={valid:h,reason:h?void 0:c.reason||d.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:s,signatureCheckMs:u,statusCheckMs:l,totalMs:Date.now()-r},checks:{basicValid:i.valid,signatureValid:c.valid,statusValid:d.valid}};return f.valid&&e.id&&this.setInCache(e.id,f),f}validateBasicProperties(e){const t=m(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error?.message}`};if(g(e))return{valid:!1,reason:"Delegation credential expired"};if(y(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;if("revoked"===r.status)return{valid:!1,reason:"Delegation status is revoked"};if("expired"===r.status)return{valid:!1,reason:"Delegation status is expired"};if(!r.issuerDid||!r.subjectDid)return{valid:!1,reason:"Missing issuer or subject DID"};if(!e.proof)return{valid:!1,reason:"Missing proof"};const n=this.validateSubjectShape(e);return n.valid?{valid:!0}:n}validateSubjectShape(e){const t=Object.keys(e.credentialSubject).filter(e=>!K.includes(e));return 0===t.length?{valid:!0}:{valid:!1,reason:`credentialSubject contains non-delegation field(s): ${t.join(", ")}. A DelegationCredential subject MUST carry only 'id' and 'delegation' (KYA-OS §11.6).`}}async verifySignature(e,t){const r=Date.now();try{const n="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!1,reason:"No DID resolver or signature verifier configured — signature cannot be verified",durationMs:Date.now()-r};const i=await t.resolve(n);if(!i)return{valid:!1,reason:`Could not resolve issuer DID: ${n}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const s=e.proof.verificationMethod;if(!s)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const o=this.findVerificationMethod(i,s);if(!o)return{valid:!1,reason:`Verification method ${s} not found`,durationMs:Date.now()-r};const a=o.publicKeyJwk;if(!a)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const c=await this.signatureVerifier(e,a);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}async checkCredentialStatus(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!1,reason:"Credential has credentialStatus but no status list resolver is configured — cannot verify revocation status",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){for(;this.cache.size>=this.maxCacheSize&&this.cacheInsertionOrder.length>0;){const e=this.cacheInsertionOrder.shift();e&&this.cache.delete(e)}this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl}),this.cacheInsertionOrder.push(e)}clearCache(){this.cache.clear(),this.cacheInsertionOrder=[]}clearCacheEntry(e){this.cache.delete(e);const t=this.cacheInsertionOrder.indexOf(e);-1!==t&&this.cacheInsertionOrder.splice(t,1)}}function H(e){return new L(e)}class j{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const r=await this.storage.getNode(e);if(!r)throw new Error(`Parent delegation not found: ${e}`);r.children.includes(t)||(r.children.push(t),await this.storage.setNode(r))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const r=t[e-1],n=t[e];if(n.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${n.id} issued by ${n.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(n.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${n.id} parentId=${n.parentId} but actual parent is ${r.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const r=await this.storage.getNode(t.parentId);r&&(r.children=r.children.filter(t=>t!==e),await this.storage.setNode(r))}await this.storage.deleteNode(e)}}}function U(e){return new j(e)}class W{compressor;decompressor;bits;size;constructor(e,t,r){this.compressor=t,this.decompressor=r,this.size=e;const n=Math.ceil(e/8);this.bits=new Uint8Array(n)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),n=e%8;t?this.bits[r]|=1<<n:this.bits[r]&=~(1<<n)}getBit(e){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),r=e%8;return!!(this.bits[t]&1<<r)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return this.base64urlEncode(e)}static async decode(e,t,r){const n=W.base64urlDecode(e),i=await r.decompress(n),s=8*i.length,o=new W(s,t,r);return o.bits=i,o}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return W.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;t+="=".repeat(r);const n=atob(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);return i}static fromSetBits(e,t,r,n){const i=new W(e,r,n);for(const e of t)i.setBit(e,!0);return i}}async function V(e,t,r){const n=W.base64urlDecode(e),i=await r.decompress(n),s=Math.floor(t/8),o=t%8;return!(s>=i.length||!(i[s]&1<<o))}class B{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,r,n,i,s){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=n,this.decompressor=i,this.statusListBaseUrl=s?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=s?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,r=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${r}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:r.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:r}=e,n=(this.updateLocks.get(r)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(r,n.catch(()=>{})),await n}async doUpdateStatus(e,t){const{statusListCredential:r,statusListIndex:n}=e,i=await this.storage.getStatusList(r);if(!i)throw new Error(`Status list not found: ${r}`);const s=await W.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),o=parseInt(n,10);s.setBit(o,t);const a=await s.encode(),c={...i,credentialSubject:{...i.credentialSubject,encodedList:a}},d={...c};delete d.proof;const u=P(d),l=await this.signingFunction(u,this.identity.getDid(),this.identity.getKeyId()),h={...c,proof:l};await this.storage.setStatusList(r,h)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,n=await this.storage.getStatusList(t);if(!n)throw new Error(`Status list not found: ${t} — cannot determine revocation status`);const i=await W.decode(n.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(r,10);return i.getBit(s)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await W.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new W(this.defaultListSize,this.compressor,this.decompressor),n=await r.encode(),i={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:n}},s=P(i),o=await this.signingFunction(s,this.identity.getDid(),this.identity.getKeyId()),a={...i,proof:o};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function J(e,t,r,n,i,s){return new B(e,t,r,n,i,s)}class z{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,n=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const s=await this.graph.getDepth(e);if(s>r)throw new Error(`Delegation depth ${s} exceeds maximum ${r}`);const o=await this.revokeNode(i,!0,t.reason,t.dryRun);n.push(o),t.onRevoke&&await t.onRevoke(o);const a=await this.graph.getDescendants(e);for(const r of a){const i=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);n.push(i),t.onRevoke&&await t.onRevoke(i)}return n}async revokeNode(e,t,r,n,i){const s={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:r};if(n)return s;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return s}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const r={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return r}async isRevoked(e){const t=await this.graph.getChain(e);for(const r of t)if(r.credentialStatusId){const t=this.parseCredentialStatus(r.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:r.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:r.id===e?void 0:r.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),r=[];(await this.isRevoked(e)).revoked&&r.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&r.push(e.id);return r}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,r,n]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(n,10).toString(),statusListCredential:r}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const r=await this.graph.validateChain(e);return r.valid?{valid:!0}:r}}function q(e,t){return new z(e,t)}function F(e,t){if(!e.constraints.audience)return!0;const r=e.constraints.audience;return"string"==typeof r?r===t:r.includes(t)}var Y=r(95354),G=r(77598),X=r(4573);const Q=e=>e.d?(0,G.createPrivateKey)({format:"jwk",key:e}):(0,G.createPublicKey)({format:"jwk",key:e});var Z=r(36463);function ee(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var te=r(57975),re=r(56233),ne=r(73960),ie=r(99769),se=r(71964);function oe(e){return ee(e)&&"string"==typeof e.kty}new WeakMap;const ae=(e,t)=>{let r;if((0,re.R)(e))r=G.KeyObject.from(e);else{if(!(0,ne.A)(e)){if(oe(e))return e.crv;throw new TypeError((0,ie.A)(e,...se.g))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new Z.T0("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},ce=(e,t)=>{let r;try{r=e instanceof G.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},de=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ue(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function le(e,t){return e.name===t}function he(e){return parseInt(e.name.slice(4),10)}function fe(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!le(e.algorithm,"HMAC"))throw ue("HMAC");const r=parseInt(t.slice(2),10);if(he(e.algorithm.hash)!==r)throw ue(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!le(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ue("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(he(e.algorithm.hash)!==r)throw ue(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!le(e.algorithm,"RSA-PSS"))throw ue("RSA-PSS");const r=parseInt(t.slice(2),10);if(he(e.algorithm.hash)!==r)throw ue(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ue("Ed25519 or Ed448");break;case"Ed25519":if(!le(e.algorithm,"Ed25519"))throw ue("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!le(e.algorithm,"ECDSA"))throw ue("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ue(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}const pe=(0,te.promisify)(G.sign);var ge=r(62165);const ye=e=>e?.[Symbol.toStringTag],me=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function ve(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&oe(t)){if(function(e){return oe(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&me(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!(0,se.A)(t))throw new TypeError((0,ie.t)(e,t,...se.g,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${ye(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,n,e):((e,t,r,n)=>{if(n&&oe(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&me(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&me(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!(0,se.A)(t))throw new TypeError((0,ie.t)(e,t,...se.g,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${ye(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${ye(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${ye(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${ye(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${ye(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}ve.bind(void 0,!1);const we=ve.bind(void 0,!0);class Se{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Z.Ye("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new Z.Ye("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(function(e,t,r,n,i){if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!s.has(t))throw new Z.T0(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(Z.Ye,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new Z.Ye('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new Z.Ye('JWS "alg" (Algorithm) Header Parameter missing or invalid');we(i,e,"sign");let s,o=this._payload;n&&(o=ge.Rd.encode((0,Y.lF)(o))),s=this._protectedHeader?ge.Rd.encode((0,Y.lF)(JSON.stringify(this._protectedHeader))):ge.Rd.encode("");const a=(0,ge.xW)(s,ge.Rd.encode("."),o),c=await(async(e,t,r)=>{const n=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,ie.A)(t,...se.g));return(0,G.createSecretKey)(t)}if(t instanceof G.KeyObject)return t;if((0,re.R)(t))return fe(t,e,"sign"),G.KeyObject.from(t);if(oe(t))return e.startsWith("HS")?(0,G.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError((0,ie.A)(t,...se.g,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=G.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new Z.T0(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),n);return t.update(r),t.digest()}return pe(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new Z.T0(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r,function(e,t){let r,n,i,s;if(t instanceof G.KeyObject)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(i=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");ce(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:i}=n,s=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${s}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==i&&i>s>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");ce(t,e),s={padding:G.constants.RSA_PKCS1_PSS_PADDING,saltLength:G.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const n=ae(t),i=de.get(e);if(n!==i)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${i}, got ${n}`);s={dsaEncoding:"ieee-p1363"};break}default:throw new Z.T0(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return i?{format:"jwk",key:t,...s}:s?{...s,key:t}:t}(e,n))})(i,e,a),d={signature:(0,Y.lF)(c),payload:""};return n&&(d.payload=ge.D0.decode(o)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=ge.D0.decode(s)),d}}class be{_flattened;constructor(e){this._flattened=new Se(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const De=e=>Math.floor(e.getTime()/1e3),Ie=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ke=e=>{const t=Ie.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(86400*r);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};function Ee(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class _e{_payload;constructor(e={}){if(!ee(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:Ee("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Ee("setNotBefore",De(e))}:this._payload={...this._payload,nbf:De(new Date)+ke(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Ee("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Ee("setExpirationTime",De(e))}:this._payload={...this._payload,exp:De(new Date)+ke(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:De(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Ee("setIssuedAt",De(e))}:this._payload="string"==typeof e?{...this._payload,iat:Ee("setIssuedAt",De(new Date)+ke(e))}:{...this._payload,iat:Ee("setIssuedAt",e)},this}}class Ae extends _e{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new be(ge.Rd.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Z.Dp("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}async function Ce(e){const{agentDid:t,userDid:r,delegationId:n,delegationChain:i,scopes:s,privateKeyJwk:o,kid:a,targetHostname:c}=e,d=await async function(e,t){if(!ee(e))throw new TypeError("JWK must be an object");switch(t||=e.alg,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return(0,Y.D4)(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new Z.T0('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Q({...e,alg:t});default:throw new Z.T0('Unsupported "kty" (Key Type) Parameter value')}}(o,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new Ae({delegation_id:n,delegation_chain:i,scope:s.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(r).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function Te(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const Pe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",$e=new Map;for(let e=0;e<Pe.length;e++){const t=Pe[e];void 0!==t&&$e.set(t,e)}function Ne(e){if(0===e.length)return"";let t=BigInt(0);for(let r=0;r<e.length;r++){const n=e[r];void 0!==n&&(t=t*BigInt(256)+BigInt(n))}let r="";for(;t>0;)r=Pe[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}function Re(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const r of e){const e=$e.get(r);if(void 0===e)throw new Error(`Invalid base58 character: ${r}`);t=t*BigInt(58)+BigInt(e)}const r=[];for(;t>0;)r.unshift(Number(t%BigInt(256))),t/=BigInt(256);let n=0;for(const t of e){if("1"!==t)break;n++}const i=new Uint8Array(n+r.length);return i.set(r,n),i}function Oe(e){if(0===e.length)return!0;for(const t of e)if(!$e.has(t))return!1;return!0}function Me(e){return"string"==typeof e&&e.startsWith("did:")}function xe(e){if(!Me(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function Ke(e){return e.trim()}function Le(e,t){return Ke(e)===Ke(t)}function He(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function je(e){const t=e.split(":");return t[t.length-1]??e}function Ue(e){return je(e)}const We=new Uint8Array([237,1]);function Ve(e){const t=new Uint8Array(We.length+e.length);return t.set(We),t.set(e,We.length),`did:key:z${Ne(t)}`}function Be(e){return Ve(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function Je(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const ze={debug:10,info:20,warn:30,error:40};function qe(){let e="info",t=!1;function r(r,...n){if(function(t){return ze[t]>=ze[e]}(r))if(t)console.error(...n);else switch(r){case"debug":"function"==typeof console.debug?console.debug(...n):console.log(...n);break;case"info":"function"==typeof console.info?console.info(...n):console.log(...n);break;case"warn":"function"==typeof console.warn?console.warn(...n):console.error(...n);break;case"error":console.error(...n)}}return{configure(r={}){r.level&&(e=r.level),!0===r.forceStderr?t=!0:!1===r.forceStderr?t=!1:"stdio"===r.transport?t=!0:"sse"!==r.transport&&"http"!==r.transport||(t=!1)},debug:(...e)=>r("debug",...e),info:(...e)=>r("info",...e),warn:(...e)=>r("warn",...e),error:(...e)=>r("error",...e)}}const Fe=qe(),Ye=new Uint8Array([237,1]),Ge=32;function Xe(e){return e.startsWith("did:key:z6Mk")}function Qe(e){if(!e.startsWith("did:key:z"))return null;try{const t=Re(e.replace("did:key:","").slice(1));return t.length<Ye.length+Ge||t[0]!==Ye[0]||t[1]!==Ye[1]?null:t.slice(Ye.length)}catch(e){return Fe.debug("Failed to extract public key from did:key",e),null}}function Ze(e){return{kty:"OKP",crv:"Ed25519",x:c(e)}}function et(){return{resolve:async e=>{if(!Xe(e))return null;const t=Qe(e);if(!t)return null;const r=Ze(t),n=e.replace("did:key:",""),i=Je(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:n}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}}}function tt(e){if(!Xe(e))return null;const t=Qe(e);if(!t)return null;const r=Ze(t),n=e.replace("did:key:",""),i=Je(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:n}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}const rt={AGENT_DID:"KYA-OS-Agent-DID",DELEGATION_CHAIN:"KYA-OS-Delegation-Chain",SESSION_ID:"KYA-OS-Session-Id",DELEGATION_PROOF:"KYA-OS-Delegation-Proof"};async function nt(e){const{session:t,delegation:r,serverIdentity:n,targetUrl:i}=e;if(!t.agentDid)throw new Error("Session must have agentDid for outbound delegation");if(!t.sessionId)throw new Error("Session must have sessionId for outbound delegation");if(!r.vcId)throw new Error("Delegation must have vcId for outbound delegation");const s=function(e){try{return new URL(e).hostname}catch{return Fe.warn("Failed to parse target URL, using as-is",{url:e}),e}}(i),o=function(e,t){const r=u(e),n=64===r.length?r.subarray(0,32):r;if(!Xe(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const i=Qe(t);if(!i)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:c(i),d:c(n)}}(n.privateKey,n.did),a=await Ce({agentDid:n.did,userDid:t.agentDid,delegationId:r.id,delegationChain:r.vcId,scopes:["delegation:propagate"],privateKeyJwk:o,kid:n.kid,targetHostname:s});return Fe.debug("Built outbound delegation headers",{agentDid:t.agentDid,delegationChain:r.vcId,sessionId:t.sessionId,targetHostname:s}),{"KYA-OS-Agent-DID":t.agentDid,"KYA-OS-Delegation-Chain":r.vcId,"KYA-OS-Session-Id":t.sessionId,"KYA-OS-Delegation-Proof":a}}class it{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return Fe.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[r,n,i]=t;let a,c,d;try{a=JSON.parse(s(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(n)try{c=JSON.parse(s(n))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{d=o(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:a,payload:c,signatureBytes:d,signingInput:`${r}.${n}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return Fe.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return Fe.error("[CryptoService] Key ID mismatch"),!1;let n;try{n=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return Fe.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return Fe.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];n={header:JSON.parse(s(e)),payload:void 0,signatureBytes:o(t),signingInput:""}}catch{return Fe.error("[CryptoService] Invalid detached JWS format"),!1}}}const i=r?.alg||"EdDSA";if(n.header.alg!==i)return Fe.error(`[CryptoService] Unsupported algorithm: ${n.header.alg}, expected ${i}`),!1;let a,d;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let n;n=r.detachedPayload instanceof Uint8Array?c(r.detachedPayload):c((new TextEncoder).encode(r.detachedPayload)),a=(new TextEncoder).encode(`${t}.${n}`)}else{if(!n.signingInput)return Fe.error("[CryptoService] Missing signing input for compact JWS"),!1;a=(new TextEncoder).encode(n.signingInput)}try{d=this.jwkToBase64PublicKey(t)}catch(e){return Fe.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(a,n.signatureBytes,d)}catch(e){return Fe.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=o(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return d(t)}}const st=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),ot=12,at=32;async function ct(e,t,r){const n={method:e.method,...e.params?{params:e.params}:{}},i=await r((new TextEncoder).encode((0,T.d)(n)));return void 0===t?{requestHash:i}:{requestHash:i,responseHash:await r((new TextEncoder).encode((0,T.d)(t.data)))}}class dt{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,r,n={}){const i=await this.generateCanonicalHashes(e,t),s={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:i.requestHash,...void 0!==i.responseHash?{responseHash:i.responseHash}:{},...n};return{jws:await this.generateJWS(s),meta:s}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t){return ct(e,t,e=>this.cryptoProvider.hash(e))}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,G.createPrivateKey)({key:X.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),n={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}},i=(0,T.d)(n),s=(new TextEncoder).encode(i);return await new be(s).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=u(e).subarray(0,at),r=new Uint8Array(st.length+t.length);r.set(st),r.set(t,st.length);const n=d(r);return"-----BEGIN PRIVATE KEY-----\n"+(n.match(/.{1,64}/g)?.join("\n")??n)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const n=await this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==n.requestHash)return!1;if(void 0!==e.meta.responseHash&&(void 0===n.responseHash||e.meta.responseHash!==n.responseHash))return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey);return new it(this.cryptoProvider).verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=u(e);if(t.length!==at)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:c(t),kid:this.identity.kid}}}async function ut(e,t,r,n,i,s={}){const o={data:t},a=new dt(r,i),c=await a.generateProof(e,o,n,s);return o.meta={proof:c},o}function lt(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const ht="_kyaos";function ft(e){return e.startsWith(ht)}function pt(e,t){const r={};for(const[e,n]of Object.entries(t))ft(e)||(r[e]=n);return{method:e,params:r}}async function gt(e){const{identity:t,crypto:r,toolName:n,args:i,audience:s,sessionId:o}=e,a=new dt(t,r),d=pt(n,i),u=c(await r.randomBytes(16)),l=Math.floor(Date.now()/1e3);return a.generateProof(d,void 0,{sessionId:o??"",audience:s,nonce:u,timestamp:l,createdAt:l,lastActivity:l,ttlMinutes:30,identityState:"anonymous"})}const yt="holder_binding_failed";function mt(e){return null!==Qe(e)}async function vt(e){const{proof:t,subjectDid:r,request:n,response:i,expectedAudience:s,proofVerifier:o}=e,a=Qe(r);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${xe(r)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:yt,reason:"Malformed proof: missing meta"};if(t.meta.did!==r)return{status:"unbound",errorCode:yt,reason:"Proof subject does not match the delegation subject"};if(void 0!==s&&!(Array.isArray(s)?s:[s]).includes(t.meta.audience))return{status:"unbound",errorCode:yt,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=Ze(a);c.kid=`${r}#${Je(r)}`;const d=await o.verifyProof(t,c,{request:n,...void 0!==i?{response:i}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:yt,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}class wt{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,r=t;return this.indexCounters.set(e,t+1),r}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}class St{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}async getDescendants(e){const t=[],r=[e],n=new Set;for(;r.length>0;){const e=r.shift();if(n.has(e))continue;n.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!n.has(e)){r.push(e);const n=this.nodes.get(e);n&&t.push(n)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,r=e.filter(e=>0===e.children.length).length;let n=0;for(const t of e){const e=this.getChainSync(t.id);n=Math.max(n,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:n}}getChainSync(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}}function bt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&0!==t.id.length&&"string"==typeof t.type&&0!==t.type.length&&"string"==typeof t.controller&&0!==t.controller.length}function Dt(e){return e.startsWith("did:web:")}function It(e){if(!Dt(e))return null;const t=e.slice(8);if(0===t.length)return null;const r=t.split(":"),n=decodeURIComponent(r[0]);return 0===n.length?null:{domain:n,path:r.slice(1).map(e=>decodeURIComponent(e))}}function kt(e){const t=It(e);if(!t)return null;const{domain:r,path:n}=t;let i=`https://${r}`;return 0===n.length?i+="/.well-known/did.json":i+="/"+n.join("/")+"/did.json",i}class Et{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!Dt(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const r=kt(e);if(!r)return Fe.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(r);if(!t.ok)return Fe.warn(`[DidWebResolver] HTTP ${t.status} fetching ${r}`),null;let n;try{n=await t.json()}catch{return Fe.warn(`[DidWebResolver] Invalid JSON from ${r}`),null}return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||0===t.id.length)return!1;if(void 0!==t.verificationMethod){if(!Array.isArray(t.verificationMethod))return!1;for(const e of t.verificationMethod)if(!bt(e))return!1}return!0}(n)?n.id!==e?(Fe.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${n.id}`),null):(this.cache.set(e,{document:n,expiresAt:Date.now()+this.cacheTtl}),n):(Fe.warn(`[DidWebResolver] Invalid DID Document structure from ${r}`),null)}catch(t){return Fe.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function _t(e,t){return new Et(e,t)}const At=new Uint8Array([237,1]),Ct=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function Tt(e,t){if(!Dt(e.did))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${e.did}")`);if(!e.kid.startsWith(`${e.did}#`))throw new Error(`buildDidWebDocument: identity.kid "${e.kid}" does not reference identity.did "${e.did}"`);const r=function(e){const t=u(e);if(32!==t.length)throw new Error(`buildDidWebDocument: expected 32-byte Ed25519 public key, got ${t.length} bytes after base64 decode`);return t}(e.publicKey),n=Ze(r),i=function(e){const t=new Uint8Array(At.length+e.length);return t.set(At),t.set(e,At.length),`z${Ne(t)}`}(r),s={id:e.kid,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyJwk:n,publicKeyMultibase:i};return{"@context":t?.additionalContexts?.length?[...Ct,...t.additionalContexts]:[...Ct],id:e.did,verificationMethod:[s],authentication:[e.kid],assertionMethod:[e.kid]}}class Pt{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,r){const n=new Uint8Array(16);globalThis.crypto.getRandomValues(n);const i=`rt_${Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}`,s=Date.now();return this.tokens.set(i,{agentDid:e,scopes:t,createdAt:s,expiresAt:s+this.ttl,metadata:r,fulfilled:!1}),i}async get(e){const t=this.tokens.get(e);return t?Date.now()>t.expiresAt?(this.tokens.delete(e),null):t.fulfilled?null:{agentDid:t.agentDid,scopes:t.scopes,createdAt:t.createdAt,expiresAt:t.expiresAt,metadata:t.metadata}:null}async fulfill(e){const t=this.tokens.get(e);t&&(t.fulfilled=!0)}clear(){this.tokens.clear()}}async function $t(e,t,r){const n=Date.now();let i,s;if(r.debug&&Fe.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.reputationService&&void 0!==r.authorization.minReputationScore){const n=r.authorization.unknownAgentPolicy??"require-consent";try{i=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),n={"Content-Type":"application/json"};let i;if(t.apiKey&&(n["X-API-Key"]=t.apiKey),i="v2"===t.apiFormat?await fetch(`${r}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:n,body:JSON.stringify({include_details:!1})}):await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:n}),!i.ok){if(404===i.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${i.status} ${i.statusText}`)}const s=await i.json(),o=s.score??0,a=(s.level??s.riskLevel??"unknown").toLowerCase(),c="low"===a||"medium"===a||"high"===a?a:"unknown";return{agentDid:s.agent_did??s.agentDid??e,score:o,totalInteractions:s.totalInteractions??0,successRate:s.successRate??0,riskLevel:c,updatedAt:s.calculatedAt?new Date(s.calculatedAt).getTime():s.updatedAt??Date.now()}}(e,r.reputationService)}catch(t){Fe.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),i={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(r.debug&&Fe.debug(`[AuthHandshake] Reputation score: ${i.score}`),null===i.score){if("deny"===n)return{authorized:!1,authError:await Nt(e,t,r,"Unknown agent denied by policy"),reputation:i,reason:"Unknown agent — policy: deny"};if("require-consent"===n)return{authorized:!1,authError:await Nt(e,t,r,"Unknown agent requires consent"),reputation:i,reason:"Unknown agent — policy: require-consent"};r.debug&&Fe.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==i.score&&i.score<r.authorization.minReputationScore)return r.debug&&Fe.debug(`[AuthHandshake] Reputation ${i.score} < ${r.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Nt(e,t,r,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}try{s=await r.delegationVerifier.verify(e,t)}catch(n){Fe.error("[AuthHandshake] Delegation verification failed:",n);const i=`Delegation verification error: ${n instanceof Error?n.message:"Unknown error"}`;return{authorized:!1,authError:await Nt(e,t,r,i),reason:i}}return s.valid&&s.delegation?(r.debug&&Fe.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-n}ms)`),{authorized:!0,delegation:s.delegation,credential:s.credential,reputation:i,reason:"Valid delegation found"}):(r.debug&&Fe.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-n}ms)`),{authorized:!1,authError:await Nt(e,t,r,s.reason??"No valid delegation found"),reputation:i,reason:s.reason??"No delegation"})}async function Nt(e,t,r,n){const i=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),s=Date.now()+(r.authorization.resumeTokenTtl??6e5),o=new URL(r.authorization.authorizationUrl);o.searchParams.set("agent_did",e),o.searchParams.set("scopes",t.join(",")),o.searchParams.set("resume_token",i);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(o.toString())}`};return I({message:n,authorizationUrl:o.toString(),resumeToken:i,expiresAt:s,scopes:t,display:a})}function Rt(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const Ot={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",CONTENT_BINDING_MISMATCH:"CONTENT_BINDING_MISMATCH",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",META_POLICY_VIOLATION:"META_POLICY_VIOLATION",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class Mt extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}function xt(e,t,r){return new Mt(e,t,r)}const Kt=120,Lt=30,Ht=600;class jt{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new it(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??Kt,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(Lt,Math.min(Ht,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,r){try{const n=this.buildCanonicalPayload(e.meta),i=(new TextEncoder).encode(n);return await this.runVerificationPipeline(e,t,i,r)}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,r){try{const n=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,r,n)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,r,n){const i=await this.validateProofStructure(e);if(!i.valid)return i;const s=i.proof,o=await this.validateNonce(s.meta.nonce,s.meta.did);if(!o.valid)return o;const a=await this.validateTimestamp(s.meta.ts);if(!a.valid)return a;const c=await this.verifySignature(s.jws,t,r,s.meta.kid);if(!c.valid)return c;if(void 0!==n){const e=await this.validateContentBinding(s,n);if(!e.valid)return e}return await this.addNonceToCache(s.meta.nonce,s.meta.did),{valid:!0}}async validateContentBinding(e,t){const{requestHash:r,responseHash:n}=await ct(t.request,t.response,e=>this.cryptoProvider.hash(e));if(e.meta.requestHash!==r)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:Ot.CONTENT_BINDING_MISMATCH};const i=void 0!==e.meta.responseHash;return i!==(void 0!==t.response)?{valid:!1,reason:i?"Proof binds a response (responseHash present) but no response was supplied to verify against — pass expected.response":"A response was supplied but the proof binds none — content/proof mismatch",errorCode:Ot.CONTENT_BINDING_MISMATCH}:i&&e.meta.responseHash!==n?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:Ot.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:Ot.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}async validateProofStructure(e){const t=C(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:Ot.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error?.message}`),details:{validationError:t.error?.message}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:Ot.NONCE_REPLAY_DETECTED,details:{nonce:e,agentDid:t}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:Ot.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,n){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:n,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:Ot.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:n,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const r=await this.fetch.resolveDID(e);if(!r)throw new Mt(Ot.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const n=r;if(!n.verificationMethod||0===n.verificationMethod.length)throw new Mt(Ot.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let i;if(t){const r=t.startsWith("#")?t:`#${t}`;if(i=n.verificationMethod.find(t=>t.id===r||t.id===`${e}${r}`),!i)throw new Mt(Ot.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:n.verificationMethod.map(e=>e.id)})}else i=n.verificationMethod[0];if(!i?.publicKeyJwk)throw new Mt(Ot.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:i?.id});const s=i.publicKeyJwk;if("OKP"!==s.kty||"Ed25519"!==s.crv||!s.x)throw new Mt(Ot.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${s.kty}, crv=${s.crv}`,{did:e,kid:t,jwk:{kty:s.kty,crv:s.crv}});const o=s;return!o.kid&&i.id&&(o.kid=i.id),o}catch(r){if(r instanceof Mt)throw r;throw Fe.error("[ProofVerifier] Failed to fetch public key from DID",{error:r}),new Mt(Ot.DID_RESOLUTION_FAILED,`DID resolution failed: ${r instanceof Error?r.message:String(r)}`,{did:e,kid:t,originalError:r instanceof Error?r.message:String(r)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}};return(0,T.d)(t)}}function Ut(e,t="strict"){const r=Object.keys(e).filter(e=>"proof"!==e);return"strict"===t&&r.length>0?{valid:!1,reason:`_meta contains keys other than 'proof' in strict mode: ${r.join(", ")}`,extraKeys:r}:{valid:!0}}function Wt(e,t="strict"){const r=e.proof;if(!r)return{success:!1,reason:"_meta does not contain proof",errorCode:Ot.MISSING_REQUIRED_FIELD};const n=Ut(e,t);if(!n.valid)return{success:!1,reason:n.reason,errorCode:Ot.META_POLICY_VIOLATION};const i=C(r);return i.success?{success:!0,proof:i.data}:{success:!1,reason:i.error?.message??"Invalid proof structure",errorCode:Ot.INVALID_PROOF_STRUCTURE}}class Vt{}class Bt{}class Jt{}class zt{}class qt{}class Ft{}class Yt extends zt{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}class Gt extends qt{nonces=new Map;async has(e,t){const r=t?`nonce:${t}:${e}`:`nonce:${e}`,n=this.nonces.get(r);return!(!n||Date.now()>n&&(this.nonces.delete(r),1))}async add(e,t,r){const n=r?`nonce:${r}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(n,i)}async cleanup(){const e=Date.now();for(const[t,r]of this.nonces)e>r&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}class Xt extends Ft{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#${Je(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return Be(e)}}class Qt{config;cryptoProvider;sessions=new Map;sessionInsertionOrder=[];maxSessions;constructor(e,t={}){this.cryptoProvider=e,this.maxSessions=t.maxSessions??1e4,this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new Gt,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof Gt&&Fe.warn("[SessionManager] Using MemoryNonceCacheProvider — not suitable for multi-instance deployments. Use Redis, DynamoDB, or Cloudflare KV for production.")}setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:n.handshake_failed,message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust timestampSkewSeconds if needed.`}};if(this.config.serverDid&&e.audience!==this.config.serverDid)return{success:!1,error:{code:n.handshake_failed,message:`Audience mismatch: expected ${this.config.serverDid}, got ${e.audience}`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:n.handshake_failed,message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const i=e.agentDid?b:D,s=Math.ceil(i/1e3);await this.config.nonceCache.add(e.nonce,s,e.agentDid);const o=await this.generateSessionId(),a=await this.buildClientInfo(e),c={sessionId:o,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,identityState:"anonymous",metaPolicy:this.config.metaPolicy,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...a&&{clientInfo:a}};return this.evictIfNeeded(),this.sessions.set(o,c),this.sessionInsertionOrder.push(o),{success:!0,session:c}}catch(e){return{success:!1,error:{code:n.handshake_failed,message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||void 0!==this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}async generateSessionId(){const e=await this.cryptoProvider.randomBytes(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");return`kyaos_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}async generateClientId(){const e=await this.cryptoProvider.randomBytes(6);return`client_${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}normalizeClientInfoString(e){if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0}async buildClientInfo(e){if(!e.clientInfo&&"string"!=typeof e.clientProtocolVersion&&void 0===e.clientCapabilities)return;const t=e.clientInfo;return{name:this.normalizeClientInfoString(t?.name)??"unknown",title:this.normalizeClientInfoString(t?.title),version:this.normalizeClientInfoString(t?.version),platform:this.normalizeClientInfoString(t?.platform),vendor:this.normalizeClientInfoString(t?.vendor),persistentId:this.normalizeClientInfoString(t?.persistentId),clientId:this.normalizeClientInfoString(t?.clientId)??await this.generateClientId(),protocolVersion:this.normalizeClientInfoString(e.clientProtocolVersion),capabilities:e.clientCapabilities}}static generateNonce(){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}evictIfNeeded(){for(;this.sessions.size>=this.maxSessions&&this.sessionInsertionOrder.length>0;){const e=this.sessionInsertionOrder.shift();e&&this.sessions.delete(e)}}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let n=e-r.lastActivity>60*r.ttlMinutes;n||void 0===this.config.absoluteSessionLifetime||(n=e-r.createdAt>60*this.config.absoluteSessionLifetime),n&&this.sessions.delete(t)}this.sessionInsertionOrder=this.sessionInsertionOrder.filter(e=>this.sessions.has(e)),await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear(),this.sessionInsertionOrder=[]}}function Zt(e){return{nonce:Qt.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function er(e){return"object"==typeof e&&null!==e&&"string"==typeof e.nonce&&e.nonce.length>0&&"string"==typeof e.audience&&e.audience.length>0&&"number"==typeof e.timestamp&&e.timestamp>0&&Number.isInteger(e.timestamp)}const tr=Buffer.from("302e020100300506032b657004220420","hex"),rr=Buffer.from("302a300506032b6570032100","hex");class nr extends Vt{async sign(e,t){const r=Buffer.from(t,"base64"),n=64===r.length?r.subarray(0,32):r,i=(0,G.createPrivateKey)({key:Buffer.concat([tr,n]),format:"der",type:"pkcs8"});return new Uint8Array((0,G.sign)(null,Buffer.from(e),i))}async verify(e,t,r){try{const n=(0,G.createPublicKey)({key:Buffer.concat([rr,Buffer.from(r,"base64")]),format:"der",type:"spki"});return(0,G.verify)(null,Buffer.from(e),n,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,G.generateKeyPairSync)("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{privateKey:t.subarray(16,48).toString("base64"),publicKey:e.subarray(12,44).toString("base64")}}async hash(e){return`sha256:${(0,G.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,G.randomBytes)(e))}}class ir extends Bt{now(){return Date.now()}isWithinSkew(e,t){return Math.abs(Date.now()-e)<=1e3*t}hasExpired(e){return Date.now()>e}calculateExpiry(e){return Date.now()+1e3*e}format(e){return new Date(e).toISOString()}}class sr extends Jt{didKeyResolver=et();didWebResolver;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1}async resolveDID(e){return e.startsWith("did:key:")?this.didKeyResolver.resolve(e):Dt(e)?this.isBlockedTarget(kt(e))?null:(this.didWebResolver||(this.didWebResolver=_t(this)),this.didWebResolver.resolve(e)):null}async fetchStatusList(e){if(this.isBlockedTarget(e))return null;try{const t=await this.fetch(e);if(!t.ok)return null;const r=await t.json();return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.type)||!t.type.includes("StatusList2021Credential"))return!1;const r=t.credentialSubject;if("object"!=typeof r||null===r)return!1;const n=r;return"StatusList2021"===n.type&&"string"==typeof n.encodedList}(r)?r:null}catch{return null}}async fetchDelegationChain(e){return[]}async fetch(e,t){if("function"!=typeof globalThis.fetch)throw new Error("Global fetch is not available in this runtime");return globalThis.fetch(e,t)}isBlockedTarget(e){if(this.allowPrivateNetworkHosts||null===e)return!1;let t;try{t=new URL(e).hostname}catch{return!1}return function(e){let t=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.includes(":"))return"::1"===t||"::"===t||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd");const r=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(!r)return!1;const n=Number(r[1]),i=Number(r[2]);return 127===n||10===n||0===n||169===n&&254===i||192===n&&168===i||172===n&&i>=16&&i<=31}(t)}}class or extends Jt{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function ar(e){return{version:"audit.v1",ts:Date.now(),session:e.session.sessionId,audience:e.session.audience,did:e.identity.did,kid:e.identity.kid,reqHash:e.requestHash,resHash:e.responseHash??"-",verified:e.verified,scope:e.scopeId??"-"}}class cr{}class dr extends cr{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(ar(e)))}async logEvent(e){this.events.push(e)}}class ur extends cr{async logAuditRecord(e){}async logEvent(e){}}const lr=256,hr=256,fr=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function pr(e,t,r){switch(t){case"exact":return e===r;case"prefix":{const t=e.endsWith("*")?e.slice(0,-1):e;return 0!==t.length&&r.startsWith(t)}case"regex":if(e.length>lr||r.length>hr)return!1;if(fr.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(r)}catch{return!1}default:return!1}}function gr(e,t){if(function(e){const t=e?.credentialSubject?.delegation;return[...t?.scopes??[],...t?.constraints?.scopes??[]]}(t).includes(e))return{satisfied:!0,usedNonExactMatcher:!1};for(const r of function(e){return e?.credentialSubject?.delegation?.constraints?.crisp?.scopes??[]}(t))if(pr(r.resource,r.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==r.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}function yr(e){const t=new Set;for(const r of e.credentialSubject.delegation.scopes??[])t.add(r);for(const r of e.credentialSubject.delegation.constraints?.scopes??[])t.add(r);return Array.from(t)}function mr(e,t){const r=yr(e),n=yr(t),i=t.credentialSubject.delegation,s=e=>`${e.matcher}\0${e.resource}`,o=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(s)),a=(i.constraints.crisp?.scopes??[]).filter(e=>!o.has(s(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${i.id} introduces crisp scope matcher(s) absent from parent ${e.credentialSubject.delegation.id}: ${a.map(e=>`${e.matcher}:${e.resource}`).join(", ")}`};if(0===r.length)return{valid:!0};if(0===n.length)return{valid:!1,reason:`Delegation ${i.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(r),d=n.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${i.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const vr=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],wr=["read","get","list","describe","search","query"];class Sr{options;constructor(e={}){this.options=e}classify(e){const t=this.options.hints?.[e.toolName];if(t?.reversibility&&t.blastRadius&&t.severity)return{reversibility:t.reversibility,blastRadius:t.blastRadius,severity:t.severity};const r=br(e.toolName),n=function(e){const t=br(e);return t.includes("prod")||t.includes("production")}(e.namespace);let i;return i=r.some(e=>vr.includes(e))?{reversibility:"irreversible",blastRadius:n?"environment":"resource",severity:n?"catastrophic":"high"}:r.some(e=>wr.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...i,...Dr(t)}}}function br(e){return e.split(/[.:/_\-\s]+/).flatMap(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/\s+/)).map(e=>e.toLowerCase()).filter(Boolean)}function Dr(e){if(!e)return{};const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}class Ir{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:r,scopeMatched:n,humanApprovals:i}=e.context;if(!n)return{decision:"deny",reason:"scope_not_matched"};if("unknown"===t||"unknown"===r)return{decision:"deny",reason:"unclassified_high_risk"};if("irreversible"===r||"catastrophic"===t||"high"===t){const e=this.cfg.stepUpQuorum??1;return i.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function kr(e,t,r,n){if(r.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const i=new Set;for(const s of e)"approve"===s.decision&&s.requestHash===t&&(r.approvers.length>0&&!r.approvers.includes(s.approverDid)||await n(s)&&i.add(s.approverDid));return i.size>=r.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${i.size}/${r.n}`}}function Er(e){return{principal:{agentDid:e.principal.agentDid,...e.principal.responsibleParty?{responsibleParty:e.principal.responsibleParty}:{}},action:{toolName:e.action.toolName},resource:{namespace:e.resource.namespace},context:{delegatedScopes:e.delegatedScopes,scopeMatched:e.scopeMatched,humanApprovals:e.humanApprovals??[],...e.risk,...void 0!==e.budgetRemaining?{budgetRemaining:e.budgetRemaining}:{}}}}const _r=["handshake","identity","reputation"];function Ar(e,t=256){const r="string"==typeof e?e:String(e);let n="";for(const e of r){const t=e.codePointAt(0)??0;n+=t<=31||t>=127&&t<=159?"�":e}return n.length>t?`${n.slice(0,t)}…`:n}function Cr(e,t){const r={did:e.identity.did,kid:e.identity.kid,privateKey:e.identity.privateKey,publicKey:e.identity.publicKey},i=e.nonceCache??new Gt,s=new Qt(t,{...e.session,serverDid:r.did,nonceCache:i}),a=new dt(r,t),u=e.delegation,l=e.auditLog??new ur,h=u?.holderBinding??"off",f="off"===h?void 0:new jt({cryptoProvider:t,clockProvider:new ir,nonceCacheProvider:i,fetchProvider:u?.fetchProvider??("function"==typeof globalThis.fetch?new sr:new or)}),g=new Map;let y;const m={name:"_kyaos",description:"KYA-OS protocol — identity verification, session handshake, and server metadata",inputSchema:{type:"object",properties:{action:{type:"string",enum:[..._r],description:"Protocol operation to perform"},nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["action"]}};async function v(e){if(!er(e))return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:n.handshake_failed,message:"Invalid handshake format: requires nonce (string), audience (string), and timestamp (positive integer)"}})}],isError:!0};const t=await s.validateHandshake(e);return t.success&&t.session&&(g.set(t.session.sessionId,t.session.nonce),y=t.session.sessionId),{content:[{type:"text",text:JSON.stringify({success:t.success,...t.session&&{sessionId:t.session.sessionId,serverDid:r.did,serverKid:r.kid},...t.error&&{error:t.error}})}],...t.error&&{isError:!0}}}async function w(){if(y&&await s.getSession(y))return y;if(!e.autoSession)return;const n=c(await t.randomBytes(16)),i=Math.floor(Date.now()/1e3),o=await s.validateHandshake({nonce:n,audience:r.did,timestamp:i});return o.success&&o.session?(y=o.session.sessionId,g.set(o.session.sessionId,o.session.nonce),y):void 0}async function S(e,t,r,n,i,o="denied",c,d){try{const u=n??await w();if(!u)return e;const l=await s.getSession(u);if(!l)return e;let h;if(void 0!==c)h=c;else{h={};for(const[e,t]of Object.entries(r))"_kyaos_delegation"!==e&&(h[e]=t)}const f={method:t,params:h},p=void 0!==d?{data:d}:void 0,g=await a.generateProof(f,p,l,{outcome:o,reason:Ar(i)});e._meta={...e._meta??{},proof:g}}catch(e){Fe.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)})}return e}const b=new Sr,D=new Ir;return{identity:e.identity,sessionManager:s,proofGenerator:a,kyaOsTool:m,handshakeTool:{name:"_kyaos_handshake",description:"KYA-OS identity handshake — establishes a cryptographic session",inputSchema:{type:"object",properties:{nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["nonce","audience","timestamp"]}},handleKyaOs:async function(t){const i="string"==typeof t.action?t.action:void 0;switch(i){case"handshake":return v(t);case"identity":return async function(){return{content:[{type:"text",text:JSON.stringify({did:r.did,kid:r.kid,name:e.identity.agentName??r.did,capabilities:["handshake","signing","verification"],protocolVersion:"1.0.0",clockSkewSeconds:s.getStats().config.timestampSkewSeconds})}]}}();case"reputation":return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:n.runtime_error,message:'action: "reputation" is not yet implemented.'}})}],isError:!0};default:return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:n.invalid_request,message:`Unknown _kyaos action: "${i??"(missing)"}". Valid actions: ${_r.join(", ")}`}})}],isError:!0}}},handleHandshake:v,wrapWithProof:function(e,t){return async(n,i,o)=>{const c=await t(n,i,o);if(c.isError)return c;const d=i??await w();if(!d)return c;const u=await s.getSession(d);if(!u)return c;try{const t={method:e,params:n},i={data:c.content},s=await a.generateProof(t,i,u,{scopeId:o?.scopeId});c._meta={proof:s};try{await l.logAuditRecord({identity:{did:r.did,kid:r.kid},session:{sessionId:u.sessionId,audience:u.audience},requestHash:s.meta.requestHash,responseHash:s.meta.responseHash,verified:"yes",scopeId:s.meta.scopeId})}catch(t){Fe.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){Fe.error("[kya-os] Proof generation failed",{tool:e,error:t instanceof Error?t.message:String(t)}),c._meta={proofError:"Proof generation failed — response is unproven"}}return c}},wrapWithDelegation:function(e,i,s){const a=et(),c=u?.fetchProvider??("function"==typeof globalThis.fetch?new sr:void 0),l=c?_t(c):void 0,g=new L({didResolver:{async resolve(e){const t=u?.didResolver;if(t){const r=await t.resolve(e);if(r)return r}return e.startsWith("did:key:")?a.resolve(e):e.startsWith("did:web:")?l?.resolve(e)??null:null}},signatureVerifier:async(e,r)=>{const n=e.proof;if(!n)return{valid:!1,reason:"Missing proof"};const i=n.proofValue;if(!i)return{valid:!1,reason:"Missing proofValue in proof"};const s=e,a={};for(const[e,t]of Object.entries(s))"proof"!==e&&(a[e]=t);const c=P(a),u=(new TextEncoder).encode(c),l=o(i),h=r;if(!h.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const f=d(o(h.x)),p=await t.verify(u,l,f);return{valid:p,reason:p?void 0:"Signature verification failed"}},statusListResolver:u?.statusListResolver}),y=(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:Ar(t)})}],isError:!0});return async(o,a)=>{const c=o._kyaos_delegation;if(null==c){const r=await t.randomBytes(16),n=Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""),s=[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join("-"),c=Math.floor(Date.now()/1e3)+300,d=I({message:`Tool "${e}" requires delegation with scope: ${i.scopeId}`,authorizationUrl:i.consentUrl,resumeToken:s,expiresAt:c,scopes:[i.scopeId]}),u=[{type:"text",text:JSON.stringify(d)}];let l=u;if(i.formatChallenge)try{l=i.formatChallenge(d)}catch(t){Fe.error("[kya-os] formatChallenge threw; using the default challenge",{tool:e,error:t instanceof Error?t.message:String(t)}),l=u}return S({content:l},e,o,a,d.message,"needs_authorization",void 0,l)}let d,l=!1;if("string"==typeof c){const t=O(c);if(!t||!t.payload.vc)return S(y(n.delegation_invalid,"Invalid VC-JWT format"),e,o,a,"Invalid VC-JWT format");d=t.payload.vc,d.proof||(d={...d,proof:{type:"JwtProof2020",jwt:c}}),l=!0}else d=c;const m=await(async()=>{try{return await(t=d,n={skipSignature:l},async function(e,t,r){const n=e?.credentialSubject?.delegation;if(!n||"object"!=typeof n||!n.constraints||"object"!=typeof n.constraints)return{valid:!1,reason:"Malformed delegation credential: missing credentialSubject.delegation or its constraints"};const i=p(e);let s=[e];if(i.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but no resolveDelegationChain handler is configured`};let r;try{r=await t.resolveDelegationChain(e)}catch(e){return{valid:!1,reason:`Failed to resolve delegation chain: ${e instanceof Error?e.message:"Unknown error"}`}}if(0===r.length)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but the resolved chain is empty`};const n=r.findIndex(e=>e.credentialSubject.delegation.id===i.id);if(-1!==n&&n!==r.length-1)return{valid:!1,reason:`Resolved delegation chain for ${i.id} must end with the leaf credential`};s=-1===n?[...r,e]:r}const o=new Set;let a,c;for(const e of s){const n=p(e);if(o.has(n.id))return{valid:!1,reason:`Delegation chain contains a circular reference at ${n.id}`};if(o.add(n.id),e.credentialStatus&&!t.statusListConfigured)return{valid:!1,reason:`Delegation ${n.id} has credentialStatus but no statusListResolver is configured`};const i=await t.verifier.verifyDelegationCredential(e,{...r?.skipSignature?{skipSignature:!0}:{}});if(!i.valid)return{valid:!1,reason:`Delegation ${n.id} invalid: ${i.reason}`};if(!F(n,t.serverDid))return{valid:!1,reason:`Delegation ${n.id} audience does not include server DID ${t.serverDid}`};if(n.parentId&&!n.constraints.audience)return{valid:!1,reason:`Delegation ${n.id} is a re-delegation (parentId: ${n.parentId}) but has no audience constraint. Re-delegations MUST include an audience constraint (KYA-OS §11.6)`};if(!a||!c){if(n.parentId)return{valid:!1,reason:`Resolved delegation chain is incomplete: root delegation ${n.id} still references parent ${n.parentId}`};a=n,c=e;continue}if(n.parentId!==a.id)return{valid:!1,reason:`Delegation ${n.id} references parent ${n.parentId} but expected ${a.id}`};if(n.issuerDid!==a.subjectDid)return{valid:!1,reason:`Delegation ${n.id} issued by ${n.issuerDid} but parent subject is ${a.subjectDid}`};const s=mr(c,e);if(!s.valid)return s;a=n,c=e}const d=p(s[s.length-1]);if(d.id!==i.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${i.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(i.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${i.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${i.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(t,{serverDid:r.did,verifier:g,resolveDelegationChain:u?.resolveDelegationChain,statusListConfigured:!!u?.statusListResolver,revocationChecker:u?.revocationChecker},n))}catch(t){return Fe.error("[kya-os] Unexpected error verifying delegation",{tool:e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),{valid:!1,reason:"Delegation credential could not be verified"}}var t,n})();if(!m.valid){const t=m.reason??"Unknown delegation validation error";return Fe.warn(`[kya-os] Delegation verification failed for "${e}": ${Ar(t)}`),S(y(n.delegation_invalid,t),e,o,a,t)}if("off"!==h&&f){const t=d.credentialSubject?.id;if(t&&mt(t)){const i=o._kyaos_proof;if(void 0===i){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(Fe.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===h)return S(y(n.holder_binding_failed,t),e,o,a,t)}else{let s=i;if("string"==typeof i)try{s=JSON.parse(i)}catch{s={}}const c=await vt({proof:s,subjectDid:t,request:pt(e,o),expectedAudience:r.did,proofVerifier:f});if("bound"!==c.status){const t=c.reason??"Holder-of-key proof did not bind the delegation subject";if(Fe.warn(`[kya-os] Holder binding ${c.status} for "${e}": ${Ar(t)}`),"enforce"===h)return S(y(n.holder_binding_failed,t),e,o,a,t)}}}else t&&Fe.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const v=gr(i.scopeId,d);if(v.usedNonExactMatcher&&Fe.warn(`[kya-os] Scope "${i.scopeId}" for "${e}" granted via a non-exact (prefix/regex) matcher. Verify this is intended — non-exact matchers widen authority.`),!v.satisfied){const t=`Required scope "${i.scopeId}" not in delegation scopes`;return Fe.warn(`[kya-os] Delegation missing required scope "${i.scopeId}" for "${e}"`),S(y(n.insufficient_scope,t),e,o,a,t)}const w={};for(const[e,t]of Object.entries(o))ft(e)||(w[e]=t);return Fe.debug(`[kya-os] Delegation verified for "${e}", scope "${i.scopeId}"`),s(w,a,{scopeId:i.scopeId})}},withPolicyGate:function(e,t,r={}){const i=r.engine??D,s=r.classifier??b,o=r.approvalsArgKey??"_kyaos_approvals",c=r.isValidApprovalSignature??(async()=>!1);return async(d,u)=>{const l={};for(const[e,t]of Object.entries(d))ft(e)||e===o||(l[e]=t);const h=r.resolveNamespace?.(d)??e,f=s.classify({toolName:e,namespace:h}),p=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,r=t.credentialSubject,n=r?.delegation?.subjectDid??r?.id??"unknown",i=r?.delegation?.controller;let s=[];try{s=yr(t)}catch{s=[]}return{agentDid:n,...i?{responsibleParty:i}:{},delegatedScopes:s}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(d._kyaos_delegation),g=Er({principal:{agentDid:p.agentDid,...p.responsibleParty?{responsibleParty:p.responsibleParty}:{}},action:{toolName:e},resource:{namespace:h},delegatedScopes:p.delegatedScopes,scopeMatched:r.scopeMatched??!1,risk:f}),y=await i.evaluate(g);if("allow"===y.decision)return t(l,u);if("deny"===y.decision)return S({content:[{type:"text",text:JSON.stringify({error:n.policy_denied,reason:Ar(y.reason)})}],isError:!0},e,d,u,y.reason,"denied",l);const m=await a.hashRequest({method:e,params:l}),v=Array.isArray(d[o])?d[o]:[];if((await kr(v,m,y.quorum,c)).satisfied)return t(l,u);const w=E({message:`Tool "${e}" requires ${y.quorum.n}-of-N approval before it may proceed (${Ar(y.reason)}).`,resumeToken:`step_up:${m}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:m,quorum:y.quorum});return S({content:[{type:"text",text:JSON.stringify(w)}],isError:!0},e,d,u,y.reason,"step_up_required",l)}}}}var Tr=r(11569);async function Pr(e){const t=await e.generateKeyPair(),r=Be(t.publicKey);return{did:r,kid:`${r}#${Je(r)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function $r(e,t){const r=Cr({identity:t.identity??await Pr(t.crypto),session:t.session,delegation:t.delegation,autoSession:t.autoSession??!0},t.crypto);if("tool"===(t.handshakeExposure??"tool")&&e.registerTool("_kyaos",{description:"KYA-OS protocol — identity verification, session handshake, and server metadata",annotations:{title:"KYA-OS Protocol",readOnlyHint:!0},inputSchema:{action:Tr.z.enum(_r).describe("Protocol operation to perform"),nonce:Tr.z.string().optional().describe("Client-generated unique nonce (handshake)"),audience:Tr.z.string().optional().describe("Intended audience (handshake)"),timestamp:Tr.z.number().optional().describe("Unix epoch seconds (handshake)"),agentDid:Tr.z.string().optional().describe("Client agent DID (handshake, optional)")}},async e=>{const t=await r.handleKyaOs(e);return{...t,content:t.content.map(e=>({...e,type:"text"}))}}),!1!==t.proofAllTools){const n=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],i=e.connect.bind(e);e.connect=e=>i(function(e,t,r=["_kyaos","_kyaos_handshake"]){const n=new Map,i={start:()=>e.start(),close:()=>e.close(),set onmessage(t){e.onmessage=t},get onmessage(){return e.onmessage},set onclose(t){e.onclose=t},get onclose(){return e.onclose},set onerror(t){e.onerror=t},get onerror(){return e.onerror},async send(r){const i=r.id,s=void 0!==i?n.get(i):void 0;if(s){n.delete(i);try{const e=r.result;if(e&&!e.isError){const n=async()=>e,i=t.wrapWithProof(s.toolName,n),o=await i(s.args);void 0!==o._meta&&(r={...r,result:o})}}catch(e){Fe.error("[kya-os-transport] Proof injection failed",{tool:s.toolName,error:e instanceof Error?e.message:String(e)});const t=r.result;t&&(t._meta={proofError:"Proof generation failed — response is unproven"},r={...r,result:t})}}return e.send(r)}},s=e.start.bind(e);return i.start=async()=>{await s();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,i=t?.name;i&&!r.includes(i)&&n.set(e.id,{toolName:i,args:t?.arguments??{}})}t?.(e)}},i}(e,r,n))}return r}}};
|
package/dist/95.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=95,exports.ids=[95],exports.modules={32410:(e,t,n)=>{n.d(t,{Y:()=>o});var r=n(13770);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)}},51095:(e,t,n)=>{n.d(t,{fromIni:()=>k});var r=n(32410),o=n(98229),i=n(43281),s=n(53347),a=n(53433);const c=e=>(0,s.g)(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p"),l=e=>!e.role_arn&&!!e.credential_source;var g=n(81781),d=n(35789),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 i.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(452),n.e(283)]).then(n.bind(n,93283)),{logger:o,userAgentAppId:s}=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:s,...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:s}=t.tokenOutput?.accessToken??{},{refreshToken:a,expiresIn:g}=t.tokenOutput??{};if(!(n&&o&&s&&a))throw new i.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:s,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 i.C(t,{logger:this.logger,tryNextLink:!1})}throw new i.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 i.C(`Token validation failed, missing fields: ${r.join(", ")}`,{logger:this.logger,tryNextLink:!1});return n}catch(t){throw new i.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 i=e.subarray(t,t+o);r=0===r[0]?r.subarray(1):r,i=0===i[0]?i.subarray(1):i;const s=Buffer.concat([Buffer.alloc(32-r.length),r]),a=Buffer.concat([Buffer.alloc(32-i.length),i]);return Buffer.concat([s,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 i=-1;for(let e=0;e<o.length;e++)if(4===o[e]){i=e;break}const s=o.slice(i+1,i+33),a=o.slice(i+33,i+65),c={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:s.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 i.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,s.g)(n,"CREDENTIALS_PROFILE","n")},C=async(e,t,g,d,f={},u=!1)=>{const p=t[e];if(Object.keys(f).length>0&&y(p))return w(p,g);if(u||((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})))(p,{profile:e,logger:g.logger}))return(async(e,t,r,g,d={},f)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");const u=t[e],{source_profile:p,region:h}=u;if(!r.roleAssumer){const{getDefaultRoleAssumer:e}=await n.e(225).then(n.bind(n,3606));r.roleAssumer=e({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...g,...r?.parentClientConfig,region:h??r?.parentClientConfig?.region??g?.region}},r.clientPlugins)}if(p&&p in d)throw new i.C(`Detected a cycle attempting to resolve credentials for profile ${(0,o.Bz)(r)}. Profiles visited: `+Object.keys(d).join(", "),{logger:r.logger});r.logger?.debug("@aws-sdk/credential-provider-ini - finding credential resolver using "+(p?`source_profile=[${p}]`:`profile=[${e}]`));const _=p?f(p,t,r,g,{...d,[p]:!0},l(t[p]??{})):(await((e,t,r)=>{const o={EcsContainer:async e=>{const{fromHttp:t}=await n.e(361).then(n.bind(n,2361)),{fromContainerMetadata:o}=await n.e(866).then(n.bind(n,8866));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(866).then(n.bind(n,8866));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(622).then(n.bind(n,55622));return async()=>t(e)().then(c)}};if(e in o)return o[e];throw new i.C(`Unsupported credential source in profile ${t}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})})(u.credential_source,e,r.logger)(r))();if(l(u))return _.then(e=>(0,s.g)(e,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));{const t={RoleArn:u.role_arn,RoleSessionName:u.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:u.external_id,DurationSeconds:parseInt(u.duration_seconds||"3600",10)},{mfa_serial:n}=u;if(n){if(!r.mfaCodeProvider)throw new i.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 _;return r.roleAssumer(o,t).then(e=>(0,s.g)(e,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}})(e,t,g,d,f,C);if(y(p))return w(p,g);if(h=p,Boolean(h)&&"object"==typeof h&&"string"==typeof h.web_identity_token_file&&"string"==typeof h.role_arn&&["undefined","string"].indexOf(typeof h.role_session_name)>-1)return(async(e,t,r)=>n.e(354).then(n.bind(n,83354)).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})({callerClientConfig:r}).then(e=>(0,s.g)(e,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q"))))(p,g,d);var h;if((e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.credential_process)(p))return(async(e,t)=>n.e(861).then(n.bind(n,46242)).then(({fromProcess:n})=>n({...e,profile:t})().then(e=>(0,s.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))(p))return await(async(e,t,r={},o)=>{const{fromSSO:i}=await n.e(533).then(n.bind(n,32914));return i({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then(e=>t.sso_session?(0,s.g)(e,"CREDENTIALS_PROFILE_SSO","r"):(0,s.g)(e,"CREDENTIALS_PROFILE_SSO_LEGACY","t"))})(e,p,g,d);if((e=>Boolean(e&&e.login_session))(p))return(async(e,t,n)=>{const a=await(c={...t,profile:e},async({callerClientConfig:e}={})=>{c?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");const t=await(0,r.Y)(c||{}),n=(0,o.Bz)({profile:c?.profile??e?.profile}),a=t[n];if(!a?.login_session)throw new i.C(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:c?.logger});const l=new _(a,c,e),g=await l.loadCredentials();return(0,s.g)(g,"CREDENTIALS_LOGIN","AD")})({callerClientConfig:n});var c;return(0,s.g)(a,"CREDENTIALS_PROFILE_LOGIN","AC")})(e,g,d);throw new i.C(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:g.logger})},k=(e={})=>async({callerClientConfig:t}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");const n=await(0,r.Y)(e);return C((0,o.Bz)({profile:e.profile??t?.profile}),n,e,t)}}};
|
|
1
|
+
"use strict";exports.id=95,exports.ids=[95],exports.modules={32410:(e,t,n)=>{n.d(t,{Y:()=>o});var r=n(13770);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)}},51095:(e,t,n)=>{n.d(t,{fromIni:()=>k});var r=n(32410),o=n(98229),i=n(43281),s=n(53347),a=n(53433);const c=e=>(0,s.g)(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p"),l=e=>!e.role_arn&&!!e.credential_source;var g=n(81781),d=n(35789),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 i.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(452),n.e(283)]).then(n.bind(n,93283)),{logger:o,userAgentAppId:s}=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:s,...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:s}=t.tokenOutput?.accessToken??{},{refreshToken:a,expiresIn:g}=t.tokenOutput??{};if(!(n&&o&&s&&a))throw new i.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:s,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 i.C(t,{logger:this.logger,tryNextLink:!1})}throw new i.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 i.C(`Token validation failed, missing fields: ${r.join(", ")}`,{logger:this.logger,tryNextLink:!1});return n}catch(t){throw new i.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 i=e.subarray(t,t+o);r=0===r[0]?r.subarray(1):r,i=0===i[0]?i.subarray(1):i;const s=Buffer.concat([Buffer.alloc(32-r.length),r]),a=Buffer.concat([Buffer.alloc(32-i.length),i]);return Buffer.concat([s,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 i=-1;for(let e=0;e<o.length;e++)if(4===o[e]){i=e;break}const s=o.slice(i+1,i+33),a=o.slice(i+33,i+65),c={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:s.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 i.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,s.g)(n,"CREDENTIALS_PROFILE","n")},C=async(e,t,g,d,f={},u=!1)=>{const p=t[e];if(Object.keys(f).length>0&&y(p))return w(p,g);if(u||((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})))(p,{profile:e,logger:g.logger}))return(async(e,t,r,g,d={},f)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");const u=t[e],{source_profile:p,region:h}=u;if(!r.roleAssumer){const{getDefaultRoleAssumer:e}=await n.e(317).then(n.bind(n,79317));r.roleAssumer=e({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...g,...r?.parentClientConfig,region:h??r?.parentClientConfig?.region??g?.region}},r.clientPlugins)}if(p&&p in d)throw new i.C(`Detected a cycle attempting to resolve credentials for profile ${(0,o.Bz)(r)}. Profiles visited: `+Object.keys(d).join(", "),{logger:r.logger});r.logger?.debug("@aws-sdk/credential-provider-ini - finding credential resolver using "+(p?`source_profile=[${p}]`:`profile=[${e}]`));const _=p?f(p,t,r,g,{...d,[p]:!0},l(t[p]??{})):(await((e,t,r)=>{const o={EcsContainer:async e=>{const{fromHttp:t}=await n.e(361).then(n.bind(n,2361)),{fromContainerMetadata:o}=await n.e(866).then(n.bind(n,8866));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(866).then(n.bind(n,8866));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(622).then(n.bind(n,55622));return async()=>t(e)().then(c)}};if(e in o)return o[e];throw new i.C(`Unsupported credential source in profile ${t}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})})(u.credential_source,e,r.logger)(r))();if(l(u))return _.then(e=>(0,s.g)(e,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));{const t={RoleArn:u.role_arn,RoleSessionName:u.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:u.external_id,DurationSeconds:parseInt(u.duration_seconds||"3600",10)},{mfa_serial:n}=u;if(n){if(!r.mfaCodeProvider)throw new i.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 _;return r.roleAssumer(o,t).then(e=>(0,s.g)(e,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}})(e,t,g,d,f,C);if(y(p))return w(p,g);if(h=p,Boolean(h)&&"object"==typeof h&&"string"==typeof h.web_identity_token_file&&"string"==typeof h.role_arn&&["undefined","string"].indexOf(typeof h.role_session_name)>-1)return(async(e,t,r)=>n.e(354).then(n.bind(n,83354)).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})({callerClientConfig:r}).then(e=>(0,s.g)(e,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q"))))(p,g,d);var h;if((e=>Boolean(e)&&"object"==typeof e&&"string"==typeof e.credential_process)(p))return(async(e,t)=>n.e(861).then(n.bind(n,46242)).then(({fromProcess:n})=>n({...e,profile:t})().then(e=>(0,s.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))(p))return await(async(e,t,r={},o)=>{const{fromSSO:i}=await n.e(533).then(n.bind(n,32914));return i({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then(e=>t.sso_session?(0,s.g)(e,"CREDENTIALS_PROFILE_SSO","r"):(0,s.g)(e,"CREDENTIALS_PROFILE_SSO_LEGACY","t"))})(e,p,g,d);if((e=>Boolean(e&&e.login_session))(p))return(async(e,t,n)=>{const a=await(c={...t,profile:e},async({callerClientConfig:e}={})=>{c?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");const t=await(0,r.Y)(c||{}),n=(0,o.Bz)({profile:c?.profile??e?.profile}),a=t[n];if(!a?.login_session)throw new i.C(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:c?.logger});const l=new _(a,c,e),g=await l.loadCredentials();return(0,s.g)(g,"CREDENTIALS_LOGIN","AD")})({callerClientConfig:n});var c;return(0,s.g)(a,"CREDENTIALS_PROFILE_LOGIN","AC")})(e,g,d);throw new i.C(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:g.logger})},k=(e={})=>async({callerClientConfig:t}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");const n=await(0,r.Y)(e);return C((0,o.Bz)({profile:e.profile??t?.profile}),n,e,t)}}};
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
10
|
exports.enableMCPIdentityCLI = enableMCPIdentityCLI;
|
|
11
11
|
const identity_1 = require("../runtime/identity");
|
|
12
|
-
const did_helpers_1 = require("@kya-os/mcp-i-
|
|
12
|
+
const did_helpers_1 = require("@kya-os/mcp-i-runtime/utils/did-helpers");
|
|
13
13
|
const kta_registration_1 = require("./kta-registration");
|
|
14
14
|
/**
|
|
15
15
|
* Enable MCP Identity for CLI
|