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