@allscale/cli 1.0.1 → 1.0.3

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.
Files changed (34) hide show
  1. package/README.md +92 -12
  2. package/dist/commands/build-info.js +12 -12
  3. package/dist/commands/claim-link/claim.js +10 -10
  4. package/dist/commands/claim-link/create.js +31 -31
  5. package/dist/commands/claim-link/get.js +13 -13
  6. package/dist/commands/claim-link/list.js +12 -12
  7. package/dist/commands/claim-link/status.js +11 -11
  8. package/dist/commands/describe.js +11 -11
  9. package/dist/commands/device-login.js +28 -27
  10. package/dist/commands/invoice/get.js +12 -12
  11. package/dist/commands/invoice/list.js +12 -12
  12. package/dist/commands/invoice/pay.js +41 -37
  13. package/dist/commands/invoice/received.js +12 -12
  14. package/dist/commands/invoice/send.js +29 -29
  15. package/dist/commands/invoice/sent.js +11 -11
  16. package/dist/commands/invoice/update.js +13 -13
  17. package/dist/commands/logout.js +19 -13
  18. package/dist/commands/operations.js +11 -11
  19. package/dist/commands/otp-login.js +17 -17
  20. package/dist/commands/otp-send.js +11 -11
  21. package/dist/commands/payout/send.js +14 -14
  22. package/dist/commands/payout/status.js +12 -12
  23. package/dist/commands/scope.js +16 -16
  24. package/dist/commands/store/create.js +16 -16
  25. package/dist/commands/transaction/get.js +12 -12
  26. package/dist/commands/transaction/list.js +12 -12
  27. package/dist/commands/wallet/list.js +12 -12
  28. package/dist/commands/wallet/send.js +27 -27
  29. package/dist/commands/whoami.js +14 -12
  30. package/dist/hooks/version-suffix.js +1 -1
  31. package/dist/index.js +11 -11
  32. package/dist/lib/help.js +10 -7
  33. package/oclif.manifest.json +24 -11
  34. package/package.json +1 -1
