@allscale/cli 0.1.0 → 1.0.2
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 +144 -45
- 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 +14 -14
- package/dist/commands/describe.js +13 -13
- package/dist/commands/device-login.js +29 -29
- package/dist/commands/invoice/get.js +15 -15
- package/dist/commands/invoice/list.js +16 -16
- package/dist/commands/invoice/pay.js +46 -43
- 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 +19 -13
- 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 +19 -18
- 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 +17 -15
- 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 +140 -296
- 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
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}
|
|
6
|
-
`);return}
|
|
7
|
-
`)}catch(r){if(H=!1,
|
|
8
|
-
`)}catch{}}}var C=
|
|
9
|
-
The CLI default is now ${
|
|
1
|
+
"use strict";var ar=Object.create;var le=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var pr=(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 lr(t))!dr.call(e,i)&&i!==n&&le(e,i,{get:()=>t[i],enumerable:!(r=cr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?ar(ur(e)):{},Ct(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e)),fr=e=>Ct(le({},"__esModule",{value:!0}),e);var No={};pr(No,{default:()=>Ne});module.exports=fr(No);var I=require("@oclif/core");var vt="public",Rt="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 z(){return"".trim()||void 0}function M(){return"public"}function R(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function 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:l}=o;if(typeof s!="string"||s.trim().length===0||typeof u!="string"||u.trim().length===0)continue;let d=typeof l=="string"?l.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 hr="device-login",gr=/^[A-Za-z0-9._-]{1,64}$/;function qe(e){return gr.test(e)?e:"<profile>"}function V(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":qe(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ue(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function $t(e){let t=qe(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 ${hr} --profile ${qe(e)}\`.`}var mr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},_r=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Ye(e){return(typeof e=="string"?e:String(e??"")).replace(_r,"")}var yr=64;function Me(e,t=new Map,n=0){if(typeof e=="string")return Ye(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=yr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let 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 c=class extends Error{code;details;constructor(t,n,r){super(Ye(n)),this.code=t,this.details=r&&Me(r),this.name="AllscaleError"}get exitCode(){return mr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Ut(e){if(e instanceof c)return e;if(e instanceof Error){if(Sr(e)){let t=Ar(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var wr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),br=[/^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 Sr(e){if(Er(e))return!0;let t=e.name??"";return wr.has(t)?t==="CLIError"?Ke(e,"parse")||Bt(e.message):!0:Bt(e.message)}function Er(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?Ye(e).split(`
|
|
2
|
+
`).some(t=>br.some(n=>n.test(t.trim()))):!1}function Ke(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Ar(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ft(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var h=A(require("fs")),ge=A(require("path")),Ht=A(require("crypto"));var kr="...<truncated>",Lr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Tr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ze=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,je=String.raw`(?:proxy[_-]?)?authorization`,Ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${je}"|'${je}'|${je})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ze}`,"gi"),Or=/\b(https?:\/\/)[^\s/?#]+@/gi,Cr=String.raw`(?:[A-Za-z0-9]+[_-])*`,vr=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(Cr),Rr=Mt(vr),xr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Gt}"|'${Gt}'|${Rr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ze}`,"gi"),He=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,Nr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${He}"|'${He}'|${He})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ze}`,"g");function de(e){return e.replace(Or,"$1<redacted>@").replace(Lr,"<redacted-jwt>").replace(Ir,"$1$2$3<redacted>").replace(xr,"$1$2<redacted>").replace(Nr,"$1$2<redacted>").replace(Tr,"Bearer <redacted>")}var Pr=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function pe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Pr.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=kr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let u="",l=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(l+p>t)break;u+=d,l+=p}return u}let i=t-r,o="",s=0;for(let u of e){let l=Buffer.byteLength(u,"utf8");if(s+l>i)break;o+=u,s+=l}return`${o}${n}`}function S(e,t=16384){return fe(Kt(de(e)),t)}var We=100,Br=8,$r=8*1024;function he(){return{remaining:$r}}function Je(e,t){let n=Math.min(16384,t.remaining),r=fe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function K(e,t,n=0,r={}){if(n>Br)return Je("<truncated>",t);if(typeof e=="string"){let i=de(e);return Je(r.escapeControls?Kt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,We),o=i.map(s=>K(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]=K(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 Yt(){return Ve}var qt="1";function Y(e,t){if(Ve){let n={...e};delete n.version;let r=he(),i={event:n.event,...n},o=K(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:qt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:qt,event:o.event,output_truncated:!0})),Xe.stderr.write(`${s}
|
|
4
|
+
`)}else Xe.stderr.write(t)}var jt="2",j=null,L=null,H=!1,Z=!1;function Dr(){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=Ht.randomBytes(4).toString("hex");return ge.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Qe=64*1024*1024,Ur=null;function et(e={}){if(e.quiet&&(Z=!0),H)return;let t=Dr();if(!t)return;j=null;let n=null;try{if((Ur??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=ge.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=h.statSync(r),d=l.mode&511;if(!l.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let i=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|i,384);let o=h.fstatSync(n),s=h.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let 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`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}Z||Y({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${S(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}j=t,L=n,H=!0}var Fr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Gr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fr.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=Mr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Gr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Mr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Kr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Wt(e.url)}:e}function qr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=K(i,he()),s=JSON.stringify({version:jt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:jt,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!H||!j||L===null)return;let t=Kr(e),n=qr(t);try{if(h.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Qe){H=!1;try{h.closeSync(L)}catch{}L=null,Z||Y({event:"sidecar_disabled",reason:"size_limit",...j===null?{}:{path:S(j)},max_bytes:Qe},`${S(`[allscale] sidecar exceeded ${Qe} bytes; disabling it for the rest of this run. Rotate or remove ${j}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
|
+
`);return}h.appendFileSync(L,`${n}
|
|
7
|
+
`)}catch(r){if(H=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{Z||Y({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var C=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{h.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"]),Yr=new Set(Array.from(ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),jr=Array.from(ee).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Hr=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(Yr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Hr.has(r)?void 0:jr.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:S(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),Q()}var te=z()??Rt,J={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function x(e){return 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[J.TOKEN]?.trim();return e&&e.length>0?e:void 0}function nt(){let e=process.env[J.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ne(){let e=process.env[J.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Zt(){let e=process.env[J.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Qt(){let e=process.env[J.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function en(){let e=process.env[J.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function tn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(z()===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=A(require("fs")),nn=A(require("os")),rt=A(require("path")),it=A(require("@iarna/toml"));var zr=".allscale",Xr="config.toml";function ot(){return rt.join(nn.homedir(),zr)}function Vr(){return rt.join(ot(),Xr)}function me(){let e=Vr();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return it.parse(t)}catch(n){throw new c("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 c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function P(e){if(!Ue(e))throw new c("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+De)}function _e(e,t){P(e);let n=x(e),r=typeof t=="string"?x(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new c("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function an(e,t){let n=x(e),r=x(t);if(!(n&&r===n))throw new c("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ye(e){let t=Qr(e);if(t)throw new c("input.invalid",t.message)}function Zr(){let e=z();if(e===void 0)return;let t=X();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Qr(e){let t=Zr();if(t===void 0||R(e))return;let{endpoints:n,fromPairs:r}=t,i=x(e),o=n.map(u=>x(u)).filter(u=>u!==null);if(i!==null&&o.includes(i))return;let s=n.map(u=>T(u)).join(", ");return{message:r?`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var ei=require("@noble/hashes/sha3");var cn=["USDT","USDC"];var bs=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var ti="unknown_otp_id",ni="invalid_code",ri="expired_code";function ii(e){return`'${e.replace(/'/g,"'\\''")}'`}function ln(e){return`Run \`allscale otp-send --email ${ii(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var oi=new Map([[ti,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${ln(t)}`],[ni,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[ri,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${ln(t)}`]]);var un=[...oi.keys()];var v=require("@oclif/core"),re=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:M()==="public"}),"api-base":I.Flags.string({description:$e,helpGroup:"GLOBAL",hidden:M()==="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(M()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ne()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=zt(this.jsonEnabled()),r=this.argv.length===0&&!n&&hi(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 c("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return 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),l=M()==="public"&&ne()!==void 0,d=i??(l?void 0:ne()),p=d??u?.api_base??te,f=tn({resolvedApiBase:p,fromExplicitOverride:d!==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:p,profile:s},f)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:l,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(M()==="public"){if(t.token!==void 0)throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ne()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:u,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(P(i),ye(i)),{apiBase:i,profile:u,token:n??Vt(),insecureStorage:r||Zt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${fi(t)}
|
|
15
|
+
`)}};var si=/_(removed|cleared|count|total)$/i;function ai(e,t){return typeof t=="number"&&si.test(e)}var ci=new Set(cn);function li(e,t){return e==="token_symbol"&&typeof t=="string"&&ci.has(t)}var ui=new Set(un);function di(e,t){return e==="otp_reason"&&typeof t=="string"&&ui.has(t)}var we=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(i=>be(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]=pe(i)&&!ai(i,o)&&!li(i,o)&&!di(i,o)?"<redacted>":be(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=pi(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function pi(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 fi(e){let t=Yt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function hi(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 gi(e,t={}){let n;try{n=rn(me())}catch{return}if(!(n.length===0||n.includes(e)))return new c("auth.unknown_profile",Dt(e)+(t.messageSuffix??""),{profile:e})}function Se(e){if(e.profileExplicit){let t=gi(e.profile);if(t)return t}return new c("auth.no_token",$t(e.profile))}var An=A(require("path"));var ct=require("crypto"),a=A(require("fs")),_=A(require("path"));var Ee=1024*1024,mi=5e3,_i=20,yi=3e4,st=4096,wi=new Int32Array(new SharedArrayBuffer(4)),ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ae(e){return e instanceof ie}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},bi=null;function $(){return new c("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function ke(){return(bi??process.platform)!=="win32"}function yn(){if(!ke())throw $()}function wn(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 oe(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function se(e,t){return e.dev===t.dev&&e.ino===t.ino}function Si(e){Atomics.wait(wi,0,0,e)}function bn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function Ei(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(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()||!se(o,s))throw new Error("credential-store parent changed while it was being inspected");oe(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(!se(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 ie;if(oe(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 Ai(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}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(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 Ai(t,r)}finally{t!==null&&a.default.closeSync(t)}}function fn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT")&&wn(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)}En(_.dirname(e))}function ki(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 ie;oe(t,"credential-store replacement target")}function Li(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.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 Sn(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 En(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 Ti(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),i=_.basename(e),o=null,s=null,u=!1;try{let l=Li(r,i);o=l.fd,s=l.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");Sn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let f=o;o=null,a.default.closeSync(f),ki(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{}}En(r)}function Ii(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Oi(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Ci(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()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");oe(n,"credential-store lock"),a.default.unlinkSync(e)}function hn(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(l){if(m(l,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Ci(n,i);return{state:(o?.target===t&&o?!bn(o.pid):Date.now()-i.mtimeMs>=yi)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function vi(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.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),l=O(i,s,u,{allowMultipleLinks:!0});return Sn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}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 Ri(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(!se(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function gn(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 xi(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");Si(_i)}function mn(e){let t=_.dirname(e),n=_.basename(e),r=Ii(e),i=Oi(e),o=vi(t,n),s=Date.now()+mi,u=!1,l=!1,d=null,p;try{for(;d===null;)try{if(gn(i)){B(s,!0);continue}a.default.linkSync(o.claimPath,r),l=!0,d=Ri(r,o.stats),u=!0}catch(f){if(l&&!u){try{D(r,o.stats)}catch{}l=!1}if(f instanceof k){B(s,!1);continue}if(!m(f,"EEXIST"))throw f;let b;try{b=hn(r,n)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}if(b.state==="absent")continue;if(b.state==="stale"){let w;try{w=xi(i)}catch(E){if(E instanceof k){B(s,!1);continue}throw E}if(w!==null){try{let E;try{E=hn(r,n)}catch(ce){if(ce instanceof k){B(s,!1);continue}throw ce}E.state==="stale"&&D(r,E.stats)}finally{at(w)}continue}}let g;try{g=gn(i)}catch(w){if(w instanceof k){B(s,!1);continue}throw w}B(s,g)}}catch(f){p=f}try{D(o.claimPath,o.stats)}catch(f){!m(f,"ENOENT")&&!u&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function at(e){try{D(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Ni(e,t){let n=Ei(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 _n(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let i=Ni(r,n);if(i===null||bn(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),l=a.default.lstatSync(o);if(!u.isFile()||l.isSymbolicLink()||!l.isFile()||!se(u,l))continue;try{oe(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 ae(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw $();if(!dn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw $()}});let s=mn(e);try{return _n(e),n({read:()=>pn(e),remove:()=>fn(e),write:()=>{throw $()}})}finally{at(s)}}if(!t.createParent){let o=!1;try{o=wn(e)}catch{throw $()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw $()}})}throw $()}if(!dn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=mn(e);try{return _n(e),n({read:()=>pn(e),remove:()=>fn(e),write:o=>Ti(e,o)})}finally{at(i)}}var lt="allscale-cli";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kn(e){return ft(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new c("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function ut(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Le(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var U,dt=!1;function Pi(){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 $i(){if(U!==void 0)return U;if(Pi())return dt=!1,U=null,U;try{U=require("keytar"),dt=!1}catch(e){dt=!Bi(e),U=null}return U}function Ln(){let e=ke()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new c("storage.unavailable","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 pt(e){try{return await e()}catch{throw Ln()}}var ht=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await pt(()=>this.keytar.getPassword(lt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!kn(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await pt(()=>this.keytar.setPassword(lt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await pt(()=>this.keytar.deletePassword(lt,t))}},Di="credentials.json",gt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??An.join(ot(),Di)}read(t){let n;try{n=t.read()}catch(i){throw Ae(i)?ut():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!ft(r)||!ft(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ae(r)?ut():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!kn(r))throw F("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:F("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof c?r:Le()}}async delete(t){try{ae(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof c?n:Le()}}async clearProfile(t){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof c?n:Ae(n)?ut():Le()}}};function Te(e){if(e.insecureStorage)return yn(),new gt(e.insecureFilePath);let t=$i();if(t)return new ht(t);throw Ln()}var mt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new c("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ie(){return new mt}async function Tn(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:Ui(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 Ui(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 On(e){let t=e.split(".");if(t.length!==3)throw new c("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let n;try{let r=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");n=JSON.parse(r)}catch{throw In()}if(typeof n!="object"||n===null||Array.isArray(n))throw In();return n}function In(){return new c("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}async function Cn(e,t){if(typeof t=="string"&&t.length>0)return t;let n=await Tn(e);switch(n.kind){case"override":case"human":return Gi(n.accessToken);case"agent":if(n.businessId!==void 0)return n.businessId;throw new c("input.invalid","Agent-key sessions carry no JWT to derive the business id from \u2014 pass --business-id explicitly. (Re-run `allscale device-login` to store your business id automatically.)");case"none":throw Se({profile:e.profile,profileExplicit:e.profileExplicit});default:return Fi(n)}}function Fi(e){throw new c("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}function Gi(e){let t=On(e),n=typeof t.user_id=="string"?t.user_id:void 0;if(!n)throw new c("input.invalid","Could not infer --business-id from the cached JWT (no user_id claim). Pass --business-id explicitly.");return n}var Oe="allscale_access_token",yt="allscale_refresh_token";function vn(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 bt(e,t){return e.find(n=>n.name===t)?.value??null}var Rn=A(require("crypto")),xn=A(require("fs")),Nn=A(require("path"));var Mi="key-id",Ki="x-allscale-cli-version",St="cli-1",qi="aScaLe_cli_obf_v1",Yi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function ji(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 Hi=ji(Yi,qi),Pn=`Bearer ${Hi}`;function Bn(e,t){let n=Ge(e);if(n!==null)return t.find(r=>Ge(r.base)===n)}function Wi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=Bn(e,t);if(r)return r.key;if(R(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:R(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Ji(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?Bn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&R(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():St}if(!R(t[0].base))return St}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():St}function zi(){return"1.0.2"}function Xi(){return new c("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Et(e,t){let n=Wi(t);if(!n)throw Xi();let r=Ji(t),i=Math.floor(Date.now()/1e3).toString(),o=Rn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Ki]:zi()};return r.length>0&&(s[Mi]=r),s}function $n(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var Vi=500,Zi=8,Dn=100;function At(e,t=0){if(t>Zi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Dn),r=n.map(i=>At(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,i]of Object.entries(e).slice(0,Dn))n[r]=pe(r)?"<redacted>":At(i,t+1);return n}return e}function Qi(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 Un(e,t=Vi){let n=Qi(e),r=n===void 0?de(e):JSON.stringify(At(n));return fe(r,t)}var kt=256*1024,Ce=class extends c{constructor(t,n,r="backend-envelope"){let 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"}},ve=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function Lt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),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,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,b)=>{l=setTimeout(()=>{b(new ve(e.status,d))},d),l.unref?.()});try{for(;;){let f=o.read(),{done:b,value:g}=p?await Promise.race([f,p]):await f;if(b)break;if(u+=g.byteLength,u>t)throw o.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(f){throw f instanceof ve&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,u).toString("utf8")}var eo="X-AllScale-Api-Key",to=3e4,no=32*1024*1024,ro=4*1024*1024;function io(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 oo(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 so(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${C(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function qn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}so(e.status,e.url)}}var Fn="--dns-result-order=ipv4first";async function Re(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",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),l=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||u)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new c("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Fn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Fn}`})}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??to;if(!Number.isFinite(r)||r<1)throw new c("input.invalid","HTTP request timeout must be a positive number of milliseconds.");P(this.opts.apiBase),ye(this.opts.apiBase);let 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=io(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new c("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof c)?new c("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{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=Yn(t.path),l=s==="required"?!0:s==="none"?!1:lo(t.path);if((u||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw Se({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=$n(t.body),p=!!o||!!r?.access_token;l&&p&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();y({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(i,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new c("transport.network",`Network error contacting ${C(i)}: ${E instanceof Error?E.message:String(E)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-b}),l&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await oo(this.refreshSingleFlight(),t.signal),ce=this.buildHeaders({attachAuth:l&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),sr=Date.now();y({type:"request",method:t.method??"GET",url:i});let Pe;try{Pe=await fetch(i,{method:t.method??"GET",headers:ce,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new c("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return y({type:"response",status:Pe.status,durationMs:Date.now()-sr}),Gn(Pe,{withMetadata:n.withMetadata,authBearing:l,responseKind:Mn(t)})}return Gn(g,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:Mn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Et(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Pn;let i=t.tokens;if(i?.agent_key)return r[eo]=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 c("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new c("auth.token_expired",`No refresh token available; log in again \u2014 ${ue()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new c("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=wt([{name:Oe,value:t.access_token},{name:yt,value:t.refresh_token}]),i=Et("",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),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(g){throw y({type:"refresh",ok:!1}),new c("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(u)}y({type:"response",status:l.status,durationMs:0});try{await qn(l)}catch(g){throw y({type:"refresh",ok:!1}),g}if(l.status!==200){let g=null;try{await Re(l);let w=await go(l);await Re(l,w),Hn(l.status,w),l.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw y({type:"refresh",ok:!1}),w}if(g)return y({type:"refresh",ok:!0,adopted:!0}),g;throw y({type:"refresh",ok:!1}),new c("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:l.status})}let d=vn(l.headers),p=bt(d,Oe),f=bt(d,yt);if(!p||!f)throw y({type:"refresh",ok:!1}),new c("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,b),y({type:"refresh",ok:!0}),b}},ao=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Yn(e){let t=e.split(/[?#]/,1)[0];return ao.some(n=>t===n||t.startsWith(`${n}/`))}var co=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Tt(e){let t=e.split(/[?#]/,1)[0];return co.some(n=>n.test(t))}function lo(e){return Yn(e)||Tt(e)}async function Gn(e,t={}){await qn(e);let n=e.status>=200&&e.status<300;n||await Re(e);let r=t.responseKind??"mutation",o=await Lt(e,n?r==="query"?no:ro:kt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Re(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 l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:s}}return s}let u=mo(s)??`HTTP ${e.status}`;if(Hn(e.status,s),fo(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new c("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new c(l,u,{status:401,body:s})}throw e.status===403?new c("auth.permission_denied",u,{status:403,body:s}):e.status===404?new c("not_found",u,{status:404,body:s}):e.status===429?new c("rate_limited",u,{status:429,body:s}):e.status>=500?new c("backend.internal",u,{status:e.status,body:s}):new c("input.invalid",u,{status:e.status,body:s})}function Mn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var uo=2014,Kn=2004;function jn(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 po(e){return jn(e,uo)}function fo(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&jn(t,Kn))throw new c("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Kn})}var ho=1e4;async function go(e,t=ho){if(e.status>=200&&e.status<300)return"";try{return await Lt(e,kt,{timeoutMs:t})}catch{return""}}function Hn(e,t){if(!(e>=200&&e<300)&&po(t))throw new c("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?Un(t):t})}function mo(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 _o=/^\/(api\/)?(v1\/)?public\//;function Wn(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&_o.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 yo=new Set;var wo=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),It=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Ot=new Set(["payroll","admin:user","admin:org","admin:audit"]);function xe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Jn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var bo=new Set(["cli_op:all"]),So=new Set([...bo].map(xe));var Ta=new Set([...[...wo,...It,...yo].map(xe),...Ot,...So]);var Eo={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"},Ao={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"},ko=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,Lo=/is not available to API keys/i,zn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Xn(e){if(typeof e!="string")return;let t=ko.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=Lo.test(n),o=!i&&zn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let u=r.split(",").map(l=>l.trim()).filter(l=>zn.test(l));s=u.length>0?u:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Vn(e){let t=Ao[e];if(t!==void 0)return{ungrantableReason:t};let n=Eo[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(Jn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Qn(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function er(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 To=new Set([8100]),Io=new Set([...To,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function nr(e,t){let n=rr(e),r={graphql_error_count:Oo(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Co(e,t,r);if(n===429)throw new c("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new c("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&Io.has(n))throw new c("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(Qn(e))throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${er(e)}`,r);if(n!==void 0)throw new c("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function rr(e){let t=tr(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=tr(r.code);if(i!==void 0)return i}}function tr(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 Oo(e){return Array.isArray(e)?e.length:e==null?0:1}function Co(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Xn(vo(e,rr(e))),s=Vn(t.operationName),u=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,p=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(u||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new c("auth.permission_denied",`${r} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let f=Zn(l),b=f.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:f.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${V()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${V()}\` with \`--scopes ${l}\`.`;return new c("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${p} ${b}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new c("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${p} Re-run \`allscale device-login\` (or \`${V()}\`) and grant the required scope.`,i)}function vo(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 l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var Ro="/api/secure/graphql";async function ir(e,t){t.showDoc&&process.stderr.write(`${t.document}
|
|
17
|
+
`);let r=await Wn(e).request({method:"POST",path:Ro,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});nr(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var xo=`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 or(e,t){let n={...t,logo_url:t.logo_url??null},r=await ir(e,{kind:"mutation",operationName:"create_store",document:xo,variables:{input:n}});if(!r?.store)throw new c("backend.internal","create_store returned no store payload. The store was likely not created \u2014 check that this business has checkout enabled and that business_id matches your login, then retry.",{data:r});return r}var Ne=class e extends re{static description="Create a store for the logged-in business. Returns the API key and an API secret that is shown only once (it cannot be retrieved later \u2014 capture it now). The secret itself stays valid for use \u2014 it just cannot be displayed again. Business must have checkout enabled; only one sandbox store is allowed per business.";static examples=['$ allscale store create --name "My Shop"','$ allscale store create --name "Live Shop" --live','$ allscale store create --name "Acme" --business-id 665f0c1234567890abcdef12'];static flags={name:v.Flags.string({helpGroup:"REQUIRED",description:"Store display name (required).",required:!0}),"business-id":v.Flags.string({char:"b",description:"Owning business id. Defaults to the logged-in business (decoded from the session token). Admins creating for another business must pass this."}),live:v.Flags.boolean({description:"Create a live store. Default is a sandbox store (backend allows only one sandbox store per business).",default:!1}),type:v.Flags.integer({description:"Store type. 1 = checkout (the default). Payout credential stores are provisioned by Payout onboarding, not by this command. Omit for checkout."}),description:v.Flags.string({description:"Optional store description."}),...re.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Cn(n,t["business-id"]),i=await or(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
|