@allscale/cli 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -12
- package/dist/commands/build-info.js +12 -12
- package/dist/commands/claim-link/claim.js +10 -10
- package/dist/commands/claim-link/create.js +31 -31
- package/dist/commands/claim-link/get.js +13 -13
- package/dist/commands/claim-link/list.js +12 -12
- package/dist/commands/claim-link/status.js +11 -11
- package/dist/commands/describe.js +11 -11
- package/dist/commands/device-login.js +28 -27
- package/dist/commands/invoice/get.js +12 -12
- package/dist/commands/invoice/list.js +12 -12
- package/dist/commands/invoice/pay.js +41 -37
- package/dist/commands/invoice/received.js +12 -12
- package/dist/commands/invoice/send.js +29 -29
- package/dist/commands/invoice/sent.js +11 -11
- package/dist/commands/invoice/update.js +13 -13
- package/dist/commands/logout.js +19 -13
- package/dist/commands/operations.js +11 -11
- package/dist/commands/otp-login.js +17 -17
- package/dist/commands/otp-send.js +11 -11
- package/dist/commands/payout/send.js +14 -14
- package/dist/commands/payout/status.js +12 -12
- package/dist/commands/scope.js +16 -16
- package/dist/commands/store/create.js +16 -16
- package/dist/commands/transaction/get.js +12 -12
- package/dist/commands/transaction/list.js +12 -12
- package/dist/commands/wallet/list.js +12 -12
- package/dist/commands/wallet/send.js +27 -27
- package/dist/commands/whoami.js +14 -12
- package/dist/hooks/version-suffix.js +1 -1
- package/dist/index.js +11 -11
- package/dist/lib/help.js +10 -7
- package/oclif.manifest.json +24 -11
- package/package.json +1 -1
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var
|
|
4
|
-
`)}else Xe.stderr.write(t)}var Ht="2",
|
|
5
|
-
`);return}
|
|
6
|
-
`);return}
|
|
7
|
-
`)}catch(r){if(H=!1,L!==null){try{
|
|
8
|
-
`)}catch{}}}var C=
|
|
1
|
+
"use strict";var cr=Object.create;var le=Object.defineProperty;var lr=Object.getOwnPropertyDescriptor;var ur=Object.getOwnPropertyNames;var dr=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty;var fr=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},vt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ur(t))!pr.call(e,o)&&o!==n&&le(e,o,{get:()=>t[o],enumerable:!(r=lr(t,o))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?cr(dr(e)):{},vt(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e)),hr=e=>vt(le({},"__esModule",{value:!0}),e);var Bi={};fr(Bi,{default:()=>Ne});module.exports=hr(Bi);var I=require("@oclif/core");var Rt="public",xt="https://app.allscale.io";var Nt=["https://app.allscale.io"];var $e="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 Pt(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 Pt(e)!==null}function Ue(e){let t=Pt(e);return t!==null&&Nt.includes(t.origin)}function z(){return"".trim()||void 0}function G(){return"public"}function R(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Me(e){try{return new URL(e).origin}catch{return null}}function X(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return 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 o=[];for(let i of r){if(typeof i!="object"||i===null)continue;let{base:s,key:u,keyId:l}=i;if(typeof s!="string"||s.trim().length===0||typeof u!="string"||u.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";o.push({base:s.trim(),key:u,keyId:d.length>0?d:"cli-1"})}return o}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 gr="device-login",mr=/^[A-Za-z0-9._-]{1,64}$/;function je(e){return mr.test(e)?e:"<profile>"}function V(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":je(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ue(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Dt(e){let t=je(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${V(e)}\` for headless automation.`}function Ut(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${gr} --profile ${je(e)}\`.`}var _r={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var yr=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(yr,"")}var wr=64;function Ge(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>=wr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let u of e)s.push(Ge(u,t,n+1));return s}let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)return e;let i={};t.set(e,i);for(let[s,u]of Object.entries(e))Object.defineProperty(i,s,{value:Ge(u,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var c=class extends Error{code;details;constructor(t,n,r){super(qe(n)),this.code=t,this.details=r&&Ge(r),this.name="AllscaleError"}get exitCode(){return _r[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Ft(e){if(e instanceof c)return e;if(e instanceof Error){if(Er(e)){let t=kr(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 br=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(Ar(e))return!0;let t=e.name??"";return br.has(t)?t==="CLIError"?Ke(e,"parse")||$t(e.message):!0:$t(e.message)}function Ar(e){if(!Ke(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ke(e,"parse")}function $t(e){return e?qe(e).split(`
|
|
2
|
+
`).some(t=>Sr.some(n=>n.test(t.trim()))):!1}function Ke(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function kr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Mt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var h=A(require("fs")),ge=A(require("path")),Wt=A(require("crypto"));var Lr="...<truncated>",Tr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Ir=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ze=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ye=String.raw`(?:proxy[_-]?)?authorization`,Or=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ye}"|'${Ye}'|${Ye})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ze}`,"gi"),Cr=/\b(https?:\/\/)[^\s/?#]+@/gi,vr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Rr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Kt=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)`,Gt=Kt(vr),xr=Kt(Rr),Nr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Gt}"|'${Gt}'|${xr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ze}`,"gi"),He=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)`,Pr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${He}"|'${He}'|${He})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ze}`,"g");function de(e){return e.replace(Cr,"$1<redacted>@").replace(Tr,"<redacted-jwt>").replace(Or,"$1$2$3<redacted>").replace(Nr,"$1$2<redacted>").replace(Pr,"$1$2<redacted>").replace(Ir,"Bearer <redacted>")}var Br=/(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 pe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Br.test(t)}function jt(e){let t="";for(let n of e){let r=n.codePointAt(0),o=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=o?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function fe(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 u="",l=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(l+p>t)break;u+=d,l+=p}return u}let o=t-r,i="",s=0;for(let u of e){let l=Buffer.byteLength(u,"utf8");if(s+l>o)break;i+=u,s+=l}return`${i}${n}`}function S(e,t=16384){return fe(jt(de(e)),t)}var We=100,$r=8,Dr=8*1024;function he(){return{remaining:Dr}}function Je(e,t){let n=Math.min(16384,t.remaining),r=fe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function K(e,t,n=0,r={}){if(n>$r)return Je("<truncated>",t);if(typeof e=="string"){let o=de(e);return Je(r.escapeControls?jt(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,We),i=o.map(s=>K(s,t,n+1,r));return e.length>o.length&&i.push(Je(`<${e.length-o.length} more items truncated>`,t)),i}if(e!==null&&typeof e=="object"){let o=Object.create(null),i=Object.entries(e);for(let[s,u]of i.slice(0,We))o[s]=K(u,t,n+1,r);return i.length>We&&(o.output_truncated=!0),o}return e}var Xe=require("process");var Ve=!1;function Ze(e){Ve=e}function Yt(){return Ve}var qt="1";function q(e,t){if(Ve){let n={...e};delete n.version;let r=he(),o={event:n.event,...n},i=K(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:qt,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:qt,event:i.event,output_truncated:!0})),Xe.stderr.write(`${s}
|
|
4
|
+
`)}else Xe.stderr.write(t)}var Ht="2",Y=null,L=null,H=!1,Z=!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=Wt.randomBytes(4).toString("hex");return ge.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Qe=64*1024*1024,Fr=null;function et(e={}){if(e.quiet&&(Z=!0),H)return;let t=Ur();if(!t)return;Y=null;let n=null;try{if((Fr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=ge.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=h.statSync(r),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 o=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)|o,384);let i=h.fstatSync(n),s=h.lstatSync(t);if(!i.isFile()||s.isSymbolicLink()||s.dev!==i.dev||s.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 u=i.mode&511;if((u&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${u.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{}Z||q({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${S(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}Y=t,L=n,H=!0}var Mr=[/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 Gr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Mr.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=Kr(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)Gr(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function Kr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function jr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Jt(e.url)}:e}function qr(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=K(o,he()),s=JSON.stringify({version:Ht,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Ht,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!H||!Y||L===null)return;let t=jr(e),n=qr(t);try{if(h.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Qe){H=!1;try{h.closeSync(L)}catch{}L=null,Z||q({event:"sidecar_disabled",reason:"size_limit",...Y===null?{}:{path:S(Y)},max_bytes:Qe},`${S(`[allscale] sidecar exceeded ${Qe} bytes; disabling it for the rest of this run. Rotate or remove ${Y}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
|
+
`);return}h.appendFileSync(L,`${n}
|
|
7
|
+
`)}catch(r){if(H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{Z||q({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var C=Jt;function zt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Q(){if(Z=!1,H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}}function Xt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||zt()||!t}var ee=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"]),Yr=new Set(Array.from(ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Hr=Array.from(ee).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Wr=new Set(["--otp-stdin","--password-stdin"]);function tt(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 s=r.slice(0,i);if(ee.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ee.has(r)){t.push(r),n+1<e.length&&(ee.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(Yr.has(i)){t.push(`${i}<redacted>`);continue}}let o=Wr.has(r)?void 0:Hr.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function Vt(e){y({type:"error",code:e.code,message:S(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),Q()}var te=z()??xt,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 x(e){return Bt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Zt(){let e=process.env[J.TOKEN]?.trim();return e&&e.length>0?e:void 0}function nt(){let e=process.env[J.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ne(){let e=process.env[J.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Qt(){let e=process.env[J.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function en(){let e=process.env[J.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function tn(){let e=process.env[J.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function nn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(z()===void 0&&te!==""&&"".length!==0&&!n&&o!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
|
|
9
9
|
The CLI default is now ${te} (production), but a saved profile wins over the default,
|
|
10
10
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
11
11
|
the old default rather than a deliberate choice.
|
|
12
12
|
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
13
|
To move to production, run: allscale device-login --api-base ${te}
|
|
14
|
-
`}var N=
|
|
15
|
-
`)}};var Xr=/_(removed|cleared|count|total)$/i;function Vr(e,t){return typeof t=="number"&&Xr.test(e)}var Zr=new Set(ln);function Qr(e,t){return e==="token_symbol"&&typeof t=="string"&&Zr.has(t)}var we=100;function Se(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(i=>Se(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,we))n[i]=de(i)&&!Vr(i,o)&&!Qr(i,o)?"<redacted>":Se(o,t+1);if(r.length>we){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-we} more keys`}return n}if(typeof e=="string"){let n=ei(e);return n!==void 0?E(JSON.stringify(Se(n,t+1))):E(e)}return e}function ei(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function ti(e){let t=qt()?void 0:2,n=Se(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:E(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function ni(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 ri(e,t={}){let n;try{n=rn(me())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Dt(e)+(t.messageSuffix??""),{profile:e})}function Ee(e){if(e.profileExplicit){let t=ri(e.profile);if(t)return t}return new l("auth.no_token",$t(e.profile))}var En=b(require("path"));var lt=require("crypto"),a=b(require("fs")),_=b(require("path"));var Ae=1024*1024,ii=5e3,oi=20,si=3e4,st=4096,ai=new Int32Array(new SharedArrayBuffer(4)),re=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function be(e){return e instanceof re}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},li=null;function $(){return new l("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 ke(){return(li??process.platform)!=="win32"}function mn(){if(!ke())throw $()}function _n(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(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 ci(e){Atomics.wait(ai,0,0,e)}function yn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function ui(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&m(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()||!oe(o,s))throw new Error("credential-store parent changed while it was being inspected");ie(o,"credential-store parent");let u=o;if((o.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),u=a.default.fstatSync(i)),(u.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 O(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&&m(o,"ENOENT")?new k:o}if(!oe(n,i))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new re;if(ie(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 di(e,t){if(t.size>Ae)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ae+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>Ae)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function un(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(m(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(m(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return di(t,r)}finally{t!==null&&a.default.closeSync(t)}}function dn(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(m(i,"ENOENT")&&_n(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);D(e,r)}finally{t!==null&&a.default.closeSync(t)}Sn(_.dirname(e))}function fi(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(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 pi(e,t){for(let n=0;n<8;n+=1){let r=(0,lt.randomBytes)(12).toString("hex"),i=_.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(m(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function wn(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 Sn(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 gi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ae)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),i=_.basename(e),o=null,s=null,u=!1;try{let c=pi(r,i);o=c.fd,s=c.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");wn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),fi(e),a.default.renameSync(s,e),u=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!u&&s!==null)try{a.default.unlinkSync(s)}catch{}}Sn(r)}function hi(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function mi(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function _i(e,t){if(t.size>st)return null;let n=Buffer.alloc(st+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>st)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 D(e,t){let n=a.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"),a.default.unlinkSync(e)}function fn(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(c){if(m(c,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw c}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=_i(n,i);return{state:(o?.target===t&&o?!yn(o.pid):Date.now()-i.mtimeMs>=si)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function yi(e,t){for(let n=0;n<8;n+=1){let r=(0,lt.randomBytes)(12).toString("hex"),i=_.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 u=a.default.fstatSync(s),c=O(i,s,u,{allowMultipleLinks:!0});return wn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:c}}catch(u){if(m(u,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw u}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function wi(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 m(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!oe(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function pn(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(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Si(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(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{D(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");ci(oi)}function gn(e){let t=_.dirname(e),n=_.basename(e),r=hi(e),i=mi(e),o=yi(t,n),s=Date.now()+ii,u=!1,c=!1,d=null,f;try{for(;d===null;)try{if(pn(i)){B(s,!0);continue}a.default.linkSync(o.claimPath,r),c=!0,d=wi(r,o.stats),u=!0}catch(p){if(c&&!u){try{D(r,o.stats)}catch{}c=!1}if(p instanceof k){B(s,!1);continue}if(!m(p,"EEXIST"))throw p;let S;try{S=fn(r,n)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}if(S.state==="absent")continue;if(S.state==="stale"){let w;try{w=Si(i)}catch(A){if(A instanceof k){B(s,!1);continue}throw A}if(w!==null){try{let A;try{A=fn(r,n)}catch(ae){if(ae instanceof k){B(s,!1);continue}throw ae}A.state==="stale"&&D(r,A.stats)}finally{at(w)}continue}}let h;try{h=pn(i)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}B(s,h)}}catch(p){f=p}try{D(o.claimPath,o.stats)}catch(p){!m(p,"ENOENT")&&!u&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function at(e){try{D(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Ei(e,t){let n=ui(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 hn(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let i=Ei(r,n);if(i===null||yn(i))continue;let o=_.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(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let u=a.default.fstatSync(s),c=a.default.lstatSync(o);if(!u.isFile()||c.isSymbolicLink()||!c.isFile()||!oe(u,c))continue;try{ie(u,"credential-store orphan")}catch{continue}D(o,u)}catch(u){if(!m(u,"ENOENT"))throw u}finally{s!==null&&a.default.closeSync(s)}}}function se(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw $();if(!cn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw $()}});let s=gn(e);try{return hn(e),n({read:()=>un(e),remove:()=>dn(e),write:()=>{throw $()}})}finally{at(s)}}if(!t.createParent){let o=!1;try{o=_n(e)}catch{throw $()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw $()}})}throw $()}if(!cn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=gn(e);try{return hn(e),n({read:()=>un(e),remove:()=>dn(e),write:o=>gi(e,o)})}finally{at(i)}}var ct="allscale-cli";function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function An(e){return pt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new l("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 ut(){return new l("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 Le(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var U,dt=!1;function Ai(){return Qt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function bi(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 ki(){if(U!==void 0)return U;if(Ai())return dt=!1,U=null,U;try{U=require("keytar"),dt=!1}catch(e){dt=!bi(e),U=null}return U}function bn(){let e=ke()?"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 l("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 ft(e){try{return await e()}catch{throw bn()}}var gt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ft(()=>this.keytar.getPassword(ct,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!An(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ft(()=>this.keytar.setPassword(ct,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ft(()=>this.keytar.deletePassword(ct,t))}},Li="credentials.json",ht=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??En.join(ot(),Li)}read(t){let n;try{n=t.read()}catch(i){throw be(i)?ut():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 be(r)?ut():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!An(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 l?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 l?r:Le()}}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 l?n:Le()}}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 l?n:be(n)?ut():Le()}}};function Te(e){if(e.insecureStorage)return mn(),new ht(e.insecureFilePath);let t=ki();if(t)return new gt(t);throw bn()}var mt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ie(){return new mt}async function kn(e){if(e.token)return{kind:"override",accessToken:e.token};let n=await Te({insecureStorage:e.insecureStorage}).get(e.profile),r=n?.api_base;return n?.agent_key?{kind:"agent",storedApiBase:r,businessId:_t(n.business_id),userEmail:_t(n.user_email),scopes:Ti(n.scopes)}:n?.access_token?{kind:"human",storedApiBase:r,accessToken:n.access_token,userEmail:_t(n.user_email)}:{kind:"none"}}function _t(e){return typeof e=="string"&&e.length>0?e:void 0}function Ti(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.length>0);return t.length>0?t:void 0}function Ln(e){let t=e.split(".");if(t.length!==3)throw new l("auth.token_expired","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");try{let n=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(n)}catch(n){throw new l("auth.token_expired",`Failed to decode JWT payload: ${n.message}`)}}async function Tn(e,t){if(typeof t=="string"&&t.length>0)return t;let n=await kn(e);switch(n.kind){case"override":case"human":return Oi(n.accessToken);case"agent":if(n.businessId!==void 0)return n.businessId;throw new l("input.invalid","Agent-key sessions carry no JWT to derive the business id from \u2014 pass --business-id explicitly. (Re-run `allscale device-login` to store your business id automatically.)");case"none":throw Ee({profile:e.profile,profileExplicit:e.profileExplicit});default:return Ii(n)}}function Ii(e){throw new l("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}function Oi(e){let t=Ln(e),n=typeof t.user_id=="string"?t.user_id:void 0;if(!n)throw new l("input.invalid","Could not infer --business-id from the cached JWT (no user_id claim). Pass --business-id explicitly.");return n}var Oe="allscale_access_token",yt="allscale_refresh_token";function In(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function wt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function St(e,t){return e.find(n=>n.name===t)?.value??null}var On=b(require("crypto")),Cn=b(require("fs")),Rn=b(require("path"));var Ci="key-id",Ri="x-allscale-cli-version",Et="cli-1",vi="aScaLe_cli_obf_v1",xi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Ni(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 Pi=Ni(xi,vi),vn=`Bearer ${Pi}`;function xn(e,t){let n=Ge(e);if(n!==null)return t.find(r=>Ge(r.base)===n)}function Bi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=xn(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function $i(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?xn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Et}if(!x(t[0].base))return Et}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Et}function Di(){return"1.0.1"}function Ui(){return new l("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 At(e,t){let n=Bi(t);if(!n)throw Ui();let r=$i(t),i=Math.floor(Date.now()/1e3).toString(),o=On.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Ri]:Di()};return r.length>0&&(s[Ci]=r),s}function Nn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var Fi=500,Gi=8,Pn=100;function bt(e,t=0){if(t>Gi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Pn),r=n.map(i=>bt(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,Pn))n[r]=de(r)?"<redacted>":bt(i,t+1);return n}return e}function Mi(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 Bn(e,t=Fi){let n=Mi(e),r=n===void 0?ue(e):JSON.stringify(bt(n));return fe(r,t)}var kt=256*1024,Ce=class extends l{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"}},Re=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 Lt(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(),s=[],u=0,c,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,S)=>{c=setTimeout(()=>{S(new Re(e.status,d))},d),c.unref?.()});try{for(;;){let p=o.read(),{done:S,value:h}=f?await Promise.race([p,f]):await p;if(S)break;if(u+=h.byteLength,u>t)throw o.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(p){throw p instanceof Re&&o.cancel(p).catch(()=>{}),p}finally{c!==void 0&&clearTimeout(c);try{o.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var Ki="X-AllScale-Api-Key",Yi=3e4,qi=32*1024*1024,Hi=4*1024*1024;function ji(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function Wi(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function Ji(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(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 Gn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Ji(e.status,e.url)}}var $n="--dns-result-order=ipv4first";async function ve(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)??"",u=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),c=/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||u)&&(i||t!==void 0&&c)))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 l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${$n} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${$n}`})}var G=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??Yi;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");P(this.opts.apiBase),ye(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=ji(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();an(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",u=Mn(t.path),c=s==="required"?!0:s==="none"?!1:Vi(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw Ee({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Nn(t.body),f=!!o||!!r?.access_token;c&&f&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:c&&f,bodyForSig:d,tokens:r,extra:t.headers}),S=Date.now();y({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(A){throw new l("transport.network",`Network error contacting ${C(i)}: ${A instanceof Error?A.message:String(A)}`)}if(y({type:"response",status:h.status,durationMs:Date.now()-S}),c&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let A=await Wi(this.refreshSingleFlight(),t.signal),ae=this.buildHeaders({attachAuth:c&&!!A.access_token,bodyForSig:d,tokens:A,extra:t.headers}),rr=Date.now();y({type:"request",method:t.method??"GET",url:i});let Pe;try{Pe=await fetch(i,{method:t.method??"GET",headers:ae,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new l("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return y({type:"response",status:Pe.status,durationMs:Date.now()-rr}),Dn(Pe,{withMetadata:n.withMetadata,authBearing:c,responseKind:Un(t)})}return Dn(h,{withMetadata:n.withMetadata,authBearing:c&&f,agentKeyAuth:c&&!!o,responseKind:Un(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...At(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=vn;let i=t.tokens;if(i?.agent_key)return r[Ki]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=wt([{name:Oe,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${ce()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=wt([{name:Oe,value:t.access_token},{name:yt,value:t.refresh_token}]),i=At("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,u=setTimeout(()=>{s=!0,o.abort()},1e4),c;try{c=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw y({type:"refresh",ok:!1}),new l("transport.network",s&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(u)}y({type:"response",status:c.status,durationMs:0});try{await Gn(c)}catch(h){throw y({type:"refresh",ok:!1}),h}if(c.status!==200){let h=null;try{await ve(c);let w=await no(c);await ve(c,w),Yn(c.status,w),c.status===401&&(h=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw y({type:"refresh",ok:!1}),w}if(h)return y({type:"refresh",ok:!0,adopted:!0}),h;throw y({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ce()}.`,{status:c.status})}let d=In(c.headers),f=St(d,Oe),p=St(d,yt);if(!f||!p)throw y({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let S={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,S),y({type:"refresh",ok:!0}),S}},zi=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Mn(e){let t=e.split(/[?#]/,1)[0];return zi.some(n=>t===n||t.startsWith(`${n}/`))}var Xi=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Tt(e){let t=e.split(/[?#]/,1)[0];return Xi.some(n=>n.test(t))}function Vi(e){return Mn(e)||Tt(e)}async function Dn(e,t={}){await Gn(e);let n=e.status>=200&&e.status<300;n||await ve(e);let r=t.responseKind??"mutation",o=await Lt(e,n?r==="query"?qi:Hi:kt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await ve(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let c={};return e.headers.forEach((d,f)=>{c[f]=d}),{status:e.status,headers:c,body:s}}return s}let u=ro(s)??`HTTP ${e.status}`;if(Yn(e.status,s),eo(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let c=t.authBearing?"auth.token_expired":"input.invalid";throw new l(c,u,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",u,{status:403,body:s}):e.status===404?new l("not_found",u,{status:404,body:s}):e.status===429?new l("rate_limited",u,{status:429,body:s}):e.status>=500?new l("backend.internal",u,{status:e.status,body:s}):new l("input.invalid",u,{status:e.status,body:s})}function Un(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Zi=2014,Fn=2004;function Kn(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 Qi(e){return Kn(e,Zi)}function eo(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Kn(t,Fn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ce()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Fn})}var to=1e4;async function no(e,t=to){if(e.status>=200&&e.status<300)return"";try{return await Lt(e,kt,{timeoutMs:t})}catch{return""}}function Yn(e,t){if(!(e>=200&&e<300)&&Qi(t))throw new l("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"?Bn(t):t})}function ro(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var io=/^\/(api\/)?(v1\/)?public\//;function qn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&io.test(n),i=n&&Tt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new G({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new G({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new G({apiBase:e.apiBase,tokenStore:Te({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new G({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var oo=new Set;var so=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"]),It=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"]),Ot=new Set(["payroll","admin:user","admin:org","admin:audit"]);function xe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Hn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var ao=new Set(["cli_op:all"]),lo=new Set([...ao].map(xe));var ua=new Set([...[...so,...It,...oo].map(xe),...Ot,...lo]);var co={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},uo={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},fo=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,po=/is not available to API keys/i,jn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Wn(e){if(typeof e!="string")return;let t=fo.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=po.test(n),o=!i&&jn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(c=>c.trim()).filter(c=>jn.test(c));s=u.length>0?u:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Jn(e){let t=uo[e];if(t!==void 0)return{ungrantableReason:t};let n=co[e];if(n!==void 0)return{scope:n}}function zn(e){if(Ot.has(xe(e)))return{kind:"ungrantable"};for(let t of It)if(Hn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Xn(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function Vn(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var go=new Set([3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5100,5150,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function Qn(e,t){let n=er(e),r={graphql_error_count:ho(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw mo(e,t,r);if(n===429)throw new l("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new l("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&go.has(n))throw new l("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(Xn(e))throw new l("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${Vn(e)}`,r);if(n!==void 0)throw new l("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function er(e){let t=Zn(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let i=Zn(r.code);if(i!==void 0)return i}}function Zn(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function ho(e){return Array.isArray(e)?e.length:e==null?0:1}function mo(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Wn(_o(e,er(e))),s=Jn(t.operationName),u=o?.notAvailableToKeys===!0,c=o?.required??s?.scope,d=o?.granted,f=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(u||s?.ungrantableReason!==void 0){let p=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new l("auth.permission_denied",`${r} is not available to agent keys${p}. Re-authorizing will NOT help \u2014 no scope grants it.${f} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(c!==void 0){let p=zn(c),S=p.kind==="ungrantable"?`\`${c}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:p.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${V()}\` with \`--scopes ${c}\`.`:`The browser approval screen does not offer \`${c}\`, so \`device-login\` cannot grant it \u2014 use \`${V()}\` with \`--scopes ${c}\`.`;return new l("auth.permission_denied",`The current agent key lacks \`${c}\`, required by ${r}.${f} ${S}`,{...i,missing_scopes:[c],...d===void 0?{}:{granted_scopes:d},...p.kind==="ungrantable"?{ungrantable:!0}:{}})}return new l("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${f} Re-run \`allscale device-login\` (or \`${V()}\`) and grant the required scope.`,i)}function _o(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let c=r(i);if(c!==void 0)return c}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var yo="/api/secure/graphql";async function tr(e,t){t.showDoc&&process.stderr.write(`${t.document}
|
|
17
|
-
`);let r=await
|
|
14
|
+
`}var N=A(require("fs")),rn=A(require("os")),rt=A(require("path")),ot=A(require("@iarna/toml"));var Xr=".allscale",Vr="config.toml";function it(){return rt.join(rn.homedir(),Xr)}function Zr(){return rt.join(it(),Vr)}function me(){let e=Zr();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return ot.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function on(e){return Object.keys(e.profile??{}).sort()}function sn(e,t){return e.profile?.[t]}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 P(e){if(!Ue(e))throw new c("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+De)}function _e(e,t){P(e);let n=x(e),r=typeof t=="string"?x(t):null;if(n&&r===n)return;let o=typeof t=="string"?T(t):"<missing origin binding>";throw new c("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function cn(e,t){let n=x(e),r=x(t);if(!(n&&r===n))throw new c("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ye(e){let t=eo(e);if(t)throw new c("input.invalid",t.message)}function Qr(){let e=z();if(e===void 0)return;let t=X();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function eo(e){let t=Qr();if(t===void 0||R(e))return;let{endpoints:n,fromPairs:r}=t,o=x(e),i=n.map(u=>x(u)).filter(u=>u!==null);if(o!==null&&i.includes(o))return;let s=n.map(u=>T(u)).join(", ");return{message:r?`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var to=require("@noble/hashes/sha3");var ln=["USDT","USDC"];var Es=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var no="unknown_otp_id",ro="invalid_code",oo="expired_code";function io(e){return`'${e.replace(/'/g,"'\\''")}'`}function un(e){return`Run \`allscale otp-send --email ${io(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var so=new Map([[no,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${un(t)}`],[ro,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[oo,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${un(t)}`]]);var dn=[...so.keys()];var v=require("@oclif/core"),re=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:G()==="public"}),"api-base":I.Flags.string({description:$e,helpGroup:"GLOBAL",hidden:G()==="public"}),"insecure-storage":I.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{Ze(this.jsonEnabled()),et(),y({type:"session-start",command:this.id??"",argv:tt(this.argv)});let t=this.constructor;if(G()==="public"){if(this.argv.some(i=>i==="--token"||i.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(i=>i==="--api-base"||i.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&&ne()!==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=Xt(this.jsonEnabled()),r=this.argv.length===0&&!n&&mo(t)?this.config.findCommand(this.id??""):void 0;if(r){Q();let i=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new i(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!tn())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 o=await this.runCommand();return y({type:"command-end",ok:!0}),Q(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Mt(o),{data:o})}catch(t){let n=Ft(t);Vt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ze(!1)}}resolveSessionApiBaseChain(t){let n=me(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||nt()!==void 0,s=an(n,r,nt()),u=sn(n,s),l=G()==="public"&&ne()!==void 0,d=o??(l?void 0:ne()),p=d??u?.api_base??te,f=nn({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:u?.api_base,profileApiBaseSource:u?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,q({event:"legacy_staging_profile",api_base:p,profile:s},f)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:l,profileApiBase:u?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||P(n),n}resolveContext(t){if(G()==="public"){if(t.token!==void 0)throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ne()!==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:o,explicitApiBase:i,envApiBaseIgnored:s,profile:u,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(P(o),ye(o)),{apiBase:o,profile:u,token:n??Zt(),insecureStorage:r||Qt(),apiBaseSource:i!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${go(t)}
|
|
15
|
+
`)}};var ao=/_(removed|cleared|count|total)$/i;function co(e,t){return typeof t=="number"&&ao.test(e)}var lo=new Set(ln);function uo(e,t){return e==="token_symbol"&&typeof t=="string"&&lo.has(t)}var po=new Set(dn);function fo(e,t){return e==="otp_reason"&&typeof t=="string"&&po.has(t)}var we=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(o=>be(o,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[o,i]of r.slice(0,we))n[o]=pe(o)&&!co(o,i)&&!uo(o,i)&&!fo(o,i)?"<redacted>":be(i,t+1);if(r.length>we){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-we} more keys`}return n}if(typeof e=="string"){let n=ho(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function ho(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 go(e){let t=Yt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function mo(e){if(e.requiresInput===!0)return!0;let t=o=>typeof o=="object"&&o!==null&&o.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(o=>t(o))||Object.values(r).some(o=>t(o))}function _o(e,t={}){let n;try{n=on(me())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",Ut(e)+(t.messageSuffix??""),{profile:e})}function Se(e){if(e.profileExplicit){let t=_o(e.profile);if(t)return t}return new c("auth.no_token",Dt(e.profile))}var kn=A(require("path"));var ct=require("crypto"),a=A(require("fs")),_=A(require("path"));var Ee=1024*1024,yo=5e3,wo=20,bo=3e4,st=4096,So=new Int32Array(new SharedArrayBuffer(4)),oe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ae(e){return e instanceof oe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Eo=null;function $(){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 ke(){return(Eo??process.platform)!=="win32"}function wn(){if(!ke())throw $()}function bn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(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 se(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ao(e){Atomics.wait(So,0,0,e)}function Sn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function ko(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&m(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=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 i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!se(i,s))throw new Error("credential-store parent changed while it was being inspected");ie(i,"credential-store parent");let u=i;if((i.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),u=a.default.fstatSync(o)),(u.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&a.default.closeSync(o)}return!0}function O(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 o;try{o=a.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&m(i,"ENOENT")?new k:i}if(!se(n,o))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.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||o.nlink!==1))throw new oe;if(ie(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function Lo(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+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>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function fn(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(o){if(m(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(m(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return Lo(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(o){if(m(o,"ENOENT")&&bn(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);D(e,r)}finally{t!==null&&a.default.closeSync(t)}An(_.dirname(e))}function To(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(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 oe;ie(t,"credential-store replacement target")}function Io(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(m(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function En(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 An(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 Oo(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),o=_.basename(e),i=null,s=null,u=!1;try{let l=Io(r,o);i=l.fd,s=l.tempPath;let d=a.default.fstatSync(i);if((O(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");En(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let f=i;i=null,a.default.closeSync(f),To(e),a.default.renameSync(s,e),u=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!u&&s!==null)try{a.default.unlinkSync(s)}catch{}}An(r)}function Co(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function vo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Ro(e,t){if(t.size>st)return null;let n=Buffer.alloc(st+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>st)return null;let o;try{o=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof o!="object"||o===null||!Number.isSafeInteger(o.pid)||(o.pid??0)<=0||typeof o.nonce!="string"||!/^[a-f0-9]{24}$/.test(o.nonce??"")||typeof o.target!="string"?null:o}function D(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");ie(n,"credential-store lock"),a.default.unlinkSync(e)}function gn(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(l){if(m(l,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Ro(n,o);return{state:(i?.target===t&&i?!Sn(i.pid):Date.now()-o.mtimeMs>=bo)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function xo(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let u=a.default.fstatSync(s),l=O(o,s,u,{allowMultipleLinks:!0});return En(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:l}}catch(u){if(m(u,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw u}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function No(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 m(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(o,t))throw new k;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function mn(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(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Po(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(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{D(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");Ao(wo)}function _n(e){let t=_.dirname(e),n=_.basename(e),r=Co(e),o=vo(e),i=xo(t,n),s=Date.now()+yo,u=!1,l=!1,d=null,p;try{for(;d===null;)try{if(mn(o)){B(s,!0);continue}a.default.linkSync(i.claimPath,r),l=!0,d=No(r,i.stats),u=!0}catch(f){if(l&&!u){try{D(r,i.stats)}catch{}l=!1}if(f instanceof k){B(s,!1);continue}if(!m(f,"EEXIST"))throw f;let b;try{b=gn(r,n)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}if(b.state==="absent")continue;if(b.state==="stale"){let w;try{w=Po(o)}catch(E){if(E instanceof k){B(s,!1);continue}throw E}if(w!==null){try{let E;try{E=gn(r,n)}catch(ce){if(ce instanceof k){B(s,!1);continue}throw ce}E.state==="stale"&&D(r,E.stats)}finally{at(w)}continue}}let g;try{g=mn(o)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}B(s,g)}}catch(f){p=f}try{D(i.claimPath,i.stats)}catch(f){!m(f,"ENOENT")&&!u&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function at(e){try{D(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Bo(e,t){let n=ko(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 o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function yn(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let o=Bo(r,n);if(o===null||Sn(o))continue;let i=_.join(t,r),s=null;try{try{s=a.default.openSync(i,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let u=a.default.fstatSync(s),l=a.default.lstatSync(i);if(!u.isFile()||l.isSymbolicLink()||!l.isFile()||!se(u,l))continue;try{ie(u,"credential-store orphan")}catch{continue}D(i,u)}catch(u){if(!m(u,"ENOENT"))throw u}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw $();if(!pn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw $()}});let s=_n(e);try{return yn(e),n({read:()=>fn(e),remove:()=>hn(e),write:()=>{throw $()}})}finally{at(s)}}if(!t.createParent){let i=!1;try{i=bn(e)}catch{throw $()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw $()}})}throw $()}if(!pn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=_n(e);try{return yn(e),n({read:()=>fn(e),remove:()=>hn(e),write:i=>Oo(e,i)})}finally{at(o)}}var lt="allscale-cli";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ln(e){return ft(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 ut(){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 Le(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var U,dt=!1;function $o(){return en()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Do(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 Uo(){if(U!==void 0)return U;if($o())return dt=!1,U=null,U;try{U=require("keytar"),dt=!1}catch(e){dt=!Do(e),U=null}return U}var Fo="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Tn(){let e=ke()?"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",`${Fo} `+e+" Never silently downgrade in production.")}async function pt(e){try{return await e()}catch{throw Tn()}}var ht=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await pt(()=>this.keytar.getPassword(lt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!Ln(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await pt(()=>this.keytar.setPassword(lt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await pt(()=>this.keytar.deletePassword(lt,t))}},Mo="credentials.json",gt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??kn.join(it(),Mo)}read(t){let n;try{n=t.read()}catch(o){throw Ae(o)?ut():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!ft(r)||!ft(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ae(r)?ut():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Ln(r))throw F("plaintext file");return r}}async get(t){try{return ae(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{ae(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof c?r:Le()}}async delete(t){try{ae(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:Le()}}async clearProfile(t){try{return ae(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:Ae(n)?ut():Le()}}};function Te(e){if(e.insecureStorage)return wn(),new gt(e.insecureFilePath);let t=Uo();if(t)return new ht(t);throw Tn()}var mt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new c("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ie(){return new mt}async function In(e){if(e.token)return{kind:"override",accessToken:e.token};let n=await Te({insecureStorage:e.insecureStorage}).get(e.profile),r=n?.api_base;return n?.agent_key?{kind:"agent",storedApiBase:r,businessId:_t(n.business_id),userEmail:_t(n.user_email),scopes:Go(n.scopes)}:n?.access_token?{kind:"human",storedApiBase:r,accessToken:n.access_token,userEmail:_t(n.user_email)}:{kind:"none"}}function _t(e){return typeof e=="string"&&e.length>0?e:void 0}function Go(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.length>0);return t.length>0?t:void 0}function Cn(e){let t=e.split(".");if(t.length!==3)throw new c("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let n;try{let r=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");n=JSON.parse(r)}catch{throw On()}if(typeof n!="object"||n===null||Array.isArray(n))throw On();return n}function On(){return new c("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}async function vn(e,t){if(typeof t=="string"&&t.length>0)return t;let n=await In(e);switch(n.kind){case"override":case"human":return jo(n.accessToken);case"agent":if(n.businessId!==void 0)return n.businessId;throw new c("input.invalid","Agent-key sessions carry no JWT to derive the business id from \u2014 pass --business-id explicitly. (Re-run `allscale device-login` to store your business id automatically.)");case"none":throw Se({profile:e.profile,profileExplicit:e.profileExplicit});default:return Ko(n)}}function Ko(e){throw new c("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}function jo(e){let t=Cn(e),n=typeof t.user_id=="string"?t.user_id:void 0;if(!n)throw new c("input.invalid","Could not infer --business-id from the cached JWT (no user_id claim). Pass --business-id explicitly.");return n}var Oe="allscale_access_token",yt="allscale_refresh_token";function Rn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function wt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function bt(e,t){return e.find(n=>n.name===t)?.value??null}var xn=A(require("crypto")),Nn=A(require("fs")),Pn=A(require("path"));var qo="key-id",Yo="x-allscale-cli-version",St="cli-1",Ho="aScaLe_cli_obf_v1",Wo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Jo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var zo=Jo(Wo,Ho),Bn=`Bearer ${zo}`;function $n(e,t){let n=Me(e);if(n!==null)return t.find(r=>Me(r.base)===n)}function Xo(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=$n(e,t);if(r)return r.key;if(R(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:R(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 Vo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?$n(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&R(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():St}if(!R(t[0].base))return St}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():St}function Zo(){return"1.0.3"}function Qo(){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 Et(e,t){let n=Xo(t);if(!n)throw Qo();let r=Vo(t),o=Math.floor(Date.now()/1e3).toString(),i=xn.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Yo]:Zo()};return r.length>0&&(s[qo]=r),s}function Dn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ei=500,ti=8,Un=100;function At(e,t=0){if(t>ti)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Un),r=n.map(o=>At(o,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,o]of Object.entries(e).slice(0,Un))n[r]=pe(r)?"<redacted>":At(o,t+1);return n}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 Fn(e,t=ei){let n=ni(e),r=n===void 0?de(e):JSON.stringify(At(n));return fe(r,t)}var kt=256*1024,Ce=class extends c{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`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.`:i?`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,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},ve=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 Lt(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"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],u=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,b)=>{l=setTimeout(()=>{b(new ve(e.status,d))},d),l.unref?.()});try{for(;;){let f=i.read(),{done:b,value:g}=p?await Promise.race([f,p]):await f;if(b)break;if(u+=g.byteLength,u>t)throw i.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(f){throw f instanceof ve&&i.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{i.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var ri="X-AllScale-Api-Key",oi=3e4,ii=32*1024*1024,si=4*1024*1024;function ai(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function ci(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function li(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${C(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 qn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}li(e.status,e.url)}}var Mn="--dns-result-order=ipv4first";async function Re(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",u=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),l=/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(!((i||u)&&(o||t!==void 0&&l)))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=${Mn} 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=${Mn}`})}var M=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??oi;if(!Number.isFinite(r)||r<1)throw new c("input.invalid","HTTP request timeout must be a positive number of milliseconds.");P(this.opts.apiBase),ye(this.opts.apiBase);let o=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),i=ai(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new c("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof c)?new c("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();cn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",u=Yn(t.path),l=s==="required"?!0:s==="none"?!1:pi(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw Se({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Dn(t.body),p=!!i||!!r?.access_token;l&&p&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();y({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new c("transport.network",`Network error contacting ${C(o)}: ${E instanceof Error?E.message:String(E)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-b}),l&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await ci(this.refreshSingleFlight(),t.signal),ce=this.buildHeaders({attachAuth:l&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),ar=Date.now();y({type:"request",method:t.method??"GET",url:o});let Pe;try{Pe=await fetch(o,{method:t.method??"GET",headers:ce,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new c("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return y({type:"response",status:Pe.status,durationMs:Date.now()-ar}),Gn(Pe,{withMetadata:n.withMetadata,authBearing:l,responseKind:Kn(t)})}return Gn(g,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!i,responseKind:Kn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Et(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Bn;let o=t.tokens;if(o?.agent_key)return r[ri]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=wt([{name:Oe,value:i}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new c("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new c("auth.token_expired",`No refresh token available; log in again \u2014 ${ue()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new c("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=wt([{name:Oe,value:t.access_token},{name:yt,value:t.refresh_token}]),o=Et("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,u=setTimeout(()=>{s=!0,i.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(g){throw y({type:"refresh",ok:!1}),new c("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(u)}y({type:"response",status:l.status,durationMs:0});try{await qn(l)}catch(g){throw y({type:"refresh",ok:!1}),g}if(l.status!==200){let g=null;try{await Re(l);let w=await _i(l);await Re(l,w),Wn(l.status,w),l.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw y({type:"refresh",ok:!1}),w}if(g)return y({type:"refresh",ok:!0,adopted:!0}),g;throw y({type:"refresh",ok:!1}),new c("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:l.status})}let d=Rn(l.headers),p=bt(d,Oe),f=bt(d,yt);if(!p||!f)throw y({type:"refresh",ok:!1}),new c("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,b),y({type:"refresh",ok:!0}),b}},ui=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Yn(e){let t=e.split(/[?#]/,1)[0];return ui.some(n=>t===n||t.startsWith(`${n}/`))}var di=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Tt(e){let t=e.split(/[?#]/,1)[0];return di.some(n=>n.test(t))}function pi(e){return Yn(e)||Tt(e)}async function Gn(e,t={}){await qn(e);let n=e.status>=200&&e.status<300;n||await Re(e);let r=t.responseKind??"mutation",i=await Lt(e,n?r==="query"?ii:si:kt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Re(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:s}}return s}let u=yi(s)??`HTTP ${e.status}`;if(Wn(e.status,s),gi(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new c("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new c(l,u,{status:401,body:s})}throw e.status===403?new c("auth.permission_denied",u,{status:403,body:s}):e.status===404?new c("not_found",u,{status:404,body:s}):e.status===429?new c("rate_limited",u,{status:429,body:s}):e.status>=500?new c("backend.internal",u,{status:e.status,body:s}):new c("input.invalid",u,{status:e.status,body:s})}function Kn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var fi=2014,jn=2004;function Hn(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 hi(e){return Hn(e,fi)}function gi(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Hn(t,jn))throw new c("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:jn})}var mi=1e4;async function _i(e,t=mi){if(e.status>=200&&e.status<300)return"";try{return await Lt(e,kt,{timeoutMs:t})}catch{return""}}function Wn(e,t){if(!(e>=200&&e<300)&&hi(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"?Fn(t):t})}function yi(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var wi=/^\/(api\/)?(v1\/)?public\//;function Jn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&wi.test(n),o=n&&Tt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Te({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new M({apiBase:e.apiBase,tokenStore:Ie(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var bi=new Set;var Si=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"]),It=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Ot=new Set(["payroll","admin:user","admin:org","admin:audit"]);function xe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function zn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Ei=new Set(["cli_op:all"]),Ai=new Set([...Ei].map(xe));var Oa=new Set([...[...Si,...It,...bi].map(xe),...Ot,...Ai]);var ki={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Li={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},Ti=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,Ii=/is not available to API keys/i,Xn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Vn(e){if(typeof e!="string")return;let t=Ti.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),o=Ii.test(n),i=!o&&Xn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(l=>l.trim()).filter(l=>Xn.test(l));s=u.length>0?u:void 0}if(!(i===void 0&&!o))return{required:i,granted:s,notAvailableToKeys:o}}function Zn(e){let t=Li[e];if(t!==void 0)return{ungrantableReason:t};let n=ki[e];if(n!==void 0)return{scope:n}}function Qn(e){if(Ot.has(xe(e)))return{kind:"ungrantable"};for(let t of It)if(zn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function er(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function tr(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var Ct=8100,Oi=new Set([Ct]),Ci=new Set([...Oi,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function rr(e,t){let n=or(e),r={graphql_error_count:vi(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Ri(e,t,r);if(n===429)throw new c("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new c("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&Ci.has(n))throw new c("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(er(e))throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${tr(e)}`,r);if(n!==void 0)throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function or(e){let t=nr(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let o=nr(r.code);if(o!==void 0)return o}}function nr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function vi(e){return Array.isArray(e)?e.length:e==null?0:1}function Ri(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,o={...n,operation:t.operationName},i=Vn(xi(e,or(e))),s=Zn(t.operationName),u=i?.notAvailableToKeys===!0,l=i?.required??s?.scope,d=i?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(u||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new c("auth.permission_denied",`${r} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...o,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=Qn(l),b=f.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:f.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${V()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${V()}\` with \`--scopes ${l}\`.`;return new c("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${p} ${b}`,{...o,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new c("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${p} Re-run \`allscale device-login\` (or \`${V()}\`) and grant the required scope.`,o)}function xi(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=o=>{if(o===null||typeof o!="object")return;let i=o.message;return typeof i=="string"?i:void 0};if(t!==void 0)for(let o of n){if(o===null||typeof o!="object")continue;let i=o.extensions;if(!i||typeof i!="object")continue;let s=i.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(o);if(l!==void 0)return l}}for(let o of n){let i=r(o);if(i!==void 0)return i}return""}var Ni="/api/secure/graphql";async function ir(e,t){t.showDoc&&process.stderr.write(`${t.document}
|
|
17
|
+
`);let r=await Jn(e).request({method:"POST",path:Ni,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});rr(r,{kind:t.kind,operationName:t.operationName});let o=r.data?.[t.operationName];return o===void 0?null:o}var Pi=`mutation create_store($input: CreateStoreInput!) {
|
|
18
18
|
create_store(input: $input) {
|
|
19
19
|
store { id name api_key is_sandbox scopes }
|
|
20
20
|
api_secret
|
|
21
21
|
}
|
|
22
|
-
}`;async function
|
|
23
|
-
\u2713 Store created: ${
|
|
24
|
-
API key: ${
|
|
22
|
+
}`;async function sr(e,t){let n={...t,logo_url:t.logo_url??null},r=await ir(e,{kind:"mutation",operationName:"create_store",document:Pi,variables:{input:n}});if(!r?.store)throw new c("backend.internal","create_store returned no store payload. The store was likely not created \u2014 check that this business has checkout enabled and that business_id matches your login, then retry.",{data:r});return r}var Ne=class e extends re{static description="Create a store for the logged-in business. Returns the API key and an API secret that is shown only once (it cannot be retrieved later \u2014 capture it now). The secret itself stays valid for use \u2014 it just cannot be displayed again. Business must have checkout enabled; only one sandbox store is allowed per business.";static examples=['$ allscale store create --name "My Shop"','$ allscale store create --name "Live Shop" --live','$ allscale store create --name "Acme" --business-id 665f0c1234567890abcdef12'];static flags={name:v.Flags.string({helpGroup:"REQUIRED",description:"Store display name (required).",required:!0}),"business-id":v.Flags.string({char:"b",description:"Owning business id. Defaults to the logged-in business (decoded from the session token). Admins creating for another business must pass this."}),live:v.Flags.boolean({description:"Create a live store. Default is a sandbox store (backend allows only one sandbox store per business).",default:!1}),type:v.Flags.integer({description:"Store type. 1 = checkout (the default). Payout credential stores are provisioned by Payout onboarding, not by this command. Omit for checkout."}),description:v.Flags.string({description:"Optional store description."}),...re.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await vn(n,t["business-id"]),o=await sr(n,{name:t.name,business_id:r,is_sandbox:!t.live,...t.type!==void 0?{type:t.type}:{},...t.description?{description:t.description}:{}}),i=o.store;return process.stderr.write(`
|
|
23
|
+
\u2713 Store created: ${i.name} (${i.id}) [${i.is_sandbox?"sandbox":"live"}]
|
|
24
|
+
API key: ${i.api_key}
|
|
25
25
|
Save the API secret from the stdout result now \u2014 it is shown only this once and cannot be retrieved again.
|
|
26
26
|
|
|
27
|
-
`),
|
|
27
|
+
`),o}};
|
|
28
28
|
//# sourceMappingURL=create.js.map
|