@allscale/cli 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,8 +13,8 @@
13
13
  To move to production, run: allscale device-login --api-base ${te}
14
14
  `}var N=A(require("fs")),rn=A(require("os")),rt=A(require("path")),ot=A(require("@iarna/toml"));var Xr=".allscale",Vr="config.toml";function it(){return rt.join(rn.homedir(),Xr)}function Zr(){return rt.join(it(),Vr)}function me(){let e=Zr();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return ot.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function on(e){return Object.keys(e.profile??{}).sort()}function sn(e,t){return e.profile?.[t]}function an(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function P(e){if(!Ue(e))throw new c("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+De)}function _e(e,t){P(e);let n=x(e),r=typeof t=="string"?x(t):null;if(n&&r===n)return;let o=typeof t=="string"?T(t):"<missing origin binding>";throw new c("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function cn(e,t){let n=x(e),r=x(t);if(!(n&&r===n))throw new c("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ye(e){let t=eo(e);if(t)throw new c("input.invalid",t.message)}function Qr(){let e=z();if(e===void 0)return;let t=X();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function eo(e){let t=Qr();if(t===void 0||R(e))return;let{endpoints:n,fromPairs:r}=t,o=x(e),i=n.map(u=>x(u)).filter(u=>u!==null);if(o!==null&&i.includes(o))return;let s=n.map(u=>T(u)).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 to=require("@noble/hashes/sha3");var ln=["USDT","USDC"];var Es=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var no="unknown_otp_id",ro="invalid_code",oo="expired_code";function io(e){return`'${e.replace(/'/g,"'\\''")}'`}function un(e){return`Run \`allscale otp-send --email ${io(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var so=new Map([[no,(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. ${un(t)}`],[ro,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.`],[oo,(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. ${un(t)}`]]);var dn=[...so.keys()];var v=require("@oclif/core"),re=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:G()==="public"}),"api-base":I.Flags.string({description:$e,helpGroup:"GLOBAL",hidden:G()==="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{Ze(this.jsonEnabled()),et(),y({type:"session-start",command:this.id??"",argv:tt(this.argv)});let t=this.constructor;if(G()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new c("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(i=>i==="--api-base"||i.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ne()!==void 0)throw new c("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=Xt(this.jsonEnabled()),r=this.argv.length===0&&!n&&mo(t)?this.config.findCommand(this.id??""):void 0;if(r){Q();let i=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new i(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!tn())throw this.argv.length>0&&await this.parse(),new c("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 o=await this.runCommand();return y({type:"command-end",ok:!0}),Q(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Mt(o),{data:o})}catch(t){let n=Ft(t);Vt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ze(!1)}}resolveSessionApiBaseChain(t){let n=me(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||nt()!==void 0,s=an(n,r,nt()),u=sn(n,s),l=G()==="public"&&ne()!==void 0,d=o??(l?void 0:ne()),p=d??u?.api_base??te,f=nn({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:u?.api_base,profileApiBaseSource:u?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,q({event:"legacy_staging_profile",api_base:p,profile:s},f)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:l,profileApiBase:u?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||P(n),n}resolveContext(t){if(G()==="public"){if(t.token!==void 0)throw new c("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 c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ne()!==void 0)throw new c("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:o,explicitApiBase:i,envApiBaseIgnored:s,profile:u,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(P(o),ye(o)),{apiBase:o,profile:u,token:n??Zt(),insecureStorage:r||Qt(),apiBaseSource:i!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${go(t)}
