@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,22 +1,23 @@
1
- "use strict";var jt=Object.create;var z=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var Vt=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})},je=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jt(t))!qt.call(e,i)&&i!==n&&z(e,i,{get:()=>t[i],enumerable:!(r=Wt(t,i))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?jt(zt(e)):{},je(t||!e||!e.__esModule?z(n,"default",{value:e,enumerable:!0}):n,e)),Zt=e=>je(z({},"__esModule",{value:!0}),e);var dr={};Vt(dr,{default:()=>le});module.exports=Zt(dr);var w=require("@oclif/core");var We="public",Je="https://app.allscale.io";var ze=["https://app.allscale.io"];var ue="Override the API base URL (public builds accept only https://app.allscale.io)";var de="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function qe(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 Ve(e){return qe(e)!==null}function pe(e){let t=qe(e);return t!==null&&ze.includes(t.origin)}function $(){return"".trim()||void 0}function M(){return"public"}function Ze(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Xe(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return fe()}function fe(){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:u}=o;if(typeof a!="string"||a.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:a.trim(),key:l,keyId:d.length>0?d:"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 Qe="drop `--headless` and use the browser-bridge flow with an agent-key session.",et="allscale device-login";var Qt="device-login";function q(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function nt(e,t="default"){return t==="headless"?`No tokens stored for profile '${e}'. Headless signing needs the user token of a legacy JWT session, which agent keys do not carry \u2014 `+Qe:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${q()}\` for headless automation`+"."}function rt(e,t){let n=t.length>0?`Saved profiles: ${t.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${n} Check the spelling first; to deliberately create '${e}', run \`allscale ${Qt} --profile ${e}\`.`}var en={"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},tn=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 me(e){return(typeof e=="string"?e:String(e??"")).replace(tn,"")}var nn=64;function ge(e,t=new Map,n=0){if(typeof e=="string")return me(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=nn)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let l of e)a.push(ge(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:ge(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(me(n)),this.code=t,this.details=r&&ge(r),this.name="AllscaleError"}get exitCode(){return en[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function it(e){if(e instanceof c)return e;if(e instanceof Error){if(sn(e)){let t=ln(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 rn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),on=[/^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 sn(e){if(an(e))return!0;let t=e.name??"";return rn.has(t)?t==="CLIError"?he(e,"parse")||tt(e.message):!0:tt(e.message)}function an(e){if(!he(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&he(e,"parse")}function tt(e){return e?me(e).split(`
2
- `).some(t=>on.some(n=>n.test(t.trim()))):!1}function he(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function ln(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function ot(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var p=E(require("fs")),Z=E(require("path")),pt=E(require("crypto"));var cn="...<truncated>",un=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,dn=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,we=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,ye=String.raw`(?:proxy[_-]?)?authorization`,pn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ye}"|'${ye}'|${ye})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${we}`,"gi"),fn=/\b(https?:\/\/)[^\s/?#]+@/gi,_e=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)`,gn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${_e}"|'${_e}'|${_e})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${we}`,"gi"),Se=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)`,hn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Se}"|'${Se}'|${Se})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${we}`,"g");function st(e){return e.replace(fn,"$1<redacted>@").replace(un,"<redacted-jwt>").replace(pn,"$1$2$3<redacted>").replace(gn,"$1$2<redacted>").replace(hn,"$1$2<redacted>").replace(dn,"Bearer <redacted>")}function at(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 lt(e,t,n=cn){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",u=0;for(let d of n){let h=Buffer.byteLength(d,"utf8");if(u+h>t)break;l+=d,u+=h}return l}let i=t-r,o="",a=0;for(let l of e){let u=Buffer.byteLength(l,"utf8");if(a+u>i)break;o+=l,a+=u}return`${o}${n}`}function y(e,t=16384){return lt(at(st(e)),t)}var Ee=100,mn=8,yn=8*1024;function V(){return{remaining:yn}}function Ae(e,t){let n=Math.min(16384,t.remaining),r=lt(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function P(e,t,n=0,r={}){if(n>mn)return Ae("<truncated>",t);if(typeof e=="string"){let i=st(e);return Ae(r.escapeControls?at(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Ee),o=i.map(a=>P(a,t,n+1,r));return e.length>i.length&&o.push(Ae(`<${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,Ee))i[a]=P(l,t,n+1,r);return o.length>Ee&&(i.output_truncated=!0),i}return e}var Le=require("process");var be=!1;function ke(e){be=e}function ut(){return be}var ct="1";function R(e,t){if(be){let n={...e};delete n.version;let r=V(),i={event:n.event,...n},o=P(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:ct,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:ct,event:o.event,output_truncated:!0})),Le.stderr.write(`${a}
4
- `)}else Le.stderr.write(t)}var dt="2",v=null,_=null,x=!1;function _n(){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=pt.randomBytes(4).toString("hex");return Z.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Oe=64*1024*1024,Sn=null;function ft(){if(x)return;let e=_n();if(!e)return;v=null;let t=null;try{if((Sn??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=Z.dirname(e);if(p.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=p.statSync(n),u=l.mode&511;if(!l.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 r=p.constants.O_NOFOLLOW??0;t=p.openSync(e,p.constants.O_APPEND|p.constants.O_CREAT|p.constants.O_WRONLY|(p.constants.O_NONBLOCK??0)|r,384);let i=p.fstatSync(t),o=p.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`);p.fchmodSync(t,384)}catch(n){if(t!==null)try{p.closeSync(t)}catch{}R({event:"sidecar_disabled",reason:"open_failed",detail:y(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${y(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}v=e,_=t,x=!0}var En=[/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 An(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return En.some(n=>n.test(t))}function wn(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=Ln(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)An(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Ln(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function bn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:wn(e.url)}:e}function kn(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=P(i,V()),a=JSON.stringify({version:dt,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:dt,timestamp:t,type:r,output_truncated:!0})),a}function G(e){if(!x||!v||_===null)return;let t=bn(e),n=kn(t);try{if(p.fstatSync(_).size+Buffer.byteLength(n,"utf8")+1>Oe){x=!1;try{p.closeSync(_)}catch{}_=null,R({event:"sidecar_disabled",reason:"size_limit",...v===null?{}:{path:y(v)},max_bytes:Oe},`${y(`[allscale] sidecar exceeded ${Oe} bytes; disabling it for the rest of this run. Rotate or remove ${v}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
1
+ "use strict";var Jt=Object.create;var V=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Qt=Object.prototype.hasOwnProperty;var en=(e,t)=>{for(var n in t)V(e,n,{get:t[n],enumerable:!0})},Je=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zt(t))!Qt.call(e,i)&&i!==n&&V(e,i,{get:()=>t[i],enumerable:!(r=Xt(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Jt(Vt(e)):{},Je(t||!e||!e.__esModule?V(n,"default",{value:e,enumerable:!0}):n,e)),tn=e=>Je(V({},"__esModule",{value:!0}),e);var Sr={};en(Sr,{default:()=>pe});module.exports=tn(Sr);var w=require("@oclif/core");var Xe="public",Ze="https://app.allscale.io";var Ve=["https://app.allscale.io"];var ge="Override the API base URL (public builds accept only https://app.allscale.io)";var he="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Qe(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 et(e){return Qe(e)!==null}function me(e){let t=Qe(e);return t!==null&&Ve.includes(t.origin)}function Y(){return"".trim()||void 0}function K(){return"public"}function tt(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function nt(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return ye()}function ye(){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:u}=o;if(typeof a!="string"||a.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:a.trim(),key:l,keyId:d.length>0?d:"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 nn="device-login",rn=/^[A-Za-z0-9._-]{1,64}$/;function P(e){return rn.test(e)?e:"<profile>"}function Q(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":P(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function it(e){let t=P(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Q(e)}\` for headless automation.`}function ot(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${nn} --profile ${P(e)}\`.`}var on={"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},sn=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 Ae(e){return(typeof e=="string"?e:String(e??"")).replace(sn,"")}var an=64;function _e(e,t=new Map,n=0){if(typeof e=="string")return Ae(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=an)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let l of e)a.push(_e(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:_e(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(Ae(n)),this.code=t,this.details=r&&_e(r),this.name="AllscaleError"}get exitCode(){return on[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function st(e){if(e instanceof c)return e;if(e instanceof Error){if(un(e)){let t=pn(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 ln=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),cn=[/^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 un(e){if(dn(e))return!0;let t=e.name??"";return ln.has(t)?t==="CLIError"?Se(e,"parse")||rt(e.message):!0:rt(e.message)}function dn(e){if(!Se(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Se(e,"parse")}function rt(e){return e?Ae(e).split(`
2
+ `).some(t=>cn.some(n=>n.test(t.trim()))):!1}function Se(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function pn(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function at(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var p=A(require("fs")),te=A(require("path")),yt=A(require("crypto"));var fn="...<truncated>",gn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,hn=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ke=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ee=String.raw`(?:proxy[_-]?)?authorization`,mn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ee}"|'${Ee}'|${Ee})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ke}`,"gi"),yn=/\b(https?:\/\/)[^\s/?#]+@/gi,_n=String.raw`(?:[A-Za-z0-9]+[_-])*`,Sn=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,ct=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)`,lt=ct(_n),An=ct(Sn),En=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${lt}"|'${lt}'|${An})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ke}`,"gi"),we=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)`,wn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${we}"|'${we}'|${we})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ke}`,"g");function ut(e){return e.replace(yn,"$1<redacted>@").replace(gn,"<redacted-jwt>").replace(mn,"$1$2$3<redacted>").replace(En,"$1$2<redacted>").replace(wn,"$1$2<redacted>").replace(hn,"Bearer <redacted>")}var bn=/(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 dt(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return bn.test(t)}function pt(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 ft(e,t,n=fn){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",u=0;for(let d of n){let m=Buffer.byteLength(d,"utf8");if(u+m>t)break;l+=d,u+=m}return l}let i=t-r,o="",a=0;for(let l of e){let u=Buffer.byteLength(l,"utf8");if(a+u>i)break;o+=l,a+=u}return`${o}${n}`}function h(e,t=16384){return ft(pt(ut(e)),t)}var be=100,Ln=8,kn=8*1024;function ee(){return{remaining:kn}}function Le(e,t){let n=Math.min(16384,t.remaining),r=ft(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function R(e,t,n=0,r={}){if(n>Ln)return Le("<truncated>",t);if(typeof e=="string"){let i=ut(e);return Le(r.escapeControls?pt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,be),o=i.map(a=>R(a,t,n+1,r));return e.length>i.length&&o.push(Le(`<${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,be))i[a]=R(l,t,n+1,r);return o.length>be&&(i.output_truncated=!0),i}return e}var Te=require("process");var Oe=!1;function Ie(e){Oe=e}function ht(){return Oe}var gt="1";function x(e,t){if(Oe){let n={...e};delete n.version;let r=ee(),i={event:n.event,...n},o=R(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:gt,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:gt,event:o.event,output_truncated:!0})),Te.stderr.write(`${a}
4
+ `)}else Te.stderr.write(t)}var mt="2",B=null,_=null,U=!1,j=!1;function Tn(){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=yt.randomBytes(4).toString("hex");return te.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Ce=64*1024*1024,On=null;function ve(e={}){if(e.quiet&&(j=!0),U)return;let t=Tn();if(!t)return;B=null;let n=null;try{if((On??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=te.dirname(t);if(p.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=p.statSync(r),d=u.mode&511;if(!u.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 i=p.constants.O_NOFOLLOW??0;n=p.openSync(t,p.constants.O_APPEND|p.constants.O_CREAT|p.constants.O_WRONLY|(p.constants.O_NONBLOCK??0)|i,384);let o=p.fstatSync(n),a=p.lstatSync(t);if(!o.isFile()||a.isSymbolicLink()||a.dev!==o.dev||a.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`);p.fchmodSync(n,384)}catch(r){if(n!==null)try{p.closeSync(n)}catch{}j||x({event:"sidecar_disabled",reason:"open_failed",detail:h(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${h(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}B=t,_=n,U=!0}var In=[/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 Cn(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return In.some(n=>n.test(t))}function vn(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=Pn(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Cn(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Pn(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Rn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:vn(e.url)}:e}function Nn(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=R(i,ee()),a=JSON.stringify({version:mt,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:mt,timestamp:t,type:r,output_truncated:!0})),a}function D(e){if(!U||!B||_===null)return;let t=Rn(e),n=Nn(t);try{if(p.fstatSync(_).size+Buffer.byteLength(n,"utf8")+1>Ce){U=!1;try{p.closeSync(_)}catch{}_=null,j||x({event:"sidecar_disabled",reason:"size_limit",...B===null?{}:{path:h(B)},max_bytes:Ce},`${h(`[allscale] sidecar exceeded ${Ce} bytes; disabling it for the rest of this run. Rotate or remove ${B}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
6
  `);return}p.appendFileSync(_,`${n}
7
- `)}catch(r){if(x=!1,_!==null){try{p.closeSync(_)}catch{}_=null}try{R({event:"sidecar_disabled",reason:"write_failed",detail:y(r.message)},`${y(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}function gt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function X(){if(x=!1,_!==null){try{p.closeSync(_)}catch{}_=null}}function ht(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||gt()||!t}var Y=$()??Je,U={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 Q(e){return Ve(e)?new URL(e).origin:null}function D(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function mt(){let e=process.env[U.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Te(){let e=process.env[U.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ee(){let e=process.env[U.API_BASE]?.trim();return e&&e.length>0?e:void 0}function yt(){let e=process.env[U.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function _t(){let e=process.env[U.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function St(){let e=process.env[U.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Et(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if($()===void 0&&Y!==""&&"".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 ${Y} (production), but a saved profile wins over the default,
7
+ `)}catch(r){if(U=!1,_!==null){try{p.closeSync(_)}catch{}_=null}try{j||x({event:"sidecar_disabled",reason:"write_failed",detail:h(r.message)},`${h(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}function _t(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function H(){if(j=!1,U=!1,_!==null){try{p.closeSync(_)}catch{}_=null}}function St(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||_t()||!t}var W=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"]),xn=new Set(Array.from(W).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Bn=Array.from(W).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Un=new Set(["--otp-stdin","--password-stdin"]);function Pe(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 a=r.slice(0,o);if(W.has(a)){t.push(`${a}=<redacted>`);continue}}}if(W.has(r)){t.push(r),n+1<e.length&&(W.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(xn.has(o)){t.push(`${o}<redacted>`);continue}}let i=Un.has(r)?void 0:Bn.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function At(e){D({type:"error",code:e.code,message:h(e.message)}),D({type:"command-end",ok:!1,exitCode:e.exitCode}),H()}var z=Y()??Ze,F={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 ne(e){return et(e)?new URL(e).origin:null}function M(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function re(){let e=process.env[F.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Re(){let e=process.env[F.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ie(){let e=process.env[F.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Et(){let e=process.env[F.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function wt(){let e=process.env[F.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function bt(){let e=process.env[F.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Lt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(Y()===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,
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: ${et} --api-base ${Y}
14
- `}var F=E(require("fs")),At=E(require("os")),Ie=E(require("path")),Ce=E(require("@iarna/toml"));var In=".allscale",Cn="config.toml";function Pe(){return Ie.join(At.homedir(),In)}function Pn(){return Ie.join(Pe(),Cn)}function te(){let e=Pn();if(!F.existsSync(e))return{};let t=F.readFileSync(e,"utf-8");try{return Ce.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function wt(e){return Object.keys(e.profile??{}).sort()}function Lt(e,t){return e.profile?.[t]}function bt(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 Ne(e){if(!pe(e))throw new c("input.invalid",`Refusing to send credentials to API base ${D(e)}. `+de)}function kt(e){let t=$();if(t===void 0||Ze(e))return;let n=Q(e),r=Xe();if(r.length>0){let o=r.map(l=>Q(l.base)).filter(l=>l!==null);if(n!==null&&o.includes(n))return;let a=r.map(l=>D(l.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${D(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=Q(t);if(!(n!==null&&n===i))throw new c("input.invalid",`Refusing to send to ${D(e)} \u2014 this build only signs for ${D(t)}. Re-login against this build's environment, or use a build for that one.`)}var Nn=require("@noble/hashes/sha3");var Ot=["USDT","USDC"];var Vr=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Tt=require("@oclif/core"),K=class e extends w.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:w.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:w.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:M()==="public"}),"api-base":w.Flags.string({description:ue,helpGroup:"GLOBAL",hidden:M()==="public"}),"insecure-storage":w.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{ke(this.jsonEnabled()),ft(),G({type:"session-start",command:this.id??"",argv:vn(this.argv)});let t=this.constructor;if(M()==="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&&ee()!==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&&!St())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=ht(this.jsonEnabled()),r=this.argv.length===0&&!n&&Gn(t)?this.config.findCommand(this.id??""):void 0;if(r){X();let o=await(0,w.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 G({type:"command-end",ok:!0}),X(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||ot(i),{data:i})}catch(t){let n=it(t);G({type:"error",code:n.code,message:y(n.message)}),G({type:"command-end",ok:!1,exitCode:n.exitCode}),X(),this.emitError(n),process.exitCode=n.exitCode;return}finally{ke(!1)}}resolveSessionApiBaseChain(t){let n=te(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Te()!==void 0,a=bt(n,r,Te()),l=Lt(n,a),u=i??ee(),d=u??l?.api_base??Y,h=Et({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return h&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,R({event:"legacy_staging_profile",api_base:d,profile:a},h)),{apiBase:d,explicitApiBase:u,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Ne(n),n}resolveContext(t){if(M()==="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&&ee()!==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:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Ne(i),kt(i)),{apiBase:i,profile:a,token:n??mt(),insecureStorage:r||yt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Mn(t)}
15
- `)}},re=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Rn=new Set(Array.from(re).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function vn(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(re.has(o)){t.push(`${o}=<redacted>`);continue}}}if(re.has(r)){t.push(r),n+1<e.length&&(re.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Rn.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var xn=/(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 Bn(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return xn.test(t)}var Un=/_(removed|cleared|count|total)$/i;function Dn(e,t){return typeof t=="number"&&Un.test(e)}var Fn=new Set(Ot);function $n(e,t){return e==="token_symbol"&&typeof t=="string"&&Fn.has(t)}var ne=100;function Re(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,ne),r=n.map(i=>Re(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,ne))n[i]=Bn(i)&&!Dn(i,o)&&!$n(i,o)?"<redacted>":Re(o,t+1);if(r.length>ne){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-ne} more keys`}return n}return typeof e=="string"?y(e):e}function Mn(e){let t=ut()?void 0:2,n=Re(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:y(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Gn(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}function Yn(e,t={}){let n;try{n=wt(te())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",rt(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function It(e){if(e.profileExplicit){let t=Yn(e.profile);if(t)return t}return new c("auth.no_token",nt(e.profile,e.flow))}var Gt=E(require("path"));var Be=require("crypto"),s=E(require("fs")),g=E(require("path"));var ie=1024*1024,Kn=5e3,Hn=20,jn=3e4,ve=4096,Wn=new Int32Array(new SharedArrayBuffer(4)),H=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function oe(e){return e instanceof H}var m=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Jn=null;function k(){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 se(){return(Jn??process.platform)!=="win32"}function Ut(){if(!se())throw k()}function Dt(e){try{return s.default.lstatSync(e),!1}catch(t){if(!f(t,"ENOENT"))throw t}try{let t=s.default.lstatSync(g.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(f(t,"ENOENT"))return!0;throw t}}function f(e,t){return typeof e=="object"&&e!==null&&e.code===t}function j(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function W(e,t){return e.dev===t.dev&&e.ino===t.ino}function zn(e){Atomics.wait(Wn,0,0,e)}function Ft(e){try{return process.kill(e,0),!0}catch(t){return!f(t,"ESRCH")}}function qn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ct(e,t){let n=g.dirname(e);t&&s.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=s.default.lstatSync(n)}catch(o){if(!t&&f(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()||!W(o,a))throw new Error("credential-store parent changed while it was being inspected");j(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&g.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 L(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&&f(o,"ENOENT")?new m:o}if(!W(n,i))throw r.retryOnPathChange?new m: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 H;if(j(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 Vn(e,t){if(t.size>ie)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(ie+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>ie)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Pt(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(f(i,"ENOENT"))try{if(s.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(f(o,"ENOENT"))return null;throw o}throw i}let n=s.default.fstatSync(t),r=L(e,t,n);return Vn(t,r)}finally{t!==null&&s.default.closeSync(t)}}function Nt(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(f(i,"ENOENT")&&Dt(e))return;throw i}let n=s.default.fstatSync(t),r=L(e,t,n);O(e,r)}finally{t!==null&&s.default.closeSync(t)}Mt(g.dirname(e))}function Zn(e){let t;try{t=s.default.lstatSync(e)}catch(n){if(f(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 H;j(t,"credential-store replacement target")}function Xn(e,t){for(let n=0;n<8;n+=1){let r=(0,Be.randomBytes)(12).toString("hex"),i=g.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(f(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function $t(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 Mt(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 Qn(e,t){let n=Buffer.from(t,"utf8");if(n.length>ie)throw new Error("credential-store file exceeds the maximum supported size");let r=g.dirname(e),i=g.basename(e),o=null,a=null,l=!1;try{let u=Xn(r,i);o=u.fd,a=u.tempPath;let d=s.default.fstatSync(o);if((L(a,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");$t(o,n),s.default.fsyncSync(o),L(a,o,s.default.fstatSync(o));let S=o;o=null,s.default.closeSync(S),Zn(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{}}Mt(r)}function er(e){return g.join(g.dirname(e),`.${g.basename(e)}.lock`)}function tr(e){return g.join(g.dirname(e),`.${g.basename(e)}.lock-recovery`)}function nr(e,t){if(t.size>ve)return null;let n=Buffer.alloc(ve+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>ve)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 O(e,t){let n=s.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!W(n,t))throw new Error("credential-store lock changed while it was being inspected");j(n,"credential-store lock"),s.default.unlinkSync(e)}function Rt(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(u){if(f(u,"ENOENT"))try{let d=s.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new m}catch(d){if(f(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=s.default.fstatSync(n),i=L(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=nr(n,i);return{state:(o?.target===t&&o?!Ft(o.pid):Date.now()-i.mtimeMs>=jn)?"stale":"active",stats:i}}finally{n!==null&&s.default.closeSync(n)}}function rr(e,t){for(let n=0;n<8;n+=1){let r=(0,Be.randomBytes)(12).toString("hex"),i=g.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),u=L(i,a,l,{allowMultipleLinks:!0});return $t(a,Buffer.from(JSON.stringify(o),"utf8")),s.default.fsyncSync(a),{claimPath:i,metadata:o,stats:u}}catch(l){if(f(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 ir(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 f(r,"ENOENT")?new m:r}try{let r=s.default.fstatSync(n),i=L(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!W(i,t))throw new m;return{fd:n,lockPath:e,stats:i}}catch(r){throw s.default.closeSync(n),r}}function vt(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(f(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 m}catch(r){if(f(r,"ENOENT"))return!1;throw r}throw n}return L(e,t,s.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&s.default.closeSync(t)}}function or(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(f(r,"EEXIST"))return null;throw r}let n=null;try{n=s.default.fstatSync(t);let r=L(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{O(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");zn(Hn)}function xt(e){let t=g.dirname(e),n=g.basename(e),r=er(e),i=tr(e),o=rr(t,n),a=Date.now()+Kn,l=!1,u=!1,d=null,h;try{for(;d===null;)try{if(vt(i)){b(a,!0);continue}s.default.linkSync(o.claimPath,r),u=!0,d=ir(r,o.stats),l=!0}catch(S){if(u&&!l){try{O(r,o.stats)}catch{}u=!1}if(S instanceof m){b(a,!1);continue}if(!f(S,"EEXIST"))throw S;let ce;try{ce=Rt(r,n)}catch(A){if(A instanceof m){b(a,!1);continue}throw A}if(ce.state==="absent")continue;if(ce.state==="stale"){let A;try{A=or(i)}catch(C){if(C instanceof m){b(a,!1);continue}throw C}if(A!==null){try{let C;try{C=Rt(r,n)}catch(He){if(He instanceof m){b(a,!1);continue}throw He}C.state==="stale"&&O(r,C.stats)}finally{xe(A)}continue}}let Ke;try{Ke=vt(i)}catch(A){if(A instanceof m){b(a,!1);continue}throw A}b(a,Ke)}}catch(S){h=S}try{O(o.claimPath,o.stats)}catch(S){!f(S,"ENOENT")&&!l&&h===void 0&&(h=S)}if(h!==void 0)throw h;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function xe(e){try{O(e.lockPath,e.stats)}finally{s.default.closeSync(e.fd)}}function sr(e,t){let n=qn(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 Bt(e){let t=g.dirname(e),n=g.basename(e);for(let r of s.default.readdirSync(t)){let i=sr(r,n);if(i===null||Ft(i))continue;let o=g.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(d){if(f(d,"ENOENT")||f(d,"ELOOP"))continue;throw d}let l=s.default.fstatSync(a),u=s.default.lstatSync(o);if(!l.isFile()||u.isSymbolicLink()||!u.isFile()||!W(l,u))continue;try{j(l,"credential-store orphan")}catch{continue}O(o,l)}catch(l){if(!f(l,"ENOENT"))throw l}finally{a!==null&&s.default.closeSync(a)}}}function J(e,t,n){if(!se()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw k();if(!Ct(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw k()}});let a=xt(e);try{return Bt(e),n({read:()=>Pt(e),remove:()=>Nt(e),write:()=>{throw k()}})}finally{xe(a)}}if(!t.createParent){let o=!1;try{o=Dt(e)}catch{throw k()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw k()}})}throw k()}if(!Ct(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=xt(e);try{return Bt(e),n({read:()=>Pt(e),remove:()=>Nt(e),write:o=>Qn(e,o)})}finally{xe(i)}}var Ue="allscale-cli";function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yt(e){return Me(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function I(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 De(){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 ae(){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 T,Fe=!1;function ar(){return _t()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function lr(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
- `,1)[0]==="Cannot find module 'keytar'"}function cr(){if(T!==void 0)return T;if(ar())return Fe=!1,T=null,T;try{T=require("keytar"),Fe=!1}catch(e){Fe=!lr(e),T=null}return T}function Kt(){let e=se()?"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 $e(e){try{return await e()}catch{throw Kt()}}var Ge=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await $e(()=>this.keytar.getPassword(Ue,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw I("OS keychain")}if(!Yt(r))throw I("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await $e(()=>this.keytar.setPassword(Ue,t,JSON.stringify(n)))}async delete(t){await this.read(t),await $e(()=>this.keytar.deletePassword(Ue,t))}},ur="credentials.json",Ye=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Gt.join(Pe(),ur)}read(t){let n;try{n=t.read()}catch(i){throw oe(i)?De():I("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw I("plaintext file")}if(!Me(r)||!Me(r.profiles))throw I("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw oe(r)?De():ae()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Yt(r))throw I("plaintext file");return r}}async get(t){try{return J(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:I("plaintext file")}}async set(t,n){try{J(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:ae()}}async delete(t){try{J(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:ae()}}async clearProfile(t){try{return J(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:oe(n)?De():ae()}}};function Ht(e){if(e.insecureStorage)return Ut(),new Ye(e.insecureFilePath);let t=cr();if(t)return new Ge(t);throw Kt()}var le=class e extends K{static description="Show the capabilities granted to the current CLI session (chosen on the browser approval screen at `device-login`, or via --scopes on `otp-login`). Scopes are ENFORCED server-side on every request. Read from the cached token bundle; no network call.";static examples=["$ allscale scope","$ allscale scope --profile prod"];static isLocalOnly=!0;static flags={...K.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),i=await Ht({insecureStorage:n.insecureStorage}).get(n.profile);if(!i)throw It({profile:n.profile,profileExplicit:n.profileExplicit});let o=i.scopes??[],a=!!i.agent_key,l=a&&typeof i.agent_key_expires_at=="number"?new Date(i.agent_key_expires_at*1e3).toISOString():void 0;return a?process.stderr.write(`Scopes for profile '${n.profile}': ${o.length>0?o.join(", "):"(none recorded)"}
17
- (agent-key session \u2014 scopes are ENFORCED server-side on every request)
18
- ${l?`Key expires at ${l}`:"Key has no recorded expiry"}; agent keys don't refresh \u2014 re-run \`allscale device-login --profile ${n.profile}\` (or \`${q(n.profile)}\`) when it expires or is revoked.
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 ${z}
14
+ `}var L=A(require("fs")),kt=A(require("os")),Ne=A(require("path")),xe=A(require("@iarna/toml"));var Fn=".allscale",Mn="config.toml";function Be(){return Ne.join(kt.homedir(),Fn)}function Gn(){return Ne.join(Be(),Mn)}function oe(){let e=Gn();if(!L.existsSync(e))return{};let t=L.readFileSync(e,"utf-8");try{return xe.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function Tt(e){return Object.keys(e.profile??{}).sort()}function Ot(e,t){return e.profile?.[t]}function It(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 Ue(e){if(!me(e))throw new c("input.invalid",`Refusing to send credentials to API base ${M(e)}. `+he)}function Ct(e){let t=Y();if(t===void 0||tt(e))return;let n=ne(e),r=nt();if(r.length>0){let o=r.map(l=>ne(l.base)).filter(l=>l!==null);if(n!==null&&o.includes(n))return;let a=r.map(l=>M(l.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${M(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=ne(t);if(!(n!==null&&n===i))throw new c("input.invalid",`Refusing to send to ${M(e)} \u2014 this build only signs for ${M(t)}. Re-login against this build's environment, or use a build for that one.`)}var Yn=require("@noble/hashes/sha3");var vt=["USDT","USDC"];var si=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Pt=require("@oclif/core"),G=class e extends w.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:w.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:w.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:K()==="public"}),"api-base":w.Flags.string({description:ge,helpGroup:"GLOBAL",hidden:K()==="public"}),"insecure-storage":w.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{Ie(this.jsonEnabled()),ve(),D({type:"session-start",command:this.id??"",argv:Pe(this.argv)});let t=this.constructor;if(K()==="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&&ie()!==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=St(this.jsonEnabled()),r=this.argv.length===0&&!n&&Jn(t)?this.config.findCommand(this.id??""):void 0;if(r){H();let o=await(0,w.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}if(t.requiresEscapeHatch&&!bt())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 D({type:"command-end",ok:!0}),H(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||at(i),{data:i})}catch(t){let n=st(t);At({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ie(!1)}}resolveSessionApiBaseChain(t){let n=oe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Re()!==void 0,a=It(n,r,Re()),l=Ot(n,a),u=i??ie(),d=u??l?.api_base??z,m=Lt({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return m&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,x({event:"legacy_staging_profile",api_base:d,profile:a},m)),{apiBase:d,explicitApiBase:u,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Ue(n),n}resolveContext(t){if(K()==="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&&ie()!==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:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Ue(i),Ct(i)),{apiBase:i,profile:a,token:n??re(),insecureStorage:r||Et(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${qn(t)}
15
+ `)}};var Kn=/_(removed|cleared|count|total)$/i;function jn(e,t){return typeof t=="number"&&Kn.test(e)}var Hn=new Set(vt);function Wn(e,t){return e==="token_symbol"&&typeof t=="string"&&Hn.has(t)}var se=100;function ae(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,se),r=n.map(i=>ae(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,se))n[i]=dt(i)&&!jn(i,o)&&!Wn(i,o)?"<redacted>":ae(o,t+1);if(r.length>se){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-se} more keys`}return n}if(typeof e=="string"){let n=zn(e);return n!==void 0?h(JSON.stringify(ae(n,t+1))):h(e)}return e}function zn(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 qn(e){let t=ht()?void 0:2,n=ae(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:h(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Jn(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 Xn(e,t={}){let n;try{n=Tt(oe())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",ot(e)+(t.messageSuffix??""),{profile:e})}function Rt(e){if(e.profileExplicit){let t=Xn(e.profile);if(t)return t}return new c("auth.no_token",it(e.profile))}var Ht=A(require("path"));var Fe=require("crypto"),s=A(require("fs")),g=A(require("path"));var le=1024*1024,Zn=5e3,Vn=20,Qn=3e4,De=4096,er=new Int32Array(new SharedArrayBuffer(4)),q=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ce(e){return e instanceof q}var y=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},tr=null;function T(){return new c("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function ue(){return(tr??process.platform)!=="win32"}function Mt(){if(!ue())throw T()}function Gt(e){try{return s.default.lstatSync(e),!1}catch(t){if(!f(t,"ENOENT"))throw t}try{let t=s.default.lstatSync(g.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(f(t,"ENOENT"))return!0;throw t}}function f(e,t){return typeof e=="object"&&e!==null&&e.code===t}function J(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function X(e,t){return e.dev===t.dev&&e.ino===t.ino}function nr(e){Atomics.wait(er,0,0,e)}function Yt(e){try{return process.kill(e,0),!0}catch(t){return!f(t,"ESRCH")}}function rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nt(e,t){let n=g.dirname(e);t&&s.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=s.default.lstatSync(n)}catch(o){if(!t&&f(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()||!X(o,a))throw new Error("credential-store parent changed while it was being inspected");J(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&g.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 b(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&&f(o,"ENOENT")?new y:o}if(!X(n,i))throw r.retryOnPathChange?new y: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 q;if(J(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 ir(e,t){if(t.size>le)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(le+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>le)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function xt(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(f(i,"ENOENT"))try{if(s.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(f(o,"ENOENT"))return null;throw o}throw i}let n=s.default.fstatSync(t),r=b(e,t,n);return ir(t,r)}finally{t!==null&&s.default.closeSync(t)}}function Bt(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(f(i,"ENOENT")&&Gt(e))return;throw i}let n=s.default.fstatSync(t),r=b(e,t,n);O(e,r)}finally{t!==null&&s.default.closeSync(t)}jt(g.dirname(e))}function or(e){let t;try{t=s.default.lstatSync(e)}catch(n){if(f(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 q;J(t,"credential-store replacement target")}function sr(e,t){for(let n=0;n<8;n+=1){let r=(0,Fe.randomBytes)(12).toString("hex"),i=g.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(f(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Kt(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 jt(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 ar(e,t){let n=Buffer.from(t,"utf8");if(n.length>le)throw new Error("credential-store file exceeds the maximum supported size");let r=g.dirname(e),i=g.basename(e),o=null,a=null,l=!1;try{let u=sr(r,i);o=u.fd,a=u.tempPath;let d=s.default.fstatSync(o);if((b(a,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Kt(o,n),s.default.fsyncSync(o),b(a,o,s.default.fstatSync(o));let S=o;o=null,s.default.closeSync(S),or(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{}}jt(r)}function lr(e){return g.join(g.dirname(e),`.${g.basename(e)}.lock`)}function cr(e){return g.join(g.dirname(e),`.${g.basename(e)}.lock-recovery`)}function ur(e,t){if(t.size>De)return null;let n=Buffer.alloc(De+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>De)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 O(e,t){let n=s.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!X(n,t))throw new Error("credential-store lock changed while it was being inspected");J(n,"credential-store lock"),s.default.unlinkSync(e)}function Ut(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(u){if(f(u,"ENOENT"))try{let d=s.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new y}catch(d){if(f(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=s.default.fstatSync(n),i=b(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=ur(n,i);return{state:(o?.target===t&&o?!Yt(o.pid):Date.now()-i.mtimeMs>=Qn)?"stale":"active",stats:i}}finally{n!==null&&s.default.closeSync(n)}}function dr(e,t){for(let n=0;n<8;n+=1){let r=(0,Fe.randomBytes)(12).toString("hex"),i=g.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),u=b(i,a,l,{allowMultipleLinks:!0});return Kt(a,Buffer.from(JSON.stringify(o),"utf8")),s.default.fsyncSync(a),{claimPath:i,metadata:o,stats:u}}catch(l){if(f(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 pr(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 f(r,"ENOENT")?new y:r}try{let r=s.default.fstatSync(n),i=b(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!X(i,t))throw new y;return{fd:n,lockPath:e,stats:i}}catch(r){throw s.default.closeSync(n),r}}function Dt(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(f(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 y}catch(r){if(f(r,"ENOENT"))return!1;throw r}throw n}return b(e,t,s.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&s.default.closeSync(t)}}function fr(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(f(r,"EEXIST"))return null;throw r}let n=null;try{n=s.default.fstatSync(t);let r=b(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{O(e,n)}catch{}throw s.default.closeSync(t),r}}function k(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");nr(Vn)}function $t(e){let t=g.dirname(e),n=g.basename(e),r=lr(e),i=cr(e),o=dr(t,n),a=Date.now()+Zn,l=!1,u=!1,d=null,m;try{for(;d===null;)try{if(Dt(i)){k(a,!0);continue}s.default.linkSync(o.claimPath,r),u=!0,d=pr(r,o.stats),l=!0}catch(S){if(u&&!l){try{O(r,o.stats)}catch{}u=!1}if(S instanceof y){k(a,!1);continue}if(!f(S,"EEXIST"))throw S;let fe;try{fe=Ut(r,n)}catch(E){if(E instanceof y){k(a,!1);continue}throw E}if(fe.state==="absent")continue;if(fe.state==="stale"){let E;try{E=fr(i)}catch(v){if(v instanceof y){k(a,!1);continue}throw v}if(E!==null){try{let v;try{v=Ut(r,n)}catch(qe){if(qe instanceof y){k(a,!1);continue}throw qe}v.state==="stale"&&O(r,v.stats)}finally{$e(E)}continue}}let ze;try{ze=Dt(i)}catch(E){if(E instanceof y){k(a,!1);continue}throw E}k(a,ze)}}catch(S){m=S}try{O(o.claimPath,o.stats)}catch(S){!f(S,"ENOENT")&&!l&&m===void 0&&(m=S)}if(m!==void 0)throw m;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function $e(e){try{O(e.lockPath,e.stats)}finally{s.default.closeSync(e.fd)}}function gr(e,t){let n=rr(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 Ft(e){let t=g.dirname(e),n=g.basename(e);for(let r of s.default.readdirSync(t)){let i=gr(r,n);if(i===null||Yt(i))continue;let o=g.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(d){if(f(d,"ENOENT")||f(d,"ELOOP"))continue;throw d}let l=s.default.fstatSync(a),u=s.default.lstatSync(o);if(!l.isFile()||u.isSymbolicLink()||!u.isFile()||!X(l,u))continue;try{J(l,"credential-store orphan")}catch{continue}O(o,l)}catch(l){if(!f(l,"ENOENT"))throw l}finally{a!==null&&s.default.closeSync(a)}}}function Z(e,t,n){if(!ue()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw T();if(!Nt(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw T()}});let a=$t(e);try{return Ft(e),n({read:()=>xt(e),remove:()=>Bt(e),write:()=>{throw T()}})}finally{$e(a)}}if(!t.createParent){let o=!1;try{o=Gt(e)}catch{throw T()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw T()}})}throw T()}if(!Nt(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=$t(e);try{return Ft(e),n({read:()=>xt(e),remove:()=>Bt(e),write:o=>ar(e,o)})}finally{$e(i)}}var Me="allscale-cli";function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wt(e){return je(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function C(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 Ge(){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 de(){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 I,Ye=!1;function hr(){return wt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function mr(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function yr(){if(I!==void 0)return I;if(hr())return Ye=!1,I=null,I;try{I=require("keytar"),Ye=!1}catch(e){Ye=!mr(e),I=null}return I}function zt(){let e=ue()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new c("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Ke(e){try{return await e()}catch{throw zt()}}var He=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Ke(()=>this.keytar.getPassword(Me,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw C("OS keychain")}if(!Wt(r))throw C("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Ke(()=>this.keytar.setPassword(Me,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Ke(()=>this.keytar.deletePassword(Me,t))}},_r="credentials.json",We=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Ht.join(Be(),_r)}read(t){let n;try{n=t.read()}catch(i){throw ce(i)?Ge():C("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw C("plaintext file")}if(!je(r)||!je(r.profiles))throw C("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ce(r)?Ge():de()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Wt(r))throw C("plaintext file");return r}}async get(t){try{return Z(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:C("plaintext file")}}async set(t,n){try{Z(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:de()}}async delete(t){try{Z(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:de()}}async clearProfile(t){try{return Z(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:ce(n)?Ge():de()}}};function qt(e){if(e.insecureStorage)return Mt(),new We(e.insecureFilePath);let t=yr();if(t)return new He(t);throw zt()}var pe=class e extends G{static description="Show the capabilities granted to the current CLI session (chosen on the browser approval screen at `device-login`, or via --scopes on `otp-login`). Scopes are checked by the backend on each request. Scope controls reduce access but do not prevent credential compromise, misuse within a granted scope, configuration errors, or unauthorized actions by an otherwise authenticated caller. Read from the cached token bundle; no network call.";static examples=["$ allscale scope","$ allscale scope --profile prod"];static isLocalOnly=!0;static flags={...G.baseFlags,token:{...G.baseFlags.token,description:"Not supported by this command. `scope` reads scopes recorded with a stored profile, so an arbitrary token has no authoritative scope source and is rejected locally. Use --profile to select the stored credential whose scopes should be shown."}};async runCommand(){let{flags:t}=await this.parse(e);if(t.token!==void 0)throw new c("input.invalid","--token is not supported by `allscale scope`: scopes are recorded metadata on a stored profile and cannot be derived from an arbitrary token. Use --profile <name> to select the credential whose recorded scopes should be shown.");let n=this.resolveContext(t);re()!==void 0&&process.stderr.write(`Note: ALLSCALE_TOKEN is set but ignored by \`scope\` \u2014 scopes are recorded metadata on a stored profile. Showing scopes recorded for profile '${n.profile}'.
17
+ `);let i=await qt({insecureStorage:n.insecureStorage}).get(n.profile);if(!i)throw Rt({profile:n.profile,profileExplicit:n.profileExplicit});let o=i.scopes??[],a=!!i.agent_key,l=a&&typeof i.agent_key_expires_at=="number"?new Date(i.agent_key_expires_at*1e3).toISOString():void 0;return a?process.stderr.write(`Scopes for profile '${n.profile}': ${o.length>0?o.join(", "):"(none recorded)"}
18
+ (agent-key session \u2014 scopes are checked by the backend on each request; scope controls reduce access but do not prevent credential compromise, misuse within a granted scope, configuration errors, or unauthorized actions by an otherwise authenticated caller)
19
+ ${l?`Key expires at ${l}`:"Key has no recorded expiry"}; agent keys don't refresh \u2014 re-run \`allscale device-login --profile ${P(n.profile)}\` (or \`${Q(n.profile)}\`) when it expires or is revoked.
19
20
  `):process.stderr.write(`Profile '${n.profile}' holds a legacy full-permission session (no agent key).
20
- Scopes apply to agent keys: run \`allscale device-login --profile ${n.profile}\` or \`${q(n.profile)}\` to mint a scope-enforced key.
21
+ Scopes apply to agent keys: run \`allscale device-login --profile ${P(n.profile)}\` or \`${Q(n.profile)}\` to mint a scoped agent key (granted scopes are checked by the backend on each request).
21
22
  `),{profile:n.profile,scopes:o,scoped:o.length>0,enforced:a,...l?{agent_key_expires_at:l}:{}}}};
22
23
  //# sourceMappingURL=scope.js.map