@astrasyncai/adapter-lambda 2.10.0 → 2.12.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/lambda/index.js +1 -1
- package/package.json +2 -2
package/dist/lambda/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _e=Object.create;var b=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var Me=(e,t)=>{for(var r in t)b(e,r,{get:t[r],enumerable:!0})},$=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Pe(t))!ke.call(e,a)&&a!==r&&b(e,a,{get:()=>t[a],enumerable:!(n=Ue(t,a))||n.enumerable});return e};var Oe=(e,t,r)=>(r=e!=null?_e(xe(e)):{},$(t||!e||!e.__esModule?b(r,"default",{value:e,enumerable:!0}):r,e)),De=e=>$(b({},"__esModule",{value:!0}),e);var Ar={};Me(Ar,{handler:()=>vr});module.exports=De(Ar);var D="5.12.0",I=`astrasync-sdk/${D}`;function Ne(e){if(!e)return{"user-agent":I};if(e instanceof Headers){let r=new Headers(e);return r.has("user-agent")||r.set("user-agent",I),r}return Array.isArray(e)?e.some(([n])=>n.toLowerCase()==="user-agent")?e:[...e,["user-agent",I]]:Object.keys(e).some(r=>r.toLowerCase()==="user-agent")?e:{"user-agent":I,...e}}var C=(e,t)=>fetch(e,{...t,headers:Ne(t?.headers)}),Sr=Object.freeze({version:1,mode:"observe",depth:"classify",pathRules:[],sampling:Object.freeze({anonymousBeaconRate:1}),failurePosture:"open"}),br=60*1e3,Ir=1440*60*1e3;function Fe(e,t){for(let r of e)if(Be(r.pattern).test(t))return r}function Be(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`,"i")}var Le=1,$e=new Set(["cookie","set-cookie","x-csrf-token","proxy-authorization","x-astrasync-signature","x-astrasync-secret","x-hub-signature","x-hub-signature-256","x-astra-verified-hop"]),je=["x-astrasync-","kya-","kya_"],He=new Set(["authorization","x-api-key","x-goog-api-key","api-key"]);function Ke(e){return e==="signature"||e.endsWith("-signature")||e.endsWith("-signature-256")}var Ve=new Set(["openai-organization","openai-project","openai-version","openai-processing-ms","anthropic-version","anthropic-beta","x-goog-user-project","x-goog-api-client","user-agent","x-agent-card-url","x-agent-provider"]),Ge=["x-goog-","x-stainless-","x-anthropic-","x-openai-","sec-ch-"],ze=["sk-ant-api03","sk-ant-api","sk-ant","sk-proj","sk-svcacct","sk-or-v1","sk-or","sk-lf","sk-","gsk_","aiza","ya29","ghp_","gho_","github_pat_","xai-","pplx-","r8_","hf_","astra-","astrae-"],Xe=64,j=1024,qe=16*1024,Ye=64,We=/^[a-z0-9][a-z0-9 ._/-]{0,63}$/;function te(e){let t=e?.trim().slice(0,Ye).toLowerCase();return t&&We.test(t)?t:void 0}function k(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n<128?t+=1:n<2048?t+=2:n>=55296&&n<=56319?(t+=4,r++):t+=3}return t}function Je(e){if(!e)return;let t=e.trim(),r=t.indexOf(" ");if(r>0){let a=t.slice(0,r).toLowerCase();(a==="bearer"||a==="basic"||a==="token")&&(t=t.slice(r+1).trim())}let n=t.toLowerCase();for(let a of ze)if(n.startsWith(a))return a}function Qe(e){return!!($e.has(e)||je.some(t=>e.startsWith(t))||Ke(e))}function Ze(e){return Ve.has(e)?!0:Ge.some(t=>e.startsWith(t))}function re(e){let t={},r={},n,a,i=0,s=0;if(!e)return{headers:t};for(let c of Object.keys(e)){if(s>=Xe)break;let u=c.toLowerCase(),y=e[c];if(y===void 0)continue;let h=Array.isArray(y)?y.join(", "):String(y);if(He.has(u)){let g=Je(h);g&&!n&&(n=g);continue}if(u==="cookie"&&(a=h.split(";").filter(g=>g.trim().length>0).length),Qe(u))continue;let l=h;k(l)>j&&(l=l.slice(0,j));let d=k(u)+k(l);i+d>qe||(i+=d,s++,t[u]=l,Ze(u)&&(r[u]=l))}let o={headers:t};return n&&(o.apiKeyFormat=n),Object.keys(r).length>0&&(o.platformHeaders=r),a!==void 0&&(o.cookieCount=a),o}var et=[{vendor:"claude",displayName:"Anthropic Claude",uaPatterns:[/claude/i,/anthropic/i],agentCardPatterns:[/anthropic\.com/i,/claude\.ai/i],apiKeyFormatPatterns:[/^sk-ant/i],headerPatterns:[/^anthropic-version/i,/^anthropic-beta/i,/^x-anthropic-/i]},{vendor:"chatgpt",displayName:"OpenAI ChatGPT",uaPatterns:[/chatgpt/i,/openai/i,/gpt-?\d/i,/\bGPTBot\b/i,/\bOAI-SearchBot\b/i],agentCardPatterns:[/openai\.com/i,/chatgpt\.com/i],apiKeyFormatPatterns:[/^sk-proj/i,/^sk-svcacct/i],headerPatterns:[/^openai-organization/i,/^openai-project/i,/^openai-version/i]},{vendor:"gemini",displayName:"Google Gemini",uaPatterns:[/gemini/i,/google-gemini/i,/bard/i,/\bGoogle-Extended\b/i,/\bGoogleOther\b/i,/\bGoogle-CloudVertexBot\b/i],agentCardPatterns:[/gemini\.google\.com/i,/ai\.google\.dev/i],apiKeyFormatPatterns:[/^aiza/i],headerPatterns:[/^x-goog-user-project/i,/^x-goog-api-client/i]},{vendor:"cursor",displayName:"Cursor",uaPatterns:[/cursor/i],agentCardPatterns:[/cursor\.sh/i,/cursor\.com/i]},{vendor:"goose",displayName:"Block Goose",uaPatterns:[/goose/i,/block-goose/i],agentCardPatterns:[/block\.xyz\/goose/i,/goose\.tools/i]},{vendor:"perplexity",displayName:"Perplexity",uaPatterns:[/perplexity/i],agentCardPatterns:[/perplexity\.ai/i],apiKeyFormatPatterns:[/^pplx-/i]},{vendor:"chatgpt-atlas",displayName:"ChatGPT Atlas browser",uaPatterns:[/\batlas\/\d/i],headerPatterns:[/^sec-ch-ua: .*atlas/i]},{vendor:"perplexity-comet",displayName:"Perplexity Comet browser",uaPatterns:[/\bcomet\/\d/i],headerPatterns:[/^sec-ch-ua: .*comet/i]},{vendor:"astrasync-bridge",displayName:"AstraSync MCP bridge (buyer-agent catalog fetch)",uaPatterns:[/^astrasync-bridge\//i]},{vendor:"astrasync-sdk",displayName:"AstraSync SDK",uaPatterns:[/^astrasync-sdk\//i]}];function tt(e,t){let r=t.userAgent??"",n=t.agentCardUrl??"",a=t.apiKeyFormat??"",i=t.ja4??"",s=t.asn??"",o=[];if(t.platformHeaders)for(let[c,u]of Object.entries(t.platformHeaders))o.push(c,`${c}: ${u}`);for(let c of e){let u=c.uaPatterns?.some(p=>p.test(r)),y=c.agentCardPatterns?.some(p=>p.test(n)),h=a.length>0&&c.apiKeyFormatPatterns?.some(p=>p.test(a)),l=o.length>0&&c.headerPatterns?.some(p=>o.some(m=>p.test(m))),d=i.length>0&&c.ja4Patterns?.some(p=>p.test(i)),g=s.length>0&&c.asnList?.includes(s);if(u||y||h||l||d||g){let p=r.split(/[\s/]/)[0]?.toLowerCase()??"",m=(()=>{try{return n?new URL(n).host:""}catch{return""}})(),P=p||m||a||i||s&&`asn${s}`||"unknown";return{vendor:c.vendor,fingerprintKey:`${c.vendor}:${P}`,displayName:c.displayName}}}}function H(e){return tt(et,e)}function rt(e){return e>=80?"PLATINUM":e>=60?"GOLD":e>=40?"SILVER":"BRONZE"}var Rr=3600*1e3,nt=new Map;function at(e){return nt.get(e)?.data}var ne=new Set(["identity.invalid_agent_id","identity.unknown_agent","agent.lookup"]),ae="Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.",st={apiBaseUrl:"https://astrasync.ai/api",debug:!1},se=!1,K=!1;async function V(e,t,r,n){se=!0;try{let a=`${e}/agents/verify-access`,s=(await C(a,{method:"HEAD"})).headers.get("content-type")??"";if(s.startsWith("text/html")){let o=`[VerificationGateway] apiBaseUrl '${e}' returned HTML (content-type: ${s}). This usually means apiBaseUrl is pointing at a marketing site instead of the API. Expected: 'https://astrasync.ai/api' (prod) or 'https://staging.astrasync.ai/api' (staging).`;if(r)throw new Error(`${o} (strictInit=true)`);console.warn(`${o} Set disableInitChecks: true on GatewayConfig to silence.`)}else t&&console.log(`[VerificationGateway] init check passed for ${e} (content-type: ${s})`);if(n){let o=await C(`${e}/agents/verify-access/self-check`,{headers:{Authorization:`Bearer ${n}`}});if(o.status===401){let c=await o.json().catch(()=>({})),u=`[VerificationGateway] the configured AstraSync API key was REJECTED at startup (${c.code??"api_key_invalid"}: ${c.message??"invalid key"}). Every inbound agent will be turned away until the key is rotated`+(c.remediation?.manageUrl?` at ${c.remediation.manageUrl}`:"")+".";if(r)throw new Error(`${u} (strictInit=true)`);console.error(u)}else if(o.ok){let c=await o.json().catch(()=>({}));typeof c.daysToExpiry=="number"&&c.daysToExpiry<=7?console.warn(`[VerificationGateway] the configured AstraSync API key expires in ${c.daysToExpiry} day(s) \u2014 rotate it at Settings \u2192 Developer Tools before integrations start failing.`):t&&console.log("[VerificationGateway] API key self-check passed")}}}catch(a){if(r)throw a;t&&console.log(`[VerificationGateway] init check failed (non-blocking): ${String(a)}`)}}var O=new Map;function oe(e,t){let r=e.credentials;return[r.astraId||"",r.apiKey||"",r.jwt||"",e.purpose||"",e.action||"",e.resourceType||"",e.resource||"",e.jurisdiction||"",e.transactionValue??"",e.currency||"",t||"",e.counterpartyUrl||"",e.counterpartyType||"",e.isSubAgentRequest?"1":"0",e.parentAgentId||"",e.subAgentDepth??"",e.durationRequired??"",e.invocationProtocol||"",e.enableRuntimeChallenge?"1":"0",e.callerMetadata?.sourceIp||"",e.callerMetadata?.userAgent||"",e.callerMetadata?.forwardedFor||"",e.callerMetadata?.agentCardUrl||"",e.commercePhase||"",e.checkoutSessionId||""].join("|")}function ot(e,t){let r=oe(e,t),n=O.get(r);return n&&n.expiresAt>Date.now()?n.result:(n&&O.delete(r),null)}var it=60;function ct(e,t,r,n){let a=r&&r>0?r:it,i=oe(e,n);O.set(i,{result:t,expiresAt:Date.now()+a*1e3})}function ie(e,t){let r={},n=/^ASTRAE?-[A-Za-z0-9_-]{1,64}$/,a=e["x-astra-id"]||e["X-Astra-Id"]||e["X-ASTRA-ID"]||e["x-astra-agentid"]||e["X-Astra-AgentId"]||e["x-astra-agent-id"]||e["X-Astra-Agent-Id"]||e["X-ASTRA-AGENT-ID"];if(a){let o=Array.isArray(a)?a[0]:typeof a=="string"?a:void 0;typeof o=="string"&&n.test(o)&&(r.astraId=o)}let i=e["x-api-key"]||e["X-Api-Key"]||e["X-API-KEY"];i&&(r.apiKey=Array.isArray(i)?i[0]:i);let s=e.authorization||e.Authorization;if(s){let o=Array.isArray(s)?s[0]:s;typeof o=="string"&&(r.authorizationHeader=o,o.startsWith("Bearer ")&&(r.jwt=o.slice(7)))}return t&&(t.astraId&&!r.astraId&&(r.astraId=t.astraId),t.apiKey&&!r.apiKey&&(r.apiKey=t.apiKey)),r}function E(e){if(e?.mcpEndpoint)return{endpoint:e.mcpEndpoint,discoveryUrl:e.mcpDiscoveryUrl,message:"If you are operating inside an MCP-capable host (Claude, ChatGPT, Cursor, or any MCP client), add the AstraSync MCP connector instead of integrating these URLs by hand: registration through the connector is KEYLESS and HUMAN-APPROVED \u2014 your human approves in an in-chat card, and you never see, hold, or transmit an API key, password, or private key."}}function dt(e,t,r={}){let n=r.source??"no_credentials",a=n==="api_error",i=n==="merchant_misconfig",s=r.urls,o=i?{message:"This site's AstraSync integration is misconfigured (its API key was revoked, expired, or rotated). Your identity and the AstraSync platform are fine \u2014 contact the site operator. Retrying will not help.",registrationUrl:s?.registrationUrl??"",documentationUrl:r.remediation?.docsUrl??s?.documentationUrl??"",steps:["Report the failure to the site operator \u2014 their AstraSync API key needs rotating","Do not retry: the failure is deterministic until the operator updates their key"]}:a?{message:"Verification is temporarily unavailable. Retry with exponential backoff; if the issue persists, contact support with the correlationId.",registrationUrl:s?.registrationUrl??"",documentationUrl:s?.documentationUrl??"",steps:["Retry the request with exponential backoff","If failures persist, share the correlationId with support"]}:{message:"This service verifies AI agents before granting access. Please register your agent with AstraSync.",registrationUrl:s?.registrationUrl??"",documentationUrl:s?.documentationUrl??"",steps:[...s?.mcpEndpoint?[`Fastest path (inside an MCP host): add the AstraSync MCP connector at ${s.mcpEndpoint} \u2014 keyless, human-approved registration`]:[],"Register for an AstraSync account","Create and register your agent","Add your ASTRA-ID to request headers","Retry your request"],...E(s)&&{mcp:E(s)}};return{identityVerified:!1,policyAllowed:!1,guidance:o,denialReasons:t?[t]:["No valid agent credentials provided"],failures:i?[{dimension:"verify_access.merchant_misconfigured",message:t??"The integration API key was rejected by AstraSync",guidance:o.message}]:a?[{dimension:"verify_access.api_error",message:t??"Verification temporarily unavailable",guidance:o.message}]:void 0,...i&&{misconfigured:!0},...a&&{retryable:!0},...r.httpStatus!==void 0&&{httpStatus:r.httpStatus},...r.retryAfterMs!==void 0&&{retryAfterMs:r.retryAfterMs},correlationId:r.correlationId,attemptId:r.attemptId,verifiedAt:new Date}}async function ut(e){try{let t=await e.json();return t&&typeof t=="object"?t:{}}catch{return{}}}function lt(e){let t=e?.find(r=>ne.has(r.dimension));if(t)return t.dimension==="agent.lookup"?`The presented agent identifier is not registered with AstraSync. ${ae}`:t.guidance?`${t.message} ${t.guidance}`:t.message}var pt=900*1e3;function ft(e){let t=e.headers?.get?.("retry-after");if(!t)return;let r=t.trim(),n;if(/^\d+(\.\d+)?$/.test(r))n=Number(r)*1e3;else{let a=Date.parse(r);if(Number.isNaN(a))return;n=a-Date.now()}return Math.min(pt,Math.max(0,Math.round(n)))}async function gt(e,t){let{credentials:r,...n}=t,a={...r.astraId&&{agentId:r.astraId},...n.purpose&&{purpose:n.purpose}};if(n.action&&(a.action=n.action),n.resourceType&&(a.resourceType=n.resourceType),n.resource&&(a.resource=n.resource),n.jurisdiction&&(a.jurisdiction=n.jurisdiction),n.transactionValue&&(a.transactionValue=n.transactionValue),n.currency&&(a.currency=n.currency),n.isSubAgentRequest&&(a.isSubAgentRequest=n.isSubAgentRequest),n.parentAgentId&&(a.parentAgentId=n.parentAgentId),n.subAgentDepth!==void 0&&(a.subAgentDepth=n.subAgentDepth),n.enableRuntimeChallenge&&(a.enableRuntimeChallenge=n.enableRuntimeChallenge),n.createSession&&(a.createSession=n.createSession),n.durationRequired&&(a.durationRequired=n.durationRequired),n.counterpartyType&&(a.counterpartyType=n.counterpartyType),n.counterpartyUrl&&(a.counterpartyUrl=n.counterpartyUrl),e.counterpartyId&&(a.counterpartyId=e.counterpartyId),n.runtimeChallengeOptions&&(a.runtimeChallengeOptions=n.runtimeChallengeOptions),n.invocationProtocol&&(a.invocationProtocol=n.invocationProtocol),n.commercePhase&&(a.commercePhase=n.commercePhase),n.checkoutSessionId&&(a.checkoutSessionId=n.checkoutSessionId),n.checkoutItems&&(a.checkoutItems=n.checkoutItems),n.buyerEmail&&(a.buyerEmail=n.buyerEmail),n.commerceArtifacts&&(a.commerceArtifacts=n.commerceArtifacts),n.attemptId&&(a.attemptId=n.attemptId),n.considerationSet&&(a.considerationSet=n.considerationSet),a.sdkVersion=D,n.callerMetadata||n.clientIp||n.userAgent){let s={...n.clientIp&&{sourceIp:n.clientIp},...n.userAgent&&{userAgent:n.userAgent},...n.callerMetadata};Object.keys(s).length>0&&(a.callerMetadata=s)}let i={"Content-Type":"application/json",...e.customHeaders};e.apiKey&&(i.Authorization=`Bearer ${e.apiKey}`,i["X-API-Key"]=e.apiKey);try{let s=await C(`${e.apiBaseUrl}/agents/verify-access`,{method:"POST",headers:i,body:JSON.stringify(a),signal:AbortSignal.timeout(e.verifyTimeoutMs??1e4)}),o=await ut(s),c=ft(s);if(s.status===410)return{success:!0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,access:{allowed:!1,reason:"endpoint_deactivated",failures:[{dimension:"endpoint.deactivated",message:typeof o?.message=="string"?o.message:"Endpoint has been deactivated",guidance:typeof o?.guidance=="string"?o.guidance:"Reactivate via POST /api/endpoints/{id}/reactivate, or update the URL on the calling agent."}]}};if(s.status===400&&o?.error==="INVALID_AGENT_ID"){let u=typeof o?.message=="string"?o.message:"Agent identifier must be a canonical ASTRA-* id.";return{success:!0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,access:{allowed:!1,reason:"invalid_agent_id",failures:[{dimension:"identity.invalid_agent_id",message:u,guidance:typeof o?.guidance=="string"?o.guidance:"Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval)."}]}}}return s.status===404&&r.astraId&&(o?.error==="AGENT_NOT_FOUND"||typeof o?.message=="string"&&/agent/i.test(o.message))?{success:!0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,access:{allowed:!1,reason:"unknown_agent",failures:[{dimension:"identity.unknown_agent",message:"The presented agent identifier is not registered with AstraSync.",guidance:ae}]}}:s.ok?o:s.status===401?{success:!1,error:o.message||o.error||"Integration API key rejected",misconfig:!0,misconfigCode:typeof o?.code=="string"?o.code:void 0,remediation:o?.remediation&&typeof o.remediation=="object"?o.remediation:void 0,correlationId:typeof o?.correlationId=="string"?o.correlationId:void 0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0}:{success:!1,error:typeof o?.message=="string"&&o.message||typeof o?.error=="string"&&o.error||`API returned ${s.status}`,correlationId:typeof o?.correlationId=="string"?o.correlationId:void 0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,httpStatus:s.status,...c!==void 0&&{retryAfterMs:c}}}catch(s){return{success:!1,error:`Failed to call verify-access API: ${s instanceof Error?s.message:"Unknown error"}`}}}async function G(e,t,r){let n={...st,...e},a=n.apiBaseUrl?at(n.apiBaseUrl):void 0;if(!se&&!n.disableInitChecks&&n.apiBaseUrl&&(n.strictInit?await V(n.apiBaseUrl,n.debug,!0,n.apiKey):V(n.apiBaseUrl,n.debug,!1,n.apiKey)),!K&&(e.minTrustScore!==void 0||e.minTrustScoreForFull!==void 0)&&(K=!0,console.warn("[VerificationGateway] minTrustScore / minTrustScoreForFull are deprecated in v2.3.0 and have no effect. Server is now the single source of truth for access decisions (verified ID + runtime challenge + PDLSS + trust score). To gate access to an endpoint, configure the endpoint's trust_score_requirement server-side.")),n.cacheTtl!==0&&!r?.bypassCache){let p=ot(t,n.counterpartyId);if(p){n.debug&&console.log("[VerificationGateway] Returning cached result");let m={...p};return t.attemptId?m.attemptId=t.attemptId:delete m.attemptId,m}}let i={...t};!i.counterpartyUrl&&n.counterpartyUrl&&(i.counterpartyUrl=n.counterpartyUrl),!i.counterpartyType&&n.counterpartyType&&(i.counterpartyType=n.counterpartyType),n.debug&&console.log("[VerificationGateway] Calling verify-access API");let s=await gt(n,i),o=s.denialReasons,c=Array.isArray(o)&&o.length>0?o:void 0;if(!s.success)return dt(n,s.error,{source:s.misconfig?"merchant_misconfig":"api_error",correlationId:s.correlationId,attemptId:s.attemptId,remediation:s.remediation,httpStatus:s.httpStatus,retryAfterMs:s.retryAfterMs,urls:a});if(!s.access?.allowed){let p=s.access?.failures;return{identityVerified:s.verificationContext?.idVerified===!0&&!p?.some(x=>ne.has(x.dimension)),policyAllowed:!1,denialReasons:c??(p&&p.length>0?p.map(x=>x.message):s.access?.reason?[s.access.reason]:["Access denied"]),failures:p,requiresStepUp:s.access?.requiresStepUp,requiresApproval:s.access?.requiresApproval,guidance:{message:lt(p)??(s.access?.reason||"Access denied by PDLSS policy"),registrationUrl:a?.registrationUrl??"",documentationUrl:a?.documentationUrl??"",...E(a)&&{mcp:E(a)}},verifiedAt:new Date,sessionId:s.sessionId,correlationId:s.correlationId,attemptId:s.attemptId,recommendation:s.recommendation,recommendationReasons:s.recommendationReasons,stepUpApproval:s.stepUpApproval,settlement:s.settlement,settlementOutcome:s.settlementOutcome,settlementToken:s.settlementToken,fulfilment:s.fulfilment}}let u=s.agent?{astraId:s.agent.astraId,name:s.agent.name,trustScore:s.agent.trustScore,trustLevel:rt(s.agent.trustScore),blockchainAnchored:s.agent.blockchainStatus==="anchored",status:s.agent.agentStatus}:void 0,y=s.developer?{astradId:s.developer.kyaOwnerId,name:s.developer.fullName,trustScore:s.developer.trustScore||0,verified:s.developer.identityVerified}:void 0,h=s.organization?{name:s.organization.name,verified:s.organization.verified,trustScore:s.organization.trustScore}:void 0,l=s.verificationContext,d={identityVerified:s.verificationContext?.idVerified===!0,policyAllowed:!0,agent:u,developer:y,organization:h,appliedPolicy:s.access?.appliedPolicy,verificationContext:l,requiresStepUp:s.access?.requiresStepUp,requiresApproval:s.access?.requiresApproval,verifiedAt:new Date,cacheTtl:n.cacheTtl,sessionId:s.sessionId,correlationId:s.correlationId,attemptId:s.attemptId,runtimeChallenge:s.runtimeChallenge,tokenGuidance:s.tokenGuidance,recommendation:s.recommendation,recommendationReasons:s.recommendationReasons,warningHeader:s.warningHeader,stepUpApproval:s.stepUpApproval,settlement:s.settlement,settlementOutcome:s.settlementOutcome,settlementToken:s.settlementToken,fulfilment:s.fulfilment};d.recommendation==="deny"?(d.policyAllowed=!1,d.denialReasons=c??d.recommendationReasons??["Access denied by AstraSync recommendation"],d.guidance=d.runtimeChallenge?{message:`Verification failed: ${d.runtimeChallenge.reason||"runtime challenge failed"}`,registrationUrl:a?.registrationUrl??"",documentationUrl:a?.documentationUrl??""}:{message:d.recommendationReasons?.[0]||"Access denied by AstraSync recommendation",registrationUrl:a?.registrationUrl??"",documentationUrl:a?.documentationUrl??""}):d.recommendation==="step_up_required"&&d.identityVerified&&(d.requiresStepUp=!0,d.denialReasons=c??d.recommendationReasons??["Step-up verification required"]);let g=d.requiresStepUp===!0||d.requiresApproval===!0||d.recommendation==="step_up_required";return n.cacheTtl!==0&&d.recommendation!=="deny"&&!g&&ct(t,d,n.cacheTtl,n.counterpartyId),d}function f(e,t){return e.headers[t.toLowerCase()]}function yt(e,t){let r=e.querystring?`?${e.querystring}`:"";return`https://${t}${e.uri}${r}`}var z=/^att_[0-9a-f]{32}$/;function ht(e){let t=f(e,"x-astra-attempt-id");if(t&&z.test(t))return t;if(e.querystring)try{let r=new URLSearchParams(e.querystring).get("astra_attempt");if(r&&z.test(r))return r}catch{}}function N(e,t){let{headers:r,apiKeyFormat:n,platformHeaders:a,cookieCount:i}=re(e.headers),s=e.connection??{},o=vt(e.querystring),c=St(e.querystring,t);return{headers:r,...n&&{apiKeyFormat:n},...a&&{platformHeaders:a},...Object.keys(s).length>0&&{connection:s},...i!==void 0&&{cookieCount:i},...o&&{queryKeys:o},...c&&{queryParams:c},schemaVersion:Le}}var mt=32,ce=64;function vt(e){if(!e)return;let t;try{t=new URLSearchParams(e)}catch{return}let r=[];for(let n of t.keys()){let a=n.toLowerCase().slice(0,ce);if(a&&!r.includes(a)&&(r.push(a),r.length>=mt))break}return r.length>0?r:void 0}var At=16,wt=256;function St(e,t){if(!e||!t||t.length===0)return;let r;try{r=new URLSearchParams(e)}catch{return}let n=s=>t.some(o=>o.endsWith("*")?s.startsWith(o.slice(0,-1)):s===o),a={},i=0;for(let[s,o]of r.entries()){let c=s.toLowerCase().slice(0,ce);if(!(!c||a[c]!==void 0||!n(c))&&(a[c]=o.slice(0,wt),++i>=At))break}return i>0?a:void 0}var bt=/^eyJ[\w-]+\.[\w-]*\.[\w-]+~/;function It(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=atob(r),a=new Uint8Array(n.length);for(let i=0;i<n.length;i++)a[i]=n.charCodeAt(i);return new TextDecoder().decode(a)}function Rt(e){try{let t=e.split(".")[0];return JSON.parse(It(t))}catch{return}}function Ct(e){if(e)try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:void 0}catch{return}}function Et(e,t){let r=yt(e,t),n=e.method,a=e.headers,i=Ct(e.bodyText),s=e.bodyTruncated?{bodyTruncated:!0}:{},o=f(e,"authorization"),c=o?.replace(/^Bearer\s+/i,""),y=[f(e,"x-payment-mandate")??f(e,"payment-mandate"),c].find(g=>g&&bt.test(g));if(y){let g=Rt(y)?.typ;return{protocol:"vi-sd-jwt",artifacts:{viSdJwt:y},evidence:{typ:g,...s}}}let h=f(e,"signature"),l=f(e,"signature-input");if(h&&l){let g=f(e,"signature-agent"),p=f(e,"x-agent-registry"),m=l.toLowerCase();return{protocol:g?"rfc9421-web-bot-auth":p?.toLowerCase().includes("visa")||m.includes("visa")?"rfc9421-tap":p?.toLowerCase().includes("mastercard")||m.includes("mastercard")?"rfc9421-agent-pay":"rfc9421",artifacts:{rfc9421:{headers:a,method:n,url:r,...e.bodyText&&{body:e.bodyText}}},evidence:{...g&&{signatureAgent:g},...p&&{registryHint:p},keyid:l.match(/keyid="([^"]+)"/)?.[1],...s}}}let d=f(e,"timestamp");if(h&&!l&&(d||f(e,"idempotency-key")))return{protocol:"acp",artifacts:{acpRequest:{method:n,url:r,headers:a,...e.bodyText&&{rawBody:e.bodyText},...i&&{body:i}}},evidence:{hasTimestamp:!!d,...s}};if(/\/checkout[-_]sessions(\/|$)/.test(e.uri))return{protocol:"ucp",artifacts:{ucpRequest:{method:n,url:r,...i&&{body:i}}},evidence:{path:e.uri,...s}};if(i){let g=i.intent_mandate??i.intentMandate,p=i.cart_mandate??i.cartMandate,m=i.payment_mandate??i.paymentMandate;if(typeof g=="string"||typeof p=="string"||typeof m=="string")return{protocol:"ap2",artifacts:{ap2Mandates:{...typeof g=="string"&&{intent:g},...typeof p=="string"&&{cart:p},...typeof m=="string"&&{payment:m}}},evidence:{mandatesPresent:[typeof g=="string"&&"intent",typeof p=="string"&&"cart",typeof m=="string"&&"payment"].filter(Boolean),...s}}}if(o&&/^Payment\s+/i.test(o))return{protocol:"mpp",artifacts:{mppRequest:{method:n,url:r,headers:a,...e.bodyText&&{rawBody:e.bodyText},...i&&{body:i}}},evidence:s};if(f(e,"x-payment"))return{protocol:"x402",artifacts:{x402Request:{method:n,url:r,headers:a,...i&&{body:i}}},evidence:s}}var Tt=/\.(css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|pdf|txt|xml)$/i,_t=/^astrasync-sdk\//i,Ut=/curl|wget|python-requests|python-urllib|node-fetch|axios|got|okhttp|go-http-client|libwww|httpie|java\/|ruby|php|scrapy|headless|phantomjs|selenium|playwright|puppeteer|bot|crawler|spider|slurp/i,Pt=/mozilla\/\d/i,xt=/^kya_[A-Za-z0-9_-]+$/;function X(e){return typeof e=="string"&&xt.test(e)}function kt(e,t){if(Tt.test(t))return{mode:e.mode,depth:e.depth,skip:!0};let r=Fe(e.pathRules,t);return r?{mode:r.mode??e.mode,depth:r.depth??e.depth,skip:r.skip===!0,...r.sampling&&{sampling:r.sampling}}:{mode:e.mode,depth:e.depth,skip:!1}}function Mt(e,t,r){let n=f(e,"user-agent")??"";if(_t.test(n))return{tier:"self"};let a=ie(e.headers,{});if(!a.astraId&&(X(a.jwt)||X(a.apiKey)))return{tier:"self",evidence:{firstPartyApiKey:!0}};if(a.astraId)return{tier:"verified",protocol:"x-astra"};let{apiKeyFormat:i,platformHeaders:s}=re(e.headers),o={userAgent:n,apiKeyFormat:i,platformHeaders:s};if(r!=="classify"){let u=Et(e,t);if(u)return{tier:"identified",protocol:u.protocol,artifacts:u.artifacts,evidence:u.evidence,fingerprint:H(o)}}let c=H(o);return c?{tier:"identified",protocol:"platform-ua",fingerprint:c}:!n||Ut.test(n)||!Pt.test(n)?{tier:"anonymous-bot",evidence:{userAgent:n||"(none)"}}:!f(e,"sec-fetch-mode")&&!f(e,"accept-language")?{tier:"anonymous-bot",evidence:{userAgent:n,spoofedBrowser:!0}}:{tier:"human"}}var Ot={"vi-sd-jwt":"This request presented Visa Intelligent Commerce credentials, but the agent is not verified with AstraSync. Register the agent to pair your VI credentials with a verified identity and mandate.","rfc9421-agent-pay":"This request carried a Mastercard Agent Pay signature, but the agent is not verified with AstraSync. Register the agent to pair Agent Pay credentials with a verified identity and mandate.","rfc9421-tap":"This request carried a Visa TAP signature, but the agent is not verified with AstraSync. Register the agent to pair TAP credentials with a verified identity and mandate.","rfc9421-web-bot-auth":"This request carried a Web Bot Auth signature, but the agent is not verified with AstraSync. Register the agent to link your signed-agent identity to a verified principal.",rfc9421:"This request carried an RFC 9421 HTTP message signature, but the agent is not verified with AstraSync. Register the agent to link the signing identity to a verified principal.",acp:"This request used the Agentic Commerce Protocol, but the agent is not verified with AstraSync. Register the agent to transact on this property.",ucp:"This request used a UCP checkout session, but the agent is not verified with AstraSync. Register the agent to transact on this property.",ap2:"This request presented AP2 mandates, but the agent is not verified with AstraSync. Register the agent to pair your mandates with a verified identity.",mpp:"This request presented MPP payment credentials, but the agent is not verified with AstraSync. Register the agent to transact on this property.",x402:"This request used x402 payment headers, but the agent is not verified with AstraSync. Register the agent to transact on this property.","platform-ua":"This traffic was identified as a platform AI agent without AstraSync credentials. Register the agent to access this property with a verified identity.","x-astra":"The presented AstraSync credentials failed verification or were denied by this property\u2019s access policy."};function Dt(e){try{let t=new URL(e).hostname.replace(/^www\./,"");if(t==="astrasync.ai"||t.endsWith(".astrasync.ai"))return`https://mcp.${t}/mcp`}catch{}}function Nt(e,t,r){let n=(r||t).replace(/\/api\/?$/,""),a=e.guidance?.mcp?.endpoint||Dt(n),i=(e.protocol&&Ot[e.protocol])??"This request could not be verified by AstraSync.";return{success:!1,error:{code:e.tier==="verified"?"INSUFFICIENT_ACCESS":"UNAUTHORIZED",message:i,...e.protocol&&{protocol:e.protocol},failures:e.reasons,...e.correlationId&&{correlationId:e.correlationId},guidance:{message:e.guidance?.message||"Register this agent with AstraSync to receive verifiable credentials.",registrationUrl:e.guidance?.registrationUrl||`${n}/register`,documentationUrl:e.guidance?.documentationUrl||`${n}/docs/edge-adapter`,...a&&{mcp:{endpoint:a,discoveryUrl:e.guidance?.mcp?.discoveryUrl||`${a.replace(/\/mcp$/,"")}/.well-known/mcp.json`,message:e.guidance?.mcp?.message||"Inside an MCP host? Add the AstraSync MCP connector at this endpoint instead of the registration URL \u2014 registration through the connector is keyless and human-approved (your human approves in an in-chat card; you never handle credentials)."}}}}}}function Ft(e){return{success:!1,error:{code:"VERIFICATION_UNAVAILABLE",message:"Agent verification is temporarily unavailable and this path enforces verification. Your identity was not evaluated and no denial was recorded \u2014 retry with exponential backoff.",failures:e.reasons,...e.correlationId&&{correlationId:e.correlationId},guidance:{message:"Retry the request with exponential backoff; the condition is transient."}}}}function Bt(e){return{success:!1,status:"manual_review",message:"This action requires human approval. Poll the step-up approval endpoint and retry once approved.",...e.stepUp&&{stepUpApproval:e.stepUp},...e.correlationId&&{correlationId:e.correlationId}}}var Lt="X-Astra-Verified-Hop";function $t(e){return`${e.astraId};${e.sessionId??""};${e.checkedAt}`}var w={trustScore:"X-AstraSync-Trust-Score",agentId:"X-AstraSync-Agent-Id",developerId:"X-AstraSync-Developer-Id",observedDecision:"X-AstraSync-Observed-Decision"},q=["x-astrasync-","x-astra-verified-hop"];function M(){return{action:"pass",injectHeaders:{},stripHeaderPrefixes:[]}}function jt(e,t,r){let n={};if(t.misconfig&&(n[w.observedDecision]="misconfig"),r.mode!=="enforce")return t.decision!=="allow"&&(n[w.observedDecision]=t.decision),Object.assign(n,Y(t),W(t)),{action:"pass",injectHeaders:n,stripHeaderPrefixes:q};switch(t.decision){case"deny":return t.unavailable?{action:"respond",status:503,headers:{"Retry-After":"30"},bodyJson:Ft(t)}:{action:"respond",status:403,headers:{},bodyJson:Nt(t,e.apiBaseUrl,e.publicBaseUrl)};case"manual_review":return{action:"respond",status:202,headers:{"Retry-After":"30"},bodyJson:Bt(t)};default:return Object.assign(n,Y(t),W(t)),{action:"pass",injectHeaders:n,stripHeaderPrefixes:q}}}function Y(e){if(!e.asat)return{};let{trustScore:t,agentId:r,developerId:n}=e.asat;return{...t!==void 0&&{[w.trustScore]:String(t)},...r&&{[w.agentId]:r},...n&&{[w.developerId]:n}}}function W(e){let t=e.asat?.agentId;return t?{[Lt]:$t({astraId:t,...e.sessionId&&{sessionId:e.sessionId},checkedAt:Date.now()})}:{}}var Ht={GET:"data.read",HEAD:"data.read",OPTIONS:"data.read",POST:"data.write",PUT:"data.write",PATCH:"data.write",DELETE:"data.delete"},Kt="data.write",Vt="data";function Gt(e){return Ht[e.toUpperCase()]??Kt}function zt(e){let t=e.indexOf(":");if(t>=0)return{purpose:e.slice(0,t)};let r=e.indexOf(".");return r>0&&r<e.length-1?{purpose:e.slice(0,r),actionCandidate:e}:{purpose:e}}function Xt(e){let t=e.astraPurpose?zt(e.astraPurpose):void 0,r,n;e.routeAction?(r=e.routeAction,n="route_config"):e.hasCustomActionExtractor&&e.customAction?(r=e.customAction,n="custom_extractor"):!e.hasCustomActionExtractor&&e.astraAction?(r=e.astraAction,n="header"):!e.hasCustomActionExtractor&&t?.actionCandidate?(r=t.actionCandidate,n="purpose_header_derived"):(r=Gt(e.method),n="method_table");let a,i;if(e.routePurpose?(a=e.routePurpose,i="route_config"):e.hasCustomPurposeExtractor?e.customPurpose&&(a=e.customPurpose,i="custom_extractor"):t?(a=t.purpose,i="header"):e.legacyPurpose?(a=e.legacyPurpose,i="legacy_header"):e.queryPurpose&&(a=e.queryPurpose,i="query"),!a){let s=r.indexOf(".");s>0?(a=r.slice(0,s),i="action_derived"):(a=Vt,i="transport_default")}return{purpose:a,action:r,purposeSource:i,actionSource:n}}async function T(e,t){let r;try{return await Promise.race([e,new Promise(n=>{r=setTimeout(()=>n(void 0),t)})])}catch{return}finally{r&&clearTimeout(r)}}var qt=e=>`${e.apiBaseUrl}\0${e.apiKey??""}\0${e.counterparty}\0${e.adapter??""}`,Yt=class{constructor(e={}){this.queue=[],this.droppedSinceLast=0,this.droppedTotal=0,this.deliveredTotal=0,this.backoffUntil=0,this.collapse=new Map,this.rejectedKeys=new Set,this.opts={maxItems:e.maxItems??1e3,maxBatch:e.maxBatch??100,maxAttempts:e.maxAttempts??3,collapseWindowMs:e.collapseWindowMs??6e4,collapseMaxKeys:e.collapseMaxKeys??1e3,requestTimeoutMs:e.requestTimeoutMs??1e4,retryBackoffMs:e.retryBackoffMs??1e3,now:e.now??Date.now}}enqueue(e,t,r){let n=this.opts.now();if(r){let a=this.collapse.get(r);if(a&&n-a.firstSeenAt<this.opts.collapseWindowMs){for(let o of[a.first,a.held])if(o&&!o.inFlight&&this.queue.includes(o)){o.item.repeatCount=(o.item.repeatCount??1)+1;return}let s=this.push(e,{...t,repeatCount:1},a.firstSeenAt+this.opts.collapseWindowMs);a.held=s;return}if(this.collapse.delete(r),this.collapse.size>=this.opts.collapseMaxKeys){let s=this.collapse.keys().next().value;s!==void 0&&this.collapse.delete(s)}let i={firstSeenAt:n};this.collapse.set(r,i),i.first=this.push(e,t,n);return}this.push(e,t,n)}flush(){return this.inFlight||(this.inFlight=this.drain().finally(()=>{this.inFlight=void 0})),this.inFlight}stats(){return{queueDepth:this.queue.length,droppedSinceLast:this.droppedSinceLast,droppedTotal:this.droppedTotal,deliveredTotal:this.deliveredTotal,flushing:this.inFlight!==void 0}}push(e,t,r){for(;this.queue.length>=this.opts.maxItems;)this.dropOldest();let n={dest:e,destKey:qt(e),item:t,attempts:0,eligibleAt:r,inFlight:!1};return this.queue.push(n),n}dropOldest(){this.queue.shift()&&this.countDropped(1)}countDropped(e){this.droppedSinceLast+=e,this.droppedTotal+=e}async drain(){for(;;){let e=this.opts.now();if(e<this.backoffUntil)return;let t=this.takeBatch(e);if(t.length===0||!await this.send(t))return}}takeBatch(e){let t=this.queue.find(a=>a.eligibleAt<=e);if(!t)return[];let r=[],n=[];for(let a of this.queue)r.length<this.opts.maxBatch&&a.destKey===t.destKey&&a.eligibleAt<=e?(a.inFlight=!0,r.push(a)):n.push(a);return this.queue=n,r}async send(e){let t=e[0].dest,r=t.apiKey&&!this.rejectedKeys.has(t.apiKey)?t.apiKey:void 0,n=this.droppedSinceLast,a={droppedSinceLast:n,queueDepth:this.queue.length,adapter:t.adapter??"edge-core",version:D},i=typeof AbortController<"u"?new AbortController:void 0,s=await T(C(`${t.apiBaseUrl}/verification-activity/edge-events`,{method:"POST",headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`}},body:JSON.stringify({events:e.map(c=>c.item),meta:a}),...i&&{signal:i.signal}}),this.opts.requestTimeoutMs);s||i?.abort();let o=s?.status;for(let c of e)c.inFlight=!1;if(o!==void 0&&o>=200&&o<300)return this.droppedSinceLast=Math.max(0,this.droppedSinceLast-n),this.deliveredTotal+=e.length,!0;if(o===401&&r)return this.rejectedKeys.add(r),this.requeue(e,!1),!0;if(o===429){let c=Number(s?.headers.get("retry-after")),u=Number.isFinite(c)&&c>0?Math.min(c,120)*1e3:3e4;return this.backoffUntil=this.opts.now()+u,this.requeue(e,!1),!1}return o!==void 0&&o>=400&&o<500?(this.countDropped(e.length),!0):(this.backoffUntil=this.opts.now()+this.opts.retryBackoffMs,this.requeue(e,!0),!1)}requeue(e,t){let r=[];for(let n of e)t&&(n.attempts+=1),n.attempts>=this.opts.maxAttempts?this.countDropped(1):r.push(n);for(this.queue=[...r,...this.queue];this.queue.length>this.opts.maxItems;)this.dropOldest()}},Wt=new Yt;function Jt(){return Wt}async function J(e,t,r,n,a,i){let s=ht(t),o=te(f(t,"x-astra-source")),c=f(t,"user-agent"),u={...e.counterpartyId&&{counterpartyId:e.counterpartyId},...e.counterpartyUrl&&{counterpartyUrl:e.counterpartyUrl},counterpartyType:"website",sourceIp:t.clientIp,userAgent:c,requestPath:t.uri,requestMethod:t.method,...s&&{attemptId:s},referer:f(t,"referer"),accept:f(t,"accept"),...o&&{declaredSource:o},protocol:r.protocol,evidence:r.evidence,observedMetadata:N(t,a),observedAt:new Date().toISOString()};for(let l of Object.keys(u))u[l]===void 0&&delete u[l];let y=Jt();y.enqueue({apiBaseUrl:e.apiBaseUrl,...i&&{apiKey:i},counterparty:e.counterpartyId||e.counterpartyUrl,...e.adapter&&{adapter:e.adapter}},u,t.clientIp?[e.counterpartyId||e.counterpartyUrl,t.clientIp,c??"",t.method,t.uri,s??""].join("\0"):void 0);let h=y.flush();if(e.waitUntil){e.waitUntil(h);return}await T(h,n)}function Qt(e,t=Math.random){return e<=0?!1:e>=1?!0:t()<e}function v(e){return{tier:e.tier,decision:"allow",reasons:[],protocol:e.protocol}}function Q(e,t,r,n,a){let i=Xt({method:t.method,astraPurpose:f(t,"x-astra-purpose"),astraAction:f(t,"x-astra-action")}),s=f(t,"x-astra-attempt-id"),o=te(f(t,"x-astra-source"));return{...s&&/^att_[0-9a-f]{32}$/.test(s)&&{attemptId:s},credentials:ie(t.headers,{}),purpose:i.purpose,action:i.action,resource:t.uri,createSession:!0,counterpartyType:"website",counterpartyUrl:e.counterpartyUrl,callerMetadata:{sourceIp:t.clientIp,userAgent:f(t,"user-agent"),referer:f(t,"referer"),host:f(t,"host"),...o&&{declaredSource:o},observedMetadata:N(t,a)},...n&&r.artifacts&&{commerceArtifacts:r.artifacts}}}function Z(e,t){let r=v(e);return r.sessionId=t.sessionId,r.correlationId=t.correlationId,r.guidance=t.guidance,t.misconfigured?(r.reasons=["verification key misconfigured \u2014 fail-open (merchant_misconfig)"],r.misconfig=!0,r):t.requiresStepUp||t.stepUpApproval?(r.decision="manual_review",r.reasons=["step-up approval required"],r.stepUp={pollUrl:t.stepUpApproval?.pollUrl,expiresAt:t.stepUpApproval?.expiresAt},r):!t.identityVerified||!t.policyAllowed?(r.decision="deny",r.reasons=t.denialReasons?.length?t.denialReasons:[t.identityVerified?"denied by access policy":"identity not verified"],r):(r.asat={trustScore:t.agent?.trustScore,agentId:t.agent?.astraId,developerId:t.developer?.astradId},r)}function R(e,t,r,n){let a=v(e);return a.unavailable=!0,a.reasons=[r],n&&(a.correlationId=n),t.mode==="enforce"&&(a.decision="deny"),a}function ee(e){return(e.failures??[]).some(t=>t.dimension==="verify_access.api_error")===!0&&!e.misconfigured}async function Zt(e,t,r,n,a,i){let{sampling:s,queryValueAllowlist:o}=i,c=e.budgets??{},u=c.beaconMs??300,y=n.mode==="enforce"?c.verifyEnforceMs??3e3:c.verifyObserveMs??1500,h={apiBaseUrl:e.apiBaseUrl,...a&&{apiKey:a},counterpartyId:e.counterpartyId,disableInitChecks:!0};try{switch(r.tier){case"verified":{if(n.depth==="classify")return v(r);let l=await T(G(h,Q(e,t,r,n.depth==="authorize",o)),y);return l?ee(l)?R(r,n,l.denialReasons?.[0]??"verify-access api error",l.correlationId):Z(r,l):R(r,n,"verify-access unreachable within budget")}case"identified":{if(n.depth==="authorize"&&r.artifacts){let d=await T(G(h,Q(e,t,r,!0,o)),y);return d?ee(d)?R(r,n,d.denialReasons?.[0]??"verify-access api error",d.correlationId):Z(r,d):R(r,n,"verify-access unreachable within budget")}await J(e,t,r,u,o,a);let l=v(r);return n.mode==="enforce"&&n.depth!=="classify"&&(l.decision="deny",l.reasons=["agent is not registered with AstraSync"]),l}case"anonymous-bot":return Qt(s.anonymousBeaconRate,e.random)&&await J(e,t,{...r,protocol:r.protocol??"ua-heuristic"},u,o,a),v(r);default:return v(r)}}catch(l){let d=v(r);return d.reasons=[`edge pipeline error \u2014 fail-open: ${l instanceof Error?l.message:String(l)}`],d}}async function de(e,t,r,n){let a=kt(r,t.uri);try{if(a.skip)return{policy:a,application:M()};let i=f(t,"x-forwarded-host")??f(t,"host")??new URL(e.counterpartyUrl).host,s=Mt(t,i,a.depth);if(s.tier==="human"||s.tier==="self")return{policy:a,classification:s,application:M()};let o=await Zt(e,t,s,a,n,{sampling:a.sampling??r.sampling,queryValueAllowlist:r.queryValueAllowlist});return o.decision!=="allow"&&e.log?.("info",a.mode==="enforce"?`${o.decision.toUpperCase()}: ${t.method} ${t.uri}`:`[OBSERVE] would have been ${o.decision.toUpperCase()}: ${t.method} ${t.uri}`,{tier:o.tier,protocol:o.protocol,reasons:o.reasons}),{policy:a,classification:s,outcome:o,application:jt(e,o,a)}}catch(i){return e.log?.("error","edge evaluation error \u2014 passing request through",{error:i instanceof Error?i.message:String(i)}),{policy:a,application:M()}}}function _(e){return e.Records[0].cf.request}function A(e,t){return e.headers[t.toLowerCase()]?.[0]?.value}function er(e){let t={};for(let[r,n]of Object.entries(e))n?.length&&(t[r]=n.map(a=>a.value).join(", "));return t}function tr(e){let t=e.body;return t?.data?{text:t.encoding==="base64"?Buffer.from(t.data,"base64").toString("utf8"):t.data,truncated:t.inputTruncated===!0}:{truncated:!1}}function ue(e){let t=e?.trim();if(!t)return;let r=/^\[([^\]]+)\](?::(\d+))?$/.exec(t);if(r)return{ip:r[1],...r[2]&&{port:r[2]}};let n=/:(\d+)$/.exec(t),a=n?t.slice(0,-n[0].length):t;if(a)return{ip:a,...n&&{port:n[1]}}}function rr(e){let t={},r=(i,s,o)=>{let c=A(e,s);c&&(t[i]=o?o(c):c)},n=ue(A(e,"cloudfront-viewer-address"));n&&(t.ip=n.ip,n.port&&(t.sourcePort=n.port)),r("country","cloudfront-viewer-country"),r("countryName","cloudfront-viewer-country-name"),r("region","cloudfront-viewer-country-region"),r("countryRegionName","cloudfront-viewer-country-region-name"),r("city","cloudfront-viewer-city"),r("latitude","cloudfront-viewer-latitude"),r("longitude","cloudfront-viewer-longitude"),r("postalCode","cloudfront-viewer-postal-code"),r("asn","cloudfront-viewer-asn"),r("tlsVersion","cloudfront-viewer-tls");{let i=A(e,"cloudfront-viewer-tls")?.split(":")[1];i&&(t.tlsCipher=i)}r("httpVersion","cloudfront-viewer-http-version"),r("timeZone","cloudfront-viewer-time-zone"),r("metroCode","cloudfront-viewer-metro-code"),r("tlsFingerprint","cloudfront-viewer-ja3-fingerprint"),r("ja4","cloudfront-viewer-ja4-fingerprint"),r("headerOrder","cloudfront-viewer-header-order",i=>i.slice(0,256)),r("headerCount","cloudfront-viewer-header-count");let a=[];for(let[i,s]of[["desktop","cloudfront-is-desktop-viewer"],["mobile","cloudfront-is-mobile-viewer"],["tablet","cloudfront-is-tablet-viewer"],["smarttv","cloudfront-is-smarttv-viewer"]])A(e,s)==="true"&&a.push(i);return a.length&&(t.device=a.join(",")),t}function le(e){let t=tr(e),r=rr(e),n=ue(A(e,"cloudfront-viewer-address"))?.ip;return{method:e.method,uri:e.uri,querystring:e.querystring??"",headers:er(e.headers),...t.text!==void 0&&{bodyText:t.text},...t.truncated&&{bodyTruncated:!0},...n&&{clientIp:n},...Object.keys(r).length>0&&{connection:r}}}function pe(e,t){if(t.action==="respond")return ar(t.status,t.bodyJson,t.headers);for(let r of t.stripHeaderPrefixes)nr(e,r);for(let[r,n]of Object.entries(t.injectHeaders))F(e,r,n);return e}function fe(e){let t=e.origin?.custom?.domainName??e.origin?.s3?.domainName??void 0;if(!t)return;let r=A(e,"host");!r||r===t||(A(e,"x-forwarded-host")||F(e,"X-Forwarded-Host",r),F(e,"Host",t))}function F(e,t,r){e.headers[t.toLowerCase()]=[{key:t,value:r}]}function nr(e,t){let r=t.toLowerCase();for(let n of Object.keys(e.headers))n.startsWith(r)&&delete e.headers[n]}function ar(e,t,r){let n={"content-type":[{key:"Content-Type",value:"application/json"}]};for(let[a,i]of Object.entries(r??{}))n[a.toLowerCase()]=[{key:a,value:i}];return{status:String(e),statusDescription:e===403?"Forbidden":e===202?"Accepted":"OK",headers:n,body:JSON.stringify(t)}}var sr="5.12.0",U=`astrasync-sdk/${sr}`;function or(e){if(!e)return{"user-agent":U};if(e instanceof Headers){let r=new Headers(e);return r.has("user-agent")||r.set("user-agent",U),r}return Array.isArray(e)?e.some(([n])=>n.toLowerCase()==="user-agent")?e:[...e,["user-agent",U]]:Object.keys(e).some(r=>r.toLowerCase()==="user-agent")?e:{"user-agent":U,...e}}var ir=(e,t)=>fetch(e,{...t,headers:or(t?.headers)}),L=Object.freeze({version:1,mode:"observe",depth:"classify",pathRules:[],sampling:Object.freeze({anonymousBeaconRate:1}),failurePosture:"open"}),ge=["observe","enforce"],ye=["classify","authenticate","authorize"];function he(e){if(typeof e!="object"||e===null)return!1;let t=e.anonymousBeaconRate;return typeof t=="number"&&t>=0&&t<=1}function cr(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.version!==1||!ge.includes(t.mode)||!ye.includes(t.depth)||!Array.isArray(t.pathRules))return!1;for(let r of t.pathRules){if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.pattern!="string"||n.pattern.length===0||n.mode!==void 0&&!ge.includes(n.mode)||n.depth!==void 0&&!ye.includes(n.depth)||n.sampling!==void 0&&!he(n.sampling))return!1}return!he(t.sampling)||t.queryValueAllowlist!==void 0&&(!Array.isArray(t.queryValueAllowlist)||t.queryValueAllowlist.length>16||!t.queryValueAllowlist.every(r=>typeof r=="string"&&r.length>0&&r.length<=64))?!1:t.failurePosture==="open"}async function dr(e,t,r){if(!t)return null;let n={Accept:"application/json"};e.apiKey&&(n.Authorization=`Bearer ${e.apiKey}`,n["X-API-Key"]=e.apiKey),r?.etag&&(n["If-None-Match"]=r.etag);try{let a=await ir(`${e.apiBaseUrl}/endpoints/${encodeURIComponent(t)}/edge-config`,{method:"GET",headers:n,signal:AbortSignal.timeout(r?.timeoutMs??5e3)});if(a.status===304)return{notModified:!0};if(!a.ok)return null;let s=(await a.json()).data?.edgeConfig;return cr(s)?{edgeConfig:s,etag:a.headers.get("etag")??void 0}:null}catch{return null}}var ur=60*1e3,lr=1440*60*1e3,S=new Map,B=new Map;function ve(e,t){return`${e}|${t}`}function pr(e){return e.mode!=="enforce"&&!e.pathRules.some(t=>t.mode==="enforce")?e:{...e,mode:"observe",pathRules:e.pathRules.map(t=>t.mode==="enforce"?{...t,mode:"observe"}:t)}}async function me(e,t){let r=ve(e.apiBaseUrl,t),n=B.get(r);if(n)return n;let a=dr(e,t,{etag:S.get(r)?.etag}).then(i=>{if(i===null)return;let s=Date.now();if("notModified"in i){let o=S.get(r);o&&(o.lastSuccessAt=s);return}S.set(r,{config:i.edgeConfig,etag:i.etag,lastSuccessAt:s})}).finally(()=>{B.delete(r)});return B.set(r,a),a}async function Ae(e,t,r){let n=r?.ttlMs??ur,a=r?.maxStaleMs??lr,i=ve(e.apiBaseUrl,t),s=S.get(i);if(s){let o=Date.now()-s.lastSuccessAt;return o>n&&me(e,t).catch(()=>{}),o>a?pr(s.config):s.config}return await me(e,t).catch(()=>{}),S.get(i)?.config??L}var fr=900*1e3,we=new Map;async function gr(e){let{SecretsManagerClient:t,GetSecretValueCommand:r}=await import("@aws-sdk/client-secrets-manager");return(await new t({region:"us-east-1"}).send(new r({SecretId:e}))).SecretString??void 0}async function Se(e){if(e.apiKey)return e.apiKey;let t=e.apiKeySecretName;if(!t)return;let r=we.get(t);if(r&&Date.now()-r.fetchedAt<fr)return r.value;try{let a=await(e.fetchSecret??gr)(t);return we.set(t,{value:a,fetchedAt:Date.now()}),a}catch(n){return e.log?.("warn","Secrets Manager fetch failed \u2014 continuing keyless",{secretName:t,error:n instanceof Error?n.message:String(n)}),r?.value}}async function be(e,t){try{return await Ae({apiBaseUrl:e.apiBaseUrl,apiKey:t},e.counterpartyId,{ttlMs:e.configTtlMs})}catch{return e.fallbackConfig??L}}function Ie(e){let t=e.log??((r,n,a)=>{console[r==="info"?"log":r](`[astrasync-edge] ${n}`,a??"")});return async function(n){let a=_(n);try{fe(a);let i=await Se({...e,log:t}),s=await be(e,i),{application:o}=await de({...e,adapter:"lambda-edge",log:t},le(a),s,i);return pe(a,o)}catch(i){return t("error","edge handler error \u2014 passing request through",{error:i instanceof Error?i.message:String(i)}),a}}}var yr={apiBaseUrl:"x-astrasync-api-base-url",publicBaseUrl:"x-astrasync-public-base-url",counterpartyId:"x-astrasync-counterparty-id",counterpartyUrl:"x-astrasync-counterparty-url",apiKeySecretName:"x-astrasync-api-key-secret-name"};function hr(e,t){return e.origin?.custom?.customHeaders?.[t]?.[0]?.value||void 0}function Re(e,t){let r=n=>hr(e,yr[n]);return{apiBaseUrl:r("apiBaseUrl")??t.apiBaseUrl,publicBaseUrl:r("publicBaseUrl")??t.publicBaseUrl,counterpartyId:r("counterpartyId")??t.counterpartyId,counterpartyUrl:r("counterpartyUrl")??t.counterpartyUrl,apiKeySecretName:r("apiKeySecretName")??t.apiKeySecretName}}function Ce(e){return[e.apiBaseUrl,e.publicBaseUrl??"",e.counterpartyId,e.counterpartyUrl,e.apiKeySecretName??""].join("|")}var mr={apiBaseUrl:"https://astrasync.ai/api",publicBaseUrl:void 0,counterpartyId:"",counterpartyUrl:"",apiKeySecretName:void 0},Ee=new Map,Te=!1,vr=async e=>{let t=Re(_(e),mr);(!t.counterpartyId||!t.counterpartyUrl)&&(Te||(Te=!0,console.error("[astrasync-edge] counterpartyId/counterpartyUrl missing \u2014 set the X-AstraSync-* origin custom headers on the distribution (see infra/template.yaml) or bake ASTRASYNC_* constants via infra/deploy.sh.")));let r=Ce(t),n=Ee.get(r);return n||(n=Ie(t),Ee.set(r,n)),n(e)};0&&(module.exports={handler});
|
|
1
|
+
"use strict";var _e=Object.create;var b=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var Me=(e,t)=>{for(var r in t)b(e,r,{get:t[r],enumerable:!0})},L=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Pe(t))!xe.call(e,a)&&a!==r&&b(e,a,{get:()=>t[a],enumerable:!(n=Ue(t,a))||n.enumerable});return e};var Oe=(e,t,r)=>(r=e!=null?_e(ke(e)):{},L(t||!e||!e.__esModule?b(r,"default",{value:e,enumerable:!0}):r,e)),De=e=>L(b({},"__esModule",{value:!0}),e);var Rr={};Me(Rr,{handler:()=>br});module.exports=De(Rr);var D="5.15.0",R=`astrasync-sdk/${D}`;function Ne(e){if(!e)return{"user-agent":R};if(e instanceof Headers){let r=new Headers(e);return r.has("user-agent")||r.set("user-agent",R),r}return Array.isArray(e)?e.some(([n])=>n.toLowerCase()==="user-agent")?e:[...e,["user-agent",R]]:Object.keys(e).some(r=>r.toLowerCase()==="user-agent")?e:{"user-agent":R,...e}}var E=(e,t)=>fetch(e,{...t,headers:Ne(t?.headers)});function Fe(e,t={}){let r="";for(let n=0;n<e.length;n++){let a=e[n];if(a==="*")r+=".*";else if(a===":"&&/[A-Za-z_]/.test(e[n+1]??"")&&(n===0||e[n-1]==="/")){let i=n+1;for(;i<e.length&&/[A-Za-z0-9_]/.test(e[i]);)i++;r+="[^/]+",n=i-1}else r+=a.replace(/[.+?^${}()|[\]\\/]/g,"\\$&")}try{return new RegExp(`^${r}$`,t.caseInsensitive?"i":"")}catch{return null}}var Cr=Object.freeze({version:1,mode:"observe",depth:"classify",pathRules:[],sampling:Object.freeze({anonymousBeaconRate:1}),failurePosture:"open"}),_r=60*1e3,Ur=1440*60*1e3;function $e(e,t){for(let r of e)if(Be(r.pattern).test(t))return r}function Be(e){return Fe(e,{caseInsensitive:!0})??/$^/}var Le=1,je=new Set(["cookie","set-cookie","x-csrf-token","proxy-authorization","x-astrasync-signature","x-astrasync-secret","x-hub-signature","x-hub-signature-256","x-astra-verified-hop"]),He=["x-astrasync-","kya-","kya_"],Ke=new Set(["authorization","x-api-key","x-goog-api-key","api-key"]);function Ve(e){return e==="signature"||e.endsWith("-signature")||e.endsWith("-signature-256")}var Ge=new Set(["openai-organization","openai-project","openai-version","openai-processing-ms","anthropic-version","anthropic-beta","x-goog-user-project","x-goog-api-client","user-agent","x-agent-card-url","x-agent-provider"]),ze=["x-goog-","x-stainless-","x-anthropic-","x-openai-","sec-ch-"],Xe=["sk-ant-api03","sk-ant-api","sk-ant","sk-proj","sk-svcacct","sk-or-v1","sk-or","sk-lf","sk-","gsk_","aiza","ya29","ghp_","gho_","github_pat_","xai-","pplx-","r8_","hf_","astra-","astrae-"],qe=64,j=1024,Ye=16*1024,Je=64,We=/^[a-z0-9][a-z0-9 ._/-]{0,63}$/;function te(e){let t=e?.trim().slice(0,Je).toLowerCase();return t&&We.test(t)?t:void 0}function x(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);n<128?t+=1:n<2048?t+=2:n>=55296&&n<=56319?(t+=4,r++):t+=3}return t}function Ze(e){if(!e)return;let t=e.trim(),r=t.indexOf(" ");if(r>0){let a=t.slice(0,r).toLowerCase();(a==="bearer"||a==="basic"||a==="token")&&(t=t.slice(r+1).trim())}let n=t.toLowerCase();for(let a of Xe)if(n.startsWith(a))return a}function Qe(e){return!!(je.has(e)||He.some(t=>e.startsWith(t))||Ve(e))}function et(e){return Ge.has(e)?!0:ze.some(t=>e.startsWith(t))}function re(e){let t={},r={},n,a,i=0,s=0;if(!e)return{headers:t};for(let c of Object.keys(e)){if(s>=qe)break;let d=c.toLowerCase(),p=e[c];if(p===void 0)continue;let y=Array.isArray(p)?p.join(", "):String(p);if(Ke.has(d)){let u=Ze(y);u&&!n&&(n=u);continue}if(d==="cookie"&&(a=y.split(";").filter(u=>u.trim().length>0).length),Qe(d))continue;let l=y;x(l)>j&&(l=l.slice(0,j));let m=x(d)+x(l);i+m>Ye||(i+=m,s++,t[d]=l,et(d)&&(r[d]=l))}let o={headers:t};return n&&(o.apiKeyFormat=n),Object.keys(r).length>0&&(o.platformHeaders=r),a!==void 0&&(o.cookieCount=a),o}var tt=[{vendor:"claude",displayName:"Anthropic Claude",uaPatterns:[/claude/i,/anthropic/i],agentCardPatterns:[/anthropic\.com/i,/claude\.ai/i],apiKeyFormatPatterns:[/^sk-ant/i],headerPatterns:[/^anthropic-version/i,/^anthropic-beta/i,/^x-anthropic-/i]},{vendor:"chatgpt",displayName:"OpenAI ChatGPT",uaPatterns:[/chatgpt/i,/openai/i,/gpt-?\d/i,/\bGPTBot\b/i,/\bOAI-SearchBot\b/i],agentCardPatterns:[/openai\.com/i,/chatgpt\.com/i],apiKeyFormatPatterns:[/^sk-proj/i,/^sk-svcacct/i],headerPatterns:[/^openai-organization/i,/^openai-project/i,/^openai-version/i]},{vendor:"gemini",displayName:"Google Gemini",uaPatterns:[/gemini/i,/google-gemini/i,/bard/i,/\bGoogle-Extended\b/i,/\bGoogleOther\b/i,/\bGoogle-CloudVertexBot\b/i],agentCardPatterns:[/gemini\.google\.com/i,/ai\.google\.dev/i],apiKeyFormatPatterns:[/^aiza/i],headerPatterns:[/^x-goog-user-project/i,/^x-goog-api-client/i]},{vendor:"cursor",displayName:"Cursor",uaPatterns:[/cursor/i],agentCardPatterns:[/cursor\.sh/i,/cursor\.com/i]},{vendor:"goose",displayName:"Block Goose",uaPatterns:[/goose/i,/block-goose/i],agentCardPatterns:[/block\.xyz\/goose/i,/goose\.tools/i]},{vendor:"perplexity",displayName:"Perplexity",uaPatterns:[/perplexity/i],agentCardPatterns:[/perplexity\.ai/i],apiKeyFormatPatterns:[/^pplx-/i]},{vendor:"chatgpt-atlas",displayName:"ChatGPT Atlas browser",uaPatterns:[/\batlas\/\d/i],headerPatterns:[/^sec-ch-ua: .*atlas/i]},{vendor:"perplexity-comet",displayName:"Perplexity Comet browser",uaPatterns:[/\bcomet\/\d/i],headerPatterns:[/^sec-ch-ua: .*comet/i]},{vendor:"astrasync-bridge",displayName:"AstraSync MCP bridge (buyer-agent catalog fetch)",uaPatterns:[/^astrasync-bridge\//i]},{vendor:"astrasync-sdk",displayName:"AstraSync SDK",uaPatterns:[/^astrasync-sdk\//i]}];function rt(e,t){let r=t.userAgent??"",n=t.agentCardUrl??"",a=t.apiKeyFormat??"",i=t.ja4??"",s=t.asn??"",o=[];if(t.platformHeaders)for(let[c,d]of Object.entries(t.platformHeaders))o.push(c,`${c}: ${d}`);for(let c of e){let d=c.uaPatterns?.some(g=>g.test(r)),p=c.agentCardPatterns?.some(g=>g.test(n)),y=a.length>0&&c.apiKeyFormatPatterns?.some(g=>g.test(a)),l=o.length>0&&c.headerPatterns?.some(g=>o.some(h=>g.test(h))),m=i.length>0&&c.ja4Patterns?.some(g=>g.test(i)),u=s.length>0&&c.asnList?.includes(s);if(d||p||y||l||m||u){let g=r.split(/[\s/]/)[0]?.toLowerCase()??"",h=(()=>{try{return n?new URL(n).host:""}catch{return""}})(),v=g||h||a||i||s&&`asn${s}`||"unknown";return{vendor:c.vendor,fingerprintKey:`${c.vendor}:${v}`,displayName:c.displayName}}}}function H(e){return rt(tt,e)}function nt(e){return e>=80?"PLATINUM":e>=60?"GOLD":e>=40?"SILVER":"BRONZE"}var Pr=3600*1e3,at=new Map;function ot(e){return at.get(e)?.data}var ne=new Set(["identity.invalid_agent_id","identity.unknown_agent","agent.lookup"]),ae="Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.",it={apiBaseUrl:"https://astrasync.ai/api",debug:!1},oe=!1,K=!1;async function V(e,t,r,n,a){oe=!0;try{let i=`${e}/agents/verify-access`,o=(await E(i,{method:"HEAD"})).headers.get("content-type")??"";if(o.startsWith("text/html")){let c=`[VerificationGateway] apiBaseUrl '${e}' returned HTML (content-type: ${o}). This usually means apiBaseUrl is pointing at a marketing site instead of the API. Expected: 'https://astrasync.ai/api' (prod) or 'https://staging.astrasync.ai/api' (staging).`;if(r)throw new Error(`${c} (strictInit=true)`);console.warn(`${c} Set disableInitChecks: true on GatewayConfig to silence.`)}else t&&console.log(`[VerificationGateway] init check passed for ${e} (content-type: ${o})`);if(n){let c=a?.id?`?counterpartyId=${encodeURIComponent(a.id)}`:a?.url?`?counterpartyUrl=${encodeURIComponent(a.url)}`:"",d=await E(`${e}/agents/verify-access/self-check${c}`,{headers:{Authorization:`Bearer ${n}`}});if(d.status===401){let p=await d.json().catch(()=>({})),y=`[VerificationGateway] the configured AstraSync API key was REJECTED at startup (${p.code??"api_key_invalid"}: ${p.message??"invalid key"}). Every inbound agent will be turned away until the key is rotated`+(p.remediation?.manageUrl?` at ${p.remediation.manageUrl}`:"")+".";if(r)throw new Error(`${y} (strictInit=true)`);console.error(y)}else if(d.ok){let p=await d.json().catch(()=>({}));if(p.counterparty&&p.counterparty.canVerify===!1){let y=`[VerificationGateway] the configured AstraSync API key cannot verify for this endpoint (${p.counterparty.message??"endpoint not found or owned by another account"}). Every inbound agent will be turned away until the key or counterparty is corrected.`;if(r)throw new Error(`${y} (strictInit=true)`);console.error(y)}typeof p.daysToExpiry=="number"&&p.daysToExpiry<=7?console.warn(`[VerificationGateway] the configured AstraSync API key expires in ${p.daysToExpiry} day(s) \u2014 rotate it at Settings \u2192 Developer Tools before integrations start failing.`):t&&console.log("[VerificationGateway] API key self-check passed")}}}catch(i){if(r)throw i;t&&console.log(`[VerificationGateway] init check failed (non-blocking): ${String(i)}`)}}var O=new Map;function ie(e,t){let r=e.credentials;return[r.astraId||"",r.apiKey||"",r.jwt||"",e.purpose||"",e.action||"",e.resourceType||"",e.resource||"",e.jurisdiction||"",e.transactionValue??"",e.currency||"",t||"",e.counterpartyUrl||"",e.counterpartyType||"",e.isSubAgentRequest?"1":"0",e.parentAgentId||"",e.subAgentDepth??"",e.durationRequired??"",e.invocationProtocol||"",e.enableRuntimeChallenge?"1":"0",e.callerMetadata?.sourceIp||"",e.callerMetadata?.userAgent||"",e.callerMetadata?.forwardedFor||"",e.callerMetadata?.agentCardUrl||"",e.commercePhase||"",e.checkoutSessionId||""].join("|")}function st(e,t){let r=ie(e,t),n=O.get(r);return n&&n.expiresAt>Date.now()?n.result:(n&&O.delete(r),null)}var ct=60;function dt(e,t,r,n){let a=r&&r>0?r:ct,i=ie(e,n);O.set(i,{result:t,expiresAt:Date.now()+a*1e3})}function se(e,t){let r={},n=/^ASTRAE?-[A-Za-z0-9_-]{1,64}$/,a=e["x-astra-id"]||e["X-Astra-Id"]||e["X-ASTRA-ID"]||e["x-astra-agentid"]||e["X-Astra-AgentId"]||e["x-astra-agent-id"]||e["X-Astra-Agent-Id"]||e["X-ASTRA-AGENT-ID"];if(a){let o=Array.isArray(a)?a[0]:typeof a=="string"?a:void 0;typeof o=="string"&&n.test(o)&&(r.astraId=o)}let i=e["x-api-key"]||e["X-Api-Key"]||e["X-API-KEY"];i&&(r.apiKey=Array.isArray(i)?i[0]:i);let s=e.authorization||e.Authorization;if(s){let o=Array.isArray(s)?s[0]:s;typeof o=="string"&&(r.authorizationHeader=o,o.startsWith("Bearer ")&&(r.jwt=o.slice(7)))}return t&&(t.astraId&&!r.astraId&&(r.astraId=t.astraId),t.apiKey&&!r.apiKey&&(r.apiKey=t.apiKey)),r}function C(e){if(e?.mcpEndpoint)return{endpoint:e.mcpEndpoint,discoveryUrl:e.mcpDiscoveryUrl,message:"If you are operating inside an MCP-capable host (Claude, ChatGPT, Cursor, or any MCP client), add the AstraSync MCP connector instead of integrating these URLs by hand: registration through the connector is KEYLESS and HUMAN-APPROVED \u2014 your human approves in an in-chat card, and you never see, hold, or transmit an API key, password, or private key."}}function ut(e,t,r={}){let n=r.source??"no_credentials",a=n==="api_error",i=n==="merchant_misconfig",s=r.urls,o=i?{message:"This site's AstraSync integration is misconfigured (its API key was revoked, expired, rotated, or belongs to another account). Your identity and the AstraSync platform are fine \u2014 contact the site operator. Retrying will not help.",registrationUrl:s?.registrationUrl??"",documentationUrl:r.remediation?.docsUrl??s?.documentationUrl??"",steps:["Report the failure to the site operator \u2014 their AstraSync API key needs replacing","Do not retry: the failure is deterministic until the operator updates their key"]}:a?{message:"Verification is temporarily unavailable. Retry with exponential backoff; if the issue persists, contact support with the correlationId.",registrationUrl:s?.registrationUrl??"",documentationUrl:s?.documentationUrl??"",steps:["Retry the request with exponential backoff","If failures persist, share the correlationId with support"]}:{message:"This service verifies AI agents before granting access. Please register your agent with AstraSync.",registrationUrl:s?.registrationUrl??"",documentationUrl:s?.documentationUrl??"",steps:[...s?.mcpEndpoint?[`Fastest path (inside an MCP host): add the AstraSync MCP connector at ${s.mcpEndpoint} \u2014 keyless, human-approved registration`]:[],"Register for an AstraSync account","Create and register your agent","Add your ASTRA-ID to request headers","Retry your request"],...C(s)&&{mcp:C(s)}};return{identityVerified:!1,policyAllowed:!1,guidance:o,denialReasons:t?[t]:["No valid agent credentials provided"],failures:i?[{dimension:"verify_access.merchant_misconfigured",message:t??"The integration API key was rejected by AstraSync",guidance:o.message}]:a?[{dimension:"verify_access.api_error",message:t??"Verification temporarily unavailable",guidance:o.message}]:void 0,...i&&{misconfigured:!0},...a&&{retryable:!0},...r.httpStatus!==void 0&&{httpStatus:r.httpStatus},...r.retryAfterMs!==void 0&&{retryAfterMs:r.retryAfterMs},correlationId:r.correlationId,attemptId:r.attemptId,verifiedAt:new Date}}async function lt(e){try{let t=await e.json();return t&&typeof t=="object"?t:{}}catch{return{}}}function pt(e){let t=e?.find(r=>ne.has(r.dimension));if(t)return t.dimension==="agent.lookup"?`The presented agent identifier is not registered with AstraSync. ${ae}`:t.guidance?`${t.message} ${t.guidance}`:t.message}var ft=900*1e3;function gt(e){let t=e.headers?.get?.("retry-after");if(!t)return;let r=t.trim(),n;if(/^\d+(\.\d+)?$/.test(r))n=Number(r)*1e3;else{let a=Date.parse(r);if(Number.isNaN(a))return;n=a-Date.now()}return Math.min(ft,Math.max(0,Math.round(n)))}async function yt(e,t){let{credentials:r,...n}=t,a={...r.astraId&&{agentId:r.astraId},...n.purpose&&{purpose:n.purpose}};if(n.action&&(a.action=n.action),n.resourceType&&(a.resourceType=n.resourceType),n.resource&&(a.resource=n.resource),n.jurisdiction&&(a.jurisdiction=n.jurisdiction),n.transactionValue&&(a.transactionValue=n.transactionValue),n.currency&&(a.currency=n.currency),n.isSubAgentRequest&&(a.isSubAgentRequest=n.isSubAgentRequest),n.parentAgentId&&(a.parentAgentId=n.parentAgentId),n.subAgentDepth!==void 0&&(a.subAgentDepth=n.subAgentDepth),n.enableRuntimeChallenge&&(a.enableRuntimeChallenge=n.enableRuntimeChallenge),n.createSession&&(a.createSession=n.createSession),n.durationRequired&&(a.durationRequired=n.durationRequired),n.counterpartyType&&(a.counterpartyType=n.counterpartyType),n.counterpartyUrl&&(a.counterpartyUrl=n.counterpartyUrl),e.counterpartyId&&(a.counterpartyId=e.counterpartyId),n.runtimeChallengeOptions&&(a.runtimeChallengeOptions=n.runtimeChallengeOptions),n.invocationProtocol&&(a.invocationProtocol=n.invocationProtocol),n.commercePhase&&(a.commercePhase=n.commercePhase),n.checkoutSessionId&&(a.checkoutSessionId=n.checkoutSessionId),n.checkoutJwt&&(a.checkoutJwt=n.checkoutJwt),n.checkoutItems&&(a.checkoutItems=n.checkoutItems),n.buyerEmail&&(a.buyerEmail=n.buyerEmail),n.commerceArtifacts&&(a.commerceArtifacts=n.commerceArtifacts),n.attemptId&&(a.attemptId=n.attemptId),n.considerationSet&&(a.considerationSet=n.considerationSet),a.sdkVersion=D,n.callerMetadata||n.clientIp||n.userAgent){let s={...n.clientIp&&{sourceIp:n.clientIp},...n.userAgent&&{userAgent:n.userAgent},...n.callerMetadata};Object.keys(s).length>0&&(a.callerMetadata=s)}let i={"Content-Type":"application/json",...e.customHeaders};e.apiKey&&(i.Authorization=`Bearer ${e.apiKey}`,i["X-API-Key"]=e.apiKey);try{let s=await E(`${e.apiBaseUrl}/agents/verify-access`,{method:"POST",headers:i,body:JSON.stringify(a),signal:AbortSignal.timeout(e.verifyTimeoutMs??1e4)}),o=await lt(s),c=gt(s);if(s.status===410)return{success:!0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,access:{allowed:!1,reason:"endpoint_deactivated",failures:[{dimension:"endpoint.deactivated",message:typeof o?.message=="string"?o.message:"Endpoint has been deactivated",guidance:typeof o?.guidance=="string"?o.guidance:"Reactivate via POST /api/endpoints/{id}/reactivate, or update the URL on the calling agent."}]}};if(s.status===400&&o?.error==="INVALID_AGENT_ID"){let d=typeof o?.message=="string"?o.message:"Agent identifier must be a canonical ASTRA-* id.";return{success:!0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,access:{allowed:!1,reason:"invalid_agent_id",failures:[{dimension:"identity.invalid_agent_id",message:d,guidance:typeof o?.guidance=="string"?o.guidance:"Present your canonical ASTRA-* id (discover it via GET /api/agents/request-registration/{requestId} after owner approval)."}]}}}if(s.status===404&&r.astraId&&(o?.error==="AGENT_NOT_FOUND"||typeof o?.message=="string"&&/agent/i.test(o.message)))return{success:!0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,access:{allowed:!1,reason:"unknown_agent",failures:[{dimension:"identity.unknown_agent",message:"The presented agent identifier is not registered with AstraSync.",guidance:ae}]}};if(!s.ok){let d=s.status===403&&o?.error==="COUNTERPARTY_KEY_MISMATCH";return s.status===401||d?{success:!1,error:o.message||o.error||"Integration API key rejected",misconfig:!0,misconfigCode:d?"counterparty_key_mismatch":typeof o?.code=="string"?o.code:void 0,remediation:o?.remediation&&typeof o.remediation=="object"?o.remediation:void 0,correlationId:typeof o?.correlationId=="string"?o.correlationId:void 0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0}:{success:!1,error:typeof o?.message=="string"&&o.message||typeof o?.error=="string"&&o.error||`API returned ${s.status}`,correlationId:typeof o?.correlationId=="string"?o.correlationId:void 0,attemptId:typeof o?.attemptId=="string"?o.attemptId:void 0,httpStatus:s.status,...c!==void 0&&{retryAfterMs:c}}}return o}catch(s){return{success:!1,error:`Failed to call verify-access API: ${s instanceof Error?s.message:"Unknown error"}`}}}async function G(e,t,r){let n={...it,...e},a=n.apiBaseUrl?ot(n.apiBaseUrl):void 0;!oe&&!n.disableInitChecks&&n.apiBaseUrl&&(n.strictInit?await V(n.apiBaseUrl,n.debug,!0,n.apiKey,{id:n.counterpartyId,url:n.counterpartyUrl??t.counterpartyUrl}):V(n.apiBaseUrl,n.debug,!1,n.apiKey,{id:n.counterpartyId,url:n.counterpartyUrl??t.counterpartyUrl})),!K&&(e.minTrustScore!==void 0||e.minTrustScoreForFull!==void 0)&&(K=!0,console.warn("[VerificationGateway] minTrustScore / minTrustScoreForFull are deprecated in v2.3.0 and have no effect. Server is now the single source of truth for access decisions (verified ID + runtime challenge + PDLSS + trust score). To gate access to an endpoint, configure the endpoint's trust_score_requirement server-side."));let i=!!t.commerceArtifacts;if(n.cacheTtl!==0&&!r?.bypassCache&&!i){let h=st(t,n.counterpartyId);if(h){n.debug&&console.log("[VerificationGateway] Returning cached result");let v={...h};return t.attemptId?v.attemptId=t.attemptId:delete v.attemptId,v}}let s={...t};!s.counterpartyUrl&&n.counterpartyUrl&&(s.counterpartyUrl=n.counterpartyUrl),!s.counterpartyType&&n.counterpartyType&&(s.counterpartyType=n.counterpartyType),n.debug&&console.log("[VerificationGateway] Calling verify-access API");let o=await yt(n,s),c=o.denialReasons,d=Array.isArray(c)&&c.length>0?c:void 0;if(!o.success)return ut(n,o.error,{source:o.misconfig?"merchant_misconfig":"api_error",correlationId:o.correlationId,attemptId:o.attemptId,remediation:o.remediation,httpStatus:o.httpStatus,retryAfterMs:o.retryAfterMs,urls:a});if(!o.access?.allowed){let h=o.access?.failures;return{identityVerified:o.verificationContext?.idVerified===!0&&!h?.some(k=>ne.has(k.dimension)),policyAllowed:!1,denialReasons:d??(h&&h.length>0?h.map(k=>k.message):o.access?.reason?[o.access.reason]:["Access denied"]),failures:h,requiresStepUp:o.access?.requiresStepUp,requiresApproval:o.access?.requiresApproval,guidance:{message:pt(h)??(o.access?.reason||"Access denied by PDLSS policy"),registrationUrl:a?.registrationUrl??"",documentationUrl:a?.documentationUrl??"",...C(a)&&{mcp:C(a)}},verifiedAt:new Date,sessionId:o.sessionId,correlationId:o.correlationId,attemptId:o.attemptId,recommendation:o.recommendation,recommendationReasons:o.recommendationReasons,stepUpApproval:o.stepUpApproval,settlement:o.settlement,settlementOutcome:o.settlementOutcome,settlementToken:o.settlementToken,fulfilment:o.fulfilment,mandates:o.mandates,kyaToken:o.kyaToken,aep:o.aep}}let p=o.agent?{astraId:o.agent.astraId,name:o.agent.name,trustScore:o.agent.trustScore,trustLevel:nt(o.agent.trustScore),blockchainAnchored:o.agent.blockchainStatus==="anchored",status:o.agent.agentStatus,...o.agent.protocolIdentities&&{protocolIdentities:o.agent.protocolIdentities}}:void 0,y=o.developer?{astradId:o.developer.kyaOwnerId,name:o.developer.fullName,trustScore:o.developer.trustScore||0,verified:o.developer.identityVerified}:void 0,l=o.organization?{name:o.organization.name,verified:o.organization.verified,trustScore:o.organization.trustScore}:void 0,m=o.verificationContext,u={identityVerified:o.verificationContext?.idVerified===!0,policyAllowed:!0,agent:p,developer:y,organization:l,appliedPolicy:o.access?.appliedPolicy,verificationContext:m,requiresStepUp:o.access?.requiresStepUp,requiresApproval:o.access?.requiresApproval,verifiedAt:new Date,cacheTtl:n.cacheTtl,sessionId:o.sessionId,correlationId:o.correlationId,attemptId:o.attemptId,runtimeChallenge:o.runtimeChallenge,tokenGuidance:o.tokenGuidance,recommendation:o.recommendation,recommendationReasons:o.recommendationReasons,warningHeader:o.warningHeader,stepUpApproval:o.stepUpApproval,settlement:o.settlement,settlementOutcome:o.settlementOutcome,settlementToken:o.settlementToken,fulfilment:o.fulfilment,mandates:o.mandates,kyaToken:o.kyaToken,aep:o.aep};u.recommendation==="deny"?(u.policyAllowed=!1,u.denialReasons=d??u.recommendationReasons??["Access denied by AstraSync recommendation"],u.guidance=u.runtimeChallenge?{message:`Verification failed: ${u.runtimeChallenge.reason||"runtime challenge failed"}`,registrationUrl:a?.registrationUrl??"",documentationUrl:a?.documentationUrl??""}:{message:u.recommendationReasons?.[0]||"Access denied by AstraSync recommendation",registrationUrl:a?.registrationUrl??"",documentationUrl:a?.documentationUrl??""}):u.recommendation==="step_up_required"&&u.identityVerified&&(u.requiresStepUp=!0,u.denialReasons=d??u.recommendationReasons??["Step-up verification required"]);let g=u.requiresStepUp===!0||u.requiresApproval===!0||u.recommendation==="step_up_required";return n.cacheTtl!==0&&u.recommendation!=="deny"&&!g&&(i||dt(t,u,n.cacheTtl,n.counterpartyId)),u}function f(e,t){return e.headers[t.toLowerCase()]}function ht(e,t){let r=e.querystring?`?${e.querystring}`:"";return`https://${t}${e.uri}${r}`}var z=/^att_[0-9a-f]{32}$/;function mt(e){let t=f(e,"x-astra-attempt-id");if(t&&z.test(t))return t;if(e.querystring)try{let r=new URLSearchParams(e.querystring).get("astra_attempt");if(r&&z.test(r))return r}catch{}}function N(e,t){let{headers:r,apiKeyFormat:n,platformHeaders:a,cookieCount:i}=re(e.headers),s=e.connection??{},o=At(e.querystring),c=It(e.querystring,t);return{headers:r,...n&&{apiKeyFormat:n},...a&&{platformHeaders:a},...Object.keys(s).length>0&&{connection:s},...i!==void 0&&{cookieCount:i},...o&&{queryKeys:o},...c&&{queryParams:c},schemaVersion:Le}}var vt=32,ce=64;function At(e){if(!e)return;let t;try{t=new URLSearchParams(e)}catch{return}let r=[];for(let n of t.keys()){let a=n.toLowerCase().slice(0,ce);if(a&&!r.includes(a)&&(r.push(a),r.length>=vt))break}return r.length>0?r:void 0}var wt=16,St=256;function It(e,t){if(!e||!t||t.length===0)return;let r;try{r=new URLSearchParams(e)}catch{return}let n=s=>t.some(o=>o.endsWith("*")?s.startsWith(o.slice(0,-1)):s===o),a={},i=0;for(let[s,o]of r.entries()){let c=s.toLowerCase().slice(0,ce);if(!(!c||a[c]!==void 0||!n(c))&&(a[c]=o.slice(0,St),++i>=wt))break}return i>0?a:void 0}var bt=/^eyJ[\w-]+\.[\w-]*\.[\w-]+~/;function Rt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=atob(r),a=new Uint8Array(n.length);for(let i=0;i<n.length;i++)a[i]=n.charCodeAt(i);return new TextDecoder().decode(a)}function Tt(e){try{let t=e.split(".")[0];return JSON.parse(Rt(t))}catch{return}}function Et(e){if(e)try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:void 0}catch{return}}function Ct(e,t){let r=ht(e,t),n=e.method,a=e.headers,i=Et(e.bodyText),s=e.bodyTruncated?{bodyTruncated:!0}:{},o=f(e,"authorization"),c=o?.replace(/^Bearer\s+/i,""),p=[f(e,"x-payment-mandate")??f(e,"payment-mandate"),c].find(u=>u&&bt.test(u));if(p){let u=Tt(p)?.typ;return{protocol:"vi-sd-jwt",artifacts:{viSdJwt:p},evidence:{typ:u,...s}}}let y=f(e,"signature"),l=f(e,"signature-input");if(y&&l){let u=f(e,"signature-agent"),g=f(e,"x-agent-registry"),h=l.toLowerCase();return{protocol:u?"rfc9421-web-bot-auth":g?.toLowerCase().includes("visa")||h.includes("visa")?"rfc9421-tap":g?.toLowerCase().includes("mastercard")||h.includes("mastercard")?"rfc9421-agent-pay":"rfc9421",artifacts:{rfc9421:{headers:a,method:n,url:r,...e.bodyText&&{body:e.bodyText}}},evidence:{...u&&{signatureAgent:u},...g&&{registryHint:g},keyid:l.match(/keyid="([^"]+)"/)?.[1],...s}}}let m=f(e,"timestamp");if(y&&!l&&(m||f(e,"idempotency-key")))return{protocol:"acp",artifacts:{acpRequest:{method:n,url:r,headers:a,...e.bodyText&&{rawBody:e.bodyText},...i&&{body:i}}},evidence:{hasTimestamp:!!m,...s}};if(/\/checkout[-_]sessions(\/|$)/.test(e.uri))return{protocol:"ucp",artifacts:{ucpRequest:{method:n,url:r,...i&&{body:i}}},evidence:{path:e.uri,...s}};if(i){let u=i.intent_mandate??i.intentMandate,g=i.cart_mandate??i.cartMandate,h=i.payment_mandate??i.paymentMandate;if(typeof u=="string"||typeof g=="string"||typeof h=="string")return{protocol:"ap2",artifacts:{ap2Mandates:{...typeof u=="string"&&{intent:u},...typeof g=="string"&&{cart:g},...typeof h=="string"&&{payment:h}}},evidence:{mandatesPresent:[typeof u=="string"&&"intent",typeof g=="string"&&"cart",typeof h=="string"&&"payment"].filter(Boolean),...s}}}if(o&&/^Payment\s+/i.test(o)||f(e,"payment-authorization"))return{protocol:"mpp",artifacts:{mppRequest:{method:n,url:r,headers:a,...e.bodyText&&{rawBody:e.bodyText},...i&&{body:i}}},evidence:s};if(f(e,"payment-signature")||f(e,"x-payment"))return{protocol:"x402",artifacts:{x402Request:{method:n,url:r,headers:a,...i&&{body:i}}},evidence:s}}var _t=/\.(css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|pdf|txt|xml)$/i,Ut=/^astrasync-sdk\//i,Pt=/curl|wget|python-requests|python-urllib|node-fetch|axios|got|okhttp|go-http-client|libwww|httpie|java\/|ruby|php|scrapy|headless|phantomjs|selenium|playwright|puppeteer|bot|crawler|spider|slurp/i,kt=/mozilla\/\d/i,xt=/^kya_[A-Za-z0-9_-]+$/;function X(e){return typeof e=="string"&&xt.test(e)}function Mt(e,t){if(_t.test(t))return{mode:e.mode,depth:e.depth,skip:!0};let r=$e(e.pathRules,t);return r?{mode:r.mode??e.mode,depth:r.depth??e.depth,skip:r.skip===!0,...r.sampling&&{sampling:r.sampling}}:{mode:e.mode,depth:e.depth,skip:!1}}function Ot(e,t,r){let n=f(e,"user-agent")??"";if(Ut.test(n))return{tier:"self"};let a=se(e.headers,{});if(!a.astraId&&(X(a.jwt)||X(a.apiKey)))return{tier:"self",evidence:{firstPartyApiKey:!0}};if(a.astraId)return{tier:"verified",protocol:"x-astra"};let{apiKeyFormat:i,platformHeaders:s}=re(e.headers),o={userAgent:n,apiKeyFormat:i,platformHeaders:s};if(r!=="classify"){let d=Ct(e,t);if(d)return{tier:"identified",protocol:d.protocol,artifacts:d.artifacts,evidence:d.evidence,fingerprint:H(o)}}let c=H(o);return c?{tier:"identified",protocol:"platform-ua",fingerprint:c}:!n||Pt.test(n)||!kt.test(n)?{tier:"anonymous-bot",evidence:{userAgent:n||"(none)"}}:!f(e,"sec-fetch-mode")&&!f(e,"accept-language")?{tier:"anonymous-bot",evidence:{userAgent:n,spoofedBrowser:!0}}:{tier:"human"}}var Dt={"vi-sd-jwt":"This request presented Visa Intelligent Commerce credentials, but the agent is not verified with AstraSync. Register the agent to pair your VI credentials with a verified identity and mandate.","rfc9421-agent-pay":"This request carried a Mastercard Agent Pay signature, but the agent is not verified with AstraSync. Register the agent to pair Agent Pay credentials with a verified identity and mandate.","rfc9421-tap":"This request carried a Visa TAP signature, but the agent is not verified with AstraSync. Register the agent to pair TAP credentials with a verified identity and mandate.","rfc9421-web-bot-auth":"This request carried a Web Bot Auth signature, but the agent is not verified with AstraSync. Register the agent to link your signed-agent identity to a verified principal.",rfc9421:"This request carried an RFC 9421 HTTP message signature, but the agent is not verified with AstraSync. Register the agent to link the signing identity to a verified principal.",acp:"This request used the Agentic Commerce Protocol, but the agent is not verified with AstraSync. Register the agent to transact on this property.",ucp:"This request used a UCP checkout session, but the agent is not verified with AstraSync. Register the agent to transact on this property.",ap2:"This request presented AP2 mandates, but the agent is not verified with AstraSync. Register the agent to pair your mandates with a verified identity.",mpp:"This request presented MPP payment credentials, but the agent is not verified with AstraSync. Register the agent to transact on this property.",x402:"This request used x402 payment headers, but the agent is not verified with AstraSync. Register the agent to transact on this property.","platform-ua":"This traffic was identified as a platform AI agent without AstraSync credentials. Register the agent to access this property with a verified identity.","x-astra":"The presented AstraSync credentials failed verification or were denied by this property\u2019s access policy."};function Nt(e){try{let t=new URL(e).hostname.replace(/^www\./,"");if(t==="astrasync.ai"||t.endsWith(".astrasync.ai"))return`https://mcp.${t}/mcp`}catch{}}function Ft(e,t,r){let n=(r||t).replace(/\/api\/?$/,""),a=e.guidance?.mcp?.endpoint||Nt(n),i=(e.protocol&&Dt[e.protocol])??"This request could not be verified by AstraSync.";return{success:!1,error:{code:e.tier==="verified"?"INSUFFICIENT_ACCESS":"UNAUTHORIZED",message:i,...e.protocol&&{protocol:e.protocol},failures:e.reasons,...e.correlationId&&{correlationId:e.correlationId},guidance:{message:e.guidance?.message||"Register this agent with AstraSync to receive verifiable credentials.",registrationUrl:e.guidance?.registrationUrl||`${n}/register`,documentationUrl:e.guidance?.documentationUrl||`${n}/docs/edge-adapter`,...a&&{mcp:{endpoint:a,discoveryUrl:e.guidance?.mcp?.discoveryUrl||`${a.replace(/\/mcp$/,"")}/.well-known/mcp.json`,message:e.guidance?.mcp?.message||"Inside an MCP host? Add the AstraSync MCP connector at this endpoint instead of the registration URL \u2014 registration through the connector is keyless and human-approved (your human approves in an in-chat card; you never handle credentials)."}}}}}}function $t(e){return{success:!1,error:{code:"VERIFICATION_UNAVAILABLE",message:"Agent verification is temporarily unavailable and this path enforces verification. Your identity was not evaluated and no denial was recorded \u2014 retry with exponential backoff.",failures:e.reasons,...e.correlationId&&{correlationId:e.correlationId},guidance:{message:"Retry the request with exponential backoff; the condition is transient."}}}}function Bt(e){return{success:!1,status:"manual_review",message:"This action requires human approval. Poll the step-up approval endpoint and retry once approved.",...e.stepUp&&{stepUpApproval:e.stepUp},...e.correlationId&&{correlationId:e.correlationId}}}var Lt="X-Astra-Verified-Hop";function jt(e){return`${e.astraId};${e.sessionId??""};${e.checkedAt}`}var S={trustScore:"X-AstraSync-Trust-Score",agentId:"X-AstraSync-Agent-Id",developerId:"X-AstraSync-Developer-Id",observedDecision:"X-AstraSync-Observed-Decision"},q=["x-astrasync-","x-astra-verified-hop"];function M(){return{action:"pass",injectHeaders:{},stripHeaderPrefixes:[]}}function Ht(e,t,r){let n={};if(t.misconfig&&(n[S.observedDecision]="misconfig"),r.mode!=="enforce")return t.decision!=="allow"&&(n[S.observedDecision]=t.decision),Object.assign(n,Y(t),J(t)),{action:"pass",injectHeaders:n,stripHeaderPrefixes:q};switch(t.decision){case"deny":return t.unavailable?{action:"respond",status:503,headers:{"Retry-After":"30"},bodyJson:$t(t)}:{action:"respond",status:403,headers:{},bodyJson:Ft(t,e.apiBaseUrl,e.publicBaseUrl)};case"manual_review":return{action:"respond",status:202,headers:{"Retry-After":"30"},bodyJson:Bt(t)};default:return Object.assign(n,Y(t),J(t)),{action:"pass",injectHeaders:n,stripHeaderPrefixes:q}}}function Y(e){if(!e.asat)return{};let{trustScore:t,agentId:r,developerId:n}=e.asat;return{...t!==void 0&&{[S.trustScore]:String(t)},...r&&{[S.agentId]:r},...n&&{[S.developerId]:n}}}function J(e){let t=e.asat?.agentId;return t?{[Lt]:jt({astraId:t,...e.sessionId&&{sessionId:e.sessionId},checkedAt:Date.now()})}:{}}var Kt={GET:"data.read",HEAD:"data.read",OPTIONS:"data.read",POST:"data.write",PUT:"data.write",PATCH:"data.write",DELETE:"data.delete"},Vt="data.write",Gt="data";function zt(e){return Kt[e.toUpperCase()]??Vt}function Xt(e){let t=e.indexOf(":");if(t>=0)return{purpose:e.slice(0,t)};let r=e.indexOf(".");return r>0&&r<e.length-1?{purpose:e.slice(0,r),actionCandidate:e}:{purpose:e}}function qt(e){let t=e.astraPurpose?Xt(e.astraPurpose):void 0,r,n;e.routeAction?(r=e.routeAction,n="route_config"):e.hasCustomActionExtractor&&e.customAction?(r=e.customAction,n="custom_extractor"):!e.hasCustomActionExtractor&&e.astraAction?(r=e.astraAction,n="header"):!e.hasCustomActionExtractor&&t?.actionCandidate?(r=t.actionCandidate,n="purpose_header_derived"):(r=zt(e.method),n="method_table");let a,i;if(e.routePurpose?(a=e.routePurpose,i="route_config"):e.hasCustomPurposeExtractor?e.customPurpose&&(a=e.customPurpose,i="custom_extractor"):t?(a=t.purpose,i="header"):e.legacyPurpose?(a=e.legacyPurpose,i="legacy_header"):e.queryPurpose&&(a=e.queryPurpose,i="query"),!a){let s=r.indexOf(".");s>0?(a=r.slice(0,s),i="action_derived"):(a=Gt,i="transport_default")}return{purpose:a,action:r,purposeSource:i,actionSource:n}}async function _(e,t){let r;try{return await Promise.race([e,new Promise(n=>{r=setTimeout(()=>n(void 0),t)})])}catch{return}finally{r&&clearTimeout(r)}}var Yt=(()=>{let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`})(),Jt=e=>`${e.apiBaseUrl}\0${e.apiKey??""}\0${e.counterparty}\0${e.adapter??""}`,Wt=class{constructor(e={}){this.queue=[],this.droppedSinceLast=0,this.droppedTotal=0,this.deliveredTotal=0,this.enqueuedTotal=0,this.backoffUntil=0,this.collapse=new Map,this.rejectedKeys=new Set,this.opts={maxItems:e.maxItems??1e3,maxBatch:e.maxBatch??100,maxAttempts:e.maxAttempts??3,collapseWindowMs:e.collapseWindowMs??6e4,collapseMaxKeys:e.collapseMaxKeys??1e3,requestTimeoutMs:e.requestTimeoutMs??1e4,retryBackoffMs:e.retryBackoffMs??1e3,holdRepeats:e.holdRepeats??!1,containerId:e.containerId??Yt,now:e.now??Date.now}}enqueue(e,t,r){let n=this.opts.now();if(r){let a=this.collapse.get(r);if(a&&n-a.firstSeenAt<this.opts.collapseWindowMs){for(let s of[a.first,a.held])if(s&&!s.inFlight&&this.queue.includes(s)){s.item.repeatCount=(s.item.repeatCount??1)+1;return}if(this.opts.holdRepeats){a.held=this.push(e,{...t,repeatCount:1},a.firstSeenAt+this.opts.collapseWindowMs);return}a.first=this.push(e,{...t,repeatCount:1},n);return}if(this.collapse.delete(r),this.collapse.size>=this.opts.collapseMaxKeys){let s=this.collapse.keys().next().value;s!==void 0&&this.collapse.delete(s)}let i={firstSeenAt:n};this.collapse.set(r,i),i.first=this.push(e,t,n);return}this.push(e,t,n)}flush(){return this.inFlight||(this.inFlight=this.drain().finally(()=>{this.inFlight=void 0})),this.inFlight}stats(){return{queueDepth:this.queue.length,droppedSinceLast:this.droppedSinceLast,droppedTotal:this.droppedTotal,deliveredTotal:this.deliveredTotal,enqueuedTotal:this.enqueuedTotal,flushing:this.inFlight!==void 0}}push(e,t,r){for(;this.queue.length>=this.opts.maxItems;)this.dropOldest();let n={dest:e,destKey:Jt(e),item:t,attempts:0,eligibleAt:r,inFlight:!1};return this.queue.push(n),this.enqueuedTotal+=1,n}dropOldest(){this.queue.shift()&&this.countDropped(1)}countDropped(e){this.droppedSinceLast+=e,this.droppedTotal+=e}async drain(){for(;;){let e=this.opts.now();if(e<this.backoffUntil)return;let t=this.takeBatch(e);if(t.length===0||!await this.send(t))return}}takeBatch(e){let t=this.queue.find(a=>a.eligibleAt<=e);if(!t)return[];let r=[],n=[];for(let a of this.queue)r.length<this.opts.maxBatch&&a.destKey===t.destKey&&a.eligibleAt<=e?(a.inFlight=!0,r.push(a)):n.push(a);return this.queue=n,r}async send(e){let t=e[0].dest,r=t.apiKey&&!this.rejectedKeys.has(t.apiKey)?t.apiKey:void 0,n=this.droppedSinceLast,a={droppedSinceLast:n,queueDepth:this.queue.length,adapter:t.adapter??"edge-core",version:D,containerId:this.opts.containerId,enqueuedTotal:this.enqueuedTotal,deliveredTotal:this.deliveredTotal,droppedTotal:this.droppedTotal},i=typeof AbortController<"u"?new AbortController:void 0,s=await _(E(`${t.apiBaseUrl}/verification-activity/edge-events`,{method:"POST",headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`}},body:JSON.stringify({events:e.map(c=>c.item),meta:a}),...i&&{signal:i.signal}}),this.opts.requestTimeoutMs);s||i?.abort();let o=s?.status;for(let c of e)c.inFlight=!1;if(o!==void 0&&o>=200&&o<300)return this.droppedSinceLast=Math.max(0,this.droppedSinceLast-n),this.deliveredTotal+=e.length,!0;if(o===401&&r)return this.rejectedKeys.add(r),this.requeue(e,!1),!0;if(o===429){let c=Number(s?.headers.get("retry-after")),d=Number.isFinite(c)&&c>0?Math.min(c,120)*1e3:3e4;return this.backoffUntil=this.opts.now()+d,this.requeue(e,!1),!1}return o!==void 0&&o>=400&&o<500?(this.countDropped(e.length),!0):(this.backoffUntil=this.opts.now()+this.opts.retryBackoffMs,this.requeue(e,!0),!1)}requeue(e,t){let r=[];for(let n of e)t&&(n.attempts+=1),n.attempts>=this.opts.maxAttempts?this.countDropped(1):r.push(n);for(this.queue=[...r,...this.queue];this.queue.length>this.opts.maxItems;)this.dropOldest()}},Zt=new Wt;function Qt(){return Zt}async function W(e,t,r,n,a,i){let s=mt(t),o=te(f(t,"x-astra-source")),c=f(t,"user-agent"),d={...e.counterpartyId&&{counterpartyId:e.counterpartyId},...e.counterpartyUrl&&{counterpartyUrl:e.counterpartyUrl},counterpartyType:"website",sourceIp:t.clientIp,userAgent:c,requestPath:t.uri,requestMethod:t.method,...s&&{attemptId:s},referer:f(t,"referer"),accept:f(t,"accept"),...o&&{declaredSource:o},protocol:r.protocol,evidence:r.evidence,observedMetadata:N(t,a),observedAt:new Date().toISOString()};for(let l of Object.keys(d))d[l]===void 0&&delete d[l];let p=Qt();p.enqueue({apiBaseUrl:e.apiBaseUrl,...i&&{apiKey:i},counterparty:e.counterpartyId||e.counterpartyUrl,...e.adapter&&{adapter:e.adapter}},d,t.clientIp?[e.counterpartyId||e.counterpartyUrl,t.clientIp,c??"",t.method,t.uri,s??""].join("\0"):void 0);let y=p.flush();if(e.waitUntil){e.waitUntil(y);return}await _(y,n)}function er(e,t=Math.random){return e<=0?!1:e>=1?!0:t()<e}function A(e){return{tier:e.tier,decision:"allow",reasons:[],protocol:e.protocol}}function Z(e,t,r,n,a){let i=qt({method:t.method,astraPurpose:f(t,"x-astra-purpose"),astraAction:f(t,"x-astra-action")}),s=f(t,"x-astra-attempt-id"),o=te(f(t,"x-astra-source"));return{...s&&/^att_[0-9a-f]{32}$/.test(s)&&{attemptId:s},credentials:se(t.headers,{}),purpose:i.purpose,action:i.action,resource:t.uri,createSession:!0,counterpartyType:"website",counterpartyUrl:e.counterpartyUrl,callerMetadata:{sourceIp:t.clientIp,userAgent:f(t,"user-agent"),referer:f(t,"referer"),host:f(t,"host"),...o&&{declaredSource:o},observedMetadata:N(t,a)},...n&&r.artifacts&&{commerceArtifacts:r.artifacts}}}function Q(e,t){let r=A(e);return r.sessionId=t.sessionId,r.correlationId=t.correlationId,r.guidance=t.guidance,t.misconfigured?(r.reasons=["verification key misconfigured \u2014 fail-open (merchant_misconfig)"],r.misconfig=!0,r):t.requiresStepUp||t.stepUpApproval?(r.decision="manual_review",r.reasons=["step-up approval required"],r.stepUp={pollUrl:t.stepUpApproval?.pollUrl,approvalUrl:t.stepUpApproval?.approvalUrl,expiresAt:t.stepUpApproval?.expiresAt},r):!t.identityVerified||!t.policyAllowed?(r.decision="deny",r.reasons=t.denialReasons?.length?t.denialReasons:[t.identityVerified?"denied by access policy":"identity not verified"],r):(r.asat={trustScore:t.agent?.trustScore,agentId:t.agent?.astraId,developerId:t.developer?.astradId},r)}function T(e,t,r,n){let a=A(e);return a.unavailable=!0,a.reasons=[r],n&&(a.correlationId=n),t.mode==="enforce"&&(a.decision="deny"),a}function ee(e){return(e.failures??[]).some(t=>t.dimension==="verify_access.api_error")===!0&&!e.misconfigured}async function tr(e,t,r,n,a,i){let{sampling:s,queryValueAllowlist:o}=i,c=e.budgets??{},d=c.beaconMs??300,p=n.mode==="enforce"?c.verifyEnforceMs??3e3:c.verifyObserveMs??1500,y={apiBaseUrl:e.apiBaseUrl,...a&&{apiKey:a},counterpartyId:e.counterpartyId,disableInitChecks:!0};try{switch(r.tier){case"verified":{if(n.depth==="classify")return A(r);let l=await _(G(y,Z(e,t,r,n.depth==="authorize",o)),p);return l?ee(l)?T(r,n,l.denialReasons?.[0]??"verify-access api error",l.correlationId):Q(r,l):T(r,n,"verify-access unreachable within budget")}case"identified":{if(n.depth==="authorize"&&r.artifacts){let m=await _(G(y,Z(e,t,r,!0,o)),p);return m?ee(m)?T(r,n,m.denialReasons?.[0]??"verify-access api error",m.correlationId):Q(r,m):T(r,n,"verify-access unreachable within budget")}await W(e,t,r,d,o,a);let l=A(r);return n.mode==="enforce"&&n.depth!=="classify"&&(l.decision="deny",l.reasons=["agent is not registered with AstraSync"]),l}case"anonymous-bot":return er(s.anonymousBeaconRate,e.random)&&await W(e,t,{...r,protocol:r.protocol??"ua-heuristic"},d,o,a),A(r);default:return A(r)}}catch(l){let m=A(r);return m.reasons=[`edge pipeline error \u2014 fail-open: ${l instanceof Error?l.message:String(l)}`],m}}async function de(e,t,r,n){let a=Mt(r,t.uri);try{if(a.skip)return{policy:a,application:M()};let i=f(t,"x-forwarded-host")??f(t,"host")??new URL(e.counterpartyUrl).host,s=Ot(t,i,a.depth);if(s.tier==="human"||s.tier==="self")return{policy:a,classification:s,application:M()};let o=nr(t,r.minTls);if(o){if(a.mode==="enforce")return e.log?.("info",`TLS ${o.negotiated} below ${o.minimum}: ${t.method} ${t.uri}`),{policy:a,classification:s,application:ar(o)};e.log?.("info",`[OBSERVE] would have required TLS ${o.minimum} (got ${o.negotiated}): ${t.method} ${t.uri}`)}let c=await tr(e,t,s,a,n,{sampling:a.sampling??r.sampling,queryValueAllowlist:r.queryValueAllowlist});return c.decision!=="allow"&&e.log?.("info",a.mode==="enforce"?`${c.decision.toUpperCase()}: ${t.method} ${t.uri}`:`[OBSERVE] would have been ${c.decision.toUpperCase()}: ${t.method} ${t.uri}`,{tier:c.tier,protocol:c.protocol,reasons:c.reasons}),{policy:a,classification:s,outcome:c,application:Ht(e,c,a)}}catch(i){return e.log?.("error","edge evaluation error \u2014 passing request through",{error:i instanceof Error?i.message:String(i)}),{policy:a,application:M()}}}function rr(e){let t=e.connection?.tlsVersion??f(e,"cloudfront-viewer-tls"),r=t?/^TLSv(1(?:\.\d)?)/i.exec(t):null;return r?r[1]==="1"?"1.0":r[1]:null}function nr(e,t){if(!t)return null;let r=rr(e);return r&&Number(r)<Number(t)?{minimum:t,negotiated:r}:null}function ar(e){return{action:"respond",status:426,headers:{"content-type":"application/json",upgrade:`TLS/${e.minimum}`,connection:"Upgrade"},bodyJson:{error:"tls_version_too_low",minimum:`TLS ${e.minimum}`,negotiated:`TLS ${e.negotiated}`,message:`This endpoint requires TLS ${e.minimum} or later for agent requests. Reconnect with TLS ${e.minimum}.`}}}function U(e){return e.Records[0].cf.request}function w(e,t){return e.headers[t.toLowerCase()]?.[0]?.value}function or(e){let t={};for(let[r,n]of Object.entries(e))n?.length&&(t[r]=n.map(a=>a.value).join(", "));return t}function ir(e){let t=e.body;return t?.data?{text:t.encoding==="base64"?Buffer.from(t.data,"base64").toString("utf8"):t.data,truncated:t.inputTruncated===!0}:{truncated:!1}}function ue(e){let t=e?.trim();if(!t)return;let r=/^\[([^\]]+)\](?::(\d+))?$/.exec(t);if(r)return{ip:r[1],...r[2]&&{port:r[2]}};let n=/:(\d+)$/.exec(t),a=n?t.slice(0,-n[0].length):t;if(a)return{ip:a,...n&&{port:n[1]}}}function sr(e){let t={},r=(i,s,o)=>{let c=w(e,s);c&&(t[i]=o?o(c):c)},n=ue(w(e,"cloudfront-viewer-address"));n&&(t.ip=n.ip,n.port&&(t.sourcePort=n.port)),r("country","cloudfront-viewer-country"),r("countryName","cloudfront-viewer-country-name"),r("region","cloudfront-viewer-country-region"),r("countryRegionName","cloudfront-viewer-country-region-name"),r("city","cloudfront-viewer-city"),r("latitude","cloudfront-viewer-latitude"),r("longitude","cloudfront-viewer-longitude"),r("postalCode","cloudfront-viewer-postal-code"),r("asn","cloudfront-viewer-asn"),r("tlsVersion","cloudfront-viewer-tls");{let i=w(e,"cloudfront-viewer-tls")?.split(":")[1];i&&(t.tlsCipher=i)}r("httpVersion","cloudfront-viewer-http-version"),r("timeZone","cloudfront-viewer-time-zone"),r("metroCode","cloudfront-viewer-metro-code"),r("tlsFingerprint","cloudfront-viewer-ja3-fingerprint"),r("ja4","cloudfront-viewer-ja4-fingerprint"),r("headerOrder","cloudfront-viewer-header-order",i=>i.slice(0,256)),r("headerCount","cloudfront-viewer-header-count");let a=[];for(let[i,s]of[["desktop","cloudfront-is-desktop-viewer"],["mobile","cloudfront-is-mobile-viewer"],["tablet","cloudfront-is-tablet-viewer"],["smarttv","cloudfront-is-smarttv-viewer"]])w(e,s)==="true"&&a.push(i);return a.length&&(t.device=a.join(",")),t}function le(e){let t=ir(e),r=sr(e),n=ue(w(e,"cloudfront-viewer-address"))?.ip;return{method:e.method,uri:e.uri,querystring:e.querystring??"",headers:or(e.headers),...t.text!==void 0&&{bodyText:t.text},...t.truncated&&{bodyTruncated:!0},...n&&{clientIp:n},...Object.keys(r).length>0&&{connection:r}}}function pe(e,t){if(t.action==="respond")return dr(t.status,t.bodyJson,t.headers);for(let r of t.stripHeaderPrefixes)cr(e,r);for(let[r,n]of Object.entries(t.injectHeaders))F(e,r,n);return e}function fe(e){let t=e.origin?.custom?.domainName??e.origin?.s3?.domainName??void 0;if(!t)return;let r=w(e,"host");!r||r===t||(w(e,"x-forwarded-host")||F(e,"X-Forwarded-Host",r),F(e,"Host",t))}function F(e,t,r){e.headers[t.toLowerCase()]=[{key:t,value:r}]}function cr(e,t){let r=t.toLowerCase();for(let n of Object.keys(e.headers))n.startsWith(r)&&delete e.headers[n]}function dr(e,t,r){let n={"content-type":[{key:"Content-Type",value:"application/json"}]};for(let[a,i]of Object.entries(r??{}))n[a.toLowerCase()]=[{key:a,value:i}];return{status:String(e),statusDescription:e===403?"Forbidden":e===202?"Accepted":"OK",headers:n,body:JSON.stringify(t)}}var ur="5.15.0",P=`astrasync-sdk/${ur}`;function lr(e){if(!e)return{"user-agent":P};if(e instanceof Headers){let r=new Headers(e);return r.has("user-agent")||r.set("user-agent",P),r}return Array.isArray(e)?e.some(([n])=>n.toLowerCase()==="user-agent")?e:[...e,["user-agent",P]]:Object.keys(e).some(r=>r.toLowerCase()==="user-agent")?e:{"user-agent":P,...e}}var pr=(e,t)=>fetch(e,{...t,headers:lr(t?.headers)});var B=Object.freeze({version:1,mode:"observe",depth:"classify",pathRules:[],sampling:Object.freeze({anonymousBeaconRate:1}),failurePosture:"open"}),ge=["observe","enforce"],ye=["classify","authenticate","authorize"];function he(e){if(typeof e!="object"||e===null)return!1;let t=e.anonymousBeaconRate;return typeof t=="number"&&t>=0&&t<=1}function fr(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.version!==1||!ge.includes(t.mode)||!ye.includes(t.depth)||!Array.isArray(t.pathRules))return!1;for(let r of t.pathRules){if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.pattern!="string"||n.pattern.length===0||n.mode!==void 0&&!ge.includes(n.mode)||n.depth!==void 0&&!ye.includes(n.depth)||n.sampling!==void 0&&!he(n.sampling))return!1}return!he(t.sampling)||t.minTls!==void 0&&t.minTls!=="1.2"&&t.minTls!=="1.3"||t.queryValueAllowlist!==void 0&&(!Array.isArray(t.queryValueAllowlist)||t.queryValueAllowlist.length>16||!t.queryValueAllowlist.every(r=>typeof r=="string"&&r.length>0&&r.length<=64))?!1:t.failurePosture==="open"}async function gr(e,t,r){if(!t)return null;let n={Accept:"application/json"};e.apiKey&&(n.Authorization=`Bearer ${e.apiKey}`,n["X-API-Key"]=e.apiKey),r?.etag&&(n["If-None-Match"]=r.etag);try{let a=await pr(`${e.apiBaseUrl}/endpoints/${encodeURIComponent(t)}/edge-config`,{method:"GET",headers:n,signal:AbortSignal.timeout(r?.timeoutMs??5e3)});if(a.status===304)return{notModified:!0};if(!a.ok)return null;let s=(await a.json()).data?.edgeConfig;return fr(s)?{edgeConfig:s,etag:a.headers.get("etag")??void 0}:null}catch{return null}}var yr=60*1e3,hr=1440*60*1e3,I=new Map,$=new Map;function ve(e,t){return`${e}|${t}`}function mr(e){return e.mode!=="enforce"&&!e.pathRules.some(t=>t.mode==="enforce")?e:{...e,mode:"observe",pathRules:e.pathRules.map(t=>t.mode==="enforce"?{...t,mode:"observe"}:t)}}async function me(e,t){let r=ve(e.apiBaseUrl,t),n=$.get(r);if(n)return n;let a=gr(e,t,{etag:I.get(r)?.etag}).then(i=>{if(i===null)return;let s=Date.now();if("notModified"in i){let o=I.get(r);o&&(o.lastSuccessAt=s);return}I.set(r,{config:i.edgeConfig,etag:i.etag,lastSuccessAt:s})}).finally(()=>{$.delete(r)});return $.set(r,a),a}async function Ae(e,t,r){let n=r?.ttlMs??yr,a=r?.maxStaleMs??hr,i=ve(e.apiBaseUrl,t),s=I.get(i);if(s){let o=Date.now()-s.lastSuccessAt;return o>n&&me(e,t).catch(()=>{}),o>a?mr(s.config):s.config}return await me(e,t).catch(()=>{}),I.get(i)?.config??B}var vr=900*1e3,we=new Map;async function Ar(e){let{SecretsManagerClient:t,GetSecretValueCommand:r}=await import("@aws-sdk/client-secrets-manager");return(await new t({region:"us-east-1"}).send(new r({SecretId:e}))).SecretString??void 0}async function Se(e){if(e.apiKey)return e.apiKey;let t=e.apiKeySecretName;if(!t)return;let r=we.get(t);if(r&&Date.now()-r.fetchedAt<vr)return r.value;try{let a=await(e.fetchSecret??Ar)(t);return we.set(t,{value:a,fetchedAt:Date.now()}),a}catch(n){return e.log?.("warn","Secrets Manager fetch failed \u2014 continuing keyless",{secretName:t,error:n instanceof Error?n.message:String(n)}),r?.value}}async function Ie(e,t){try{return await Ae({apiBaseUrl:e.apiBaseUrl,apiKey:t},e.counterpartyId,{ttlMs:e.configTtlMs})}catch{return e.fallbackConfig??B}}function be(e){let t=e.log??((r,n,a)=>{console[r==="info"?"log":r](`[astrasync-edge] ${n}`,a??"")});return async function(n){let a=U(n);try{fe(a);let i=await Se({...e,log:t}),s=await Ie(e,i),{application:o}=await de({...e,adapter:"lambda-edge",log:t},le(a),s,i);return pe(a,o)}catch(i){return t("error","edge handler error \u2014 passing request through",{error:i instanceof Error?i.message:String(i)}),a}}}var wr={apiBaseUrl:"x-astrasync-api-base-url",publicBaseUrl:"x-astrasync-public-base-url",counterpartyId:"x-astrasync-counterparty-id",counterpartyUrl:"x-astrasync-counterparty-url",apiKeySecretName:"x-astrasync-api-key-secret-name"};function Sr(e,t){return e.origin?.custom?.customHeaders?.[t]?.[0]?.value||void 0}function Re(e,t){let r=n=>Sr(e,wr[n]);return{apiBaseUrl:r("apiBaseUrl")??t.apiBaseUrl,publicBaseUrl:r("publicBaseUrl")??t.publicBaseUrl,counterpartyId:r("counterpartyId")??t.counterpartyId,counterpartyUrl:r("counterpartyUrl")??t.counterpartyUrl,apiKeySecretName:r("apiKeySecretName")??t.apiKeySecretName}}function Te(e){return[e.apiBaseUrl,e.publicBaseUrl??"",e.counterpartyId,e.counterpartyUrl,e.apiKeySecretName??""].join("|")}var Ir={apiBaseUrl:"https://astrasync.ai/api",publicBaseUrl:void 0,counterpartyId:"",counterpartyUrl:"",apiKeySecretName:void 0},Ee=new Map,Ce=!1,br=async e=>{let t=Re(U(e),Ir);(!t.counterpartyId||!t.counterpartyUrl)&&(Ce||(Ce=!0,console.error("[astrasync-edge] counterpartyId/counterpartyUrl missing \u2014 set the X-AstraSync-* origin custom headers on the distribution (see infra/template.yaml) or bake ASTRASYNC_* constants via infra/deploy.sh.")));let r=Te(t),n=Ee.get(r);return n||(n=be(t),Ee.set(r,n)),n(e)};0&&(module.exports={handler});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astrasyncai/adapter-lambda",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.12.0",
|
|
4
4
|
"description": "AstraSync Trusted Agent Gateway — Lambda@Edge/CloudFront adapter",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"directory": "packages/adapter-lambda"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@astrasyncai/verification-gateway": "^5.
|
|
50
|
+
"@astrasyncai/verification-gateway": "^5.15.0",
|
|
51
51
|
"@aws-sdk/client-secrets-manager": "^3.632.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|