@allscale/cli 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,5 +13,5 @@
13
13
  To move to production, run: allscale device-login --api-base ${ee}
14
14
  `}var B=A(require("fs")),tn=A(require("os")),tt=A(require("path")),nt=A(require("@iarna/toml"));var Mr=".allscale",Kr="config.toml";function rt(){return tt.join(tn.homedir(),Mr)}function jr(){return tt.join(rt(),Kr)}function me(){let e=jr();if(!B.existsSync(e))return{};let t=B.readFileSync(e,"utf-8");try{return nt.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function nn(e){return Object.keys(e.profile??{}).sort()}function rn(e,t){return e.profile?.[t]}function on(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 R(e){if(!$e(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Be)}function _e(e,t){R(e);let n=P(e),r=typeof t=="string"?P(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 sn(e,t){let n=P(e),r=P(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 ye(e){let t=Yr(e);if(t)throw new l("input.invalid",t.message)}function qr(){let e=J();if(e===void 0)return;let t=V();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Yr(e){let t=qr();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,o=P(e),i=n.map(c=>P(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 Hr=require("@noble/hashes/sha3");var an=["USDT","USDC"];var os=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Wr="unknown_otp_id",zr="invalid_code",Jr="expired_code";function Vr(e){return`'${e.replace(/'/g,"'\\''")}'`}function ln(e){return`Run \`allscale otp-send --email ${Vr(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Xr=new Map([[Wr,(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. ${ln(t)}`],[zr,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.`],[Jr,(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. ${ln(t)}`]]);var cn=[...Xr.keys()];var re=require("@oclif/core"),ne=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:v()==="public"}),"api-base":I.Flags.string({description:Pe,helpGroup:"GLOBAL",hidden:v()==="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{Ve(this.jsonEnabled()),Ze(),w({type:"session-start",command:this.id??"",argv:Qe(this.argv)});let t=this.constructor;if(v()==="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&&te()!==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=zt(this.jsonEnabled()),r=this.argv.length===0&&!n&&so(t)?this.config.findCommand(this.id??""):void 0;if(r){Z();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&&!Qt())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 w({type:"command-end",ok:!0}),Z(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ut(o),{data:o})}catch(t){let n=Dt(t);Jt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ve(!1)}}resolveSessionApiBaseChain(t){let n=me(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||et()!==void 0,s=on(n,r,et()),c=rn(n,s),u=v()==="public"&&te()!==void 0,d=o??(u?void 0:te()),f=d??c?.api_base??ee,p=en({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,q({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||R(n),n}resolveContext(t){if(v()==="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&&te()!==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||(R(o),ye(o)),{apiBase:o,profile:c,token:n??Vt(),insecureStorage:r||Xt(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${io(t)}
