@allscale/cli 0.1.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -41
- package/bin/dev.js +11 -1
- package/bin/run-oclif.js +216 -27
- package/bin/run.js +19 -1
- package/dist/commands/build-info.js +13 -13
- package/dist/commands/claim-link/claim.js +14 -14
- package/dist/commands/claim-link/create.js +40 -37
- package/dist/commands/claim-link/get.js +26 -15
- package/dist/commands/claim-link/list.js +15 -15
- package/dist/commands/claim-link/status.js +13 -13
- package/dist/commands/describe.js +13 -13
- package/dist/commands/device-login.js +23 -24
- package/dist/commands/invoice/get.js +15 -15
- package/dist/commands/invoice/list.js +16 -16
- package/dist/commands/invoice/pay.js +40 -41
- package/dist/commands/invoice/received.js +16 -16
- package/dist/commands/invoice/send.js +42 -34
- package/dist/commands/invoice/sent.js +15 -15
- package/dist/commands/invoice/update.js +17 -15
- package/dist/commands/logout.js +14 -14
- package/dist/commands/operations.js +13 -13
- package/dist/commands/otp-login.js +21 -20
- package/dist/commands/otp-send.js +13 -13
- package/dist/commands/payout/send.js +14 -14
- package/dist/commands/payout/status.js +15 -15
- package/dist/commands/scope.js +17 -16
- package/dist/commands/store/create.js +17 -17
- package/dist/commands/transaction/get.js +15 -15
- package/dist/commands/transaction/list.js +15 -15
- package/dist/commands/wallet/list.js +15 -15
- package/dist/commands/wallet/send.js +40 -43
- package/dist/commands/whoami.js +14 -14
- package/dist/hooks/version-suffix.js +1 -1
- package/dist/index.js +14 -14
- package/dist/lib/help.js +7 -2
- package/dist/lib/output/audit-lifecycle.js +7 -0
- package/oclif.manifest.json +123 -292
- package/package.json +4 -6
- package/dist/commands/claim-link/preview.js +0 -18
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var g=
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}
|
|
6
|
-
`);return}g.appendFileSync(
|
|
7
|
-
`)}catch(r){if(H=!1,
|
|
8
|
-
`)}catch{}}}var C=
|
|
9
|
-
The CLI default is now ${
|
|
1
|
+
"use strict";var ir=Object.create;var le=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ar=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var cr=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},Ct=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sr(t))!lr.call(e,i)&&i!==n&&le(e,i,{get:()=>t[i],enumerable:!(r=or(t,i))||r.enumerable});return e};var b=(e,t,n)=>(n=e!=null?ir(ar(e)):{},Ct(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e)),ur=e=>Ct(le({},"__esModule",{value:!0}),e);var So={};cr(So,{default:()=>Ne});module.exports=ur(So);var I=require("@oclif/core");var Rt="public",vt="https://app.allscale.io";var xt=["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 Nt(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 Pt(e){return Nt(e)!==null}function Ue(e){let t=Nt(e);return t!==null&&xt.includes(t.origin)}function J(){return"".trim()||void 0}function z(){return"public"}function x(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Ge(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 i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:u,keyId:c}=o;if(typeof s!="string"||s.trim().length===0||typeof u!="string"||u.trim().length===0)continue;let d=typeof c=="string"?c.trim():"";i.push({base:s.trim(),key:u,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var dr="device-login",fr=/^[A-Za-z0-9._-]{1,64}$/;function Ye(e){return fr.test(e)?e:"<profile>"}function V(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Ye(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ce(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function $t(e){let t=Ye(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${V(e)}\` for headless automation.`}function Dt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${dr} --profile ${Ye(e)}\`.`}var pr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},gr=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(gr,"")}var hr=64;function Me(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>=hr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let u of e)s.push(Me(u,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,u]of Object.entries(e))Object.defineProperty(o,s,{value:Me(u,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var l=class extends Error{code;details;constructor(t,n,r){super(qe(n)),this.code=t,this.details=r&&Me(r),this.name="AllscaleError"}get exitCode(){return pr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Ut(e){if(e instanceof l)return e;if(e instanceof Error){if(yr(e)){let t=Sr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var mr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),_r=[/^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 yr(e){if(wr(e))return!0;let t=e.name??"";return mr.has(t)?t==="CLIError"?Ke(e,"parse")||Bt(e.message):!0:Bt(e.message)}function wr(e){if(!Ke(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ke(e,"parse")}function Bt(e){return e?qe(e).split(`
|
|
2
|
+
`).some(t=>_r.some(n=>n.test(t.trim()))):!1}function Ke(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Sr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ft(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var g=b(require("fs")),ge=b(require("path")),jt=b(require("crypto"));var Er="...<truncated>",Ar=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,br=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ze=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,He=String.raw`(?:proxy[_-]?)?authorization`,kr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${He}"|'${He}'|${He})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ze}`,"gi"),Lr=/\b(https?:\/\/)[^\s/?#]+@/gi,Tr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Ir=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Mt=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=Mt(Tr),Or=Mt(Ir),Cr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Gt}"|'${Gt}'|${Or})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ze}`,"gi"),je=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)`,Rr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${je}"|'${je}'|${je})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ze}`,"g");function ue(e){return e.replace(Lr,"$1<redacted>@").replace(Ar,"<redacted-jwt>").replace(kr,"$1$2$3<redacted>").replace(Cr,"$1$2<redacted>").replace(Rr,"$1$2<redacted>").replace(br,"Bearer <redacted>")}var vr=/(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 de(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return vr.test(t)}function Kt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function fe(e,t,n=Er){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let u="",c=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(c+f>t)break;u+=d,c+=f}return u}let i=t-r,o="",s=0;for(let u of e){let c=Buffer.byteLength(u,"utf8");if(s+c>i)break;o+=u,s+=c}return`${o}${n}`}function E(e,t=16384){return fe(Kt(ue(e)),t)}var We=100,xr=8,Nr=8*1024;function pe(){return{remaining:Nr}}function Je(e,t){let n=Math.min(16384,t.remaining),r=fe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function M(e,t,n=0,r={}){if(n>xr)return Je("<truncated>",t);if(typeof e=="string"){let i=ue(e);return Je(r.escapeControls?Kt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,We),o=i.map(s=>M(s,t,n+1,r));return e.length>i.length&&o.push(Je(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,u]of o.slice(0,We))i[s]=M(u,t,n+1,r);return o.length>We&&(i.output_truncated=!0),i}return e}var Xe=require("process");var Ve=!1;function Ze(e){Ve=e}function qt(){return Ve}var Yt="1";function Y(e,t){if(Ve){let n={...e};delete n.version;let r=pe(),i={event:n.event,...n},o=M(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Yt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Yt,event:o.event,output_truncated:!0})),Xe.stderr.write(`${s}
|
|
4
|
+
`)}else Xe.stderr.write(t)}var Ht="2",q=null,L=null,H=!1,Z=!1;function Pr(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=jt.randomBytes(4).toString("hex");return ge.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Qe=64*1024*1024,Br=null;function et(e={}){if(e.quiet&&(Z=!0),H)return;let t=Pr();if(!t)return;q=null;let n=null;try{if((Br??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(g.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=g.statSync(r),d=c.mode&511;if(!c.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let i=g.constants.O_NOFOLLOW??0;n=g.openSync(t,g.constants.O_APPEND|g.constants.O_CREAT|g.constants.O_WRONLY|(g.constants.O_NONBLOCK??0)|i,384);let o=g.fstatSync(n),s=g.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let u=o.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`);g.fchmodSync(n,384)}catch(r){if(n!==null)try{g.closeSync(n)}catch{}Z||Y({event:"sidecar_disabled",reason:"open_failed",detail:E(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${E(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}q=t,L=n,H=!0}var $r=[/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 Dr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return $r.some(n=>n.test(t))}function Wt(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=Ur(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Dr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Ur(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Fr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Wt(e.url)}:e}function Gr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=M(i,pe()),s=JSON.stringify({version:Ht,timestamp:t,type:r,...o});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||!q||L===null)return;let t=Fr(e),n=Gr(t);try{if(g.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Qe){H=!1;try{g.closeSync(L)}catch{}L=null,Z||Y({event:"sidecar_disabled",reason:"size_limit",...q===null?{}:{path:E(q)},max_bytes:Qe},`${E(`[allscale] sidecar exceeded ${Qe} bytes; disabling it for the rest of this run. Rotate or remove ${q}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
|
+
`);return}g.appendFileSync(L,`${n}
|
|
7
|
+
`)}catch(r){if(H=!1,L!==null){try{g.closeSync(L)}catch{}L=null}try{Z||Y({event:"sidecar_disabled",reason:"write_failed",detail:E(r.message)},`${E(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var C=Wt;function Jt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Q(){if(Z=!1,H=!1,L!==null){try{g.closeSync(L)}catch{}L=null}}function zt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Jt()||!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"]),Mr=new Set(Array.from(ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Kr=Array.from(ee).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Yr=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 o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);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 o=r.slice(0,2);if(Mr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Yr.has(r)?void 0:Kr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function Xt(e){y({type:"error",code:e.code,message:E(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),Q()}var te=J()??vt,W={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function R(e){return Pt(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 Vt(){let e=process.env[W.TOKEN]?.trim();return e&&e.length>0?e:void 0}function nt(){let e=process.env[W.PROFILE]?.trim();return e&&e.length>0?e:void 0}function he(){let e=process.env[W.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Zt(){let e=process.env[W.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Qt(){let e=process.env[W.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function en(){let e=process.env[W.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function tn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(J()===void 0&&te!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
|
|
9
|
+
The CLI default is now ${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
|
-
To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
|
-
To move to production, run:
|
|
14
|
-
`}var
|
|
15
|
-
`)}},pe=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"]),Br=new Set(Array.from(pe).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function $r(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(pe.has(o)){t.push(`${o}=<redacted>`);continue}}}if(pe.has(r)){t.push(r),n+1<e.length&&(pe.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(Br.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Dr=/(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 Ur(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Dr.test(t)}var Fr=/_(removed|cleared|count|total)$/i;function Gr(e,t){return typeof t=="number"&&Fr.test(e)}var Mr=new Set(Qt);function Kr(e,t){return e==="token_symbol"&&typeof t=="string"&&Mr.has(t)}var fe=100;function Ze(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,fe),r=n.map(i=>Ze(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,fe))n[i]=Ur(i)&&!Gr(i,o)&&!Kr(i,o)?"<redacted>":Ze(o,t+1);if(r.length>fe){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-fe} more keys`}return n}return typeof e=="string"?b(e):e}function Yr(e){let t=$t()?void 0:2,n=Ze(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:b(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Hr(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 qr(e,t={}){let n;try{n=zt(ue())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Ct(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function ge(e){if(e.profileExplicit){let t=qr(e.profile);if(t)return t}return new l("auth.no_token",Ot(e.profile,e.flow))}var pn=E(require("path"));var tt=require("crypto"),a=E(require("fs")),m=E(require("path"));var he=1024*1024,jr=5e3,Jr=20,Wr=3e4,Qe=4096,zr=new Int32Array(new SharedArrayBuffer(4)),ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function me(e){return e instanceof ee}var A=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Vr=null;function B(){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 _e(){return(Vr??process.platform)!=="win32"}function ln(){if(!_e())throw B()}function cn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!h(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(m.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(h(t,"ENOENT"))return!0;throw t}}function h(e,t){return typeof e=="object"&&e!==null&&e.code===t}function te(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ne(e,t){return e.dev===t.dev&&e.ino===t.ino}function Xr(e){Atomics.wait(zr,0,0,e)}function un(e){try{return process.kill(e,0),!0}catch(t){return!h(t,"ESRCH")}}function Zr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function en(e,t){let n=m.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&h(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()||!ne(o,s))throw new Error("credential-store parent changed while it was being inspected");te(o,"credential-store parent");let u=o;if((o.mode&63)!==0&&m.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&&h(o,"ENOENT")?new A:o}if(!ne(n,i))throw r.retryOnPathChange?new A: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 ee;if(te(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 Qr(e,t){if(t.size>he)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(he+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>he)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function tn(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(h(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(h(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return Qr(t,r)}finally{t!==null&&a.default.closeSync(t)}}function nn(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(h(i,"ENOENT")&&cn(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);$(e,r)}finally{t!==null&&a.default.closeSync(t)}fn(m.dirname(e))}function ei(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(h(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 ee;te(t,"credential-store replacement target")}function ti(e,t){for(let n=0;n<8;n+=1){let r=(0,tt.randomBytes)(12).toString("hex"),i=m.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(h(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function dn(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 fn(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 ni(e,t){let n=Buffer.from(t,"utf8");if(n.length>he)throw new Error("credential-store file exceeds the maximum supported size");let r=m.dirname(e),i=m.basename(e),o=null,s=null,u=!1;try{let c=ti(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");dn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),ei(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{}}fn(r)}function ri(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock`)}function ii(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock-recovery`)}function oi(e,t){if(t.size>Qe)return null;let n=Buffer.alloc(Qe+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>Qe)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function $(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ne(n,t))throw new Error("credential-store lock changed while it was being inspected");te(n,"credential-store lock"),a.default.unlinkSync(e)}function rn(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(h(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 A}catch(d){if(h(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=oi(n,i);return{state:(o?.target===t&&o?!un(o.pid):Date.now()-i.mtimeMs>=Wr)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function si(e,t){for(let n=0;n<8;n+=1){let r=(0,tt.randomBytes)(12).toString("hex"),i=m.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 dn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:c}}catch(u){if(h(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 ai(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 h(r,"ENOENT")?new A:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ne(i,t))throw new A;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function on(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(h(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 A}catch(r){if(h(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 li(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(h(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{$(e,n)}catch{}throw a.default.closeSync(t),r}}function P(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");Xr(Jr)}function sn(e){let t=m.dirname(e),n=m.basename(e),r=ri(e),i=ii(e),o=si(t,n),s=Date.now()+jr,u=!1,c=!1,d=null,f;try{for(;d===null;)try{if(on(i)){P(s,!0);continue}a.default.linkSync(o.claimPath,r),c=!0,d=ai(r,o.stats),u=!0}catch(p){if(c&&!u){try{$(r,o.stats)}catch{}c=!1}if(p instanceof A){P(s,!1);continue}if(!h(p,"EEXIST"))throw p;let w;try{w=rn(r,n)}catch(L){if(L instanceof A){P(s,!1);continue}throw L}if(w.state==="absent")continue;if(w.state==="stale"){let L;try{L=li(i)}catch(S){if(S instanceof A){P(s,!1);continue}throw S}if(L!==null){try{let S;try{S=rn(r,n)}catch(ie){if(ie instanceof A){P(s,!1);continue}throw ie}S.state==="stale"&&$(r,S.stats)}finally{et(L)}continue}}let _;try{_=on(i)}catch(L){if(L instanceof A){P(s,!1);continue}throw L}P(s,_)}}catch(p){f=p}try{$(o.claimPath,o.stats)}catch(p){!h(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 et(e){try{$(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function ci(e,t){let n=Zr(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 an(e){let t=m.dirname(e),n=m.basename(e);for(let r of a.default.readdirSync(t)){let i=ci(r,n);if(i===null||un(i))continue;let o=m.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(h(d,"ENOENT")||h(d,"ELOOP"))continue;throw d}let u=a.default.fstatSync(s),c=a.default.lstatSync(o);if(!u.isFile()||c.isSymbolicLink()||!c.isFile()||!ne(u,c))continue;try{te(u,"credential-store orphan")}catch{continue}$(o,u)}catch(u){if(!h(u,"ENOENT"))throw u}finally{s!==null&&a.default.closeSync(s)}}}function re(e,t,n){if(!_e()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw B();if(!en(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw B()}});let s=sn(e);try{return an(e),n({read:()=>tn(e),remove:()=>nn(e),write:()=>{throw B()}})}finally{et(s)}}if(!t.createParent){let o=!1;try{o=cn(e)}catch{throw B()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw B()}})}throw B()}if(!en(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=sn(e);try{return an(e),n({read:()=>tn(e),remove:()=>nn(e),write:o=>ni(e,o)})}finally{et(i)}}var nt="allscale-cli";function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gn(e){return st(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function U(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 rt(){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 ye(){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 D,it=!1;function ui(){return qt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function di(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 fi(){if(D!==void 0)return D;if(ui())return it=!1,D=null,D;try{D=require("keytar"),it=!1}catch(e){it=!di(e),D=null}return D}function hn(){let e=_e()?"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 ot(e){try{return await e()}catch{throw hn()}}var at=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ot(()=>this.keytar.getPassword(nt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw U("OS keychain")}if(!gn(r))throw U("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ot(()=>this.keytar.setPassword(nt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ot(()=>this.keytar.deletePassword(nt,t))}},pi="credentials.json",lt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??pn.join(Ve(),pi)}read(t){let n;try{n=t.read()}catch(i){throw me(i)?rt():U("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw U("plaintext file")}if(!st(r)||!st(r.profiles))throw U("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw me(r)?rt():ye()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!gn(r))throw U("plaintext file");return r}}async get(t){try{return re(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:U("plaintext file")}}async set(t,n){try{re(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:ye()}}async delete(t){try{re(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:ye()}}async clearProfile(t){try{return re(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:me(n)?rt():ye()}}};function we(e){if(e.insecureStorage)return ln(),new lt(e.insecureFilePath);let t=fi();if(t)return new at(t);throw hn()}var ct=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 Se(){return new ct}async function mn(e){if(e.token)return{kind:"override",accessToken:e.token};let n=await we({insecureStorage:e.insecureStorage}).get(e.profile),r=n?.api_base;return n?.agent_key?{kind:"agent",storedApiBase:r,businessId:gi(n.business_id)}:n?.access_token?{kind:"human",storedApiBase:r,accessToken:n.access_token}:{kind:"none"}}function gi(e){return typeof e=="string"&&e.length>0?e:void 0}function _n(e){let t=e.split(".");if(t.length!==3)throw new l("auth.token_expired","Stored token is not a valid JWT.");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 yn(e,t){if(typeof t=="string"&&t.length>0)return t;let n=await mn(e);switch(n.kind){case"override":case"human":return mi(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 ge({profile:e.profile,profileExplicit:e.profileExplicit});default:return hi(n)}}function hi(e){throw new l("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}function mi(e){let t=_n(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 Ee="allscale_access_token",ut="allscale_refresh_token";function wn(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 dt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function ft(e,t){return e.find(n=>n.name===t)?.value??null}var Sn=E(require("crypto")),En=E(require("fs")),An=E(require("path"));var _i="key-id",yi="x-allscale-cli-version",pt="cli-1",wi="aScaLe_cli_obf_v1",Si="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Ei(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 Ai=Ei(Si,wi),bn=`Bearer ${Ai}`;function kn(e,t){let n=Ne(e);if(n!==null)return t.find(r=>Ne(r.base)===n)}function bi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=kn(e,t);if(r)return r.key;if(N(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:N(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function ki(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?kn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&N(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():pt}if(!N(t[0].base))return pt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():pt}function Li(){return"0.1.0"}function Ti(){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 gt(e,t){let n=bi(t);if(!n)throw Ti();let r=ki(t),i=Math.floor(Date.now()/1e3).toString(),o=Sn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[yi]:Li()};return r.length>0&&(s[_i]=r),s}function Ln(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ht=256*1024,Ae=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"}},be=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 mt(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 Ae(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,w)=>{c=setTimeout(()=>{w(new be(e.status,d))},d),c.unref?.()});try{for(;;){let p=o.read(),{done:w,value:_}=f?await Promise.race([p,f]):await p;if(w)break;if(u+=_.byteLength,u>t)throw o.cancel().catch(()=>{}),new Ae(e.status,t,n.oversizeKind);s.push(Buffer.from(_))}}catch(p){throw p instanceof be&&o.cancel(p).catch(()=>{}),p}finally{c!==void 0&&clearTimeout(c);try{o.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var Ii="X-AllScale-Api-Key",Oi=3e4,Ci=32*1024*1024,Ri=4*1024*1024;function vi(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 Ni(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 xi(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 Rn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}xi(e.status,e.url)}}var Tn="--dns-result-order=ipv4first";async function ke(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=${Tn} 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=${Tn}`})}var F=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 l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");x(this.opts.apiBase),de(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=vi(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();Zt(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",u=vn(t.path),c=s==="required"?!0:s==="none"?!1:$i(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw ge({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Ln(t.body),f=!!o||!!r?.access_token;c&&f&&!this.opts.override&&Xe(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:c&&f,bodyForSig:d,tokens:r,extra:t.headers}),w=Date.now();y({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let _;try{_=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(S){throw new l("transport.network",`Network error contacting ${C(i)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:_.status,durationMs:Date.now()-w}),c&&!!r?.access_token&&!o&&_.status===401&&!t._isRefresh&&!this.opts.override){let S=await Ni(this.refreshSingleFlight(),t.signal),ie=this.buildHeaders({attachAuth:c&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),zn=Date.now();y({type:"request",method:t.method??"GET",url:i});let Te;try{Te=await fetch(i,{method:t.method??"GET",headers:ie,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Ie){throw new l("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Ie instanceof Error?Ie.message:String(Ie)}`)}return y({type:"response",status:Te.status,durationMs:Date.now()-zn}),In(Te,{withMetadata:n.withMetadata,authBearing:c,responseKind:On(t)})}return In(_,{withMetadata:n.withMetadata,authBearing:c&&f,agentKeyAuth:c&&!!o,responseKind:On(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...gt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=bn;let i=t.tokens;if(i?.agent_key)return r[Ii]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=dt([{name:Ee,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}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 ${Be()}.`);if(Xe(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=dt([{name:Ee,value:t.access_token},{name:ut,value:t.refresh_token}]),i=gt("",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(_){throw y({type:"refresh",ok:!1}),new l("transport.network",s&&_ instanceof Error&&_.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${_ instanceof Error?_.message:String(_)}`)}finally{clearTimeout(u)}y({type:"response",status:c.status,durationMs:0});try{await Rn(c)}catch(_){throw y({type:"refresh",ok:!1}),_}if(c.status!==200){y({type:"refresh",ok:!1}),await ke(c);let _=await Fi(c);throw await ke(c,_),Nn(c.status,_),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Be()}.`,{status:c.status})}let d=wn(c.headers),f=ft(d,Ee),p=ft(d,ut);if(!f||!p)throw y({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let w={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,w),y({type:"refresh",ok:!0}),w}},Pi=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function vn(e){let t=e.split(/[?#]/,1)[0];return Pi.some(n=>t===n||t.startsWith(`${n}/`))}var Bi=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function _t(e){let t=e.split(/[?#]/,1)[0];return Bi.some(n=>n.test(t))}function $i(e){return vn(e)||_t(e)}async function In(e,t={}){await Rn(e);let n=e.status>=200&&e.status<300;n||await ke(e);let r=t.responseKind??"mutation",o=await mt(e,n?r==="query"?Ci:Ri:ht,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await ke(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=Gi(s)??`HTTP ${e.status}`;if(Nn(e.status,s),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 On(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Cn=2014;function Di(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===Cn||n===String(Cn)}var Ui=1e4;async function Fi(e,t=Ui){if(e.status>=200&&e.status<300)return"";try{return await mt(e,ht,{timeoutMs:t})}catch{return""}}function Nn(e,t){if(!(e>=200&&e<300)&&Di(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"?t.slice(0,500):t})}function Gi(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 Mi=/^\/(api\/)?(v1\/)?public\//;function xn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Mi.test(n),i=n&&_t(n),o=r&&!i&&!t.forceAuth;if(e.token)return new F({apiBase:e.apiBase,tokenStore:Se(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new F({apiBase:e.apiBase,tokenStore:Se(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new F({apiBase:e.apiBase,tokenStore:we({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new F({apiBase:e.apiBase,tokenStore:Se(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var Pn=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:all"]),Bn=new Set(["payroll","admin:user","admin:org","admin:audit"]);function $n(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Dn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Ki={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"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",create_store:"store:all",auto_payout_session_status:"claim_link:read_only",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Yi={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"},Hi=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,qi=/is not available to API keys/i,Un=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Fn(e){if(typeof e!="string")return;let t=Hi.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=qi.test(n),o=!i&&Un.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(c=>c.trim()).filter(c=>Un.test(c));s=u.length>0?u:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Gn(e){let t=Yi[e];if(t!==void 0)return{ungrantableReason:t};let n=Ki[e];if(n!==void 0)return{scope:n}}function Mn(e){if(Bn.has($n(e)))return{kind:"ungrantable"};for(let t of Pn)if(Dn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Kn(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function Yn(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("; ")}function qn(e,t){let n=jn(e),r={graphql_error_count:ji(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Ji(e,t,r);if(n===3400)throw new l("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(Kn(e))throw new l("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${Yn(e)}`,r);if(n!==void 0)throw new l("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function jn(e){let t=Hn(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=Hn(r.code);if(i!==void 0)return i}}function Hn(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 ji(e){return Array.isArray(e)?e.length:e==null?0:1}function Ji(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Fn(Wi(e,jn(e))),s=Gn(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=Mn(c),w=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 \`${X()}\` with \`--scopes ${c}\`.`:`The browser approval screen does not offer \`${c}\`, so \`device-login\` cannot grant it \u2014 use \`${X()}\` with \`--scopes ${c}\`.`;return new l("auth.permission_denied",`The current agent key lacks \`${c}\`, required by ${r}.${f} ${w}`,{...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 \`${X()}\`) and grant the required scope.`,i)}function Wi(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 zi="/api/secure/graphql";async function Jn(e,t){t.showDoc&&process.stderr.write(`${t.document}
|
|
17
|
-
`);let r=await
|
|
12
|
+
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
|
+
To move to production, run: allscale device-login --api-base ${te}
|
|
14
|
+
`}var N=b(require("fs")),nn=b(require("os")),rt=b(require("path")),it=b(require("@iarna/toml"));var jr=".allscale",Wr="config.toml";function ot(){return rt.join(nn.homedir(),jr)}function Jr(){return rt.join(ot(),Wr)}function me(){let e=Jr();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return it.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function rn(e){return Object.keys(e.profile??{}).sort()}function on(e,t){return e.profile?.[t]}function sn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("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 l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+De)}function _e(e,t){P(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function an(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ye(e){let t=J();if(t===void 0||x(e))return;let n=R(e),r=X();if(r.length>0){let o=r.map(u=>R(u.base)).filter(u=>u!==null);if(n!==null&&o.includes(n))return;let s=r.map(u=>T(u.base)).join(", ");throw new l("input.invalid",`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.`)}let i=R(t);if(!(n!==null&&n===i))throw new l("input.invalid",`Refusing to send to ${T(e)} \u2014 this build only signs for ${T(t)}. Re-login against this build's environment, or use a build for that one.`)}var zr=require("@noble/hashes/sha3");var ln=["USDT","USDC"];var as=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var v=require("@oclif/core"),ne=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:z()==="public"}),"api-base":I.Flags.string({description:$e,helpGroup:"GLOBAL",hidden:z()==="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(z()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&he()!==void 0)throw new l("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=zt(this.jsonEnabled()),r=this.argv.length===0&&!n&&ni(t)?this.config.findCommand(this.id??""):void 0;if(r){Q();let o=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!en())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return y({type:"command-end",ok:!0}),Q(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ft(i),{data:i})}catch(t){let n=Ut(t);Xt({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,i=t["api-base"]??void 0,o=r!==void 0||nt()!==void 0,s=sn(n,r,nt()),u=on(n,s),c=i??he(),d=c??u?.api_base??te,f=tn({resolvedApiBase:d,fromExplicitOverride:c!==void 0,profileApiBase:u?.api_base,profileApiBaseSource:u?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,Y({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:c,profileApiBase:u?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||P(n),n}resolveContext(t){if(z()==="public"){if(t.token!==void 0)throw new l("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 l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&he()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:u,profileExplicit:c}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(P(i),ye(i)),{apiBase:i,profile:s,token:n??Vt(),insecureStorage:r||Zt(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:c}}emitError(t){process.stderr.write(`${ti(t)}
|
|
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 qn(e).request({method:"POST",path:yo,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});Qn(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var wo=`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
|
|
22
|
+
}`;async function nr(e,t){let n={...t,logo_url:t.logo_url??null},r=await tr(e,{kind:"mutation",operationName:"create_store",document:wo,variables:{input:n}});if(!r?.store)throw new l("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 ne{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."}),...ne.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Tn(n,t["business-id"]),i=await nr(n,{name:t.name,business_id:r,is_sandbox:!t.live,...t.type!==void 0?{type:t.type}:{},...t.description?{description:t.description}:{}}),o=i.store;return process.stderr.write(`
|
|
23
23
|
\u2713 Store created: ${o.name} (${o.id}) [${o.is_sandbox?"sandbox":"live"}]
|
|
24
24
|
API key: ${o.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
|
`),i}};
|
|
28
28
|
//# sourceMappingURL=create.js.map
|