@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/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- "use strict";var Bn=Object.create;var oe=Object.defineProperty;var Dn=Object.getOwnPropertyDescriptor;var Un=Object.getOwnPropertyNames;var Fn=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var Mn=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Un(t))!$n.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(r=Dn(t,i))||r.enumerable});return e};var w=(e,t,n)=>(n=e!=null?Bn(Fn(e)):{},yt(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),Gn=e=>yt(oe({},"__esModule",{value:!0}),e);var xi={};Mn(xi,{AllscaleCommand:()=>ye,AllscaleError:()=>l,Args:()=>j.Args,Flags:()=>j.Flags,Transport:()=>be,decodeJwt:()=>mn,isExpired:()=>_n,pickTokenStore:()=>Nn});module.exports=Gn(xi);var I=require("@oclif/core");var St="public",Et="https://app.allscale.io";var At=["https://app.allscale.io"];var Re="Override the API base URL (public builds accept only https://app.allscale.io)";var ve="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function wt(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 bt(e){return wt(e)!==null}function Pe(e){let t=wt(e);return t!==null&&At.includes(t.origin)}function W(){return"".trim()||void 0}function J(){return"public"}function v(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function xe(e){try{return new URL(e).origin}catch{return null}}function z(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Ne()}function Ne(){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:u}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:s.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 Kn="device-login",Yn=/^[A-Za-z0-9._-]{1,64}$/;function Ue(e){return Yn.test(e)?e:"<profile>"}function Hn(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Ue(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function se(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Tt(e){let t=Ue(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Hn(e)}\` for headless automation.`}function kt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${Kn} --profile ${Ue(e)}\`.`}var qn={"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_expired":5,"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},jn=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 Fe(e){return(typeof e=="string"?e:String(e??"")).replace(jn,"")}var Wn=64;function Be(e,t=new Map,n=0){if(typeof e=="string")return Fe(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Wn)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Be(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:Be(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var l=class extends Error{code;details;constructor(t,n,r){super(Fe(n)),this.code=t,this.details=r&&Be(r),this.name="AllscaleError"}get exitCode(){return qn[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function It(e){if(e instanceof l)return e;if(e instanceof Error){if(Xn(e)){let t=Zn(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var Jn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),zn=[/^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 Xn(e){if(Vn(e))return!0;let t=e.name??"";return Jn.has(t)?t==="CLIError"?De(e,"parse")||Lt(e.message):!0:Lt(e.message)}function Vn(e){if(!De(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&De(e,"parse")}function Lt(e){return e?Fe(e).split(`
2
- `).some(t=>zn.some(n=>n.test(t.trim()))):!1}function De(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Zn(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ot(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var p=w(require("fs")),de=w(require("path")),Bt=w(require("crypto"));var Qn="...<truncated>",er=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,tr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Ye=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,$e=String.raw`(?:proxy[_-]?)?authorization`,nr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${$e}"|'${$e}'|${$e})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Ye}`,"gi"),rr=/\b(https?:\/\/)[^\s/?#]+@/gi,ir=String.raw`(?:[A-Za-z0-9]+[_-])*`,or=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)`,Ct=Rt(ir),sr=Rt(or),ar=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ct}"|'${Ct}'|${sr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Ye}`,"gi"),Me=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)`,cr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Me}"|'${Me}'|${Me})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Ye}`,"g");function ae(e){return e.replace(rr,"$1<redacted>@").replace(er,"<redacted-jwt>").replace(nr,"$1$2$3<redacted>").replace(ar,"$1$2<redacted>").replace(cr,"$1$2<redacted>").replace(tr,"Bearer <redacted>")}var lr=/(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 ce(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return lr.test(t)}function vt(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 le(e,t,n=Qn){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let i=t-r,o="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>i)break;o+=c,s+=u}return`${o}${n}`}function E(e,t=16384){return le(vt(ae(e)),t)}var Ge=100,ur=8,dr=8*1024;function ue(){return{remaining:dr}}function Ke(e,t){let n=Math.min(16384,t.remaining),r=le(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function F(e,t,n=0,r={}){if(n>ur)return Ke("<truncated>",t);if(typeof e=="string"){let i=ae(e);return Ke(r.escapeControls?vt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Ge),o=i.map(s=>F(s,t,n+1,r));return e.length>i.length&&o.push(Ke(`<${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,Ge))i[s]=F(c,t,n+1,r);return o.length>Ge&&(i.output_truncated=!0),i}return e}var He=require("process");var qe=!1;function je(e){qe=e}function Nt(){return qe}var Pt="1";function M(e,t){if(qe){let n={...e};delete n.version;let r=ue(),i={event:n.event,...n},o=F(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Pt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Pt,event:o.event,output_truncated:!0})),He.stderr.write(`${s}
4
- `)}else He.stderr.write(t)}var xt="2",G=null,T=null,K=!1,X=!1;function fr(){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=Bt.randomBytes(4).toString("hex");return de.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var We=64*1024*1024,pr=null;function Je(e={}){if(e.quiet&&(X=!0),K)return;let t=fr();if(!t)return;G=null;let n=null;try{if((pr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=de.dirname(t);if(p.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=p.statSync(r),d=u.mode&511;if(!u.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=p.constants.O_NOFOLLOW??0;n=p.openSync(t,p.constants.O_APPEND|p.constants.O_CREAT|p.constants.O_WRONLY|(p.constants.O_NONBLOCK??0)|i,384);let o=p.fstatSync(n),s=p.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`);p.fchmodSync(n,384)}catch(r){if(n!==null)try{p.closeSync(n)}catch{}X||M({event:"sidecar_disabled",reason:"open_failed",detail:E(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${E(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}G=t,T=n,K=!0}var gr=[/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 hr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return gr.some(n=>n.test(t))}function Dt(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=mr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)hr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function mr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function _r(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Dt(e.url)}:e}function yr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=F(i,ue()),s=JSON.stringify({version:xt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:xt,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!K||!G||T===null)return;let t=_r(e),n=yr(t);try{if(p.fstatSync(T).size+Buffer.byteLength(n,"utf8")+1>We){K=!1;try{p.closeSync(T)}catch{}T=null,X||M({event:"sidecar_disabled",reason:"size_limit",...G===null?{}:{path:E(G)},max_bytes:We},`${E(`[allscale] sidecar exceeded ${We} bytes; disabling it for the rest of this run. Rotate or remove ${G}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}p.appendFileSync(T,`${n}
7
- `)}catch(r){if(K=!1,T!==null){try{p.closeSync(T)}catch{}T=null}try{X||M({event:"sidecar_disabled",reason:"write_failed",detail:E(r.message)},`${E(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var C=Dt;function Ut(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function V(){if(X=!1,K=!1,T!==null){try{p.closeSync(T)}catch{}T=null}}function Ft(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Ut()||!t}var Z=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"]),Sr=new Set(Array.from(Z).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Er=Array.from(Z).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Ar=new Set(["--otp-stdin","--password-stdin"]);function ze(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(Z.has(s)){t.push(`${s}=<redacted>`);continue}}}if(Z.has(r)){t.push(r),n+1<e.length&&(Z.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(Sr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Ar.has(r)?void 0:Er.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function $t(e){y({type:"error",code:e.code,message:E(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),V()}var Q=W()??Et,H={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 R(e){return bt(e)?new URL(e).origin:null}function k(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Mt(){let e=process.env[H.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Xe(){let e=process.env[H.PROFILE]?.trim();return e&&e.length>0?e:void 0}function fe(){let e=process.env[H.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Gt(){let e=process.env[H.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Kt(){let e=process.env[H.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Yt(){let e=process.env[H.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Ht(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(W()===void 0&&Q!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
1
+ "use strict";var $n=Object.create;var se=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Mn=Object.getOwnPropertyNames;var Gn=Object.getPrototypeOf,Kn=Object.prototype.hasOwnProperty;var Yn=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Mn(t))!Kn.call(e,i)&&i!==n&&se(e,i,{get:()=>t[i],enumerable:!(r=Fn(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?$n(Gn(e)):{},yt(t||!e||!e.__esModule?se(n,"default",{value:e,enumerable:!0}):n,e)),qn=e=>yt(se({},"__esModule",{value:!0}),e);var Hi={};Yn(Hi,{AllscaleCommand:()=>ye,AllscaleError:()=>l,Args:()=>W.Args,Flags:()=>W.Flags,Transport:()=>be,decodeJwt:()=>En,isExpired:()=>wn,pickTokenStore:()=>Dn});module.exports=qn(Hi);var I=require("@oclif/core");var Et="public",wt="https://app.allscale.io";var St=["https://app.allscale.io"];var ve="Override the API base URL (public builds accept only https://app.allscale.io)";var Re="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function At(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 bt(e){return At(e)!==null}function Ne(e){let t=At(e);return t!==null&&St.includes(t.origin)}function J(){return"".trim()||void 0}function $(){return"public"}function v(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function xe(e){try{return new URL(e).origin}catch{return null}}function z(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Pe()}function Pe(){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:u}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:s.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 jn="device-login",Hn=/^[A-Za-z0-9._-]{1,64}$/;function Ue(e){return Hn.test(e)?e:"<profile>"}function Wn(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Ue(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ae(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function kt(e){let t=Ue(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Wn(e)}\` for headless automation.`}function Tt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${jn} --profile ${Ue(e)}\`.`}var Jn={"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},zn=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 $e(e){return(typeof e=="string"?e:String(e??"")).replace(zn,"")}var Vn=64;function Be(e,t=new Map,n=0){if(typeof e=="string")return $e(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Vn)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Be(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:Be(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var l=class extends Error{code;details;constructor(t,n,r){super($e(n)),this.code=t,this.details=r&&Be(r),this.name="AllscaleError"}get exitCode(){return Jn[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function It(e){if(e instanceof l)return e;if(e instanceof Error){if(Qn(e)){let t=tr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var Xn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Zn=[/^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 Qn(e){if(er(e))return!0;let t=e.name??"";return Xn.has(t)?t==="CLIError"?De(e,"parse")||Lt(e.message):!0:Lt(e.message)}function er(e){if(!De(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&De(e,"parse")}function Lt(e){return e?$e(e).split(`
2
+ `).some(t=>Zn.some(n=>n.test(t.trim()))):!1}function De(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function tr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ot(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var h=A(require("fs")),fe=A(require("path")),Bt=A(require("crypto"));var nr="...<truncated>",rr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,ir=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Ye=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Fe=String.raw`(?:proxy[_-]?)?authorization`,or=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Fe}"|'${Fe}'|${Fe})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Ye}`,"gi"),sr=/\b(https?:\/\/)[^\s/?#]+@/gi,ar=String.raw`(?:[A-Za-z0-9]+[_-])*`,cr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,vt=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)`,Ct=vt(ar),lr=vt(cr),ur=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ct}"|'${Ct}'|${lr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Ye}`,"gi"),Me=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)`,dr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Me}"|'${Me}'|${Me})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Ye}`,"g");function ce(e){return e.replace(sr,"$1<redacted>@").replace(rr,"<redacted-jwt>").replace(or,"$1$2$3<redacted>").replace(ur,"$1$2<redacted>").replace(dr,"$1$2<redacted>").replace(ir,"Bearer <redacted>")}var fr=/(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 fr.test(t)}function Rt(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 ue(e,t,n=nr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let i=t-r,o="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>i)break;o+=c,s+=u}return`${o}${n}`}function w(e,t=16384){return ue(Rt(ce(e)),t)}var Ge=100,pr=8,hr=8*1024;function de(){return{remaining:hr}}function Ke(e,t){let n=Math.min(16384,t.remaining),r=ue(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function F(e,t,n=0,r={}){if(n>pr)return Ke("<truncated>",t);if(typeof e=="string"){let i=ce(e);return Ke(r.escapeControls?Rt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Ge),o=i.map(s=>F(s,t,n+1,r));return e.length>i.length&&o.push(Ke(`<${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,Ge))i[s]=F(c,t,n+1,r);return o.length>Ge&&(i.output_truncated=!0),i}return e}var qe=require("process");var je=!1;function He(e){je=e}function Pt(){return je}var Nt="1";function G(e,t){if(je){let n={...e};delete n.version;let r=de(),i={event:n.event,...n},o=F(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Nt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Nt,event:o.event,output_truncated:!0})),qe.stderr.write(`${s}
4
+ `)}else qe.stderr.write(t)}var xt="2",K=null,k=null,Y=!1,V=!1;function gr(){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=Bt.randomBytes(4).toString("hex");return fe.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var We=64*1024*1024,mr=null;function Je(e={}){if(e.quiet&&(V=!0),Y)return;let t=gr();if(!t)return;K=null;let n=null;try{if((mr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=fe.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=h.statSync(r),d=u.mode&511;if(!u.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=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|i,384);let o=h.fstatSync(n),s=h.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`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}V||G({event:"sidecar_disabled",reason:"open_failed",detail:w(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${w(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}K=t,k=n,Y=!0}var _r=[/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 yr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return _r.some(n=>n.test(t))}function Dt(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=Er(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)yr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Er(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function wr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Dt(e.url)}:e}function Sr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=F(i,de()),s=JSON.stringify({version:xt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:xt,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!Y||!K||k===null)return;let t=wr(e),n=Sr(t);try{if(h.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>We){Y=!1;try{h.closeSync(k)}catch{}k=null,V||G({event:"sidecar_disabled",reason:"size_limit",...K===null?{}:{path:w(K)},max_bytes:We},`${w(`[allscale] sidecar exceeded ${We} bytes; disabling it for the rest of this run. Rotate or remove ${K}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}h.appendFileSync(k,`${n}
7
+ `)}catch(r){if(Y=!1,k!==null){try{h.closeSync(k)}catch{}k=null}try{V||G({event:"sidecar_disabled",reason:"write_failed",detail:w(r.message)},`${w(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var C=Dt;function Ut(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function X(){if(V=!1,Y=!1,k!==null){try{h.closeSync(k)}catch{}k=null}}function $t(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Ut()||!t}var Z=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"]),Ar=new Set(Array.from(Z).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),br=Array.from(Z).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Lr=new Set(["--otp-stdin","--password-stdin"]);function ze(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(Z.has(s)){t.push(`${s}=<redacted>`);continue}}}if(Z.has(r)){t.push(r),n+1<e.length&&(Z.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(Ar.has(o)){t.push(`${o}<redacted>`);continue}}let i=Lr.has(r)?void 0:br.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function Ft(e){y({type:"error",code:e.code,message:w(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),X()}var Q=J()??wt,j={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 R(e){return bt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Mt(){let e=process.env[j.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Ve(){let e=process.env[j.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ee(){let e=process.env[j.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Gt(){let e=process.env[j.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Kt(){let e=process.env[j.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Yt(){let e=process.env[j.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function qt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(J()===void 0&&Q!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
9
  The CLI default is now ${Q} (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
13
  To move to production, run: allscale device-login --api-base ${Q}
14
- `}var P=w(require("fs")),qt=w(require("os")),Ve=w(require("path")),Ze=w(require("@iarna/toml"));var Lr=".allscale",Tr="config.toml";function Qe(){return Ve.join(qt.homedir(),Lr)}function kr(){return Ve.join(Qe(),Tr)}function pe(){let e=kr();if(!P.existsSync(e))return{};let t=P.readFileSync(e,"utf-8");try{return Ze.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function jt(e){return Object.keys(e.profile??{}).sort()}function Wt(e,t){return e.profile?.[t]}function Jt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function q(e){if(!Pe(e))throw new l("input.invalid",`Refusing to send credentials to API base ${k(e)}. `+ve)}function ge(e,t){q(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let i=typeof t=="string"?k(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${k(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function zt(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${k(t)} because it is outside the configured API origin ${k(e)}.`)}function he(e){let t=W();if(t===void 0||v(e))return;let n=R(e),r=z();if(r.length>0){let o=r.map(c=>R(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>k(c.base)).join(", ");throw new l("input.invalid",`Refusing to send to ${k(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=R(t);if(!(n!==null&&n===i))throw new l("input.invalid",`Refusing to send to ${k(e)} \u2014 this build only signs for ${k(t)}. Re-login against this build's environment, or use a build for that one.`)}var Ir=require("@noble/hashes/sha3");var Xt=["USDT","USDC"];var wo=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var j=require("@oclif/core"),ye=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:J()==="public"}),"api-base":I.Flags.string({description:Re,helpGroup:"GLOBAL",hidden:J()==="public"}),"insecure-storage":I.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{je(this.jsonEnabled()),Je(),y({type:"session-start",command:this.id??"",argv:ze(this.argv)});let t=this.constructor;if(J()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("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 l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&fe()!==void 0)throw new l("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=Ft(this.jsonEnabled()),r=this.argv.length===0&&!n&&xr(t)?this.config.findCommand(this.id??""):void 0;if(r){V();let o=await(0,I.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&&!Yt())throw this.argv.length>0&&await this.parse(),new l("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}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ot(i),{data:i})}catch(t){let n=It(t);$t({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{je(!1)}}resolveSessionApiBaseChain(t){let n=pe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Xe()!==void 0,s=Jt(n,r,Xe()),c=Wt(n,s),u=i??fe(),d=u??c?.api_base??Q,f=Ht({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,M({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||q(n),n}resolveContext(t){if(J()==="public"){if(t.token!==void 0)throw new l("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 l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&fe()!==void 0)throw new l("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:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(i),he(i)),{apiBase:i,profile:s,token:n??Mt(),insecureStorage:r||Gt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Nr(t)}
15
- `)}};var Or=/_(removed|cleared|count|total)$/i;function Cr(e,t){return typeof t=="number"&&Or.test(e)}var Rr=new Set(Xt);function vr(e,t){return e==="token_symbol"&&typeof t=="string"&&Rr.has(t)}var me=100;function _e(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,me),r=n.map(i=>_e(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,me))n[i]=ce(i)&&!Cr(i,o)&&!vr(i,o)?"<redacted>":_e(o,t+1);if(r.length>me){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-me} more keys`}return n}if(typeof e=="string"){let n=Pr(e);return n!==void 0?E(JSON.stringify(_e(n,t+1))):E(e)}return e}function Pr(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 Nr(e){let t=Nt()?void 0:2,n=_e(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:E(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function xr(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 Se="allscale_access_token",et="allscale_refresh_token";function Vt(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function tt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function nt(e,t){return e.find(n=>n.name===t)?.value??null}var Zt=w(require("crypto")),Qt=w(require("fs")),en=w(require("path"));var Br="key-id",Dr="x-allscale-cli-version",rt="cli-1",Ur="aScaLe_cli_obf_v1",Fr="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function $r(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 Mr=$r(Fr,Ur),tn=`Bearer ${Mr}`;function nn(e,t){let n=xe(e);if(n!==null)return t.find(r=>xe(r.base)===n)}function Gr(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=nn(e,t);if(r)return r.key;if(v(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:v(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 Kr(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?nn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&v(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():rt}if(!v(t[0].base))return rt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():rt}function Yr(){return"1.0.1"}function Hr(){return new l("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 it(e,t){let n=Gr(t);if(!n)throw Hr();let r=Kr(t),i=Math.floor(Date.now()/1e3).toString(),o=Zt.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Dr]:Yr()};return r.length>0&&(s[Br]=r),s}function rn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function qr(e,t={}){let n;try{n=jt(pe())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",kt(e)+(t.messageSuffix??""),{profile:e})}function on(e){if(e.profileExplicit){let t=qr(e.profile);if(t)return t}return new l("auth.no_token",Tt(e.profile))}var jr=500,Wr=8,sn=100;function ot(e,t=0){if(t>Wr)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,sn),r=n.map(i=>ot(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,sn))n[r]=ce(r)?"<redacted>":ot(i,t+1);return n}return e}function Jr(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 an(e,t=jr){let n=Jr(e),r=n===void 0?ae(e):JSON.stringify(ot(n));return le(r,t)}var st=256*1024,Ee=class extends l{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"}},Ae=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 at(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 Ee(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((g,L)=>{u=setTimeout(()=>{L(new Ae(e.status,d))},d),u.unref?.()});try{for(;;){let g=o.read(),{done:L,value:h}=f?await Promise.race([g,f]):await g;if(L)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(g){throw g instanceof Ae&&o.cancel(g).catch(()=>{}),g}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var zr="X-AllScale-Api-Key",Xr=3e4,Vr=32*1024*1024,Zr=4*1024*1024;function Qr(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function ei(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function ti(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(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 fn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ti(e.status,e.url)}}var cn="--dns-result-order=ipv4first";async function we(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${cn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${cn}`})}var be=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??Xr;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");q(this.opts.apiBase),he(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=Qr(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();zt(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=pn(t.path),u=s==="required"?!0:s==="none"?!1:oi(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw on({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=rn(t.body),f=!!o||!!r?.access_token;u&&f&&!this.opts.override&&ge(this.opts.apiBase,r?.api_base);let g=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),L=Date.now();y({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:g,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(A){throw new l("transport.network",`Network error contacting ${C(i)}: ${A instanceof Error?A.message:String(A)}`)}if(y({type:"response",status:h.status,durationMs:Date.now()-L}),u&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let A=await ei(this.refreshSingleFlight(),t.signal),ie=this.buildHeaders({attachAuth:u&&!!A.access_token,bodyForSig:d,tokens:A,extra:t.headers}),xn=Date.now();y({type:"request",method:t.method??"GET",url:i});let Oe;try{Oe=await fetch(i,{method:t.method??"GET",headers:ie,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Ce){throw new l("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Ce instanceof Error?Ce.message:String(Ce)}`)}return y({type:"response",status:Oe.status,durationMs:Date.now()-xn}),ln(Oe,{withMetadata:n.withMetadata,authBearing:u,responseKind:un(t)})}return ln(h,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!o,responseKind:un(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...it(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=tn;let i=t.tokens;if(i?.agent_key)return r[zr]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=tt([{name:Se,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(ge(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${se()}.`);if(ge(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=tt([{name:Se,value:t.access_token},{name:et,value:t.refresh_token}]),i=it("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw y({type:"refresh",ok:!1}),new l("transport.network",s&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}y({type:"response",status:u.status,durationMs:0});try{await fn(u)}catch(h){throw y({type:"refresh",ok:!1}),h}if(u.status!==200){let h=null;try{await we(u);let S=await ui(u);await we(u,S),hn(u.status,S),u.status===401&&(h=await this.adoptConcurrentlyRotatedTokens(t))}catch(S){throw y({type:"refresh",ok:!1}),S}if(h)return y({type:"refresh",ok:!0,adopted:!0}),h;throw y({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${se()}.`,{status:u.status})}let d=Vt(u.headers),f=nt(d,Se),g=nt(d,et);if(!f||!g)throw y({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let L={...t,access_token:f,refresh_token:g};return await this.opts.tokenStore.set(this.opts.profile,L),y({type:"refresh",ok:!0}),L}},ni=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function pn(e){let t=e.split(/[?#]/,1)[0];return ni.some(n=>t===n||t.startsWith(`${n}/`))}var ri=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function ii(e){let t=e.split(/[?#]/,1)[0];return ri.some(n=>n.test(t))}function oi(e){return pn(e)||ii(e)}async function ln(e,t={}){await fn(e);let n=e.status>=200&&e.status<300;n||await we(e);let r=t.responseKind??"mutation",o=await at(e,n?r==="query"?Vr:Zr:st,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await we(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=di(s)??`HTTP ${e.status}`;if(hn(e.status,s),ci(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function un(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var si=2014,dn=2004;function gn(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 ai(e){return gn(e,si)}function ci(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&gn(t,dn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${se()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:dn})}var li=1e4;async function ui(e,t=li){if(e.status>=200&&e.status<300)return"";try{return await at(e,st,{timeoutMs:t})}catch{return""}}function hn(e,t){if(!(e>=200&&e<300)&&ai(t))throw new l("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"?an(t):t})}function di(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}function mn(e){let t=e.split(".");if(t.length!==3)throw new l("auth.token_expired","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");try{let n=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(n)}catch(n){throw new l("auth.token_expired",`Failed to decode JWT payload: ${n.message}`)}}function _n(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var Rn=w(require("path"));var ut=require("crypto"),a=w(require("fs")),_=w(require("path"));var Le=1024*1024,fi=5e3,pi=20,gi=3e4,ct=4096,hi=new Int32Array(new SharedArrayBuffer(4)),ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Te(e){return e instanceof ee}var b=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},mi=null;function x(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function ke(){return(mi??process.platform)!=="win32"}function Tn(){if(!ke())throw x()}function kn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(e,t){return typeof e=="object"&&e!==null&&e.code===t}function te(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ne(e,t){return e.dev===t.dev&&e.ino===t.ino}function _i(e){Atomics.wait(hi,0,0,e)}function In(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function yi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&m(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!ne(o,s))throw new Error("credential-store parent changed while it was being inspected");te(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),c=a.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&m(o,"ENOENT")?new b:o}if(!ne(n,i))throw r.retryOnPathChange?new b:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new ee;if(te(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Si(e,t){if(t.size>Le)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Le+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Le)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Sn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(m(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return Si(t,r)}finally{t!==null&&a.default.closeSync(t)}}function En(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT")&&kn(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);B(e,r)}finally{t!==null&&a.default.closeSync(t)}Cn(_.dirname(e))}function Ei(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new ee;te(t,"credential-store replacement target")}function Ai(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.randomBytes)(12).toString("hex"),i=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(m(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function On(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Cn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function wi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Le)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),i=_.basename(e),o=null,s=null,c=!1;try{let u=Ai(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");On(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let g=o;o=null,a.default.closeSync(g),Ei(e),a.default.renameSync(s,e),c=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Cn(r)}function bi(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Li(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Ti(e,t){if(t.size>ct)return null;let n=Buffer.alloc(ct+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>ct)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function B(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ne(n,t))throw new Error("credential-store lock changed while it was being inspected");te(n,"credential-store lock"),a.default.unlinkSync(e)}function An(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(m(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new b}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Ti(n,i);return{state:(o?.target===t&&o?!In(o.pid):Date.now()-i.mtimeMs>=gi)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function ki(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.randomBytes)(12).toString("hex"),i=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(i,s,c,{allowMultipleLinks:!0});return On(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ii(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw m(r,"ENOENT")?new b:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ne(i,t))throw new b;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function wn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new b}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Oi(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{B(e,n)}catch{}throw a.default.closeSync(t),r}}function N(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");_i(pi)}function bn(e){let t=_.dirname(e),n=_.basename(e),r=bi(e),i=Li(e),o=ki(t,n),s=Date.now()+fi,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(wn(i)){N(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Ii(r,o.stats),c=!0}catch(g){if(u&&!c){try{B(r,o.stats)}catch{}u=!1}if(g instanceof b){N(s,!1);continue}if(!m(g,"EEXIST"))throw g;let L;try{L=An(r,n)}catch(S){if(S instanceof b){N(s,!1);continue}throw S}if(L.state==="absent")continue;if(L.state==="stale"){let S;try{S=Oi(i)}catch(A){if(A instanceof b){N(s,!1);continue}throw A}if(S!==null){try{let A;try{A=An(r,n)}catch(ie){if(ie instanceof b){N(s,!1);continue}throw ie}A.state==="stale"&&B(r,A.stats)}finally{lt(S)}continue}}let h;try{h=wn(i)}catch(S){if(S instanceof b){N(s,!1);continue}throw S}N(s,h)}}catch(g){f=g}try{B(o.claimPath,o.stats)}catch(g){!m(g,"ENOENT")&&!c&&f===void 0&&(f=g)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function lt(e){try{B(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Ci(e,t){let n=yi(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function Ln(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let i=Ci(r,n);if(i===null||In(i))continue;let o=_.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!ne(c,u))continue;try{te(c,"credential-store orphan")}catch{continue}B(o,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function re(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw x();if(!yn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw x()}});let s=bn(e);try{return Ln(e),n({read:()=>Sn(e),remove:()=>En(e),write:()=>{throw x()}})}finally{lt(s)}}if(!t.createParent){let o=!1;try{o=kn(e)}catch{throw x()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw x()}})}throw x()}if(!yn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=bn(e);try{return Ln(e),n({read:()=>Sn(e),remove:()=>En(e),write:o=>wi(e,o)})}finally{lt(i)}}var dt="allscale-cli";function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e){return ht(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function U(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function ft(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Ie(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var D,pt=!1;function Ri(){return Kt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function vi(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
- `,1)[0]==="Cannot find module 'keytar'"}function Pi(){if(D!==void 0)return D;if(Ri())return pt=!1,D=null,D;try{D=require("keytar"),pt=!1}catch(e){pt=!vi(e),D=null}return D}function Pn(){let e=ke()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function gt(e){try{return await e()}catch{throw Pn()}}var mt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await gt(()=>this.keytar.getPassword(dt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw U("OS keychain")}if(!vn(r))throw U("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await gt(()=>this.keytar.setPassword(dt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await gt(()=>this.keytar.deletePassword(dt,t))}},Ni="credentials.json",_t=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Rn.join(Qe(),Ni)}read(t){let n;try{n=t.read()}catch(i){throw Te(i)?ft():U("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw U("plaintext file")}if(!ht(r)||!ht(r.profiles))throw U("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Te(r)?ft():Ie()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!vn(r))throw U("plaintext file");return r}}async get(t){try{return re(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:U("plaintext file")}}async set(t,n){try{re(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof l?r:Ie()}}async delete(t){try{re(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Ie()}}async clearProfile(t){try{return re(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Te(n)?ft():Ie()}}};function Nn(e){if(e.insecureStorage)return Tn(),new _t(e.insecureFilePath);let t=Pi();if(t)return new mt(t);throw Pn()}0&&(module.exports={AllscaleCommand,AllscaleError,Args,Flags,Transport,decodeJwt,isExpired,pickTokenStore});
14
+ `}var N=A(require("fs")),jt=A(require("os")),Xe=A(require("path")),Ze=A(require("@iarna/toml"));var Ir=".allscale",Or="config.toml";function Qe(){return Xe.join(jt.homedir(),Ir)}function Cr(){return Xe.join(Qe(),Or)}function pe(){let e=Cr();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return Ze.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function Ht(e){return Object.keys(e.profile??{}).sort()}function Wt(e,t){return e.profile?.[t]}function Jt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function H(e){if(!Ne(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Re)}function he(e,t){H(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function zt(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ge(e){let t=Rr(e);if(t)throw new l("input.invalid",t.message)}function vr(){let e=J();if(e===void 0)return;let t=z();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Rr(e){let t=vr();if(t===void 0||v(e))return;let{endpoints:n,fromPairs:r}=t,i=R(e),o=n.map(c=>R(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(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 ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Nr=require("@noble/hashes/sha3");var Vt=["USDT","USDC"];var xo=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Pr="unknown_otp_id",xr="invalid_code",Br="expired_code";function Dr(e){return`'${e.replace(/'/g,"'\\''")}'`}function Xt(e){return`Run \`allscale otp-send --email ${Dr(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Ur=new Map([[Pr,(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. ${Xt(t)}`],[xr,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.`],[Br,(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. ${Xt(t)}`]]);var Zt=[...Ur.keys()];var W=require("@oclif/core"),ye=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:$()==="public"}),"api-base":I.Flags.string({description:ve,helpGroup:"GLOBAL",hidden:$()==="public"}),"insecure-storage":I.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{He(this.jsonEnabled()),Je(),y({type:"session-start",command:this.id??"",argv:ze(this.argv)});let t=this.constructor;if($()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("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 l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ee()!==void 0)throw new l("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(this.jsonEnabled()),r=this.argv.length===0&&!n&&Hr(t)?this.config.findCommand(this.id??""):void 0;if(r){X();let o=await(0,I.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&&!Yt())throw this.argv.length>0&&await this.parse(),new l("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()||Ot(i),{data:i})}catch(t){let n=It(t);Ft({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{He(!1)}}resolveSessionApiBaseChain(t){let n=pe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Ve()!==void 0,s=Jt(n,r,Ve()),c=Wt(n,s),u=$()==="public"&&ee()!==void 0,d=i??(u?void 0:ee()),f=d??c?.api_base??Q,p=qt({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,G({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||H(n),n}resolveContext(t){if($()==="public"){if(t.token!==void 0)throw new l("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 l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ee()!==void 0)throw new l("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:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(H(i),ge(i)),{apiBase:i,profile:c,token:n??Mt(),insecureStorage:r||Gt(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${jr(t)}
15
+ `)}};var $r=/_(removed|cleared|count|total)$/i;function Fr(e,t){return typeof t=="number"&&$r.test(e)}var Mr=new Set(Vt);function Gr(e,t){return e==="token_symbol"&&typeof t=="string"&&Mr.has(t)}var Kr=new Set(Zt);function Yr(e,t){return e==="otp_reason"&&typeof t=="string"&&Kr.has(t)}var me=100;function _e(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,me),r=n.map(i=>_e(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,me))n[i]=le(i)&&!Fr(i,o)&&!Gr(i,o)&&!Yr(i,o)?"<redacted>":_e(o,t+1);if(r.length>me){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-me} more keys`}return n}if(typeof e=="string"){let n=qr(e);return n!==void 0?w(JSON.stringify(_e(n,t+1))):w(e)}return e}function qr(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 jr(e){let t=Pt()?void 0:2,n=_e(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:w(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Hr(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 Ee="allscale_access_token",et="allscale_refresh_token";function Qt(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function tt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function nt(e,t){return e.find(n=>n.name===t)?.value??null}var en=A(require("crypto")),tn=A(require("fs")),nn=A(require("path"));var Wr="key-id",Jr="x-allscale-cli-version",rt="cli-1",zr="aScaLe_cli_obf_v1",Vr="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Xr(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 Zr=Xr(Vr,zr),rn=`Bearer ${Zr}`;function on(e,t){let n=xe(e);if(n!==null)return t.find(r=>xe(r.base)===n)}function Qr(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=on(e,t);if(r)return r.key;if(v(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:v(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 ei(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?on(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&v(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():rt}if(!v(t[0].base))return rt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():rt}function ti(){return"1.0.2"}function ni(){return new l("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 it(e,t){let n=Qr(t);if(!n)throw ni();let r=ei(t),i=Math.floor(Date.now()/1e3).toString(),o=en.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Jr]:ti()};return r.length>0&&(s[Wr]=r),s}function sn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ri(e,t={}){let n;try{n=Ht(pe())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Tt(e)+(t.messageSuffix??""),{profile:e})}function an(e){if(e.profileExplicit){let t=ri(e.profile);if(t)return t}return new l("auth.no_token",kt(e.profile))}var ii=500,oi=8,cn=100;function ot(e,t=0){if(t>oi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,cn),r=n.map(i=>ot(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,cn))n[r]=le(r)?"<redacted>":ot(i,t+1);return n}return e}function si(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 ln(e,t=ii){let n=si(e),r=n===void 0?ce(e):JSON.stringify(ot(n));return ue(r,t)}var st=256*1024,we=class extends l{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"}},Se=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 at(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 we(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,L)=>{u=setTimeout(()=>{L(new Se(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:L,value:g}=f?await Promise.race([p,f]):await p;if(L)break;if(c+=g.byteLength,c>t)throw o.cancel().catch(()=>{}),new we(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Se&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var ai="X-AllScale-Api-Key",ci=3e4,li=32*1024*1024,ui=4*1024*1024;function di(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function fi(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function pi(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(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 hn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}pi(e.status,e.url)}}var un="--dns-result-order=ipv4first";async function Ae(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${un} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${un}`})}var be=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??ci;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");H(this.opts.apiBase),ge(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=di(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();zt(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=gn(t.path),u=s==="required"?!0:s==="none"?!1:_i(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw an({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=sn(t.body),f=!!o||!!r?.access_token;u&&f&&!this.opts.override&&he(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),L=Date.now();y({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(S){throw new l("transport.network",`Network error contacting ${C(i)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-L}),u&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let S=await fi(this.refreshSingleFlight(),t.signal),oe=this.buildHeaders({attachAuth:u&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),Un=Date.now();y({type:"request",method:t.method??"GET",url:i});let Oe;try{Oe=await fetch(i,{method:t.method??"GET",headers:oe,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Ce){throw new l("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Ce instanceof Error?Ce.message:String(Ce)}`)}return y({type:"response",status:Oe.status,durationMs:Date.now()-Un}),dn(Oe,{withMetadata:n.withMetadata,authBearing:u,responseKind:fn(t)})}return dn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!o,responseKind:fn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...it(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=rn;let i=t.tokens;if(i?.agent_key)return r[ai]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=tt([{name:Ee,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(he(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${ae()}.`);if(he(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=tt([{name:Ee,value:t.access_token},{name:et,value:t.refresh_token}]),i=it("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(g){throw y({type:"refresh",ok:!1}),new l("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}y({type:"response",status:u.status,durationMs:0});try{await hn(u)}catch(g){throw y({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await Ae(u);let E=await Ai(u);await Ae(u,E),_n(u.status,E),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(E){throw y({type:"refresh",ok:!1}),E}if(g)return y({type:"refresh",ok:!0,adopted:!0}),g;throw y({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ae()}.`,{status:u.status})}let d=Qt(u.headers),f=nt(d,Ee),p=nt(d,et);if(!f||!p)throw y({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let L={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,L),y({type:"refresh",ok:!0}),L}},hi=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function gn(e){let t=e.split(/[?#]/,1)[0];return hi.some(n=>t===n||t.startsWith(`${n}/`))}var gi=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function mi(e){let t=e.split(/[?#]/,1)[0];return gi.some(n=>n.test(t))}function _i(e){return gn(e)||mi(e)}async function dn(e,t={}){await hn(e);let n=e.status>=200&&e.status<300;n||await Ae(e);let r=t.responseKind??"mutation",o=await at(e,n?r==="query"?li:ui:st,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ae(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=bi(s)??`HTTP ${e.status}`;if(_n(e.status,s),wi(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function fn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var yi=2014,pn=2004;function mn(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 Ei(e){return mn(e,yi)}function wi(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&mn(t,pn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ae()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:pn})}var Si=1e4;async function Ai(e,t=Si){if(e.status>=200&&e.status<300)return"";try{return await at(e,st,{timeoutMs:t})}catch{return""}}function _n(e,t){if(!(e>=200&&e<300)&&Ei(t))throw new l("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"?ln(t):t})}function bi(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}function En(e){let t=e.split(".");if(t.length!==3)throw new l("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let n;try{let r=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");n=JSON.parse(r)}catch{throw yn()}if(typeof n!="object"||n===null||Array.isArray(n))throw yn();return n}function yn(){return new l("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}function wn(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var Pn=A(require("path"));var ut=require("crypto"),a=A(require("fs")),_=A(require("path"));var Le=1024*1024,Li=5e3,ki=20,Ti=3e4,ct=4096,Ii=new Int32Array(new SharedArrayBuffer(4)),te=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ke(e){return e instanceof te}var b=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Oi=null;function x(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Te(){return(Oi??process.platform)!=="win32"}function On(){if(!Te())throw x()}function Cn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ne(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function re(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ci(e){Atomics.wait(Ii,0,0,e)}function vn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function vi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&m(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!re(o,s))throw new Error("credential-store parent changed while it was being inspected");ne(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),c=a.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&m(o,"ENOENT")?new b:o}if(!re(n,i))throw r.retryOnPathChange?new b:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new te;if(ne(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Ri(e,t){if(t.size>Le)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Le+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Le)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function An(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(m(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return Ri(t,r)}finally{t!==null&&a.default.closeSync(t)}}function bn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT")&&Cn(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);B(e,r)}finally{t!==null&&a.default.closeSync(t)}Nn(_.dirname(e))}function Ni(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new te;ne(t,"credential-store replacement target")}function Pi(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.randomBytes)(12).toString("hex"),i=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(m(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Rn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Nn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function xi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Le)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),i=_.basename(e),o=null,s=null,c=!1;try{let u=Pi(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Rn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ni(e),a.default.renameSync(s,e),c=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Nn(r)}function Bi(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Di(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Ui(e,t){if(t.size>ct)return null;let n=Buffer.alloc(ct+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>ct)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function B(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!re(n,t))throw new Error("credential-store lock changed while it was being inspected");ne(n,"credential-store lock"),a.default.unlinkSync(e)}function Ln(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(m(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new b}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Ui(n,i);return{state:(o?.target===t&&o?!vn(o.pid):Date.now()-i.mtimeMs>=Ti)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function $i(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.randomBytes)(12).toString("hex"),i=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(i,s,c,{allowMultipleLinks:!0});return Rn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Fi(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw m(r,"ENOENT")?new b:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!re(i,t))throw new b;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function kn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new b}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Mi(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{B(e,n)}catch{}throw a.default.closeSync(t),r}}function P(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");Ci(ki)}function Tn(e){let t=_.dirname(e),n=_.basename(e),r=Bi(e),i=Di(e),o=$i(t,n),s=Date.now()+Li,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(kn(i)){P(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Fi(r,o.stats),c=!0}catch(p){if(u&&!c){try{B(r,o.stats)}catch{}u=!1}if(p instanceof b){P(s,!1);continue}if(!m(p,"EEXIST"))throw p;let L;try{L=Ln(r,n)}catch(E){if(E instanceof b){P(s,!1);continue}throw E}if(L.state==="absent")continue;if(L.state==="stale"){let E;try{E=Mi(i)}catch(S){if(S instanceof b){P(s,!1);continue}throw S}if(E!==null){try{let S;try{S=Ln(r,n)}catch(oe){if(oe instanceof b){P(s,!1);continue}throw oe}S.state==="stale"&&B(r,S.stats)}finally{lt(E)}continue}}let g;try{g=kn(i)}catch(E){if(E instanceof b){P(s,!1);continue}throw E}P(s,g)}}catch(p){f=p}try{B(o.claimPath,o.stats)}catch(p){!m(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function lt(e){try{B(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Gi(e,t){let n=vi(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function In(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let i=Gi(r,n);if(i===null||vn(i))continue;let o=_.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!re(c,u))continue;try{ne(c,"credential-store orphan")}catch{continue}B(o,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ie(e,t,n){if(!Te()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw x();if(!Sn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw x()}});let s=Tn(e);try{return In(e),n({read:()=>An(e),remove:()=>bn(e),write:()=>{throw x()}})}finally{lt(s)}}if(!t.createParent){let o=!1;try{o=Cn(e)}catch{throw x()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw x()}})}throw x()}if(!Sn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Tn(e);try{return In(e),n({read:()=>An(e),remove:()=>bn(e),write:o=>xi(e,o)})}finally{lt(i)}}var dt="allscale-cli";function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e){return gt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function U(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function ft(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Ie(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var D,pt=!1;function Ki(){return Kt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Yi(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function qi(){if(D!==void 0)return D;if(Ki())return pt=!1,D=null,D;try{D=require("keytar"),pt=!1}catch(e){pt=!Yi(e),D=null}return D}function Bn(){let e=Te()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function ht(e){try{return await e()}catch{throw Bn()}}var mt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ht(()=>this.keytar.getPassword(dt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw U("OS keychain")}if(!xn(r))throw U("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ht(()=>this.keytar.setPassword(dt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ht(()=>this.keytar.deletePassword(dt,t))}},ji="credentials.json",_t=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Pn.join(Qe(),ji)}read(t){let n;try{n=t.read()}catch(i){throw ke(i)?ft():U("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw U("plaintext file")}if(!gt(r)||!gt(r.profiles))throw U("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ke(r)?ft():Ie()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!xn(r))throw U("plaintext file");return r}}async get(t){try{return ie(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:U("plaintext file")}}async set(t,n){try{ie(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof l?r:Ie()}}async delete(t){try{ie(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Ie()}}async clearProfile(t){try{return ie(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:ke(n)?ft():Ie()}}};function Dn(e){if(e.insecureStorage)return On(),new _t(e.insecureFilePath);let t=qi();if(t)return new mt(t);throw Bn()}0&&(module.exports={AllscaleCommand,AllscaleError,Args,Flags,Transport,decodeJwt,isExpired,pickTokenStore});
17
17
  //# sourceMappingURL=index.js.map
@@ -204,7 +204,7 @@
204
204
  "type": "option"
205
205
  },
206
206
  "scopes": {
207
- "description": "Requested scopes for the eventual agent key, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs the approval screen can grant: invoice:{read_only,all}, contact:{read_only,all}, transaction:read_only, wallet:read_only, claim_link:{read_only,all}, store:{read_only,all}. The final set is chosen — and can be overridden — on that screen, and is checked by the backend on each request. The Wallets toggle is on by default and grants `wallet:read_only`, which `wallet list` needs and `invoice pay` needs as ONE of its two scopes `invoice pay` also needs `invoice:all` request it here with `--scopes invoice:all` (it is forwarded to the approval screen), and tick the Invoices write tier there, since that toggle starts at Read. Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any pairing session is registered — the same check, and the same exit code, as `otp-login --scopes`. A recognised scope the screen declines to grant is reported after the key is minted, not up front.",
207
+ "description": "Requested scopes for the eventual agent key, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs the approval screen can grant: invoice:{read_only,all}, contact:{read_only,all}, transaction:read_only, wallet:{read_only,all}, claim_link:{read_only,all}, store:{read_only,all}. The final set is chosen — and can be overridden — on that screen, and is checked by the backend on each request. The Wallets read toggle is on by default and grants `wallet:read_only`, which `wallet list` needs. `invoice pay` needs `invoice:all` AND `wallet:all` its withdrawal registration rides the same broker op as `wallet send` (backend gates the op, not the verb), and the write tier covers its payer-address read via the implication — so request both (`--scopes invoice:all --scopes wallet:all`) and tick the Invoices write tier plus the Wallets Allow-changes tier on the screen (Invoices starts at Read; Allow-changes starts OFF). `wallet send` requires `wallet:all` the same way; every transfer still requires your in-browser confirmation. Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any pairing session is registered — the same check, and the same exit code, as `otp-login --scopes`. A recognised scope the screen has no toggle for is also rejected locally, with the remediation that actually works: otp-login for operational scopes (or `--allow-unrenderable-scopes` when your web app is newer than this CLI's catalog), nothing for payroll/admin:* — the approval page refuses the whole authorization when even one requested scope is unrenderable, so deferring the answer to the browser would strand you after a pairing session already exists. An explicitly requested `cli_op:*` is not an error: the backend appends it to every pairing-minted key, so it is omitted from the request with a note and the resulting key is identical. Only a scope the screen renders and the user declines is reported after the key is minted.",
208
208
  "name": "scopes",
209
209
  "hasDynamicHelp": false,
210
210
  "multiple": true,
@@ -216,6 +216,12 @@
216
216
  "allowNo": false,
217
217
  "type": "boolean"
218
218
  },
219
+ "allow-unrenderable-scopes": {
220
+ "description": "Forward a scope to the approval screen even when this CLI's catalog says the screen has no toggle for it. Escape hatch for a stale catalog: the screen-grantable list above is a MIRROR of the web app's approval screen and can lag a frontend release, and without this flag a lagging mirror makes such a scope impossible to request until a CLI update ships. The screen stays the authority — if it truly cannot render the scope it refuses the WHOLE authorization after the pairing session exists (the stranding the local check normally prevents), so use this only when you have reason to believe the web app is newer than this CLI. Scopes no login path can mint (payroll/admin:*) are still rejected locally; this flag does not touch them.",
221
+ "name": "allow-unrenderable-scopes",
222
+ "allowNo": false,
223
+ "type": "boolean"
224
+ },
219
225
  "yes": {
220
226
  "char": "y",
221
227
  "description": "Skip the interactive confirmation and start the pairing immediately. Only a BARE invocation is ever prompted, so passing any flag already skips it; use this to say so explicitly. Automation that allocates a pty for stdin/stdout/stderr and runs the command bare is indistinguishable from a human — that is the case this flag exists for.",
@@ -247,10 +253,10 @@
247
253
  "logout": {
248
254
  "aliases": [],
249
255
  "args": {},
250
- "description": "Clear cached credentials (session token + store keys) for a profile. By default, clears BOTH the OS keychain and plaintext file store. With --insecure-storage or ALLSCALE_INSECURE_STORAGE=1, clears only plaintext files and never probes the keychain; omit/unset that opt-in when a full-machine sweep is wanted. If the keychain is suppressed or unavailable, a bare logout fails closed after attempting the plaintext-file cleanup.",
256
+ "description": "Clear cached credentials (session token + store keys) for a profile. By default, clears BOTH the OS keychain and plaintext file store. With --insecure-storage or ALLSCALE_INSECURE_STORAGE=1, clears only plaintext files and never probes the keychain; omit/unset that opt-in when a full-machine sweep is wanted. If the keychain is suppressed or unavailable, a bare logout fails closed after attempting the plaintext-file cleanup. A bare interactive invocation asks for confirmation before anything is removed; any flag (or --yes) skips the prompt, and machine callers are never prompted.",
251
257
  "examples": [
252
- "$ allscale logout",
253
- "$ allscale logout --profile staging"
258
+ "$ allscale logout --profile staging",
259
+ "$ allscale logout --yes"
254
260
  ],
255
261
  "flags": {
256
262
  "json": {
@@ -292,6 +298,13 @@
292
298
  "name": "insecure-storage",
293
299
  "allowNo": false,
294
300
  "type": "boolean"
301
+ },
302
+ "yes": {
303
+ "char": "y",
304
+ "description": "Skip the interactive confirmation and clear the credentials immediately. Only a BARE invocation is ever prompted, so passing any flag already skips it; use this to say so explicitly. Automation that allocates a pty for stdin/stdout/stderr and runs the command bare is indistinguishable from a human — that is the case this flag exists for.",
305
+ "name": "yes",
306
+ "allowNo": false,
307
+ "type": "boolean"
295
308
  }
296
309
  },
297
310
  "hasDynamicHelp": false,
@@ -467,7 +480,7 @@
467
480
  "type": "option"
468
481
  },
469
482
  "scopes": {
470
- "description": "Scopes the minted agent key should carry, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs that reach a real operation today: invoice:{read_only,all}, contact:{read_only,all}, claim_link:{read_only,all}, transaction:{read_only,all}, store:{read_only,all}, wallet:{read_only,all}. transaction:all, wallet:all reach only their category's READS — no write operation is wired to either today, so the `:read_only` tier grants exactly as much; prefer it unless you have a reason to hold the wider scope. Other pairs are accepted by the catalog but grant nothing, and this command does NOT warn when a requested scope is clipped — verify with `allscale scope` after minting. Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any OTP is sent — the same check, and the same exit code, as `device-login --scopes`. Required — the backend deliberately has no full-permission default. Requested scopes are clipped to your account's role; granted scopes are checked by the backend on each request.",
483
+ "description": "Scopes the minted agent key should carry, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs that reach a real operation today: invoice:{read_only,all}, contact:{read_only,all}, claim_link:{read_only,all}, transaction:{read_only,all}, store:{read_only,all}, wallet:{read_only,all}. transaction:all read-only in practice: no write operation is wired there today, so the `:read_only` tier grants exactly as much; prefer it unless you have a reason to hold the wider scope. `wallet:all` additionally lets the key register `wallet send` transfers; every transfer still requires your in-browser confirmation. Other pairs are accepted by the catalog but grant nothing, and this command does NOT warn when a requested scope is clipped — verify with `allscale scope` after minting. Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any OTP is sent — the same check, and the same exit code, as `device-login --scopes`. Required — the backend deliberately has no full-permission default. Requested scopes are clipped to your account's role; granted scopes are checked by the backend on each request.",
471
484
  "helpGroup": "REQUIRED",
472
485
  "name": "scopes",
473
486
  "required": true,
@@ -695,7 +708,7 @@
695
708
  "whoami": {
696
709
  "aliases": [],
697
710
  "args": {},
698
- "description": "Show the current authenticated identity from the stored credential (agent-key sessions report business_id / scopes / expiry; legacy password sessions decode the cached JWT). No network call.",
711
+ "description": "Show the current authenticated identity from the stored credential (agent-key sessions report business_id / scopes / expiry; legacy password sessions decode the cached JWT). No network call. The reported `api_base` is the endpoint this session resolves to — its saved profile pin, else this build's own environment. A published build ignores ALLSCALE_API_BASE, and says so on stderr rather than echoing it as the session endpoint; an internal build honours the variable, so it is echoed there. Either way, a resolved endpoint that networked commands would refuse — an untrusted origin, or a real AllScale environment outside this build's signing binding, whether it came from the variable or from the profile's saved pin — is disclosed on stderr. This command stays usable offline and never fails closed.",
699
712
  "examples": [
700
713
  "$ allscale whoami",
701
714
  "$ allscale whoami --profile prod"
@@ -1586,7 +1599,7 @@
1586
1599
  "required": true
1587
1600
  }
1588
1601
  },
1589
- "description": "Pay an invoice where you are the payer, from your AllScale wallet. Use `allscale invoice sent` to list the invoices you owe (add --status SENT --status ACKNOWLEDGED --status FAILED for the ones you can start paying). An OVERDUE invoice cannot start a new payment: if an earlier attempt of yours may still be in flight, reconcile that first — otherwise ask the issuer to extend its due date, which revives it. Resolves the invoice's destination + amount, moves the funds via the same signing path as `wallet send` (the transfer is confirmed in the browser), then reports and confirms the payment. Needs TWO scopes: `invoice:all` to create, report and confirm the pay intent, and `wallet:read_only` to look up the address you are paying FROM. Neither LOGIN flow grants `invoice:all` for you: on `device-login` the Invoices toggle starts at Read, so tick its write tier on the approval screen; on `otp-login` pass BOTH --scopes invoice:all --scopes wallet:read_only, because naming any scope turns every unnamed category off.",
1602
+ "description": "Pay an invoice where you are the payer, from your AllScale wallet. Use `allscale invoice sent` to list the invoices you owe (add --status SENT --status ACKNOWLEDGED --status FAILED for the ones you can start paying). An OVERDUE invoice cannot start a new payment: if an earlier attempt of yours may still be in flight, reconcile that first — otherwise ask the issuer to extend its due date, which revives it. Resolves the invoice's destination + amount, moves the funds via the same signing path as `wallet send` (the transfer is confirmed in the browser), then reports and confirms the payment. Needs TWO scopes: `invoice:all` to create, report and confirm the pay intent, and `wallet:all` to register the withdrawal — the same broker op `wallet send` uses (backend gates the op, not the verb); it also covers the payer-address lookup, since `:all` implies `:read_only`. Neither LOGIN flow grants either write tier for you: on `device-login` the Invoices toggle starts at Read and the Wallets Allow-changes tier starts OFF, so tick both on the approval screen; on `otp-login` pass BOTH --scopes invoice:all --scopes wallet:all, because naming any scope turns every unnamed category off.",
1590
1603
  "examples": [
1591
1604
  "$ allscale invoice pay 65ab1234567890abcdef0123",
1592
1605
  "$ allscale invoice pay 65ab1234567890abcdef0123 --chain bsc --stable-coin USDT"
@@ -1975,7 +1988,7 @@
1975
1988
  "type": "option"
1976
1989
  },
1977
1990
  "payment-type": {
1978
- "description": "What the invoice is denominated in AND which stablecoin it may be paid with: 0 = fiat (pair with --currency-int), 1 = USDT, 2 = USDC. Passing 1 or 2 EXPLICITLY pins the invoice to that coin — a payment arriving in the other stablecoin is rejected, and the payer's email names only this coin. Omit the flag and the invoice accepts whichever stablecoins your business is configured for (it is still denominated in USDT, the default). For 0 the amount is fiat but settlement is still in a stablecoin, so the payer may likewise use any coin your business accepts. Run `allscale describe create_payment` for the full list. Default: 1 (denomination only — omitting the flag pins nothing).",
1991
+ "description": "What the invoice is denominated in AND which stablecoin it may be paid with: 0 = fiat (pair with --currency-int), 1 = USDT, 2 = USDC. Passing 1 or 2 EXPLICITLY pins the invoice to that coin — a payment arriving in the other stablecoin is rejected, and the payer's email names only this coin. Omit the flag and the invoice accepts whichever stablecoins your business is configured for (it is still denominated in USDT, the default). For 0 the amount is fiat but settlement is still in a stablecoin, so the payer may likewise use any coin your business accepts. Any other value is rejected locally (exit 2) — the backend would otherwise issue an invoice in an undocumented asset. Default: 1 (denomination only — omitting the flag pins nothing).",
1979
1992
  "name": "payment-type",
1980
1993
  "default": 1,
1981
1994
  "hasDynamicHelp": false,
@@ -3015,7 +3028,7 @@
3015
3028
  "wallet:send": {
3016
3029
  "aliases": [],
3017
3030
  "args": {},
3018
- "description": "Withdraw a stablecoin from your AllScale wallet to an EVM address. The transfer is confirmed in the browser; the CLI prints the transaction hash and explorer URL only after its on-chain receipt confirms.",
3031
+ "description": "Withdraw a stablecoin from your AllScale wallet to an EVM address. The transfer is confirmed in the browser; the CLI prints the transaction hash and explorer URL only after its on-chain receipt confirms. Needs `wallet:all` on an agent key: it registers the withdrawal op (`wallet:read_only` alone cannot). Every transfer still requires your in-browser confirmation.",
3019
3032
  "examples": [
3020
3033
  "$ allscale wallet send --idempotency-key order-1042 --to 0x1234567890abcdef1234567890abcdef12345678 --amount 100 --chain ethereum",
3021
3034
  "$ allscale wallet send --idempotency-key order-1043 --to 0x1234567890abcdef1234567890abcdef12345678 --amount 50 --chain polygon --stable-coin USDC",
@@ -3156,5 +3169,5 @@
3156
3169
  ]
3157
3170
  }
3158
3171
  },
3159
- "version": "1.0.1"
3172
+ "version": "1.0.2"
3160
3173
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allscale/cli",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Command-line interface for AllScale — drives the same actions a user can take in app.allscale.io",
5
5
  "keywords": [
6
6
  "allscale",