15
15
  `)}};var ao=/_(removed|cleared|count|total)$/i;function co(e,t){return typeof t=="number"&&ao.test(e)}var lo=new Set(ln);function uo(e,t){return e==="token_symbol"&&typeof t=="string"&&lo.has(t)}var po=new Set(dn);function fo(e,t){return e==="otp_reason"&&typeof t=="string"&&po.has(t)}var we=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(o=>be(o,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[o,i]of r.slice(0,we))n[o]=pe(o)&&!co(o,i)&&!uo(o,i)&&!fo(o,i)?"<redacted>":be(i,t+1);if(r.length>we){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-we} more keys`}return n}if(typeof e=="string"){let n=ho(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function ho(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 go(e){let t=Yt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function mo(e){if(e.requiresInput===!0)return!0;let t=o=>typeof o=="object"&&o!==null&&o.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(o=>t(o))||Object.values(r).some(o=>t(o))}function _o(e,t={}){let n;try{n=on(me())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",Ut(e)+(t.messageSuffix??""),{profile:e})}function Se(e){if(e.profileExplicit){let t=_o(e.profile);if(t)return t}return new c("auth.no_token",Dt(e.profile))}var kn=A(require("path"));var ct=require("crypto"),a=A(require("fs")),_=A(require("path"));var Ee=1024*1024,yo=5e3,wo=20,bo=3e4,st=4096,So=new Int32Array(new SharedArrayBuffer(4)),oe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ae(e){return e instanceof oe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Eo=null;function $(){return new c("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(Eo??process.platform)!=="win32"}function wn(){if(!ke())throw $()}function bn(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 ie(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function se(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ao(e){Atomics.wait(So,0,0,e)}function Sn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function ko(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&m(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=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 i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!se(i,s))throw new Error("credential-store parent changed while it was being inspected");ie(i,"credential-store parent");let u=i;if((i.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),u=a.default.fstatSync(o)),(u.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&a.default.closeSync(o)}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 o;try{o=a.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&m(i,"ENOENT")?new k:i}if(!se(n,o))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.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||o.nlink!==1))throw new oe;if(ie(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function Lo(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+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>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function fn(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(o){if(m(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(m(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return Lo(t,r)}finally{t!==null&&a.default.closeSync(t)}}function hn(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(o){if(m(o,"ENOENT")&&bn(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);D(e,r)}finally{t!==null&&a.default.closeSync(t)}An(_.dirname(e))}function To(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 oe;ie(t,"credential-store replacement target")}function Io(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(m(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function En(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 An(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 Oo(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),o=_.basename(e),i=null,s=null,u=!1;try{let l=Io(r,o);i=l.fd,s=l.tempPath;let d=a.default.fstatSync(i);if((O(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");En(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let f=i;i=null,a.default.closeSync(f),To(e),a.default.renameSync(s,e),u=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!u&&s!==null)try{a.default.unlinkSync(s)}catch{}}An(r)}function Co(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function vo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Ro(e,t){if(t.size>st)return null;let n=Buffer.alloc(st+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>st)return null;let o;try{o=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof o!="object"||o===null||!Number.isSafeInteger(o.pid)||(o.pid??0)<=0||typeof o.nonce!="string"||!/^[a-f0-9]{24}$/.test(o.nonce??"")||typeof o.target!="string"?null:o}function D(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");ie(n,"credential-store lock"),a.default.unlinkSync(e)}function gn(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(l){if(m(l,"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 k}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Ro(n,o);return{state:(i?.target===t&&i?!Sn(i.pid):Date.now()-o.mtimeMs>=bo)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function xo(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let u=a.default.fstatSync(s),l=O(o,s,u,{allowMultipleLinks:!0});return En(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:l}}catch(u){if(m(u,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw u}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function No(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 k:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(o,t))throw new k;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function mn(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 k}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 Po(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{D(e,n)}catch{}throw a.default.closeSync(t),r}}function B(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");Ao(wo)}function _n(e){let t=_.dirname(e),n=_.basename(e),r=Co(e),o=vo(e),i=xo(t,n),s=Date.now()+yo,u=!1,l=!1,d=null,p;try{for(;d===null;)try{if(mn(o)){B(s,!0);continue}a.default.linkSync(i.claimPath,r),l=!0,d=No(r,i.stats),u=!0}catch(f){if(l&&!u){try{D(r,i.stats)}catch{}l=!1}if(f instanceof k){B(s,!1);continue}if(!m(f,"EEXIST"))throw f;let b;try{b=gn(r,n)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}if(b.state==="absent")continue;if(b.state==="stale"){let w;try{w=Po(o)}catch(E){if(E instanceof k){B(s,!1);continue}throw E}if(w!==null){try{let E;try{E=gn(r,n)}catch(ce){if(ce instanceof k){B(s,!1);continue}throw ce}E.state==="stale"&&D(r,E.stats)}finally{at(w)}continue}}let g;try{g=mn(o)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}B(s,g)}}catch(f){p=f}try{D(i.claimPath,i.stats)}catch(f){!m(f,"ENOENT")&&!u&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function at(e){try{D(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Bo(e,t){let n=ko(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 o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function yn(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let o=Bo(r,n);if(o===null||Sn(o))continue;let i=_.join(t,r),s=null;try{try{s=a.default.openSync(i,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 u=a.default.fstatSync(s),l=a.default.lstatSync(i);if(!u.isFile()||l.isSymbolicLink()||!l.isFile()||!se(u,l))continue;try{ie(u,"credential-store orphan")}catch{continue}D(i,u)}catch(u){if(!m(u,"ENOENT"))throw u}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw $();if(!pn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw $()}});let s=_n(e);try{return yn(e),n({read:()=>fn(e),remove:()=>hn(e),write:()=>{throw $()}})}finally{at(s)}}if(!t.createParent){let i=!1;try{i=bn(e)}catch{throw $()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw $()}})}throw $()}if(!pn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=_n(e);try{return yn(e),n({read:()=>fn(e),remove:()=>hn(e),write:i=>Oo(e,i)})}finally{at(o)}}var lt="allscale-cli";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ln(e){return ft(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new c("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 ut(){return new c("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 Le(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var U,dt=!1;function $o(){return en()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Do(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 Uo(){if(U!==void 0)return U;if($o())return dt=!1,U=null,U;try{U=require("keytar"),dt=!1}catch(e){dt=!Do(e),U=null}return U}var Fo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Tn(){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 c("storage.unavailable",`${Fo} `+e+" Never silently downgrade in production.")}async function pt(e){try{return await e()}catch{throw Tn()}}var ht=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await pt(()=>this.keytar.getPassword(lt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!Ln(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await pt(()=>this.keytar.setPassword(lt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await pt(()=>this.keytar.deletePassword(lt,t))}},Mo="credentials.json",gt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??kn.join(it(),Mo)}read(t){let n;try{n=t.read()}catch(o){throw Ae(o)?ut():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!ft(r)||!ft(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ae(r)?ut():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Ln(r))throw F("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:F("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof c?r:Le()}}async delete(t){try{ae(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 c?n:Le()}}async clearProfile(t){try{return ae(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 c?n:Ae(n)?ut():Le()}}};function Te(e){if(e.insecureStorage)return wn(),new gt(e.insecureFilePath);let t=Uo();if(t)return new ht(t);throw Tn()}var mt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new c("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ie(){return new mt}async function In(e){if(e.token)return{kind:"override",accessToken:e.token};let n=await Te({insecureStorage:e.insecureStorage}).get(e.profile),r=n?.api_base;return n?.agent_key?{kind:"agent",storedApiBase:r,businessId:_t(n.business_id),userEmail:_t(n.user_email),scopes:Go(n.scopes)}:n?.access_token?{kind:"human",storedApiBase:r,accessToken:n.access_token,userEmail:_t(n.user_email)}:{kind:"none"}}function _t(e){return typeof e=="string"&&e.length>0?e:void 0}function Go(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.length>0);return t.length>0?t:void 0}function Cn(e){let t=e.split(".");if(t.length!==3)throw new c("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 On()}if(typeof n!="object"||n===null||Array.isArray(n))throw On();return n}function On(){return new c("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.")}async function vn(e,t){if(typeof t=="string"&&t.length>0)return t;let n=await In(e);switch(n.kind){case"override":case"human":return jo(n.accessToken);case"agent":if(n.businessId!==void 0)return n.businessId;throw new c("input.invalid","Agent-key sessions carry no JWT to derive the business id from \u2014 pass --business-id explicitly. (Re-run `allscale device-login` to store your business id automatically.)");case"none":throw Se({profile:e.profile,profileExplicit:e.profileExplicit});default:return Ko(n)}}function Ko(e){throw new c("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}function jo(e){let t=Cn(e),n=typeof t.user_id=="string"?t.user_id:void 0;if(!n)throw new c("input.invalid","Could not infer --business-id from the cached JWT (no user_id claim). Pass --business-id explicitly.");return n}var Oe="allscale_access_token",yt="allscale_refresh_token";function Rn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function wt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function bt(e,t){return e.find(n=>n.name===t)?.value??null}var xn=A(require("crypto")),Nn=A(require("fs")),Pn=A(require("path"));var qo="key-id",Yo="x-allscale-cli-version",St="cli-1",Ho="aScaLe_cli_obf_v1",Wo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Jo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var zo=Jo(Wo,Ho),Bn=`Bearer ${zo}`;function $n(e,t){let n=Me(e);if(n!==null)return t.find(r=>Me(r.base)===n)}function Xo(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=$n(e,t);if(r)return r.key;if(R(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:R(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 Vo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?$n(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&R(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():St}if(!R(t[0].base))return St}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():St}function Zo(){return"1.0.3"}function Qo(){return new c("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 Et(e,t){let n=Xo(t);if(!n)throw Qo();let r=Vo(t),o=Math.floor(Date.now()/1e3).toString(),i=xn.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Yo]:Zo()};return r.length>0&&(s[qo]=r),s}function Dn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ei=500,ti=8,Un=100;function At(e,t=0){if(t>ti)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Un),r=n.map(o=>At(o,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,o]of Object.entries(e).slice(0,Un))n[r]=pe(r)?"<redacted>":At(o,t+1);return n}return e}function ni(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 Fn(e,t=ei){let n=ni(e),r=n===void 0?de(e):JSON.stringify(At(n));return fe(r,t)}var kt=256*1024,Ce=class extends c{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`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.`:i?`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,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},ve=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 Lt(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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],u=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,b)=>{l=setTimeout(()=>{b(new ve(e.status,d))},d),l.unref?.()});try{for(;;){let f=i.read(),{done:b,value:g}=p?await Promise.race([f,p]):await f;if(b)break;if(u+=g.byteLength,u>t)throw i.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(f){throw f instanceof ve&&i.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{i.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var ri="X-AllScale-Api-Key",oi=3e4,ii=32*1024*1024,si=4*1024*1024;function ai(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function ci(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function li(e,t){if(!(e<300||e>=400))throw new c("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 qn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}li(e.status,e.url)}}var Mn="--dns-result-order=ipv4first";async function Re(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",u=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),l=/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(!((i||u)&&(o||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new c("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=${Mn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Mn}`})}var M=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??oi;if(!Number.isFinite(r)||r<1)throw new c("input.invalid","HTTP request timeout must be a positive number of milliseconds.");P(this.opts.apiBase),ye(this.opts.apiBase);let o=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),i=ai(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new c("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 c)?new c("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();cn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",u=Yn(t.path),l=s==="required"?!0:s==="none"?!1:pi(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw Se({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Dn(t.body),p=!!i||!!r?.access_token;l&&p&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();y({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new c("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-b}),l&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await ci(this.refreshSingleFlight(),t.signal),ce=this.buildHeaders({attachAuth:l&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),ar=Date.now();y({type:"request",method:t.method??"GET",url:o});let Pe;try{Pe=await fetch(o,{method:t.method??"GET",headers:ce,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new c("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return y({type:"response",status:Pe.status,durationMs:Date.now()-ar}),Gn(Pe,{withMetadata:n.withMetadata,authBearing:l,responseKind:Kn(t)})}return Gn(g,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!i,responseKind:Kn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Et(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Bn;let o=t.tokens;if(o?.agent_key)return r[ri]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=wt([{name:Oe,value:i}]))}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(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new c("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 c("auth.token_expired",`No refresh token available; log in again \u2014 ${ue()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new c("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=wt([{name:Oe,value:t.access_token},{name:yt,value:t.refresh_token}]),o=Et("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,u=setTimeout(()=>{s=!0,i.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(g){throw y({type:"refresh",ok:!1}),new c("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(u)}y({type:"response",status:l.status,durationMs:0});try{await qn(l)}catch(g){throw y({type:"refresh",ok:!1}),g}if(l.status!==200){let g=null;try{await Re(l);let w=await _i(l);await Re(l,w),Wn(l.status,w),l.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw y({type:"refresh",ok:!1}),w}if(g)return y({type:"refresh",ok:!0,adopted:!0}),g;throw y({type:"refresh",ok:!1}),new c("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:l.status})}let d=Rn(l.headers),p=bt(d,Oe),f=bt(d,yt);if(!p||!f)throw y({type:"refresh",ok:!1}),new c("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,b),y({type:"refresh",ok:!0}),b}},ui=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Yn(e){let t=e.split(/[?#]/,1)[0];return ui.some(n=>t===n||t.startsWith(`${n}/`))}var di=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Tt(e){let t=e.split(/[?#]/,1)[0];return di.some(n=>n.test(t))}function pi(e){return Yn(e)||Tt(e)}async function Gn(e,t={}){await qn(e);let n=e.status>=200&&e.status<300;n||await Re(e);let r=t.responseKind??"mutation",i=await Lt(e,n?r==="query"?ii:si:kt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Re(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:s}}return s}let u=yi(s)??`HTTP ${e.status}`;if(Wn(e.status,s),gi(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new c("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 l=t.authBearing?"auth.token_expired":"input.invalid";throw new c(l,u,{status:401,body:s})}throw e.status===403?new c("auth.permission_denied",u,{status:403,body:s}):e.status===404?new c("not_found",u,{status:404,body:s}):e.status===429?new c("rate_limited",u,{status:429,body:s}):e.status>=500?new c("backend.internal",u,{status:e.status,body:s}):new c("input.invalid",u,{status:e.status,body:s})}function Kn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var fi=2014,jn=2004;function Hn(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 hi(e){return Hn(e,fi)}function gi(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Hn(t,jn))throw new c("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} 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:jn})}var mi=1e4;async function _i(e,t=mi){if(e.status>=200&&e.status<300)return"";try{return await Lt(e,kt,{timeoutMs:t})}catch{return""}}function Wn(e,t){if(!(e>=200&&e<300)&&hi(t))throw new c("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"?Fn(t):t})}function yi(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)}var wi=/^\/(api\/)?(v1\/)?public\//;function Jn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&wi.test(n),o=n&&Tt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Te({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var bi=new Set;var Si=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),It=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Ot=new Set(["payroll","admin:user","admin:org","admin:audit"]);function xe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function zn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Ei=new Set(["cli_op:all"]),Ai=new Set([...Ei].map(xe));var Oa=new Set([...[...Si,...It,...bi].map(xe),...Ot,...Ai]);var ki={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Li={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},Ti=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,Ii=/is not available to API keys/i,Xn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Vn(e){if(typeof e!="string")return;let t=Ti.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),o=Ii.test(n),i=!o&&Xn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(l=>l.trim()).filter(l=>Xn.test(l));s=u.length>0?u:void 0}if(!(i===void 0&&!o))return{required:i,granted:s,notAvailableToKeys:o}}function Zn(e){let t=Li[e];if(t!==void 0)return{ungrantableReason:t};let n=ki[e];if(n!==void 0)return{scope:n}}function Qn(e){if(Ot.has(xe(e)))return{kind:"ungrantable"};for(let t of It)if(zn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function er(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function tr(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var Ct=8100,Oi=new Set([Ct]),Ci=new Set([...Oi,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function rr(e,t){let n=or(e),r={graphql_error_count:vi(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Ri(e,t,r);if(n===429)throw new c("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new c("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&Ci.has(n))throw new c("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(er(e))throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${tr(e)}`,r);if(n!==void 0)throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function or(e){let t=nr(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let o=nr(r.code);if(o!==void 0)return o}}function nr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function vi(e){return Array.isArray(e)?e.length:e==null?0:1}function Ri(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,o={...n,operation:t.operationName},i=Vn(xi(e,or(e))),s=Zn(t.operationName),u=i?.notAvailableToKeys===!0,l=i?.required??s?.scope,d=i?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(u||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new c("auth.permission_denied",`${r} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...o,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=Qn(l),b=f.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:f.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${V()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${V()}\` with \`--scopes ${l}\`.`;return new c("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${p} ${b}`,{...o,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new c("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${p} Re-run \`allscale device-login\` (or \`${V()}\`) and grant the required scope.`,o)}function xi(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=o=>{if(o===null||typeof o!="object")return;let i=o.message;return typeof i=="string"?i:void 0};if(t!==void 0)for(let o of n){if(o===null||typeof o!="object")continue;let i=o.extensions;if(!i||typeof i!="object")continue;let s=i.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(o);if(l!==void 0)return l}}for(let o of n){let i=r(o);if(i!==void 0)return i}return""}var Ni="/api/secure/graphql";async function ir(e,t){t.showDoc&&process.stderr.write(`${t.document}
17
- `);let r=await Jn(e).request({method:"POST",path:Ni,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});rr(r,{kind:t.kind,operationName:t.operationName});let o=r.data?.[t.operationName];return o===void 0?null:o}var Pi=`mutation create_store($input: CreateStoreInput!) {
16
+ `,1)[0]==="Cannot find module 'keytar'"}function Uo(){if(U!==void 0)return U;if($o())return dt=!1,U=null,U;try{U=require("keytar"),dt=!1}catch(e){dt=!Do(e),U=null}return U}var Fo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Tn(){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 c("storage.unavailable",`${Fo} `+e+" Never silently downgrade in production.")}async function pt(e){try{return await e()}catch{throw Tn()}}var ht=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await pt(()=>this.keytar.getPassword(lt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!Ln(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await pt(()=>this.keytar.setPassword(lt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await pt(()=>this.keytar.deletePassword(lt,t))}},Mo="credentials.json",gt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??kn.join(it(),Mo)}read(t){let n;try{n=t.read()}catch(o){throw Ae(o)?ut():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!ft(r)||!ft(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ae(r)?ut():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Ln(r))throw F("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:F("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof c?r:Le()}}async delete(t){try{ae(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 c?n:Le()}}async clearProfile(t){try{return ae(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 c?n:Ae(n)?ut():Le()}}};function Te(e){if(e.insecureStorage)return wn(),new gt(e.insecureFilePath);let t=Uo();if(t)return new ht(t);throw Tn()}var mt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new c("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ie(){return new mt}async function In(e){if(e.token)return{kind:"override",accessToken:e.token};let n=await Te({insecureStorage:e.insecureStorage}).get(e.profile),r=n?.api_base;return n?.agent_key?{kind:"agent",storedApiBase:r,businessId:_t(n.business_id),userEmail:_t(n.user_email),scopes:Go(n.scopes)}:n?.access_token?{kind:"human",storedApiBase:r,accessToken:n.access_token,userEmail:_t(n.user_email)}:{kind:"none"}}function _t(e){return typeof e=="string"&&e.length>0?e:void 0}function Go(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.length>0);return t.length>0?t:void 0}function Cn(e){let t=e.split(".");if(t.length!==3)throw new c("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 On()}if(typeof n!="object"||n===null||Array.isArray(n))throw On();return n}function On(){return new c("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.")}async function vn(e,t){if(typeof t=="string"&&t.length>0)return t;let n=await In(e);switch(n.kind){case"override":case"human":return jo(n.accessToken);case"agent":if(n.businessId!==void 0)return n.businessId;throw new c("input.invalid","Agent-key sessions carry no JWT to derive the business id from \u2014 pass --business-id explicitly. (Re-run `allscale device-login` to store your business id automatically.)");case"none":throw Se({profile:e.profile,profileExplicit:e.profileExplicit});default:return Ko(n)}}function Ko(e){throw new c("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}function jo(e){let t=Cn(e),n=typeof t.user_id=="string"?t.user_id:void 0;if(!n)throw new c("input.invalid","Could not infer --business-id from the cached JWT (no user_id claim). Pass --business-id explicitly.");return n}var Oe="allscale_access_token",yt="allscale_refresh_token";function Rn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function wt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function bt(e,t){return e.find(n=>n.name===t)?.value??null}var xn=A(require("crypto")),Nn=A(require("fs")),Pn=A(require("path"));var qo="key-id",Yo="x-allscale-cli-version",St="cli-1",Ho="aScaLe_cli_obf_v1",Wo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Jo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var zo=Jo(Wo,Ho),Bn=`Bearer ${zo}`;function $n(e,t){let n=Me(e);if(n!==null)return t.find(r=>Me(r.base)===n)}function Xo(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=$n(e,t);if(r)return r.key;if(R(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:R(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 Vo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?$n(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&R(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():St}if(!R(t[0].base))return St}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():St}function Zo(){return"1.0.4"}function Qo(){return new c("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 Et(e,t){let n=Xo(t);if(!n)throw Qo();let r=Vo(t),o=Math.floor(Date.now()/1e3).toString(),i=xn.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Yo]:Zo()};return r.length>0&&(s[qo]=r),s}function Dn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ei=500,ti=8,Un=100;function At(e,t=0){if(t>ti)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Un),r=n.map(o=>At(o,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,o]of Object.entries(e).slice(0,Un))n[r]=pe(r)?"<redacted>":At(o,t+1);return n}return e}function ni(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 Fn(e,t=ei){let n=ni(e),r=n===void 0?de(e):JSON.stringify(At(n));return fe(r,t)}var kt=256*1024,Ce=class extends c{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`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.`:i?`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,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},ve=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 Lt(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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],u=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,b)=>{l=setTimeout(()=>{b(new ve(e.status,d))},d),l.unref?.()});try{for(;;){let f=i.read(),{done:b,value:g}=p?await Promise.race([f,p]):await f;if(b)break;if(u+=g.byteLength,u>t)throw i.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(f){throw f instanceof ve&&i.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{i.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var ri="X-AllScale-Api-Key",oi=3e4,ii=32*1024*1024,si=4*1024*1024;function ai(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function ci(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function li(e,t){if(!(e<300||e>=400))throw new c("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 qn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}li(e.status,e.url)}}var Mn="--dns-result-order=ipv4first";async function Re(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",u=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),l=/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(!((i||u)&&(o||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new c("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=${Mn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Mn}`})}var M=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??oi;if(!Number.isFinite(r)||r<1)throw new c("input.invalid","HTTP request timeout must be a positive number of milliseconds.");P(this.opts.apiBase),ye(this.opts.apiBase);let o=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),i=ai(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new c("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 c)?new c("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();cn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",u=Yn(t.path),l=s==="required"?!0:s==="none"?!1:pi(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw Se({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Dn(t.body),p=!!i||!!r?.access_token;l&&p&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();y({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new c("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-b}),l&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await ci(this.refreshSingleFlight(),t.signal),ce=this.buildHeaders({attachAuth:l&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),ar=Date.now();y({type:"request",method:t.method??"GET",url:o});let Pe;try{Pe=await fetch(o,{method:t.method??"GET",headers:ce,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new c("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return y({type:"response",status:Pe.status,durationMs:Date.now()-ar}),Gn(Pe,{withMetadata:n.withMetadata,authBearing:l,responseKind:Kn(t)})}return Gn(g,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!i,responseKind:Kn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Et(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Bn;let o=t.tokens;if(o?.agent_key)return r[ri]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=wt([{name:Oe,value:i}]))}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(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new c("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 c("auth.token_expired",`No refresh token available; log in again \u2014 ${ue()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new c("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=wt([{name:Oe,value:t.access_token},{name:yt,value:t.refresh_token}]),o=Et("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,u=setTimeout(()=>{s=!0,i.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(g){throw y({type:"refresh",ok:!1}),new c("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(u)}y({type:"response",status:l.status,durationMs:0});try{await qn(l)}catch(g){throw y({type:"refresh",ok:!1}),g}if(l.status!==200){let g=null;try{await Re(l);let w=await _i(l);await Re(l,w),Wn(l.status,w),l.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw y({type:"refresh",ok:!1}),w}if(g)return y({type:"refresh",ok:!0,adopted:!0}),g;throw y({type:"refresh",ok:!1}),new c("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:l.status})}let d=Rn(l.headers),p=bt(d,Oe),f=bt(d,yt);if(!p||!f)throw y({type:"refresh",ok:!1}),new c("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,b),y({type:"refresh",ok:!0}),b}},ui=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Yn(e){let t=e.split(/[?#]/,1)[0];return ui.some(n=>t===n||t.startsWith(`${n}/`))}var di=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Tt(e){let t=e.split(/[?#]/,1)[0];return di.some(n=>n.test(t))}function pi(e){return Yn(e)||Tt(e)}async function Gn(e,t={}){await qn(e);let n=e.status>=200&&e.status<300;n||await Re(e);let r=t.responseKind??"mutation",i=await Lt(e,n?r==="query"?ii:si:kt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Re(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:s}}return s}let u=yi(s)??`HTTP ${e.status}`;if(Wn(e.status,s),gi(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new c("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 l=t.authBearing?"auth.token_expired":"input.invalid";throw new c(l,u,{status:401,body:s})}throw e.status===403?new c("auth.permission_denied",u,{status:403,body:s}):e.status===404?new c("not_found",u,{status:404,body:s}):e.status===429?new c("rate_limited",u,{status:429,body:s}):e.status>=500?new c("backend.internal",u,{status:e.status,body:s}):new c("input.invalid",u,{status:e.status,body:s})}function Kn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var fi=2014,jn=2004;function Hn(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 hi(e){return Hn(e,fi)}function gi(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Hn(t,jn))throw new c("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} 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:jn})}var mi=1e4;async function _i(e,t=mi){if(e.status>=200&&e.status<300)return"";try{return await Lt(e,kt,{timeoutMs:t})}catch{return""}}function Wn(e,t){if(!(e>=200&&e<300)&&hi(t))throw new c("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"?Fn(t):t})}function yi(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)}var wi=/^\/(api\/)?(v1\/)?public\//;function Jn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&wi.test(n),o=n&&Tt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Te({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var bi=new Set;var Si=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),It=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Ot=new Set(["payroll","admin:user","admin:org","admin:audit"]);function xe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function zn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Ei=new Set(["cli_op:all"]),Ai=new Set([...Ei].map(xe));var Oa=new Set([...[...Si,...It,...bi].map(xe),...Ot,...Ai]);var ki={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Li={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},Ti=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,Ii=/is not available to API keys/i,Xn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Vn(e){if(typeof e!="string")return;let t=Ti.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),o=Ii.test(n),i=!o&&Xn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(l=>l.trim()).filter(l=>Xn.test(l));s=u.length>0?u:void 0}if(!(i===void 0&&!o))return{required:i,granted:s,notAvailableToKeys:o}}function Zn(e){let t=Li[e];if(t!==void 0)return{ungrantableReason:t};let n=ki[e];if(n!==void 0)return{scope:n}}function Qn(e){if(Ot.has(xe(e)))return{kind:"ungrantable"};for(let t of It)if(zn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function er(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function tr(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var Ct=8100,Oi=new Set([Ct]),Ci=new Set([...Oi,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function rr(e,t){let n=or(e),r={graphql_error_count:vi(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Ri(e,t,r);if(n===429)throw new c("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new c("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&Ci.has(n))throw new c("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(er(e))throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${tr(e)}`,r);if(n!==void 0)throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function or(e){let t=nr(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let o=nr(r.code);if(o!==void 0)return o}}function nr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function vi(e){return Array.isArray(e)?e.length:e==null?0:1}function Ri(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,o={...n,operation:t.operationName},i=Vn(xi(e,or(e))),s=Zn(t.operationName),u=i?.notAvailableToKeys===!0,l=i?.required??s?.scope,d=i?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(u||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new c("auth.permission_denied",`${r} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...o,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=Qn(l),b=f.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:f.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${V()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${V()}\` with \`--scopes ${l}\`.`;return new c("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${p} ${b}`,{...o,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new c("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${p} Re-run \`allscale device-login\` (or \`${V()}\`) and grant the required scope.`,o)}function xi(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=o=>{if(o===null||typeof o!="object")return;let i=o.message;return typeof i=="string"?i:void 0};if(t!==void 0)for(let o of n){if(o===null||typeof o!="object")continue;let i=o.extensions;if(!i||typeof i!="object")continue;let s=i.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(o);if(l!==void 0)return l}}for(let o of n){let i=r(o);if(i!==void 0)return i}return""}var Ni="/api/secure/graphql";async function ir(e,t){t.showDoc&&process.stderr.write(`${t.document}
17
+ `);let r=await Jn(e).request({method:"POST",path:Ni,responseKind:t.kind,...t.signal===void 0?{}:{signal:t.signal},body:{query:t.document,variables:t.variables,operationName:t.operationName}});rr(r,{kind:t.kind,operationName:t.operationName});let o=r.data?.[t.operationName];return o===void 0?null:o}var Pi=`mutation create_store($input: CreateStoreInput!) {
18
18
  create_store(input: $input) {
19
19
  store { id name api_key is_sandbox scopes }
20
20
  api_secret