@allscale/cli 1.0.3 → 1.0.5
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 +5 -1
- package/dist/commands/claim-link/claim.js +12 -12
- package/dist/commands/claim-link/create.js +28 -28
- package/dist/commands/claim-link/get.js +11 -11
- package/dist/commands/claim-link/list.js +10 -10
- package/dist/commands/claim-link/status.js +12 -12
- package/dist/commands/describe.js +3 -3
- package/dist/commands/device-login.js +20 -20
- package/dist/commands/invoice/get.js +11 -11
- package/dist/commands/invoice/list.js +11 -11
- package/dist/commands/invoice/pay.js +44 -44
- package/dist/commands/invoice/received.js +11 -11
- package/dist/commands/invoice/send.js +23 -23
- package/dist/commands/invoice/sent.js +10 -10
- package/dist/commands/invoice/update.js +11 -11
- package/dist/commands/operations.js +6 -6
- package/dist/commands/otp-login.js +14 -14
- package/dist/commands/otp-send.js +10 -10
- package/dist/commands/payout/send.js +9 -9
- package/dist/commands/payout/status.js +11 -11
- package/dist/commands/store/create.js +12 -12
- package/dist/commands/transaction/get.js +11 -11
- package/dist/commands/transaction/list.js +10 -10
- package/dist/commands/wallet/list.js +11 -11
- package/dist/commands/wallet/send.js +27 -27
- package/dist/index.js +13 -13
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var f=S(require("fs")),
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}j=t,k=n,H=!0}var
|
|
1
|
+
"use strict";var cr=Object.create;var pe=Object.defineProperty;var lr=Object.getOwnPropertyDescriptor;var ur=Object.getOwnPropertyNames;var dr=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty;var fr=(e,t)=>{for(var n in t)pe(e,n,{get:t[n],enumerable:!0})},Gt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ur(t))!pr.call(e,i)&&i!==n&&pe(e,i,{get:()=>t[i],enumerable:!(r=lr(t,i))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?cr(dr(e)):{},Gt(t||!e||!e.__esModule?pe(n,"default",{value:e,enumerable:!0}):n,e)),gr=e=>Gt(pe({},"__esModule",{value:!0}),e);var Eo={};fr(Eo,{default:()=>je});module.exports=gr(Eo);var Ye=require("process");var I=require("@oclif/core");var Kt="public",Yt="https://app.allscale.io";var jt=["https://app.allscale.io"];var We="Override the API base URL (public builds accept only https://app.allscale.io)";var Je="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Ht(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 qt(e){return Ht(e)!==null}function ze(e){let t=Ht(e);return t!==null&&jt.includes(t.origin)}function J(){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 Ve(e){try{return new URL(e).origin}catch{return null}}function z(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Xe()}function Xe(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:l,keyId:u}=o;if(typeof s!="string"||s.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:s.trim(),key:l,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var hr=/^[A-Za-z0-9._-]{1,64}$/;function mr(e){return hr.test(e)?e:"<profile>"}function et(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":mr(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}var yr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var _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 tt(e){return(typeof e=="string"?e:String(e??"")).replace(_r,"")}var wr=64;function Ze(e,t=new Map,n=0){if(typeof e=="string")return tt(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=wr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let l of e)s.push(Ze(l,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,l]of Object.entries(e))Object.defineProperty(o,s,{value:Ze(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(tt(n)),this.code=t,this.details=r&&Ze(r),this.name="AllscaleError"}get exitCode(){return yr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Jt(e){if(e instanceof c)return e;if(e instanceof Error){if(Er(e)){let t=kr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var br=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Sr=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Er(e){if(Ar(e))return!0;let t=e.name??"";return br.has(t)?t==="CLIError"?Qe(e,"parse")||Wt(e.message):!0:Wt(e.message)}function Ar(e){if(!Qe(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Qe(e,"parse")}function Wt(e){return e?tt(e).split(`
|
|
2
|
+
`).some(t=>Sr.some(n=>n.test(t.trim()))):!1}function Qe(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function kr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function zt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var f=S(require("fs")),_e=S(require("path")),tn=S(require("crypto"));var Lr="...<truncated>",Tr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Or=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,st=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,nt=String.raw`(?:proxy[_-]?)?authorization`,Ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${nt}"|'${nt}'|${nt})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${st}`,"gi"),vr=/\b(https?:\/\/)[^\s/?#]+@/gi,Cr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Rr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Vt=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)`,Xt=Vt(Cr),Pr=Vt(Rr),xr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Xt}"|'${Xt}'|${Pr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${st}`,"gi"),rt=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])((?:"${rt}"|'${rt}'|${rt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${st}`,"g");function fe(e){return e.replace(vr,"$1<redacted>@").replace(Tr,"<redacted-jwt>").replace(Ir,"$1$2$3<redacted>").replace(xr,"$1$2<redacted>").replace(Nr,"$1$2<redacted>").replace(Or,"Bearer <redacted>")}var Br=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function ge(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Br.test(t)}function Zt(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 he(e,t,n=Lr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",u=0;for(let d of n){let g=Buffer.byteLength(d,"utf8");if(u+g>t)break;l+=d,u+=g}return l}let i=t-r,o="",s=0;for(let l of e){let u=Buffer.byteLength(l,"utf8");if(s+u>i)break;o+=l,s+=u}return`${o}${n}`}function b(e,t=16384){return he(Zt(fe(e)),t)}var it=100,Dr=8,$r=8*1024;function me(){return{remaining:$r}}function ot(e,t){let n=Math.min(16384,t.remaining),r=he(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function G(e,t,n=0,r={}){if(n>Dr)return ot("<truncated>",t);if(typeof e=="string"){let i=fe(e);return ot(r.escapeControls?Zt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,it),o=i.map(s=>G(s,t,n+1,r));return e.length>i.length&&o.push(ot(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,l]of o.slice(0,it))i[s]=G(l,t,n+1,r);return o.length>it&&(i.output_truncated=!0),i}return e}var at=require("process");var ct=!1;function lt(e){ct=e}function ye(){return ct}var Qt="1";function Y(e,t){if(ct){let n={...e};delete n.version;let r=me(),i={event:n.event,...n},o=G(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})),at.stderr.write(`${s}
|
|
4
|
+
`)}else at.stderr.write(t)}var en="2",j=null,k=null,H=!1,X=!1;function Ur(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=tn.randomBytes(4).toString("hex");return _e.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var ut=64*1024*1024,Fr=null;function dt(e={}){if(e.quiet&&(X=!0),H)return;let t=Ur();if(!t)return;j=null;let n=null;try{if((Fr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=_e.dirname(t);if(f.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=f.statSync(r),d=u.mode&511;if(!u.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let i=f.constants.O_NOFOLLOW??0;n=f.openSync(t,f.constants.O_APPEND|f.constants.O_CREAT|f.constants.O_WRONLY|(f.constants.O_NONBLOCK??0)|i,384);let o=f.fstatSync(n),s=f.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let l=o.mode&511;if((l&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${l.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);f.fchmodSync(n,384)}catch(r){if(n!==null)try{f.closeSync(n)}catch{}X||Y({event:"sidecar_disabled",reason:"open_failed",detail:b(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${b(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}j=t,k=n,H=!0}var Mr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Gr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Mr.some(n=>n.test(t))}function nn(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=Kr(t.pathname);let 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 Kr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Yr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:nn(e.url)}:e}function jr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=G(i,me()),s=JSON.stringify({version:en,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:en,timestamp:t,type:r,output_truncated:!0})),s}function P(e){if(!H||!j||k===null)return;let t=Yr(e),n=jr(t);try{if(f.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>ut){H=!1;try{f.closeSync(k)}catch{}k=null,X||Y({event:"sidecar_disabled",reason:"size_limit",...j===null?{}:{path:b(j)},max_bytes:ut},`${b(`[allscale] sidecar exceeded ${ut} 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
6
|
`);return}f.appendFileSync(k,`${n}
|
|
7
7
|
`)}catch(r){if(H=!1,k!==null){try{f.closeSync(k)}catch{}k=null}try{X||Y({event:"sidecar_disabled",reason:"write_failed",detail:b(r.message)},`${b(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
-
`)}catch{}}}var nn
|
|
8
|
+
`)}catch{}}}var rn=nn;function we(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function V(){if(X=!1,H=!1,k!==null){try{f.closeSync(k)}catch{}k=null}}function on(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||we()||!t}var Z=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Hr=new Set(Array.from(Z).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),qr=Array.from(Z).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Wr=new Set(["--otp-stdin","--password-stdin"]);function pt(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(Z.has(s)){t.push(`${s}=<redacted>`);continue}}}if(Z.has(r)){t.push(r),n+1<e.length&&(Z.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(Hr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Wr.has(r)?void 0:qr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function sn(e){P({type:"error",code:e.code,message:b(e.message)}),P({type:"command-end",ok:!1,exitCode:e.exitCode}),V()}var Q=J()??Yt,W={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function ft(e){return qt(e)?new URL(e).origin:null}function ee(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function an(){let e=process.env[W.TOKEN]?.trim();return e&&e.length>0?e:void 0}function gt(){let e=process.env[W.PROFILE]?.trim();return e&&e.length>0?e:void 0}function te(){let e=process.env[W.API_BASE]?.trim();return e&&e.length>0?e:void 0}function cn(){let e=process.env[W.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ln(){let e=process.env[W.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function un(){let e=process.env[W.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function dn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(J()===void 0&&Q!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
|
|
9
9
|
The CLI default is now ${Q} (production), but a saved profile wins over the default,
|
|
10
10
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
11
11
|
the old default rather than a deliberate choice.
|
|
12
12
|
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
13
|
To move to production, run: allscale device-login --api-base ${Q}
|
|
14
|
-
`}var L=S(require("fs")),dn=S(require("os")),gt=S(require("path")),we=S(require("@iarna/toml"));var zr=".allscale",Xr="config.toml";function be(){return gt.join(dn.homedir(),zr)}function Se(){return gt.join(be(),Xr)}function ne(){let e=Se();if(!L.existsSync(e))return{};let t=L.readFileSync(e,"utf-8");try{return we.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function pn(e){let t=be();L.existsSync(t)||L.mkdirSync(t,{recursive:!0,mode:448});let n=we.stringify(e),r=Se();L.writeFileSync(r,n,{mode:384});try{L.chmodSync(r,384)}catch{}}function fn(e,t){return e.profile?.[t]}function gn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function hn(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 Ee(e){if(!ze(e))throw new c("input.invalid",`Refusing to send credentials to API base ${ee(e)}. `+Je)}function ht(e){let t=Zr(e);if(t)throw new c("input.invalid",t.message)}function Vr(){let e=J();if(e===void 0)return;let t=z();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Zr(e){let t=Vr();if(t===void 0||R(e))return;let{endpoints:n,fromPairs:r}=t,i=pt(e),o=n.map(l=>pt(l)).filter(l=>l!==null);if(i!==null&&o.includes(i))return;let s=n.map(l=>ee(l)).join(", ");return{message:r?`Refusing to send to ${ee(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 ${ee(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Qr=require("@noble/hashes/sha3");var mn=["USDT","USDC"];var ls=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var yn=3100,ei=2090,ti=2001,ni=2092,T="allscale.io";function ke(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Le(e){try{let t=JSON.parse(e);if(typeof t.code=="number"&&Number.isInteger(t.code))return t.code;if(typeof t.code=="string"&&/^\d+$/.test(t.code)){let n=Number(t.code);if(Number.isSafeInteger(n))return n}}catch{}}var ri="unknown_otp_id",ii="invalid_code",oi="expired_code";function _n(e){try{let n=JSON.parse(e).extensions;if(!n||typeof n!="object")return;let r=n.reason;if(typeof r=="string"&&r.length>0)return r}catch{}}function si(e,t){return new c("not_found",`No AllScale account exists for '${e}' on this environment. Check the address for typos, try the email the account was created with, or sign up first if you do not have an account yet.`,{status:t,backend_code:yn})}function mt(e,t,n,r,i){let o=ke(e),s=o.endsWith(`.${T}`)?`@${T} subdomains are not whitelisted \u2014 use a bare @${T} address, or contact support / wait for the backend allowlist fix.`:`Use an @${T} address, or contact support / wait for the backend allowlist fix.`,l=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${T} addresses can receive a login code here. Re-run with an @${T} address.`:`Backend returned ${t} when sending OTP to external domain '${o}'. External-domain OTP delivery is likely restricted on this environment (e.g. Cloudflare verification); only @${T} is whitelisted.`;return new c(r,l,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function ai(e,t){return new c("auth.permission_denied","Login rejected: the email or password is incorrect. Note that AllScale Pay accounts have no password \u2014 use `allscale device-login` or `allscale otp-login` for those.",{status:e,...t===void 0?{}:{backend_code:t}})}function wn(e){if(e.length===0)throw new c("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new c("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function Te(e){if(e.trim().length===0)throw new c("input.invalid","An otp_id is required. Pass the value `allscale otp-send` returned via --otp-id, or omit --otp-id to have `allscale otp-login` send a fresh code.")}function ci(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ae(e){return`Run \`allscale otp-send --email ${ci(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}function yt(e,t,n,r){let i="incorrect, expired, already used, or locked after too many attempts";if(n){let s="This run's send step issued the otp_id moments ago and would itself have failed if the account did not exist, so neither a missing account nor an unknown otp_id explains this";return r?`${e}. ${s} \u2014 the code is what remains: ${i}. Request a fresh code and try again.`:`${e}, and the backend did not identify the failure. ${s}, but an unrecognised refusal can also come from a proxy or gateway the request never reached the app through \u2014 so a stale code (${i}) is the likeliest cause, not the only one. Request a fresh code; if it fails the same way, the refusal is not about the code.`}let o=`the code may be ${i} \u2014 or the account may not exist here, or --otp-id may not be an otp_id this environment issued`;return r?`${e}, and the CLI cannot tell which cause applies: ${o}. ${Ae(t)}`:`${e}, and the backend did not identify the failure: ${o} \u2014 or the request may not have reached the application at all. ${Ae(t)}`}var bn=new Map([[ri,(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. ${Ae(t)}`],[ii,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.`],[oi,(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. ${Ae(t)}`]]);function li(e,t,n,r=!1){if(n!==void 0)return bn.get(n)?.(e,t,r)}var Sn=[...bn.keys()];function En(e){if(e)throw new c("input.invalid","--no-existence-check is no longer supported: registration via the CLI OTP flow was removed (the CLI login endpoint only signs in existing accounts). Create the account in the AllScale web app first, then re-run without this flag.")}var ui=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:yn,build:e=>si(e.email,e.status)},{flows:["otp-send"],status:403,code:ei,when:e=>{let t=ke(e.email);return t.length>0&&t!==T},build:e=>mt(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:ni,build:e=>new c("auth.signature_rejected","The AllScale API rejected this request because this CLI build is not signed with the CLI signing key (the login endpoint is CLI-only). This is a build problem, not an input error: download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry. If you are already on the latest version, or this is a local/dev build signed with a non-CLI key, the signing-key row is misprovisioned \u2014 contact AllScale support.",{status:e.status,backend_code:e.backendCode})},{flows:["password"],status:400,code:ti,build:e=>ai(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>{let t=li("OTP rejected",e.email,e.reason,e.otpIdFromSendLeg===!0);return new c("input.invalid",t??yt("OTP rejected",e.email,e.otpIdFromSendLeg===!0,!0),{status:e.status,backend_code:e.backendCode,...t===void 0?{}:{otp_reason:e.reason}})}},{flows:["otp-verify"],status:400,code:7531,build:e=>new c("input.invalid","The backend requires at least one scope for the minted agent key \u2014 pass --scopes (e.g. --scopes invoice:read_only).",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7530,build:e=>new c("input.invalid","None of the requested scopes can be granted to this account, so no key was issued. Retry with different --scopes.",{status:e.status,backend_code:e.backendCode})}];function Oe(e){if(e.backendCode!==void 0){for(let t of ui)if(t.code===e.backendCode&&t.status===e.status&&t.flows.includes(e.flow)&&(t.when===void 0||t.when(e)))return t.build(e)}}var O=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:We,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{ct(this.jsonEnabled()),ut(),P({type:"session-start",command:this.id??"",argv:dt(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&&te()!==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=rn(this.jsonEnabled()),r=this.argv.length===0&&!n&&wi(t)?this.config.findCommand(this.id??""):void 0;if(r){V();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&&!ln())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 P({type:"command-end",ok:!0}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Jt(i),{data:i})}catch(t){let n=Wt(t);on({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{ct(!1)}}resolveSessionApiBaseChain(t){let n=ne(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||ft()!==void 0,s=hn(n,r,ft()),l=fn(n,s),u=M()==="public"&&te()!==void 0,d=i??(u?void 0:te()),g=d??l?.api_base??Q,p=un({resolvedApiBase:g,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,Y({event:"legacy_staging_profile",api_base:g,profile:s},p)),{apiBase:g,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Ee(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&&te()!==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:l,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Ee(i),ht(i)),{apiBase:i,profile:l,token:n??sn(),insecureStorage:r||an(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${_i(t)}
|
|
15
|
-
`)}};var di=/_(removed|cleared|count|total)$/i;function pi(e,t){return typeof t=="number"&&di.test(e)}var fi=new Set(mn);function gi(e,t){return e==="token_symbol"&&typeof t=="string"&&fi.has(t)}var hi=new Set(Sn);function mi(e,t){return e==="otp_reason"&&typeof t=="string"&&hi.has(t)}var Ie=100;function ve(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ie),r=n.map(i=>ve(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Ie))n[i]=fe(i)&&!pi(i,o)&&!gi(i,o)&&!mi(i,o)?"<redacted>":ve(o,t+1);if(r.length>Ie){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ie} more keys`}return n}if(typeof e=="string"){let n=yi(e);return n!==void 0?b(JSON.stringify(ve(n,t+1))):b(e)}return e}function yi(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 _i(e){let t=me()?void 0:2,n=ve(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:b(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function wi(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 _t(e){let t=new Map;for(let n of e){let r=n.lastIndexOf(":");if(r===-1){t.set(n,t.get(n)??new Set);continue}let i=n.slice(0,r),o=n.slice(r+1),s=t.get(i)??new Set;s.add(o),t.set(i,s)}return[...t].map(([n,r])=>{if(r.size===0)return n;if(r.size===1)return`${n}:${[...r][0]}`;let i=["read_only","all"].filter(o=>r.has(o));for(let o of r)i.includes(o)||i.push(o);return`${n}:{${i.join(",")}}`}).join(", ")}var bi=new Set,wt=new Set(["transaction:all"]),Ce=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"]),Si=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"]),An=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Re(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Ei(e){let t=e.lastIndexOf(":");if(t<=0||t===e.length-1)return!1;let n=e.slice(t+1);return n==="read_only"||n==="all"}var Ai=new Set(["cli_op:all"]),kn=new Set([...Ai].map(Re));var bt=new Set([...[...Ce,...Si,...bi].map(Re),...An,...kn]);function Ln(e,t){return ki({known:bt,ungrantable:An,implicit:kn,renderedAbove:e,blocksUngrantableLocally:t?.blocksUngrantableLocally??!1})}function C(e,t,n){return e===1?t:n}function ki(e){let{known:t,ungrantable:n,implicit:r}=e,i=new Set([...e.renderedAbove].map(d=>Re(d))),o=[...t].filter(d=>n.has(d)).sort(),s=[...t].filter(d=>r.has(d)).sort(),l=[...t].filter(d=>i.has(d)&&!n.has(d)&&!r.has(d)).sort(),u=[];return t.size>0&&u.push(`Every category recognised as a spelling, so a usable value can be found without guessing: ${[...t].sort().join(", ")}.`),l.length>0&&u.push(`${l.join(", ")} ${C(l.length,"carries","carry")} the tiers listed above.`),o.length>0&&u.push(`${o.join(", ")} ${C(o.length,"is","are")} in the catalog but granted to NOBODY \u2014 every mint path drops ${C(o.length,"it","them")}, so no login command can deliver ${C(o.length,"it","them")}`+(e.blocksUngrantableLocally?`; this command rejects ${C(o.length,"it","them")} locally, before any pairing session.`:`, and requesting ${C(o.length,"it","them")} gains nothing.`)),s.length>0&&u.push(`${s.join(", ")} ${C(s.length,"is","are")} attached to every key the backend mints, by both login commands, without being requested \u2014 you never need to ask for ${C(s.length,"it","them")}, and asking is not an error.`),`${u.join(" ")} `}function Li(e){return e.filter(t=>!Ei(t)||!bt.has(Re(t)))}function Tn(e){if(!e||e.length===0)return;let t=Li(e);if(t.length!==0)throw new c("input.invalid",`Unrecognised --scopes value${t.length>1?"s":""}: ${t.join(", ")}. Scope strings are <category>:<tier>, where tier is read_only or all. Known categories: ${[...bt].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}var Fn=S(require("path"));var At=require("crypto"),a=S(require("fs")),m=S(require("path"));var Pe=1024*1024,Ti=5e3,Oi=20,Ii=3e4,St=4096,vi=new Int32Array(new SharedArrayBuffer(4)),ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function xe(e){return e instanceof ie}var E=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ci=null;function N(){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 Ne(){return(Ci??process.platform)!=="win32"}function Nn(){if(!Ne())throw N()}function Bn(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 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 Ri(e){Atomics.wait(vi,0,0,e)}function Dn(e){try{return process.kill(e,0),!0}catch(t){return!h(t,"ESRCH")}}function Pi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function On(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()||!se(o,s))throw new Error("credential-store parent changed while it was being inspected");oe(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&m.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),l=a.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function v(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 E:o}if(!se(n,i))throw r.retryOnPathChange?new E: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 xi(e,t){if(t.size>Pe)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Pe+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Pe)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function In(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=v(e,t,n);return xi(t,r)}finally{t!==null&&a.default.closeSync(t)}}function vn(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")&&Bn(e))return;throw i}let n=a.default.fstatSync(t),r=v(e,t,n);B(e,r)}finally{t!==null&&a.default.closeSync(t)}Un(m.dirname(e))}function Ni(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 ie;oe(t,"credential-store replacement target")}function Bi(e,t){for(let n=0;n<8;n+=1){let r=(0,At.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 $n(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 Un(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 Di(e,t){let n=Buffer.from(t,"utf8");if(n.length>Pe)throw new Error("credential-store file exceeds the maximum supported size");let r=m.dirname(e),i=m.basename(e),o=null,s=null,l=!1;try{let u=Bi(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((v(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");$n(o,n),a.default.fsyncSync(o),v(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ni(e),a.default.renameSync(s,e),l=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!l&&s!==null)try{a.default.unlinkSync(s)}catch{}}Un(r)}function $i(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock`)}function Ui(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock-recovery`)}function Fi(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 B(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 Cn(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(u){if(h(u,"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 E}catch(d){if(h(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=v(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Fi(n,i);return{state:(o?.target===t&&o?!Dn(o.pid):Date.now()-i.mtimeMs>=Ii)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Mi(e,t){for(let n=0;n<8;n+=1){let r=(0,At.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 l=a.default.fstatSync(s),u=v(i,s,l,{allowMultipleLinks:!0});return $n(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(l){if(h(l,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw l}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Gi(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 E:r}try{let r=a.default.fstatSync(n),i=v(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(i,t))throw new E;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function Rn(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 E}catch(r){if(h(r,"ENOENT"))return!1;throw r}throw n}return v(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Ki(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=v(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{B(e,n)}catch{}throw a.default.closeSync(t),r}}function x(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");Ri(Oi)}function Pn(e){let t=m.dirname(e),n=m.basename(e),r=$i(e),i=Ui(e),o=Mi(t,n),s=Date.now()+Ti,l=!1,u=!1,d=null,g;try{for(;d===null;)try{if(Rn(i)){x(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Gi(r,o.stats),l=!0}catch(p){if(u&&!l){try{B(r,o.stats)}catch{}u=!1}if(p instanceof E){x(s,!1);continue}if(!h(p,"EEXIST"))throw p;let w;try{w=Cn(r,n)}catch(y){if(y instanceof E){x(s,!1);continue}throw y}if(w.state==="absent")continue;if(w.state==="stale"){let y;try{y=Ki(i)}catch(_){if(_ instanceof E){x(s,!1);continue}throw _}if(y!==null){try{let _;try{_=Cn(r,n)}catch(U){if(U instanceof E){x(s,!1);continue}throw U}_.state==="stale"&&B(r,_.stats)}finally{Et(y)}continue}}let A;try{A=Rn(i)}catch(y){if(y instanceof E){x(s,!1);continue}throw y}x(s,A)}}catch(p){g=p}try{B(o.claimPath,o.stats)}catch(p){!h(p,"ENOENT")&&!l&&g===void 0&&(g=p)}if(g!==void 0)throw g;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function Et(e){try{B(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Yi(e,t){let n=Pi(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 xn(e){let t=m.dirname(e),n=m.basename(e);for(let r of a.default.readdirSync(t)){let i=Yi(r,n);if(i===null||Dn(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 l=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!l.isFile()||u.isSymbolicLink()||!u.isFile()||!se(l,u))continue;try{oe(l,"credential-store orphan")}catch{continue}B(o,l)}catch(l){if(!h(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!Ne()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw N();if(!On(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw N()}});let s=Pn(e);try{return xn(e),n({read:()=>In(e),remove:()=>vn(e),write:()=>{throw N()}})}finally{Et(s)}}if(!t.createParent){let o=!1;try{o=Bn(e)}catch{throw N()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw N()}})}throw N()}if(!On(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Pn(e);try{return xn(e),n({read:()=>In(e),remove:()=>vn(e),write:o=>Di(e,o)})}finally{Et(i)}}var kt="allscale-cli";function It(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mn(e){return It(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function $(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 Lt(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Be(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var D,Tt=!1;function ji(){return cn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Hi(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 qi(){if(D!==void 0)return D;if(ji())return Tt=!1,D=null,D;try{D=require("keytar"),Tt=!1}catch(e){Tt=!Hi(e),D=null}return D}var Wi="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Gn(){let e=Ne()?"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",`${Wi} `+e+" Never silently downgrade in production.")}async function Ot(e){try{return await e()}catch{throw Gn()}}var vt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Ot(()=>this.keytar.getPassword(kt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw $("OS keychain")}if(!Mn(r))throw $("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Ot(()=>this.keytar.setPassword(kt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Ot(()=>this.keytar.deletePassword(kt,t))}},Ji="credentials.json",Ct=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Fn.join(be(),Ji)}read(t){let n;try{n=t.read()}catch(i){throw xe(i)?Lt():$("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw $("plaintext file")}if(!It(r)||!It(r.profiles))throw $("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw xe(r)?Lt():Be()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Mn(r))throw $("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:$("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:Be()}}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:Be()}}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:xe(n)?Lt():Be()}}};function Kn(e){if(e.insecureStorage)return Nn(),new Ct(e.insecureFilePath);let t=qi();if(t)return new vt(t);throw Gn()}async function Yn(e,t){await e.get(t)}async function jn(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof c?r.message:b(String(r)),o=n.agent_key?"An agent key was already minted for this account but could not be stored, so it is now orphaned: it cannot be listed or revoked from the CLI (key management is control-plane and rejects agent-key sessions). Remove it from the web dashboard.":"The session credential could not be stored, so nothing was persisted \u2014 no key record was created on the account. Re-run the command to authenticate again once storage is available.";throw new c(r instanceof c?r.code:"storage.unavailable",`${i} ${o}`,r instanceof c?r.details:void 0)}}var Hn=S(require("crypto")),qn=S(require("fs")),Wn=S(require("path"));var zi="key-id",Xi="x-allscale-cli-version",Rt="cli-1",Vi="aScaLe_cli_obf_v1",Zi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Qi(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 eo=Qi(Zi,Vi),to=`Bearer ${eo}`;function Jn(e,t){let n=Ve(e);if(n!==null)return t.find(r=>Ve(r.base)===n)}function no(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=Jn(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 ro(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?Jn(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():Rt}if(!R(t[0].base))return Rt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Rt}function io(){return"1.0.3"}function oo(){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 De(e,t){let n=no(t);if(!n)throw oo();let r=ro(t),i=Math.floor(Date.now()/1e3).toString(),o=Hn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Xi]:io()};return r.length>0&&(s[zi]=r),s}function $e(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var so=500,ao=8,zn=100;function Pt(e,t=0){if(t>ao)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,zn),r=n.map(i=>Pt(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,zn))n[r]=fe(r)?"<redacted>":Pt(i,t+1);return n}return e}function co(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 Ue(e,t=so){let n=co(e),r=n===void 0?pe(e):JSON.stringify(Pt(n));return ge(r,t)}var le=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"}},Fe=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 xt(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=[],l=0,u,d=n.timeoutMs,g=d===void 0?void 0:new Promise((p,w)=>{u=setTimeout(()=>{w(new Fe(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:w,value:A}=g?await Promise.race([p,g]):await p;if(w)break;if(l+=A.byteLength,l>t)throw o.cancel().catch(()=>{}),new ce(e.status,t,n.oversizeKind);s.push(Buffer.from(A))}}catch(p){throw p instanceof Fe&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}async function Nt(e,t){let n;try{n=await xt(e,t)}catch(r){if(r instanceof ce)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var ha=32*1024*1024,ma=4*1024*1024;function lo(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${nn(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 Me(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}lo(e.status,e.url)}}var uo=2014;function po(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 fo(e){return po(e,uo)}var go=1e4;async function Ge(e,t=go){if(e.status>=200&&e.status<300)return"";try{return await xt(e,le,{timeoutMs:t})}catch{return""}}function Ke(e,t){if(!(e>=200&&e<300)&&fo(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"?Ue(t):t})}var $t=require("process");var ho={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Xn(e){if(typeof e=="string")return e;if(typeof e=="number")return ho[e]??`user_type_${e}`}function Bt(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var Dt=require("process");var Vn=new Set;function Zn(e,t,n){me()||_e()||Dt.stderr.isTTY&&(Vn.has(e)||(Vn.add(e),Dt.stderr.write(`warning: ${e} was read from the command line, where other users on this host can see it via \`ps\` (and where your shell records it in history). Prefer ${t} or ${n}.
|
|
17
|
-
`)))}var mo="/api/v1/public/turnkey/cli/email-otps",yo="/api/v1/public/turnkey/email-otps",
|
|
18
|
-
`),
|
|
19
|
-
`);if(n!==-1)return e.slice(0,n).trim();if(Buffer.byteLength(e,"utf-8")>=bo)throw new c("input.invalid","OTP input exceeded the expected length (1 KB) before a newline; check the --otp-stdin pipe.")}}catch(t){throw t instanceof c?t:new c("input.invalid",`Failed to read OTP from stdin: ${t instanceof Error?t.message:String(t)}`)}return e.trim()}var je=class e extends re{static description="Terminal-only Email OTP login for headless / scripted shells. Works with any account email (external domains included; the account must already exist). Sends the code (unless --otp-id is supplied), reads it in the terminal, and mints a scoped agent API key whose granted scopes the backend checks on each request \u2014 the credential issued by the current CLI login flows. Scopes are set with --scopes (required; no full-permission default exists).";static examples=["$ allscale otp-login --email me@example.com --scopes invoice:read_only # interactive: prompts on stdin",`$ printf '%s' "$OTP" | allscale otp-login --email me@example.com --scopes invoice:all --otp-stdin`,"$ ALLSCALE_OTP=$(read-from-mailbox) allscale otp-login --email me@example.com --scopes claim_link:all","$ allscale otp-login --email me@example.com --scopes invoice:read_only --otp-id otp-request-id --otp 123456"];static flags={email:O.Flags.string({helpGroup:"REQUIRED",char:"e",description:"Account email",required:!0}),scopes:O.Flags.string({helpGroup:"REQUIRED",description:"Scopes the minted agent key should carry, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs that reach a real operation today: "+
|
|
20
|
-
`)}catch(_){throw _ instanceof c&&_.code==="rate_limited"&&_.details?.status===429?new c(_.code,"OTP send was rate-limited. If a code was already sent for this email by `allscale otp-send` or an earlier `allscale otp-login`, re-run the same `allscale otp-login` command with `--otp-id <earlier-otp-id>` using the exact otp_id that command returned or printed, and the same OTP input; otherwise wait before requesting another code.",_.details):_}let g=await
|
|
14
|
+
`}var L=S(require("fs")),pn=S(require("os")),ht=S(require("path")),be=S(require("@iarna/toml"));var Xr=".allscale",Vr="config.toml";function Se(){return ht.join(pn.homedir(),Xr)}function Ee(){return ht.join(Se(),Vr)}function ne(){let e=Ee();if(!L.existsSync(e))return{};let t=L.readFileSync(e,"utf-8");try{return be.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function fn(e){let t=Se();L.existsSync(t)||L.mkdirSync(t,{recursive:!0,mode:448});let n=be.stringify(e),r=Ee();L.writeFileSync(r,n,{mode:384});try{L.chmodSync(r,384)}catch{}}function gn(e,t){return e.profile?.[t]}function hn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function mn(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 Ae(e){if(!ze(e))throw new c("input.invalid",`Refusing to send credentials to API base ${ee(e)}. `+Je)}function mt(e){let t=Qr(e);if(t)throw new c("input.invalid",t.message)}function Zr(){let e=J();if(e===void 0)return;let t=z();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=ft(e),o=n.map(l=>ft(l)).filter(l=>l!==null);if(i!==null&&o.includes(i))return;let s=n.map(l=>ee(l)).join(", ");return{message:r?`Refusing to send to ${ee(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 ${ee(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 yn=["USDT","USDC"];var ls=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var _n=3100,ti=2090,ni=2001,ri=2092,T="allscale.io";function Le(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Te(e){try{let t=JSON.parse(e);if(typeof t.code=="number"&&Number.isInteger(t.code))return t.code;if(typeof t.code=="string"&&/^\d+$/.test(t.code)){let n=Number(t.code);if(Number.isSafeInteger(n))return n}}catch{}}var ii="unknown_otp_id",oi="invalid_code",si="expired_code";function wn(e){try{let n=JSON.parse(e).extensions;if(!n||typeof n!="object")return;let r=n.reason;if(typeof r=="string"&&r.length>0)return r}catch{}}function ai(e,t){return new c("not_found",`No AllScale account exists for '${e}' on this environment. Check the address for typos, try the email the account was created with, or sign up first if you do not have an account yet.`,{status:t,backend_code:_n})}function yt(e,t,n,r,i){let o=Le(e),s=o.endsWith(`.${T}`)?`@${T} subdomains are not whitelisted \u2014 use a bare @${T} address, or contact support / wait for the backend allowlist fix.`:`Use an @${T} address, or contact support / wait for the backend allowlist fix.`,l=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${T} addresses can receive a login code here. Re-run with an @${T} address.`:`Backend returned ${t} when sending OTP to external domain '${o}'. External-domain OTP delivery is likely restricted on this environment (e.g. Cloudflare verification); only @${T} is whitelisted.`;return new c(r,l,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function ci(e,t){return new c("auth.permission_denied","Login rejected: the email or password is incorrect. Note that AllScale Pay accounts have no password \u2014 use `allscale device-login` or `allscale otp-login` for those.",{status:e,...t===void 0?{}:{backend_code:t}})}function bn(e){if(e.length===0)throw new c("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new c("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function Oe(e){if(e.trim().length===0)throw new c("input.invalid","An otp_id is required. Pass the value `allscale otp-send` returned via --otp-id, or omit --otp-id to have `allscale otp-login` send a fresh code.")}function li(e){return`'${e.replace(/'/g,"'\\''")}'`}function ke(e){return`Run \`allscale otp-send --email ${li(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}function _t(e,t,n,r){let i="incorrect, expired, already used, or locked after too many attempts";if(n){let s="This run's send step issued the otp_id moments ago and would itself have failed if the account did not exist, so neither a missing account nor an unknown otp_id explains this";return r?`${e}. ${s} \u2014 the code is what remains: ${i}. Request a fresh code and try again.`:`${e}, and the backend did not identify the failure. ${s}, but an unrecognised refusal can also come from a proxy or gateway the request never reached the app through \u2014 so a stale code (${i}) is the likeliest cause, not the only one. Request a fresh code; if it fails the same way, the refusal is not about the code.`}let o=`the code may be ${i} \u2014 or the account may not exist here, or --otp-id may not be an otp_id this environment issued`;return r?`${e}, and the CLI cannot tell which cause applies: ${o}. ${ke(t)}`:`${e}, and the backend did not identify the failure: ${o} \u2014 or the request may not have reached the application at all. ${ke(t)}`}var Sn=new Map([[ii,(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. ${ke(t)}`],[oi,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.`],[si,(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. ${ke(t)}`]]);function ui(e,t,n,r=!1){if(n!==void 0)return Sn.get(n)?.(e,t,r)}var En=[...Sn.keys()];function An(e){if(e)throw new c("input.invalid","--no-existence-check is no longer supported: registration via the CLI OTP flow was removed (the CLI login endpoint only signs in existing accounts). Create the account in the AllScale web app first, then re-run without this flag.")}var di=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:_n,build:e=>ai(e.email,e.status)},{flows:["otp-send"],status:403,code:ti,when:e=>{let t=Le(e.email);return t.length>0&&t!==T},build:e=>yt(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:ri,build:e=>new c("auth.signature_rejected","The AllScale API rejected this request because this CLI build is not signed with the CLI signing key (the login endpoint is CLI-only). This is a build problem, not an input error: download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry. If you are already on the latest version, or this is a local/dev build signed with a non-CLI key, the signing-key row is misprovisioned \u2014 contact AllScale support.",{status:e.status,backend_code:e.backendCode})},{flows:["password"],status:400,code:ni,build:e=>ci(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>{let t=ui("OTP rejected",e.email,e.reason,e.otpIdFromSendLeg===!0);return new c("input.invalid",t??_t("OTP rejected",e.email,e.otpIdFromSendLeg===!0,!0),{status:e.status,backend_code:e.backendCode,...t===void 0?{}:{otp_reason:e.reason}})}},{flows:["otp-verify"],status:400,code:7531,build:e=>new c("input.invalid","The backend requires at least one scope for the minted agent key \u2014 pass --scopes (e.g. --scopes invoice:read_only).",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7530,build:e=>new c("input.invalid","None of the requested scopes can be granted to this account, so no key was issued. Retry with different --scopes.",{status:e.status,backend_code:e.backendCode})}];function Ie(e){if(e.backendCode!==void 0){for(let t of di)if(t.code===e.backendCode&&t.status===e.status&&t.flows.includes(e.flow)&&(t.when===void 0||t.when(e)))return t.build(e)}}var O=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:We,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{lt(this.jsonEnabled()),dt(),P({type:"session-start",command:this.id??"",argv:pt(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&&te()!==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=on(this.jsonEnabled()),r=this.argv.length===0&&!n&&bi(t)?this.config.findCommand(this.id??""):void 0;if(r){V();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&&!un())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 P({type:"command-end",ok:!0}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||zt(i),{data:i})}catch(t){let n=Jt(t);sn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{lt(!1)}}resolveSessionApiBaseChain(t){let n=ne(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||gt()!==void 0,s=mn(n,r,gt()),l=gn(n,s),u=M()==="public"&&te()!==void 0,d=i??(u?void 0:te()),g=d??l?.api_base??Q,p=dn({resolvedApiBase:g,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,Y({event:"legacy_staging_profile",api_base:g,profile:s},p)),{apiBase:g,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Ae(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&&te()!==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:l,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Ae(i),mt(i)),{apiBase:i,profile:l,token:n??an(),insecureStorage:r||cn(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${wi(t)}
|
|
15
|
+
`)}};var pi=/_(removed|cleared|count|total)$/i;function fi(e,t){return typeof t=="number"&&pi.test(e)}var gi=new Set(yn);function hi(e,t){return e==="token_symbol"&&typeof t=="string"&&gi.has(t)}var mi=new Set(En);function yi(e,t){return e==="otp_reason"&&typeof t=="string"&&mi.has(t)}var ve=100;function Ce(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,ve),r=n.map(i=>Ce(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,ve))n[i]=ge(i)&&!fi(i,o)&&!hi(i,o)&&!yi(i,o)?"<redacted>":Ce(o,t+1);if(r.length>ve){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-ve} more keys`}return n}if(typeof e=="string"){let n=_i(e);return n!==void 0?b(JSON.stringify(Ce(n,t+1))):b(e)}return e}function _i(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 wi(e){let t=ye()?void 0:2,n=Ce(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 bi(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 wt(e){let t=new Map;for(let n of e){let r=n.lastIndexOf(":");if(r===-1){t.set(n,t.get(n)??new Set);continue}let i=n.slice(0,r),o=n.slice(r+1),s=t.get(i)??new Set;s.add(o),t.set(i,s)}return[...t].map(([n,r])=>{if(r.size===0)return n;if(r.size===1)return`${n}:${[...r][0]}`;let i=["read_only","all"].filter(o=>r.has(o));for(let o of r)i.includes(o)||i.push(o);return`${n}:{${i.join(",")}}`}).join(", ")}var Si=new Set,bt=new Set(["transaction:all"]),Re=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"]),kn=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"]),St=new Set(["payroll","admin:user","admin:org","admin:audit"]);function ie(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Ei(e){let t=e.lastIndexOf(":");if(t<=0||t===e.length-1)return!1;let n=e.slice(t+1);return n==="read_only"||n==="all"}var Ai=new Set(["cli_op:all"]),Ln=new Set([...Ai].map(ie));var Et=new Set([...[...Re,...kn,...Si].map(ie),...St,...Ln]);function Tn(e,t){return ki({known:Et,ungrantable:St,implicit:Ln,renderedAbove:e,blocksUngrantableLocally:t?.blocksUngrantableLocally??!1})}function C(e,t,n){return e===1?t:n}function ki(e){let{known:t,ungrantable:n,implicit:r}=e,i=new Set([...e.renderedAbove].map(d=>ie(d))),o=[...t].filter(d=>n.has(d)).sort(),s=[...t].filter(d=>r.has(d)).sort(),l=[...t].filter(d=>i.has(d)&&!n.has(d)&&!r.has(d)).sort(),u=[];return t.size>0&&u.push(`Every category recognised as a spelling, so a usable value can be found without guessing: ${[...t].sort().join(", ")}.`),l.length>0&&u.push(`${l.join(", ")} ${C(l.length,"carries","carry")} the tiers listed above.`),o.length>0&&u.push(`${o.join(", ")} ${C(o.length,"is","are")} in the catalog but granted to NOBODY \u2014 every mint path drops ${C(o.length,"it","them")}, so no login command can deliver ${C(o.length,"it","them")}`+(e.blocksUngrantableLocally?`; this command rejects ${C(o.length,"it","them")} locally, before any pairing session.`:`, and requesting ${C(o.length,"it","them")} gains nothing.`)),s.length>0&&u.push(`${s.join(", ")} ${C(s.length,"is","are")} attached to every key the backend mints, by both login commands, without being requested \u2014 you never need to ask for ${C(s.length,"it","them")}, and asking is not an error.`),`${u.join(" ")} `}function Li(e){return e.filter(t=>!Ei(t)||!Et.has(ie(t)))}function On(e){if(!e||e.length===0)return;let t=Li(e);if(t.length!==0)throw new c("input.invalid",`Unrecognised --scopes value${t.length>1?"s":""}: ${t.join(", ")}. Scope strings are <category>:<tier>, where tier is read_only or all. Known categories: ${[...Et].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}var Mn=S(require("path"));var Lt=require("crypto"),a=S(require("fs")),m=S(require("path"));var Pe=1024*1024,Ti=5e3,Oi=20,Ii=3e4,At=4096,vi=new Int32Array(new SharedArrayBuffer(4)),oe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function xe(e){return e instanceof oe}var E=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ci=null;function N(){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 Ne(){return(Ci??process.platform)!=="win32"}function Bn(){if(!Ne())throw N()}function Dn(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 se(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ae(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ri(e){Atomics.wait(vi,0,0,e)}function $n(e){try{return process.kill(e,0),!0}catch(t){return!h(t,"ESRCH")}}function Pi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function In(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()||!ae(o,s))throw new Error("credential-store parent changed while it was being inspected");se(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&m.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),l=a.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function v(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 E:o}if(!ae(n,i))throw r.retryOnPathChange?new E: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 oe;if(se(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function xi(e,t){if(t.size>Pe)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Pe+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Pe)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function vn(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=v(e,t,n);return xi(t,r)}finally{t!==null&&a.default.closeSync(t)}}function Cn(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")&&Dn(e))return;throw i}let n=a.default.fstatSync(t),r=v(e,t,n);B(e,r)}finally{t!==null&&a.default.closeSync(t)}Fn(m.dirname(e))}function Ni(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 oe;se(t,"credential-store replacement target")}function Bi(e,t){for(let n=0;n<8;n+=1){let r=(0,Lt.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 Un(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 Di(e,t){let n=Buffer.from(t,"utf8");if(n.length>Pe)throw new Error("credential-store file exceeds the maximum supported size");let r=m.dirname(e),i=m.basename(e),o=null,s=null,l=!1;try{let u=Bi(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((v(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Un(o,n),a.default.fsyncSync(o),v(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ni(e),a.default.renameSync(s,e),l=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!l&&s!==null)try{a.default.unlinkSync(s)}catch{}}Fn(r)}function $i(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock`)}function Ui(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock-recovery`)}function Fi(e,t){if(t.size>At)return null;let n=Buffer.alloc(At+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>At)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 B(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ae(n,t))throw new Error("credential-store lock changed while it was being inspected");se(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(u){if(h(u,"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 E}catch(d){if(h(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=v(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Fi(n,i);return{state:(o?.target===t&&o?!$n(o.pid):Date.now()-i.mtimeMs>=Ii)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Mi(e,t){for(let n=0;n<8;n+=1){let r=(0,Lt.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 l=a.default.fstatSync(s),u=v(i,s,l,{allowMultipleLinks:!0});return Un(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(l){if(h(l,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw l}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Gi(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 E:r}try{let r=a.default.fstatSync(n),i=v(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ae(i,t))throw new E;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function Pn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(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 E}catch(r){if(h(r,"ENOENT"))return!1;throw r}throw n}return v(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Ki(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=v(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{B(e,n)}catch{}throw a.default.closeSync(t),r}}function x(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");Ri(Oi)}function xn(e){let t=m.dirname(e),n=m.basename(e),r=$i(e),i=Ui(e),o=Mi(t,n),s=Date.now()+Ti,l=!1,u=!1,d=null,g;try{for(;d===null;)try{if(Pn(i)){x(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Gi(r,o.stats),l=!0}catch(p){if(u&&!l){try{B(r,o.stats)}catch{}u=!1}if(p instanceof E){x(s,!1);continue}if(!h(p,"EEXIST"))throw p;let w;try{w=Rn(r,n)}catch(y){if(y instanceof E){x(s,!1);continue}throw y}if(w.state==="absent")continue;if(w.state==="stale"){let y;try{y=Ki(i)}catch(_){if(_ instanceof E){x(s,!1);continue}throw _}if(y!==null){try{let _;try{_=Rn(r,n)}catch(U){if(U instanceof E){x(s,!1);continue}throw U}_.state==="stale"&&B(r,_.stats)}finally{kt(y)}continue}}let A;try{A=Pn(i)}catch(y){if(y instanceof E){x(s,!1);continue}throw y}x(s,A)}}catch(p){g=p}try{B(o.claimPath,o.stats)}catch(p){!h(p,"ENOENT")&&!l&&g===void 0&&(g=p)}if(g!==void 0)throw g;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function kt(e){try{B(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Yi(e,t){let n=Pi(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 Nn(e){let t=m.dirname(e),n=m.basename(e);for(let r of a.default.readdirSync(t)){let i=Yi(r,n);if(i===null||$n(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 l=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!l.isFile()||u.isSymbolicLink()||!u.isFile()||!ae(l,u))continue;try{se(l,"credential-store orphan")}catch{continue}B(o,l)}catch(l){if(!h(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function ce(e,t,n){if(!Ne()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw N();if(!In(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw N()}});let s=xn(e);try{return Nn(e),n({read:()=>vn(e),remove:()=>Cn(e),write:()=>{throw N()}})}finally{kt(s)}}if(!t.createParent){let o=!1;try{o=Dn(e)}catch{throw N()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw N()}})}throw N()}if(!In(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=xn(e);try{return Nn(e),n({read:()=>vn(e),remove:()=>Cn(e),write:o=>Di(e,o)})}finally{kt(i)}}var Tt="allscale-cli";function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gn(e){return Ct(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function $(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 Ot(){return new c("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Be(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var D,It=!1;function ji(){return ln()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Hi(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 qi(){if(D!==void 0)return D;if(ji())return It=!1,D=null,D;try{D=require("keytar"),It=!1}catch(e){It=!Hi(e),D=null}return D}var Wi="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Kn(){let e=Ne()?"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",`${Wi} `+e+" Never silently downgrade in production.")}async function vt(e){try{return await e()}catch{throw Kn()}}var Rt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await vt(()=>this.keytar.getPassword(Tt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw $("OS keychain")}if(!Gn(r))throw $("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await vt(()=>this.keytar.setPassword(Tt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await vt(()=>this.keytar.deletePassword(Tt,t))}},Ji="credentials.json",Pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Mn.join(Se(),Ji)}read(t){let n;try{n=t.read()}catch(i){throw xe(i)?Ot():$("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw $("plaintext file")}if(!Ct(r)||!Ct(r.profiles))throw $("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw xe(r)?Ot():Be()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Gn(r))throw $("plaintext file");return r}}async get(t){try{return ce(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:$("plaintext file")}}async set(t,n){try{ce(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof c?r:Be()}}async delete(t){try{ce(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof c?n:Be()}}async clearProfile(t){try{return ce(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:xe(n)?Ot():Be()}}};function Yn(e){if(e.insecureStorage)return Bn(),new Pt(e.insecureFilePath);let t=qi();if(t)return new Rt(t);throw Kn()}async function jn(e,t){await e.get(t)}async function Hn(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof c?r.message:b(String(r)),o=n.agent_key?"An agent key was already minted for this account but could not be stored, so it is now orphaned: it cannot be listed or revoked from the CLI (key management is control-plane and rejects agent-key sessions). Remove it from the web dashboard.":"The session credential could not be stored, so nothing was persisted \u2014 no key record was created on the account. Re-run the command to authenticate again once storage is available.";throw new c(r instanceof c?r.code:"storage.unavailable",`${i} ${o}`,r instanceof c?r.details:void 0)}}var qn=S(require("crypto")),Wn=S(require("fs")),Jn=S(require("path"));var zi="key-id",Xi="x-allscale-cli-version",xt="cli-1",Vi="aScaLe_cli_obf_v1",Zi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Qi(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 eo=Qi(Zi,Vi),to=`Bearer ${eo}`;function zn(e,t){let n=Ve(e);if(n!==null)return t.find(r=>Ve(r.base)===n)}function no(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=zn(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 ro(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?zn(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():xt}if(!R(t[0].base))return xt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():xt}function io(){return"1.0.5"}function oo(){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 De(e,t){let n=no(t);if(!n)throw oo();let r=ro(t),i=Math.floor(Date.now()/1e3).toString(),o=qn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Xi]:io()};return r.length>0&&(s[zi]=r),s}function $e(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var so=500,ao=8,Xn=100;function Nt(e,t=0){if(t>ao)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Xn),r=n.map(i=>Nt(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,Xn))n[r]=ge(r)?"<redacted>":Nt(i,t+1);return n}return e}function co(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 Ue(e,t=so){let n=co(e),r=n===void 0?fe(e):JSON.stringify(Nt(n));return he(r,t)}var ue=256*1024,le=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"}},Fe=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 Bt(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 le(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,u,d=n.timeoutMs,g=d===void 0?void 0:new Promise((p,w)=>{u=setTimeout(()=>{w(new Fe(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:w,value:A}=g?await Promise.race([p,g]):await p;if(w)break;if(l+=A.byteLength,l>t)throw o.cancel().catch(()=>{}),new le(e.status,t,n.oversizeKind);s.push(Buffer.from(A))}}catch(p){throw p instanceof Fe&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}async function Dt(e,t){let n;try{n=await Bt(e,t)}catch(r){if(r instanceof le)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var La=32*1024*1024,Ta=4*1024*1024;function lo(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${rn(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 Me(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}lo(e.status,e.url)}}var uo=2014;function po(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 fo(e){return po(e,uo)}var go=1e4;async function Ge(e,t=go){if(e.status>=200&&e.status<300)return"";try{return await Bt(e,ue,{timeoutMs:t})}catch{return""}}function Ke(e,t){if(!(e>=200&&e<300)&&fo(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"?Ue(t):t})}var Ft=require("process");var ho={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Vn(e){if(typeof e=="string")return e;if(typeof e=="number")return ho[e]??`user_type_${e}`}function $t(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var Ut=require("process");var Zn=new Set;function Qn(e,t,n){ye()||we()||Ut.stderr.isTTY&&(Zn.has(e)||(Zn.add(e),Ut.stderr.write(`warning: ${e} was read from the command line, where other users on this host can see it via \`ps\` (and where your shell records it in history). Prefer ${t} or ${n}.
|
|
17
|
+
`)))}var mo="/api/v1/public/turnkey/cli/email-otps",yo="/api/v1/public/turnkey/email-otps",tr=Symbol("cli-otp-route-missing");async function nr(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=De($e(n),e);try{return await fetch(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(s){throw new c("transport.network",`Network error contacting ${r}: ${s.message}`)}}async function rr(e){let t=await Dt(e,ue);if(typeof t.data!="string"||t.data.trim().length===0)throw new c("backend.internal","OTP send response did not include otp_id.",{body:Ue(JSON.stringify(t))});return{otp_id:t.data}}async function ir(e,t){let n=await _o(e,t);return n!==tr?n:wo(e,t)}async function _o(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await nr(e,mo,n);await Me(r);let i=await Ge(r);Ke(r.status,i);let o=Te(i),s=Ie({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return tr;if(r.status===429)throw new c("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw new c("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new c("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return rr(r)}async function wo(e,t){let n={email:t.email,check_user_existence:!0};t.name!==void 0&&(n.name=t.name),t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await nr(e,yo,n);await Me(r);let i=await Ge(r);Ke(r.status,i);let o=Te(i),s=Ie({flow:"otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404)throw new c("not_found","OTP send endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});let l=Le(t.email),u=l.length>0&&l!==T;if(r.status===429)throw new c("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw r.status===500&&u?yt(t.email,r.status,o,"backend.internal",!1):new c("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new c("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return rr(r)}async function or(e,t){Oe(t.otp_id);let n=new URL("/api/v1/public/turnkey/sessions:email-otp",e).toString(),r={email:t.email,otp_id:t.otp_id,otp_code:t.otp_code,credential_mode:"agent_key",scopes:t.scopes};t.device_label!==void 0&&(r.device_label=t.device_label),t.referer_id!==void 0&&(r.referer_id=t.referer_id);let i=JSON.stringify(r),o=De($e(r),e),s;try{s=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(F){throw new c("transport.network",`Network error contacting ${n}: ${F.message}`)}await Me(s);let l=await Ge(s);Ke(s.status,l);let u=Te(l),d=wn(l),g=Ie({flow:"otp-verify",status:s.status,backendCode:u,email:t.email,otpIdFromSendLeg:t.otpIdFromSendLeg===!0,reason:d});if(g)throw g;if(s.status===401||s.status===403)throw new c("auth.permission_denied",_t(`OTP verification was refused (HTTP ${s.status})`,t.email,t.otpIdFromSendLeg===!0,!1),{status:s.status});if(s.status===404)throw new c("not_found","OTP auth endpoint not found (HTTP 404). This AllScale deployment may not support this login flow yet; try again later or contact AllScale support.",{status:404});if(s.status===429)throw new c("rate_limited","OTP verification throttled by the backend. Wait before retrying.",{status:429});if(s.status>=500)throw new c("backend.internal",`Backend returned ${s.status} during OTP auth.`,{status:s.status});if(s.status!==200){let F=u;throw new c("input.invalid",`OTP auth failed: HTTP ${s.status}`,{status:s.status,...F===void 0?{}:{backend_code:F}})}let w=(await Dt(s,ue)).data??{},A=Vn(w.user_type)??"business",y=w.agent_key;if(typeof y!="string"||y.length===0)throw new c("backend.internal","Requested a scoped agent key, but the backend answered with a legacy cookie session \u2014 it may not support scoped OTP keys yet, or a rolling deploy may be in progress. Refusing to store the broader credential; the OTP code was consumed, so request a new one before retrying.",{status:200,expected_credential:"agent_key"});let _=w.scopes,U=Array.isArray(_)&&_.every(F=>typeof F=="string")?_:[],He=w.agent_key_expires_at,qe=w.business_id,Mt=$t(w.user?.email)??$t(t.email);return{user:w.user??{},user_type:A,scopes:U,tokens:{access_token:"",refresh_token:"",agent_key:y,...typeof He=="number"&&He>0?{agent_key_expires_at:He}:{},...U.length>0?{scopes:U}:{},...typeof qe=="string"&&qe.length>0?{business_id:qe}:{},...Mt===void 0?{}:{user_email:Mt},user_type:A,api_base:e}}}var de="ALLSCALE_OTP";function sr(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[de];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function ar(e,t){if(typeof e=="string"&&e.trim().length>0)return Qn("--otp",de,"--otp-stdin"),e.trim();if(t){let r=process.env[de];return typeof r=="string"&&r.trim().length>0&&Ft.stderr.write(`warning: --otp-stdin is set, so ${de} is ignored (stdin takes precedence).
|
|
18
|
+
`),er()}let n=process.env[de];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(process.stdin.isTTY)return Ft.stderr.write("OTP code: "),er()}var bo=1024;async function er(){let e="";try{for await(let t of process.stdin){e+=t;let n=e.indexOf(`
|
|
19
|
+
`);if(n!==-1)return e.slice(0,n).trim();if(Buffer.byteLength(e,"utf-8")>=bo)throw new c("input.invalid","OTP input exceeded the expected length (1 KB) before a newline; check the --otp-stdin pipe.")}}catch(t){throw t instanceof c?t:new c("input.invalid",`Failed to read OTP from stdin: ${t instanceof Error?t.message:String(t)}`)}return e.trim()}var je=class e extends re{static description="Terminal-only Email OTP login for headless / scripted shells. Works with any account email (external domains included; the account must already exist). Sends the code (unless --otp-id is supplied), reads it in the terminal, and mints a scoped agent API key whose granted scopes the backend checks on each request \u2014 the credential issued by the current CLI login flows. Scopes are set with --scopes (required; no full-permission default exists).";static examples=["$ allscale otp-login --email me@example.com --scopes invoice:read_only # interactive: prompts on stdin",`$ printf '%s' "$OTP" | allscale otp-login --email me@example.com --scopes invoice:all --otp-stdin`,"$ ALLSCALE_OTP=$(read-from-mailbox) allscale otp-login --email me@example.com --scopes claim_link:all","$ allscale otp-login --email me@example.com --scopes invoice:read_only --otp-id otp-request-id --otp 123456"];static flags={email:O.Flags.string({helpGroup:"REQUIRED",char:"e",description:"Account email",required:!0}),scopes:O.Flags.string({helpGroup:"REQUIRED",description:"Scopes the minted agent key should carry, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs that reach a real operation today: "+wt(Re)+". "+(bt.size>0?wt(bt)+" \u2014 read-only in practice: no write operation is wired there today, so the `:read_only` tier grants exactly as much; prefer it unless you have a reason to hold the wider scope. ":"")+"`wallet:all` additionally lets the key register `wallet send` transfers; every transfer still requires your in-browser confirmation. Other pairs are accepted by the catalog but grant nothing, and this command does NOT warn when a requested scope is clipped \u2014 verify with `allscale scope` after minting. "+Tn(Re)+"Values are checked locally first: an unrecognised `<category>:<tier>` string exits 2 before any OTP is sent \u2014 the same check, and the same exit code, as `device-login --scopes`. Required \u2014 the backend deliberately has no full-permission default. Requested scopes are clipped to your account's role; granted scopes are checked by the backend on each request.",multiple:!0,required:!0}),"otp-id":O.Flags.string({description:"Skip the send step and use this otp_id (e.g. from a previous `otp-send`)"}),otp:O.Flags.string({description:"OTP code from the email. Prefer ALLSCALE_OTP or --otp-stdin to keep it out of shell history.",exclusive:["otp-stdin"]}),"otp-stdin":O.Flags.boolean({description:"Read the OTP code as one line from stdin",default:!1,exclusive:["otp"]}),"no-existence-check":O.Flags.boolean({description:"(DEPRECATED \u2014 now errors) Registration via the CLI OTP flow was removed: the CLI-only login endpoint signs in existing accounts only. Create the account in the AllScale web app first, then log in without this flag.",default:!1,hidden:!0}),"device-label":O.Flags.string({description:"Human-readable device/agent label recorded on the minted key so it is identifiable in the key management list."}),...re.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=t.email.trim();bn(n),An(!!t["no-existence-check"]),On(t.scopes);let r=this.resolveContext(t);if(!sr(t.otp,!!t["otp-stdin"]))throw new c("input.invalid","An OTP code source is required. Pass --otp, set ALLSCALE_OTP, pipe via --otp-stdin, or run interactively.");let o=Yn({insecureStorage:r.insecureStorage});await jn(o,r.profile);let s=t["otp-id"],l=s!==void 0,u=s?.trim()??"",d=!1;if(l&&Oe(u),!l)try{u=(await ir(r.apiBase,{email:n})).otp_id,d=!0,Ye.stderr.write(`OTP sent to ${n}. otp_id=${u}. Check your inbox; the code is short-lived.
|
|
20
|
+
`)}catch(_){throw _ instanceof c&&_.code==="rate_limited"&&_.details?.status===429?new c(_.code,"OTP send was rate-limited. If a code was already sent for this email by `allscale otp-send` or an earlier `allscale otp-login`, re-run the same `allscale otp-login` command with `--otp-id <earlier-otp-id>` using the exact otp_id that command returned or printed, and the same OTP input; otherwise wait before requesting another code.",_.details):_}let g=await ar(t.otp,!!t["otp-stdin"]);if(!g)throw new c("input.invalid","An OTP code is required. Pass --otp, set ALLSCALE_OTP, pipe via --otp-stdin, or run interactively.");let p=await or(r.apiBase,{email:n,otp_id:u,otp_code:g,otpIdFromSendLeg:d,scopes:t.scopes,device_label:t["device-label"]});await Hn(o,r.profile,p.tokens);let w=ne(),A=hn(w,r.profile,{api_base:r.apiBase,user_type:So(p.user_type),api_base_source:r.apiBaseSource});A.default||(A.default=r.profile),fn(A),Ye.stderr.write(`Saved tokens to ${o.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${r.profile}). Profile metadata: ${Ee()}
|
|
21
21
|
`);let y=typeof p.tokens.agent_key_expires_at=="number"?new Date(p.tokens.agent_key_expires_at*1e3).toISOString():void 0;return Ye.stderr.write(`Credential: scoped agent key. Scopes${p.scopes.length>0?` (${p.scopes.join(", ")})`:""} are checked by the backend on each request.
|
|
22
|
-
${y?`The key expires at ${y}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`${
|
|
22
|
+
${y?`The key expires at ${y}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`${et(r.profile)}\` when it expires or is revoked.
|
|
23
23
|
`),{profile:r.profile,api_base:r.apiBase,user_type:p.user_type,storage:o.kind,...p.tokens.business_id===void 0?{}:{business_id:p.tokens.business_id},...p.tokens.user_email===void 0?{}:{user_email:p.tokens.user_email},credential:"agent_key",scopes:p.scopes,...y?{agent_key_expires_at:y}:{}}}};function So(e){return e==="business"||e==="employee"||e==="admin"?e:"business"}
|
|
24
24
|
//# sourceMappingURL=otp-login.js.map
|