@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.
- package/dist/commands/claim-link/claim.js +5 -5
- package/dist/commands/claim-link/create.js +24 -24
- package/dist/commands/claim-link/get.js +2 -2
- package/dist/commands/claim-link/list.js +2 -2
- package/dist/commands/claim-link/status.js +1 -1
- package/dist/commands/device-login.js +1 -1
- package/dist/commands/invoice/get.js +1 -1
- package/dist/commands/invoice/list.js +1 -1
- package/dist/commands/invoice/pay.js +44 -44
- package/dist/commands/invoice/received.js +1 -1
- package/dist/commands/invoice/send.js +1 -1
- package/dist/commands/invoice/sent.js +1 -1
- package/dist/commands/invoice/update.js +1 -1
- package/dist/commands/otp-login.js +1 -1
- package/dist/commands/otp-send.js +1 -1
- package/dist/commands/payout/send.js +9 -9
- package/dist/commands/payout/status.js +2 -2
- package/dist/commands/store/create.js +2 -2
- package/dist/commands/transaction/get.js +1 -1
- package/dist/commands/transaction/list.js +1 -1
- package/dist/commands/wallet/list.js +1 -1
- package/dist/commands/wallet/send.js +1 -1
- package/dist/index.js +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
To move to production, run: allscale device-login --api-base ${ye}
|
|
14
14
|
`}var Y=T(require("fs")),In=T(require("os")),wt=T(require("path")),bt=T(require("@iarna/toml"));var Ho=".allscale",jo="config.toml";function Et(){return wt.join(In.homedir(),Ho)}function Yo(){return wt.join(Et(),jo)}function Pe(){let e=Yo();if(!Y.existsSync(e))return{};let t=Y.readFileSync(e,"utf-8");try{return bt.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function vn(e){return Object.keys(e.profile??{}).sort()}function Rn(e,t){return e.profile?.[t]}function Cn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function q(e){if(!te(e))throw new a("input.invalid",`Refusing to send credentials to API base ${I(e)}. `+pe)}function Be(e,t){q(e);let n=j(e),r=typeof t=="string"?j(t):null;if(n&&r===n)return;let o=typeof t=="string"?I(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${I(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function Nn(e,t){let n=j(e),r=j(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${I(t)} because it is outside the configured API origin ${I(e)}.`)}function De(e){let t=Wo(e);if(t)throw new a("input.invalid",t.message)}function qo(){let e=fe();if(e===void 0)return;let t=he();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Wo(e){let t=qo();if(t===void 0||H(e))return;let{endpoints:n,fromPairs:r}=t,o=j(e),i=n.map(c=>j(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))return;let s=n.map(c=>I(c)).join(", ");return{message:r?`Refusing to send to ${I(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 ${I(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var xn=require("@noble/hashes/sha3");function Pn(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Jo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Bn=["ethereum","bsc","base","polygon","arbitrum","optimism"],$e=["USDT","USDC"];function Dn(e){return Jo[e.toLowerCase()]??null}function $n(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}function Un(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,xn.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let o=0;o<t.length;o+=1){let i=t[o];if(!/[a-fA-F]/.test(i))continue;let s=Number.parseInt(r[o],16)>=8;if(s&&i!==i.toUpperCase()||!s&&i!==i.toLowerCase())return!1}return!0}var ue="0x1234567890abcdef1234567890abcdef12345678";function zo(e){return e.toLowerCase()===ue}function Fn(e,t="--to"){if(zo(e))throw new a("input.invalid",`${t} is the documentation example address; pass a destination address you control.`)}var Vo=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Mn(e){return Vo.has(e.toLowerCase())}function St(e,t){let r={1:"https://etherscan.io/tx",6:"https://bscscan.com/tx",5:"https://basescan.org/tx",8:"https://polygonscan.com/tx",9:"https://optimistic.etherscan.io/tx",7:"https://arbiscan.io/tx"}[e];return r?`${r}/${t}`:""}function Gn(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Kn(e){return e===1?"USDT":"USDC"}var Xo="unknown_otp_id",Zo="invalid_code",Qo="expired_code";function ei(e){return`'${e.replace(/'/g,"'\\''")}'`}function Hn(e){return`Run \`allscale otp-send --email ${ei(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var ti=new Map([[Xo,(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. ${Hn(t)}`],[Zo,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.`],[Qo,(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. ${Hn(t)}`]]);var jn=[...ti.keys()];var P=require("@oclif/core"),be=class e extends $.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:$.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:$.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:ne()==="public"}),"api-base":$.Flags.string({description:Ze,helpGroup:"GLOBAL",hidden:ne()==="public"}),"insecure-storage":$.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{ht(this.jsonEnabled()),mt(),m({type:"session-start",command:this.id??"",argv:_t(this.argv)});let t=this.constructor;if(ne()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(i=>i==="--api-base"||i.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&we()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=En(this.jsonEnabled()),r=this.argv.length===0&&!n&&ui(t)?this.config.findCommand(this.id??""):void 0;if(r){me();let i=await(0,$.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 a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let o=await this.runCommand();return m({type:"command-end",ok:!0}),me(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||dn(o),{data:o})}catch(t){let n=un(t);Sn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{ht(!1)}}resolveSessionApiBaseChain(t){let n=Pe(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||yt()!==void 0,s=Cn(n,r,yt()),c=Rn(n,s),u=ne()==="public"&&we()!==void 0,d=o??(u?void 0:we()),p=d??c?.api_base??ye,h=On({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return h&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ie({event:"legacy_staging_profile",api_base:p,profile:s},h)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||q(n),n}resolveContext(t){if(ne()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&we()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:o,explicitApiBase:i,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(o),De(o)),{apiBase:o,profile:c,token:n??An(),insecureStorage:r||kn(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${ci(t)}
|
|
15
15
|
`)}};var ni=/_(removed|cleared|count|total)$/i;function ri(e,t){return typeof t=="number"&&ni.test(e)}var oi=new Set($e);function ii(e,t){return e==="token_symbol"&&typeof t=="string"&&oi.has(t)}var si=new Set(jn);function ai(e,t){return e==="otp_reason"&&typeof t=="string"&&si.has(t)}var Ue=100;function Fe(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ue),r=n.map(o=>Fe(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,Ue))n[o]=Re(o)&&!ri(o,i)&&!ii(o,i)&&!ai(o,i)?"<redacted>":Fe(i,t+1);if(r.length>Ue){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-Ue} more keys`}return n}if(typeof e=="string"){let n=li(e);return n!==void 0?O(JSON.stringify(Fe(n,t+1))):O(e)}return e}function li(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 ci(e){let t=mn()?void 0:2,n=Fe(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:O(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function ui(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))}var $r=require("crypto"),A=require("process");var G=/^0x[0-9a-fA-F]{64}$/,di=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function Yn(e){return typeof e=="string"&&di.includes(e)}var or=T(require("path"));var Lt=require("crypto"),l=T(require("fs")),E=T(require("path"));var Me=1024*1024,pi=5e3,fi=20,hi=3e4,At=4096,gi=new Int32Array(new SharedArrayBuffer(4)),Ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ge(e){return e instanceof Ee}var v=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},mi=null;function J(){return new a("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 Qn(){if(!Ke())throw J()}function er(e){try{return l.default.lstatSync(e),!1}catch(t){if(!b(t,"ENOENT"))throw t}try{let t=l.default.lstatSync(E.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(b(t,"ENOENT"))return!0;throw t}}function b(e,t){return typeof e=="object"&&e!==null&&e.code===t}function Se(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function Ae(e,t){return e.dev===t.dev&&e.ino===t.ino}function _i(e){Atomics.wait(gi,0,0,e)}function tr(e){try{return process.kill(e,0),!0}catch(t){return!b(t,"ESRCH")}}function yi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qn(e,t){let n=E.dirname(e);t&&l.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=l.default.lstatSync(n)}catch(i){if(!t&&b(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=l.default.openSync(n,l.default.constants.O_RDONLY|(l.default.constants.O_DIRECTORY??0)|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0));let i=l.default.fstatSync(o),s=l.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!Ae(i,s))throw new Error("credential-store parent changed while it was being inspected");Se(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&E.basename(n)===".allscale"&&(l.default.fchmodSync(o,448),c=l.default.fstatSync(o)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&l.default.closeSync(o)}return!0}function U(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=l.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&b(i,"ENOENT")?new v:i}if(!Ae(n,o))throw r.retryOnPathChange?new v: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 Ee;if(Se(n,"credential-store file"),process.platform!=="win32"){l.default.fchmodSync(t,384);let i=l.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 wi(e,t){if(t.size>Me)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Me+1),r=0;for(;r<n.length;){let o=l.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Me)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Wn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(o){if(b(o,"ENOENT"))try{if(l.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(b(i,"ENOENT"))return null;throw i}throw o}let n=l.default.fstatSync(t),r=U(e,t,n);return wi(t,r)}finally{t!==null&&l.default.closeSync(t)}}function Jn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(o){if(b(o,"ENOENT")&&er(e))return;throw o}let n=l.default.fstatSync(t),r=U(e,t,n);z(e,r)}finally{t!==null&&l.default.closeSync(t)}rr(E.dirname(e))}function bi(e){let t;try{t=l.default.lstatSync(e)}catch(n){if(b(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;Se(t,"credential-store replacement target")}function Ei(e,t){for(let n=0;n<8;n+=1){let r=(0,Lt.randomBytes)(12).toString("hex"),o=E.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:l.default.openSync(o,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_WRONLY|(l.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(b(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function nr(e,t){let n=0;for(;n<t.length;){let r=l.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 rr(e){if(process.platform==="win32")return;let t=null;try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_DIRECTORY??0)|(l.default.constants.O_NOFOLLOW??0)),l.default.fsyncSync(t)}catch{}finally{if(t!==null)try{l.default.closeSync(t)}catch{}}}function Si(e,t){let n=Buffer.from(t,"utf8");if(n.length>Me)throw new Error("credential-store file exceeds the maximum supported size");let r=E.dirname(e),o=E.basename(e),i=null,s=null,c=!1;try{let u=Ei(r,o);i=u.fd,s=u.tempPath;let d=l.default.fstatSync(i);if((U(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");nr(i,n),l.default.fsyncSync(i),U(s,i,l.default.fstatSync(i));let h=i;i=null,l.default.closeSync(h),bi(e),l.default.renameSync(s,e),c=!0}finally{if(i!==null)try{l.default.closeSync(i)}catch{}if(!c&&s!==null)try{l.default.unlinkSync(s)}catch{}}rr(r)}function Ai(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function ki(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function Li(e,t){if(t.size>At)return null;let n=Buffer.alloc(At+1),r=0;for(;r<n.length;){let i=l.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>At)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 z(e,t){let n=l.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!Ae(n,t))throw new Error("credential-store lock changed while it was being inspected");Se(n,"credential-store lock"),l.default.unlinkSync(e)}function zn(e,t){let n=null;try{try{n=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(u){if(b(u,"ENOENT"))try{let d=l.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new v}catch(d){if(b(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=l.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Li(n,o);return{state:(i?.target===t&&i?!tr(i.pid):Date.now()-o.mtimeMs>=hi)?"stale":"active",stats:o}}finally{n!==null&&l.default.closeSync(n)}}function Ti(e,t){for(let n=0;n<8;n+=1){let r=(0,Lt.randomBytes)(12).toString("hex"),o=E.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=l.default.openSync(o,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_WRONLY|(l.default.constants.O_NOFOLLOW??0),384);let c=l.default.fstatSync(s),u=U(o,s,c,{allowMultipleLinks:!0});return nr(s,Buffer.from(JSON.stringify(i),"utf8")),l.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(b(c,"EEXIST"))continue;try{l.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&l.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Oi(e,t){let n;try{n=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(r){throw b(r,"ENOENT")?new v:r}try{let r=l.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!Ae(o,t))throw new v;return{fd:n,lockPath:e,stats:o}}catch(r){throw l.default.closeSync(n),r}}function Vn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(n){if(b(n,"ENOENT"))try{let r=l.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new v}catch(r){if(b(r,"ENOENT"))return!1;throw r}throw n}return U(e,t,l.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&l.default.closeSync(t)}}function Ii(e){let t;try{t=l.default.openSync(e,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_RDWR|(l.default.constants.O_NOFOLLOW??0),384)}catch(r){if(b(r,"EEXIST"))return null;throw r}let n=null;try{n=l.default.fstatSync(t);let r=U(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{z(e,n)}catch{}throw l.default.closeSync(t),r}}function W(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(fi)}function Xn(e){let t=E.dirname(e),n=E.basename(e),r=Ai(e),o=ki(e),i=Ti(t,n),s=Date.now()+pi,c=!1,u=!1,d=null,p;try{for(;d===null;)try{if(Vn(o)){W(s,!0);continue}l.default.linkSync(i.claimPath,r),u=!0,d=Oi(r,i.stats),c=!0}catch(h){if(u&&!c){try{z(r,i.stats)}catch{}u=!1}if(h instanceof v){W(s,!1);continue}if(!b(h,"EEXIST"))throw h;let g;try{g=zn(r,n)}catch(y){if(y instanceof v){W(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=Ii(o)}catch(_){if(_ instanceof v){W(s,!1);continue}throw _}if(y!==null){try{let _;try{_=zn(r,n)}catch(k){if(k instanceof v){W(s,!1);continue}throw k}_.state==="stale"&&z(r,_.stats)}finally{kt(y)}continue}}let f;try{f=Vn(o)}catch(y){if(y instanceof v){W(s,!1);continue}throw y}W(s,f)}}catch(h){p=h}try{z(i.claimPath,i.stats)}catch(h){!b(h,"ENOENT")&&!c&&p===void 0&&(p=h)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function kt(e){try{z(e.lockPath,e.stats)}finally{l.default.closeSync(e.fd)}}function vi(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 o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function Zn(e){let t=E.dirname(e),n=E.basename(e);for(let r of l.default.readdirSync(t)){let o=vi(r,n);if(o===null||tr(o))continue;let i=E.join(t,r),s=null;try{try{s=l.default.openSync(i,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(d){if(b(d,"ENOENT")||b(d,"ELOOP"))continue;throw d}let c=l.default.fstatSync(s),u=l.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!Ae(c,u))continue;try{Se(c,"credential-store orphan")}catch{continue}z(i,c)}catch(c){if(!b(c,"ENOENT"))throw c}finally{s!==null&&l.default.closeSync(s)}}}function ke(e,t,n){if(!Ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw J();if(!qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw J()}});let s=Xn(e);try{return Zn(e),n({read:()=>Wn(e),remove:()=>Jn(e),write:()=>{throw J()}})}finally{kt(s)}}if(!t.createParent){let i=!1;try{i=er(e)}catch{throw J()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw J()}})}throw J()}if(!qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=Xn(e);try{return Zn(e),n({read:()=>Wn(e),remove:()=>Jn(e),write:i=>Si(e,i)})}finally{kt(o)}}var Tt="allscale-cli";function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ir(e){return Rt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function X(e){return new a("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 Ot(){return new a("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 He(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var V,It=!1;function Ri(){return Ln()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Ci(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 Ni(){if(V!==void 0)return V;if(Ri())return It=!1,V=null,V;try{V=require("keytar"),It=!1}catch(e){It=!Ci(e),V=null}return V}var xi="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function sr(){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 a("storage.unavailable",`${xi} `+e+" Never silently downgrade in production.")}async function vt(e){try{return await e()}catch{throw sr()}}var Ct=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await vt(()=>this.keytar.getPassword(Tt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!ir(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await vt(()=>this.keytar.setPassword(Tt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await vt(()=>this.keytar.deletePassword(Tt,t))}},Pi="credentials.json",Nt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??or.join(Et(),Pi)}read(t){let n;try{n=t.read()}catch(o){throw Ge(o)?Ot():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Rt(r)||!Rt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ge(r)?Ot():He()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!ir(r))throw X("plaintext file");return r}}async get(t){try{return ke(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{ke(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 a?r:He()}}async delete(t){try{ke(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 a?n:He()}}async clearProfile(t){try{return ke(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 a?n:Ge(n)?Ot():He()}}};function ar(e){if(e.insecureStorage)return Qn(),new Nt(e.insecureFilePath);let t=Ni();if(t)return new Ct(t);throw sr()}var xt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function je(){return new xt}var Ye="allscale_access_token",Pt="allscale_refresh_token";function lr(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 Bt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Dt(e,t){return e.find(n=>n.name===t)?.value??null}var cr=T(require("crypto")),ur=T(require("fs")),dr=T(require("path"));var Bi="key-id",Di="x-allscale-cli-version",$t="cli-1",$i="aScaLe_cli_obf_v1",Ui="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Fi(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 Mi=Fi(Ui,$i),pr=`Bearer ${Mi}`;function fr(e,t){let n=tt(e);if(n!==null)return t.find(r=>tt(r.base)===n)}function Gi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=he();if(t.length>0){let r=fr(e,t);if(r)return r.key;if(H(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:H(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 Ki(e){{let r="cli-1".trim();if(r.length>0)return r}let t=he();if(t.length>0){let r=e!==void 0?fr(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&H(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():$t}if(!H(t[0].base))return $t}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():$t}function Hi(){return"1.0.3"}function ji(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ut(e,t){let n=Gi(t);if(!n)throw ji();let r=Ki(t),o=Math.floor(Date.now()/1e3).toString(),i=cr.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Di]:Hi()};return r.length>0&&(s[Bi]=r),s}function hr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Yi(e,t={}){let n;try{n=vn(Pe())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",cn(e)+(t.messageSuffix??""),{profile:e})}function gr(e){if(e.profileExplicit){let t=Yi(e.profile);if(t)return t}return new a("auth.no_token",ln(e.profile))}var qi=500,Wi=8,mr=100;function Ft(e,t=0){if(t>Wi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,mr),r=n.map(o=>Ft(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,mr))n[r]=Re(r)?"<redacted>":Ft(o,t+1);return n}return e}function Ji(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 _r(e,t=qi){let n=Ji(e),r=n===void 0?ve(e):JSON.stringify(Ft(n));return Ce(r,t)}var Mt=256*1024,qe=class extends a{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"}},We=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 Gt(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 qe(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,p=d===void 0?void 0:new Promise((h,g)=>{u=setTimeout(()=>{g(new We(e.status,d))},d),u.unref?.()});try{for(;;){let h=i.read(),{done:g,value:f}=p?await Promise.race([h,p]):await h;if(g)break;if(c+=f.byteLength,c>t)throw i.cancel().catch(()=>{}),new qe(e.status,t,n.oversizeKind);s.push(Buffer.from(f))}}catch(h){throw h instanceof We&&i.cancel(h).catch(()=>{}),h}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var zi="X-AllScale-Api-Key",Vi=3e4,Xi=32*1024*1024,Zi=4*1024*1024;function Qi(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 es(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 ts(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${M(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 Sr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ts(e.status,e.url)}}var yr="--dns-result-order=ipv4first";async function Je(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)??"",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(!((i||c)&&(o||t!==void 0&&u)))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 a("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=${yr} 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=${yr}`})}var Z=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??Vi;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");q(this.opts.apiBase),De(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=Qi(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new a("transport.timeout",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${M(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();Nn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Ar(t.path),u=s==="required"?!0:s==="none"?!1:os(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw gr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=hr(t.body),p=!!i||!!r?.access_token;u&&p&&!this.opts.override&&Be(this.opts.apiBase,r?.api_base);let h=this.buildHeaders({attachAuth:u&&p,bodyForSig:d,tokens:r,extra:t.headers}),g=Date.now();m({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let f;try{f=await fetch(o,{method:t.method??"GET",headers:h,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(_){throw new a("transport.network",`Network error contacting ${M(o)}: ${_ instanceof Error?_.message:String(_)}`)}if(m({type:"response",status:f.status,durationMs:Date.now()-g}),u&&!!r?.access_token&&!i&&f.status===401&&!t._isRefresh&&!this.opts.override){let _=await es(this.refreshSingleFlight(),t.signal),k=this.buildHeaders({attachAuth:u&&!!_.access_token,bodyForSig:d,tokens:_,extra:t.headers}),x=Date.now();m({type:"request",method:t.method??"GET",url:o});let L;try{L=await fetch(o,{method:t.method??"GET",headers:k,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(K){throw new a("transport.network",`Network error contacting ${M(o)} on refresh-retry: ${K instanceof Error?K.message:String(K)}`)}return m({type:"response",status:L.status,durationMs:Date.now()-x}),wr(L,{withMetadata:n.withMetadata,authBearing:u,responseKind:br(t)})}return wr(f,{withMetadata:n.withMetadata,authBearing:u&&p,agentKeyAuth:u&&!!i,responseKind:br(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ut(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=pr;let o=t.tokens;if(o?.agent_key)return r[zi]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=Bt([{name:Ye,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(Be(this.opts.apiBase,n.api_base),n.agent_key)throw new a("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 a("auth.token_expired",`No refresh token available; log in again \u2014 ${Ie()}.`);if(Be(this.opts.apiBase,t.api_base),t.agent_key)throw new a("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=Bt([{name:Ye,value:t.access_token},{name:Pt,value:t.refresh_token}]),o=Ut("",this.opts.apiBase);m({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(f){throw m({type:"refresh",ok:!1}),new a("transport.network",s&&f instanceof Error&&f.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${f instanceof Error?f.message:String(f)}`)}finally{clearTimeout(c)}m({type:"response",status:u.status,durationMs:0});try{await Sr(u)}catch(f){throw m({type:"refresh",ok:!1}),f}if(u.status!==200){let f=null;try{await Je(u);let y=await cs(u);await Je(u,y),Lr(u.status,y),u.status===401&&(f=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw m({type:"refresh",ok:!1}),y}if(f)return m({type:"refresh",ok:!0,adopted:!0}),f;throw m({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Ie()}.`,{status:u.status})}let d=lr(u.headers),p=Dt(d,Ye),h=Dt(d,Pt);if(!p||!h)throw m({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let g={...t,access_token:p,refresh_token:h};return await this.opts.tokenStore.set(this.opts.profile,g),m({type:"refresh",ok:!0}),g}},ns=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Ar(e){let t=e.split(/[?#]/,1)[0];return ns.some(n=>t===n||t.startsWith(`${n}/`))}var rs=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Kt(e){let t=e.split(/[?#]/,1)[0];return rs.some(n=>n.test(t))}function os(e){return Ar(e)||Kt(e)}async function wr(e,t={}){await Sr(e);let n=e.status>=200&&e.status<300;n||await Je(e);let r=t.responseKind??"mutation",i=await Gt(e,n?r==="query"?Xi:Zi:Mt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Je(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 u={};return e.headers.forEach((d,p)=>{u[p]=d}),{status:e.status,headers:u,body:s}}return s}let c=us(s)??`HTTP ${e.status}`;if(Lr(e.status,s),as(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new a("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 a(u,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function br(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var is=2014,Er=2004;function kr(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 ss(e){return kr(e,is)}function as(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&kr(t,Er))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Ie()} 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:Er})}var ls=1e4;async function cs(e,t=ls){if(e.status>=200&&e.status<300)return"";try{return await Gt(e,Mt,{timeoutMs:t})}catch{return""}}function Lr(e,t){if(!(e>=200&&e<300)&&ss(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?_r(t):t})}function us(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 ds=/^\/(api\/)?(v1\/)?public\//;function Ht(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ds.test(n),o=n&&Kt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new Z({apiBase:e.apiBase,tokenStore:ar({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var N={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},ps=new Set(Object.values(N));async function Tr(e,t,n){let{body:r,headers:o}=await gs(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:fs(o)}}function fs(e){let t=e.date??e.Date??Object.entries(e).find(([r])=>r.toLowerCase()==="date")?.[1];if(t===void 0)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}async function jt(e,t){return hs(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function hs(e,t,n,r){let o;try{o=await e.request({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Or(i,r);if(s!==null)throw s}throw i}return Ir(o,r)}async function gs(e,t,n,r){let o;try{o=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Or(i,r);if(s!==null)throw s}throw i}return{body:Ir(o.body,r),headers:o.headers??{}}}function Or(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,o=typeof r.code=="number"?r.code:void 0;if(o===void 0||o===0||!ps.has(o))return null;let i=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return vr(o,i,t)}function Ir(e,t){if(e.code!==void 0&&e.code!==0)throw vr(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function vr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case N.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case N.CLI_OP_EXPIRED:return new a("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:r});case N.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case N.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_INVALID_PAYLOAD:case N.CLI_OP_SELF_TRANSFER:case N.CLI_OP_INSUFFICIENT_BALANCE:case N.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case N.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var Nr=require("child_process");function Rr(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var ms=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function _s(e,t,n,r){if(Rr(e.CI)||ms.some(s=>Rr(e[s])))return"ci";let i=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!i?"ssh":n===!0||r===!0?null:"no-tty"}function ys(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+t+n:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+t+n:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+t+n}async function xr(e,t={}){if(!Qe(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${I(e)}`);let n=t._env??process.env,r=t._platform??process.platform,o=n.BROWSER?.trim();if(o&&o.toLowerCase()==="none")throw new a("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let i=o?null:_s(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(i)throw new a("wallet.requires_browser_auth",ys(i));if(r==="linux"&&!n.DISPLAY&&!o)throw new a("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let s=ws(r,o);await bs(s.command,[...s.args,e])}function ws(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function bs(e,t){return new Promise((n,r)=>{let o;try{o=(0,Nr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Cr(e,s));return}let i=!1;o.once("error",s=>{i||(i=!0,r(Cr(e,s)))}),setImmediate(()=>{i||(i=!0,o.unref(),n())})})}function Cr(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Pr=T(require("http"));var Es=9e4,Ss=16*1024;function Br(e){let t=e.timeoutMs??Es;return new Promise((n,r)=>{let o=!1,i=!1,s=null,c,u,d=new Promise((h,g)=>{c=h,u=g}),p=Pr.createServer((h,g)=>{As(h,g,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>o,tryConsume:()=>o?!1:(o=!0,!0),onSuccess:f=>{s&&clearTimeout(s),c(f),p.close()}})});p.on("error",h=>{let g=new a("transport.network",`Loopback listener error: ${h.message}`);i?u(g):r(g),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let h=p.address();if(!h||typeof h=="string"){p.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let g=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,f=g!=null?Math.max(1,Math.min(t,g)):t,y=g!=null&&g<=t;s=setTimeout(()=>{u(new a("wallet.bridge_timeout",`Bridge timed out after ${f}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),p.close()},f),s.unref?.(),i=!0,n({port:h.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function As(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(c["Access-Control-Allow-Private-Network"]="true"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let o=0,i=[],s=!1;e.on("data",c=>{if(!s){if(o+=c.length,o>Ss){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}i.push(c)}}),e.on("end",()=>{if(s)return;let c=Buffer.concat(i).toString("utf-8"),u;try{u=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!u||typeof u!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=u,p=typeof d.state=="string"?d.state:"",h=typeof d.result_token=="string"?d.result_token:void 0,g=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!ks(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(h===void 0&&g===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:h,result_data:g})}),e.on("error",()=>{s||(s=!0)})}function ks(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function Yt(e){try{return JSON.parse(e),!0}catch{return!1}}function Dr(){let e=process.stdin,t="",n=!1,r=()=>{},o=250,i=null,s=()=>{i&&(clearTimeout(i),i=null)},c=()=>{s(),i=setTimeout(()=>{n||(u(),r(t.trim()))},o),i.unref?.()},u=()=>{n=!0,s(),e.off("data",d),e.off("end",p),e.off("error",h),e.pause()},d=f=>{if(n)return;s(),t+=f.toString();let y=t.trim(),_=t.length-t.trimStart().length,k=t.indexOf(`
|
|
16
|
+
`,1)[0]==="Cannot find module 'keytar'"}function Ni(){if(V!==void 0)return V;if(Ri())return It=!1,V=null,V;try{V=require("keytar"),It=!1}catch(e){It=!Ci(e),V=null}return V}var xi="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function sr(){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 a("storage.unavailable",`${xi} `+e+" Never silently downgrade in production.")}async function vt(e){try{return await e()}catch{throw sr()}}var Ct=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await vt(()=>this.keytar.getPassword(Tt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!ir(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await vt(()=>this.keytar.setPassword(Tt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await vt(()=>this.keytar.deletePassword(Tt,t))}},Pi="credentials.json",Nt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??or.join(Et(),Pi)}read(t){let n;try{n=t.read()}catch(o){throw Ge(o)?Ot():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Rt(r)||!Rt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ge(r)?Ot():He()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!ir(r))throw X("plaintext file");return r}}async get(t){try{return ke(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{ke(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 a?r:He()}}async delete(t){try{ke(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 a?n:He()}}async clearProfile(t){try{return ke(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 a?n:Ge(n)?Ot():He()}}};function ar(e){if(e.insecureStorage)return Qn(),new Nt(e.insecureFilePath);let t=Ni();if(t)return new Ct(t);throw sr()}var xt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function je(){return new xt}var Ye="allscale_access_token",Pt="allscale_refresh_token";function lr(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 Bt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Dt(e,t){return e.find(n=>n.name===t)?.value??null}var cr=T(require("crypto")),ur=T(require("fs")),dr=T(require("path"));var Bi="key-id",Di="x-allscale-cli-version",$t="cli-1",$i="aScaLe_cli_obf_v1",Ui="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Fi(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 Mi=Fi(Ui,$i),pr=`Bearer ${Mi}`;function fr(e,t){let n=tt(e);if(n!==null)return t.find(r=>tt(r.base)===n)}function Gi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=he();if(t.length>0){let r=fr(e,t);if(r)return r.key;if(H(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:H(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 Ki(e){{let r="cli-1".trim();if(r.length>0)return r}let t=he();if(t.length>0){let r=e!==void 0?fr(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&H(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():$t}if(!H(t[0].base))return $t}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():$t}function Hi(){return"1.0.4"}function ji(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ut(e,t){let n=Gi(t);if(!n)throw ji();let r=Ki(t),o=Math.floor(Date.now()/1e3).toString(),i=cr.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Di]:Hi()};return r.length>0&&(s[Bi]=r),s}function hr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Yi(e,t={}){let n;try{n=vn(Pe())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",cn(e)+(t.messageSuffix??""),{profile:e})}function gr(e){if(e.profileExplicit){let t=Yi(e.profile);if(t)return t}return new a("auth.no_token",ln(e.profile))}var qi=500,Wi=8,mr=100;function Ft(e,t=0){if(t>Wi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,mr),r=n.map(o=>Ft(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,mr))n[r]=Re(r)?"<redacted>":Ft(o,t+1);return n}return e}function Ji(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 _r(e,t=qi){let n=Ji(e),r=n===void 0?ve(e):JSON.stringify(Ft(n));return Ce(r,t)}var Mt=256*1024,qe=class extends a{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"}},We=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 Gt(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 qe(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,p=d===void 0?void 0:new Promise((h,g)=>{u=setTimeout(()=>{g(new We(e.status,d))},d),u.unref?.()});try{for(;;){let h=i.read(),{done:g,value:f}=p?await Promise.race([h,p]):await h;if(g)break;if(c+=f.byteLength,c>t)throw i.cancel().catch(()=>{}),new qe(e.status,t,n.oversizeKind);s.push(Buffer.from(f))}}catch(h){throw h instanceof We&&i.cancel(h).catch(()=>{}),h}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var zi="X-AllScale-Api-Key",Vi=3e4,Xi=32*1024*1024,Zi=4*1024*1024;function Qi(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 es(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 ts(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${M(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 Sr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ts(e.status,e.url)}}var yr="--dns-result-order=ipv4first";async function Je(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)??"",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(!((i||c)&&(o||t!==void 0&&u)))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 a("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=${yr} 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=${yr}`})}var Z=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??Vi;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");q(this.opts.apiBase),De(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=Qi(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new a("transport.timeout",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${M(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();Nn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Ar(t.path),u=s==="required"?!0:s==="none"?!1:os(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw gr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=hr(t.body),p=!!i||!!r?.access_token;u&&p&&!this.opts.override&&Be(this.opts.apiBase,r?.api_base);let h=this.buildHeaders({attachAuth:u&&p,bodyForSig:d,tokens:r,extra:t.headers}),g=Date.now();m({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let f;try{f=await fetch(o,{method:t.method??"GET",headers:h,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(_){throw new a("transport.network",`Network error contacting ${M(o)}: ${_ instanceof Error?_.message:String(_)}`)}if(m({type:"response",status:f.status,durationMs:Date.now()-g}),u&&!!r?.access_token&&!i&&f.status===401&&!t._isRefresh&&!this.opts.override){let _=await es(this.refreshSingleFlight(),t.signal),k=this.buildHeaders({attachAuth:u&&!!_.access_token,bodyForSig:d,tokens:_,extra:t.headers}),x=Date.now();m({type:"request",method:t.method??"GET",url:o});let L;try{L=await fetch(o,{method:t.method??"GET",headers:k,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(K){throw new a("transport.network",`Network error contacting ${M(o)} on refresh-retry: ${K instanceof Error?K.message:String(K)}`)}return m({type:"response",status:L.status,durationMs:Date.now()-x}),wr(L,{withMetadata:n.withMetadata,authBearing:u,responseKind:br(t)})}return wr(f,{withMetadata:n.withMetadata,authBearing:u&&p,agentKeyAuth:u&&!!i,responseKind:br(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ut(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=pr;let o=t.tokens;if(o?.agent_key)return r[zi]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=Bt([{name:Ye,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(Be(this.opts.apiBase,n.api_base),n.agent_key)throw new a("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 a("auth.token_expired",`No refresh token available; log in again \u2014 ${Ie()}.`);if(Be(this.opts.apiBase,t.api_base),t.agent_key)throw new a("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=Bt([{name:Ye,value:t.access_token},{name:Pt,value:t.refresh_token}]),o=Ut("",this.opts.apiBase);m({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(f){throw m({type:"refresh",ok:!1}),new a("transport.network",s&&f instanceof Error&&f.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${f instanceof Error?f.message:String(f)}`)}finally{clearTimeout(c)}m({type:"response",status:u.status,durationMs:0});try{await Sr(u)}catch(f){throw m({type:"refresh",ok:!1}),f}if(u.status!==200){let f=null;try{await Je(u);let y=await cs(u);await Je(u,y),Lr(u.status,y),u.status===401&&(f=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw m({type:"refresh",ok:!1}),y}if(f)return m({type:"refresh",ok:!0,adopted:!0}),f;throw m({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Ie()}.`,{status:u.status})}let d=lr(u.headers),p=Dt(d,Ye),h=Dt(d,Pt);if(!p||!h)throw m({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let g={...t,access_token:p,refresh_token:h};return await this.opts.tokenStore.set(this.opts.profile,g),m({type:"refresh",ok:!0}),g}},ns=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Ar(e){let t=e.split(/[?#]/,1)[0];return ns.some(n=>t===n||t.startsWith(`${n}/`))}var rs=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Kt(e){let t=e.split(/[?#]/,1)[0];return rs.some(n=>n.test(t))}function os(e){return Ar(e)||Kt(e)}async function wr(e,t={}){await Sr(e);let n=e.status>=200&&e.status<300;n||await Je(e);let r=t.responseKind??"mutation",i=await Gt(e,n?r==="query"?Xi:Zi:Mt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Je(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 u={};return e.headers.forEach((d,p)=>{u[p]=d}),{status:e.status,headers:u,body:s}}return s}let c=us(s)??`HTTP ${e.status}`;if(Lr(e.status,s),as(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new a("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 a(u,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function br(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var is=2014,Er=2004;function kr(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 ss(e){return kr(e,is)}function as(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&kr(t,Er))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Ie()} 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:Er})}var ls=1e4;async function cs(e,t=ls){if(e.status>=200&&e.status<300)return"";try{return await Gt(e,Mt,{timeoutMs:t})}catch{return""}}function Lr(e,t){if(!(e>=200&&e<300)&&ss(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?_r(t):t})}function us(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 ds=/^\/(api\/)?(v1\/)?public\//;function Ht(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ds.test(n),o=n&&Kt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new Z({apiBase:e.apiBase,tokenStore:ar({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var N={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},ps=new Set(Object.values(N));async function Tr(e,t,n){let{body:r,headers:o}=await gs(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:fs(o)}}function fs(e){let t=e.date??e.Date??Object.entries(e).find(([r])=>r.toLowerCase()==="date")?.[1];if(t===void 0)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}async function jt(e,t){return hs(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function hs(e,t,n,r){let o;try{o=await e.request({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Or(i,r);if(s!==null)throw s}throw i}return Ir(o,r)}async function gs(e,t,n,r){let o;try{o=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Or(i,r);if(s!==null)throw s}throw i}return{body:Ir(o.body,r),headers:o.headers??{}}}function Or(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,o=typeof r.code=="number"?r.code:void 0;if(o===void 0||o===0||!ps.has(o))return null;let i=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return vr(o,i,t)}function Ir(e,t){if(e.code!==void 0&&e.code!==0)throw vr(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function vr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case N.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case N.CLI_OP_EXPIRED:return new a("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:r});case N.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case N.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_INVALID_PAYLOAD:case N.CLI_OP_SELF_TRANSFER:case N.CLI_OP_INSUFFICIENT_BALANCE:case N.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case N.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var Nr=require("child_process");function Rr(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var ms=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function _s(e,t,n,r){if(Rr(e.CI)||ms.some(s=>Rr(e[s])))return"ci";let i=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!i?"ssh":n===!0||r===!0?null:"no-tty"}function ys(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+t+n:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+t+n:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+t+n}async function xr(e,t={}){if(!Qe(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${I(e)}`);let n=t._env??process.env,r=t._platform??process.platform,o=n.BROWSER?.trim();if(o&&o.toLowerCase()==="none")throw new a("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let i=o?null:_s(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(i)throw new a("wallet.requires_browser_auth",ys(i));if(r==="linux"&&!n.DISPLAY&&!o)throw new a("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let s=ws(r,o);await bs(s.command,[...s.args,e])}function ws(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function bs(e,t){return new Promise((n,r)=>{let o;try{o=(0,Nr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Cr(e,s));return}let i=!1;o.once("error",s=>{i||(i=!0,r(Cr(e,s)))}),setImmediate(()=>{i||(i=!0,o.unref(),n())})})}function Cr(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Pr=T(require("http"));var Es=9e4,Ss=16*1024;function Br(e){let t=e.timeoutMs??Es;return new Promise((n,r)=>{let o=!1,i=!1,s=null,c,u,d=new Promise((h,g)=>{c=h,u=g}),p=Pr.createServer((h,g)=>{As(h,g,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>o,tryConsume:()=>o?!1:(o=!0,!0),onSuccess:f=>{s&&clearTimeout(s),c(f),p.close()}})});p.on("error",h=>{let g=new a("transport.network",`Loopback listener error: ${h.message}`);i?u(g):r(g),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let h=p.address();if(!h||typeof h=="string"){p.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let g=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,f=g!=null?Math.max(1,Math.min(t,g)):t,y=g!=null&&g<=t;s=setTimeout(()=>{u(new a("wallet.bridge_timeout",`Bridge timed out after ${f}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),p.close()},f),s.unref?.(),i=!0,n({port:h.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function As(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(c["Access-Control-Allow-Private-Network"]="true"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let o=0,i=[],s=!1;e.on("data",c=>{if(!s){if(o+=c.length,o>Ss){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}i.push(c)}}),e.on("end",()=>{if(s)return;let c=Buffer.concat(i).toString("utf-8"),u;try{u=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!u||typeof u!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=u,p=typeof d.state=="string"?d.state:"",h=typeof d.result_token=="string"?d.result_token:void 0,g=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!ks(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(h===void 0&&g===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:h,result_data:g})}),e.on("error",()=>{s||(s=!0)})}function ks(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function Yt(e){try{return JSON.parse(e),!0}catch{return!1}}function Dr(){let e=process.stdin,t="",n=!1,r=()=>{},o=250,i=null,s=()=>{i&&(clearTimeout(i),i=null)},c=()=>{s(),i=setTimeout(()=>{n||(u(),r(t.trim()))},o),i.unref?.()},u=()=>{n=!0,s(),e.off("data",d),e.off("end",p),e.off("error",h),e.pause()},d=f=>{if(n)return;s(),t+=f.toString();let y=t.trim(),_=t.length-t.trimStart().length,k=t.indexOf(`
|
|
17
17
|
`,_),x=k===-1?"":t.slice(_,k).trim();if(y.startsWith("{")){if(Yt(y)){u(),r(y);return}if(k===-1){c();return}if(!Yt(x)&&!x.endsWith("}")){let L=t.slice(k+1),K=L.split(`
|
|
18
18
|
`).find(F=>F.trim()!=="")??"";if(x==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(K))){c();return}}u(),r(Yt(x)?x:t.slice(_).trim());return}if(k!==-1){u(),r(x);return}else!y&&t.includes(`
|
|
19
19
|
`)&&(u(),r(""))},p=()=>{if(n)return;let f=t.trim();if(!f){u();return}u(),r(f)},h=()=>{n||u()},g=new Promise(f=>{r=f});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",h),{promise:g,cancel:()=>{n||u()}}}function Ls(e){let t;return{promise:new Promise(r=>{if(e.aborted){r({source:"aborted"});return}t=()=>r({source:"aborted"}),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t!==void 0&&e.removeEventListener("abort",t)}}}async function Ur(e){let t=Ht(e.ctx),n=e.browserBase??e.ctx.apiBase,r=Cs(n),o=e._openBrowser??xr,i=e._startListener??Br,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,u=(0,$r.randomBytes)(32).toString("hex"),d=Date.now(),p=await Tr(t,e.op,e.payload);m({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let g=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,f=2147483647,_=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,k=9e5,x=6e4,L=g!=null&&Number.isFinite(g)&&g>0?g:null,K=Math.max(0,Math.round((L??0)/1e3)),R=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,F=R!=null&&R<=f?R:null,B,de,Jt=!1,zt=!1,Vt=!1;if(L!=null){let S=Math.min(L,f),D=L>f;F!=null&&F<S?(B=F,de="caller"):(B=S,de=D?"timer_ceiling":"op_ttl",Jt=!D&&R!=null&&R>S)}else{let S=p.expires_at*1e3-d,D=Number.isFinite(S)?Math.min(Math.max(S,x),k):k,Q=F??_;Q>D?(B=D,de="op_ttl_unverified",zt=R!=null&&R>D):(B=Q,de=F!=null?"caller":"unknown_ttl"),Vt=R!=null&&F==null}let Vr=de==="op_ttl",Xr=L!=null?`~${K}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${Xr}, waiting up to ${Math.round(B/1e3)}s for confirmation).
|
package/dist/index.js
CHANGED
|
@@ -12,6 +12,6 @@
|
|
|
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
14
|
`}var N=b(require("fs")),jt=b(require("os")),Ve=b(require("path")),Ze=b(require("@iarna/toml"));var Ir=".allscale",Or="config.toml";function Qe(){return Ve.join(jt.homedir(),Ir)}function Cr(){return Ve.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 o=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 ${o}. 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,o=R(e),i=n.map(c=>R(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))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 Xt=["USDT","USDC"];var Bi=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 Vt(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. ${Vt(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. ${Vt(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(i=>i==="--token"||i.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(i=>i==="--api-base"||i.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){V();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&&!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 o=await this.runCommand();return y({type:"command-end",ok:!0}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ot(o),{data:o})}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,o=t["api-base"]??void 0,i=r!==void 0||Xe()!==void 0,s=Jt(n,r,Xe()),c=Wt(n,s),u=$()==="public"&&ee()!==void 0,d=o??(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:i}}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:o,explicitApiBase:i,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(H(o),ge(o)),{apiBase:o,profile:c,token:n??Mt(),insecureStorage:r||Gt(),apiBaseSource:i!==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(Xt);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(o=>_e(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,me))n[o]=le(o)&&!Fr(o,i)&&!Gr(o,i)&&!Yr(o,i)?"<redacted>":_e(i,t+1);if(r.length>me){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-me} more keys`}return n}if(typeof e=="string"){let n=qr(e);return n!==void 0?E(JSON.stringify(_e(n,t+1))):E(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:E(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Hr(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))}var we="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(";"),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 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=b(require("crypto")),tn=b(require("fs")),nn=b(require("path"));var Wr="key-id",Jr="x-allscale-cli-version",rt="cli-1",zr="aScaLe_cli_obf_v1",Xr="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Vr(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 Zr=Vr(Xr,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 o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o: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 eo(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 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():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 to(){return"1.0.3"}function no(){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 ot(e,t){let n=Qr(t);if(!n)throw no();let r=eo(t),o=Math.floor(Date.now()/1e3).toString(),i=en.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Jr]:to()};return r.length>0&&(s[Wr]=r),s}function sn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ro(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=ro(e.profile);if(t)return t}return new l("auth.no_token",kt(e.profile))}var oo=500,io=8,cn=100;function it(e,t=0){if(t>io)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,cn),r=n.map(o=>it(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,cn))n[r]=le(r)?"<redacted>":it(o,t+1);return n}return e}function so(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=oo){let n=so(e),r=n===void 0?ce(e):JSON.stringify(it(n));return ue(r,t)}var st=256*1024,Ee=class extends l{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"}},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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);if(!e.body)return"";let i=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=i.read(),{done:L,value:g}=f?await Promise.race([p,f]):await p;if(L)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Se&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var ao="X-AllScale-Api-Key",co=3e4,lo=32*1024*1024,uo=4*1024*1024;function fo(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 po(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 ho(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{}ho(e.status,e.url)}}var un="--dns-result-order=ipv4first";async function be(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)??"",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(!((i||c)&&(o||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 Ae=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??co;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 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=fo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.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{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();zt(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=gn(t.path),u=s==="required"?!0:s==="none"?!1:yo(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw an({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=sn(t.body),f=!!i||!!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:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{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(o)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-L}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let S=await po(this.refreshSingleFlight(),t.signal),ie=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:o});let Oe;try{Oe=await fetch(o,{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(o)} 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&&!!i,responseKind:fn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...ot(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=rn;let o=t.tokens;if(o?.agent_key)return r[ao]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=tt([{name:we,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(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:we,value:t.access_token},{name:et,value:t.refresh_token}]),o=ot("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=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 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 be(u);let w=await Ao(u);await be(u,w),_n(u.status,w),u.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 l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ae()}.`,{status:u.status})}let d=Qt(u.headers),f=nt(d,we),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}},go=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function gn(e){let t=e.split(/[?#]/,1)[0];return go.some(n=>t===n||t.startsWith(`${n}/`))}var mo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function _o(e){let t=e.split(/[?#]/,1)[0];return mo.some(n=>n.test(t))}function yo(e){return gn(e)||_o(e)}async function dn(e,t={}){await hn(e);let n=e.status>=200&&e.status<300;n||await be(e);let r=t.responseKind??"mutation",i=await at(e,n?r==="query"?lo:uo:st,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await be(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 u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=Lo(s)??`HTTP ${e.status}`;if(_n(e.status,s),So(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 wo=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 Eo(e){return mn(e,wo)}function So(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 bo=1e4;async function Ao(e,t=bo){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)&&Eo(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 Lo(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 wn(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 En(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var Pn=b(require("path"));var ut=require("crypto"),a=b(require("fs")),_=b(require("path"));var Le=1024*1024,ko=5e3,To=20,Io=3e4,ct=4096,Oo=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 A=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Co=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(Co??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 vo(e){Atomics.wait(Oo,0,0,e)}function vn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function Ro(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(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()||!re(i,s))throw new Error("credential-store parent changed while it was being inspected");ne(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),c=a.default.fstatSync(o)),(c.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 A:i}if(!re(n,o))throw r.retryOnPathChange?new A: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 te;if(ne(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 No(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 o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Le)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}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(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 No(t,r)}finally{t!==null&&a.default.closeSync(t)}}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(o){if(m(o,"ENOENT")&&Cn(e))return;throw o}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 Po(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 xo(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.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 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 Bo(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),o=_.basename(e),i=null,s=null,c=!1;try{let u=xo(r,o);i=u.fd,s=u.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");Rn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),Po(e),a.default.renameSync(s,e),c=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Nn(r)}function Do(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Uo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function $o(e,t){if(t.size>ct)return null;let n=Buffer.alloc(ct+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>ct)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 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 A}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=$o(n,o);return{state:(i?.target===t&&i?!vn(i.pid):Date.now()-o.mtimeMs>=Io)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function Fo(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.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 c=a.default.fstatSync(s),u=O(o,s,c,{allowMultipleLinks:!0});return Rn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Mo(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 A:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!re(o,t))throw new A;return{fd:n,lockPath:e,stats:o}}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 A}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 Go(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");vo(To)}function Tn(e){let t=_.dirname(e),n=_.basename(e),r=Do(e),o=Uo(e),i=Fo(t,n),s=Date.now()+ko,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(kn(o)){P(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=Mo(r,i.stats),c=!0}catch(p){if(u&&!c){try{B(r,i.stats)}catch{}u=!1}if(p instanceof A){P(s,!1);continue}if(!m(p,"EEXIST"))throw p;let L;try{L=Ln(r,n)}catch(w){if(w instanceof A){P(s,!1);continue}throw w}if(L.state==="absent")continue;if(L.state==="stale"){let w;try{w=Go(o)}catch(S){if(S instanceof A){P(s,!1);continue}throw S}if(w!==null){try{let S;try{S=Ln(r,n)}catch(ie){if(ie instanceof A){P(s,!1);continue}throw ie}S.state==="stale"&&B(r,S.stats)}finally{lt(w)}continue}}let g;try{g=kn(o)}catch(w){if(w instanceof A){P(s,!1);continue}throw w}P(s,g)}}catch(p){f=p}try{B(i.claimPath,i.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 Ko(e,t){let n=Ro(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 In(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let o=Ko(r,n);if(o===null||vn(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 c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!re(c,u))continue;try{ne(c,"credential-store orphan")}catch{continue}B(i,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function oe(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:()=>bn(e),remove:()=>An(e),write:()=>{throw x()}})}finally{lt(s)}}if(!t.createParent){let i=!1;try{i=Cn(e)}catch{throw x()}if(i)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 o=Tn(e);try{return In(e),n({read:()=>bn(e),remove:()=>An(e),write:i=>Bo(e,i)})}finally{lt(o)}}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 Yo(){return Kt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function qo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
|
|
15
|
+
`)}};var $r=/_(removed|cleared|count|total)$/i;function Fr(e,t){return typeof t=="number"&&$r.test(e)}var Mr=new Set(Xt);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(o=>_e(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,me))n[o]=le(o)&&!Fr(o,i)&&!Gr(o,i)&&!Yr(o,i)?"<redacted>":_e(i,t+1);if(r.length>me){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-me} more keys`}return n}if(typeof e=="string"){let n=qr(e);return n!==void 0?E(JSON.stringify(_e(n,t+1))):E(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:E(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Hr(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))}var we="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(";"),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 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=b(require("crypto")),tn=b(require("fs")),nn=b(require("path"));var Wr="key-id",Jr="x-allscale-cli-version",rt="cli-1",zr="aScaLe_cli_obf_v1",Xr="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Vr(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 Zr=Vr(Xr,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 o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o: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 eo(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 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():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 to(){return"1.0.4"}function no(){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 ot(e,t){let n=Qr(t);if(!n)throw no();let r=eo(t),o=Math.floor(Date.now()/1e3).toString(),i=en.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Jr]:to()};return r.length>0&&(s[Wr]=r),s}function sn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ro(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=ro(e.profile);if(t)return t}return new l("auth.no_token",kt(e.profile))}var oo=500,io=8,cn=100;function it(e,t=0){if(t>io)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,cn),r=n.map(o=>it(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,cn))n[r]=le(r)?"<redacted>":it(o,t+1);return n}return e}function so(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=oo){let n=so(e),r=n===void 0?ce(e):JSON.stringify(it(n));return ue(r,t)}var st=256*1024,Ee=class extends l{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"}},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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);if(!e.body)return"";let i=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=i.read(),{done:L,value:g}=f?await Promise.race([p,f]):await p;if(L)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Se&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var ao="X-AllScale-Api-Key",co=3e4,lo=32*1024*1024,uo=4*1024*1024;function fo(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 po(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 ho(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{}ho(e.status,e.url)}}var un="--dns-result-order=ipv4first";async function be(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)??"",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(!((i||c)&&(o||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 Ae=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??co;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 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=fo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.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{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();zt(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=gn(t.path),u=s==="required"?!0:s==="none"?!1:yo(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw an({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=sn(t.body),f=!!i||!!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:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{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(o)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-L}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let S=await po(this.refreshSingleFlight(),t.signal),ie=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:o});let Oe;try{Oe=await fetch(o,{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(o)} 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&&!!i,responseKind:fn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...ot(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=rn;let o=t.tokens;if(o?.agent_key)return r[ao]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=tt([{name:we,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(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:we,value:t.access_token},{name:et,value:t.refresh_token}]),o=ot("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=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 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 be(u);let w=await Ao(u);await be(u,w),_n(u.status,w),u.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 l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ae()}.`,{status:u.status})}let d=Qt(u.headers),f=nt(d,we),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}},go=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function gn(e){let t=e.split(/[?#]/,1)[0];return go.some(n=>t===n||t.startsWith(`${n}/`))}var mo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function _o(e){let t=e.split(/[?#]/,1)[0];return mo.some(n=>n.test(t))}function yo(e){return gn(e)||_o(e)}async function dn(e,t={}){await hn(e);let n=e.status>=200&&e.status<300;n||await be(e);let r=t.responseKind??"mutation",i=await at(e,n?r==="query"?lo:uo:st,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await be(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 u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=Lo(s)??`HTTP ${e.status}`;if(_n(e.status,s),So(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 wo=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 Eo(e){return mn(e,wo)}function So(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 bo=1e4;async function Ao(e,t=bo){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)&&Eo(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 Lo(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 wn(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 En(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var Pn=b(require("path"));var ut=require("crypto"),a=b(require("fs")),_=b(require("path"));var Le=1024*1024,ko=5e3,To=20,Io=3e4,ct=4096,Oo=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 A=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Co=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(Co??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 vo(e){Atomics.wait(Oo,0,0,e)}function vn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function Ro(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(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()||!re(i,s))throw new Error("credential-store parent changed while it was being inspected");ne(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),c=a.default.fstatSync(o)),(c.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 A:i}if(!re(n,o))throw r.retryOnPathChange?new A: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 te;if(ne(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 No(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 o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Le)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}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(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 No(t,r)}finally{t!==null&&a.default.closeSync(t)}}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(o){if(m(o,"ENOENT")&&Cn(e))return;throw o}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 Po(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 xo(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.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 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 Bo(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),o=_.basename(e),i=null,s=null,c=!1;try{let u=xo(r,o);i=u.fd,s=u.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");Rn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),Po(e),a.default.renameSync(s,e),c=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Nn(r)}function Do(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Uo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function $o(e,t){if(t.size>ct)return null;let n=Buffer.alloc(ct+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>ct)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 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 A}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=$o(n,o);return{state:(i?.target===t&&i?!vn(i.pid):Date.now()-o.mtimeMs>=Io)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function Fo(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.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 c=a.default.fstatSync(s),u=O(o,s,c,{allowMultipleLinks:!0});return Rn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Mo(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 A:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!re(o,t))throw new A;return{fd:n,lockPath:e,stats:o}}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 A}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 Go(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");vo(To)}function Tn(e){let t=_.dirname(e),n=_.basename(e),r=Do(e),o=Uo(e),i=Fo(t,n),s=Date.now()+ko,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(kn(o)){P(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=Mo(r,i.stats),c=!0}catch(p){if(u&&!c){try{B(r,i.stats)}catch{}u=!1}if(p instanceof A){P(s,!1);continue}if(!m(p,"EEXIST"))throw p;let L;try{L=Ln(r,n)}catch(w){if(w instanceof A){P(s,!1);continue}throw w}if(L.state==="absent")continue;if(L.state==="stale"){let w;try{w=Go(o)}catch(S){if(S instanceof A){P(s,!1);continue}throw S}if(w!==null){try{let S;try{S=Ln(r,n)}catch(ie){if(ie instanceof A){P(s,!1);continue}throw ie}S.state==="stale"&&B(r,S.stats)}finally{lt(w)}continue}}let g;try{g=kn(o)}catch(w){if(w instanceof A){P(s,!1);continue}throw w}P(s,g)}}catch(p){f=p}try{B(i.claimPath,i.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 Ko(e,t){let n=Ro(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 In(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let o=Ko(r,n);if(o===null||vn(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 c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!re(c,u))continue;try{ne(c,"credential-store orphan")}catch{continue}B(i,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function oe(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:()=>bn(e),remove:()=>An(e),write:()=>{throw x()}})}finally{lt(s)}}if(!t.createParent){let i=!1;try{i=Cn(e)}catch{throw x()}if(i)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 o=Tn(e);try{return In(e),n({read:()=>bn(e),remove:()=>An(e),write:i=>Bo(e,i)})}finally{lt(o)}}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 Yo(){return Kt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function qo(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
16
|
`,1)[0]==="Cannot find module 'keytar'"}function jo(){if(D!==void 0)return D;if(Yo())return pt=!1,D=null,D;try{D=require("keytar"),pt=!1}catch(e){pt=!qo(e),D=null}return D}var Ho="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";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",`${Ho} `+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))}},Wo="credentials.json",_t=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Pn.join(Qe(),Wo)}read(t){let n;try{n=t.read()}catch(o){throw ke(o)?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 oe(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{oe(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 l?r:Ie()}}async delete(t){try{oe(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 oe(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=jo();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
|
package/oclif.manifest.json
CHANGED