@allscale/cli 0.1.0 → 1.0.1

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