15
15
  `)}};var Zr=/_(removed|cleared|count|total)$/i;function Qr(e,t){return typeof t=="number"&&Zr.test(e)}var eo=new Set(an);function to(e,t){return e==="token_symbol"&&typeof t=="string"&&eo.has(t)}var no=new Set(cn);function ro(e,t){return e==="otp_reason"&&typeof t=="string"&&no.has(t)}var we=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(o=>be(o,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[o,i]of r.slice(0,we))n[o]=fe(o)&&!Qr(o,i)&&!to(o,i)&&!ro(o,i)?"<redacted>":be(i,t+1);if(r.length>we){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-we} more keys`}return n}if(typeof e=="string"){let n=oo(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function oo(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 io(e){let t=jt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function so(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 Sn=A(require("path"));var st=require("crypto"),a=A(require("fs")),y=A(require("path"));var Ee=1024*1024,ao=5e3,lo=20,co=3e4,ot=4096,uo=new Int32Array(new SharedArrayBuffer(4)),oe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Se(e){return e instanceof oe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},fo=null;function D(){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 Ae(){return(fo??process.platform)!=="win32"}function _n(){if(!Ae())throw D()}function yn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!_(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(y.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(_(t,"ENOENT"))return!0;throw t}}function _(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ie(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function se(e,t){return e.dev===t.dev&&e.ino===t.ino}function po(e){Atomics.wait(uo,0,0,e)}function wn(e){try{return process.kill(e,0),!0}catch(t){return!_(t,"ESRCH")}}function ho(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function un(e,t){let n=y.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&_(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!se(i,s))throw new Error("credential-store parent changed while it was being inspected");ie(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&y.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&&_(i,"ENOENT")?new k:i}if(!se(n,o))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||o.nlink!==1))throw new oe;if(ie(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function go(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function dn(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(_(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(_(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return go(t,r)}finally{t!==null&&a.default.closeSync(t)}}function fn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(_(o,"ENOENT")&&yn(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);U(e,r)}finally{t!==null&&a.default.closeSync(t)}En(y.dirname(e))}function mo(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(_(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new oe;ie(t,"credential-store replacement target")}function _o(e,t){for(let n=0;n<8;n+=1){let r=(0,st.randomBytes)(12).toString("hex"),o=y.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(_(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function bn(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 En(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 yo(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=y.dirname(e),o=y.basename(e),i=null,s=null,c=!1;try{let u=_o(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");bn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),mo(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{}}En(r)}function wo(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock`)}function bo(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock-recovery`)}function Eo(e,t){if(t.size>ot)return null;let n=Buffer.alloc(ot+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>ot)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 U(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");ie(n,"credential-store lock"),a.default.unlinkSync(e)}function pn(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(_(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 k}catch(d){if(_(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=Eo(n,o);return{state:(i?.target===t&&i?!wn(i.pid):Date.now()-o.mtimeMs>=co)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function So(e,t){for(let n=0;n<8;n+=1){let r=(0,st.randomBytes)(12).toString("hex"),o=y.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 bn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(_(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 Ao(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 _(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(o,t))throw new k;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function hn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(_(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(_(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 ko(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(_(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{U(e,n)}catch{}throw a.default.closeSync(t),r}}function $(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");po(lo)}function gn(e){let t=y.dirname(e),n=y.basename(e),r=wo(e),o=bo(e),i=So(t,n),s=Date.now()+ao,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(hn(o)){$(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=Ao(r,i.stats),c=!0}catch(p){if(u&&!c){try{U(r,i.stats)}catch{}u=!1}if(p instanceof k){$(s,!1);continue}if(!_(p,"EEXIST"))throw p;let b;try{b=pn(r,n)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}if(b.state==="absent")continue;if(b.state==="stale"){let m;try{m=ko(o)}catch(E){if(E instanceof k){$(s,!1);continue}throw E}if(m!==null){try{let E;try{E=pn(r,n)}catch(N){if(N instanceof k){$(s,!1);continue}throw N}E.state==="stale"&&U(r,E.stats)}finally{it(m)}continue}}let g;try{g=hn(o)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}$(s,g)}}catch(p){f=p}try{U(i.claimPath,i.stats)}catch(p){!_(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 it(e){try{U(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Lo(e,t){let n=ho(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 mn(e){let t=y.dirname(e),n=y.basename(e);for(let r of a.default.readdirSync(t)){let o=Lo(r,n);if(o===null||wn(o))continue;let i=y.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(_(d,"ENOENT")||_(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!se(c,u))continue;try{ie(c,"credential-store orphan")}catch{continue}U(i,c)}catch(c){if(!_(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!Ae()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!un(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let s=gn(e);try{return mn(e),n({read:()=>dn(e),remove:()=>fn(e),write:()=>{throw D()}})}finally{it(s)}}if(!t.createParent){let i=!1;try{i=yn(e)}catch{throw D()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!un(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=gn(e);try{return mn(e),n({read:()=>dn(e),remove:()=>fn(e),write:i=>yo(e,i)})}finally{it(o)}}var at="allscale-cli";function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function An(e){return dt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(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 lt(){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 ke(){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 F,ct=!1;function To(){return Zt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Io(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 Oo(){if(F!==void 0)return F;if(To())return ct=!1,F=null,F;try{F=require("keytar"),ct=!1}catch(e){ct=!Io(e),F=null}return F}var vo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function kn(){let e=Ae()?"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",`${vo} `+e+" Never silently downgrade in production.")}async function ut(e){try{return await e()}catch{throw kn()}}var ft=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ut(()=>this.keytar.getPassword(at,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!An(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ut(()=>this.keytar.setPassword(at,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ut(()=>this.keytar.deletePassword(at,t))}},Co="credentials.json",pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Sn.join(rt(),Co)}read(t){let n;try{n=t.read()}catch(o){throw Se(o)?lt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!dt(r)||!dt(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Se(r)?lt():ke()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!An(r))throw G("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:G("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof l?r:ke()}}async delete(t){try{ae(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:ke()}}async clearProfile(t){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Se(n)?lt():ke()}}};function Ln(e){if(e.insecureStorage)return _n(),new pt(e.insecureFilePath);let t=Oo();if(t)return new ft(t);throw kn()}var ht=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Le(){return new ht}var Te="allscale_access_token",gt="allscale_refresh_token";function Tn(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 mt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function _t(e,t){return e.find(n=>n.name===t)?.value??null}var In=A(require("crypto")),On=A(require("fs")),vn=A(require("path"));var Ro="key-id",No="x-allscale-cli-version",yt="cli-1",xo="aScaLe_cli_obf_v1",Po="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Bo(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 $o=Bo(Po,xo),Cn=`Bearer ${$o}`;function Rn(e,t){let n=Ue(e);if(n!==null)return t.find(r=>Ue(r.base)===n)}function Do(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=Rn(e,t);if(r)return r.key;if(x(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:x(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 Uo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?Rn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(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():yt}if(!x(t[0].base))return yt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():yt}function Fo(){return"1.0.3"}function Go(){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 wt(e,t){let n=Do(t);if(!n)throw Go();let r=Uo(t),o=Math.floor(Date.now()/1e3).toString(),i=In.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[No]:Fo()};return r.length>0&&(s[Ro]=r),s}function Nn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Mo(e,t={}){let n;try{n=nn(me())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",$t(e)+(t.messageSuffix??""),{profile:e})}function xn(e){if(e.profileExplicit){let t=Mo(e.profile);if(t)return t}return new l("auth.no_token",Bt(e.profile))}var Ko=500,jo=8,Pn=100;function bt(e,t=0){if(t>jo)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Pn),r=n.map(o=>bt(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,Pn))n[r]=fe(r)?"<redacted>":bt(o,t+1);return n}return e}function qo(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 Bn(e,t=Ko){let n=qo(e),r=n===void 0?de(e):JSON.stringify(bt(n));return pe(r,t)}var Et=256*1024,Ie=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"}},Oe=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 St(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 Ie(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,b)=>{u=setTimeout(()=>{b(new Oe(e.status,d))},d),u.unref?.()});try{for(;;){let p=i.read(),{done:b,value:g}=f?await Promise.race([p,f]):await p;if(b)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ie(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Oe&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var Yo="X-AllScale-Api-Key",Ho=3e4,Wo=32*1024*1024,zo=4*1024*1024;function Jo(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 Vo(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 Xo(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 Gn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Xo(e.status,e.url)}}var $n="--dns-result-order=ipv4first";async function ve(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=${$n} 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=${$n}`})}var M=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??Ho;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),ye(this.opts.apiBase);let o=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),i=Jo(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();sn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Mn(t.path),u=s==="required"?!0:s==="none"?!1:ei(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw xn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Nn(t.body),f=!!i||!!r?.access_token;u&&f&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();w({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(E){throw new l("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-b}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await Vo(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),Zn=Date.now();w({type:"request",method:t.method??"GET",url:o});let Ne;try{Ne=await fetch(o,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(xe){throw new l("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${xe instanceof Error?xe.message:String(xe)}`)}return w({type:"response",status:Ne.status,durationMs:Date.now()-Zn}),Dn(Ne,{withMetadata:n.withMetadata,authBearing:u,responseKind:Un(t)})}return Dn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!i,responseKind:Un(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...wt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Cn;let o=t.tokens;if(o?.agent_key)return r[Yo]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=mt([{name:Te,value:i}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new 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 ${ue()}.`);if(_e(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=mt([{name:Te,value:t.access_token},{name:gt,value:t.refresh_token}]),o=wt("",this.opts.apiBase);w({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 w({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)}w({type:"response",status:u.status,durationMs:0});try{await Gn(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await ve(u);let m=await ii(u);await ve(u,m),jn(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:u.status})}let d=Tn(u.headers),f=_t(d,Te),p=_t(d,gt);if(!f||!p)throw w({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,b),w({type:"refresh",ok:!0}),b}},Zo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Mn(e){let t=e.split(/[?#]/,1)[0];return Zo.some(n=>t===n||t.startsWith(`${n}/`))}var Qo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function At(e){let t=e.split(/[?#]/,1)[0];return Qo.some(n=>n.test(t))}function ei(e){return Mn(e)||At(e)}async function Dn(e,t={}){await Gn(e);let n=e.status>=200&&e.status<300;n||await ve(e);let r=t.responseKind??"mutation",i=await St(e,n?r==="query"?Wo:zo:Et,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await ve(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=si(s)??`HTTP ${e.status}`;if(jn(e.status,s),ri(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function Un(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var ti=2014,Fn=2004;function Kn(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 ni(e){return Kn(e,ti)}function ri(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Kn(t,Fn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Fn})}var oi=1e4;async function ii(e,t=oi){if(e.status>=200&&e.status<300)return"";try{return await St(e,Et,{timeoutMs:t})}catch{return""}}function jn(e,t){if(!(e>=200&&e<300)&&ni(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"?Bn(t):t})}function si(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 ai=/^\/(api\/)?(v1\/)?public\//;function kt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ai.test(n),o=n&&At(n),i=r&&!o&&!t.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Ln({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var li=new Set;var ci=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),qn=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Yn=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Lt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var ui=new Set(["cli_op:all"]),di=new Set([...ui].map(Lt));var ta=new Set([...[...ci,...qn,...li].map(Lt),...Yn,...di]);var le=8100,fi=new Set([le]),ga=new Set([...fi,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Hn="/api/v1/public/claim-links";var pi=1e4,hi="No Claim Link matches this claim token. The token did reach the backend \u2014 an empty or malformed one is refused locally, before anything is sent \u2014 and the public receiver endpoint answers the same way for every token that resolves to nothing, so it will not confirm whether a token exists. Re-check the claim link or URL you were given. An expired or already-claimed link is NOT this error: it still resolves, and comes back as a status snapshot or a 200 claim outcome.";function gi(e){let t=e?.body;if(!t||typeof t!="object")return;let n=t.code;if(typeof n=="number")return n;if(typeof n=="string"&&/^[0-9]+$/.test(n))return Number(n)}function Wn(e){throw e instanceof l&&e.code==="not_found"&&gi(e.details)===le?new l("not_found",hi,{status:404,backend_code:le}):e}function zn(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Hn}/${n}:claim`:`${Hn}/${n}`}function Ce(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let o=t.trim();if(!o)throw new l("input.invalid","--claim-token is empty.");return Tt(o,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return Tt(mi(r),"--claim-url")}async function Jn(e,t,n=pi){let r=e["claim-url"]?.trim();if(!r)return Ce(e);let o;try{o=new URL(r)}catch{return Ce(e)}let i=/^\/s\/([^/]+)\/?$/.exec(o.pathname);if(!i||e["claim-token"]!==void 0)return Ce(e);R(t);let s=new URL(t).origin;if(o.origin!==s||o.username||o.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(i[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let b;try{b=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=b.headers.get("location");try{b.body?.cancel().catch(()=>{})}catch{}if(b.status!==302||!g)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:b.status});let m;try{m=new URL(g,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let E=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!E)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(E[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return Tt(N,"--claim-url")}function Tt(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function mi(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),o=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],i=o.endsWith(":claim")?o.slice(0,-6):o;try{return decodeURIComponent(i)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function Vn(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function Xn(e,t=""){let n=v()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var Re=class e extends ne{static description="Read the public receiver-facing status snapshot for a Claim Link bearer token or URL.";static examples=["$ allscale claim-link status --claim-token claim-token-from-share-link","$ allscale claim-link status --claim-url https://app.allscale.io/claim/claim-token-from-share-link"];static usage=Xn("status");static requiresInput=!0;static flags={"claim-token":re.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":re.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),...ne.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Jn(t,n.apiBase),o=zn(r),s=await kt(n,{pathHint:o}).request({method:"GET",path:o,auth:"none"}).catch(Wn);return Vn(s)}};
16
+ `,1)[0]==="Cannot find module 'keytar'"}function Oo(){if(F!==void 0)return F;if(To())return ct=!1,F=null,F;try{F=require("keytar"),ct=!1}catch(e){ct=!Io(e),F=null}return F}var vo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function kn(){let e=Ae()?"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",`${vo} `+e+" Never silently downgrade in production.")}async function ut(e){try{return await e()}catch{throw kn()}}var ft=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ut(()=>this.keytar.getPassword(at,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!An(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ut(()=>this.keytar.setPassword(at,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ut(()=>this.keytar.deletePassword(at,t))}},Co="credentials.json",pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Sn.join(rt(),Co)}read(t){let n;try{n=t.read()}catch(o){throw Se(o)?lt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!dt(r)||!dt(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Se(r)?lt():ke()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!An(r))throw G("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:G("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof l?r:ke()}}async delete(t){try{ae(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:ke()}}async clearProfile(t){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Se(n)?lt():ke()}}};function Ln(e){if(e.insecureStorage)return _n(),new pt(e.insecureFilePath);let t=Oo();if(t)return new ft(t);throw kn()}var ht=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Le(){return new ht}var Te="allscale_access_token",gt="allscale_refresh_token";function Tn(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 mt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function _t(e,t){return e.find(n=>n.name===t)?.value??null}var In=A(require("crypto")),On=A(require("fs")),vn=A(require("path"));var Ro="key-id",No="x-allscale-cli-version",yt="cli-1",xo="aScaLe_cli_obf_v1",Po="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Bo(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 $o=Bo(Po,xo),Cn=`Bearer ${$o}`;function Rn(e,t){let n=Ue(e);if(n!==null)return t.find(r=>Ue(r.base)===n)}function Do(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=Rn(e,t);if(r)return r.key;if(x(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:x(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 Uo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?Rn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(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():yt}if(!x(t[0].base))return yt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():yt}function Fo(){return"1.0.4"}function Go(){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 wt(e,t){let n=Do(t);if(!n)throw Go();let r=Uo(t),o=Math.floor(Date.now()/1e3).toString(),i=In.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[No]:Fo()};return r.length>0&&(s[Ro]=r),s}function Nn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Mo(e,t={}){let n;try{n=nn(me())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",$t(e)+(t.messageSuffix??""),{profile:e})}function xn(e){if(e.profileExplicit){let t=Mo(e.profile);if(t)return t}return new l("auth.no_token",Bt(e.profile))}var Ko=500,jo=8,Pn=100;function bt(e,t=0){if(t>jo)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Pn),r=n.map(o=>bt(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,Pn))n[r]=fe(r)?"<redacted>":bt(o,t+1);return n}return e}function qo(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 Bn(e,t=Ko){let n=qo(e),r=n===void 0?de(e):JSON.stringify(bt(n));return pe(r,t)}var Et=256*1024,Ie=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"}},Oe=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 St(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 Ie(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,b)=>{u=setTimeout(()=>{b(new Oe(e.status,d))},d),u.unref?.()});try{for(;;){let p=i.read(),{done:b,value:g}=f?await Promise.race([p,f]):await p;if(b)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ie(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Oe&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var Yo="X-AllScale-Api-Key",Ho=3e4,Wo=32*1024*1024,zo=4*1024*1024;function Jo(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 Vo(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 Xo(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 Gn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Xo(e.status,e.url)}}var $n="--dns-result-order=ipv4first";async function ve(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=${$n} 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=${$n}`})}var M=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??Ho;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),ye(this.opts.apiBase);let o=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),i=Jo(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();sn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Mn(t.path),u=s==="required"?!0:s==="none"?!1:ei(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw xn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Nn(t.body),f=!!i||!!r?.access_token;u&&f&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();w({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(E){throw new l("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-b}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await Vo(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),Zn=Date.now();w({type:"request",method:t.method??"GET",url:o});let Ne;try{Ne=await fetch(o,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(xe){throw new l("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${xe instanceof Error?xe.message:String(xe)}`)}return w({type:"response",status:Ne.status,durationMs:Date.now()-Zn}),Dn(Ne,{withMetadata:n.withMetadata,authBearing:u,responseKind:Un(t)})}return Dn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!i,responseKind:Un(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...wt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Cn;let o=t.tokens;if(o?.agent_key)return r[Yo]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=mt([{name:Te,value:i}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new 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 ${ue()}.`);if(_e(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=mt([{name:Te,value:t.access_token},{name:gt,value:t.refresh_token}]),o=wt("",this.opts.apiBase);w({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 w({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)}w({type:"response",status:u.status,durationMs:0});try{await Gn(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await ve(u);let m=await ii(u);await ve(u,m),jn(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:u.status})}let d=Tn(u.headers),f=_t(d,Te),p=_t(d,gt);if(!f||!p)throw w({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,b),w({type:"refresh",ok:!0}),b}},Zo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Mn(e){let t=e.split(/[?#]/,1)[0];return Zo.some(n=>t===n||t.startsWith(`${n}/`))}var Qo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function At(e){let t=e.split(/[?#]/,1)[0];return Qo.some(n=>n.test(t))}function ei(e){return Mn(e)||At(e)}async function Dn(e,t={}){await Gn(e);let n=e.status>=200&&e.status<300;n||await ve(e);let r=t.responseKind??"mutation",i=await St(e,n?r==="query"?Wo:zo:Et,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await ve(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=si(s)??`HTTP ${e.status}`;if(jn(e.status,s),ri(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function Un(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var ti=2014,Fn=2004;function Kn(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 ni(e){return Kn(e,ti)}function ri(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Kn(t,Fn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Fn})}var oi=1e4;async function ii(e,t=oi){if(e.status>=200&&e.status<300)return"";try{return await St(e,Et,{timeoutMs:t})}catch{return""}}function jn(e,t){if(!(e>=200&&e<300)&&ni(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"?Bn(t):t})}function si(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 ai=/^\/(api\/)?(v1\/)?public\//;function kt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ai.test(n),o=n&&At(n),i=r&&!o&&!t.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Ln({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new M({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var li=new Set;var ci=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),qn=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Yn=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Lt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var ui=new Set(["cli_op:all"]),di=new Set([...ui].map(Lt));var ta=new Set([...[...ci,...qn,...li].map(Lt),...Yn,...di]);var le=8100,fi=new Set([le]),ga=new Set([...fi,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Hn="/api/v1/public/claim-links";var pi=1e4,hi="No Claim Link matches this claim token. The token did reach the backend \u2014 an empty or malformed one is refused locally, before anything is sent \u2014 and the public receiver endpoint answers the same way for every token that resolves to nothing, so it will not confirm whether a token exists. Re-check the claim link or URL you were given. An expired or already-claimed link is NOT this error: it still resolves, and comes back as a status snapshot or a 200 claim outcome.";function gi(e){let t=e?.body;if(!t||typeof t!="object")return;let n=t.code;if(typeof n=="number")return n;if(typeof n=="string"&&/^[0-9]+$/.test(n))return Number(n)}function Wn(e){throw e instanceof l&&e.code==="not_found"&&gi(e.details)===le?new l("not_found",hi,{status:404,backend_code:le}):e}function zn(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Hn}/${n}:claim`:`${Hn}/${n}`}function Ce(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let o=t.trim();if(!o)throw new l("input.invalid","--claim-token is empty.");return Tt(o,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return Tt(mi(r),"--claim-url")}async function Jn(e,t,n=pi){let r=e["claim-url"]?.trim();if(!r)return Ce(e);let o;try{o=new URL(r)}catch{return Ce(e)}let i=/^\/s\/([^/]+)\/?$/.exec(o.pathname);if(!i||e["claim-token"]!==void 0)return Ce(e);R(t);let s=new URL(t).origin;if(o.origin!==s||o.username||o.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(i[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let b;try{b=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=b.headers.get("location");try{b.body?.cancel().catch(()=>{})}catch{}if(b.status!==302||!g)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:b.status});let m;try{m=new URL(g,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let E=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!E)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(E[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return Tt(N,"--claim-url")}function Tt(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function mi(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),o=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],i=o.endsWith(":claim")?o.slice(0,-6):o;try{return decodeURIComponent(i)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function Vn(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function Xn(e,t=""){let n=v()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var Re=class e extends ne{static description="Read the public receiver-facing status snapshot for a Claim Link bearer token or URL.";static examples=["$ allscale claim-link status --claim-token claim-token-from-share-link","$ allscale claim-link status --claim-url https://app.allscale.io/claim/claim-token-from-share-link"];static usage=Xn("status");static requiresInput=!0;static flags={"claim-token":re.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":re.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),...ne.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Jn(t,n.apiBase),o=zn(r),s=await kt(n,{pathHint:o}).request({method:"GET",path:o,auth:"none"}).catch(Wn);return Vn(s)}};
17
17
  //# sourceMappingURL=status.js.map
@@ -13,7 +13,7 @@
13
13
  To move to production, run: allscale device-login --api-base ${ie}
14
14
  `}var T=A(require("fs")),un=A(require("os")),ut=A(require("path")),ve=A(require("@iarna/toml"));var si=".allscale",ai="config.toml";function Te(){return ut.join(un.homedir(),si)}function Ie(){return ut.join(Te(),ai)}function se(){let e=Ie();if(!T.existsSync(e))return{};let t=T.readFileSync(e,"utf-8");try{return ve.parse(t)}catch(n){throw new u("internal",`Failed to parse ${e}: ${n.message}`)}}function dn(e){let t=Te();T.existsSync(t)||T.mkdirSync(t,{recursive:!0,mode:448});let n=ve.stringify(e),r=Ie();T.writeFileSync(r,n,{mode:384});try{T.chmodSync(r,384)}catch{}}function pn(e,t){return e.profile?.[t]}function fn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function hn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new u("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function Oe(e){if(!_e(e))throw new u("input.invalid",`Refusing to send credentials to API base ${B(e)}. `+He)}function dt(e){let t=ci(e);if(t)throw new u("input.invalid",t.message)}function li(){let e=Z();if(e===void 0)return;let t=Q();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function ci(e){let t=li();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,i=lt(e),o=n.map(l=>lt(l)).filter(l=>l!==null);if(i!==null&&o.includes(i))return;let s=n.map(l=>B(l)).join(", ");return{message:r?`Refusing to send to ${B(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 ${B(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var ui=require("@noble/hashes/sha3");var gn=["USDT","USDC"];var Is=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var di="unknown_otp_id",pi="invalid_code",fi="expired_code";function hi(e){return`'${e.replace(/'/g,"'\\''")}'`}function mn(e){return`Run \`allscale otp-send --email ${hi(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var gi=new Map([[di,(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. ${mn(t)}`],[pi,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.`],[fi,(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. ${mn(t)}`]]);var _n=[...gi.keys()];var N=require("@oclif/core"),ae=class e extends O.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:O.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:O.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:Y()==="public"}),"api-base":O.Flags.string({description:qe,helpGroup:"GLOBAL",hidden:Y()==="public"}),"insecure-storage":O.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{it(this.jsonEnabled()),st(),I({type:"session-start",command:this.id??"",argv:at(this.argv)});let t=this.constructor;if(Y()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new u("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new u("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&oe()!==void 0)throw new u("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=Le(this.jsonEnabled()),r=this.argv.length===0&&!n&&ki(t)?this.config.findCommand(this.id??""):void 0;if(r){ne();let o=await(0,O.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!ln())throw this.argv.length>0&&await this.parse(),new u("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return I({type:"command-end",ok:!0}),ne(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ht(i),{data:i})}catch(t){let n=qt(t);rn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{it(!1)}}resolveSessionApiBaseChain(t){let n=se(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||ct()!==void 0,s=hn(n,r,ct()),l=pn(n,s),d=Y()==="public"&&oe()!==void 0,c=i??(d?void 0:oe()),h=c??l?.api_base??ie,p=cn({resolvedApiBase:h,fromExplicitOverride:c!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,v({event:"legacy_staging_profile",api_base:h,profile:s},p)),{apiBase:h,explicitApiBase:c,envApiBaseIgnored:d,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Oe(n),n}resolveContext(t){if(Y()==="public"){if(t.token!==void 0)throw new u("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 u("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&oe()!==void 0)throw new u("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:l,profileApiBase:d,profileExplicit:c}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Oe(i),dt(i)),{apiBase:i,profile:l,token:n??on(),insecureStorage:r||sn(),apiBaseSource:o!==void 0?"explicit":d!==void 0?"profile":"default",profileExplicit:c,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${Ai(t)}
15
15
  `)}};var mi=/_(removed|cleared|count|total)$/i;function _i(e,t){return typeof t=="number"&&mi.test(e)}var yi=new Set(gn);function wi(e,t){return e==="token_symbol"&&typeof t=="string"&&yi.has(t)}var bi=new Set(_n);function Si(e,t){return e==="otp_reason"&&typeof t=="string"&&bi.has(t)}var Re=100;function Ce(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Re),r=n.map(i=>Ce(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Re))n[i]=we(i)&&!_i(i,o)&&!wi(i,o)&&!Si(i,o)?"<redacted>":Ce(o,t+1);if(r.length>Re){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Re} more keys`}return n}if(typeof e=="string"){let n=Ei(e);return n!==void 0?E(JSON.stringify(Ce(n,t+1))):E(e)}return e}function Ei(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 Ai(e){let t=Vt()?void 0:2,n=Ce(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 ki(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}function yn(e){let t=new Map;for(let n of e){let r=n.lastIndexOf(":");if(r===-1){t.set(n,t.get(n)??new Set);continue}let i=n.slice(0,r),o=n.slice(r+1),s=t.get(i)??new Set;s.add(o),t.set(i,s)}return[...t].map(([n,r])=>{if(r.size===0)return n;if(r.size===1)return`${n}:${[...r][0]}`;let i=["read_only","all"].filter(o=>r.has(o));for(let o of r)i.includes(o)||i.push(o);return`${n}:{${i.join(",")}}`}).join(", ")}var wn=new Set;var bn=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),X=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),le=new Set(["payroll","admin:user","admin:org","admin:audit"]);function D(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function ce(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}function pt(e){return[...X].some(t=>ce(t,e))}function Ne(e){let t=e.lastIndexOf(":");if(t<=0||t===e.length-1)return!1;let n=e.slice(t+1);return n==="read_only"||n==="all"}var Sn=new Set(["cli_op:all"]),En=new Set([...Sn].map(D));function Li(e){return[...Sn].some(t=>ce(t,e))}var ft=new Set([...[...bn,...X,...wn].map(D),...le,...En]);function An(e,t){return vi({known:ft,ungrantable:le,implicit:En,renderedAbove:e,blocksUngrantableLocally:t?.blocksUngrantableLocally??!1})}function P(e,t,n){return e===1?t:n}function vi(e){let{known:t,ungrantable:n,implicit:r}=e,i=new Set([...e.renderedAbove].map(c=>D(c))),o=[...t].filter(c=>n.has(c)).sort(),s=[...t].filter(c=>r.has(c)).sort(),l=[...t].filter(c=>i.has(c)&&!n.has(c)&&!r.has(c)).sort(),d=[];return t.size>0&&d.push(`Every category recognised as a spelling, so a usable value can be found without guessing: ${[...t].sort().join(", ")}.`),l.length>0&&d.push(`${l.join(", ")} ${P(l.length,"carries","carry")} the tiers listed above.`),o.length>0&&d.push(`${o.join(", ")} ${P(o.length,"is","are")} in the catalog but granted to NOBODY \u2014 every mint path drops ${P(o.length,"it","them")}, so no login command can deliver ${P(o.length,"it","them")}`+(e.blocksUngrantableLocally?`; this command rejects ${P(o.length,"it","them")} locally, before any pairing session.`:`, and requesting ${P(o.length,"it","them")} gains nothing.`)),s.length>0&&d.push(`${s.join(", ")} ${P(s.length,"is","are")} attached to every key the backend mints, by both login commands, without being requested \u2014 you never need to ask for ${P(s.length,"it","them")}, and asking is not an error.`),`${d.join(" ")} `}function Ti(e){return e.filter(t=>!Ne(t)||!ft.has(D(t)))}function kn(e){if(!e||e.length===0)return;let t=Ti(e);if(t.length!==0)throw new u("input.invalid",`Unrecognised --scopes value${t.length>1?"s":""}: ${t.join(", ")}. Scope strings are <category>:<tier>, where tier is read_only or all. Known categories: ${[...ft].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}function ht(e){let t={otpLoginOnly:[],reachesNothing:[],ungrantable:[],implicitOnly:[]};for(let n of e){if(!Ne(n))continue;if(Li(n)){t.implicitOnly.push(n);continue}let r=D(n);if(le.has(r)){t.ungrantable.push(n);continue}if(!pt(n)){if(wn.has(n)){t.reachesNothing.push(n);continue}if(bn.has(n)){t.otpLoginOnly.push(n);continue}}}return t}function Ln(e,t){if(!e||e.length===0)return;let n=ht(e),{otpLoginOnly:r,reachesNothing:i,ungrantable:o}=n,s=t?.allowUnrenderable?[]:r,l=[...s,...i,...o];if(l.length!==0)throw new u("input.invalid",`The browser approval screen cannot deliver --scopes value${l.length>1?"s":""}: ${l.join(", ")}. `+(s.length>0?`The screen has no toggle for ${s.join(", ")} \u2014 mint ${s.length>1?"them":"it"} with \`allscale otp-login --email <email> --scopes <scope>\` instead. If your web app's approval screen does offer ${s.length>1?"these":"it"} (this CLI's copy of the screen's catalog can lag a frontend release), re-run with --allow-unrenderable-scopes to let the screen decide. `:"")+(i.length>0?`${i.join(", ")} reaches no operation today \u2014 a key can carry it, but nothing accepts it, so no login path makes it useful. `:"")+(o.length>0?`${o.join(", ")} is not grantable to new keys at all \u2014 no login path can mint it; remove it. `:"")+"Nothing was sent \u2014 no pairing session was created, no browser was opened, and no key was issued.",{unpairable_scopes:n})}var In=require("child_process");function vn(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Ii=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Oi(e,t,n,r){if(vn(e.CI)||Ii.some(s=>vn(e[s])))return"ci";let o=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":n===!0||r===!0?null:"no-tty"}function Ri(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 On(e,t={}){if(!We(e))throw new u("input.invalid",`Refusing to launch browser for untrusted origin: ${B(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new u("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 o=i?null:Oi(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new u("wallet.requires_browser_auth",Ri(o));if(r==="linux"&&!n.DISPLAY&&!i)throw new u("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=Ci(r,i);await Ni(s.command,[...s.args,e])}function Ci(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 Ni(e,t){return new Promise((n,r)=>{let i;try{i=(0,In.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Tn(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(Tn(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function Tn(e,t){return new u("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var gt=require("process"),Rn=require("readline");async function Cn(e){let t=(0,Rn.createInterface)({input:process.stdin,output:gt.stderr}),n;try{let r=await new Promise(o=>{let s=!1,l=d=>{s||(s=!0,o(d))};t.on("SIGINT",()=>l(void 0)),t.on("close",()=>l(void 0)),n=()=>l(void 0),process.on("SIGINT",n),t.question(`${e} [Y/n] `,l)});if(r===void 0)return gt.stderr.write(`
16
- `),!1;let i=r.trim().toLowerCase();return i===""||i==="y"||i==="yes"}finally{n&&process.removeListener("SIGINT",n),t.close()}}var Nn=A(require("crypto")),Pn=A(require("fs")),xn=A(require("path"));var Pi="key-id",xi="x-allscale-cli-version",mt="cli-1",Bi="aScaLe_cli_obf_v1",Di="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function $i(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var Ui=$i(Di,Bi),Fi=`Bearer ${Ui}`;function Bn(e,t){let n=Je(e);if(n!==null)return t.find(r=>Je(r.base)===n)}function Mi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=Q();if(t.length>0){let r=Bn(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(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 Gi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=Q();if(t.length>0){let r=e!==void 0?Bn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():mt}if(!x(t[0].base))return mt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():mt}function Ki(){return"1.0.3"}function Yi(){return new u("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 Pe(e,t){let n=Mi(t);if(!n)throw Yi();let r=Gi(t),i=Math.floor(Date.now()/1e3).toString(),o=Nn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[xi]:Ki()};return r.length>0&&(s[Pi]=r),s}function xe(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ji=500,qi=8,Dn=100;function _t(e,t=0){if(t>qi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Dn),r=n.map(i=>_t(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,Dn))n[r]=we(r)?"<redacted>":_t(i,t+1);return n}return e}function Hi(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 ue(e,t=ji){let n=Hi(e),r=n===void 0?ye(e):JSON.stringify(_t(n));return be(r,t)}var yt=256*1024,Be=class extends u{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},V=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 wt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,d,c=n.timeoutMs,h=c===void 0?void 0:new Promise((p,g)=>{d=setTimeout(()=>{g(new V(e.status,c))},c),d.unref?.()});try{for(;;){let p=o.read(),{done:g,value:S}=h?await Promise.race([p,h]):await p;if(g)break;if(l+=S.byteLength,l>t)throw o.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);s.push(Buffer.from(S))}}catch(p){throw p instanceof V&&o.cancel(p).catch(()=>{}),p}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var Ra=32*1024*1024,Ca=4*1024*1024;function Wi(e,t){if(!(e<300||e>=400))throw new u("transport.network",`API returned HTTP ${e} (a redirect) for ${tn(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 bt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Wi(e.status,e.url)}}var $n="--dns-result-order=ipv4first";async function de(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),d=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||l)&&(i||t!==void 0&&d)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let h=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new u("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=${$n} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...h?{cf_ray:h}:{},ipv4_workaround:`NODE_OPTIONS=${$n}`})}var zi=2014;function Ji(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 Xi(e){return Ji(e,zi)}function St(e,t){if(!(e>=200&&e<300)&&Xi(t))throw new u("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"?ue(t):t})}var Vi={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Un(e){if(typeof e=="string")return e;if(typeof e=="number")return Vi[e]??`user_type_${e}`}function Fn(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var Zi="/api/public/auth/cli_authorize_init",Qi="/api/public/auth/cli_authorize_poll",Et=1e4,At=1e4,eo=1e3,to=3,no=3e4,Gn=900,Kn="empty_response",Yn="invalid_response",jn="poll_fetch_failure",qn="poll_request_timeout",Hn="poll_body_failure",Wn="poll_body_timeout",ro="approved_credential_mismatch",io="pairing_expired_backend_ttl",zn="pairing_token_unrecognized",oo="pairing_token_unrecognized_after_window_closed",so="pairing_deadline_backend_ttl",ao="pairing_deadline_cli_ceiling";async function lo(e,t={}){let n=new URL(Zi,e).toString(),r={credential_mode:"agent_key"};t.scopes!==void 0&&(r.scopes=t.scopes),t.device_label!==void 0&&(r.device_label=t.device_label);let i=JSON.stringify(r),o=Pe(xe(r),e),s=Date.now()+Et,l;try{l=await Zn(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i},Et)}catch(p){throw Xn(n,p,"init",Et)}if(await de(l),l.status===429)throw new u("rate_limited","Device-pairing init was rate-limited.",{status:429});if(await bt(l),l.status!==200){let p=await De(l,s,n,"init");throw await de(l,p),St(l.status,p),new u(l.status>=500?"backend.internal":"input.invalid",`Device-pairing init failed: HTTP ${l.status}`,{status:l.status,body:ue(p)})}let c=po(await De(l,s,n,"init")).data??{};for(let p of["polling_token","verification_code","verification_url"])if(typeof c[p]!="string"||c[p].length===0)throw new u("backend.internal",`Device-pairing init response missing required field: ${p}`);if(typeof c.expires_at!="number"||c.expires_at<=0)throw new u("backend.internal","Device-pairing init response missing or invalid expires_at");let h=typeof c.poll_interval=="number"&&c.poll_interval>0?c.poll_interval:2;return{polling_token:c.polling_token,verification_code:c.verification_code,verification_url:c.verification_url,expires_at:c.expires_at,poll_interval:h}}async function co(e,t,n=At){let r=new URL(Qi,e).toString(),i={polling_token:t},o=JSON.stringify(i),s=Pe(xe(i),e),l=Number.isFinite(n)&&n>0?Math.max(1,Math.min(At,Math.floor(n))):At,d=Date.now()+l,c;try{c=await Zn(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s},body:o},l)}catch(C){throw Xn(r,C,"poll",l)}if(await de(c),c.status===429)throw new u("rate_limited","Device-pairing poll was rate-limited.",{status:429});if(await bt(c),c.status!==200){let C=await De(c,d,r,"poll");await de(c,C),St(c.status,C);let K=ho(C);if(K===7510)throw Vn({backendCode:K,status:c.status,reason:io});if(K===7511){let $t=fo(c.headers);throw new u("auth.no_token","The backend no longer recognizes this pairing session, so no credential could be collected. Nothing was stored locally. Re-run `allscale device-login` to get a new verification code. If you already approved this pairing in the browser, it may have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard.",{status:c.status,backend_code:K,reason:zn,...$t===null?{}:{server_now:$t}})}throw K===7530?new u("input.invalid","None of the approved scopes can be granted to this account, so no key was issued. Re-run `allscale device-login` and approve different scopes.",{status:c.status,backend_code:K}):new u(c.status>=500?"backend.internal":"input.invalid",`Device-pairing poll failed: HTTP ${c.status}`,{status:c.status,body:ue(C)})}let h=await De(c,d,r,"poll");if(h.trim().length===0)throw new u("backend.internal","Device-pairing poll returned an empty HTTP 200 response.",{status:200,reason:Kn});let p;try{p=JSON.parse(h)}catch{throw kt()}if(p===null||typeof p!="object"||Array.isArray(p))throw kt();let g=p,S=g.data?.status;if(S==="pending")return{status:"pending"};if(S!=="approved")throw kt();let y=Un(g.data?.user_type)??"business",f=g.data?.scopes,m=Array.isArray(f)&&f.every(C=>typeof C=="string")?f:void 0,_r=m&&m.length>0?{scopes:m}:{},Ke=g.data?.agent_key;if(typeof Ke!="string"||Ke.length===0)throw new u("backend.internal","Requested a scoped agent key, but the backend approved a legacy full-permission cookie session \u2014 it may not support scoped keys yet, or a rolling deploy may be in progress. Refusing to store the broader credential. The one-shot approval was consumed, so do not start a new pairing blindly; review your active CLI keys in the AllScale web dashboard first, before re-running `allscale device-login`.",{status:200,outcome_ambiguous:!0,reason:ro,expected_credential:"agent_key"});let Ye=g.data?.agent_key_expires_at,je=g.data?.business_id,yr=typeof je=="string"&&je.length>0?{business_id:je}:{},Dt=Fn(g.data?.user_email),wr=Dt===void 0?{}:{user_email:Dt};return{status:"approved",user_type:y,credential:"agent_key",tokens:{access_token:"",refresh_token:"",agent_key:Ke,...typeof Ye=="number"&&Ye>0?{agent_key_expires_at:Ye}:{},user_type:y,api_base:e,..._r,...yr,...wr}}}async function Jn(e,t){let n=await lo(e,{scopes:t.scopes,device_label:t.device_label}),r=t._now??(()=>Math.floor(Date.now()/1e3)),i=typeof t._maxWallSeconds=="number"&&t._maxWallSeconds>0?t._maxWallSeconds:Gn,o=Math.min(n.expires_at,r()+i),s=o>=n.expires_at;await t.onInit(n,{pollingDeadlineAt:o});let l=t._sleep??(S=>new Promise(y=>{setTimeout(y,S)})),d=Math.max(eo,n.poll_interval*1e3),c=0,h=d,p=0,g;for(;;){let S=(o-r())*1e3;if(S<=0)throw Mn(g,p,s);await l(Math.min(h,S));let y=(o-r())*1e3;if(y<=0)throw Mn(g,p,s);c+=1;let f;try{f=await co(e,n.polling_token,y)}catch(m){if(g!==void 0&&m instanceof u&&m.code==="auth.no_token")throw Lt(g,p,"invalid_polling_token_after_transient_failure");if(m instanceof u&&m.code==="auth.no_token"&&m.details?.reason===zn&&typeof m.details.server_now=="number"&&m.details.server_now>=n.expires_at)throw Vn({backendCode:7511,...typeof m.details.status=="number"?{status:m.details.status}:{},reason:oo});if(!uo(m))throw m;if(p+=1,g=m,p>to)throw Lt(m,p,"transient_retry_budget_exhausted");h=Math.min(no,d*2**p);continue}if(f.status==="approved")return{...f,verification_code:n.verification_code};p=0,g=void 0,h=d,t.onPending?.(c)}}function Xn(e,t,n,r){return t instanceof Error&&t.name==="AbortError"?new u("transport.timeout",`Device-pairing ${n} against ${e} timed out after ${r}ms.`,{timeout_ms:r,stage:n,reason:n==="poll"?qn:"init_request_timeout"}):new u("transport.network",`Network error during device-pairing ${n} against ${e}.`,{stage:n,reason:n==="poll"?jn:"init_fetch_failure"})}function uo(e){if(!(e instanceof u))return!1;if(e.code==="transport.network")return e.details?.stage==="poll"&&(e.details.reason===jn||e.details.reason===Hn);if(e.code==="transport.timeout")return e.details?.stage==="poll"&&(e.details.reason===qn||e.details.reason===Wn);if(e.code!=="backend.internal")return!1;let t=e.details?.status;return typeof t=="number"&&t>=500&&t<=599||e.details?.reason===Kn||e.details?.reason===Yn}function Vn(e){return new u("auth.device_pairing_timeout","The device-pairing approval window closed before the browser confirmed, so no credential was issued and nothing was written to this machine. Re-run `allscale device-login` to get a new verification code. If you approved in the browser just as the window closed, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard.",{reason:e.reason,...e.status===void 0?{}:{status:e.status},...e.backendCode===void 0?{}:{backend_code:e.backendCode}})}function kt(){return new u("backend.internal","Device-pairing poll returned a malformed or unexpected HTTP 200 response.",{status:200,reason:Yn})}function Mn(e,t,n){return e!==void 0?Lt(e,t,"pairing_deadline_elapsed_after_transient_failure"):new u("auth.device_pairing_timeout",`Device-pairing timed out before the browser confirmed \u2014 the pairing window closed, or the CLI reached its ${Gn/60}-minute polling ceiling. Nothing was stored locally. If you approved in the browser after seeing this, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard. Then re-run \`allscale device-login\`.`,{reason:n?so:ao})}function Lt(e,t,n){let r=e.details?.status;return new u("backend.internal","Device-pairing result is ambiguous: a poll response was lost after the browser may have approved the one-shot exchange. A credential may have been issued without reaching this CLI. Do not assume a blind retry is safe; check the browser result, and review your active CLI keys in the AllScale web dashboard, before starting a new pairing.",{outcome_ambiguous:!0,reason:n,transient_failures:t,last_transient_error_code:e.code,...typeof r=="number"?{last_http_status:r}:{}})}async function De(e,t,n,r){let i=Math.max(1,t-Date.now());try{return await wt(e,yt,{timeoutMs:i})}catch(o){throw o instanceof u?o:o instanceof V?new u("transport.timeout",`Device-pairing ${r} response body timed out after ${o.timeoutMs}ms.`,{status:o.status,timeout_ms:o.timeoutMs,stage:r,reason:r==="poll"?Wn:"init_body_timeout"}):new u("transport.network",`Network error while reading the device-pairing ${r} response body from ${n}.`,{status:e.status,stage:r,reason:r==="poll"?Hn:"init_body_failure"})}}async function Zn(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n);i.unref?.();try{return await fetch(e,{...t,redirect:"manual",signal:r.signal})}finally{clearTimeout(i)}}function po(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function fo(e){let t=e.get("date");if(t===null)return null;let n=Date.parse(t);return Number.isNaN(n)?null:Math.floor(n/1e3)}function ho(e){if(e)try{let t=JSON.parse(e);if(typeof t.code=="number")return t.code}catch{}}var dr=A(require("path"));var It=require("crypto"),a=A(require("fs")),b=A(require("path"));var $e=1024*1024,go=5e3,mo=20,_o=3e4,vt=4096,yo=new Int32Array(new SharedArrayBuffer(4)),pe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ue(e){return e instanceof pe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},wo=null;function U(){return new u("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 Fe(){return(wo??process.platform)!=="win32"}function sr(){if(!Fe())throw U()}function ar(e){try{return a.default.lstatSync(e),!1}catch(t){if(!w(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(b.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(w(t,"ENOENT"))return!0;throw t}}function w(e,t){return typeof e=="object"&&e!==null&&e.code===t}function fe(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function he(e,t){return e.dev===t.dev&&e.ino===t.ino}function bo(e){Atomics.wait(yo,0,0,e)}function lr(e){try{return process.kill(e,0),!0}catch(t){return!w(t,"ESRCH")}}function So(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qn(e,t){let n=b.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&w(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!he(o,s))throw new Error("credential-store parent changed while it was being inspected");fe(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&b.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),l=a.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function R(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&w(o,"ENOENT")?new k:o}if(!he(n,i))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new pe;if(fe(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Eo(e,t){if(t.size>$e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc($e+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>$e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function er(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(w(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(w(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=R(e,t,n);return Eo(t,r)}finally{t!==null&&a.default.closeSync(t)}}function tr(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(w(i,"ENOENT")&&ar(e))return;throw i}let n=a.default.fstatSync(t),r=R(e,t,n);F(e,r)}finally{t!==null&&a.default.closeSync(t)}ur(b.dirname(e))}function Ao(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(w(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 pe;fe(t,"credential-store replacement target")}function ko(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(w(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function cr(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 ur(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 Lo(e,t){let n=Buffer.from(t,"utf8");if(n.length>$e)throw new Error("credential-store file exceeds the maximum supported size");let r=b.dirname(e),i=b.basename(e),o=null,s=null,l=!1;try{let d=ko(r,i);o=d.fd,s=d.tempPath;let c=a.default.fstatSync(o);if((R(s,o,c).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");cr(o,n),a.default.fsyncSync(o),R(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ao(e),a.default.renameSync(s,e),l=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!l&&s!==null)try{a.default.unlinkSync(s)}catch{}}ur(r)}function vo(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function To(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function Io(e,t){if(t.size>vt)return null;let n=Buffer.alloc(vt+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>vt)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function F(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!he(n,t))throw new Error("credential-store lock changed while it was being inspected");fe(n,"credential-store lock"),a.default.unlinkSync(e)}function nr(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(d){if(w(d,"ENOENT"))try{let c=a.default.lstatSync(e);throw c.isSymbolicLink()||!c.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(c){if(w(c,"ENOENT"))return{state:"absent"};throw c}throw d}let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Io(n,i);return{state:(o?.target===t&&o?!lr(o.pid):Date.now()-i.mtimeMs>=_o)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Oo(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let l=a.default.fstatSync(s),d=R(i,s,l,{allowMultipleLinks:!0});return cr(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:d}}catch(l){if(w(l,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw l}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ro(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 w(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!he(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function rr(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(w(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(w(r,"ENOENT"))return!1;throw r}throw n}return R(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Co(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(w(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=R(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{F(e,n)}catch{}throw a.default.closeSync(t),r}}function $(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");bo(mo)}function ir(e){let t=b.dirname(e),n=b.basename(e),r=vo(e),i=To(e),o=Oo(t,n),s=Date.now()+go,l=!1,d=!1,c=null,h;try{for(;c===null;)try{if(rr(i)){$(s,!0);continue}a.default.linkSync(o.claimPath,r),d=!0,c=Ro(r,o.stats),l=!0}catch(p){if(d&&!l){try{F(r,o.stats)}catch{}d=!1}if(p instanceof k){$(s,!1);continue}if(!w(p,"EEXIST"))throw p;let g;try{g=nr(r,n)}catch(y){if(y instanceof k){$(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=Co(i)}catch(f){if(f instanceof k){$(s,!1);continue}throw f}if(y!==null){try{let f;try{f=nr(r,n)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}f.state==="stale"&&F(r,f.stats)}finally{Tt(y)}continue}}let S;try{S=rr(i)}catch(y){if(y instanceof k){$(s,!1);continue}throw y}$(s,S)}}catch(p){h=p}try{F(o.claimPath,o.stats)}catch(p){!w(p,"ENOENT")&&!l&&h===void 0&&(h=p)}if(h!==void 0)throw h;if(c===null)throw new Error("credential-store lock acquisition failed");return c}function Tt(e){try{F(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function No(e,t){let n=So(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function or(e){let t=b.dirname(e),n=b.basename(e);for(let r of a.default.readdirSync(t)){let i=No(r,n);if(i===null||lr(i))continue;let o=b.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(c){if(w(c,"ENOENT")||w(c,"ELOOP"))continue;throw c}let l=a.default.fstatSync(s),d=a.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!he(l,d))continue;try{fe(l,"credential-store orphan")}catch{continue}F(o,l)}catch(l){if(!w(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function ge(e,t,n){if(!Fe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw U();if(!Qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw U()}});let s=ir(e);try{return or(e),n({read:()=>er(e),remove:()=>tr(e),write:()=>{throw U()}})}finally{Tt(s)}}if(!t.createParent){let o=!1;try{o=ar(e)}catch{throw U()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw U()}})}throw U()}if(!Qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=ir(e);try{return or(e),n({read:()=>er(e),remove:()=>tr(e),write:o=>Lo(e,o)})}finally{Tt(i)}}var Ot="allscale-cli";function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pr(e){return Pt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(e){return new u("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 Rt(){return new u("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 Me(){return new u("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var M,Ct=!1;function Po(){return an()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function xo(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;let i=r.trim().toLowerCase();return i===""||i==="y"||i==="yes"}finally{n&&process.removeListener("SIGINT",n),t.close()}}var Nn=A(require("crypto")),Pn=A(require("fs")),xn=A(require("path"));var Pi="key-id",xi="x-allscale-cli-version",mt="cli-1",Bi="aScaLe_cli_obf_v1",Di="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function $i(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var Ui=$i(Di,Bi),Fi=`Bearer ${Ui}`;function Bn(e,t){let n=Je(e);if(n!==null)return t.find(r=>Je(r.base)===n)}function Mi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=Q();if(t.length>0){let r=Bn(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(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 Gi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=Q();if(t.length>0){let r=e!==void 0?Bn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():mt}if(!x(t[0].base))return mt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():mt}function Ki(){return"1.0.4"}function Yi(){return new u("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 Pe(e,t){let n=Mi(t);if(!n)throw Yi();let r=Gi(t),i=Math.floor(Date.now()/1e3).toString(),o=Nn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[xi]:Ki()};return r.length>0&&(s[Pi]=r),s}function xe(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ji=500,qi=8,Dn=100;function _t(e,t=0){if(t>qi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Dn),r=n.map(i=>_t(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,Dn))n[r]=we(r)?"<redacted>":_t(i,t+1);return n}return e}function Hi(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 ue(e,t=ji){let n=Hi(e),r=n===void 0?ye(e):JSON.stringify(_t(n));return be(r,t)}var yt=256*1024,Be=class extends u{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},V=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 wt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,d,c=n.timeoutMs,h=c===void 0?void 0:new Promise((p,g)=>{d=setTimeout(()=>{g(new V(e.status,c))},c),d.unref?.()});try{for(;;){let p=o.read(),{done:g,value:S}=h?await Promise.race([p,h]):await p;if(g)break;if(l+=S.byteLength,l>t)throw o.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);s.push(Buffer.from(S))}}catch(p){throw p instanceof V&&o.cancel(p).catch(()=>{}),p}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var Ra=32*1024*1024,Ca=4*1024*1024;function Wi(e,t){if(!(e<300||e>=400))throw new u("transport.network",`API returned HTTP ${e} (a redirect) for ${tn(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 bt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Wi(e.status,e.url)}}var $n="--dns-result-order=ipv4first";async function de(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),d=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||l)&&(i||t!==void 0&&d)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let h=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new u("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=${$n} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...h?{cf_ray:h}:{},ipv4_workaround:`NODE_OPTIONS=${$n}`})}var zi=2014;function Ji(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 Xi(e){return Ji(e,zi)}function St(e,t){if(!(e>=200&&e<300)&&Xi(t))throw new u("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"?ue(t):t})}var Vi={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Un(e){if(typeof e=="string")return e;if(typeof e=="number")return Vi[e]??`user_type_${e}`}function Fn(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var Zi="/api/public/auth/cli_authorize_init",Qi="/api/public/auth/cli_authorize_poll",Et=1e4,At=1e4,eo=1e3,to=3,no=3e4,Gn=900,Kn="empty_response",Yn="invalid_response",jn="poll_fetch_failure",qn="poll_request_timeout",Hn="poll_body_failure",Wn="poll_body_timeout",ro="approved_credential_mismatch",io="pairing_expired_backend_ttl",zn="pairing_token_unrecognized",oo="pairing_token_unrecognized_after_window_closed",so="pairing_deadline_backend_ttl",ao="pairing_deadline_cli_ceiling";async function lo(e,t={}){let n=new URL(Zi,e).toString(),r={credential_mode:"agent_key"};t.scopes!==void 0&&(r.scopes=t.scopes),t.device_label!==void 0&&(r.device_label=t.device_label);let i=JSON.stringify(r),o=Pe(xe(r),e),s=Date.now()+Et,l;try{l=await Zn(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i},Et)}catch(p){throw Xn(n,p,"init",Et)}if(await de(l),l.status===429)throw new u("rate_limited","Device-pairing init was rate-limited.",{status:429});if(await bt(l),l.status!==200){let p=await De(l,s,n,"init");throw await de(l,p),St(l.status,p),new u(l.status>=500?"backend.internal":"input.invalid",`Device-pairing init failed: HTTP ${l.status}`,{status:l.status,body:ue(p)})}let c=po(await De(l,s,n,"init")).data??{};for(let p of["polling_token","verification_code","verification_url"])if(typeof c[p]!="string"||c[p].length===0)throw new u("backend.internal",`Device-pairing init response missing required field: ${p}`);if(typeof c.expires_at!="number"||c.expires_at<=0)throw new u("backend.internal","Device-pairing init response missing or invalid expires_at");let h=typeof c.poll_interval=="number"&&c.poll_interval>0?c.poll_interval:2;return{polling_token:c.polling_token,verification_code:c.verification_code,verification_url:c.verification_url,expires_at:c.expires_at,poll_interval:h}}async function co(e,t,n=At){let r=new URL(Qi,e).toString(),i={polling_token:t},o=JSON.stringify(i),s=Pe(xe(i),e),l=Number.isFinite(n)&&n>0?Math.max(1,Math.min(At,Math.floor(n))):At,d=Date.now()+l,c;try{c=await Zn(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s},body:o},l)}catch(C){throw Xn(r,C,"poll",l)}if(await de(c),c.status===429)throw new u("rate_limited","Device-pairing poll was rate-limited.",{status:429});if(await bt(c),c.status!==200){let C=await De(c,d,r,"poll");await de(c,C),St(c.status,C);let K=ho(C);if(K===7510)throw Vn({backendCode:K,status:c.status,reason:io});if(K===7511){let $t=fo(c.headers);throw new u("auth.no_token","The backend no longer recognizes this pairing session, so no credential could be collected. Nothing was stored locally. Re-run `allscale device-login` to get a new verification code. If you already approved this pairing in the browser, it may have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard.",{status:c.status,backend_code:K,reason:zn,...$t===null?{}:{server_now:$t}})}throw K===7530?new u("input.invalid","None of the approved scopes can be granted to this account, so no key was issued. Re-run `allscale device-login` and approve different scopes.",{status:c.status,backend_code:K}):new u(c.status>=500?"backend.internal":"input.invalid",`Device-pairing poll failed: HTTP ${c.status}`,{status:c.status,body:ue(C)})}let h=await De(c,d,r,"poll");if(h.trim().length===0)throw new u("backend.internal","Device-pairing poll returned an empty HTTP 200 response.",{status:200,reason:Kn});let p;try{p=JSON.parse(h)}catch{throw kt()}if(p===null||typeof p!="object"||Array.isArray(p))throw kt();let g=p,S=g.data?.status;if(S==="pending")return{status:"pending"};if(S!=="approved")throw kt();let y=Un(g.data?.user_type)??"business",f=g.data?.scopes,m=Array.isArray(f)&&f.every(C=>typeof C=="string")?f:void 0,_r=m&&m.length>0?{scopes:m}:{},Ke=g.data?.agent_key;if(typeof Ke!="string"||Ke.length===0)throw new u("backend.internal","Requested a scoped agent key, but the backend approved a legacy full-permission cookie session \u2014 it may not support scoped keys yet, or a rolling deploy may be in progress. Refusing to store the broader credential. The one-shot approval was consumed, so do not start a new pairing blindly; review your active CLI keys in the AllScale web dashboard first, before re-running `allscale device-login`.",{status:200,outcome_ambiguous:!0,reason:ro,expected_credential:"agent_key"});let Ye=g.data?.agent_key_expires_at,je=g.data?.business_id,yr=typeof je=="string"&&je.length>0?{business_id:je}:{},Dt=Fn(g.data?.user_email),wr=Dt===void 0?{}:{user_email:Dt};return{status:"approved",user_type:y,credential:"agent_key",tokens:{access_token:"",refresh_token:"",agent_key:Ke,...typeof Ye=="number"&&Ye>0?{agent_key_expires_at:Ye}:{},user_type:y,api_base:e,..._r,...yr,...wr}}}async function Jn(e,t){let n=await lo(e,{scopes:t.scopes,device_label:t.device_label}),r=t._now??(()=>Math.floor(Date.now()/1e3)),i=typeof t._maxWallSeconds=="number"&&t._maxWallSeconds>0?t._maxWallSeconds:Gn,o=Math.min(n.expires_at,r()+i),s=o>=n.expires_at;await t.onInit(n,{pollingDeadlineAt:o});let l=t._sleep??(S=>new Promise(y=>{setTimeout(y,S)})),d=Math.max(eo,n.poll_interval*1e3),c=0,h=d,p=0,g;for(;;){let S=(o-r())*1e3;if(S<=0)throw Mn(g,p,s);await l(Math.min(h,S));let y=(o-r())*1e3;if(y<=0)throw Mn(g,p,s);c+=1;let f;try{f=await co(e,n.polling_token,y)}catch(m){if(g!==void 0&&m instanceof u&&m.code==="auth.no_token")throw Lt(g,p,"invalid_polling_token_after_transient_failure");if(m instanceof u&&m.code==="auth.no_token"&&m.details?.reason===zn&&typeof m.details.server_now=="number"&&m.details.server_now>=n.expires_at)throw Vn({backendCode:7511,...typeof m.details.status=="number"?{status:m.details.status}:{},reason:oo});if(!uo(m))throw m;if(p+=1,g=m,p>to)throw Lt(m,p,"transient_retry_budget_exhausted");h=Math.min(no,d*2**p);continue}if(f.status==="approved")return{...f,verification_code:n.verification_code};p=0,g=void 0,h=d,t.onPending?.(c)}}function Xn(e,t,n,r){return t instanceof Error&&t.name==="AbortError"?new u("transport.timeout",`Device-pairing ${n} against ${e} timed out after ${r}ms.`,{timeout_ms:r,stage:n,reason:n==="poll"?qn:"init_request_timeout"}):new u("transport.network",`Network error during device-pairing ${n} against ${e}.`,{stage:n,reason:n==="poll"?jn:"init_fetch_failure"})}function uo(e){if(!(e instanceof u))return!1;if(e.code==="transport.network")return e.details?.stage==="poll"&&(e.details.reason===jn||e.details.reason===Hn);if(e.code==="transport.timeout")return e.details?.stage==="poll"&&(e.details.reason===qn||e.details.reason===Wn);if(e.code!=="backend.internal")return!1;let t=e.details?.status;return typeof t=="number"&&t>=500&&t<=599||e.details?.reason===Kn||e.details?.reason===Yn}function Vn(e){return new u("auth.device_pairing_timeout","The device-pairing approval window closed before the browser confirmed, so no credential was issued and nothing was written to this machine. Re-run `allscale device-login` to get a new verification code. If you approved in the browser just as the window closed, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard.",{reason:e.reason,...e.status===void 0?{}:{status:e.status},...e.backendCode===void 0?{}:{backend_code:e.backendCode}})}function kt(){return new u("backend.internal","Device-pairing poll returned a malformed or unexpected HTTP 200 response.",{status:200,reason:Yn})}function Mn(e,t,n){return e!==void 0?Lt(e,t,"pairing_deadline_elapsed_after_transient_failure"):new u("auth.device_pairing_timeout",`Device-pairing timed out before the browser confirmed \u2014 the pairing window closed, or the CLI reached its ${Gn/60}-minute polling ceiling. Nothing was stored locally. If you approved in the browser after seeing this, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard. Then re-run \`allscale device-login\`.`,{reason:n?so:ao})}function Lt(e,t,n){let r=e.details?.status;return new u("backend.internal","Device-pairing result is ambiguous: a poll response was lost after the browser may have approved the one-shot exchange. A credential may have been issued without reaching this CLI. Do not assume a blind retry is safe; check the browser result, and review your active CLI keys in the AllScale web dashboard, before starting a new pairing.",{outcome_ambiguous:!0,reason:n,transient_failures:t,last_transient_error_code:e.code,...typeof r=="number"?{last_http_status:r}:{}})}async function De(e,t,n,r){let i=Math.max(1,t-Date.now());try{return await wt(e,yt,{timeoutMs:i})}catch(o){throw o instanceof u?o:o instanceof V?new u("transport.timeout",`Device-pairing ${r} response body timed out after ${o.timeoutMs}ms.`,{status:o.status,timeout_ms:o.timeoutMs,stage:r,reason:r==="poll"?Wn:"init_body_timeout"}):new u("transport.network",`Network error while reading the device-pairing ${r} response body from ${n}.`,{status:e.status,stage:r,reason:r==="poll"?Hn:"init_body_failure"})}}async function Zn(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n);i.unref?.();try{return await fetch(e,{...t,redirect:"manual",signal:r.signal})}finally{clearTimeout(i)}}function po(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function fo(e){let t=e.get("date");if(t===null)return null;let n=Date.parse(t);return Number.isNaN(n)?null:Math.floor(n/1e3)}function ho(e){if(e)try{let t=JSON.parse(e);if(typeof t.code=="number")return t.code}catch{}}var dr=A(require("path"));var It=require("crypto"),a=A(require("fs")),b=A(require("path"));var $e=1024*1024,go=5e3,mo=20,_o=3e4,vt=4096,yo=new Int32Array(new SharedArrayBuffer(4)),pe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ue(e){return e instanceof pe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},wo=null;function U(){return new u("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 Fe(){return(wo??process.platform)!=="win32"}function sr(){if(!Fe())throw U()}function ar(e){try{return a.default.lstatSync(e),!1}catch(t){if(!w(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(b.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(w(t,"ENOENT"))return!0;throw t}}function w(e,t){return typeof e=="object"&&e!==null&&e.code===t}function fe(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function he(e,t){return e.dev===t.dev&&e.ino===t.ino}function bo(e){Atomics.wait(yo,0,0,e)}function lr(e){try{return process.kill(e,0),!0}catch(t){return!w(t,"ESRCH")}}function So(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qn(e,t){let n=b.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&w(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!he(o,s))throw new Error("credential-store parent changed while it was being inspected");fe(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&b.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),l=a.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function R(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&w(o,"ENOENT")?new k:o}if(!he(n,i))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new pe;if(fe(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Eo(e,t){if(t.size>$e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc($e+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>$e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function er(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(w(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(w(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=R(e,t,n);return Eo(t,r)}finally{t!==null&&a.default.closeSync(t)}}function tr(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(w(i,"ENOENT")&&ar(e))return;throw i}let n=a.default.fstatSync(t),r=R(e,t,n);F(e,r)}finally{t!==null&&a.default.closeSync(t)}ur(b.dirname(e))}function Ao(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(w(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 pe;fe(t,"credential-store replacement target")}function ko(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(w(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function cr(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 ur(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 Lo(e,t){let n=Buffer.from(t,"utf8");if(n.length>$e)throw new Error("credential-store file exceeds the maximum supported size");let r=b.dirname(e),i=b.basename(e),o=null,s=null,l=!1;try{let d=ko(r,i);o=d.fd,s=d.tempPath;let c=a.default.fstatSync(o);if((R(s,o,c).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");cr(o,n),a.default.fsyncSync(o),R(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ao(e),a.default.renameSync(s,e),l=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!l&&s!==null)try{a.default.unlinkSync(s)}catch{}}ur(r)}function vo(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function To(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function Io(e,t){if(t.size>vt)return null;let n=Buffer.alloc(vt+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>vt)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function F(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!he(n,t))throw new Error("credential-store lock changed while it was being inspected");fe(n,"credential-store lock"),a.default.unlinkSync(e)}function nr(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(d){if(w(d,"ENOENT"))try{let c=a.default.lstatSync(e);throw c.isSymbolicLink()||!c.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(c){if(w(c,"ENOENT"))return{state:"absent"};throw c}throw d}let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Io(n,i);return{state:(o?.target===t&&o?!lr(o.pid):Date.now()-i.mtimeMs>=_o)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Oo(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let l=a.default.fstatSync(s),d=R(i,s,l,{allowMultipleLinks:!0});return cr(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:d}}catch(l){if(w(l,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw l}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ro(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 w(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!he(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function rr(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(w(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(w(r,"ENOENT"))return!1;throw r}throw n}return R(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Co(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(w(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=R(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{F(e,n)}catch{}throw a.default.closeSync(t),r}}function $(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");bo(mo)}function ir(e){let t=b.dirname(e),n=b.basename(e),r=vo(e),i=To(e),o=Oo(t,n),s=Date.now()+go,l=!1,d=!1,c=null,h;try{for(;c===null;)try{if(rr(i)){$(s,!0);continue}a.default.linkSync(o.claimPath,r),d=!0,c=Ro(r,o.stats),l=!0}catch(p){if(d&&!l){try{F(r,o.stats)}catch{}d=!1}if(p instanceof k){$(s,!1);continue}if(!w(p,"EEXIST"))throw p;let g;try{g=nr(r,n)}catch(y){if(y instanceof k){$(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=Co(i)}catch(f){if(f instanceof k){$(s,!1);continue}throw f}if(y!==null){try{let f;try{f=nr(r,n)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}f.state==="stale"&&F(r,f.stats)}finally{Tt(y)}continue}}let S;try{S=rr(i)}catch(y){if(y instanceof k){$(s,!1);continue}throw y}$(s,S)}}catch(p){h=p}try{F(o.claimPath,o.stats)}catch(p){!w(p,"ENOENT")&&!l&&h===void 0&&(h=p)}if(h!==void 0)throw h;if(c===null)throw new Error("credential-store lock acquisition failed");return c}function Tt(e){try{F(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function No(e,t){let n=So(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function or(e){let t=b.dirname(e),n=b.basename(e);for(let r of a.default.readdirSync(t)){let i=No(r,n);if(i===null||lr(i))continue;let o=b.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(c){if(w(c,"ENOENT")||w(c,"ELOOP"))continue;throw c}let l=a.default.fstatSync(s),d=a.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!he(l,d))continue;try{fe(l,"credential-store orphan")}catch{continue}F(o,l)}catch(l){if(!w(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function ge(e,t,n){if(!Fe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw U();if(!Qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw U()}});let s=ir(e);try{return or(e),n({read:()=>er(e),remove:()=>tr(e),write:()=>{throw U()}})}finally{Tt(s)}}if(!t.createParent){let o=!1;try{o=ar(e)}catch{throw U()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw U()}})}throw U()}if(!Qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=ir(e);try{return or(e),n({read:()=>er(e),remove:()=>tr(e),write:o=>Lo(e,o)})}finally{Tt(i)}}var Ot="allscale-cli";function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pr(e){return Pt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(e){return new u("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 Rt(){return new u("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 Me(){return new u("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var M,Ct=!1;function Po(){return an()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function xo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
17
17
  `,1)[0]==="Cannot find module 'keytar'"}function Bo(){if(M!==void 0)return M;if(Po())return Ct=!1,M=null,M;try{M=require("keytar"),Ct=!1}catch(e){Ct=!xo(e),M=null}return M}var Do="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function fr(){let e=Fe()?"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 u("storage.unavailable",`${Do} `+e+" Never silently downgrade in production.")}async function Nt(e){try{return await e()}catch{throw fr()}}var xt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Nt(()=>this.keytar.getPassword(Ot,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!pr(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Nt(()=>this.keytar.setPassword(Ot,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Nt(()=>this.keytar.deletePassword(Ot,t))}},$o="credentials.json",Bt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??dr.join(Te(),$o)}read(t){let n;try{n=t.read()}catch(i){throw Ue(i)?Rt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!Pt(r)||!Pt(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ue(r)?Rt():Me()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!pr(r))throw G("plaintext file");return r}}async get(t){try{return ge(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof u?n:G("plaintext file")}}async set(t,n){try{ge(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof u?r:Me()}}async delete(t){try{ge(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 u?n:Me()}}async clearProfile(t){try{return ge(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 u?n:Ue(n)?Rt():Me()}}};function hr(e){if(e.insecureStorage)return sr(),new Bt(e.insecureFilePath);let t=Bo();if(t)return new xt(t);throw fr()}async function gr(e,t){await e.get(t)}async function mr(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof u?r.message:E(String(r)),o=n.agent_key?"An agent key was already minted for this account but could not be stored, so it is now orphaned: it cannot be listed or revoked from the CLI (key management is control-plane and rejects agent-key sessions). Remove it from the web dashboard.":"The session credential could not be stored, so nothing was persisted \u2014 no key record was created on the account. Re-run the command to authenticate again once storage is available.";throw new u(r instanceof u?r.code:"storage.unavailable",`${i} ${o}`,r instanceof u?r.details:void 0)}}var Ge=class e extends ae{static description="Log in via browser-confirmed device pairing. Use an existing web session or sign in there with Passkey or Email (enter the Email OTP on the webpage), then approve the CLI. The backend mints a scoped agent key \u2014 the credential issued by the current CLI login flows; no web sign-in secret is entered in the terminal.";static examples=["$ allscale device-login","$ allscale device-login --device-label tom-mbp-2026","$ allscale device-login --device-label CI-runner --scopes invoice:read_only --scopes claim_link:all"];static flags={"device-label":N.Flags.string({description:"Human-readable label shown in the browser approval UI so the user can confirm they're authorizing the right device."}),scopes:N.Flags.string({description:"Requested scopes for the eventual agent key, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs the approval screen can grant: "+yn(X)+". The final set is chosen \u2014 and can be overridden \u2014 on that screen, and is checked by the backend on each request. With no requested scopes, every category starts OFF and the user must select at least one. Passing --scopes preselects each exact matching tier the screen can grant. `wallet list` needs `wallet:read_only`. `invoice pay` needs `invoice:all` AND `wallet:all` \u2014 its withdrawal registration rides the same broker op as `wallet send` (backend gates the op, not the verb), and the write tier covers its payer-address read via the implication \u2014 so request both (`--scopes invoice:all --scopes wallet:all`) to preselect both write tiers, or select both Allow-changes switches before authorizing. `wallet send` requires `wallet:all` the same way; every transfer still requires your in-browser confirmation. "+An(X,{blocksUngrantableLocally:!0})+"Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any pairing session is registered \u2014 the same check, and the same exit code, as `otp-login --scopes`. A recognised scope the screen has no toggle for is also rejected locally, with the remediation that actually works: otp-login for operational scopes (or `--allow-unrenderable-scopes` when your web app is newer than this CLI's catalog), nothing for payroll/admin:* \u2014 the approval page refuses the whole authorization when even one requested scope is unrenderable, so deferring the answer to the browser would strand you after a pairing session already exists. An explicitly requested `cli_op:*` is not an error: the backend appends it to every pairing-minted key, so it is omitted from the request with a note. If another requested scope remains, the resulting key is identical; if it was the only one, the approval screen starts every category OFF and requires the user to choose at least one. Only a scope the screen renders and the user declines is reported after the key is minted.",multiple:!0}),"no-browser":N.Flags.boolean({description:"Skip launching the browser; print the verification URL only. Open it in a browser to sign in with Passkey or Email and approve (the Email OTP stays on the webpage). Useful for CI or ssh sessions.",default:!1}),"allow-unrenderable-scopes":N.Flags.boolean({description:"Forward a scope to the approval screen even when this CLI's catalog says the screen has no toggle for it. Escape hatch for a stale catalog: the screen-grantable list above is a MIRROR of the web app's approval screen and can lag a frontend release, and without this flag a lagging mirror makes such a scope impossible to request until a CLI update ships. The screen stays the authority \u2014 if it truly cannot render the scope it refuses the WHOLE authorization after the pairing session exists (the stranding the local check normally prevents), so use this only when you have reason to believe the web app is newer than this CLI. Scopes no login path can mint (payroll/admin:*) are still rejected locally; this flag does not touch them.",default:!1}),yes:N.Flags.boolean({char:"y",description:"Skip the interactive confirmation and start the pairing immediately. Only a BARE invocation is ever prompted, so passing any flag already skips it; use this to say so explicitly. Automation that allocates a pty for stdin/stdout/stderr and runs the command bare is indistinguishable from a human \u2014 that is the case this flag exists for.",default:!1}),...ae.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);kn(t.scopes),Ln(t.scopes,{allowUnrenderable:t["allow-unrenderable-scopes"]});let n=this.resolveContext(t),r=hr({insecureStorage:n.insecureStorage});if(this.argv.length===0&&!t.yes&&!Le(this.jsonEnabled())&&process.stderr.isTTY===!0&&(process.stderr.write(`\`allscale device-login\` will now:
18
18
  - register a new pairing session with ${n.apiBase}
19
19
  - open your browser at the approval page