mppx 0.21.3 → 0.21.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# mppx
|
|
2
2
|
|
|
3
|
+
## 0.21.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8b6b501: Required an explicit host allowlist or fixed Node host before accepting signed identity headers in Node and Express adapters. Unconfigured adapters now return 421 for those requests.
|
|
8
|
+
|
|
3
9
|
## 0.21.3
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/dist/cli/cli.js
CHANGED
|
@@ -263,7 +263,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
263
263
|
`))a.push(o.join(``)+i.slice(0,e)),o=[],s=0,i=i.slice(e+2);i&&(o.push(i),s+=i.length),n&&(a.push(o.join(``)),o=[],s=0),l&&a.length>0&&(a.shift(),l=!1),s>1048576&&(o=o.at(-1)?.endsWith(`
|
|
264
264
|
`)?[`
|
|
265
265
|
`]:[],s=o.length,l=!0);for(let e of a){let n=kO(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}YA();const BB={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function VB(e){let t=BB[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function HB(e){console.log(`\n${X.bold(e)}`)}function UB(e,t){for(let n of e)VB(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}Rx(),YA();const WB=vb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||AA()){let t=await gB({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1,payment:MB});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of hB({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>UB(e,n),payment:MB}))switch(t.phase){case`discovery`:if(HB(`Discovery (/openapi.json)`),UB(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=mB.split(`
|
|
266
|
-
`);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,HB(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),UB(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),UB(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}GB(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function GB(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function KB(e){return JB(e)?e.offers:[e]}function qB(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=YB(t.amount)??YB(i.amount)??null,o=YB(t.currency)??YB(i.currency),s=YB(e.description)??YB(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function JB(e){return`offers`in e&&!(`_canonicalRequest`in e)}function YB(e){return typeof e==`string`?e:void 0}var XB=R((()=>{})),ZB=at({generate:()=>QB,generateProxy:()=>$B});function QB(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>tV(e,r));return eV({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function $B(e){let t=e.routes.map(t=>({...t,path:nV(e.basePath,t.path)}));return eV({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function eV(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=bD.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function tV(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:KB(t).map(qB)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:aS(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:qB(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function nV(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var rV=R((()=>{sS(),ED(),XB()}));Rx(),iC(),GE(),WT(),tT(),mT(),_T(),Gx(),rS(),zC(),fT(),Iw(),fA(),lj(),YA();const iV=`0.21.3`,aV=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),oV=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),sV=p.object({message:p.string(),path:p.string(),severity:p.string()}),cV=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),lV=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function uV(e){return e.format===`json`&&e.formatExplicit}function dV(e,t,n){if(uV(e))return e.ok(t);n()}async function fV(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function pV(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function mV(e){return typeof e==`string`?e:void 0}function hV(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function gV(e){let t=hV(e);return{...mV(e.description)?{description:mV(e.description)}:{},id:mV(e.id)??mV(e.name)??`unknown`,...mV(e.name)?{name:mV(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...mV(e.status)?{status:mV(e.status)}:{},...mV(e.serviceUrl)||mV(e.url)?{url:mV(e.serviceUrl)??mV(e.url)}:{}}}function _V(e){return{...mV(e.description)?{description:mV(e.description)}:{},method:mV(e.method)??`GET`,path:mV(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function vV(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=mV(t.amount),r=mV(t.currency),i=mV(t.method),a=mV(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function yV(e){return e.request.currency??e.request.asset}function bV(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=yV(e);return typeof t==`string`&&t.toLowerCase()===n})}async function xV(e,t,n={}){let r=()=>eT().getChallenges(e),i=()=>pT().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}async function SV(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function CV(e){if(!LC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${xS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function wV(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function TV(e,t){return ZL(bV(await xV(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function EV(e){return hT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function DV(e,t){if(!LC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:xS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[_w]:lT({accepts:[fw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function OV(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function kV(e,t,n,r){let i=!1,a=t,o=OV(a),s={...n,redirect:`manual`,headers:XT(n.headers)};o.host&&NV(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=XT(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=OV(a),o.host&&NV(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function AV(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&MV(i),OV(i.href)}function jV(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(OV(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&MV(r),OV(r.href)}function MV(e){throw new z({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function NV(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function PV(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function FV(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new z({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new z({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function IV(e,t){let n=t.toLowerCase();return e.find(e=>{let t=mV(e.id)?.toLowerCase(),r=mV(e.name)?.toLowerCase();return t===n||r===n})}const LV=vb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:iV,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await tR(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=dj(),i={"User-Agent":e.options.userAgent??`mppx/${iV}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=QL(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=OV(o),f=d.url;d.host&&(i.Host=d.host);try{let r=kA(e.options.methodOpt),a=yR(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&SA(o,s,t);let p=await kV(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});CA(m,c),await fV(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await xV(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=bV(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(yV).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=$L(n?.config)?.length?v:await fL(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>CV(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=ZL(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=LC(S),ee=T?jV(p.logicalUrl,(PV(S)??m.url)||p.logicalUrl):AV(o,d,p.logicalUrl);if(!T)try{BT(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let te=DV(S,m),E=S.request.currency??``,D=S.request.decimals??6,O,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),E=A.tokenSymbol,D=A.tokenDecimals,O=A.explorerUrl);let ne=!e.options.silent&&e.options.confirm,j=new Set;{CA(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,EA(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:E,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,wA(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=TA(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,wA(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)j.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||ne){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
|
|
266
|
+
`);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,HB(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),UB(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),UB(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}GB(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function GB(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function KB(e){return JB(e)?e.offers:[e]}function qB(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=YB(t.amount)??YB(i.amount)??null,o=YB(t.currency)??YB(i.currency),s=YB(e.description)??YB(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function JB(e){return`offers`in e&&!(`_canonicalRequest`in e)}function YB(e){return typeof e==`string`?e:void 0}var XB=R((()=>{})),ZB=at({generate:()=>QB,generateProxy:()=>$B});function QB(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>tV(e,r));return eV({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function $B(e){let t=e.routes.map(t=>({...t,path:nV(e.basePath,t.path)}));return eV({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function eV(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=bD.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function tV(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:KB(t).map(qB)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:aS(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:qB(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function nV(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var rV=R((()=>{sS(),ED(),XB()}));Rx(),iC(),GE(),WT(),tT(),mT(),_T(),Gx(),rS(),zC(),fT(),Iw(),fA(),lj(),YA();const iV=`0.21.4`,aV=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),oV=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),sV=p.object({message:p.string(),path:p.string(),severity:p.string()}),cV=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),lV=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function uV(e){return e.format===`json`&&e.formatExplicit}function dV(e,t,n){if(uV(e))return e.ok(t);n()}async function fV(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function pV(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function mV(e){return typeof e==`string`?e:void 0}function hV(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function gV(e){let t=hV(e);return{...mV(e.description)?{description:mV(e.description)}:{},id:mV(e.id)??mV(e.name)??`unknown`,...mV(e.name)?{name:mV(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...mV(e.status)?{status:mV(e.status)}:{},...mV(e.serviceUrl)||mV(e.url)?{url:mV(e.serviceUrl)??mV(e.url)}:{}}}function _V(e){return{...mV(e.description)?{description:mV(e.description)}:{},method:mV(e.method)??`GET`,path:mV(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function vV(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=mV(t.amount),r=mV(t.currency),i=mV(t.method),a=mV(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function yV(e){return e.request.currency??e.request.asset}function bV(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=yV(e);return typeof t==`string`&&t.toLowerCase()===n})}async function xV(e,t,n={}){let r=()=>eT().getChallenges(e),i=()=>pT().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}async function SV(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function CV(e){if(!LC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${xS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function wV(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function TV(e,t){return ZL(bV(await xV(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function EV(e){return hT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function DV(e,t){if(!LC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:xS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[_w]:lT({accepts:[fw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function OV(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function kV(e,t,n,r){let i=!1,a=t,o=OV(a),s={...n,redirect:`manual`,headers:XT(n.headers)};o.host&&NV(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=XT(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=OV(a),o.host&&NV(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function AV(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&MV(i),OV(i.href)}function jV(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(OV(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&MV(r),OV(r.href)}function MV(e){throw new z({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function NV(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function PV(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function FV(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new z({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new z({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function IV(e,t){let n=t.toLowerCase();return e.find(e=>{let t=mV(e.id)?.toLowerCase(),r=mV(e.name)?.toLowerCase();return t===n||r===n})}const LV=vb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:iV,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await tR(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=dj(),i={"User-Agent":e.options.userAgent??`mppx/${iV}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=QL(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=OV(o),f=d.url;d.host&&(i.Host=d.host);try{let r=kA(e.options.methodOpt),a=yR(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&SA(o,s,t);let p=await kV(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});CA(m,c),await fV(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await xV(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=bV(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(yV).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=$L(n?.config)?.length?v:await fL(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>CV(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=ZL(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=LC(S),ee=T?jV(p.logicalUrl,(PV(S)??m.url)||p.logicalUrl):AV(o,d,p.logicalUrl);if(!T)try{BT(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let te=DV(S,m),E=S.request.currency??``,D=S.request.decimals??6,O,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),E=A.tokenSymbol,D=A.tokenDecimals,O=A.explorerUrl);let ne=!e.options.silent&&e.options.confirm,j=new Set;{CA(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,EA(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:E,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,wA(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=TA(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,wA(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)j.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||ne){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
|
|
267
267
|
`);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(ne&&(t(`
|
|
268
268
|
`),!await NA(`Proceed with ${S.intent}?`,!0))){t(`Aborted.
|
|
269
269
|
`);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!jA(nj(e.options.account));if(Ok(S)&&re&&!w&&!(C&&n?.config.plugins?.includes(C))){try{await bz({challenge:S,challengeResponse:te,credentialContext:await YL(S,n?.config.extensions,A?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:ee.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return lz(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:w&&Ok(S)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let M=w&&Ok(S)?void 0:await YL(S,n?.config.extensions,A?.credentialContext),N,ie;if(w&&Ok(S)){let e=te;N=await JE({methods:[w],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await YL(e,n?.config.extensions,A?.credentialContext);return rR(S,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(ee.url,{...p.init,context:M,redirect:`manual`})}else{if(h?.key===CV(S))ie=h.credential;else if(A?.createCredential)ie=await A.createCredential(te,M);else if(A)ie=await JE({methods:A.methods,polyfill:!1,transport:EV(S)}).createCredential(te,M);else if(w)ie=await JE({methods:[w],polyfill:!1,transport:EV(S)}).createCredential(te,M);else throw Error(`unreachable`);let n=T?vw:US(S),r={...XT(p.init.headers),[n]:ie};T&&NV(r,ee.host),C?.prepareCredentialRequest?.({challenge:S,credential:ie,headers:r});let i={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&SA(ee.url,i,t),N=await u(ee.url,i)}if(h=ie===void 0?void 0:{credential:ie,key:CV(S)},N.status===402&&!(w&&Ok(S))&&i+1<3&&wV(N.url,p.response.url)){let t=t=>TV(t,{config:n?.config,currency:e.options.currency,ignoreX402ResponseUrl:g,protocol:e.options.protocol}),r=new Response(null,{headers:N.headers,status:N.status,statusText:N.statusText});if(Object.defineProperty(r,"url",{value:N.url}),await t(r.clone())){await N.body?.cancel().catch(()=>{}),m=r;continue}if(e.options.protocol!==`mpp`&&!g){let e=await SV(N,1048576);if(e.complete&&await t(e.response.clone())){m=e.response;continue}N=e.response}}if(e.options.fail&&N.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${N.status}`,exitCode:22});if(N.status===402){let n=await N.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,DA(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(CA(N,c),!(ie&&await C?.handleResponse?.({challenge:S,credential:ie,response:N,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:ne,confirm:NA,tokenSymbol:E,tokenDecimals:D,explorerUrl:O,shownKeys:j}))){let n=N.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(k.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||j.has(t)||t===`reference`&&o)continue;let e=C?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${PA(BigInt(n),E,D)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&O?r.push([t,OA(`${O}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Current mppx package version. */
|
|
2
|
-
export declare const version = "0.21.
|
|
2
|
+
export declare const version = "0.21.4";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.21.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.21.4";
|
|
5
5
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/internal/version.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated by scripts/sync-version.ts.
|
|
2
2
|
/** Current mppx package version. */
|
|
3
|
-
export const version = '0.21.
|
|
3
|
+
export const version = '0.21.4';
|
|
4
4
|
/** Canonical SDK identifier for this mppx release. */
|
|
5
5
|
export const sdkIdentifier = `mppx/${version}`;
|
|
6
6
|
//# sourceMappingURL=version.js.map
|
|
@@ -25,7 +25,7 @@ export declare namespace Mppx {
|
|
|
25
25
|
}
|
|
26
26
|
/** Optional ingress validation shared by Express payment handlers. */
|
|
27
27
|
export type AdapterOptions = {
|
|
28
|
-
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it.
|
|
28
|
+
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it. Required for signed identity requests unless a fixed Node host is configured; an empty list rejects all hosts. Configure trusted ingress to enforce the same list. */
|
|
29
29
|
allowedHosts?: readonly string[] | undefined;
|
|
30
30
|
};
|
|
31
31
|
/**
|
package/dist/server/Request.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http';
|
|
2
2
|
export type FetchHandler = (request: Request) => Promise<Response> | Response;
|
|
3
3
|
export type RequestListenerOptions = {
|
|
4
|
-
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it.
|
|
4
|
+
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it. Required for signed identity requests unless a fixed Node host is configured; an empty list rejects all hosts. Validate at trusted ingress too; forwarded hosts are not trusted. */
|
|
5
5
|
allowedHosts?: readonly string[] | undefined;
|
|
6
6
|
host?: string | undefined;
|
|
7
7
|
/** Maximum accepted request body size in bytes. @default 10485760 (10 MiB) */
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
const normalizedHosts = new WeakMap();
|
|
2
2
|
/** Validates every incoming authority before Node or Express normalizes duplicate headers. */
|
|
3
3
|
export function isAllowed(request, allowedHosts, urlAuthority, allowNormalizedOnly = false) {
|
|
4
|
-
if (allowedHosts === undefined)
|
|
5
|
-
|
|
4
|
+
if (allowedHosts === undefined) {
|
|
5
|
+
// Identity signatures bind the URL; an attacker-controlled Host cannot establish its audience.
|
|
6
|
+
return (allowNormalizedOnly ||
|
|
7
|
+
!Object.keys(request.headers).some((name) => ['agent-id', 'agent-signature', 'signature', 'signature-input'].includes(name.toLowerCase())));
|
|
8
|
+
}
|
|
6
9
|
if (typeof urlAuthority !== 'string' || urlAuthority.length === 0)
|
|
7
10
|
return false;
|
|
8
11
|
const authorities = [urlAuthority];
|