@allscale/cli 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,39 +1,40 @@
1
- "use strict";var cr=Object.create;var fe=Object.defineProperty;var ur=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var fr=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty;var gr=(e,t)=>{for(var n in t)fe(e,n,{get:t[n],enumerable:!0})},Dt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of dr(t))!pr.call(e,i)&&i!==n&&fe(e,i,{get:()=>t[i],enumerable:!(r=ur(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?cr(fr(e)):{},Dt(t||!e||!e.__esModule?fe(n,"default",{value:e,enumerable:!0}):n,e)),hr=e=>Dt(fe({},"__esModule",{value:!0}),e);var mo={};gr(mo,{APPROVAL_SCREEN_SCOPES:()=>oe,UNGRANTABLE_CATEGORIES:()=>Re,approvalScreenCanGrant:()=>gt,default:()=>Ge,isWellFormedScope:()=>Pe,scopeCategory:()=>j,scopeSatisfies:()=>Ce});module.exports=hr(mo);var R=require("@oclif/core");var Ut="public",$t="https://app.allscale.io";var Ft=["https://app.allscale.io"];var je="Override the API base URL (public builds accept only https://app.allscale.io)";var We="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Mt(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Gt(e){return Mt(e)!==null}function pe(e){let t=Mt(e);return t!==null&&Ft.includes(t.origin)}function Je(e){return pe(e)}function z(){return"".trim()||void 0}function X(){return"public"}function N(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Xe(e){try{return new URL(e).origin}catch{return null}}function V(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return ze()}function ze(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:l,keyId:d}=o;if(typeof s!="string"||s.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let u=typeof d=="string"?d.trim():"";i.push({base:s.trim(),key:l,keyId:u.length>0?u:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var mr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},_r=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Qe(e){return(typeof e=="string"?e:String(e??"")).replace(_r,"")}var yr=64;function Ve(e,t=new Map,n=0){if(typeof e=="string")return Qe(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=yr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let l of e)s.push(Ve(l,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,l]of Object.entries(e))Object.defineProperty(o,s,{value:Ve(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(Qe(n)),this.code=t,this.details=r&&Ve(r),this.name="AllscaleError"}get exitCode(){return mr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Kt(e){if(e instanceof c)return e;if(e instanceof Error){if(Er(e)){let t=Ar(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var wr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Sr=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Er(e){if(br(e))return!0;let t=e.name??"";return wr.has(t)?t==="CLIError"?Ze(e,"parse")||Yt(e.message):!0:Yt(e.message)}function br(e){if(!Ze(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ze(e,"parse")}function Yt(e){return e?Qe(e).split(`
2
- `).some(t=>Sr.some(n=>n.test(t.trim()))):!1}function Ze(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Ar(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ht(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var h=A(require("fs")),Se=A(require("path")),Vt=A(require("crypto"));var Lr="...<truncated>",kr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Tr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,it=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,et=String.raw`(?:proxy[_-]?)?authorization`,Ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${et}"|'${et}'|${et})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${it}`,"gi"),Or=/\b(https?:\/\/)[^\s/?#]+@/gi,vr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Rr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,jt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,qt=jt(vr),Cr=jt(Rr),Pr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${qt}"|'${qt}'|${Cr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${it}`,"gi"),tt=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,Nr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${tt}"|'${tt}'|${tt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${it}`,"g");function ge(e){return e.replace(Or,"$1<redacted>@").replace(kr,"<redacted-jwt>").replace(Ir,"$1$2$3<redacted>").replace(Pr,"$1$2<redacted>").replace(Nr,"$1$2<redacted>").replace(Tr,"Bearer <redacted>")}var xr=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function he(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return xr.test(t)}function Wt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function me(e,t,n=Lr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",d=0;for(let u of n){let p=Buffer.byteLength(u,"utf8");if(d+p>t)break;l+=u,d+=p}return l}let i=t-r,o="",s=0;for(let l of e){let d=Buffer.byteLength(l,"utf8");if(s+d>i)break;o+=l,s+=d}return`${o}${n}`}function b(e,t=16384){return me(Wt(ge(e)),t)}var nt=100,Br=8,Dr=8*1024;function _e(){return{remaining:Dr}}function rt(e,t){let n=Math.min(16384,t.remaining),r=me(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function M(e,t,n=0,r={}){if(n>Br)return rt("<truncated>",t);if(typeof e=="string"){let i=ge(e);return rt(r.escapeControls?Wt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,nt),o=i.map(s=>M(s,t,n+1,r));return e.length>i.length&&o.push(rt(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,l]of o.slice(0,nt))i[s]=M(l,t,n+1,r);return o.length>nt&&(i.output_truncated=!0),i}return e}var ye=require("process");var we=!1;function ot(e){we=e}function zt(){return we}function Z(e){we||ye.stderr.write(e)}var Jt="1";function O(e,t){if(we){let n={...e};delete n.version;let r=_e(),i={event:n.event,...n},o=M(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Jt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Jt,event:o.event,output_truncated:!0})),ye.stderr.write(`${s}
4
- `)}else ye.stderr.write(t)}var Xt="2",Y=null,k=null,K=!1,Q=!1;function Ur(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=Vt.randomBytes(4).toString("hex");return Se.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var st=64*1024*1024,$r=null;function at(e={}){if(e.quiet&&(Q=!0),K)return;let t=Ur();if(!t)return;Y=null;let n=null;try{if(($r??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=Se.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let d=h.statSync(r),u=d.mode&511;if(!d.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let i=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|i,384);let o=h.fstatSync(n),s=h.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let l=o.mode&511;if((l&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${l.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}Q||O({event:"sidecar_disabled",reason:"open_failed",detail:b(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${b(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}Y=t,k=n,K=!0}var Fr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Mr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fr.some(n=>n.test(t))}function Zt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=Gr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Mr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Gr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Yr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Zt(e.url)}:e}function Kr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=M(i,_e()),s=JSON.stringify({version:Xt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Xt,timestamp:t,type:r,output_truncated:!0})),s}function v(e){if(!K||!Y||k===null)return;let t=Yr(e),n=Kr(t);try{if(h.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>st){K=!1;try{h.closeSync(k)}catch{}k=null,Q||O({event:"sidecar_disabled",reason:"size_limit",...Y===null?{}:{path:b(Y)},max_bytes:st},`${b(`[allscale] sidecar exceeded ${st} bytes; disabling it for the rest of this run. Rotate or remove ${Y}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}h.appendFileSync(k,`${n}
7
- `)}catch(r){if(K=!1,k!==null){try{h.closeSync(k)}catch{}k=null}try{Q||O({event:"sidecar_disabled",reason:"write_failed",detail:b(r.message)},`${b(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var Qt=Zt;function en(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function ee(){if(Q=!1,K=!1,k!==null){try{h.closeSync(k)}catch{}k=null}}function Ee(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||en()||!t}var te=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Hr=new Set(Array.from(te).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),qr=Array.from(te).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),jr=new Set(["--otp-stdin","--password-stdin"]);function lt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(te.has(s)){t.push(`${s}=<redacted>`);continue}}}if(te.has(r)){t.push(r),n+1<e.length&&(te.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(Hr.has(o)){t.push(`${o}<redacted>`);continue}}let i=jr.has(r)?void 0:qr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function tn(e){v({type:"error",code:e.code,message:b(e.message)}),v({type:"command-end",ok:!1,exitCode:e.exitCode}),ee()}var ne=z()??$t,q={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function be(e){return Gt(e)?new URL(e).origin:null}function P(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function nn(){let e=process.env[q.TOKEN]?.trim();return e&&e.length>0?e:void 0}function ct(){let e=process.env[q.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Ae(){let e=process.env[q.API_BASE]?.trim();return e&&e.length>0?e:void 0}function rn(){let e=process.env[q.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function on(){let e=process.env[q.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function sn(){let e=process.env[q.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function an(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(z()===void 0&&ne!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
1
+ "use strict";var _r=Object.create;var he=Object.defineProperty;var yr=Object.getOwnPropertyDescriptor;var wr=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,Sr=Object.prototype.hasOwnProperty;var Er=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:!0})},Dt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of wr(t))!Sr.call(e,i)&&i!==n&&he(e,i,{get:()=>t[i],enumerable:!(r=yr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?_r(br(e)):{},Dt(t||!e||!e.__esModule?he(n,"default",{value:e,enumerable:!0}):n,e)),Ar=e=>Dt(he({},"__esModule",{value:!0}),e);var Uo={};Er(Uo,{APPROVAL_SCREEN_SCOPES:()=>se,UNGRANTABLE_CATEGORIES:()=>Re,approvalScreenCanGrant:()=>dt,default:()=>Me,isWellFormedScope:()=>Ce,scopeCategory:()=>J,scopeSatisfies:()=>ae});module.exports=Ar(Uo);var O=require("@oclif/core");var $t="public",Ut="https://app.allscale.io";var Ft=["https://app.allscale.io"];var qe="Override the API base URL (public builds accept only https://app.allscale.io)";var je="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Mt(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Gt(e){return Mt(e)!==null}function ge(e){let t=Mt(e);return t!==null&&Ft.includes(t.origin)}function He(e){return ge(e)}function V(){return"".trim()||void 0}function G(){return"public"}function P(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Je(e){try{return new URL(e).origin}catch{return null}}function X(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return We()}function We(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:l,keyId:d}=o;if(typeof s!="string"||s.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let u=typeof d=="string"?d.trim():"";i.push({base:s.trim(),key:l,keyId:u.length>0?u:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var kr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},Lr=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Xe(e){return(typeof e=="string"?e:String(e??"")).replace(Lr,"")}var Tr=64;function ze(e,t=new Map,n=0){if(typeof e=="string")return Xe(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Tr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let l of e)s.push(ze(l,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,l]of Object.entries(e))Object.defineProperty(o,s,{value:ze(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(Xe(n)),this.code=t,this.details=r&&ze(r),this.name="AllscaleError"}get exitCode(){return kr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Yt(e){if(e instanceof c)return e;if(e instanceof Error){if(Or(e)){let t=Cr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var Ir=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),vr=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Or(e){if(Rr(e))return!0;let t=e.name??"";return Ir.has(t)?t==="CLIError"?Ve(e,"parse")||Kt(e.message):!0:Kt(e.message)}function Rr(e){if(!Ve(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ve(e,"parse")}function Kt(e){return e?Xe(e).split(`
2
+ `).some(t=>vr.some(n=>n.test(t.trim()))):!1}function Ve(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Cr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function qt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var _=A(require("fs")),Ee=A(require("path")),Xt=A(require("crypto"));var Nr="...<truncated>",Pr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,xr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,nt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ze=String.raw`(?:proxy[_-]?)?authorization`,Br=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ze}"|'${Ze}'|${Ze})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${nt}`,"gi"),Dr=/\b(https?:\/\/)[^\s/?#]+@/gi,$r=String.raw`(?:[A-Za-z0-9]+[_-])*`,Ur=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Ht=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,jt=Ht($r),Fr=Ht(Ur),Mr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${jt}"|'${jt}'|${Fr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${nt}`,"gi"),Qe=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,Gr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Qe}"|'${Qe}'|${Qe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${nt}`,"g");function me(e){return e.replace(Dr,"$1<redacted>@").replace(Pr,"<redacted-jwt>").replace(Br,"$1$2$3<redacted>").replace(Mr,"$1$2<redacted>").replace(Gr,"$1$2<redacted>").replace(xr,"Bearer <redacted>")}var Kr=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function _e(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Kr.test(t)}function Wt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function ye(e,t,n=Nr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",d=0;for(let u of n){let h=Buffer.byteLength(u,"utf8");if(d+h>t)break;l+=u,d+=h}return l}let i=t-r,o="",s=0;for(let l of e){let d=Buffer.byteLength(l,"utf8");if(s+d>i)break;o+=l,s+=d}return`${o}${n}`}function E(e,t=16384){return ye(Wt(me(e)),t)}var et=100,Yr=8,qr=8*1024;function we(){return{remaining:qr}}function tt(e,t){let n=Math.min(16384,t.remaining),r=ye(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function K(e,t,n=0,r={}){if(n>Yr)return tt("<truncated>",t);if(typeof e=="string"){let i=me(e);return tt(r.escapeControls?Wt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,et),o=i.map(s=>K(s,t,n+1,r));return e.length>i.length&&o.push(tt(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,l]of o.slice(0,et))i[s]=K(l,t,n+1,r);return o.length>et&&(i.output_truncated=!0),i}return e}var be=require("process");var Se=!1;function rt(e){Se=e}function zt(){return Se}function Z(e){Se||be.stderr.write(e)}var Jt="1";function T(e,t){if(Se){let n={...e};delete n.version;let r=we(),i={event:n.event,...n},o=K(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Jt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Jt,event:o.event,output_truncated:!0})),be.stderr.write(`${s}
4
+ `)}else be.stderr.write(t)}var Vt="2",q=null,L=null,j=!1,Q=!1;function jr(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=Xt.randomBytes(4).toString("hex");return Ee.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var it=64*1024*1024,Hr=null;function ot(e={}){if(e.quiet&&(Q=!0),j)return;let t=jr();if(!t)return;q=null;let n=null;try{if((Hr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=Ee.dirname(t);if(_.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let d=_.statSync(r),u=d.mode&511;if(!d.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let i=_.constants.O_NOFOLLOW??0;n=_.openSync(t,_.constants.O_APPEND|_.constants.O_CREAT|_.constants.O_WRONLY|(_.constants.O_NONBLOCK??0)|i,384);let o=_.fstatSync(n),s=_.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let l=o.mode&511;if((l&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${l.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);_.fchmodSync(n,384)}catch(r){if(n!==null)try{_.closeSync(n)}catch{}Q||T({event:"sidecar_disabled",reason:"open_failed",detail:E(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${E(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}q=t,L=n,j=!0}var Wr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Jr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Wr.some(n=>n.test(t))}function Zt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=zr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Jr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function zr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Vr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Zt(e.url)}:e}function Xr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=K(i,we()),s=JSON.stringify({version:Vt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Vt,timestamp:t,type:r,output_truncated:!0})),s}function v(e){if(!j||!q||L===null)return;let t=Vr(e),n=Xr(t);try{if(_.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>it){j=!1;try{_.closeSync(L)}catch{}L=null,Q||T({event:"sidecar_disabled",reason:"size_limit",...q===null?{}:{path:E(q)},max_bytes:it},`${E(`[allscale] sidecar exceeded ${it} bytes; disabling it for the rest of this run. Rotate or remove ${q}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}_.appendFileSync(L,`${n}
7
+ `)}catch(r){if(j=!1,L!==null){try{_.closeSync(L)}catch{}L=null}try{Q||T({event:"sidecar_disabled",reason:"write_failed",detail:E(r.message)},`${E(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var Qt=Zt;function en(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function ee(){if(Q=!1,j=!1,L!==null){try{_.closeSync(L)}catch{}L=null}}function Ae(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||en()||!t}var te=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Zr=new Set(Array.from(te).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Qr=Array.from(te).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),ei=new Set(["--otp-stdin","--password-stdin"]);function st(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(te.has(s)){t.push(`${s}=<redacted>`);continue}}}if(te.has(r)){t.push(r),n+1<e.length&&(te.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(Zr.has(o)){t.push(`${o}<redacted>`);continue}}let i=ei.has(r)?void 0:Qr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function tn(e){v({type:"error",code:e.code,message:E(e.message)}),v({type:"command-end",ok:!1,exitCode:e.exitCode}),ee()}var ne=V()??Ut,W={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function at(e){return Gt(e)?new URL(e).origin:null}function x(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function nn(){let e=process.env[W.TOKEN]?.trim();return e&&e.length>0?e:void 0}function lt(){let e=process.env[W.PROFILE]?.trim();return e&&e.length>0?e:void 0}function re(){let e=process.env[W.API_BASE]?.trim();return e&&e.length>0?e:void 0}function rn(){let e=process.env[W.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function on(){let e=process.env[W.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function sn(){let e=process.env[W.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function an(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(V()===void 0&&ne!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
9
  The CLI default is now ${ne} (production), but a saved profile wins over the default,
10
10
  so this session still uses staging. That pin was written before the default changed, so it may just be
11
11
  the old default rather than a deliberate choice.
12
12
  To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
13
13
  To move to production, run: allscale device-login --api-base ${ne}
14
- `}var I=A(require("fs")),ln=A(require("os")),ut=A(require("path")),Le=A(require("@iarna/toml"));var zr=".allscale",Xr="config.toml";function ke(){return ut.join(ln.homedir(),zr)}function Te(){return ut.join(ke(),Xr)}function re(){let e=Te();if(!I.existsSync(e))return{};let t=I.readFileSync(e,"utf-8");try{return Le.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function cn(e){let t=ke();I.existsSync(t)||I.mkdirSync(t,{recursive:!0,mode:448});let n=Le.stringify(e),r=Te();I.writeFileSync(r,n,{mode:384});try{I.chmodSync(r,384)}catch{}}function un(e,t){return e.profile?.[t]}function dn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function fn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function Ie(e){if(!pe(e))throw new c("input.invalid",`Refusing to send credentials to API base ${P(e)}. `+We)}function dt(e){let t=z();if(t===void 0||N(e))return;let n=be(e),r=V();if(r.length>0){let o=r.map(l=>be(l.base)).filter(l=>l!==null);if(n!==null&&o.includes(n))return;let s=r.map(l=>P(l.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${P(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=be(t);if(!(n!==null&&n===i))throw new c("input.invalid",`Refusing to send to ${P(e)} \u2014 this build only signs for ${P(t)}. Re-login against this build's environment, or use a build for that one.`)}var Vr=require("@noble/hashes/sha3");var pn=["USDT","USDC"];var ns=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var x=require("@oclif/core"),ie=class e extends R.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:R.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:R.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:X()==="public"}),"api-base":R.Flags.string({description:je,helpGroup:"GLOBAL",hidden:X()==="public"}),"insecure-storage":R.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{ot(this.jsonEnabled()),at(),v({type:"session-start",command:this.id??"",argv:lt(this.argv)});let t=this.constructor;if(X()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Ae()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=Ee(this.jsonEnabled()),r=this.argv.length===0&&!n&&ii(t)?this.config.findCommand(this.id??""):void 0;if(r){ee();let o=await(0,R.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&&!sn())throw this.argv.length>0&&await this.parse(),new c("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return v({type:"command-end",ok:!0}),ee(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ht(i),{data:i})}catch(t){let n=Kt(t);tn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{ot(!1)}}resolveSessionApiBaseChain(t){let n=re(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||ct()!==void 0,s=fn(n,r,ct()),l=un(n,s),d=i??Ae(),u=d??l?.api_base??ne,p=an({resolvedApiBase:u,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,O({event:"legacy_staging_profile",api_base:u,profile:s},p)),{apiBase:u,explicitApiBase:d,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Ie(n),n}resolveContext(t){if(X()==="public"){if(t.token!==void 0)throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Ae()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Ie(i),dt(i)),{apiBase:i,profile:s,token:n??nn(),insecureStorage:r||rn(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d}}emitError(t){process.stderr.write(`${ri(t)}
15
- `)}};var Zr=/_(removed|cleared|count|total)$/i;function Qr(e,t){return typeof t=="number"&&Zr.test(e)}var ei=new Set(pn);function ti(e,t){return e==="token_symbol"&&typeof t=="string"&&ei.has(t)}var Oe=100;function ve(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Oe),r=n.map(i=>ve(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Oe))n[i]=he(i)&&!Qr(i,o)&&!ti(i,o)?"<redacted>":ve(o,t+1);if(r.length>Oe){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Oe} more keys`}return n}if(typeof e=="string"){let n=ni(e);return n!==void 0?b(JSON.stringify(ve(n,t+1))):b(e)}return e}function ni(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function ri(e){let t=zt()?void 0:2,n=ve(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:b(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function ii(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 gn(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 ft=new Set;var pt=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"]),oe=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Re=new Set(["payroll","admin:user","admin:org","admin:audit"]);function j(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 gt(e){return[...oe].some(t=>Ce(t,e))}function Pe(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 oi=new Set(["cli_op:all"]),si=new Set([...oi].map(j));var hn=new Set([...[...pt,...oe,...ft].map(j),...Re,...si]);function ai(e){return e.filter(t=>!Pe(t)||!hn.has(j(t)))}function mn(e){if(!e||e.length===0)return;let t=ai(e);if(t.length!==0)throw new c("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: ${[...hn].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}var wn=require("child_process");function _n(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var li=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function ci(e,t,n,r){if(_n(e.CI)||li.some(s=>_n(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 ui(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 Sn(e,t={}){if(!Je(e))throw new c("input.invalid",`Refusing to launch browser for untrusted origin: ${P(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new c("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:ci(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new c("wallet.requires_browser_auth",ui(o));if(r==="linux"&&!n.DISPLAY&&!i)throw new c("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=di(r,i);await fi(s.command,[...s.args,e])}function di(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 fi(e,t){return new Promise((n,r)=>{let i;try{i=(0,wn.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(yn(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(yn(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function yn(e,t){return new c("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var ht=require("process"),En=require("readline");async function bn(e){let t=(0,En.createInterface)({input:process.stdin,output:ht.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 ht.stderr.write(`
16
- `),!1;let i=r.trim().toLowerCase();return i===""||i==="y"||i==="yes"}finally{n&&process.removeListener("SIGINT",n),t.close()}}var An=A(require("crypto")),Ln=A(require("fs")),kn=A(require("path"));var pi="key-id",gi="x-allscale-cli-version",mt="cli-1",hi="aScaLe_cli_obf_v1",mi="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 yi=_i(mi,hi),wi=`Bearer ${yi}`;function Tn(e,t){let n=Xe(e);if(n!==null)return t.find(r=>Xe(r.base)===n)}function Si(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=Tn(e,t);if(r)return r.key;if(N(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:N(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Ei(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?Tn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&N(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(!N(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 bi(){return"1.0.1"}function Ai(){return new c("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ne(e,t){let n=Si(t);if(!n)throw Ai();let r=Ei(t),i=Math.floor(Date.now()/1e3).toString(),o=An.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[gi]:bi()};return r.length>0&&(s[pi]=r),s}function xe(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var Li=500,ki=8,In=100;function _t(e,t=0){if(t>ki)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,In),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,In))n[r]=he(r)?"<redacted>":_t(i,t+1);return n}return e}function Ti(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 W(e,t=Li){let n=Ti(e),r=n===void 0?ge(e):JSON.stringify(_t(n));return me(r,t)}var yt=256*1024,Be=class extends c{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"}},J=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,u=n.timeoutMs,p=u===void 0?void 0:new Promise((f,g)=>{d=setTimeout(()=>{g(new J(e.status,u))},u),d.unref?.()});try{for(;;){let f=o.read(),{done:g,value:m}=p?await Promise.race([f,p]):await f;if(g)break;if(l+=m.byteLength,l>t)throw o.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);s.push(Buffer.from(m))}}catch(f){throw f instanceof J&&o.cancel(f).catch(()=>{}),f}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var ta=32*1024*1024,na=4*1024*1024;function Ii(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${Qt(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 St(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Ii(e.status,e.url)}}var On="--dns-result-order=ipv4first";async function se(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 p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new c("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${On} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${On}`})}var Oi=2014;function vi(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 Ri(e){return vi(e,Oi)}function De(e,t){if(!(e>=200&&e<300)&&Ri(t))throw new c("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?W(t):t})}var Ci={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function vn(e){if(typeof e=="string")return e;if(typeof e=="number")return Ci[e]??`user_type_${e}`}function Rn(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 Pi="/api/public/auth/cli_authorize_init",Ni="/api/public/auth/cli_authorize_poll",Et=1e4,bt=1e4,xi=1e3,Bi=3,Di=3e4,Pn=900,Nn="empty_response",xn="invalid_response",Bn="poll_fetch_failure",Dn="poll_request_timeout",Un="poll_body_failure",$n="poll_body_timeout",Ui="approved_credential_mismatch";async function $i(e,t={}){let n=new URL(Pi,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=Ne(xe(r),e),s=Date.now()+Et,l;try{l=await Gn(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i},Et)}catch(f){throw Mn(n,f,"init",Et)}if(await se(l),l.status===429)throw new c("rate_limited","Device-pairing init was rate-limited.",{status:429});if(await St(l),l.status!==200){let f=await ae(l,s,n,"init");throw await se(l,f),De(l.status,f),new c(l.status>=500?"backend.internal":"input.invalid",`Device-pairing init failed: HTTP ${l.status}`,{status:l.status,body:W(f)})}let u=Gi(await ae(l,s,n,"init")).data??{};for(let f of["polling_token","verification_code","verification_url"])if(typeof u[f]!="string"||u[f].length===0)throw new c("backend.internal",`Device-pairing init response missing required field: ${f}`);if(typeof u.expires_at!="number"||u.expires_at<=0)throw new c("backend.internal","Device-pairing init response missing or invalid expires_at");let p=typeof u.poll_interval=="number"&&u.poll_interval>0?u.poll_interval:2;return{polling_token:u.polling_token,verification_code:u.verification_code,verification_url:u.verification_url,expires_at:u.expires_at,poll_interval:p}}async function Fi(e,t,n=bt){let r=new URL(Ni,e).toString(),i={polling_token:t},o=JSON.stringify(i),s=Ne(xe(i),e),l=Number.isFinite(n)&&n>0?Math.max(1,Math.min(bt,Math.floor(n))):bt,d=Date.now()+l,u;try{u=await Gn(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s},body:o},l)}catch(T){throw Mn(r,T,"poll",l)}if(await se(u),u.status===429)throw new c("rate_limited","Device-pairing poll was rate-limited.",{status:429});if(u.status>=500){let T=await ae(u,d,r,"poll");De(u.status,T);let qe=Yi(T);throw qe===7510?new c("auth.token_expired","Device-pairing window expired. Re-run `allscale device-login`."):qe===7511?new c("auth.no_token","Polling token is invalid or already consumed. Re-run `allscale device-login`."):qe===7530?new c("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."):new c("backend.internal",`Device-pairing poll failed: HTTP ${u.status}`,{status:u.status,body:W(T)})}if(await St(u),u.status!==200){let T=await ae(u,d,r,"poll");throw await se(u,T),De(u.status,T),new c("input.invalid",`Device-pairing poll failed: HTTP ${u.status}`,{status:u.status,body:W(T)})}let p=await ae(u,d,r,"poll");if(p.trim().length===0)throw new c("backend.internal","Device-pairing poll returned an empty HTTP 200 response.",{status:200,reason:Nn});let f;try{f=JSON.parse(p)}catch{throw At()}if(f===null||typeof f!="object"||Array.isArray(f))throw At();let g=f,m=g.data?.status;if(m==="pending")return{status:"pending"};if(m!=="approved")throw At();let S=vn(g.data?.user_type)??"business",_=g.data?.scopes,E=Array.isArray(_)&&_.every(T=>typeof T=="string")?_:void 0,sr=E&&E.length>0?{scopes:E}:{},Ye=g.data?.agent_key;if(typeof Ye!="string"||Ye.length===0)throw new c("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:Ui,expected_credential:"agent_key"});let Ke=g.data?.agent_key_expires_at,He=g.data?.business_id,ar=typeof He=="string"&&He.length>0?{business_id:He}:{},Bt=Rn(g.data?.user_email),lr=Bt===void 0?{}:{user_email:Bt};return{status:"approved",user_type:S,credential:"agent_key",tokens:{access_token:"",refresh_token:"",agent_key:Ye,...typeof Ke=="number"&&Ke>0?{agent_key_expires_at:Ke}:{},user_type:S,api_base:e,...sr,...ar,...lr}}}async function Fn(e,t){let n=await $i(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:Pn,o=Math.min(n.expires_at,r()+i);await t.onInit(n,{pollingDeadlineAt:o});let s=t._sleep??(g=>new Promise(m=>{setTimeout(m,g)})),l=Math.max(xi,n.poll_interval*1e3),d=0,u=l,p=0,f;for(;;){let g=(o-r())*1e3;if(g<=0)throw Cn(f,p);await s(Math.min(u,g));let m=(o-r())*1e3;if(m<=0)throw Cn(f,p);d+=1;let S;try{S=await Fi(e,n.polling_token,m)}catch(_){if(f!==void 0&&_ instanceof c&&_.code==="auth.no_token")throw Lt(f,p,"invalid_polling_token_after_transient_failure");if(!Mi(_))throw _;if(p+=1,f=_,p>Bi)throw Lt(_,p,"transient_retry_budget_exhausted");u=Math.min(Di,l*2**p);continue}if(S.status==="approved")return{...S,verification_code:n.verification_code};p=0,f=void 0,u=l,t.onPending?.(d)}}function Mn(e,t,n,r){return t instanceof Error&&t.name==="AbortError"?new c("transport.timeout",`Device-pairing ${n} against ${e} timed out after ${r}ms.`,{timeout_ms:r,stage:n,reason:n==="poll"?Dn:"init_request_timeout"}):new c("transport.network",`Network error during device-pairing ${n} against ${e}.`,{stage:n,reason:n==="poll"?Bn:"init_fetch_failure"})}function Mi(e){if(!(e instanceof c))return!1;if(e.code==="transport.network")return e.details?.stage==="poll"&&(e.details.reason===Bn||e.details.reason===Un);if(e.code==="transport.timeout")return e.details?.stage==="poll"&&(e.details.reason===Dn||e.details.reason===$n);if(e.code!=="backend.internal")return!1;let t=e.details?.status;return typeof t=="number"&&t>=500&&t<=599||e.details?.reason===Nn||e.details?.reason===xn}function At(){return new c("backend.internal","Device-pairing poll returned a malformed or unexpected HTTP 200 response.",{status:200,reason:xn})}function Cn(e,t){return e!==void 0?Lt(e,t,"pairing_deadline_elapsed_after_transient_failure"):new c("auth.token_expired",`Device-pairing timed out before the browser confirmed \u2014 the pairing window closed, or the CLI reached its ${Pn/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\`.`)}function Lt(e,t,n){let r=e.details?.status;return new c("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 ae(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 c?o:o instanceof J?new c("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"?$n:"init_body_timeout"}):new c("transport.network",`Network error while reading the device-pairing ${r} response body from ${n}.`,{status:e.status,stage:r,reason:r==="poll"?Un:"init_body_failure"})}}async function Gn(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 Gi(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function Yi(e){if(e)try{let t=JSON.parse(e);if(typeof t.code=="number")return t.code}catch{}}var er=A(require("path"));var It=require("crypto"),a=A(require("fs")),w=A(require("path"));var Ue=1024*1024,Ki=5e3,Hi=20,qi=3e4,kt=4096,ji=new Int32Array(new SharedArrayBuffer(4)),le=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function $e(e){return e instanceof le}var L=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Wi=null;function D(){return new c("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Fe(){return(Wi??process.platform)!=="win32"}function zn(){if(!Fe())throw D()}function Xn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!y(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(w.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(y(t,"ENOENT"))return!0;throw t}}function y(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ce(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ue(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ji(e){Atomics.wait(ji,0,0,e)}function Vn(e){try{return process.kill(e,0),!0}catch(t){return!y(t,"ESRCH")}}function zi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yn(e,t){let n=w.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&y(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()||!ue(o,s))throw new Error("credential-store parent changed while it was being inspected");ce(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&w.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 C(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&&y(o,"ENOENT")?new L:o}if(!ue(n,i))throw r.retryOnPathChange?new L: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 le;if(ce(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 Xi(e,t){if(t.size>Ue)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ue+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>Ue)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Kn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(y(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(y(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=C(e,t,n);return Xi(t,r)}finally{t!==null&&a.default.closeSync(t)}}function Hn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(y(i,"ENOENT")&&Xn(e))return;throw i}let n=a.default.fstatSync(t),r=C(e,t,n);U(e,r)}finally{t!==null&&a.default.closeSync(t)}Qn(w.dirname(e))}function Vi(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(y(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 le;ce(t,"credential-store replacement target")}function Zi(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=w.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(y(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Zn(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 Qn(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 Qi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ue)throw new Error("credential-store file exceeds the maximum supported size");let r=w.dirname(e),i=w.basename(e),o=null,s=null,l=!1;try{let d=Zi(r,i);o=d.fd,s=d.tempPath;let u=a.default.fstatSync(o);if((C(s,o,u).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Zn(o,n),a.default.fsyncSync(o),C(s,o,a.default.fstatSync(o));let f=o;o=null,a.default.closeSync(f),Vi(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{}}Qn(r)}function eo(e){return w.join(w.dirname(e),`.${w.basename(e)}.lock`)}function to(e){return w.join(w.dirname(e),`.${w.basename(e)}.lock-recovery`)}function no(e,t){if(t.size>kt)return null;let n=Buffer.alloc(kt+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>kt)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 U(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ue(n,t))throw new Error("credential-store lock changed while it was being inspected");ce(n,"credential-store lock"),a.default.unlinkSync(e)}function qn(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(y(d,"ENOENT"))try{let u=a.default.lstatSync(e);throw u.isSymbolicLink()||!u.isFile()?new Error("credential-store lock must be a real regular file"):new L}catch(u){if(y(u,"ENOENT"))return{state:"absent"};throw u}throw d}let r=a.default.fstatSync(n),i=C(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=no(n,i);return{state:(o?.target===t&&o?!Vn(o.pid):Date.now()-i.mtimeMs>=qi)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function ro(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=w.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=C(i,s,l,{allowMultipleLinks:!0});return Zn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:d}}catch(l){if(y(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 io(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 y(r,"ENOENT")?new L:r}try{let r=a.default.fstatSync(n),i=C(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ue(i,t))throw new L;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function jn(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(y(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 L}catch(r){if(y(r,"ENOENT"))return!1;throw r}throw n}return C(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function oo(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(y(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=C(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 B(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");Ji(Hi)}function Wn(e){let t=w.dirname(e),n=w.basename(e),r=eo(e),i=to(e),o=ro(t,n),s=Date.now()+Ki,l=!1,d=!1,u=null,p;try{for(;u===null;)try{if(jn(i)){B(s,!0);continue}a.default.linkSync(o.claimPath,r),d=!0,u=io(r,o.stats),l=!0}catch(f){if(d&&!l){try{U(r,o.stats)}catch{}d=!1}if(f instanceof L){B(s,!1);continue}if(!y(f,"EEXIST"))throw f;let g;try{g=qn(r,n)}catch(S){if(S instanceof L){B(s,!1);continue}throw S}if(g.state==="absent")continue;if(g.state==="stale"){let S;try{S=oo(i)}catch(_){if(_ instanceof L){B(s,!1);continue}throw _}if(S!==null){try{let _;try{_=qn(r,n)}catch(E){if(E instanceof L){B(s,!1);continue}throw E}_.state==="stale"&&U(r,_.stats)}finally{Tt(S)}continue}}let m;try{m=jn(i)}catch(S){if(S instanceof L){B(s,!1);continue}throw S}B(s,m)}}catch(f){p=f}try{U(o.claimPath,o.stats)}catch(f){!y(f,"ENOENT")&&!l&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(u===null)throw new Error("credential-store lock acquisition failed");return u}function Tt(e){try{U(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function so(e,t){let n=zi(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 Jn(e){let t=w.dirname(e),n=w.basename(e);for(let r of a.default.readdirSync(t)){let i=so(r,n);if(i===null||Vn(i))continue;let o=w.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(u){if(y(u,"ENOENT")||y(u,"ELOOP"))continue;throw u}let l=a.default.fstatSync(s),d=a.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!ue(l,d))continue;try{ce(l,"credential-store orphan")}catch{continue}U(o,l)}catch(l){if(!y(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function de(e,t,n){if(!Fe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!Yn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let s=Wn(e);try{return Jn(e),n({read:()=>Kn(e),remove:()=>Hn(e),write:()=>{throw D()}})}finally{Tt(s)}}if(!t.createParent){let o=!1;try{o=Xn(e)}catch{throw D()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!Yn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Wn(e);try{return Jn(e),n({read:()=>Kn(e),remove:()=>Hn(e),write:o=>Qi(e,o)})}finally{Tt(i)}}var Ot="allscale-cli";function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tr(e){return Pt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new c("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function vt(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Me(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var $,Rt=!1;function ao(){return on()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function lo(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
- `,1)[0]==="Cannot find module 'keytar'"}function co(){if($!==void 0)return $;if(ao())return Rt=!1,$=null,$;try{$=require("keytar"),Rt=!1}catch(e){Rt=!lo(e),$=null}return $}function nr(){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 c("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Ct(e){try{return await e()}catch{throw nr()}}var Nt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Ct(()=>this.keytar.getPassword(Ot,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!tr(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Ct(()=>this.keytar.setPassword(Ot,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Ct(()=>this.keytar.deletePassword(Ot,t))}},uo="credentials.json",xt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??er.join(ke(),uo)}read(t){let n;try{n=t.read()}catch(i){throw $e(i)?vt():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!Pt(r)||!Pt(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw $e(r)?vt():Me()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!tr(r))throw F("plaintext file");return r}}async get(t){try{return de(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:F("plaintext file")}}async set(t,n){try{de(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 c?r:Me()}}async delete(t){try{de(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof c?n:Me()}}async clearProfile(t){try{return de(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof c?n:$e(n)?vt():Me()}}};function rr(e){if(e.insecureStorage)return zn(),new xt(e.insecureFilePath);let t=co();if(t)return new Nt(t);throw nr()}async function ir(e,t){await e.get(t)}async function or(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof c?r.message:b(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 c(r instanceof c?r.code:"storage.unavailable",`${i} ${o}`,r instanceof c?r.details:void 0)}}var Ge=class e extends ie{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":x.Flags.string({description:"Human-readable label shown in the browser approval UI so the user can confirm they're authorizing the right device."}),scopes:x.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: "+gn(oe)+". The final set is chosen \u2014 and can be overridden \u2014 on that screen, and is checked by the backend on each request. The Wallets toggle is on by default and grants `wallet:read_only`, which `wallet list` needs and `invoice pay` needs as ONE of its two scopes \u2014 `invoice pay` also needs `invoice:all` \u2014 request it here with `--scopes invoice:all` (it is forwarded to the approval screen), and tick the Invoices write tier there, since that toggle starts at Read. Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any pairing session is registered \u2014 the same check, and the same exit code, as `otp-login --scopes`. A recognised scope the screen declines to grant is reported after the key is minted, not up front.",multiple:!0}),"no-browser":x.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}),yes:x.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}),...ie.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);mn(t.scopes);let n=this.resolveContext(t),r=rr({insecureStorage:n.insecureStorage});if(this.argv.length===0&&!t.yes&&!Ee(this.jsonEnabled())&&process.stderr.isTTY===!0&&(process.stderr.write(`\`allscale device-login\` will now:
14
+ `}var I=A(require("fs")),ln=A(require("os")),ct=A(require("path")),ke=A(require("@iarna/toml"));var ri=".allscale",ii="config.toml";function Le(){return ct.join(ln.homedir(),ri)}function Te(){return ct.join(Le(),ii)}function ie(){let e=Te();if(!I.existsSync(e))return{};let t=I.readFileSync(e,"utf-8");try{return ke.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function cn(e){let t=Le();I.existsSync(t)||I.mkdirSync(t,{recursive:!0,mode:448});let n=ke.stringify(e),r=Te();I.writeFileSync(r,n,{mode:384});try{I.chmodSync(r,384)}catch{}}function un(e,t){return e.profile?.[t]}function dn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function pn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function Ie(e){if(!ge(e))throw new c("input.invalid",`Refusing to send credentials to API base ${x(e)}. `+je)}function ut(e){let t=si(e);if(t)throw new c("input.invalid",t.message)}function oi(){let e=V();if(e===void 0)return;let t=X();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function si(e){let t=oi();if(t===void 0||P(e))return;let{endpoints:n,fromPairs:r}=t,i=at(e),o=n.map(l=>at(l)).filter(l=>l!==null);if(i!==null&&o.includes(i))return;let s=n.map(l=>x(l)).join(", ");return{message:r?`Refusing to send to ${x(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 ${x(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var ai=require("@noble/hashes/sha3");var fn=["USDT","USDC"];var ks=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var li="unknown_otp_id",ci="invalid_code",ui="expired_code";function di(e){return`'${e.replace(/'/g,"'\\''")}'`}function hn(e){return`Run \`allscale otp-send --email ${di(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var pi=new Map([[li,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${hn(t)}`],[ci,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.`],[ui,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${hn(t)}`]]);var gn=[...pi.keys()];var N=require("@oclif/core"),oe=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:G()==="public"}),"api-base":O.Flags.string({description:qe,helpGroup:"GLOBAL",hidden:G()==="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{rt(this.jsonEnabled()),ot(),v({type:"session-start",command:this.id??"",argv:st(this.argv)});let t=this.constructor;if(G()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&re()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=Ae(this.jsonEnabled()),r=this.argv.length===0&&!n&&Si(t)?this.config.findCommand(this.id??""):void 0;if(r){ee();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&&!sn())throw this.argv.length>0&&await this.parse(),new c("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return v({type:"command-end",ok:!0}),ee(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||qt(i),{data:i})}catch(t){let n=Yt(t);tn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{rt(!1)}}resolveSessionApiBaseChain(t){let n=ie(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||lt()!==void 0,s=pn(n,r,lt()),l=un(n,s),d=G()==="public"&&re()!==void 0,u=i??(d?void 0:re()),h=u??l?.api_base??ne,p=an({resolvedApiBase:h,fromExplicitOverride:u!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,T({event:"legacy_staging_profile",api_base:h,profile:s},p)),{apiBase:h,explicitApiBase:u,envApiBaseIgnored:d,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Ie(n),n}resolveContext(t){if(G()==="public"){if(t.token!==void 0)throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&re()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:l,profileApiBase:d,profileExplicit:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Ie(i),ut(i)),{apiBase:i,profile:l,token:n??nn(),insecureStorage:r||rn(),apiBaseSource:o!==void 0?"explicit":d!==void 0?"profile":"default",profileExplicit:u,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${bi(t)}
15
+ `)}};var fi=/_(removed|cleared|count|total)$/i;function hi(e,t){return typeof t=="number"&&fi.test(e)}var gi=new Set(fn);function mi(e,t){return e==="token_symbol"&&typeof t=="string"&&gi.has(t)}var _i=new Set(gn);function yi(e,t){return e==="otp_reason"&&typeof t=="string"&&_i.has(t)}var ve=100;function Oe(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,ve),r=n.map(i=>Oe(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,ve))n[i]=_e(i)&&!hi(i,o)&&!mi(i,o)&&!yi(i,o)?"<redacted>":Oe(o,t+1);if(r.length>ve){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-ve} more keys`}return n}if(typeof e=="string"){let n=wi(e);return n!==void 0?E(JSON.stringify(Oe(n,t+1))):E(e)}return e}function wi(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 bi(e){let t=zt()?void 0:2,n=Oe(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 Si(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 mn(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 _n=new Set;var yn=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"]),se=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"]),Re=new Set(["payroll","admin:user","admin:org","admin:audit"]);function J(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function ae(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}function dt(e){return[...se].some(t=>ae(t,e))}function Ce(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 wn=new Set(["cli_op:all"]),Ei=new Set([...wn].map(J));function Ai(e){return[...wn].some(t=>ae(t,e))}var bn=new Set([...[...yn,...se,..._n].map(J),...Re,...Ei]);function ki(e){return e.filter(t=>!Ce(t)||!bn.has(J(t)))}function Sn(e){if(!e||e.length===0)return;let t=ki(e);if(t.length!==0)throw new c("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: ${[...bn].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}function pt(e){let t={otpLoginOnly:[],reachesNothing:[],ungrantable:[],implicitOnly:[]};for(let n of e){if(!Ce(n))continue;if(Ai(n)){t.implicitOnly.push(n);continue}let r=J(n);if(Re.has(r)){t.ungrantable.push(n);continue}if(!dt(n)){if(_n.has(n)){t.reachesNothing.push(n);continue}if(yn.has(n)){t.otpLoginOnly.push(n);continue}}}return t}function En(e,t){if(!e||e.length===0)return;let n=pt(e),{otpLoginOnly:r,reachesNothing:i,ungrantable:o}=n,s=t?.allowUnrenderable?[]:r,l=[...s,...i,...o];if(l.length!==0)throw new c("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 Ln=require("child_process");function An(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Li=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Ti(e,t,n,r){if(An(e.CI)||Li.some(s=>An(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 Ii(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 Tn(e,t={}){if(!He(e))throw new c("input.invalid",`Refusing to launch browser for untrusted origin: ${x(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new c("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:Ti(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new c("wallet.requires_browser_auth",Ii(o));if(r==="linux"&&!n.DISPLAY&&!i)throw new c("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=vi(r,i);await Oi(s.command,[...s.args,e])}function vi(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 Oi(e,t){return new Promise((n,r)=>{let i;try{i=(0,Ln.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(kn(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(kn(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function kn(e,t){return new c("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var ft=require("process"),In=require("readline");async function vn(e){let t=(0,In.createInterface)({input:process.stdin,output:ft.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 ft.stderr.write(`
16
+ `),!1;let i=r.trim().toLowerCase();return i===""||i==="y"||i==="yes"}finally{n&&process.removeListener("SIGINT",n),t.close()}}var On=A(require("crypto")),Rn=A(require("fs")),Cn=A(require("path"));var Ri="key-id",Ci="x-allscale-cli-version",ht="cli-1",Ni="aScaLe_cli_obf_v1",Pi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function xi(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 Bi=xi(Pi,Ni),Di=`Bearer ${Bi}`;function Nn(e,t){let n=Je(e);if(n!==null)return t.find(r=>Je(r.base)===n)}function $i(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=Nn(e,t);if(r)return r.key;if(P(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:P(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 Ui(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?Nn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&P(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():ht}if(!P(t[0].base))return ht}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():ht}function Fi(){return"1.0.2"}function Mi(){return new c("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ne(e,t){let n=$i(t);if(!n)throw Mi();let r=Ui(t),i=Math.floor(Date.now()/1e3).toString(),o=On.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Ci]:Fi()};return r.length>0&&(s[Ri]=r),s}function Pe(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var Gi=500,Ki=8,Pn=100;function gt(e,t=0){if(t>Ki)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Pn),r=n.map(i=>gt(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,Pn))n[r]=_e(r)?"<redacted>":gt(i,t+1);return n}return e}function Yi(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 le(e,t=Gi){let n=Yi(e),r=n===void 0?me(e):JSON.stringify(gt(n));return ye(r,t)}var mt=256*1024,xe=class extends c{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},z=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function _t(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 xe(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,d,u=n.timeoutMs,h=u===void 0?void 0:new Promise((p,g)=>{d=setTimeout(()=>{g(new z(e.status,u))},u),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 xe(e.status,t,n.oversizeKind);s.push(Buffer.from(S))}}catch(p){throw p instanceof z&&o.cancel(p).catch(()=>{}),p}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var Ta=32*1024*1024,Ia=4*1024*1024;function qi(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${Qt(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 yt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}qi(e.status,e.url)}}var xn="--dns-result-order=ipv4first";async function ce(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 c("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${xn} 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=${xn}`})}var ji=2014;function Hi(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 Wi(e){return Hi(e,ji)}function wt(e,t){if(!(e>=200&&e<300)&&Wi(t))throw new c("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?le(t):t})}var Ji={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Bn(e){if(typeof e=="string")return e;if(typeof e=="number")return Ji[e]??`user_type_${e}`}function Dn(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",Vi="/api/public/auth/cli_authorize_poll",bt=1e4,St=1e4,Xi=1e3,Zi=3,Qi=3e4,Un=900,Fn="empty_response",Mn="invalid_response",Gn="poll_fetch_failure",Kn="poll_request_timeout",Yn="poll_body_failure",qn="poll_body_timeout",eo="approved_credential_mismatch",to="pairing_expired_backend_ttl",jn="pairing_token_unrecognized",no="pairing_token_unrecognized_after_window_closed",ro="pairing_deadline_backend_ttl",io="pairing_deadline_cli_ceiling";async function oo(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=Ne(Pe(r),e),s=Date.now()+bt,l;try{l=await zn(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i},bt)}catch(p){throw Wn(n,p,"init",bt)}if(await ce(l),l.status===429)throw new c("rate_limited","Device-pairing init was rate-limited.",{status:429});if(await yt(l),l.status!==200){let p=await Be(l,s,n,"init");throw await ce(l,p),wt(l.status,p),new c(l.status>=500?"backend.internal":"input.invalid",`Device-pairing init failed: HTTP ${l.status}`,{status:l.status,body:le(p)})}let u=lo(await Be(l,s,n,"init")).data??{};for(let p of["polling_token","verification_code","verification_url"])if(typeof u[p]!="string"||u[p].length===0)throw new c("backend.internal",`Device-pairing init response missing required field: ${p}`);if(typeof u.expires_at!="number"||u.expires_at<=0)throw new c("backend.internal","Device-pairing init response missing or invalid expires_at");let h=typeof u.poll_interval=="number"&&u.poll_interval>0?u.poll_interval:2;return{polling_token:u.polling_token,verification_code:u.verification_code,verification_url:u.verification_url,expires_at:u.expires_at,poll_interval:h}}async function so(e,t,n=St){let r=new URL(Vi,e).toString(),i={polling_token:t},o=JSON.stringify(i),s=Ne(Pe(i),e),l=Number.isFinite(n)&&n>0?Math.max(1,Math.min(St,Math.floor(n))):St,d=Date.now()+l,u;try{u=await zn(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s},body:o},l)}catch(C){throw Wn(r,C,"poll",l)}if(await ce(u),u.status===429)throw new c("rate_limited","Device-pairing poll was rate-limited.",{status:429});if(await yt(u),u.status!==200){let C=await Be(u,d,r,"poll");await ce(u,C),wt(u.status,C);let M=uo(C);if(M===7510)throw Jn({backendCode:M,status:u.status,reason:to});if(M===7511){let Bt=co(u.headers);throw new c("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:u.status,backend_code:M,reason:jn,...Bt===null?{}:{server_now:Bt}})}throw M===7530?new c("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:u.status,backend_code:M}):new c(u.status>=500?"backend.internal":"input.invalid",`Device-pairing poll failed: HTTP ${u.status}`,{status:u.status,body:le(C)})}let h=await Be(u,d,r,"poll");if(h.trim().length===0)throw new c("backend.internal","Device-pairing poll returned an empty HTTP 200 response.",{status:200,reason:Fn});let p;try{p=JSON.parse(h)}catch{throw Et()}if(p===null||typeof p!="object"||Array.isArray(p))throw Et();let g=p,S=g.data?.status;if(S==="pending")return{status:"pending"};if(S!=="approved")throw Et();let y=Bn(g.data?.user_type)??"business",f=g.data?.scopes,m=Array.isArray(f)&&f.every(C=>typeof C=="string")?f:void 0,hr=m&&m.length>0?{scopes:m}:{},Ge=g.data?.agent_key;if(typeof Ge!="string"||Ge.length===0)throw new c("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:eo,expected_credential:"agent_key"});let Ke=g.data?.agent_key_expires_at,Ye=g.data?.business_id,gr=typeof Ye=="string"&&Ye.length>0?{business_id:Ye}:{},xt=Dn(g.data?.user_email),mr=xt===void 0?{}:{user_email:xt};return{status:"approved",user_type:y,credential:"agent_key",tokens:{access_token:"",refresh_token:"",agent_key:Ge,...typeof Ke=="number"&&Ke>0?{agent_key_expires_at:Ke}:{},user_type:y,api_base:e,...hr,...gr,...mr}}}async function Hn(e,t){let n=await oo(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:Un,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(Xi,n.poll_interval*1e3),u=0,h=d,p=0,g;for(;;){let S=(o-r())*1e3;if(S<=0)throw $n(g,p,s);await l(Math.min(h,S));let y=(o-r())*1e3;if(y<=0)throw $n(g,p,s);u+=1;let f;try{f=await so(e,n.polling_token,y)}catch(m){if(g!==void 0&&m instanceof c&&m.code==="auth.no_token")throw At(g,p,"invalid_polling_token_after_transient_failure");if(m instanceof c&&m.code==="auth.no_token"&&m.details?.reason===jn&&typeof m.details.server_now=="number"&&m.details.server_now>=n.expires_at)throw Jn({backendCode:7511,...typeof m.details.status=="number"?{status:m.details.status}:{},reason:no});if(!ao(m))throw m;if(p+=1,g=m,p>Zi)throw At(m,p,"transient_retry_budget_exhausted");h=Math.min(Qi,d*2**p);continue}if(f.status==="approved")return{...f,verification_code:n.verification_code};p=0,g=void 0,h=d,t.onPending?.(u)}}function Wn(e,t,n,r){return t instanceof Error&&t.name==="AbortError"?new c("transport.timeout",`Device-pairing ${n} against ${e} timed out after ${r}ms.`,{timeout_ms:r,stage:n,reason:n==="poll"?Kn:"init_request_timeout"}):new c("transport.network",`Network error during device-pairing ${n} against ${e}.`,{stage:n,reason:n==="poll"?Gn:"init_fetch_failure"})}function ao(e){if(!(e instanceof c))return!1;if(e.code==="transport.network")return e.details?.stage==="poll"&&(e.details.reason===Gn||e.details.reason===Yn);if(e.code==="transport.timeout")return e.details?.stage==="poll"&&(e.details.reason===Kn||e.details.reason===qn);if(e.code!=="backend.internal")return!1;let t=e.details?.status;return typeof t=="number"&&t>=500&&t<=599||e.details?.reason===Fn||e.details?.reason===Mn}function Jn(e){return new c("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 Et(){return new c("backend.internal","Device-pairing poll returned a malformed or unexpected HTTP 200 response.",{status:200,reason:Mn})}function $n(e,t,n){return e!==void 0?At(e,t,"pairing_deadline_elapsed_after_transient_failure"):new c("auth.device_pairing_timeout",`Device-pairing timed out before the browser confirmed \u2014 the pairing window closed, or the CLI reached its ${Un/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?ro:io})}function At(e,t,n){let r=e.details?.status;return new c("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 Be(e,t,n,r){let i=Math.max(1,t-Date.now());try{return await _t(e,mt,{timeoutMs:i})}catch(o){throw o instanceof c?o:o instanceof z?new c("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"?qn:"init_body_timeout"}):new c("transport.network",`Network error while reading the device-pairing ${r} response body from ${n}.`,{status:e.status,stage:r,reason:r==="poll"?Yn:"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 lo(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function co(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 uo(e){if(e)try{let t=JSON.parse(e);if(typeof t.code=="number")return t.code}catch{}}var lr=A(require("path"));var Tt=require("crypto"),a=A(require("fs")),b=A(require("path"));var De=1024*1024,po=5e3,fo=20,ho=3e4,kt=4096,go=new Int32Array(new SharedArrayBuffer(4)),ue=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function $e(e){return e instanceof ue}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},mo=null;function D(){return new c("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Ue(){return(mo??process.platform)!=="win32"}function rr(){if(!Ue())throw D()}function ir(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 de(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function pe(e,t){return e.dev===t.dev&&e.ino===t.ino}function _o(e){Atomics.wait(go,0,0,e)}function or(e){try{return process.kill(e,0),!0}catch(t){return!w(t,"ESRCH")}}function yo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vn(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()||!pe(o,s))throw new Error("credential-store parent changed while it was being inspected");de(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(!pe(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 ue;if(de(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 wo(e,t){if(t.size>De)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(De+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>De)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Xn(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 wo(t,r)}finally{t!==null&&a.default.closeSync(t)}}function Zn(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")&&ir(e))return;throw i}let n=a.default.fstatSync(t),r=R(e,t,n);$(e,r)}finally{t!==null&&a.default.closeSync(t)}ar(b.dirname(e))}function bo(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 ue;de(t,"credential-store replacement target")}function So(e,t){for(let n=0;n<8;n+=1){let r=(0,Tt.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 sr(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 ar(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 Eo(e,t){let n=Buffer.from(t,"utf8");if(n.length>De)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=So(r,i);o=d.fd,s=d.tempPath;let u=a.default.fstatSync(o);if((R(s,o,u).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");sr(o,n),a.default.fsyncSync(o),R(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),bo(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{}}ar(r)}function Ao(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function ko(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function Lo(e,t){if(t.size>kt)return null;let n=Buffer.alloc(kt+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>kt)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 $(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!pe(n,t))throw new Error("credential-store lock changed while it was being inspected");de(n,"credential-store lock"),a.default.unlinkSync(e)}function Qn(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 u=a.default.lstatSync(e);throw u.isSymbolicLink()||!u.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(u){if(w(u,"ENOENT"))return{state:"absent"};throw u}throw d}let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Lo(n,i);return{state:(o?.target===t&&o?!or(o.pid):Date.now()-i.mtimeMs>=ho)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function To(e,t){for(let n=0;n<8;n+=1){let r=(0,Tt.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 sr(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 Io(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(!pe(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}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(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 vo(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{$(e,n)}catch{}throw a.default.closeSync(t),r}}function B(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");_o(fo)}function tr(e){let t=b.dirname(e),n=b.basename(e),r=Ao(e),i=ko(e),o=To(t,n),s=Date.now()+po,l=!1,d=!1,u=null,h;try{for(;u===null;)try{if(er(i)){B(s,!0);continue}a.default.linkSync(o.claimPath,r),d=!0,u=Io(r,o.stats),l=!0}catch(p){if(d&&!l){try{$(r,o.stats)}catch{}d=!1}if(p instanceof k){B(s,!1);continue}if(!w(p,"EEXIST"))throw p;let g;try{g=Qn(r,n)}catch(y){if(y instanceof k){B(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=vo(i)}catch(f){if(f instanceof k){B(s,!1);continue}throw f}if(y!==null){try{let f;try{f=Qn(r,n)}catch(m){if(m instanceof k){B(s,!1);continue}throw m}f.state==="stale"&&$(r,f.stats)}finally{Lt(y)}continue}}let S;try{S=er(i)}catch(y){if(y instanceof k){B(s,!1);continue}throw y}B(s,S)}}catch(p){h=p}try{$(o.claimPath,o.stats)}catch(p){!w(p,"ENOENT")&&!l&&h===void 0&&(h=p)}if(h!==void 0)throw h;if(u===null)throw new Error("credential-store lock acquisition failed");return u}function Lt(e){try{$(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Oo(e,t){let n=yo(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 nr(e){let t=b.dirname(e),n=b.basename(e);for(let r of a.default.readdirSync(t)){let i=Oo(r,n);if(i===null||or(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(u){if(w(u,"ENOENT")||w(u,"ELOOP"))continue;throw u}let l=a.default.fstatSync(s),d=a.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!pe(l,d))continue;try{de(l,"credential-store orphan")}catch{continue}$(o,l)}catch(l){if(!w(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function fe(e,t,n){if(!Ue()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!Vn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let s=tr(e);try{return nr(e),n({read:()=>Xn(e),remove:()=>Zn(e),write:()=>{throw D()}})}finally{Lt(s)}}if(!t.createParent){let o=!1;try{o=ir(e)}catch{throw D()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!Vn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=tr(e);try{return nr(e),n({read:()=>Xn(e),remove:()=>Zn(e),write:o=>Eo(e,o)})}finally{Lt(i)}}var It="allscale-cli";function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cr(e){return Ct(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new c("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function vt(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Fe(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var U,Ot=!1;function Ro(){return on()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Co(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
+ `,1)[0]==="Cannot find module 'keytar'"}function No(){if(U!==void 0)return U;if(Ro())return Ot=!1,U=null,U;try{U=require("keytar"),Ot=!1}catch(e){Ot=!Co(e),U=null}return U}function ur(){let e=Ue()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new c("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Rt(e){try{return await e()}catch{throw ur()}}var Nt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Rt(()=>this.keytar.getPassword(It,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!cr(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Rt(()=>this.keytar.setPassword(It,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Rt(()=>this.keytar.deletePassword(It,t))}},Po="credentials.json",Pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??lr.join(Le(),Po)}read(t){let n;try{n=t.read()}catch(i){throw $e(i)?vt():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!Ct(r)||!Ct(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw $e(r)?vt():Fe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!cr(r))throw F("plaintext file");return r}}async get(t){try{return fe(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:F("plaintext file")}}async set(t,n){try{fe(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 c?r:Fe()}}async delete(t){try{fe(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof c?n:Fe()}}async clearProfile(t){try{return fe(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof c?n:$e(n)?vt():Fe()}}};function dr(e){if(e.insecureStorage)return rr(),new Pt(e.insecureFilePath);let t=No();if(t)return new Nt(t);throw ur()}async function pr(e,t){await e.get(t)}async function fr(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof c?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 c(r instanceof c?r.code:"storage.unavailable",`${i} ${o}`,r instanceof c?r.details:void 0)}}var Me=class e extends oe{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: "+mn(se)+". The final set is chosen \u2014 and can be overridden \u2014 on that screen, and is checked by the backend on each request. The Wallets read toggle is on by default and grants `wallet:read_only`, which `wallet list` needs. `invoice pay` needs `invoice:all` AND `wallet:all` \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`) and tick the Invoices write tier plus the Wallets Allow-changes tier on the screen (Invoices starts at Read; Allow-changes starts OFF). `wallet send` requires `wallet:all` the same way; every transfer still requires your in-browser confirmation. Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any pairing session is registered \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 and the resulting key is identical. 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}),...oe.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);Sn(t.scopes),En(t.scopes,{allowUnrenderable:t["allow-unrenderable-scopes"]});let n=this.resolveContext(t),r=dr({insecureStorage:n.insecureStorage});if(this.argv.length===0&&!t.yes&&!Ae(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
20
20
  - wait for your approval, then store a scoped agent key (profile: ${n.profile})
21
- `),!await bn("Start device pairing?")))throw new c("user.cancelled","Device pairing cancelled \u2014 no pairing session was created.");await ir(r,n.profile);let o=await Fn(n.apiBase,{scopes:t.scopes,device_label:t["device-label"],onInit:async(g,{pollingDeadlineAt:m})=>{await fo(g,!!t["no-browser"],m)},onPending:g=>{(g===1||g%5===0)&&Z(`Still waiting for approval (poll ${g})...
22
- `)}});await or(r,n.profile,o.tokens);let s=re(),l=dn(s,n.profile,{api_base:n.apiBase,user_type:ho(o.user_type),api_base_source:n.apiBaseSource});l.default||(l.default=n.profile),cn(l),Z(`Saved tokens to ${r.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${n.profile}). Profile metadata: ${Te()}
23
- `);let d=o.tokens.scopes??[],u=typeof o.tokens.agent_key_expires_at=="number"?new Date(o.tokens.agent_key_expires_at*1e3).toISOString():void 0;Z(`Credential: scoped agent key. Scopes${d.length>0?` (${d.join(", ")})`:""} are checked by the backend on each request.
24
- ${u?`The key expires at ${u}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`allscale device-login\` when it expires or is revoked.
25
- `);let f=(t.scopes??[]).filter(g=>!d.some(m=>Ce(m,g)));if(f.length>0){let g=f.filter(E=>!gt(E)),m=g.filter(E=>Pe(E)&&Re.has(j(E))),S=g.filter(E=>ft.has(E)),_=g.filter(E=>pt.has(E));O({event:"scopes_not_granted",requested_not_granted:f,granted:d,..._.length>0?{otp_login_would_grant:_}:{},...S.length>0?{reaches_no_operation:S}:{},...m.length>0?{ungrantable:m}:{}},`warning: requested scope(s) not granted: ${f.join(", ")}. The browser approval screen replaces the requested set with its own selection.
26
- `+(_.length>0?`The screen cannot offer ${_.join(", ")} \u2014 use \`allscale otp-login --scopes <scope>\` for those.
27
- `:"")+(S.length>0?`${S.join(", ")} reaches no operation today \u2014 a key can carry it, but nothing accepts it, so no login path makes it useful.
28
- `:"")+(m.length>0?`${m.join(", ")} is not grantable to new keys at all \u2014 no login path can mint it.
29
- `:""))}return{profile:n.profile,api_base:n.apiBase,user_type:o.user_type,storage:r.kind,verification_code:o.verification_code,device_label:t["device-label"]??void 0,credential:o.credential,...o.tokens.business_id===void 0?{}:{business_id:o.tokens.business_id},...o.tokens.user_email===void 0?{}:{user_email:o.tokens.user_email},scopes:d,...u?{agent_key_expires_at:u}:{}}}};async function fo(e,t,n){let r={verification_url:e.verification_url,verification_code:e.verification_code,polling_deadline_at:new Date(n*1e3).toISOString()};if(v({type:"device_authorization",...r}),O({event:"device_authorization",...r},`
21
+ `),!await vn("Start device pairing?")))throw new c("user.cancelled","Device pairing cancelled \u2014 no pairing session was created.");await pr(r,n.profile);let o=t.scopes,s=pt(o??[]);if(s.implicitOnly.length>0){let f=o!==void 0&&o.length===s.implicitOnly.length;T({event:"implicit_scopes_omitted",omitted:s.implicitOnly},`note: ${s.implicitOnly.join(", ")} ${s.implicitOnly.length>1?"are":"is"} appended automatically to every pairing-minted key \u2014 omitted from the request`+(f?`. No requested scopes remain, so none are sent: the approval screen will offer its DEFAULT selection, not an empty one.
22
+ `:`; the resulting key is identical.
23
+ `))}t["allow-unrenderable-scopes"]&&s.otpLoginOnly.length>0&&T({event:"unrenderable_scopes_forwarded",scopes:s.otpLoginOnly},`warning: this CLI's catalog says the approval screen has no toggle for ${s.otpLoginOnly.join(", ")}; forwarding anyway because --allow-unrenderable-scopes is set. If the screen refuses the whole authorization, mint with \`allscale otp-login --email <email> --scopes <scope>\` instead.
24
+ `);let l=o?.filter(f=>!s.implicitOnly.includes(f)),d=l!==void 0&&l.length===0?void 0:l,u=await Hn(n.apiBase,{scopes:d,device_label:t["device-label"],onInit:async(f,{pollingDeadlineAt:m})=>{await xo(f,!!t["no-browser"],m)},onPending:f=>{(f===1||f%5===0)&&Z(`Still waiting for approval (poll ${f})...
25
+ `)}});await fr(r,n.profile,u.tokens);let h=ie(),p=dn(h,n.profile,{api_base:n.apiBase,user_type:$o(u.user_type),api_base_source:n.apiBaseSource});p.default||(p.default=n.profile),cn(p),Z(`Saved tokens to ${r.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${n.profile}). Profile metadata: ${Te()}
26
+ `);let g=u.tokens.scopes??[],S=typeof u.tokens.agent_key_expires_at=="number"?new Date(u.tokens.agent_key_expires_at*1e3).toISOString():void 0;Z(`Credential: scoped agent key. Scopes${g.length>0?` (${g.join(", ")})`:""} are checked by the backend on each request.
27
+ ${S?`The key expires at ${S}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`allscale device-login\` when it expires or is revoked.
28
+ `);let y=(d??[]).filter(f=>!g.some(m=>ae(m,f)));if(y.length>0){let f=t["allow-unrenderable-scopes"]?y.filter(m=>s.otpLoginOnly.includes(m)):[];T({event:"scopes_not_granted",requested_not_granted:y,granted:g,...f.length>0?{otp_login_would_grant:f}:{}},`warning: requested scope(s) not granted: ${y.join(", ")}. The browser approval screen replaces the requested set with its own selection.
29
+ `+(f.length>0?`The screen narrowed ${f.join(", ")} rather than refusing it \u2014 as this CLI's catalog predicted, it has no toggle for ${f.length>1?"them":"it"}. Mint ${f.length>1?"them":"it"} with \`allscale otp-login --email <email> --scopes <scope>\` instead.
30
+ `:""))}return{profile:n.profile,api_base:n.apiBase,user_type:u.user_type,storage:r.kind,verification_code:u.verification_code,device_label:t["device-label"]??void 0,credential:u.credential,...u.tokens.business_id===void 0?{}:{business_id:u.tokens.business_id},...u.tokens.user_email===void 0?{}:{user_email:u.tokens.user_email},scopes:g,...S?{agent_key_expires_at:S}:{}}}};async function xo(e,t,n){let r={verification_url:e.verification_url,verification_code:e.verification_code,polling_deadline_at:new Date(n*1e3).toISOString()};if(v({type:"device_authorization",...r}),T({event:"device_authorization",...r},`
30
31
  Open this URL to authorize the CLI:
31
32
  ${e.verification_url}
32
33
 
33
- Or visit ${go(e.verification_url)} and enter:
34
+ Or visit ${Do(e.verification_url)} and enter:
34
35
  ${e.verification_code}
35
36
 
36
- Waiting for approval \u2014 the CLI stops polling at ${new Date(n*1e3).toISOString()} (about ${po(n)}).
37
- `),!t)try{await Sn(e.verification_url)}catch(i){let o=i instanceof c?i.message:String(i);Z(`(couldn't open the browser automatically: ${o})
38
- `)}}function po(e){let t=Math.max(0,Math.round(e-Date.now()/1e3));if(t<90)return`${t} second${t===1?"":"s"}`;let n=Math.round(t/60);return`${n} minute${n===1?"":"s"}`}function go(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function ho(e){return e==="business"||e==="employee"||e==="admin"?e:"business"}0&&(module.exports={APPROVAL_SCREEN_SCOPES,UNGRANTABLE_CATEGORIES,approvalScreenCanGrant,isWellFormedScope,scopeCategory,scopeSatisfies});
37
+ Waiting for approval \u2014 the CLI stops polling at ${new Date(n*1e3).toISOString()} (about ${Bo(n)}).
38
+ `),!t)try{await Tn(e.verification_url)}catch(i){let o=i instanceof c?i.message:String(i);Z(`(couldn't open the browser automatically: ${o})
39
+ `)}}function Bo(e){let t=Math.max(0,Math.round(e-Date.now()/1e3));if(t<90)return`${t} second${t===1?"":"s"}`;let n=Math.round(t/60);return`${n} minute${n===1?"":"s"}`}function Do(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function $o(e){return e==="business"||e==="employee"||e==="admin"?e:"business"}0&&(module.exports={APPROVAL_SCREEN_SCOPES,UNGRANTABLE_CATEGORIES,approvalScreenCanGrant,isWellFormedScope,scopeCategory,scopeSatisfies});
39
40
  //# sourceMappingURL=device-login.js.map