@allscale/cli 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -5
- package/dist/commands/build-info.js +9 -9
- package/dist/commands/claim-link/claim.js +10 -10
- package/dist/commands/claim-link/create.js +30 -30
- package/dist/commands/claim-link/get.js +13 -13
- package/dist/commands/claim-link/list.js +11 -11
- package/dist/commands/claim-link/status.js +10 -10
- package/dist/commands/describe.js +8 -8
- package/dist/commands/device-login.js +24 -24
- package/dist/commands/invoice/get.js +10 -10
- package/dist/commands/invoice/list.js +8 -8
- package/dist/commands/invoice/pay.js +28 -28
- package/dist/commands/invoice/received.js +8 -8
- package/dist/commands/invoice/send.js +22 -22
- package/dist/commands/invoice/sent.js +4 -4
- package/dist/commands/invoice/update.js +11 -11
- package/dist/commands/logout.js +12 -12
- package/dist/commands/operations.js +7 -7
- package/dist/commands/otp-login.js +19 -19
- package/dist/commands/otp-send.js +7 -7
- package/dist/commands/payout/send.js +12 -12
- package/dist/commands/payout/status.js +12 -12
- package/dist/commands/scope.js +12 -12
- package/dist/commands/store/create.js +15 -15
- package/dist/commands/transaction/get.js +11 -11
- package/dist/commands/transaction/list.js +5 -5
- package/dist/commands/wallet/list.js +9 -9
- package/dist/commands/wallet/send.js +27 -27
- package/dist/commands/whoami.js +12 -12
- package/dist/index.js +9 -9
- package/dist/lib/help.js +10 -7
- package/oclif.manifest.json +5 -5
- package/package.json +1 -1
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var f=
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}
|
|
1
|
+
"use strict";var ar=Object.create;var de=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var pr=(e,t)=>{for(var n in t)de(e,n,{get:t[n],enumerable:!0})},Ft=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of lr(t))!dr.call(e,i)&&i!==n&&de(e,i,{get:()=>t[i],enumerable:!(r=cr(t,i))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?ar(ur(e)):{},Ft(t||!e||!e.__esModule?de(n,"default",{value:e,enumerable:!0}):n,e)),fr=e=>Ft(de({},"__esModule",{value:!0}),e);var Eo={};pr(Eo,{default:()=>je});module.exports=fr(Eo);var Ye=require("process");var I=require("@oclif/core");var Mt="public",Gt="https://app.allscale.io";var Kt=["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 Yt(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 jt(e){return Yt(e)!==null}function ze(e){let t=Yt(e);return t!==null&&Kt.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 gr=/^[A-Za-z0-9._-]{1,64}$/;function hr(e){return gr.test(e)?e:"<profile>"}function qt(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":hr(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}var mr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var yr=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function et(e){return(typeof e=="string"?e:String(e??"")).replace(yr,"")}var _r=64;function Ze(e,t=new Map,n=0){if(typeof e=="string")return et(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=_r)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(et(n)),this.code=t,this.details=r&&Ze(r),this.name="AllscaleError"}get exitCode(){return mr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Wt(e){if(e instanceof c)return e;if(e instanceof Error){if(Sr(e)){let t=Ar(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var wr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),br=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Sr(e){if(Er(e))return!0;let t=e.name??"";return wr.has(t)?t==="CLIError"?Qe(e,"parse")||Ht(e.message):!0:Ht(e.message)}function Er(e){if(!Qe(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Qe(e,"parse")}function Ht(e){return e?et(e).split(`
|
|
2
|
+
`).some(t=>br.some(n=>n.test(t.trim()))):!1}function Qe(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Ar(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Jt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var f=S(require("fs")),ye=S(require("path")),en=S(require("crypto"));var kr="...<truncated>",Lr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Tr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ot=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,tt=String.raw`(?:proxy[_-]?)?authorization`,Or=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${tt}"|'${tt}'|${tt})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ot}`,"gi"),Ir=/\b(https?:\/\/)[^\s/?#]+@/gi,vr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Cr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Xt=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)`,zt=Xt(vr),Rr=Xt(Cr),Pr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${zt}"|'${zt}'|${Rr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ot}`,"gi"),nt=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)`,xr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${nt}"|'${nt}'|${nt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ot}`,"g");function pe(e){return e.replace(Ir,"$1<redacted>@").replace(Lr,"<redacted-jwt>").replace(Or,"$1$2$3<redacted>").replace(Pr,"$1$2<redacted>").replace(xr,"$1$2<redacted>").replace(Tr,"Bearer <redacted>")}var Nr=/(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 fe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Nr.test(t)}function Vt(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 ge(e,t,n=kr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let 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 ge(Vt(pe(e)),t)}var rt=100,Br=8,Dr=8*1024;function he(){return{remaining:Dr}}function it(e,t){let n=Math.min(16384,t.remaining),r=ge(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function G(e,t,n=0,r={}){if(n>Br)return it("<truncated>",t);if(typeof e=="string"){let i=pe(e);return it(r.escapeControls?Vt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,rt),o=i.map(s=>G(s,t,n+1,r));return e.length>i.length&&o.push(it(`<${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,rt))i[s]=G(l,t,n+1,r);return o.length>rt&&(i.output_truncated=!0),i}return e}var st=require("process");var at=!1;function ct(e){at=e}function me(){return at}var Zt="1";function Y(e,t){if(at){let n={...e};delete n.version;let r=he(),i={event:n.event,...n},o=G(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Zt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Zt,event:o.event,output_truncated:!0})),st.stderr.write(`${s}
|
|
4
|
+
`)}else st.stderr.write(t)}var Qt="2",j=null,k=null,H=!1,X=!1;function $r(){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=en.randomBytes(4).toString("hex");return ye.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var lt=64*1024*1024,Ur=null;function ut(e={}){if(e.quiet&&(X=!0),H)return;let t=$r();if(!t)return;j=null;let n=null;try{if((Ur??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=ye.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 Fr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Mr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fr.some(n=>n.test(t))}function tn(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=Gr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Mr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Gr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Kr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:tn(e.url)}:e}function Yr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=G(i,he()),s=JSON.stringify({version:Qt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Qt,timestamp:t,type:r,output_truncated:!0})),s}function P(e){if(!H||!j||k===null)return;let t=Kr(e),n=Yr(t);try{if(f.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>lt){H=!1;try{f.closeSync(k)}catch{}k=null,X||Y({event:"sidecar_disabled",reason:"size_limit",...j===null?{}:{path:b(j)},max_bytes:lt},`${b(`[allscale] sidecar exceeded ${lt} 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
|
-
`)}catch(r){if(
|
|
8
|
-
`)}catch{}}}var
|
|
9
|
-
The CLI default is now ${
|
|
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=tn;function _e(){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 rn(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||_e()||!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"]),jr=new Set(Array.from(Z).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Hr=Array.from(Z).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),qr=new Set(["--otp-stdin","--password-stdin"]);function dt(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(jr.has(o)){t.push(`${o}<redacted>`);continue}}let i=qr.has(r)?void 0:Hr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function on(e){P({type:"error",code:e.code,message:b(e.message)}),P({type:"command-end",ok:!1,exitCode:e.exitCode}),V()}var Q=J()??Gt,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 pt(e){return jt(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 sn(){let e=process.env[W.TOKEN]?.trim();return e&&e.length>0?e:void 0}function ft(){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 an(){let e=process.env[W.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function cn(){let e=process.env[W.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ln(){let e=process.env[W.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function un(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
|
+
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
|
-
To move to production, run: allscale device-login --api-base ${
|
|
14
|
-
`}var L=b(require("fs")),ln=b(require("os")),dt=b(require("path")),ye=b(require("@iarna/toml"));var Hr=".allscale",qr="config.toml";function we(){return dt.join(ln.homedir(),Hr)}function Se(){return dt.join(we(),qr)}function te(){let e=Se();if(!L.existsSync(e))return{};let t=L.readFileSync(e,"utf-8");try{return ye.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function un(e){let t=we();L.existsSync(t)||L.mkdirSync(t,{recursive:!0,mode:448});let n=ye.stringify(e),r=Se();L.writeFileSync(r,n,{mode:384});try{L.chmodSync(r,384)}catch{}}function dn(e,t){return e.profile?.[t]}function pn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function fn(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 be(e){if(!qe(e))throw new c("input.invalid",`Refusing to send credentials to API base ${Q(e)}. `+He)}function pt(e){let t=Jr(e);if(t)throw new c("input.invalid",t.message)}function Wr(){let e=W();if(e===void 0)return;let t=J();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Jr(e){let t=Wr();if(t===void 0||C(e))return;let{endpoints:n,fromPairs:r}=t,i=lt(e),o=n.map(l=>lt(l)).filter(l=>l!==null);if(i!==null&&o.includes(i))return;let s=n.map(l=>Q(l)).join(", ");return{message:r?`Refusing to send to ${Q(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 ${Q(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var zr=require("@noble/hashes/sha3");var gn=["USDT","USDC"];var os=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var hn=3100,Vr=2090,Xr=2001,Zr=2092,T="allscale.io";function Ae(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function ke(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 Qr="unknown_otp_id",ei="invalid_code",ti="expired_code";function mn(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 ni(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:hn})}function ft(e,t,n,r,i){let o=Ae(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 ri(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 _n(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 Le(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 ii(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ee(e){return`Run \`allscale otp-send --email ${ii(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}function gt(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}. ${Ee(t)}`:`${e}, and the backend did not identify the failure: ${o} \u2014 or the request may not have reached the application at all. ${Ee(t)}`}var yn=new Map([[Qr,(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. ${Ee(t)}`],[ei,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.`],[ti,(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. ${Ee(t)}`]]);function oi(e,t,n,r=!1){if(n!==void 0)return yn.get(n)?.(e,t,r)}var wn=[...yn.keys()];function Sn(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 si=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:hn,build:e=>ni(e.email,e.status)},{flows:["otp-send"],status:403,code:Vr,when:e=>{let t=Ae(e.email);return t.length>0&&t!==T},build:e=>ft(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:Zr,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:Xr,build:e=>ri(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>{let t=oi("OTP rejected",e.email,e.reason,e.otpIdFromSendLeg===!0);return new c("input.invalid",t??gt("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 Te(e){if(e.backendCode!==void 0){for(let t of si)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"),ne=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:F()==="public"}),"api-base":I.Flags.string({description:je,helpGroup:"GLOBAL",hidden:F()==="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{ot(this.jsonEnabled()),at(),R({type:"session-start",command:this.id??"",argv:ct(this.argv)});let t=this.constructor;if(F()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ee()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=tn(this.jsonEnabled()),r=this.argv.length===0&&!n&&hi(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&&!an())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 R({type:"command-end",ok:!0}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||qt(i),{data:i})}catch(t){let n=Ht(t);nn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{ot(!1)}}resolveSessionApiBaseChain(t){let n=te(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||ut()!==void 0,s=fn(n,r,ut()),l=dn(n,s),u=F()==="public"&&ee()!==void 0,d=i??(u?void 0:ee()),g=d??l?.api_base??Z,p=cn({resolvedApiBase:g,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,K({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||be(n),n}resolveContext(t){if(F()==="public"){if(t.token!==void 0)throw new c("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ee()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:l,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(be(i),pt(i)),{apiBase:i,profile:l,token:n??rn(),insecureStorage:r||on(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${gi(t)}
|
|
15
|
-
`)}};var ai=/_(removed|cleared|count|total)$/i;function ci(e,t){return typeof t=="number"&&ai.test(e)}var li=new Set(gn);function ui(e,t){return e==="token_symbol"&&typeof t=="string"&&li.has(t)}var di=new Set(wn);function pi(e,t){return e==="otp_reason"&&typeof t=="string"&&di.has(t)}var Oe=100;function Ie(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Oe),r=n.map(i=>Ie(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,Oe))n[i]=pe(i)&&!ci(i,o)&&!ui(i,o)&&!pi(i,o)?"<redacted>":Ie(o,t+1);if(r.length>Oe){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Oe} more keys`}return n}if(typeof e=="string"){let n=fi(e);return n!==void 0?S(JSON.stringify(Ie(n,t+1))):S(e)}return e}function fi(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 gi(e){let t=he()?void 0:2,n=Ie(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function hi(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}function ht(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 mi=new Set,mt=new Set(["transaction:all"]),_t=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"]),_i=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"]),yi=new Set(["payroll","admin:user","admin:org","admin:audit"]);function yt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function wi(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 Si=new Set(["cli_op:all"]),bi=new Set([...Si].map(yt));var bn=new Set([...[..._t,..._i,...mi].map(yt),...yi,...bi]);function Ei(e){return e.filter(t=>!wi(t)||!bn.has(yt(t)))}function En(e){if(!e||e.length===0)return;let t=Ei(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: ${[...bn].sort().join(", ")}. Nothing was sent \u2014 no OTP was requested, no pairing session was created, and no key was issued.`,{unrecognised_scopes:t})}var Bn=b(require("path"));var bt=require("crypto"),a=b(require("fs")),m=b(require("path"));var ve=1024*1024,Ai=5e3,ki=20,Li=3e4,wt=4096,Ti=new Int32Array(new SharedArrayBuffer(4)),re=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ce(e){return e instanceof re}var E=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Oi=null;function x(){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 Re(){return(Oi??process.platform)!=="win32"}function Cn(){if(!Re())throw x()}function Rn(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 ie(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function oe(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ii(e){Atomics.wait(Ti,0,0,e)}function Pn(e){try{return process.kill(e,0),!0}catch(t){return!h(t,"ESRCH")}}function vi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function An(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()||!oe(o,s))throw new Error("credential-store parent changed while it was being inspected");ie(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(!oe(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 re;if(ie(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Ci(e,t){if(t.size>ve)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(ve+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>ve)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function kn(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 Ci(t,r)}finally{t!==null&&a.default.closeSync(t)}}function Ln(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")&&Rn(e))return;throw i}let n=a.default.fstatSync(t),r=v(e,t,n);N(e,r)}finally{t!==null&&a.default.closeSync(t)}Nn(m.dirname(e))}function Ri(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 re;ie(t,"credential-store replacement target")}function Pi(e,t){for(let n=0;n<8;n+=1){let r=(0,bt.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 xn(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 Nn(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 xi(e,t){let n=Buffer.from(t,"utf8");if(n.length>ve)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=Pi(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");xn(o,n),a.default.fsyncSync(o),v(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ri(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{}}Nn(r)}function Ni(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock`)}function Bi(e){return m.join(m.dirname(e),`.${m.basename(e)}.lock-recovery`)}function Di(e,t){if(t.size>wt)return null;let n=Buffer.alloc(wt+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>wt)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 N(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!oe(n,t))throw new Error("credential-store lock changed while it was being inspected");ie(n,"credential-store lock"),a.default.unlinkSync(e)}function Tn(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=Di(n,i);return{state:(o?.target===t&&o?!Pn(o.pid):Date.now()-i.mtimeMs>=Li)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function $i(e,t){for(let n=0;n<8;n+=1){let r=(0,bt.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 xn(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 Ui(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(!oe(i,t))throw new E;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function On(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(h(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new 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 Fi(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{N(e,n)}catch{}throw a.default.closeSync(t),r}}function P(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");Ii(ki)}function In(e){let t=m.dirname(e),n=m.basename(e),r=Ni(e),i=Bi(e),o=$i(t,n),s=Date.now()+Ai,l=!1,u=!1,d=null,g;try{for(;d===null;)try{if(On(i)){P(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Ui(r,o.stats),l=!0}catch(p){if(u&&!l){try{N(r,o.stats)}catch{}u=!1}if(p instanceof E){P(s,!1);continue}if(!h(p,"EEXIST"))throw p;let w;try{w=Tn(r,n)}catch(_){if(_ instanceof E){P(s,!1);continue}throw _}if(w.state==="absent")continue;if(w.state==="stale"){let _;try{_=Fi(i)}catch(y){if(y instanceof E){P(s,!1);continue}throw y}if(_!==null){try{let y;try{y=Tn(r,n)}catch($){if($ instanceof E){P(s,!1);continue}throw $}y.state==="stale"&&N(r,y.stats)}finally{St(_)}continue}}let A;try{A=On(i)}catch(_){if(_ instanceof E){P(s,!1);continue}throw _}P(s,A)}}catch(p){g=p}try{N(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 St(e){try{N(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Mi(e,t){let n=vi(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 vn(e){let t=m.dirname(e),n=m.basename(e);for(let r of a.default.readdirSync(t)){let i=Mi(r,n);if(i===null||Pn(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()||!oe(l,u))continue;try{ie(l,"credential-store orphan")}catch{continue}N(o,l)}catch(l){if(!h(l,"ENOENT"))throw l}finally{s!==null&&a.default.closeSync(s)}}}function se(e,t,n){if(!Re()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw x();if(!An(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw x()}});let s=In(e);try{return vn(e),n({read:()=>kn(e),remove:()=>Ln(e),write:()=>{throw x()}})}finally{St(s)}}if(!t.createParent){let o=!1;try{o=Rn(e)}catch{throw x()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw x()}})}throw x()}if(!An(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=In(e);try{return vn(e),n({read:()=>kn(e),remove:()=>Ln(e),write:o=>xi(e,o)})}finally{St(i)}}var Et="allscale-cli";function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dn(e){return Tt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function D(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 At(){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 Pe(){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 B,kt=!1;function Gi(){return sn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Ki(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 Yi(){if(B!==void 0)return B;if(Gi())return kt=!1,B=null,B;try{B=require("keytar"),kt=!1}catch(e){kt=!Ki(e),B=null}return B}function $n(){let e=Re()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new c("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Lt(e){try{return await e()}catch{throw $n()}}var Ot=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Lt(()=>this.keytar.getPassword(Et,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw D("OS keychain")}if(!Dn(r))throw D("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Lt(()=>this.keytar.setPassword(Et,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Lt(()=>this.keytar.deletePassword(Et,t))}},ji="credentials.json",It=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Bn.join(we(),ji)}read(t){let n;try{n=t.read()}catch(i){throw Ce(i)?At():D("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw D("plaintext file")}if(!Tt(r)||!Tt(r.profiles))throw D("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ce(r)?At():Pe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Dn(r))throw D("plaintext file");return r}}async get(t){try{return se(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:D("plaintext file")}}async set(t,n){try{se(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof c?r:Pe()}}async delete(t){try{se(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof c?n:Pe()}}async clearProfile(t){try{return se(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof c?n:Ce(n)?At():Pe()}}};function Un(e){if(e.insecureStorage)return Cn(),new It(e.insecureFilePath);let t=Yi();if(t)return new Ot(t);throw $n()}async function Fn(e,t){await e.get(t)}async function Mn(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof c?r.message:S(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 Gn=b(require("crypto")),Kn=b(require("fs")),Yn=b(require("path"));var Hi="key-id",qi="x-allscale-cli-version",vt="cli-1",Wi="aScaLe_cli_obf_v1",Ji="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function zi(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 Vi=zi(Ji,Wi),Xi=`Bearer ${Vi}`;function jn(e,t){let n=Je(e);if(n!==null)return t.find(r=>Je(r.base)===n)}function Zi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=J();if(t.length>0){let r=jn(e,t);if(r)return r.key;if(C(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:C(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 Qi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=J();if(t.length>0){let r=e!==void 0?jn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&C(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():vt}if(!C(t[0].base))return vt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():vt}function eo(){return"1.0.2"}function to(){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 xe(e,t){let n=Zi(t);if(!n)throw to();let r=Qi(t),i=Math.floor(Date.now()/1e3).toString(),o=Gn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[qi]:eo()};return r.length>0&&(s[Hi]=r),s}function Ne(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var no=500,ro=8,Hn=100;function Ct(e,t=0){if(t>ro)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Hn),r=n.map(i=>Ct(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,Hn))n[r]=pe(r)?"<redacted>":Ct(i,t+1);return n}return e}function io(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 Be(e,t=no){let n=io(e),r=n===void 0?de(e):JSON.stringify(Ct(n));return fe(r,t)}var ce=256*1024,ae=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"}},De=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 Rt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new ae(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,u,d=n.timeoutMs,g=d===void 0?void 0:new Promise((p,w)=>{u=setTimeout(()=>{w(new De(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 ae(e.status,t,n.oversizeKind);s.push(Buffer.from(A))}}catch(p){throw p instanceof De&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}async function Pt(e,t){let n;try{n=await Rt(e,t)}catch(r){if(r instanceof ae)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var da=32*1024*1024,pa=4*1024*1024;function oo(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${en(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 $e(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}oo(e.status,e.url)}}var so=2014;function ao(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 co(e){return ao(e,so)}var lo=1e4;async function Ue(e,t=lo){if(e.status>=200&&e.status<300)return"";try{return await Rt(e,ce,{timeoutMs:t})}catch{return""}}function Fe(e,t){if(!(e>=200&&e<300)&&co(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"?Be(t):t})}var Bt=require("process");var uo={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function qn(e){if(typeof e=="string")return e;if(typeof e=="number")return uo[e]??`user_type_${e}`}function xt(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 Nt=require("process");var Wn=new Set;function Jn(e,t,n){he()||_e()||Nt.stderr.isTTY&&(Wn.has(e)||(Wn.add(e),Nt.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
|
|
18
|
-
`),
|
|
19
|
-
`);if(n!==-1)return e.slice(0,n).trim();if(Buffer.byteLength(e,"utf-8")>=
|
|
20
|
-
`)}catch(
|
|
21
|
-
`);let
|
|
22
|
-
${
|
|
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,...
|
|
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",er=Symbol("cli-otp-route-missing");async function tr(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 nr(e){let t=await Nt(e,le);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 rr(e,t){let n=await _o(e,t);return n!==er?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 tr(e,mo,n);await Me(r);let i=await Ge(r);Ke(r.status,i);let o=Le(i),s=Oe({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return er;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 nr(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 tr(e,yo,n);await Me(r);let i=await Ge(r);Ke(r.status,i);let o=Le(i),s=Oe({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=ke(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?mt(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 nr(r)}async function ir(e,t){Te(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=Le(l),d=_n(l),g=Oe({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",yt(`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 Nt(s,le)).data??{},A=Xn(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,Ut=Bt(w.user?.email)??Bt(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}:{},...Ut===void 0?{}:{user_email:Ut},user_type:A,api_base:e}}}var ue="ALLSCALE_OTP";function or(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[ue];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function sr(e,t){if(typeof e=="string"&&e.trim().length>0)return Zn("--otp",ue,"--otp-stdin"),e.trim();if(t){let r=process.env[ue];return typeof r=="string"&&r.trim().length>0&&$t.stderr.write(`warning: --otp-stdin is set, so ${ue} is ignored (stdin takes precedence).
|
|
18
|
+
`),Qn()}let n=process.env[ue];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(process.stdin.isTTY)return $t.stderr.write("OTP code: "),Qn()}var bo=1024;async function Qn(){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: "+_t(Ce)+". "+(wt.size>0?_t(wt)+" \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. "+Ln(Ce)+"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();wn(n),En(!!t["no-existence-check"]),Tn(t.scopes);let r=this.resolveContext(t);if(!or(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=Kn({insecureStorage:r.insecureStorage});await Yn(o,r.profile);let s=t["otp-id"],l=s!==void 0,u=s?.trim()??"",d=!1;if(l&&Te(u),!l)try{u=(await rr(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 sr(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 ir(r.apiBase,{email:n,otp_id:u,otp_code:g,otpIdFromSendLeg:d,scopes:t.scopes,device_label:t["device-label"]});await jn(o,r.profile,p.tokens);let w=ne(),A=gn(w,r.profile,{api_base:r.apiBase,user_type:So(p.user_type),api_base_source:r.apiBaseSource});A.default||(A.default=r.profile),pn(A),Ye.stderr.write(`Saved tokens to ${o.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${r.profile}). Profile metadata: ${Se()}
|
|
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 \`${qt(r.profile)}\` when it expires or is revoked.
|
|
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
|