@allscale/cli 1.0.1 → 1.0.2
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/README.md +38 -11
- package/dist/commands/build-info.js +12 -12
- package/dist/commands/claim-link/claim.js +10 -10
- package/dist/commands/claim-link/create.js +27 -27
- package/dist/commands/claim-link/get.js +13 -13
- package/dist/commands/claim-link/list.js +12 -12
- package/dist/commands/claim-link/status.js +11 -11
- package/dist/commands/describe.js +11 -11
- package/dist/commands/device-login.js +26 -25
- package/dist/commands/invoice/get.js +12 -12
- package/dist/commands/invoice/list.js +12 -12
- package/dist/commands/invoice/pay.js +41 -37
- package/dist/commands/invoice/received.js +12 -12
- package/dist/commands/invoice/send.js +27 -27
- package/dist/commands/invoice/sent.js +11 -11
- package/dist/commands/invoice/update.js +13 -13
- package/dist/commands/logout.js +19 -13
- package/dist/commands/operations.js +11 -11
- package/dist/commands/otp-login.js +18 -18
- package/dist/commands/otp-send.js +11 -11
- package/dist/commands/payout/send.js +13 -13
- package/dist/commands/payout/status.js +12 -12
- package/dist/commands/scope.js +17 -17
- package/dist/commands/store/create.js +13 -13
- package/dist/commands/transaction/get.js +12 -12
- package/dist/commands/transaction/list.js +12 -12
- package/dist/commands/wallet/list.js +12 -12
- package/dist/commands/wallet/send.js +25 -25
- package/dist/commands/whoami.js +14 -12
- package/dist/hooks/version-suffix.js +1 -1
- package/dist/index.js +11 -11
- package/oclif.manifest.json +23 -10
- package/package.json +1 -1
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var u=
|
|
4
|
-
`)}else me.stderr.write(t)}var
|
|
5
|
-
`);return}
|
|
1
|
+
"use strict";var Pt=Object.create;var M=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var Bt=Object.getPrototypeOf,Dt=Object.prototype.hasOwnProperty;var Ut=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},Ke=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Nt(t))!Dt.call(e,i)&&i!==n&&M(e,i,{get:()=>t[i],enumerable:!(r=xt(t,i))||r.enumerable});return e};var m=(e,t,n)=>(n=e!=null?Pt(Bt(e)):{},Ke(t||!e||!e.__esModule?M(n,"default",{value:e,enumerable:!0}):n,e)),$t=e=>Ke(M({},"__esModule",{value:!0}),e);var _r={};Ut(_r,{default:()=>te});module.exports=$t(_r);var vt=require("process");var A=require("@oclif/core");var Ye="public",He="https://app.allscale.io";var je=["https://app.allscale.io"];var re="Override the API base URL (public builds accept only https://app.allscale.io)";var ie="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function qe(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function We(e){return qe(e)!==null}function oe(e){let t=qe(e);return t!==null&&je.includes(t.origin)}function C(){return"".trim()||void 0}function w(){return"public"}function E(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function ae(e){try{return new URL(e).origin}catch{return null}}function R(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return se()}function se(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:d}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let l=typeof d=="string"?d.trim():"";i.push({base:s.trim(),key:c,keyId:l.length>0?l:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var Ft={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},Gt=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function de(e){return(typeof e=="string"?e:String(e??"")).replace(Gt,"")}var Mt=64;function ce(e,t=new Map,n=0){if(typeof e=="string")return de(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Mt)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ce(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ce(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(de(n)),this.code=t,this.details=r&&ce(r),this.name="AllscaleError"}get exitCode(){return Ft[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function ze(e){if(e instanceof a)return e;if(e instanceof Error){if(Ht(e)){let t=qt(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var Kt=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Yt=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Ht(e){if(jt(e))return!0;let t=e.name??"";return Kt.has(t)?t==="CLIError"?ue(e,"parse")||Je(e.message):!0:Je(e.message)}function jt(e){if(!ue(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&ue(e,"parse")}function Je(e){return e?de(e).split(`
|
|
2
|
+
`).some(t=>Yt.some(n=>n.test(t.trim()))):!1}function ue(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function qt(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ve(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var u=m(require("fs")),q=m(require("path")),nt=m(require("crypto"));var Wt="...<truncated>",Jt=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,zt=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,he=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,le=String.raw`(?:proxy[_-]?)?authorization`,Vt=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${le}"|'${le}'|${le})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${he}`,"gi"),Xt=/\b(https?:\/\/)[^\s/?#]+@/gi,Zt=String.raw`(?:[A-Za-z0-9]+[_-])*`,Qt=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Ze=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,Xe=Ze(Zt),en=Ze(Qt),tn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Xe}"|'${Xe}'|${en})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${he}`,"gi"),pe=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,nn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${pe}"|'${pe}'|${pe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${he}`,"g");function K(e){return e.replace(Xt,"$1<redacted>@").replace(Jt,"<redacted-jwt>").replace(Vt,"$1$2$3<redacted>").replace(tn,"$1$2<redacted>").replace(nn,"$1$2<redacted>").replace(zt,"Bearer <redacted>")}var rn=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function Y(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return rn.test(t)}function Qe(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function H(e,t,n=Wt){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",d=0;for(let l of n){let h=Buffer.byteLength(l,"utf8");if(d+h>t)break;c+=l,d+=h}return c}let i=t-r,o="",s=0;for(let c of e){let d=Buffer.byteLength(c,"utf8");if(s+d>i)break;o+=c,s+=d}return`${o}${n}`}function p(e,t=16384){return H(Qe(K(e)),t)}var fe=100,on=8,sn=8*1024;function j(){return{remaining:sn}}function ge(e,t){let n=Math.min(16384,t.remaining),r=H(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function S(e,t,n=0,r={}){if(n>on)return ge("<truncated>",t);if(typeof e=="string"){let i=K(e);return ge(r.escapeControls?Qe(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,fe),o=i.map(s=>S(s,t,n+1,r));return e.length>i.length&&o.push(ge(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,c]of o.slice(0,fe))i[s]=S(c,t,n+1,r);return o.length>fe&&(i.output_truncated=!0),i}return e}var me=require("process");var _e=!1;function Ae(e){_e=e}function Ee(){return _e}var et="1";function T(e,t){if(_e){let n={...e};delete n.version;let r=j(),i={event:n.event,...n},o=S(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:et,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:et,event:o.event,output_truncated:!0})),me.stderr.write(`${s}
|
|
4
|
+
`)}else me.stderr.write(t)}var tt="2",I=null,f=null,k=!1,v=!1;function an(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=nt.randomBytes(4).toString("hex");return q.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var be=64*1024*1024,cn=null;function ye(e={}){if(e.quiet&&(v=!0),k)return;let t=an();if(!t)return;I=null;let n=null;try{if((cn??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=q.dirname(t);if(u.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let d=u.statSync(r),l=d.mode&511;if(!d.isDirectory()||(l&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${l.toString(8).padStart(3,"0")}`)}let i=u.constants.O_NOFOLLOW??0;n=u.openSync(t,u.constants.O_APPEND|u.constants.O_CREAT|u.constants.O_WRONLY|(u.constants.O_NONBLOCK??0)|i,384);let o=u.fstatSync(n),s=u.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=o.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);u.fchmodSync(n,384)}catch(r){if(n!==null)try{u.closeSync(n)}catch{}v||T({event:"sidecar_disabled",reason:"open_failed",detail:p(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${p(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}I=t,f=n,k=!0}var un=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function dn(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return un.some(n=>n.test(t))}function rt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=ln(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)dn(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function ln(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function pn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:rt(e.url)}:e}function fn(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=S(i,j()),s=JSON.stringify({version:tt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:tt,timestamp:t,type:r,output_truncated:!0})),s}function b(e){if(!k||!I||f===null)return;let t=pn(e),n=fn(t);try{if(u.fstatSync(f).size+Buffer.byteLength(n,"utf8")+1>be){k=!1;try{u.closeSync(f)}catch{}f=null,v||T({event:"sidecar_disabled",reason:"size_limit",...I===null?{}:{path:p(I)},max_bytes:be},`${p(`[allscale] sidecar exceeded ${be} bytes; disabling it for the rest of this run. Rotate or remove ${I}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
6
|
`);return}u.appendFileSync(f,`${n}
|
|
7
|
-
`)}catch(r){if(
|
|
8
|
-
`)}catch{}}}var rt
|
|
9
|
-
The CLI default is now ${
|
|
7
|
+
`)}catch(r){if(k=!1,f!==null){try{u.closeSync(f)}catch{}f=null}try{v||T({event:"sidecar_disabled",reason:"write_failed",detail:p(r.message)},`${p(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var it=rt;function we(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function P(){if(v=!1,k=!1,f!==null){try{u.closeSync(f)}catch{}f=null}}function ot(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||we()||!t}var x=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),gn=new Set(Array.from(x).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),hn=Array.from(x).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),mn=new Set(["--otp-stdin","--password-stdin"]);function Se(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(x.has(s)){t.push(`${s}=<redacted>`);continue}}}if(x.has(r)){t.push(r),n+1<e.length&&(x.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(gn.has(o)){t.push(`${o}<redacted>`);continue}}let i=mn.has(r)?void 0:hn.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function st(e){b({type:"error",code:e.code,message:p(e.message)}),b({type:"command-end",ok:!1,exitCode:e.exitCode}),P()}var N=C()??He,B={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function Le(e){return We(e)?new URL(e).origin:null}function D(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function at(){let e=process.env[B.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Te(){let e=process.env[B.PROFILE]?.trim();return e&&e.length>0?e:void 0}function U(){let e=process.env[B.API_BASE]?.trim();return e&&e.length>0?e:void 0}function ct(){let e=process.env[B.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ut(){let e=process.env[B.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function dt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(C()===void 0&&N!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
|
|
9
|
+
The CLI default is now ${N} (production), but a saved profile wins over the default,
|
|
10
10
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
11
11
|
the old default rather than a deliberate choice.
|
|
12
12
|
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
|
-
To move to production, run: allscale device-login --api-base ${
|
|
14
|
-
`}var b=g(require("fs")),lt=g(require("os")),Te=g(require("path")),Ie=g(require("@iarna/toml"));var _n=".allscale",An="config.toml";function En(){return Te.join(lt.homedir(),_n)}function yn(){return Te.join(En(),An)}function ke(){let e=yn();if(!b.existsSync(e))return{};let t=b.readFileSync(e,"utf-8");try{return Ie.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function dt(e,t){return e.profile?.[t]}function pt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function J(e){if(!oe(e))throw new a("input.invalid",`Refusing to send credentials to API base ${C(e)}. `+ie)}function Ce(e){let t=O();if(t===void 0||E(e))return;let n=q(e),r=P();if(r.length>0){let o=r.map(c=>q(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>C(c.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${C(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=q(t);if(!(n!==null&&n===i))throw new a("input.invalid",`Refusing to send to ${C(e)} \u2014 this build only signs for ${C(t)}. Re-login against this build's environment, or use a build for that one.`)}var bn=require("@noble/hashes/sha3");var ft=["USDT","USDC"];var Jr=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var $=require("@oclif/core"),U=class e extends _.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:_.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:_.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:R()==="public"}),"api-base":_.Flags.string({description:re,helpGroup:"GLOBAL",hidden:R()==="public"}),"insecure-storage":_.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ae(this.jsonEnabled()),be(),y({type:"session-start",command:this.id??"",argv:we(this.argv)});let t=this.constructor;if(R()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&W()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=it(this.jsonEnabled()),r=this.argv.length===0&&!n&&Cn(t)?this.config.findCommand(this.id??""):void 0;if(r){x();let o=await(0,_.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!ct())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return y({type:"command-end",ok:!0}),x(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||ze(i),{data:i})}catch(t){let n=Je(t);ot({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ae(!1)}}resolveSessionApiBaseChain(t){let n=ke(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Le()!==void 0,s=pt(n,r,Le()),c=dt(n,s),l=i??W(),d=l??c?.api_base??B,m=ut({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return m&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,L({event:"legacy_staging_profile",api_base:d,profile:s},m)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||J(n),n}resolveContext(t){if(R()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&W()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(J(i),Ce(i)),{apiBase:i,profile:s,token:n??st(),insecureStorage:r||at(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${kn(t)}
|
|
15
|
-
`)}};var Sn=/_(removed|cleared|count|total)$/i;function wn(e,t){return typeof t=="number"&&Sn.test(e)}var Ln=new Set(ft);function Tn(e,t){return e==="token_symbol"&&typeof t=="string"&&Ln.has(t)}var z=100;function V(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,z),r=n.map(i=>V(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,z))n[i]=K(i)&&!wn(i,o)&&!Tn(i,o)?"<redacted>":V(o,t+1);if(r.length>z){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-z} more keys`}return n}if(typeof e=="string"){let n=In(e);return n!==void 0?p(JSON.stringify(V(n,t+1))):p(e)}return e}function In(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function kn(e){let t=Ee()?void 0:2,n=V(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:p(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Cn(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var gt=g(require("crypto")),ht=g(require("fs")),mt=g(require("path"));var On="key-id",Rn="x-allscale-cli-version",Oe="cli-1",Pn="aScaLe_cli_obf_v1",vn="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function xn(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var Nn=xn(vn,Pn),Bn=`Bearer ${Nn}`;function _t(e,t){let n=ae(e);if(n!==null)return t.find(r=>ae(r.base)===n)}function Dn(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=P();if(t.length>0){let r=_t(e,t);if(r)return r.key;if(E(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:E(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Un(e){{let r="cli-1".trim();if(r.length>0)return r}let t=P();if(t.length>0){let r=e!==void 0?_t(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&E(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Oe}if(!E(t[0].base))return Oe}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Oe}function $n(){return"1.0.1"}function Fn(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Re(e,t){let n=Dn(t);if(!n)throw Fn();let r=Un(t),i=Math.floor(Date.now()/1e3).toString(),o=gt.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Rn]:$n()};return r.length>0&&(s[On]=r),s}function Pe(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var Gn=500,Mn=8,At=100;function ve(e,t=0){if(t>Mn)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,At),r=n.map(i=>ve(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,At))n[r]=K(r)?"<redacted>":ve(i,t+1);return n}return e}function Kn(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function X(e,t=Gn){let n=Kn(e),r=n===void 0?M(e):JSON.stringify(ve(n));return Y(r,t)}var Q=256*1024,F=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Z=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function xe(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new F(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,m=d===void 0?void 0:new Promise((A,ne)=>{l=setTimeout(()=>{ne(new Z(e.status,d))},d),l.unref?.()});try{for(;;){let A=o.read(),{done:ne,value:Ge}=m?await Promise.race([A,m]):await A;if(ne)break;if(c+=Ge.byteLength,c>t)throw o.cancel().catch(()=>{}),new F(e.status,t,n.oversizeKind);s.push(Buffer.from(Ge))}}catch(A){throw A instanceof Z&&o.cancel(A).catch(()=>{}),A}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}async function Et(e,t){let n;try{n=await xe(e,t)}catch(r){if(r instanceof F)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var Mi=32*1024*1024,Ki=4*1024*1024;function Yn(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${rt(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Ne(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Yn(e.status,e.url)}}var Hn=2014;function jn(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function qn(e){return jn(e,Hn)}var Wn=1e4;async function Be(e,t=Wn){if(e.status>=200&&e.status<300)return"";try{return await xe(e,Q,{timeoutMs:t})}catch{return""}}function De(e,t){if(!(e>=200&&e<300)&&qn(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?X(t):t})}var nr=require("process");var Jn=require("process");var bt=3100,zn=2090,Vn=2001,Xn=2092,h="allscale.io";function ee(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Ue(e){try{let t=JSON.parse(e);if(typeof t.code=="number"&&Number.isInteger(t.code))return t.code;if(typeof t.code=="string"&&/^\d+$/.test(t.code)){let n=Number(t.code);if(Number.isSafeInteger(n))return n}}catch{}}function Zn(e,t){return new a("not_found",`No AllScale account exists for '${e}' on this environment. Check the address for typos, try the email the account was created with, or sign up first if you do not have an account yet.`,{status:t,backend_code:bt})}function $e(e,t,n,r,i){let o=ee(e),s=o.endsWith(`.${h}`)?`@${h} subdomains are not whitelisted \u2014 use a bare @${h} address, or contact support / wait for the backend allowlist fix.`:`Use an @${h} address, or contact support / wait for the backend allowlist fix.`,c=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${h} addresses can receive a login code here. Re-run with an @${h} address.`:`Backend returned ${t} when sending OTP to external domain '${o}'. External-domain OTP delivery is likely restricted on this environment (e.g. Cloudflare verification); only @${h} is whitelisted.`;return new a(r,c,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function Qn(e,t){return new a("auth.permission_denied","Login rejected: the email or password is incorrect. Note that AllScale Pay accounts have no password \u2014 use `allscale device-login` or `allscale otp-login` for those.",{status:e,...t===void 0?{}:{backend_code:t}})}function St(e){if(e.length===0)throw new a("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new a("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function er(e){return`'${e.replace(/'/g,"'\\''")}'`}function yt(e){return`Run \`allscale otp-send --email ${er(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}function wt(e,t,n,r){let i="incorrect, expired, already used, or locked after too many attempts";if(n){let s="This run's send step issued the otp_id moments ago and would itself have failed if the account did not exist, so neither a missing account nor an unknown otp_id explains this";return r?`${e}. ${s} \u2014 the code is what remains: ${i}. Request a fresh code and try again.`:`${e}, and the backend did not identify the failure. ${s}, but an unrecognised refusal can also come from a proxy or gateway the request never reached the app through \u2014 so a stale code (${i}) is the likeliest cause, not the only one. Request a fresh code; if it fails the same way, the refusal is not about the code.`}let o=`the code may be ${i} \u2014 or the account may not exist here, or --otp-id may not be an otp_id this environment issued`;return r?`${e}, and the CLI cannot tell which cause applies: ${o}. ${yt(t)}`:`${e}, and the backend did not identify the failure: ${o} \u2014 or the request may not have reached the application at all. ${yt(t)}`}function Lt(e){if(e)throw new a("input.invalid","--no-existence-check is no longer supported: registration via the CLI OTP flow was removed (the CLI login endpoint only signs in existing accounts). Create the account in the AllScale web app first, then re-run without this flag.")}var tr=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:bt,build:e=>Zn(e.email,e.status)},{flows:["otp-send"],status:403,code:zn,when:e=>{let t=ee(e.email);return t.length>0&&t!==h},build:e=>$e(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:Xn,build:e=>new a("auth.signature_rejected","The AllScale API rejected this request because this CLI build is not signed with the CLI signing key (the login endpoint is CLI-only). This is a build problem, not an input error: download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry. If you are already on the latest version, or this is a local/dev build signed with a non-CLI key, the signing-key row is misprovisioned \u2014 contact AllScale support.",{status:e.status,backend_code:e.backendCode})},{flows:["password"],status:400,code:Vn,build:e=>Qn(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>new a("input.invalid",wt("OTP rejected",e.email,e.otpIdFromSendLeg===!0,!0),{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7531,build:e=>new a("input.invalid","The backend requires at least one scope for the minted agent key \u2014 pass --scopes (e.g. --scopes invoice:read_only).",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7530,build:e=>new a("input.invalid","None of the requested scopes can be granted to this account, so no key was issued. Retry with different --scopes.",{status:e.status,backend_code:e.backendCode})}];function Fe(e){if(e.backendCode!==void 0){for(let t of tr)if(t.code===e.backendCode&&t.status===e.status&&t.flows.includes(e.flow)&&(t.when===void 0||t.when(e)))return t.build(e)}}var rr="/api/v1/public/turnkey/cli/email-otps",ir="/api/v1/public/turnkey/email-otps",Tt=Symbol("cli-otp-route-missing");async function It(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=Re(Pe(n),e);try{return await fetch(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(s){throw new a("transport.network",`Network error contacting ${r}: ${s.message}`)}}async function kt(e){let t=await Et(e,Q);if(typeof t.data!="string"||t.data.trim().length===0)throw new a("backend.internal","OTP send response did not include otp_id.",{body:X(JSON.stringify(t))});return{otp_id:t.data}}async function Ct(e,t){let n=await or(e,t);return n!==Tt?n:sr(e,t)}async function or(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await It(e,rr,n);await Ne(r);let i=await Be(r);De(r.status,i);let o=Ue(i),s=Fe({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return Tt;if(r.status===429)throw new a("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw new a("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new a("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return kt(r)}async function sr(e,t){let n={email:t.email,check_user_existence:!0};t.name!==void 0&&(n.name=t.name),t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await It(e,ir,n);await Ne(r);let i=await Be(r);De(r.status,i);let o=Ue(i),s=Fe({flow:"otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404)throw new a("not_found","OTP send endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});let c=ee(t.email),l=c.length>0&&c!==h;if(r.status===429)throw new a("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw r.status===500&&l?$e(t.email,r.status,o,"backend.internal",!1):new a("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new a("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return kt(r)}var te=class e extends U{static description="Send an email OTP for login. Works with any account email (external domains included). Returns the otp_id; the user receives the code by email. Login only: the account must already exist.";static examples=["$ allscale otp-send --email me@example.com"];static flags={email:$.Flags.string({helpGroup:"REQUIRED",char:"e",description:"Account email",required:!0}),"no-existence-check":$.Flags.boolean({description:"(DEPRECATED \u2014 now errors) Registration via the CLI OTP flow was removed: the CLI-only login endpoint signs in existing accounts only. Create the account in the AllScale web app first, then log in without this flag.",default:!1,hidden:!0}),...U.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=t.email.trim();St(n),Lt(!!t["no-existence-check"]);let r=this.resolveContext(t),i=await Ct(r.apiBase,{email:n});return Ot.stderr.write(`OTP sent to ${n}. Check the inbox; the code is short-lived.
|
|
13
|
+
To move to production, run: allscale device-login --api-base ${N}
|
|
14
|
+
`}var y=m(require("fs")),lt=m(require("os")),Ie=m(require("path")),ke=m(require("@iarna/toml"));var En=".allscale",bn="config.toml";function yn(){return Ie.join(lt.homedir(),En)}function wn(){return Ie.join(yn(),bn)}function Oe(){let e=wn();if(!y.existsSync(e))return{};let t=y.readFileSync(e,"utf-8");try{return ke.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function pt(e,t){return e.profile?.[t]}function ft(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function W(e){if(!oe(e))throw new a("input.invalid",`Refusing to send credentials to API base ${D(e)}. `+ie)}function Ce(e){let t=Ln(e);if(t)throw new a("input.invalid",t.message)}function Sn(){let e=C();if(e===void 0)return;let t=R();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Ln(e){let t=Sn();if(t===void 0||E(e))return;let{endpoints:n,fromPairs:r}=t,i=Le(e),o=n.map(c=>Le(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let s=n.map(c=>D(c)).join(", ");return{message:r?`Refusing to send to ${D(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${D(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Tn=require("@noble/hashes/sha3");var gt=["USDT","USDC"];var ii=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var ht=3100,In=2090,kn=2001,On=2092,_="allscale.io";function z(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Re(e){try{let t=JSON.parse(e);if(typeof t.code=="number"&&Number.isInteger(t.code))return t.code;if(typeof t.code=="string"&&/^\d+$/.test(t.code)){let n=Number(t.code);if(Number.isSafeInteger(n))return n}}catch{}}var Cn="unknown_otp_id",Rn="invalid_code",vn="expired_code";function Pn(e,t){return new a("not_found",`No AllScale account exists for '${e}' on this environment. Check the address for typos, try the email the account was created with, or sign up first if you do not have an account yet.`,{status:t,backend_code:ht})}function ve(e,t,n,r,i){let o=z(e),s=o.endsWith(`.${_}`)?`@${_} subdomains are not whitelisted \u2014 use a bare @${_} address, or contact support / wait for the backend allowlist fix.`:`Use an @${_} address, or contact support / wait for the backend allowlist fix.`,c=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${_} addresses can receive a login code here. Re-run with an @${_} address.`:`Backend returned ${t} when sending OTP to external domain '${o}'. External-domain OTP delivery is likely restricted on this environment (e.g. Cloudflare verification); only @${_} is whitelisted.`;return new a(r,c,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function xn(e,t){return new a("auth.permission_denied","Login rejected: the email or password is incorrect. Note that AllScale Pay accounts have no password \u2014 use `allscale device-login` or `allscale otp-login` for those.",{status:e,...t===void 0?{}:{backend_code:t}})}function mt(e){if(e.length===0)throw new a("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new a("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function Nn(e){return`'${e.replace(/'/g,"'\\''")}'`}function J(e){return`Run \`allscale otp-send --email ${Nn(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}function _t(e,t,n,r){let i="incorrect, expired, already used, or locked after too many attempts";if(n){let s="This run's send step issued the otp_id moments ago and would itself have failed if the account did not exist, so neither a missing account nor an unknown otp_id explains this";return r?`${e}. ${s} \u2014 the code is what remains: ${i}. Request a fresh code and try again.`:`${e}, and the backend did not identify the failure. ${s}, but an unrecognised refusal can also come from a proxy or gateway the request never reached the app through \u2014 so a stale code (${i}) is the likeliest cause, not the only one. Request a fresh code; if it fails the same way, the refusal is not about the code.`}let o=`the code may be ${i} \u2014 or the account may not exist here, or --otp-id may not be an otp_id this environment issued`;return r?`${e}, and the CLI cannot tell which cause applies: ${o}. ${J(t)}`:`${e}, and the backend did not identify the failure: ${o} \u2014 or the request may not have reached the application at all. ${J(t)}`}var At=new Map([[Cn,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${J(t)}`],[Rn,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[vn,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${J(t)}`]]);function Bn(e,t,n,r=!1){if(n!==void 0)return At.get(n)?.(e,t,r)}var Et=[...At.keys()];function bt(e){if(e)throw new a("input.invalid","--no-existence-check is no longer supported: registration via the CLI OTP flow was removed (the CLI login endpoint only signs in existing accounts). Create the account in the AllScale web app first, then re-run without this flag.")}var Dn=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:ht,build:e=>Pn(e.email,e.status)},{flows:["otp-send"],status:403,code:In,when:e=>{let t=z(e.email);return t.length>0&&t!==_},build:e=>ve(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:On,build:e=>new a("auth.signature_rejected","The AllScale API rejected this request because this CLI build is not signed with the CLI signing key (the login endpoint is CLI-only). This is a build problem, not an input error: download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry. If you are already on the latest version, or this is a local/dev build signed with a non-CLI key, the signing-key row is misprovisioned \u2014 contact AllScale support.",{status:e.status,backend_code:e.backendCode})},{flows:["password"],status:400,code:kn,build:e=>xn(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>{let t=Bn("OTP rejected",e.email,e.reason,e.otpIdFromSendLeg===!0);return new a("input.invalid",t??_t("OTP rejected",e.email,e.otpIdFromSendLeg===!0,!0),{status:e.status,backend_code:e.backendCode,...t===void 0?{}:{otp_reason:e.reason}})}},{flows:["otp-verify"],status:400,code:7531,build:e=>new a("input.invalid","The backend requires at least one scope for the minted agent key \u2014 pass --scopes (e.g. --scopes invoice:read_only).",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7530,build:e=>new a("input.invalid","None of the requested scopes can be granted to this account, so no key was issued. Retry with different --scopes.",{status:e.status,backend_code:e.backendCode})}];function Pe(e){if(e.backendCode!==void 0){for(let t of Dn)if(t.code===e.backendCode&&t.status===e.status&&t.flows.includes(e.flow)&&(t.when===void 0||t.when(e)))return t.build(e)}}var F=require("@oclif/core"),$=class e extends A.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:A.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:A.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:w()==="public"}),"api-base":A.Flags.string({description:re,helpGroup:"GLOBAL",hidden:w()==="public"}),"insecure-storage":A.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ae(this.jsonEnabled()),ye(),b({type:"session-start",command:this.id??"",argv:Se(this.argv)});let t=this.constructor;if(w()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&U()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=ot(this.jsonEnabled()),r=this.argv.length===0&&!n&&jn(t)?this.config.findCommand(this.id??""):void 0;if(r){P();let o=await(0,A.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!ut())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return b({type:"command-end",ok:!0}),P(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ve(i),{data:i})}catch(t){let n=ze(t);st({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ae(!1)}}resolveSessionApiBaseChain(t){let n=Oe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Te()!==void 0,s=ft(n,r,Te()),c=pt(n,s),d=w()==="public"&&U()!==void 0,l=i??(d?void 0:U()),h=l??c?.api_base??N,g=dt({resolvedApiBase:h,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return g&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,T({event:"legacy_staging_profile",api_base:h,profile:s},g)),{apiBase:h,explicitApiBase:l,envApiBaseIgnored:d,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||W(n),n}resolveContext(t){if(w()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&U()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:c,profileApiBase:d,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(W(i),Ce(i)),{apiBase:i,profile:c,token:n??at(),insecureStorage:r||ct(),apiBaseSource:o!==void 0?"explicit":d!==void 0?"profile":"default",profileExplicit:l,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${Hn(t)}
|
|
15
|
+
`)}};var Un=/_(removed|cleared|count|total)$/i;function $n(e,t){return typeof t=="number"&&Un.test(e)}var Fn=new Set(gt);function Gn(e,t){return e==="token_symbol"&&typeof t=="string"&&Fn.has(t)}var Mn=new Set(Et);function Kn(e,t){return e==="otp_reason"&&typeof t=="string"&&Mn.has(t)}var V=100;function X(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,V),r=n.map(i=>X(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,V))n[i]=Y(i)&&!$n(i,o)&&!Gn(i,o)&&!Kn(i,o)?"<redacted>":X(o,t+1);if(r.length>V){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-V} more keys`}return n}if(typeof e=="string"){let n=Yn(e);return n!==void 0?p(JSON.stringify(X(n,t+1))):p(e)}return e}function Yn(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Hn(e){let t=Ee()?void 0:2,n=X(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:p(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function jn(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var yt=m(require("crypto")),wt=m(require("fs")),St=m(require("path"));var qn="key-id",Wn="x-allscale-cli-version",xe="cli-1",Jn="aScaLe_cli_obf_v1",zn="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Vn(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var Xn=Vn(zn,Jn),Zn=`Bearer ${Xn}`;function Lt(e,t){let n=ae(e);if(n!==null)return t.find(r=>ae(r.base)===n)}function Qn(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=R();if(t.length>0){let r=Lt(e,t);if(r)return r.key;if(E(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:E(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function er(e){{let r="cli-1".trim();if(r.length>0)return r}let t=R();if(t.length>0){let r=e!==void 0?Lt(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&E(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():xe}if(!E(t[0].base))return xe}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():xe}function tr(){return"1.0.2"}function nr(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ne(e,t){let n=Qn(t);if(!n)throw nr();let r=er(t),i=Math.floor(Date.now()/1e3).toString(),o=yt.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Wn]:tr()};return r.length>0&&(s[qn]=r),s}function Be(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var rr=500,ir=8,Tt=100;function De(e,t=0){if(t>ir)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Tt),r=n.map(i=>De(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,Tt))n[r]=Y(r)?"<redacted>":De(i,t+1);return n}return e}function or(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Z(e,t=rr){let n=or(e),r=n===void 0?K(e):JSON.stringify(De(n));return H(r,t)}var ee=256*1024,G=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Q=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function Ue(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new G(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,d,l=n.timeoutMs,h=l===void 0?void 0:new Promise((g,ne)=>{d=setTimeout(()=>{ne(new Q(e.status,l))},l),d.unref?.()});try{for(;;){let g=o.read(),{done:ne,value:Me}=h?await Promise.race([g,h]):await g;if(ne)break;if(c+=Me.byteLength,c>t)throw o.cancel().catch(()=>{}),new G(e.status,t,n.oversizeKind);s.push(Buffer.from(Me))}}catch(g){throw g instanceof Q&&o.cancel(g).catch(()=>{}),g}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}async function It(e,t){let n;try{n=await Ue(e,t)}catch(r){if(r instanceof G)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var eo=32*1024*1024,to=4*1024*1024;function sr(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${it(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function $e(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}sr(e.status,e.url)}}var ar=2014;function cr(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function ur(e){return cr(e,ar)}var dr=1e4;async function Fe(e,t=dr){if(e.status>=200&&e.status<300)return"";try{return await Ue(e,ee,{timeoutMs:t})}catch{return""}}function Ge(e,t){if(!(e>=200&&e<300)&&ur(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?Z(t):t})}var pr=require("process");var lr=require("process");var fr="/api/v1/public/turnkey/cli/email-otps",gr="/api/v1/public/turnkey/email-otps",kt=Symbol("cli-otp-route-missing");async function Ot(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=Ne(Be(n),e);try{return await fetch(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(s){throw new a("transport.network",`Network error contacting ${r}: ${s.message}`)}}async function Ct(e){let t=await It(e,ee);if(typeof t.data!="string"||t.data.trim().length===0)throw new a("backend.internal","OTP send response did not include otp_id.",{body:Z(JSON.stringify(t))});return{otp_id:t.data}}async function Rt(e,t){let n=await hr(e,t);return n!==kt?n:mr(e,t)}async function hr(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await Ot(e,fr,n);await $e(r);let i=await Fe(r);Ge(r.status,i);let o=Re(i),s=Pe({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return kt;if(r.status===429)throw new a("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw new a("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new a("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return Ct(r)}async function mr(e,t){let n={email:t.email,check_user_existence:!0};t.name!==void 0&&(n.name=t.name),t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await Ot(e,gr,n);await $e(r);let i=await Fe(r);Ge(r.status,i);let o=Re(i),s=Pe({flow:"otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404)throw new a("not_found","OTP send endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});let c=z(t.email),d=c.length>0&&c!==_;if(r.status===429)throw new a("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw r.status===500&&d?ve(t.email,r.status,o,"backend.internal",!1):new a("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new a("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return Ct(r)}var te=class e extends ${static description="Send an email OTP for login. Works with any account email (external domains included). Returns the otp_id; the user receives the code by email. Login only: the account must already exist.";static examples=["$ allscale otp-send --email me@example.com"];static flags={email:F.Flags.string({helpGroup:"REQUIRED",char:"e",description:"Account email",required:!0}),"no-existence-check":F.Flags.boolean({description:"(DEPRECATED \u2014 now errors) Registration via the CLI OTP flow was removed: the CLI-only login endpoint signs in existing accounts only. Create the account in the AllScale web app first, then log in without this flag.",default:!1,hidden:!0}),...$.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=t.email.trim();mt(n),bt(!!t["no-existence-check"]);let r=this.resolveContext(t),i=await Rt(r.apiBase,{email:n});return vt.stderr.write(`OTP sent to ${n}. Check the inbox; the code is short-lived.
|
|
16
16
|
`),{email:n,otp_id:i.otp_id,api_base:r.apiBase}}};
|
|
17
17
|
//# sourceMappingURL=otp-send.js.map
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var u=m(require("fs")),X=m(require("path")),ct=m(require("crypto"));var
|
|
4
|
-
`)}else Ie.stderr.write(t)}var at="2",
|
|
5
|
-
`);return}
|
|
1
|
+
"use strict";var Jt=Object.create;var z=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,Zt=Object.prototype.hasOwnProperty;var en=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})},je=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xt(t))!Zt.call(e,i)&&i!==n&&z(e,i,{get:()=>t[i],enumerable:!(r=Vt(t,i))||r.enumerable});return e};var m=(e,t,n)=>(n=e!=null?Jt(Qt(e)):{},je(t||!e||!e.__esModule?z(n,"default",{value:e,enumerable:!0}):n,e)),tn=e=>je(z({},"__esModule",{value:!0}),e);var vr={};en(vr,{default:()=>oe});module.exports=tn(vr);var E=require("@oclif/core");var We="public",ze="https://app.allscale.io",x="https://openapi.allscale.io";var Je=["https://app.allscale.io"],Ve=["https://openapi.allscale.io"],B=[];var Xe={"https://openapi.allscale.io":"production \u2014 real funds"},se="Override the API base URL (public builds accept only https://app.allscale.io)";var ae="Standalone partner API origin for store-HMAC payouts. Defaults to https://openapi.allscale.io. Also via ALLSCALE_PAYOUT_API_BASE.",ce="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.",le="Only https://openapi.allscale.io is allowed. Set --payout-api-base (or ALLSCALE_PAYOUT_API_BASE) to choose it explicitly; otherwise the public build uses its production partner API default.";function ue(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Qe(e){return ue(e)!==null}function de(e){let t=ue(e);return t!==null&&Je.includes(t.origin)}function D(e){let t=ue(e);return t!==null&&Ve.includes(t.origin)}function pe(e){return!1}function J(e){return x}function $(){return"".trim()||void 0}function I(){return"public"}function he(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function ge(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return fe()}function fe(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:a,key:c,keyId:l}=o;if(typeof a!="string"||a.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:a.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var nn={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},rn=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function ye(e){return(typeof e=="string"?e:String(e??"")).replace(rn,"")}var on=64;function me(e,t=new Map,n=0){if(typeof e=="string")return ye(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=on)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let c of e)a.push(me(c,t,n+1));return a}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[a,c]of Object.entries(e))Object.defineProperty(o,a,{value:me(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(t,n,r){super(ye(n)),this.code=t,this.details=r&&me(r),this.name="AllscaleError"}get exitCode(){return nn[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function et(e){if(e instanceof s)return e;if(e instanceof Error){if(cn(e)){let t=un(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new s("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var sn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),an=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function cn(e){if(ln(e))return!0;let t=e.name??"";return sn.has(t)?t==="CLIError"?_e(e,"parse")||Ze(e.message):!0:Ze(e.message)}function ln(e){if(!_e(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&_e(e,"parse")}function Ze(e){return e?ye(e).split(`
|
|
2
|
+
`).some(t=>an.some(n=>n.test(t.trim()))):!1}function _e(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function un(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function tt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var u=m(require("fs")),X=m(require("path")),ct=m(require("crypto"));var dn="...<truncated>",pn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,fn=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,be=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,we=String.raw`(?:proxy[_-]?)?authorization`,hn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${we}"|'${we}'|${we})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${be}`,"gi"),gn=/\b(https?:\/\/)[^\s/?#]+@/gi,mn=String.raw`(?:[A-Za-z0-9]+[_-])*`,_n=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,rt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,nt=rt(mn),yn=rt(_n),wn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${nt}"|'${nt}'|${yn})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${be}`,"gi"),Ee=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,En=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ee}"|'${Ee}'|${Ee})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${be}`,"g");function ke(e){return e.replace(gn,"$1<redacted>@").replace(pn,"<redacted-jwt>").replace(hn,"$1$2$3<redacted>").replace(wn,"$1$2<redacted>").replace(En,"$1$2<redacted>").replace(fn,"Bearer <redacted>")}var Sn=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function Le(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Sn.test(t)}function it(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function Te(e,t,n=dn){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(l+f>t)break;c+=d,l+=f}return c}let i=t-r,o="",a=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(a+l>i)break;o+=c,a+=l}return`${o}${n}`}function g(e,t=16384){return Te(it(ke(e)),t)}var Se=100,An=8,bn=8*1024;function V(){return{remaining:bn}}function Ae(e,t){let n=Math.min(16384,t.remaining),r=Te(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function O(e,t,n=0,r={}){if(n>An)return Ae("<truncated>",t);if(typeof e=="string"){let i=ke(e);return Ae(r.escapeControls?it(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Se),o=i.map(a=>O(a,t,n+1,r));return e.length>i.length&&o.push(Ae(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[a,c]of o.slice(0,Se))i[a]=O(c,t,n+1,r);return o.length>Se&&(i.output_truncated=!0),i}return e}var Ie=require("process");var Oe=!1;function Ce(e){Oe=e}function st(){return Oe}var ot="1";function S(e,t){if(Oe){let n={...e};delete n.version;let r=V(),i={event:n.event,...n},o=O(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:ot,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:ot,event:o.event,output_truncated:!0})),Ie.stderr.write(`${a}
|
|
4
|
+
`)}else Ie.stderr.write(t)}var at="2",R=null,y=null,v=!1,U=!1;function kn(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=ct.randomBytes(4).toString("hex");return X.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Re=64*1024*1024,Ln=null;function ve(e={}){if(e.quiet&&(U=!0),v)return;let t=kn();if(!t)return;R=null;let n=null;try{if((Ln??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=X.dirname(t);if(u.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=u.statSync(r),d=l.mode&511;if(!l.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let i=u.constants.O_NOFOLLOW??0;n=u.openSync(t,u.constants.O_APPEND|u.constants.O_CREAT|u.constants.O_WRONLY|(u.constants.O_NONBLOCK??0)|i,384);let o=u.fstatSync(n),a=u.lstatSync(t);if(!o.isFile()||a.isSymbolicLink()||a.dev!==o.dev||a.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=o.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);u.fchmodSync(n,384)}catch(r){if(n!==null)try{u.closeSync(n)}catch{}U||S({event:"sidecar_disabled",reason:"open_failed",detail:g(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${g(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}R=t,y=n,v=!0}var Tn=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function In(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Tn.some(n=>n.test(t))}function lt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=On(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)In(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function On(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Cn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:lt(e.url)}:e}function Rn(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=O(i,V()),a=JSON.stringify({version:at,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:at,timestamp:t,type:r,output_truncated:!0})),a}function L(e){if(!v||!R||y===null)return;let t=Cn(e),n=Rn(t);try{if(u.fstatSync(y).size+Buffer.byteLength(n,"utf8")+1>Re){v=!1;try{u.closeSync(y)}catch{}y=null,U||S({event:"sidecar_disabled",reason:"size_limit",...R===null?{}:{path:g(R)},max_bytes:Re},`${g(`[allscale] sidecar exceeded ${Re} bytes; disabling it for the rest of this run. Rotate or remove ${R}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
6
|
`);return}u.appendFileSync(y,`${n}
|
|
7
|
-
`)}catch(r){if(
|
|
8
|
-
`)}catch{}}}var ut=lt;function dt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function
|
|
7
|
+
`)}catch(r){if(v=!1,y!==null){try{u.closeSync(y)}catch{}y=null}try{U||S({event:"sidecar_disabled",reason:"write_failed",detail:g(r.message)},`${g(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var ut=lt;function dt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function F(){if(U=!1,v=!1,y!==null){try{u.closeSync(y)}catch{}y=null}}function pt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||dt()||!t}var M=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),vn=new Set(Array.from(M).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Pn=Array.from(M).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Nn=new Set(["--otp-stdin","--password-stdin"]);function Pe(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let a=r.slice(0,o);if(M.has(a)){t.push(`${a}=<redacted>`);continue}}}if(M.has(r)){t.push(r),n+1<e.length&&(M.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(vn.has(o)){t.push(`${o}<redacted>`);continue}}let i=Nn.has(r)?void 0:Pn.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function ft(e){L({type:"error",code:e.code,message:g(e.message)}),L({type:"command-end",ok:!1,exitCode:e.exitCode}),F()}var G=$()??ze,A={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function K(e){return Qe(e)?new URL(e).origin:null}function b(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function ht(){let e=process.env[A.TOKEN]?.trim();return e&&e.length>0?e:void 0}function xe(){let e=process.env[A.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Y(){let e=process.env[A.API_BASE]?.trim();return e&&e.length>0?e:void 0}function gt(){let e=process.env[A.PAYOUT_API_BASE]?.trim();return e&&e.length>0?e:void 0}function mt(){let e=process.env[A.STORE_API_KEY]?.trim();return e&&e.length>0?e:void 0}function _t(){let e=process.env[A.STORE_API_SECRET]?.trim();return e&&e.length>0?e:void 0}function yt(){let e=process.env[A.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function wt(){let e=process.env[A.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Et(e){let t;try{t=new URL(e).origin}catch{}let n=t===void 0?void 0:Xe[t],r=n===void 0?"":` (${n})`;return`Notice: no --payout-api-base given; using ${e}${r}.
|
|
9
9
|
Set --payout-api-base (or ALLSCALE_PAYOUT_API_BASE) to choose the destination explicitly.
|
|
10
|
-
`}function
|
|
11
|
-
The CLI default is now ${
|
|
10
|
+
`}function St(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if($()===void 0&&G!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
|
|
11
|
+
The CLI default is now ${G} (production), but a saved profile wins over the default,
|
|
12
12
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
13
13
|
the old default rather than a deliberate choice.
|
|
14
14
|
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
15
|
-
To move to production, run: allscale device-login --api-base ${
|
|
16
|
-
`}var
|
|
17
|
-
`)}};var
|
|
15
|
+
To move to production, run: allscale device-login --api-base ${G}
|
|
16
|
+
`}var T=m(require("fs")),At=m(require("os")),Be=m(require("path")),De=m(require("@iarna/toml"));var xn=".allscale",Bn="config.toml";function bt(){return Be.join(At.homedir(),xn)}function Dn(){return Be.join(bt(),Bn)}function $e(){let e=Dn();if(!T.existsSync(e))return{};let t=T.readFileSync(e,"utf-8");try{return De.parse(t)}catch(n){throw new s("internal",`Failed to parse ${e}: ${n.message}`)}}function kt(e,t){return e.profile?.[t]}function Lt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new s("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function q(e){if(!de(e))throw new s("input.invalid",`Refusing to send credentials to API base ${b(e)}. `+ce)}function H(e){if(!D(e))throw new s("input.invalid",`Refusing to send store credentials to payout API base ${b(e)}. `+le)}function Ue(e,t){let n=K(e),r=K(t);if(!(n&&r===n))throw new s("input.invalid",`Refusing API request to ${b(t)} because it is outside the configured API origin ${b(e)}.`)}function Fe(e){let t=Un(e);if(t)throw new s("input.invalid",t.message)}function $n(){let e=$();if(e===void 0)return;let t=ge();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Un(e){let t=$n();if(t===void 0||he(e))return;let{endpoints:n,fromPairs:r}=t,i=K(e),o=n.map(c=>K(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let a=n.map(c=>b(c)).join(", ");return{message:r?`Refusing to send to ${b(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${b(e)} \u2014 this build only signs for ${a}. Re-login against this build's environment, or use a build for that one.`}}var Fn=require("@noble/hashes/sha3");function Tt(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Mn={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},It=["ethereum","bsc","base","polygon","arbitrum","optimism"],Q=["USDT","USDC"];function Ot(e){return Mn[e.toLowerCase()]??null}function Ct(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var ui=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Gn="unknown_otp_id",Kn="invalid_code",Yn="expired_code";function qn(e){return`'${e.replace(/'/g,"'\\''")}'`}function Rt(e){return`Run \`allscale otp-send --email ${qn(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Hn=new Map([[Gn,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${Rt(t)}`],[Kn,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[Yn,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${Rt(t)}`]]);var vt=[...Hn.keys()];var _=require("@oclif/core"),j=class e extends E.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:E.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:E.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:I()==="public"}),"api-base":E.Flags.string({description:se,helpGroup:"GLOBAL",hidden:I()==="public"}),"insecure-storage":E.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ce(this.jsonEnabled()),ve(),L({type:"session-start",command:this.id??"",argv:Pe(this.argv)});let t=this.constructor;if(I()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new s("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Y()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=pt(this.jsonEnabled()),r=this.argv.length===0&&!n&&er(t)?this.config.findCommand(this.id??""):void 0;if(r){F();let o=await(0,E.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!wt())throw this.argv.length>0&&await this.parse(),new s("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return L({type:"command-end",ok:!0}),F(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||tt(i),{data:i})}catch(t){let n=et(t);ft({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ce(!1)}}resolveSessionApiBaseChain(t){let n=$e(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||xe()!==void 0,a=Lt(n,r,xe()),c=kt(n,a),l=I()==="public"&&Y()!==void 0,d=i??(l?void 0:Y()),f=d??c?.api_base??G,p=St({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,S({event:"legacy_staging_profile",api_base:f,profile:a},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:l,profileApiBase:c?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||q(n),n}resolveContext(t){if(I()==="public"){if(t.token!==void 0)throw new s("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Y()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:a,profile:c,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(i),Fe(i)),{apiBase:i,profile:c,token:n??ht(),insecureStorage:r||yt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:a}}emitError(t){process.stderr.write(`${Zn(t)}
|
|
17
|
+
`)}};var jn=/_(removed|cleared|count|total)$/i;function Wn(e,t){return typeof t=="number"&&jn.test(e)}var zn=new Set(Q);function Jn(e,t){return e==="token_symbol"&&typeof t=="string"&&zn.has(t)}var Vn=new Set(vt);function Xn(e,t){return e==="otp_reason"&&typeof t=="string"&&Vn.has(t)}var Z=100;function ee(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Z),r=n.map(i=>ee(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Z))n[i]=Le(i)&&!Wn(i,o)&&!Jn(i,o)&&!Xn(i,o)?"<redacted>":ee(o,t+1);if(r.length>Z){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Z} more keys`}return n}if(typeof e=="string"){let n=Qn(e);return n!==void 0?g(JSON.stringify(ee(n,t+1))):g(e)}return e}function Qn(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Zn(e){let t=st()?void 0:2,n=ee(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:g(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function er(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var tr=m(require("crypto")),nr=m(require("fs")),rr=m(require("path"));var ir="aScaLe_cli_obf_v1",or="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function sr(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var ar=sr(or,ir),cr=`Bearer ${ar}`;var Me=256*1024,te=class extends s{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},ne=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function Ge(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new te(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],c=0,l,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,h)=>{l=setTimeout(()=>{h(new ne(e.status,d))},d),l.unref?.()});try{for(;;){let p=o.read(),{done:h,value:k}=f?await Promise.race([p,f]):await p;if(h)break;if(c+=k.byteLength,c>t)throw o.cancel().catch(()=>{}),new te(e.status,t,n.oversizeKind);a.push(Buffer.from(k))}}catch(p){throw p instanceof ne&&o.cancel(p).catch(()=>{}),p}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(a,c).toString("utf8")}var lo=32*1024*1024,uo=4*1024*1024;function lr(e,t){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${ut(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Pt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}lr(e.status,e.url)}}var N=require("crypto");function ur(e){return(0,N.createHash)("sha256").update(e??"").digest("hex")}function dr(e){let t=ur(e.body),n=`${e.method.toUpperCase()}
|
|
18
18
|
${e.path}
|
|
19
19
|
${e.query}
|
|
20
20
|
${e.ts}
|
|
21
21
|
${e.nonce}
|
|
22
|
-
${t}`;return Buffer.from(n,"utf-8")}function tr(e,t){return`v1=${(0,N.createHmac)("sha256",Buffer.from(e,"utf-8")).update(t).digest("base64")}`}function nr(){return(0,N.randomBytes)(16).toString("hex")}function rr(){return String(Math.floor(Date.now()/1e3))}var re={apiKey:"X-API-Key",timestamp:"X-Timestamp",nonce:"X-Nonce",signature:"X-Signature"};function Pt(e){let t=e.ts??rr(),n=e.nonce??nr(),r=er({method:e.method,path:e.path,query:e.query??"",ts:t,nonce:n,body:e.body}),i=tr(e.apiSecret,r);return{[re.apiKey]:e.apiKey,[re.timestamp]:t,[re.nonce]:n,[re.signature]:i}}var vt="/v1/claim_link_auto_payouts",ir=12e4,E={OK:0,VALIDATION_ERROR:10001,AUTH_MISSING_HEADERS:20001,AUTH_BAD_SIGNATURE:20002,FORBIDDEN:30001,SCOPE_FORBIDDEN:30002,RATE_LIMIT_EXCEEDED:40001,CREATE_ERROR:50103,API_DISABLED:50104,DUPLICATE_REFERENCE:50105,REFERENCE_CONFLICT:50106};function or(e){let t={amount:e.amount,stable_coin:e.stableCoin,chain:e.chain,reference_id:e.referenceId};return e.receiverEmail&&(t.receiver_email=e.receiverEmail),e.senderDisplayName&&(t.sender_display_name=e.senderDisplayName),e.senderMessage&&(t.sender_message=e.senderMessage),JSON.stringify(t)}function sr(e,t){let n=t?.code,r=t?.error?.details?.reason??t?.error?.message??`HTTP ${e}`,i={httpStatus:e,code:n,reason:r};switch(n){case E.FORBIDDEN:return new s("auth.permission_denied",`This store key is not allowed to perform this operation (${r}). Check the key belongs to the right store and environment.`,i);case E.SCOPE_FORBIDDEN:return new s("auth.permission_denied","This store key is not authorized for auto-payout (missing claim_link:auto_payout scope). Complete Payout onboarding for this store, then retry.",i);case E.API_DISABLED:return new s("auth.permission_denied","Auto-payout is unavailable: it is disabled in this environment, or this is a sandbox key (live signing requires a production store key).",i);case E.DUPLICATE_REFERENCE:return new s("rate_limited",`A create for reference_id is already in flight; retry shortly (a settled duplicate returns the original link). reason: ${r}`,i);case E.REFERENCE_CONFLICT:return new s("input.invalid",`This reference_id was already used for a different payout request (${r}). Reuse it only with the original chain, token, and amount; otherwise choose a new reference_id.`,{...i,...ar(t?.error?.details)});case E.VALIDATION_ERROR:return new s("input.invalid",`Auto-payout request rejected: ${r}`,i);case E.AUTH_MISSING_HEADERS:case E.AUTH_BAD_SIGNATURE:return new s("auth.permission_denied",`Store-key authentication failed (${r}). Check --api-key / ALLSCALE_STORE_API_SECRET and that the system clock is accurate.`,i);case E.RATE_LIMIT_EXCEEDED:return new s("rate_limited",`Rate limited: ${r}`,i);case E.CREATE_ERROR:return new s("backend.internal",`Auto-payout could not fund the claim link (${r}). Run \`allscale payout status\` to check the session is active and has enough remaining cap/balance before retrying.`,i);default:return new s("backend.internal",`Auto-payout failed: ${r}`,i)}}function ar(e){if(!e)return{};let t={};typeof e.reference_id=="string"&&(t.reference_id=e.reference_id);for(let n of["existing","request"]){let r=e[n];if(!r||typeof r!="object"||Array.isArray(r))continue;let i=r,o={};(typeof i.chain=="string"||typeof i.chain=="number")&&(o.chain=i.chain),typeof i.token_symbol=="string"&&(o.token_symbol=i.token_symbol),(typeof i.amount=="string"||typeof i.amount=="number")&&(o.amount=i.amount),t[n]=o}return t}function cr(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=r=>t[r]===null||typeof t[r]=="string";return typeof t.claim_link_id=="string"&&t.claim_link_id.length>0&&n("reference_id")&&(typeof t.amount=="string"||typeof t.amount=="number")&&typeof t.token_symbol=="string"&&typeof t.chain_id=="number"&&Number.isFinite(t.chain_id)&&typeof t.status=="string"&&n("token")&&n("claim_url")&&n("funding_tx_hash")&&(t.funded_amount===null||typeof t.funded_amount=="string"||typeof t.funded_amount=="number")&&typeof t.idempotent_hit=="boolean"}async function Nt(e){H(e.apiBase);let t=new URL(vt,e.apiBase).toString();$e(e.apiBase,t);let n=or(e.input),r={"Content-Type":"application/json",...Pt({apiKey:e.apiKey,apiSecret:e.apiSecret,method:"POST",path:vt,body:n})},i=new AbortController,o=!1,a=setTimeout(()=>{o=!0,i.abort()},e.timeoutMs??ir),c=g=>{let k=g instanceof s&&typeof g.details?.status=="number"&&Number.isSafeInteger(g.details.status)?g.details.status:void 0,j=g instanceof s&&typeof g.details?.max_body_bytes=="number"&&Number.isSafeInteger(g.details.max_body_bytes)?g.details.max_body_bytes:void 0;return new s(o?"transport.timeout":"transport.network",o?"Auto-payout timed out waiting for the funding receipt. The payment MAY have been broadcast \u2014 re-run with the SAME --reference-id to safely resolve it (idempotent).":"Auto-payout transport failed after dispatch. The payout request may still have been created; retry or reconcile with the SAME --reference-id.",{reference_id:e.input.referenceId,...k===void 0?{}:{status:k},...j===void 0?{}:{max_body_bytes:j}})},l,d;try{l=await fetch(t,{method:"POST",headers:r,body:n,signal:i.signal,redirect:"manual"}),await Rt(l),d=await Ge(l,Me)}catch(g){throw c(g)}finally{clearTimeout(a)}let p=null;try{p=d?JSON.parse(d):null}catch{p=null}let f=p&&typeof p=="object"&&!Array.isArray(p)?p:null;if(l.ok&&f?.code===E.OK&&cr(f.payload))return f.payload;throw l.ok&&(!f||typeof f.code!="number"||f.code===E.OK)?new s("backend.internal","Auto-payout returned an unreadable success response. The payout may still have been created; do not use a new reference id. Retry or reconcile with the SAME --reference-id.",{httpStatus:l.status,reference_id:e.input.referenceId}):sr(l.status,f)}var dr=m(require("path"));var lr=require("crypto"),ur=m(require("fs")),Ke=m(require("path"));var oo=1024*1024;var so=new Int32Array(new SharedArrayBuffer(4));var pr=new Set;var fr=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),xt=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Bt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Ye(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var gr=new Set(["cli_op:all"]),hr=new Set([...gr].map(Ye));var Oo=new Set([...[...fr,...xt,...pr].map(Ye),...Bt,...hr]);var mr=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,_r=/^0(?:\.0+)?$/,Dt=128;function Ut(e,t,n={}){if(t.length>Dt)throw new s("input.invalid",`${e} is too long; decimal values may contain at most ${Dt} characters.`);let r=t.trim();if(!mr.test(r))throw new s("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&_r.test(r))throw new s("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function $t(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new s("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function ie(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new s("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}function Ft(e){let t=ie("--receiver-email",e,254);if(t!==void 0){if(!t.includes("@"))throw new s("input.invalid","--receiver-email is not a valid email.");return t}}var He=11,Mt=[...It,...B],yr=B.length>0,qe="the beta or sandbox partner API, or an explicit loopback payout API",Gt=yr?`EVM chain slug. sepolia is a testnet and is accepted only by ${qe}.`:"EVM mainnet chain slug.";function Kt(e){let t=e.toLowerCase();return t==="sepolia"&&B.includes(t)?He:Ot(t)}function Yt(e){return e===He}function Ht(e,t){return e===He?6:Lt(e,t)}var oe=class e extends q{static description="Create and auto-fund a claim link from this store's enabled auto-payout wallet. Authenticates with the store API key/secret (NOT your login), so it needs a store that has completed Payout onboarding. Idempotent on --reference-id.";static examples=["$ ALLSCALE_STORE_API_SECRET=your_store_api_secret allscale payout send --api-key ak_your_api_key --amount 10 --chain base --reference-id order-1042","$ allscale payout send --payout-api-base https://openapi.allscale.io --api-key ak_your_api_key --api-secret your_store_api_secret --amount 25 --stable-coin USDC --chain polygon --reference-id inv-77 --receiver-email client@example.com"];static flags={amount:_.Flags.string({helpGroup:"REQUIRED",description:"Claimable amount in token units (decimal string, e.g. 10 or 25.50); at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:_.Flags.string({helpGroup:"REQUIRED",description:Gt,options:[...Mt],required:!0}),"reference-id":_.Flags.string({helpGroup:"REQUIRED",description:"Your idempotency key (e.g. your order id). REQUIRED \u2014 a retry with the same value is safe (no double-fund).",required:!0}),"payout-api-base":_.Flags.string({description:ae}),"stable-coin":_.Flags.string({description:"Stablecoin to fund in.",options:[...Z],default:"USDT"}),"receiver-email":_.Flags.string({description:"Optional email to send the claim invite to."}),"sender-display-name":_.Flags.string({description:"Optional display name shown to the receiver. Max 100 chars."}),message:_.Flags.string({description:"Optional message shown to the receiver. Max 200 chars."}),"api-key":_.Flags.string({description:"Store API key (public id). Falls back to ALLSCALE_STORE_API_KEY."}),"api-secret":_.Flags.string({description:"Store API secret. Prefer the ALLSCALE_STORE_API_SECRET env var (a flag value can leak via shell history / process list)."}),...q.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);if(t["payout-api-base"]!==void 0&&t["api-base"]!==void 0)throw new s("input.invalid","Use only one of --payout-api-base or the legacy --api-base for payout send.");let n=t["payout-api-base"]?.trim(),r=t["api-base"]?.trim(),i=r!==void 0&&D(r)?r:void 0;if(r!==void 0&&i===void 0){let jt=z(r);(!!1||jt===x)&&H(r)}let o=n??i??ht(),a=o??x;H(a);let c=Kt(t.chain);if(c===null)throw new s("input.invalid",`Unsupported --chain '${t.chain}'.`);if(Yt(c)&&!pe(a))throw new s("input.invalid",`--chain sepolia is testnet-only and can be used only with ${qe}. No request was sent.`);o===void 0&&w({event:"payout_destination",payout_api_base:a},St(a));let l=(t["api-key"]??mt())?.trim(),d=(t["api-secret"]??_t())?.trim();if(!l)throw new s("input.invalid","Missing store API key. Pass --api-key or set ALLSCALE_STORE_API_KEY.");if(!d)throw new s("input.invalid","Missing store API secret. Set ALLSCALE_STORE_API_SECRET (preferred) or pass --api-secret.");let p=Ut("--amount",t.amount),f=t["reference-id"].trim();if(!f)throw new s("input.invalid","--reference-id must be a non-empty idempotency key (it deduplicates retries).");let g=Ct(t["stable-coin"]);if(g===null)throw new s("input.invalid",`Unsupported --stable-coin '${t["stable-coin"]}'.`);$t("--amount",p,Ht(c,g));let k=Ft(t["receiver-email"]),j=ie("--sender-display-name",t["sender-display-name"],100),qt=ie("--message",t.message,200);return Nt({apiBase:a,apiKey:l,apiSecret:d,input:{amount:p,stableCoin:g,chain:c,referenceId:f,receiverEmail:k,senderDisplayName:j,senderMessage:qt}})}};
|
|
22
|
+
${t}`;return Buffer.from(n,"utf-8")}function pr(e,t){return`v1=${(0,N.createHmac)("sha256",Buffer.from(e,"utf-8")).update(t).digest("base64")}`}function fr(){return(0,N.randomBytes)(16).toString("hex")}function hr(){return String(Math.floor(Date.now()/1e3))}var re={apiKey:"X-API-Key",timestamp:"X-Timestamp",nonce:"X-Nonce",signature:"X-Signature"};function Nt(e){let t=e.ts??hr(),n=e.nonce??fr(),r=dr({method:e.method,path:e.path,query:e.query??"",ts:t,nonce:n,body:e.body}),i=pr(e.apiSecret,r);return{[re.apiKey]:e.apiKey,[re.timestamp]:t,[re.nonce]:n,[re.signature]:i}}var xt="/v1/claim_link_auto_payouts",gr=12e4,w={OK:0,VALIDATION_ERROR:10001,AUTH_MISSING_HEADERS:20001,AUTH_BAD_SIGNATURE:20002,FORBIDDEN:30001,SCOPE_FORBIDDEN:30002,RATE_LIMIT_EXCEEDED:40001,CREATE_ERROR:50103,API_DISABLED:50104,DUPLICATE_REFERENCE:50105,REFERENCE_CONFLICT:50106};function mr(e){let t={amount:e.amount,stable_coin:e.stableCoin,chain:e.chain,reference_id:e.referenceId};return e.receiverEmail&&(t.receiver_email=e.receiverEmail),e.senderDisplayName&&(t.sender_display_name=e.senderDisplayName),e.senderMessage&&(t.sender_message=e.senderMessage),JSON.stringify(t)}function _r(e,t){let n=t?.code,r=t?.error?.details?.reason??t?.error?.message??`HTTP ${e}`,i={httpStatus:e,code:n,reason:r};switch(n){case w.FORBIDDEN:return new s("auth.permission_denied",`This store key is not allowed to perform this operation (${r}). Check the key belongs to the right store and environment.`,i);case w.SCOPE_FORBIDDEN:return new s("auth.permission_denied","This store key is not authorized for auto-payout (missing claim_link:auto_payout scope). Complete Payout onboarding for this store, then retry.",i);case w.API_DISABLED:return new s("auth.permission_denied","Auto-payout is unavailable: it is disabled in this environment, or this is a sandbox key (live signing requires a production store key).",i);case w.DUPLICATE_REFERENCE:return new s("rate_limited",`A create for reference_id is already in flight; retry shortly (a settled duplicate returns the original link). reason: ${r}`,i);case w.REFERENCE_CONFLICT:return new s("input.invalid",`This reference_id was already used for a different payout request (${r}). Reuse it only with the original chain, token, and amount; otherwise choose a new reference_id.`,{...i,...yr(t?.error?.details)});case w.VALIDATION_ERROR:return new s("input.invalid",`Auto-payout request rejected: ${r}`,i);case w.AUTH_MISSING_HEADERS:case w.AUTH_BAD_SIGNATURE:return new s("auth.permission_denied",`Store-key authentication failed (${r}). Check --api-key / ALLSCALE_STORE_API_SECRET and that the system clock is accurate.`,i);case w.RATE_LIMIT_EXCEEDED:return new s("rate_limited",`Rate limited: ${r}`,i);case w.CREATE_ERROR:return new s("backend.internal",`Auto-payout could not fund the claim link (${r}). Run \`allscale payout status\` to check the session is active and has enough remaining cap/balance before retrying.`,i);default:return new s("backend.internal",`Auto-payout failed: ${r}`,i)}}function yr(e){if(!e)return{};let t={};typeof e.reference_id=="string"&&(t.reference_id=e.reference_id);for(let n of["existing","request"]){let r=e[n];if(!r||typeof r!="object"||Array.isArray(r))continue;let i=r,o={};(typeof i.chain=="string"||typeof i.chain=="number")&&(o.chain=i.chain),typeof i.token_symbol=="string"&&(o.token_symbol=i.token_symbol),(typeof i.amount=="string"||typeof i.amount=="number")&&(o.amount=i.amount),t[n]=o}return t}function wr(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=r=>t[r]===null||typeof t[r]=="string";return typeof t.claim_link_id=="string"&&t.claim_link_id.length>0&&n("reference_id")&&(typeof t.amount=="string"||typeof t.amount=="number")&&typeof t.token_symbol=="string"&&typeof t.chain_id=="number"&&Number.isFinite(t.chain_id)&&typeof t.status=="string"&&n("token")&&n("claim_url")&&n("funding_tx_hash")&&(t.funded_amount===null||typeof t.funded_amount=="string"||typeof t.funded_amount=="number")&&typeof t.idempotent_hit=="boolean"}async function Bt(e){H(e.apiBase);let t=new URL(xt,e.apiBase).toString();Ue(e.apiBase,t);let n=mr(e.input),r={"Content-Type":"application/json",...Nt({apiKey:e.apiKey,apiSecret:e.apiSecret,method:"POST",path:xt,body:n})},i=new AbortController,o=!1,a=setTimeout(()=>{o=!0,i.abort()},e.timeoutMs??gr),c=h=>{let k=h instanceof s&&typeof h.details?.status=="number"&&Number.isSafeInteger(h.details.status)?h.details.status:void 0,W=h instanceof s&&typeof h.details?.max_body_bytes=="number"&&Number.isSafeInteger(h.details.max_body_bytes)?h.details.max_body_bytes:void 0;return new s(o?"transport.timeout":"transport.network",o?"Auto-payout timed out waiting for the funding receipt. The payment MAY have been broadcast \u2014 re-run with the SAME --reference-id to safely resolve it (idempotent).":"Auto-payout transport failed after dispatch. The payout request may still have been created; retry or reconcile with the SAME --reference-id.",{reference_id:e.input.referenceId,...k===void 0?{}:{status:k},...W===void 0?{}:{max_body_bytes:W}})},l,d;try{l=await fetch(t,{method:"POST",headers:r,body:n,signal:i.signal,redirect:"manual"}),await Pt(l),d=await Ge(l,Me)}catch(h){throw c(h)}finally{clearTimeout(a)}let f=null;try{f=d?JSON.parse(d):null}catch{f=null}let p=f&&typeof f=="object"&&!Array.isArray(f)?f:null;if(l.ok&&p?.code===w.OK&&wr(p.payload))return p.payload;throw l.ok&&(!p||typeof p.code!="number"||p.code===w.OK)?new s("backend.internal","Auto-payout returned an unreadable success response. The payout may still have been created; do not use a new reference id. Retry or reconcile with the SAME --reference-id.",{httpStatus:l.status,reference_id:e.input.referenceId}):_r(l.status,p)}var Ar=m(require("path"));var Er=require("crypto"),Sr=m(require("fs")),Ke=m(require("path"));var So=1024*1024;var Ao=new Int32Array(new SharedArrayBuffer(4));var br=new Set;var kr=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),Dt=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),$t=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Ye(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var Lr=new Set(["cli_op:all"]),Tr=new Set([...Lr].map(Ye));var Yo=new Set([...[...kr,...Dt,...br].map(Ye),...$t,...Tr]);var Ir=new Set([8100]),is=new Set([...Ir,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Or=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,Cr=/^0(?:\.0+)?$/,Ut=128;function Ft(e,t,n={}){if(t.length>Ut)throw new s("input.invalid",`${e} is too long; decimal values may contain at most ${Ut} characters.`);let r=t.trim();if(!Or.test(r))throw new s("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&Cr.test(r))throw new s("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Mt(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new s("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function ie(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new s("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}function Gt(e){let t=ie("--receiver-email",e,254);if(t!==void 0){if(!t.includes("@"))throw new s("input.invalid","--receiver-email is not a valid email.");return t}}var qe=11,Kt=[...It,...B],Rr=B.length>0,He="the beta or sandbox partner API, or an explicit loopback payout API",Yt=Rr?`EVM chain slug. sepolia is a testnet and is accepted only by ${He}.`:"EVM mainnet chain slug.";function qt(e){let t=e.toLowerCase();return t==="sepolia"&&B.includes(t)?qe:Ot(t)}function Ht(e){return e===qe}function jt(e,t){return e===qe?6:Tt(e,t)}var oe=class e extends j{static description="Create and auto-fund a claim link from this store's enabled auto-payout wallet. Authenticates with the store API key/secret (NOT your login), so it needs a store that has completed Payout onboarding. Idempotent on --reference-id.";static examples=["$ ALLSCALE_STORE_API_SECRET=your_store_api_secret allscale payout send --api-key ak_your_api_key --amount 10 --chain base --reference-id order-1042","$ allscale payout send --payout-api-base https://openapi.allscale.io --api-key ak_your_api_key --api-secret your_store_api_secret --amount 25 --stable-coin USDC --chain polygon --reference-id inv-77 --receiver-email client@example.com"];static flags={amount:_.Flags.string({helpGroup:"REQUIRED",description:"Claimable amount in token units (decimal string, e.g. 10 or 25.50); at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:_.Flags.string({helpGroup:"REQUIRED",description:Yt,options:[...Kt],required:!0}),"reference-id":_.Flags.string({helpGroup:"REQUIRED",description:"Your idempotency key (e.g. your order id). REQUIRED \u2014 a retry with the same value is safe (no double-fund).",required:!0}),"payout-api-base":_.Flags.string({description:ae}),"stable-coin":_.Flags.string({description:"Stablecoin to fund in.",options:[...Q],default:"USDT"}),"receiver-email":_.Flags.string({description:"Optional email to send the claim invite to."}),"sender-display-name":_.Flags.string({description:"Optional display name shown to the receiver. Max 100 chars."}),message:_.Flags.string({description:"Optional message shown to the receiver. Max 200 chars."}),"api-key":_.Flags.string({description:"Store API key (public id). Falls back to ALLSCALE_STORE_API_KEY."}),"api-secret":_.Flags.string({description:"Store API secret. Prefer the ALLSCALE_STORE_API_SECRET env var (a flag value can leak via shell history / process list)."}),...j.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);if(t["payout-api-base"]!==void 0&&t["api-base"]!==void 0)throw new s("input.invalid","Use only one of --payout-api-base or the legacy --api-base for payout send.");let n=t["payout-api-base"]?.trim(),r=t["api-base"]?.trim(),i=r!==void 0&&D(r)?r:void 0;if(r!==void 0&&i===void 0){let zt=J(r);(!!1||zt===x)&&H(r)}let o=n??i??gt(),a=o??x;H(a);let c=qt(t.chain);if(c===null)throw new s("input.invalid",`Unsupported --chain '${t.chain}'.`);if(Ht(c)&&!pe(a))throw new s("input.invalid",`--chain sepolia is testnet-only and can be used only with ${He}. No request was sent.`);o===void 0&&S({event:"payout_destination",payout_api_base:a},Et(a));let l=(t["api-key"]??mt())?.trim(),d=(t["api-secret"]??_t())?.trim();if(!l)throw new s("input.invalid","Missing store API key. Pass --api-key or set ALLSCALE_STORE_API_KEY.");if(!d)throw new s("input.invalid","Missing store API secret. Set ALLSCALE_STORE_API_SECRET (preferred) or pass --api-secret.");let f=Ft("--amount",t.amount),p=t["reference-id"].trim();if(!p)throw new s("input.invalid","--reference-id must be a non-empty idempotency key (it deduplicates retries).");let h=Ct(t["stable-coin"]);if(h===null)throw new s("input.invalid",`Unsupported --stable-coin '${t["stable-coin"]}'.`);Mt("--amount",f,jt(c,h));let k=Gt(t["receiver-email"]),W=ie("--sender-display-name",t["sender-display-name"],100),Wt=ie("--message",t.message,200);return Bt({apiBase:a,apiKey:l,apiSecret:d,input:{amount:f,stableCoin:h,chain:c,referenceId:p,receiverEmail:k,senderDisplayName:W,senderMessage:Wt}})}};
|
|
23
23
|
//# sourceMappingURL=send.js.map
|