@@ -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.
9
- The CLI default is now ${ne} (production), but a saved profile wins over the default,
1
+ "use strict";var br=Object.create;var me=Object.defineProperty;var Sr=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var Ar=Object.getPrototypeOf,kr=Object.prototype.hasOwnProperty;var Lr=(e,t)=>{for(var n in t)me(e,n,{get:t[n],enumerable:!0})},Ut=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Er(t))!kr.call(e,i)&&i!==n&&me(e,i,{get:()=>t[i],enumerable:!(r=Sr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?br(Ar(e)):{},Ut(t||!e||!e.__esModule?me(n,"default",{value:e,enumerable:!0}):n,e)),vr=e=>Ut(me({},"__esModule",{value:!0}),e);var Ko={};Lr(Ko,{APPROVAL_SCREEN_SCOPES:()=>X,UNGRANTABLE_CATEGORIES:()=>le,approvalScreenCanGrant:()=>pt,default:()=>Ge,isWellFormedScope:()=>Ne,scopeCategory:()=>D,scopeSatisfies:()=>ce});module.exports=vr(Ko);var O=require("@oclif/core");var Ft="public",Mt="https://app.allscale.io";var Gt=["https://app.allscale.io"];var qe="Override the API base URL (public builds accept only https://app.allscale.io)";var He="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Kt(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 Yt(e){return Kt(e)!==null}function _e(e){let t=Kt(e);return t!==null&&Gt.includes(t.origin)}function We(e){return _e(e)}function Z(){return"".trim()||void 0}function Y(){return"public"}function x(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 Q(){{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 c=typeof d=="string"?d.trim():"";i.push({base:s.trim(),key:l,keyId:c.length>0?c:"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 Tr={"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};var Ir=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 Ze(e){return(typeof e=="string"?e:String(e??"")).replace(Ir,"")}var Or=64;function Xe(e,t=new Map,n=0){if(typeof e=="string")return Ze(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Or)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let l of e)s.push(Xe(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:Xe(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var u=class extends Error{code;details;constructor(t,n,r){super(Ze(n)),this.code=t,this.details=r&&Xe(r),this.name="AllscaleError"}get exitCode(){return Tr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function qt(e){if(e instanceof u)return e;if(e instanceof Error){if(Nr(e)){let t=xr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new u("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new u("internal",e.message,{name:e.name})}return new u("internal","Unknown error",{value:String(e)})}var Rr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Cr=[/^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 Nr(e){if(Pr(e))return!0;let t=e.name??"";return Rr.has(t)?t==="CLIError"?Ve(e,"parse")||jt(e.message):!0:jt(e.message)}function Pr(e){if(!Ve(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ve(e,"parse")}function jt(e){return e?Ze(e).split(`
2
+ `).some(t=>Cr.some(n=>n.test(t.trim()))):!1}function Ve(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function xr(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 _=A(require("fs")),ke=A(require("path")),Qt=A(require("crypto"));var Br="...<truncated>",Dr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,$r=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,rt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Qe=String.raw`(?:proxy[_-]?)?authorization`,Ur=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Qe}"|'${Qe}'|${Qe})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${rt}`,"gi"),Fr=/\b(https?:\/\/)[^\s/?#]+@/gi,Mr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Gr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,zt=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)`,Wt=zt(Mr),Kr=zt(Gr),Yr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Wt}"|'${Wt}'|${Kr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${rt}`,"gi"),et=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)`,jr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${et}"|'${et}'|${et})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${rt}`,"g");function ye(e){return e.replace(Fr,"$1<redacted>@").replace(Dr,"<redacted-jwt>").replace(Ur,"$1$2$3<redacted>").replace(Yr,"$1$2<redacted>").replace(jr,"$1$2<redacted>").replace($r,"Bearer <redacted>")}var qr=/(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 we(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return qr.test(t)}function Jt(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 be(e,t,n=Br){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 c of n){let h=Buffer.byteLength(c,"utf8");if(d+h>t)break;l+=c,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 be(Jt(ye(e)),t)}var tt=100,Hr=8,Wr=8*1024;function Se(){return{remaining:Wr}}function nt(e,t){let n=Math.min(16384,t.remaining),r=be(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function j(e,t,n=0,r={}){if(n>Hr)return nt("<truncated>",t);if(typeof e=="string"){let i=ye(e);return nt(r.escapeControls?Jt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,tt),o=i.map(s=>j(s,t,n+1,r));return e.length>i.length&&o.push(nt(`<${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,tt))i[s]=j(l,t,n+1,r);return o.length>tt&&(i.output_truncated=!0),i}return e}var Ee=require("process");var Ae=!1;function it(e){Ae=e}function Vt(){return Ae}function ee(e){Ae||Ee.stderr.write(e)}var Xt="1";function v(e,t){if(Ae){let n={...e};delete n.version;let r=Se(),i={event:n.event,...n},o=j(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Xt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Xt,event:o.event,output_truncated:!0})),Ee.stderr.write(`${s}
4
+ `)}else Ee.stderr.write(t)}var Zt="2",H=null,L=null,W=!1,te=!1;function zr(){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=Qt.randomBytes(4).toString("hex");return ke.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var ot=64*1024*1024,Jr=null;function st(e={}){if(e.quiet&&(te=!0),W)return;let t=zr();if(!t)return;H=null;let n=null;try{if((Jr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=ke.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),c=d.mode&511;if(!d.isDirectory()||(c&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${c.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{}te||v({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}H=t,L=n,W=!0}var Xr=[/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 Vr(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.some(n=>n.test(t))}function en(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)Vr(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 Qr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:en(e.url)}:e}function ei(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=j(i,Se()),s=JSON.stringify({version:Zt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Zt,timestamp:t,type:r,output_truncated:!0})),s}function I(e){if(!W||!H||L===null)return;let t=Qr(e),n=ei(t);try{if(_.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>ot){W=!1;try{_.closeSync(L)}catch{}L=null,te||v({event:"sidecar_disabled",reason:"size_limit",...H===null?{}:{path:E(H)},max_bytes:ot},`${E(`[allscale] sidecar exceeded ${ot} bytes; disabling it for the rest of this run. Rotate or remove ${H}, 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(W=!1,L!==null){try{_.closeSync(L)}catch{}L=null}try{te||v({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 tn=en;function nn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function ne(){if(te=!1,W=!1,L!==null){try{_.closeSync(L)}catch{}L=null}}function Le(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||nn()||!t}var re=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"]),ti=new Set(Array.from(re).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),ni=Array.from(re).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),ri=new Set(["--otp-stdin","--password-stdin"]);function at(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(re.has(s)){t.push(`${s}=<redacted>`);continue}}}if(re.has(r)){t.push(r),n+1<e.length&&(re.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(ti.has(o)){t.push(`${o}<redacted>`);continue}}let i=ri.has(r)?void 0:ni.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function rn(e){I({type:"error",code:e.code,message:E(e.message)}),I({type:"command-end",ok:!1,exitCode:e.exitCode}),ne()}var ie=Z()??Mt,J={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function lt(e){return Yt(e)?new URL(e).origin:null}function B(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function on(){let e=process.env[J.TOKEN]?.trim();return e&&e.length>0?e:void 0}function ct(){let e=process.env[J.PROFILE]?.trim();return e&&e.length>0?e:void 0}function oe(){let e=process.env[J.API_BASE]?.trim();return e&&e.length>0?e:void 0}function sn(){let e=process.env[J.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function an(){let e=process.env[J.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ln(){let e=process.env[J.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function cn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(Z()===void 0&&ie!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${ie} (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
- 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:
13
+ To move to production, run: allscale device-login --api-base ${ie}
14
+ `}var T=A(require("fs")),un=A(require("os")),ut=A(require("path")),ve=A(require("@iarna/toml"));var si=".allscale",ai="config.toml";function Te(){return ut.join(un.homedir(),si)}function Ie(){return ut.join(Te(),ai)}function se(){let e=Ie();if(!T.existsSync(e))return{};let t=T.readFileSync(e,"utf-8");try{return ve.parse(t)}catch(n){throw new u("internal",`Failed to parse ${e}: ${n.message}`)}}function dn(e){let t=Te();T.existsSync(t)||T.mkdirSync(t,{recursive:!0,mode:448});let n=ve.stringify(e),r=Ie();T.writeFileSync(r,n,{mode:384});try{T.chmodSync(r,384)}catch{}}function pn(e,t){return e.profile?.[t]}function fn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function hn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new u("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function Oe(e){if(!_e(e))throw new u("input.invalid",`Refusing to send credentials to API base ${B(e)}. `+He)}function dt(e){let t=ci(e);if(t)throw new u("input.invalid",t.message)}function li(){let e=Z();if(e===void 0)return;let t=Q();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function ci(e){let t=li();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,i=lt(e),o=n.map(l=>lt(l)).filter(l=>l!==null);if(i!==null&&o.includes(i))return;let s=n.map(l=>B(l)).join(", ");return{message:r?`Refusing to send to ${B(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${B(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var ui=require("@noble/hashes/sha3");var gn=["USDT","USDC"];var Is=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var di="unknown_otp_id",pi="invalid_code",fi="expired_code";function hi(e){return`'${e.replace(/'/g,"'\\''")}'`}function mn(e){return`Run \`allscale otp-send --email ${hi(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var gi=new Map([[di,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${mn(t)}`],[pi,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[fi,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${mn(t)}`]]);var _n=[...gi.keys()];var N=require("@oclif/core"),ae=class e extends O.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:O.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:O.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:Y()==="public"}),"api-base":O.Flags.string({description:qe,helpGroup:"GLOBAL",hidden:Y()==="public"}),"insecure-storage":O.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{it(this.jsonEnabled()),st(),I({type:"session-start",command:this.id??"",argv:at(this.argv)});let t=this.constructor;if(Y()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new u("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new u("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&oe()!==void 0)throw new u("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=Le(this.jsonEnabled()),r=this.argv.length===0&&!n&&ki(t)?this.config.findCommand(this.id??""):void 0;if(r){ne();let o=await(0,O.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!ln())throw this.argv.length>0&&await this.parse(),new u("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return I({type:"command-end",ok:!0}),ne(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ht(i),{data:i})}catch(t){let n=qt(t);rn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{it(!1)}}resolveSessionApiBaseChain(t){let n=se(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||ct()!==void 0,s=hn(n,r,ct()),l=pn(n,s),d=Y()==="public"&&oe()!==void 0,c=i??(d?void 0:oe()),h=c??l?.api_base??ie,p=cn({resolvedApiBase:h,fromExplicitOverride:c!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,v({event:"legacy_staging_profile",api_base:h,profile:s},p)),{apiBase:h,explicitApiBase:c,envApiBaseIgnored:d,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Oe(n),n}resolveContext(t){if(Y()==="public"){if(t.token!==void 0)throw new u("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new u("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&oe()!==void 0)throw new u("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:l,profileApiBase:d,profileExplicit:c}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Oe(i),dt(i)),{apiBase:i,profile:l,token:n??on(),insecureStorage:r||sn(),apiBaseSource:o!==void 0?"explicit":d!==void 0?"profile":"default",profileExplicit:c,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${Ai(t)}
15
+ `)}};var mi=/_(removed|cleared|count|total)$/i;function _i(e,t){return typeof t=="number"&&mi.test(e)}var yi=new Set(gn);function wi(e,t){return e==="token_symbol"&&typeof t=="string"&&yi.has(t)}var bi=new Set(_n);function Si(e,t){return e==="otp_reason"&&typeof t=="string"&&bi.has(t)}var Re=100;function Ce(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Re),r=n.map(i=>Ce(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Re))n[i]=we(i)&&!_i(i,o)&&!wi(i,o)&&!Si(i,o)?"<redacted>":Ce(o,t+1);if(r.length>Re){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Re} more keys`}return n}if(typeof e=="string"){let n=Ei(e);return n!==void 0?E(JSON.stringify(Ce(n,t+1))):E(e)}return e}function Ei(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Ai(e){let t=Vt()?void 0:2,n=Ce(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:E(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function ki(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}function yn(e){let t=new Map;for(let n of e){let r=n.lastIndexOf(":");if(r===-1){t.set(n,t.get(n)??new Set);continue}let i=n.slice(0,r),o=n.slice(r+1),s=t.get(i)??new Set;s.add(o),t.set(i,s)}return[...t].map(([n,r])=>{if(r.size===0)return n;if(r.size===1)return`${n}:${[...r][0]}`;let i=["read_only","all"].filter(o=>r.has(o));for(let o of r)i.includes(o)||i.push(o);return`${n}:{${i.join(",")}}`}).join(", ")}var wn=new Set;var bn=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),X=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),le=new Set(["payroll","admin:user","admin:org","admin:audit"]);function D(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function ce(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}function pt(e){return[...X].some(t=>ce(t,e))}function Ne(e){let t=e.lastIndexOf(":");if(t<=0||t===e.length-1)return!1;let n=e.slice(t+1);return n==="read_only"||n==="all"}var Sn=new Set(["cli_op:all"]),En=new Set([...Sn].map(D));function Li(e){return[...Sn].some(t=>ce(t,e))}var ft=new Set([...[...bn,...X,...wn].map(D),...le,...En]);function An(e,t){return vi({known:ft,ungrantable:le,implicit:En,renderedAbove:e,blocksUngrantableLocally:t?.blocksUngrantableLocally??!1})}function P(e,t,n){return e===1?t:n}function vi(e){let{known:t,ungrantable:n,implicit:r}=e,i=new Set([...e.renderedAbove].map(c=>D(c))),o=[...t].filter(c=>n.has(c)).sort(),s=[...t].filter(c=>r.has(c)).sort(),l=[...t].filter(c=>i.has(c)&&!n.has(c)&&!r.has(c)).sort(),d=[];return t.size>0&&d.push(`Every category recognised as a spelling, so a usable value can be found without guessing: ${[...t].sort().join(", ")}.`),l.length>0&&d.push(`${l.join(", ")} ${P(l.length,"carries","carry")} the tiers listed above.`),o.length>0&&d.push(`${o.join(", ")} ${P(o.length,"is","are")} in the catalog but granted to NOBODY \u2014 every mint path drops ${P(o.length,"it","them")}, so no login command can deliver ${P(o.length,"it","them")}`+(e.blocksUngrantableLocally?`; this command rejects ${P(o.length,"it","them")} locally, before any pairing session.`:`, and requesting ${P(o.length,"it","them")} gains nothing.`)),s.length>0&&d.push(`${s.join(", ")} ${P(s.length,"is","are")} attached to every key the backend mints, by both login commands, without being requested \u2014 you never need to ask for ${P(s.length,"it","them")}, and asking is not an error.`),`${d.join(" ")} `}function Ti(e){return e.filter(t=>!Ne(t)||!ft.has(D(t)))}function kn(e){if(!e||e.length===0)return;let t=Ti(e);if(t.length!==0)throw new u("input.invalid",`Unrecognised --scopes value${t.length>1?"s":""}: ${t.join(", ")}. Scope strings are <category>:<tier>, where tier is read_only or all. Known categories: ${[...ft].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}function ht(e){let t={otpLoginOnly:[],reachesNothing:[],ungrantable:[],implicitOnly:[]};for(let n of e){if(!Ne(n))continue;if(Li(n)){t.implicitOnly.push(n);continue}let r=D(n);if(le.has(r)){t.ungrantable.push(n);continue}if(!pt(n)){if(wn.has(n)){t.reachesNothing.push(n);continue}if(bn.has(n)){t.otpLoginOnly.push(n);continue}}}return t}function Ln(e,t){if(!e||e.length===0)return;let n=ht(e),{otpLoginOnly:r,reachesNothing:i,ungrantable:o}=n,s=t?.allowUnrenderable?[]:r,l=[...s,...i,...o];if(l.length!==0)throw new u("input.invalid",`The browser approval screen cannot deliver --scopes value${l.length>1?"s":""}: ${l.join(", ")}. `+(s.length>0?`The screen has no toggle for ${s.join(", ")} \u2014 mint ${s.length>1?"them":"it"} with \`allscale otp-login --email <email> --scopes <scope>\` instead. If your web app's approval screen does offer ${s.length>1?"these":"it"} (this CLI's copy of the screen's catalog can lag a frontend release), re-run with --allow-unrenderable-scopes to let the screen decide. `:"")+(i.length>0?`${i.join(", ")} reaches no operation today \u2014 a key can carry it, but nothing accepts it, so no login path makes it useful. `:"")+(o.length>0?`${o.join(", ")} is not grantable to new keys at all \u2014 no login path can mint it; remove it. `:"")+"Nothing was sent \u2014 no pairing session was created, no browser was opened, and no key was issued.",{unpairable_scopes:n})}var In=require("child_process");function vn(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Ii=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Oi(e,t,n,r){if(vn(e.CI)||Ii.some(s=>vn(e[s])))return"ci";let o=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":n===!0||r===!0?null:"no-tty"}function Ri(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+t+n:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+t+n:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+t+n}async function On(e,t={}){if(!We(e))throw new u("input.invalid",`Refusing to launch browser for untrusted origin: ${B(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new u("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let o=i?null:Oi(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new u("wallet.requires_browser_auth",Ri(o));if(r==="linux"&&!n.DISPLAY&&!i)throw new u("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let s=Ci(r,i);await Ni(s.command,[...s.args,e])}function Ci(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Ni(e,t){return new Promise((n,r)=>{let i;try{i=(0,In.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Tn(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(Tn(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function Tn(e,t){return new u("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var gt=require("process"),Rn=require("readline");async function Cn(e){let t=(0,Rn.createInterface)({input:process.stdin,output:gt.stderr}),n;try{let r=await new Promise(o=>{let s=!1,l=d=>{s||(s=!0,o(d))};t.on("SIGINT",()=>l(void 0)),t.on("close",()=>l(void 0)),n=()=>l(void 0),process.on("SIGINT",n),t.question(`${e} [Y/n] `,l)});if(r===void 0)return gt.stderr.write(`
16
+ `),!1;let i=r.trim().toLowerCase();return i===""||i==="y"||i==="yes"}finally{n&&process.removeListener("SIGINT",n),t.close()}}var Nn=A(require("crypto")),Pn=A(require("fs")),xn=A(require("path"));var Pi="key-id",xi="x-allscale-cli-version",mt="cli-1",Bi="aScaLe_cli_obf_v1",Di="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function $i(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var Ui=$i(Di,Bi),Fi=`Bearer ${Ui}`;function Bn(e,t){let n=Je(e);if(n!==null)return t.find(r=>Je(r.base)===n)}function Mi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=Q();if(t.length>0){let r=Bn(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Gi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=Q();if(t.length>0){let r=e!==void 0?Bn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():mt}if(!x(t[0].base))return mt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():mt}function Ki(){return"1.0.3"}function Yi(){return new u("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Pe(e,t){let n=Mi(t);if(!n)throw Yi();let r=Gi(t),i=Math.floor(Date.now()/1e3).toString(),o=Nn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[xi]:Ki()};return r.length>0&&(s[Pi]=r),s}function xe(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ji=500,qi=8,Dn=100;function _t(e,t=0){if(t>qi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Dn),r=n.map(i=>_t(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,Dn))n[r]=we(r)?"<redacted>":_t(i,t+1);return n}return e}function Hi(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function ue(e,t=ji){let n=Hi(e),r=n===void 0?ye(e):JSON.stringify(_t(n));return be(r,t)}var yt=256*1024,Be=class extends u{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},V=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function wt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,d,c=n.timeoutMs,h=c===void 0?void 0:new Promise((p,g)=>{d=setTimeout(()=>{g(new V(e.status,c))},c),d.unref?.()});try{for(;;){let p=o.read(),{done:g,value:S}=h?await Promise.race([p,h]):await p;if(g)break;if(l+=S.byteLength,l>t)throw o.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);s.push(Buffer.from(S))}}catch(p){throw p instanceof V&&o.cancel(p).catch(()=>{}),p}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var Ra=32*1024*1024,Ca=4*1024*1024;function Wi(e,t){if(!(e<300||e>=400))throw new u("transport.network",`API returned HTTP ${e} (a redirect) for ${tn(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function bt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Wi(e.status,e.url)}}var $n="--dns-result-order=ipv4first";async function de(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),d=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||l)&&(i||t!==void 0&&d)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let h=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new u("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${$n} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...h?{cf_ray:h}:{},ipv4_workaround:`NODE_OPTIONS=${$n}`})}var zi=2014;function Ji(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function Xi(e){return Ji(e,zi)}function St(e,t){if(!(e>=200&&e<300)&&Xi(t))throw new u("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?ue(t):t})}var Vi={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Un(e){if(typeof e=="string")return e;if(typeof e=="number")return Vi[e]??`user_type_${e}`}function Fn(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var Zi="/api/public/auth/cli_authorize_init",Qi="/api/public/auth/cli_authorize_poll",Et=1e4,At=1e4,eo=1e3,to=3,no=3e4,Gn=900,Kn="empty_response",Yn="invalid_response",jn="poll_fetch_failure",qn="poll_request_timeout",Hn="poll_body_failure",Wn="poll_body_timeout",ro="approved_credential_mismatch",io="pairing_expired_backend_ttl",zn="pairing_token_unrecognized",oo="pairing_token_unrecognized_after_window_closed",so="pairing_deadline_backend_ttl",ao="pairing_deadline_cli_ceiling";async function lo(e,t={}){let n=new URL(Zi,e).toString(),r={credential_mode:"agent_key"};t.scopes!==void 0&&(r.scopes=t.scopes),t.device_label!==void 0&&(r.device_label=t.device_label);let i=JSON.stringify(r),o=Pe(xe(r),e),s=Date.now()+Et,l;try{l=await Zn(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i},Et)}catch(p){throw Xn(n,p,"init",Et)}if(await de(l),l.status===429)throw new u("rate_limited","Device-pairing init was rate-limited.",{status:429});if(await bt(l),l.status!==200){let p=await De(l,s,n,"init");throw await de(l,p),St(l.status,p),new u(l.status>=500?"backend.internal":"input.invalid",`Device-pairing init failed: HTTP ${l.status}`,{status:l.status,body:ue(p)})}let c=po(await De(l,s,n,"init")).data??{};for(let p of["polling_token","verification_code","verification_url"])if(typeof c[p]!="string"||c[p].length===0)throw new u("backend.internal",`Device-pairing init response missing required field: ${p}`);if(typeof c.expires_at!="number"||c.expires_at<=0)throw new u("backend.internal","Device-pairing init response missing or invalid expires_at");let h=typeof c.poll_interval=="number"&&c.poll_interval>0?c.poll_interval:2;return{polling_token:c.polling_token,verification_code:c.verification_code,verification_url:c.verification_url,expires_at:c.expires_at,poll_interval:h}}async function co(e,t,n=At){let r=new URL(Qi,e).toString(),i={polling_token:t},o=JSON.stringify(i),s=Pe(xe(i),e),l=Number.isFinite(n)&&n>0?Math.max(1,Math.min(At,Math.floor(n))):At,d=Date.now()+l,c;try{c=await Zn(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s},body:o},l)}catch(C){throw Xn(r,C,"poll",l)}if(await de(c),c.status===429)throw new u("rate_limited","Device-pairing poll was rate-limited.",{status:429});if(await bt(c),c.status!==200){let C=await De(c,d,r,"poll");await de(c,C),St(c.status,C);let K=ho(C);if(K===7510)throw Vn({backendCode:K,status:c.status,reason:io});if(K===7511){let $t=fo(c.headers);throw new u("auth.no_token","The backend no longer recognizes this pairing session, so no credential could be collected. Nothing was stored locally. Re-run `allscale device-login` to get a new verification code. If you already approved this pairing in the browser, it may have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard.",{status:c.status,backend_code:K,reason:zn,...$t===null?{}:{server_now:$t}})}throw K===7530?new u("input.invalid","None of the approved scopes can be granted to this account, so no key was issued. Re-run `allscale device-login` and approve different scopes.",{status:c.status,backend_code:K}):new u(c.status>=500?"backend.internal":"input.invalid",`Device-pairing poll failed: HTTP ${c.status}`,{status:c.status,body:ue(C)})}let h=await De(c,d,r,"poll");if(h.trim().length===0)throw new u("backend.internal","Device-pairing poll returned an empty HTTP 200 response.",{status:200,reason:Kn});let p;try{p=JSON.parse(h)}catch{throw kt()}if(p===null||typeof p!="object"||Array.isArray(p))throw kt();let g=p,S=g.data?.status;if(S==="pending")return{status:"pending"};if(S!=="approved")throw kt();let y=Un(g.data?.user_type)??"business",f=g.data?.scopes,m=Array.isArray(f)&&f.every(C=>typeof C=="string")?f:void 0,_r=m&&m.length>0?{scopes:m}:{},Ke=g.data?.agent_key;if(typeof Ke!="string"||Ke.length===0)throw new u("backend.internal","Requested a scoped agent key, but the backend approved a legacy full-permission cookie session \u2014 it may not support scoped keys yet, or a rolling deploy may be in progress. Refusing to store the broader credential. The one-shot approval was consumed, so do not start a new pairing blindly; review your active CLI keys in the AllScale web dashboard first, before re-running `allscale device-login`.",{status:200,outcome_ambiguous:!0,reason:ro,expected_credential:"agent_key"});let Ye=g.data?.agent_key_expires_at,je=g.data?.business_id,yr=typeof je=="string"&&je.length>0?{business_id:je}:{},Dt=Fn(g.data?.user_email),wr=Dt===void 0?{}:{user_email:Dt};return{status:"approved",user_type:y,credential:"agent_key",tokens:{access_token:"",refresh_token:"",agent_key:Ke,...typeof Ye=="number"&&Ye>0?{agent_key_expires_at:Ye}:{},user_type:y,api_base:e,..._r,...yr,...wr}}}async function Jn(e,t){let n=await lo(e,{scopes:t.scopes,device_label:t.device_label}),r=t._now??(()=>Math.floor(Date.now()/1e3)),i=typeof t._maxWallSeconds=="number"&&t._maxWallSeconds>0?t._maxWallSeconds:Gn,o=Math.min(n.expires_at,r()+i),s=o>=n.expires_at;await t.onInit(n,{pollingDeadlineAt:o});let l=t._sleep??(S=>new Promise(y=>{setTimeout(y,S)})),d=Math.max(eo,n.poll_interval*1e3),c=0,h=d,p=0,g;for(;;){let S=(o-r())*1e3;if(S<=0)throw Mn(g,p,s);await l(Math.min(h,S));let y=(o-r())*1e3;if(y<=0)throw Mn(g,p,s);c+=1;let f;try{f=await co(e,n.polling_token,y)}catch(m){if(g!==void 0&&m instanceof u&&m.code==="auth.no_token")throw Lt(g,p,"invalid_polling_token_after_transient_failure");if(m instanceof u&&m.code==="auth.no_token"&&m.details?.reason===zn&&typeof m.details.server_now=="number"&&m.details.server_now>=n.expires_at)throw Vn({backendCode:7511,...typeof m.details.status=="number"?{status:m.details.status}:{},reason:oo});if(!uo(m))throw m;if(p+=1,g=m,p>to)throw Lt(m,p,"transient_retry_budget_exhausted");h=Math.min(no,d*2**p);continue}if(f.status==="approved")return{...f,verification_code:n.verification_code};p=0,g=void 0,h=d,t.onPending?.(c)}}function Xn(e,t,n,r){return t instanceof Error&&t.name==="AbortError"?new u("transport.timeout",`Device-pairing ${n} against ${e} timed out after ${r}ms.`,{timeout_ms:r,stage:n,reason:n==="poll"?qn:"init_request_timeout"}):new u("transport.network",`Network error during device-pairing ${n} against ${e}.`,{stage:n,reason:n==="poll"?jn:"init_fetch_failure"})}function uo(e){if(!(e instanceof u))return!1;if(e.code==="transport.network")return e.details?.stage==="poll"&&(e.details.reason===jn||e.details.reason===Hn);if(e.code==="transport.timeout")return e.details?.stage==="poll"&&(e.details.reason===qn||e.details.reason===Wn);if(e.code!=="backend.internal")return!1;let t=e.details?.status;return typeof t=="number"&&t>=500&&t<=599||e.details?.reason===Kn||e.details?.reason===Yn}function Vn(e){return new u("auth.device_pairing_timeout","The device-pairing approval window closed before the browser confirmed, so no credential was issued and nothing was written to this machine. Re-run `allscale device-login` to get a new verification code. If you approved in the browser just as the window closed, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard.",{reason:e.reason,...e.status===void 0?{}:{status:e.status},...e.backendCode===void 0?{}:{backend_code:e.backendCode}})}function kt(){return new u("backend.internal","Device-pairing poll returned a malformed or unexpected HTTP 200 response.",{status:200,reason:Yn})}function Mn(e,t,n){return e!==void 0?Lt(e,t,"pairing_deadline_elapsed_after_transient_failure"):new u("auth.device_pairing_timeout",`Device-pairing timed out before the browser confirmed \u2014 the pairing window closed, or the CLI reached its ${Gn/60}-minute polling ceiling. Nothing was stored locally. If you approved in the browser after seeing this, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard. Then re-run \`allscale device-login\`.`,{reason:n?so:ao})}function Lt(e,t,n){let r=e.details?.status;return new u("backend.internal","Device-pairing result is ambiguous: a poll response was lost after the browser may have approved the one-shot exchange. A credential may have been issued without reaching this CLI. Do not assume a blind retry is safe; check the browser result, and review your active CLI keys in the AllScale web dashboard, before starting a new pairing.",{outcome_ambiguous:!0,reason:n,transient_failures:t,last_transient_error_code:e.code,...typeof r=="number"?{last_http_status:r}:{}})}async function De(e,t,n,r){let i=Math.max(1,t-Date.now());try{return await wt(e,yt,{timeoutMs:i})}catch(o){throw o instanceof u?o:o instanceof V?new u("transport.timeout",`Device-pairing ${r} response body timed out after ${o.timeoutMs}ms.`,{status:o.status,timeout_ms:o.timeoutMs,stage:r,reason:r==="poll"?Wn:"init_body_timeout"}):new u("transport.network",`Network error while reading the device-pairing ${r} response body from ${n}.`,{status:e.status,stage:r,reason:r==="poll"?Hn:"init_body_failure"})}}async function Zn(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n);i.unref?.();try{return await fetch(e,{...t,redirect:"manual",signal:r.signal})}finally{clearTimeout(i)}}function po(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function fo(e){let t=e.get("date");if(t===null)return null;let n=Date.parse(t);return Number.isNaN(n)?null:Math.floor(n/1e3)}function ho(e){if(e)try{let t=JSON.parse(e);if(typeof t.code=="number")return t.code}catch{}}var dr=A(require("path"));var It=require("crypto"),a=A(require("fs")),b=A(require("path"));var $e=1024*1024,go=5e3,mo=20,_o=3e4,vt=4096,yo=new Int32Array(new SharedArrayBuffer(4)),pe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ue(e){return e instanceof pe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},wo=null;function U(){return new u("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Fe(){return(wo??process.platform)!=="win32"}function sr(){if(!Fe())throw U()}function ar(e){try{return a.default.lstatSync(e),!1}catch(t){if(!w(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(b.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(w(t,"ENOENT"))return!0;throw t}}function w(e,t){return typeof e=="object"&&e!==null&&e.code===t}function fe(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function he(e,t){return e.dev===t.dev&&e.ino===t.ino}function bo(e){Atomics.wait(yo,0,0,e)}function lr(e){try{return process.kill(e,0),!0}catch(t){return!w(t,"ESRCH")}}function So(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qn(e,t){let n=b.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&w(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!he(o,s))throw new Error("credential-store parent changed while it was being inspected");fe(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&b.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),l=a.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function R(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&w(o,"ENOENT")?new k:o}if(!he(n,i))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new pe;if(fe(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Eo(e,t){if(t.size>$e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc($e+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>$e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function er(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(w(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(w(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=R(e,t,n);return Eo(t,r)}finally{t!==null&&a.default.closeSync(t)}}function tr(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(w(i,"ENOENT")&&ar(e))return;throw i}let n=a.default.fstatSync(t),r=R(e,t,n);F(e,r)}finally{t!==null&&a.default.closeSync(t)}ur(b.dirname(e))}function Ao(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(w(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new pe;fe(t,"credential-store replacement target")}function ko(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(w(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function cr(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function ur(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Lo(e,t){let n=Buffer.from(t,"utf8");if(n.length>$e)throw new Error("credential-store file exceeds the maximum supported size");let r=b.dirname(e),i=b.basename(e),o=null,s=null,l=!1;try{let d=ko(r,i);o=d.fd,s=d.tempPath;let c=a.default.fstatSync(o);if((R(s,o,c).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");cr(o,n),a.default.fsyncSync(o),R(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ao(e),a.default.renameSync(s,e),l=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!l&&s!==null)try{a.default.unlinkSync(s)}catch{}}ur(r)}function vo(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function To(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function Io(e,t){if(t.size>vt)return null;let n=Buffer.alloc(vt+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>vt)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function F(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!he(n,t))throw new Error("credential-store lock changed while it was being inspected");fe(n,"credential-store lock"),a.default.unlinkSync(e)}function nr(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(w(d,"ENOENT"))try{let c=a.default.lstatSync(e);throw c.isSymbolicLink()||!c.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(c){if(w(c,"ENOENT"))return{state:"absent"};throw c}throw d}let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Io(n,i);return{state:(o?.target===t&&o?!lr(o.pid):Date.now()-i.mtimeMs>=_o)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Oo(e,t){for(let n=0;n<8;n+=1){let r=(0,It.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let l=a.default.fstatSync(s),d=R(i,s,l,{allowMultipleLinks:!0});return cr(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:d}}catch(l){if(w(l,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw l}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ro(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw w(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!he(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function rr(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(w(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(w(r,"ENOENT"))return!1;throw r}throw n}return R(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Co(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(w(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=R(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{F(e,n)}catch{}throw a.default.closeSync(t),r}}function $(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");bo(mo)}function ir(e){let t=b.dirname(e),n=b.basename(e),r=vo(e),i=To(e),o=Oo(t,n),s=Date.now()+go,l=!1,d=!1,c=null,h;try{for(;c===null;)try{if(rr(i)){$(s,!0);continue}a.default.linkSync(o.claimPath,r),d=!0,c=Ro(r,o.stats),l=!0}catch(p){if(d&&!l){try{F(r,o.stats)}catch{}d=!1}if(p instanceof k){$(s,!1);continue}if(!w(p,"EEXIST"))throw p;let g;try{g=nr(r,n)}catch(y){if(y instanceof k){$(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=Co(i)}catch(f){if(f instanceof k){$(s,!1);continue}throw f}if(y!==null){try{let f;try{f=nr(r,n)}catch(m){if(m instanceof k){$(s,!1);continue}throw m}f.state==="stale"&&F(r,f.stats)}finally{Tt(y)}continue}}let S;try{S=rr(i)}catch(y){if(y instanceof k){$(s,!1);continue}throw y}$(s,S)}}catch(p){h=p}try{F(o.claimPath,o.stats)}catch(p){!w(p,"ENOENT")&&!l&&h===void 0&&(h=p)}if(h!==void 0)throw h;if(c===null)throw new Error("credential-store lock acquisition failed");return c}function Tt(e){try{F(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function No(e,t){let n=So(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function or(e){let t=b.dirname(e),n=b.basename(e);for(let r of a.default.readdirSync(t)){let i=No(r,n);if(i===null||lr(i))continue;let o=b.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(c){if(w(c,"ENOENT")||w(c,"ELOOP"))continue;throw c}let l=a.default.fstatSync(s),d=a.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!he(l,d))continue;try{fe(l,"credential-store orphan")}catch{continue}F(o,l)}catch(l){if(!w(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function ge(e,t,n){if(!Fe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw U();if(!Qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw U()}});let s=ir(e);try{return or(e),n({read:()=>er(e),remove:()=>tr(e),write:()=>{throw U()}})}finally{Tt(s)}}if(!t.createParent){let o=!1;try{o=ar(e)}catch{throw U()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw U()}})}throw U()}if(!Qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=ir(e);try{return or(e),n({read:()=>er(e),remove:()=>tr(e),write:o=>Lo(e,o)})}finally{Tt(i)}}var Ot="allscale-cli";function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pr(e){return Pt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(e){return new u("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function Rt(){return new u("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Me(){return new u("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var M,Ct=!1;function Po(){return an()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function xo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
17
+ `,1)[0]==="Cannot find module 'keytar'"}function Bo(){if(M!==void 0)return M;if(Po())return Ct=!1,M=null,M;try{M=require("keytar"),Ct=!1}catch(e){Ct=!xo(e),M=null}return M}var Do="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function fr(){let e=Fe()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new u("storage.unavailable",`${Do} `+e+" Never silently downgrade in production.")}async function Nt(e){try{return await e()}catch{throw fr()}}var xt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Nt(()=>this.keytar.getPassword(Ot,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!pr(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Nt(()=>this.keytar.setPassword(Ot,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Nt(()=>this.keytar.deletePassword(Ot,t))}},$o="credentials.json",Bt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??dr.join(Te(),$o)}read(t){let n;try{n=t.read()}catch(i){throw Ue(i)?Rt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!Pt(r)||!Pt(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ue(r)?Rt():Me()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!pr(r))throw G("plaintext file");return r}}async get(t){try{return ge(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof u?n:G("plaintext file")}}async set(t,n){try{ge(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof u?r:Me()}}async delete(t){try{ge(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof u?n:Me()}}async clearProfile(t){try{return ge(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof u?n:Ue(n)?Rt():Me()}}};function hr(e){if(e.insecureStorage)return sr(),new Bt(e.insecureFilePath);let t=Bo();if(t)return new xt(t);throw fr()}async function gr(e,t){await e.get(t)}async function mr(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof u?r.message:E(String(r)),o=n.agent_key?"An agent key was already minted for this account but could not be stored, so it is now orphaned: it cannot be listed or revoked from the CLI (key management is control-plane and rejects agent-key sessions). Remove it from the web dashboard.":"The session credential could not be stored, so nothing was persisted \u2014 no key record was created on the account. Re-run the command to authenticate again once storage is available.";throw new u(r instanceof u?r.code:"storage.unavailable",`${i} ${o}`,r instanceof u?r.details:void 0)}}var Ge=class e extends ae{static description="Log in via browser-confirmed device pairing. Use an existing web session or sign in there with Passkey or Email (enter the Email OTP on the webpage), then approve the CLI. The backend mints a scoped agent key \u2014 the credential issued by the current CLI login flows; no web sign-in secret is entered in the terminal.";static examples=["$ allscale device-login","$ allscale device-login --device-label tom-mbp-2026","$ allscale device-login --device-label CI-runner --scopes invoice:read_only --scopes claim_link:all"];static flags={"device-label":N.Flags.string({description:"Human-readable label shown in the browser approval UI so the user can confirm they're authorizing the right device."}),scopes:N.Flags.string({description:"Requested scopes for the eventual agent key, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs the approval screen can grant: "+yn(X)+". The final set is chosen \u2014 and can be overridden \u2014 on that screen, and is checked by the backend on each request. With no requested scopes, every category starts OFF and the user must select at least one. Passing --scopes preselects each exact matching tier the screen can grant. `wallet list` needs `wallet:read_only`. `invoice pay` needs `invoice:all` AND `wallet:all` \u2014 its withdrawal registration rides the same broker op as `wallet send` (backend gates the op, not the verb), and the write tier covers its payer-address read via the implication \u2014 so request both (`--scopes invoice:all --scopes wallet:all`) to preselect both write tiers, or select both Allow-changes switches before authorizing. `wallet send` requires `wallet:all` the same way; every transfer still requires your in-browser confirmation. "+An(X,{blocksUngrantableLocally:!0})+"Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any pairing session is registered \u2014 the same check, and the same exit code, as `otp-login --scopes`. A recognised scope the screen has no toggle for is also rejected locally, with the remediation that actually works: otp-login for operational scopes (or `--allow-unrenderable-scopes` when your web app is newer than this CLI's catalog), nothing for payroll/admin:* \u2014 the approval page refuses the whole authorization when even one requested scope is unrenderable, so deferring the answer to the browser would strand you after a pairing session already exists. An explicitly requested `cli_op:*` is not an error: the backend appends it to every pairing-minted key, so it is omitted from the request with a note. If another requested scope remains, the resulting key is identical; if it was the only one, the approval screen starts every category OFF and requires the user to choose at least one. Only a scope the screen renders and the user declines is reported after the key is minted.",multiple:!0}),"no-browser":N.Flags.boolean({description:"Skip launching the browser; print the verification URL only. Open it in a browser to sign in with Passkey or Email and approve (the Email OTP stays on the webpage). Useful for CI or ssh sessions.",default:!1}),"allow-unrenderable-scopes":N.Flags.boolean({description:"Forward a scope to the approval screen even when this CLI's catalog says the screen has no toggle for it. Escape hatch for a stale catalog: the screen-grantable list above is a MIRROR of the web app's approval screen and can lag a frontend release, and without this flag a lagging mirror makes such a scope impossible to request until a CLI update ships. The screen stays the authority \u2014 if it truly cannot render the scope it refuses the WHOLE authorization after the pairing session exists (the stranding the local check normally prevents), so use this only when you have reason to believe the web app is newer than this CLI. Scopes no login path can mint (payroll/admin:*) are still rejected locally; this flag does not touch them.",default:!1}),yes:N.Flags.boolean({char:"y",description:"Skip the interactive confirmation and start the pairing immediately. Only a BARE invocation is ever prompted, so passing any flag already skips it; use this to say so explicitly. Automation that allocates a pty for stdin/stdout/stderr and runs the command bare is indistinguishable from a human \u2014 that is the case this flag exists for.",default:!1}),...ae.baseFlags};async runCommand(){let{flags:t}=await this.parse(e);kn(t.scopes),Ln(t.scopes,{allowUnrenderable:t["allow-unrenderable-scopes"]});let n=this.resolveContext(t),r=hr({insecureStorage:n.insecureStorage});if(this.argv.length===0&&!t.yes&&!Le(this.jsonEnabled())&&process.stderr.isTTY===!0&&(process.stderr.write(`\`allscale device-login\` will now:
18
18
  - register a new pairing session with ${n.apiBase}
19
19
  - open your browser at the approval page
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 Cn("Start device pairing?")))throw new u("user.cancelled","Device pairing cancelled \u2014 no pairing session was created.");await gr(r,n.profile);let o=t.scopes,s=ht(o??[]);if(s.implicitOnly.length>0){let f=o!==void 0&&o.length===s.implicitOnly.length;v({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 starts every category OFF and requires a choice.
22
+ `:`; the resulting key is identical.
23
+ `))}t["allow-unrenderable-scopes"]&&s.otpLoginOnly.length>0&&v({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,c=await Jn(n.apiBase,{scopes:d,device_label:t["device-label"],onInit:async(f,{pollingDeadlineAt:m})=>{await Uo(f,!!t["no-browser"],m)},onPending:f=>{(f===1||f%5===0)&&ee(`Still waiting for approval (poll ${f})...
25
+ `)}});await mr(r,n.profile,c.tokens);let h=se(),p=fn(h,n.profile,{api_base:n.apiBase,user_type:Go(c.user_type),api_base_source:n.apiBaseSource});p.default||(p.default=n.profile),dn(p),ee(`Saved tokens to ${r.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${n.profile}). Profile metadata: ${Ie()}
26
+ `);let g=c.tokens.scopes??[],S=typeof c.tokens.agent_key_expires_at=="number"?new Date(c.tokens.agent_key_expires_at*1e3).toISOString():void 0;ee(`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=>ce(m,f)));if(y.length>0){let f=t["allow-unrenderable-scopes"]?y.filter(m=>s.otpLoginOnly.includes(m)):[];v({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:c.user_type,storage:r.kind,verification_code:c.verification_code,device_label:t["device-label"]??void 0,credential:c.credential,...c.tokens.business_id===void 0?{}:{business_id:c.tokens.business_id},...c.tokens.user_email===void 0?{}:{user_email:c.tokens.user_email},scopes:g,...S?{agent_key_expires_at:S}:{}}}};async function Uo(e,t,n){let r={verification_url:e.verification_url,verification_code:e.verification_code,polling_deadline_at:new Date(n*1e3).toISOString()};if(I({type:"device_authorization",...r}),v({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 ${Mo(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 ${Fo(n)}).
38
+ `),!t)try{await On(e.verification_url)}catch(i){let o=i instanceof u?i.message:String(i);ee(`(couldn't open the browser automatically: ${o})
39
+ `)}}function Fo(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 Mo(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Go(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