@allscale/cli 0.1.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -45
- package/bin/dev.js +11 -1
- package/bin/run-oclif.js +216 -27
- package/bin/run.js +19 -1
- package/dist/commands/build-info.js +13 -13
- package/dist/commands/claim-link/claim.js +14 -14
- package/dist/commands/claim-link/create.js +40 -37
- package/dist/commands/claim-link/get.js +26 -15
- package/dist/commands/claim-link/list.js +15 -15
- package/dist/commands/claim-link/status.js +14 -14
- package/dist/commands/describe.js +13 -13
- package/dist/commands/device-login.js +29 -29
- package/dist/commands/invoice/get.js +15 -15
- package/dist/commands/invoice/list.js +16 -16
- package/dist/commands/invoice/pay.js +46 -43
- package/dist/commands/invoice/received.js +16 -16
- package/dist/commands/invoice/send.js +42 -34
- package/dist/commands/invoice/sent.js +15 -15
- package/dist/commands/invoice/update.js +17 -15
- package/dist/commands/logout.js +19 -13
- package/dist/commands/operations.js +13 -13
- package/dist/commands/otp-login.js +21 -20
- package/dist/commands/otp-send.js +13 -13
- package/dist/commands/payout/send.js +14 -14
- package/dist/commands/payout/status.js +15 -15
- package/dist/commands/scope.js +19 -18
- package/dist/commands/store/create.js +17 -17
- package/dist/commands/transaction/get.js +15 -15
- package/dist/commands/transaction/list.js +15 -15
- package/dist/commands/wallet/list.js +15 -15
- package/dist/commands/wallet/send.js +40 -43
- package/dist/commands/whoami.js +17 -15
- package/dist/hooks/version-suffix.js +1 -1
- package/dist/index.js +14 -14
- package/dist/lib/help.js +7 -2
- package/dist/lib/output/audit-lifecycle.js +7 -0
- package/oclif.manifest.json +140 -296
- package/package.json +4 -6
- package/dist/commands/claim-link/preview.js +0 -18
|
@@ -1,23 +1,24 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var f=
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}
|
|
6
|
-
`);return}f.appendFileSync(
|
|
7
|
-
`)}catch(r){if(
|
|
8
|
-
`)}catch{}}}var
|
|
9
|
-
The CLI default is now ${
|
|
1
|
+
"use strict";var rr=Object.create;var ue=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var or=Object.getOwnPropertyNames;var sr=Object.getPrototypeOf,ar=Object.prototype.hasOwnProperty;var cr=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},$t=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of or(t))!ar.call(e,i)&&i!==n&&ue(e,i,{get:()=>t[i],enumerable:!(r=ir(t,i))||r.enumerable});return e};var b=(e,t,n)=>(n=e!=null?rr(sr(e)):{},$t(t||!e||!e.__esModule?ue(n,"default",{value:e,enumerable:!0}):n,e)),lr=e=>$t(ue({},"__esModule",{value:!0}),e);var yo={};cr(yo,{default:()=>Ge});module.exports=lr(yo);var Me=require("process");var I=require("@oclif/core");var Ut="public",Ft="https://app.allscale.io";var Mt=["https://app.allscale.io"];var je="Override the API base URL (public builds accept only https://app.allscale.io)";var He="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Gt(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 Kt(e){return Gt(e)!==null}function qe(e){let t=Gt(e);return t!==null&&Mt.includes(t.origin)}function W(){return"".trim()||void 0}function F(){return"public"}function C(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Je(e){try{return new URL(e).origin}catch{return null}}function J(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return We()}function We(){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 ur=/^[A-Za-z0-9._-]{1,64}$/;function dr(e){return ur.test(e)?e:"<profile>"}function jt(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":dr(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}var pr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_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},fr=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 Xe(e){return(typeof e=="string"?e:String(e??"")).replace(fr,"")}var gr=64;function ze(e,t=new Map,n=0){if(typeof e=="string")return Xe(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=gr)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(Xe(n)),this.code=t,this.details=r&&ze(r),this.name="AllscaleError"}get exitCode(){return pr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Ht(e){if(e instanceof c)return e;if(e instanceof Error){if(_r(e)){let t=wr(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 hr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),mr=[/^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 _r(e){if(yr(e))return!0;let t=e.name??"";return hr.has(t)?t==="CLIError"?Ve(e,"parse")||Yt(e.message):!0:Yt(e.message)}function yr(e){if(!Ve(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ve(e,"parse")}function Yt(e){return e?Xe(e).split(`
|
|
2
|
+
`).some(t=>mr.some(n=>n.test(t.trim()))):!1}function Ve(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function wr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function qt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var f=b(require("fs")),me=b(require("path")),Zt=b(require("crypto"));var Sr="...<truncated>",br=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Er=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,nt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ze=String.raw`(?:proxy[_-]?)?authorization`,Ar=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ze}"|'${Ze}'|${Ze})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${nt}`,"gi"),kr=/\b(https?:\/\/)[^\s/?#]+@/gi,Lr=String.raw`(?:[A-Za-z0-9]+[_-])*`,Tr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Jt=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)`,Wt=Jt(Lr),Or=Jt(Tr),Ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Wt}"|'${Wt}'|${Or})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${nt}`,"gi"),Qe=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)`,vr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Qe}"|'${Qe}'|${Qe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${nt}`,"g");function de(e){return e.replace(kr,"$1<redacted>@").replace(br,"<redacted-jwt>").replace(Ar,"$1$2$3<redacted>").replace(Ir,"$1$2<redacted>").replace(vr,"$1$2<redacted>").replace(Er,"Bearer <redacted>")}var Cr=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function pe(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Cr.test(t)}function zt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function fe(e,t,n=Sr){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 S(e,t=16384){return fe(zt(de(e)),t)}var et=100,Rr=8,Pr=8*1024;function ge(){return{remaining:Pr}}function tt(e,t){let n=Math.min(16384,t.remaining),r=fe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function M(e,t,n=0,r={}){if(n>Rr)return tt("<truncated>",t);if(typeof e=="string"){let i=de(e);return tt(r.escapeControls?zt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,et),o=i.map(s=>M(s,t,n+1,r));return e.length>i.length&&o.push(tt(`<${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,et))i[s]=M(l,t,n+1,r);return o.length>et&&(i.output_truncated=!0),i}return e}var rt=require("process");var it=!1;function ot(e){it=e}function he(){return it}var Vt="1";function K(e,t){if(it){let n={...e};delete n.version;let r=ge(),i={event:n.event,...n},o=M(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Vt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Vt,event:o.event,output_truncated:!0})),rt.stderr.write(`${s}
|
|
4
|
+
`)}else rt.stderr.write(t)}var Xt="2",Y=null,k=null,j=!1,z=!1;function xr(){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=Zt.randomBytes(4).toString("hex");return me.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var st=64*1024*1024,Nr=null;function at(e={}){if(e.quiet&&(z=!0),j)return;let t=xr();if(!t)return;Y=null;let n=null;try{if((Nr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=me.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{}z||K({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${S(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}Y=t,k=n,j=!0}var Br=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Dr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Br.some(n=>n.test(t))}function Qt(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=$r(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Dr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function $r(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Ur(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Qt(e.url)}:e}function Fr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=M(i,ge()),s=JSON.stringify({version:Xt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Xt,timestamp:t,type:r,output_truncated:!0})),s}function R(e){if(!j||!Y||k===null)return;let t=Ur(e),n=Fr(t);try{if(f.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>st){j=!1;try{f.closeSync(k)}catch{}k=null,z||K({event:"sidecar_disabled",reason:"size_limit",...Y===null?{}:{path:S(Y)},max_bytes:st},`${S(`[allscale] sidecar exceeded ${st} bytes; disabling it for the rest of this run. Rotate or remove ${Y}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
|
+
`);return}f.appendFileSync(k,`${n}
|
|
7
|
+
`)}catch(r){if(j=!1,k!==null){try{f.closeSync(k)}catch{}k=null}try{z||K({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var en=Qt;function _e(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function V(){if(z=!1,j=!1,k!==null){try{f.closeSync(k)}catch{}k=null}}function tn(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||_e()||!t}var X=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Mr=new Set(Array.from(X).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Gr=Array.from(X).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Kr=new Set(["--otp-stdin","--password-stdin"]);function ct(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(X.has(s)){t.push(`${s}=<redacted>`);continue}}}if(X.has(r)){t.push(r),n+1<e.length&&(X.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(Mr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Kr.has(r)?void 0:Gr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function nn(e){R({type:"error",code:e.code,message:S(e.message)}),R({type:"command-end",ok:!1,exitCode:e.exitCode}),V()}var Z=W()??Ft,q={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 lt(e){return Kt(e)?new URL(e).origin:null}function Q(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function rn(){let e=process.env[q.TOKEN]?.trim();return e&&e.length>0?e:void 0}function ut(){let e=process.env[q.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ee(){let e=process.env[q.API_BASE]?.trim();return e&&e.length>0?e:void 0}function on(){let e=process.env[q.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function sn(){let e=process.env[q.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function an(){let e=process.env[q.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function cn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(W()===void 0&&Z!==""&&"".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 ${Z} (production), but a saved profile wins over the default,
|
|
10
10
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
11
11
|
the old default rather than a deliberate choice.
|
|
12
|
-
To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
|
-
To move to production, run:
|
|
14
|
-
`}var O=w(require("fs")),Wt=w(require("os")),Qe=w(require("path")),de=w(require("@iarna/toml"));var mr=".allscale",_r="config.toml";function pe(){return Qe.join(Wt.homedir(),mr)}function fe(){return Qe.join(pe(),_r)}function X(){let e=fe();if(!O.existsSync(e))return{};let t=O.readFileSync(e,"utf-8");try{return de.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function Jt(e){let t=pe();O.existsSync(t)||O.mkdirSync(t,{recursive:!0,mode:448});let n=de.stringify(e);O.writeFileSync(fe(),n,{mode:384})}function zt(e,t){return e.profile?.[t]}function Vt(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function Xt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function ge(e){if(!De(e))throw new l("input.invalid",`Refusing to send credentials to API base ${q(e)}. `+Be)}function et(e){let t=W();if(t===void 0||R(e))return;let n=ce(e),r=z();if(r.length>0){let o=r.map(c=>ce(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>q(c.base)).join(", ");throw new l("input.invalid",`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.`)}let i=ce(t);if(!(n!==null&&n===i))throw new l("input.invalid",`Refusing to send to ${q(e)} \u2014 this build only signs for ${q(t)}. Re-login against this build's environment, or use a build for that one.`)}var yr=require("@noble/hashes/sha3");var Zt=["USDT","USDC"];var po=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var k=require("@oclif/core"),Z=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:J()==="public"}),"api-base":I.Flags.string({description:xe,helpGroup:"GLOBAL",hidden:J()==="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{Ve(this.jsonEnabled()),Ut(),Y({type:"session-start",command:this.id??"",argv:Sr(this.argv)});let t=this.constructor;if(J()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ue()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!jt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=Gt(this.jsonEnabled()),r=this.argv.length===0&&!n&&Ir(t)?this.config.findCommand(this.id??""):void 0;if(r){le();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}let i=await this.runCommand();return Y({type:"command-end",ok:!0}),le(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ct(i),{data:i})}catch(t){let n=It(t);Y({type:"error",code:n.code,message:S(n.message)}),Y({type:"command-end",ok:!1,exitCode:n.exitCode}),le(),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ve(!1)}}resolveSessionApiBaseChain(t){let n=X(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Ze()!==void 0,s=Xt(n,r,Ze()),c=zt(n,s),u=i??ue(),d=u??c?.api_base??V,m=qt({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return m&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,M({event:"legacy_staging_profile",api_base:d,profile:s},m)),{apiBase:d,explicitApiBase:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||ge(n),n}resolveContext(t){if(J()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ue()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(ge(i),et(i)),{apiBase:i,profile:s,token:n??Kt(),insecureStorage:r||Yt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Or(t)}
|
|
15
|
-
`)}},me=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"]),wr=new Set(Array.from(me).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Sr(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(me.has(o)){t.push(`${o}=<redacted>`);continue}}}if(me.has(r)){t.push(r),n+1<e.length&&(me.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(wr.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Er=/(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 br(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Er.test(t)}var Ar=/_(removed|cleared|count|total)$/i;function kr(e,t){return typeof t=="number"&&Ar.test(e)}var Lr=new Set(Zt);function Tr(e,t){return e==="token_symbol"&&typeof t=="string"&&Lr.has(t)}var he=100;function tt(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,he),r=n.map(i=>tt(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,he))n[i]=br(i)&&!kr(i,o)&&!Tr(i,o)?"<redacted>":tt(o,t+1);if(r.length>he){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-he} more keys`}return n}return typeof e=="string"?S(e):e}function Or(e){let t=xt()?void 0:2,n=tt(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 Ir(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 Qt(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 en=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","store:all","wallet:read_only"]);var gn=w(require("path"));var it=require("crypto"),a=w(require("fs")),h=w(require("path"));var _e=1024*1024,Cr=5e3,Rr=20,Pr=3e4,nt=4096,vr=new Int32Array(new SharedArrayBuffer(4)),Q=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ye(e){return e instanceof Q}var E=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Nr=null;function v(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function we(){return(Nr??process.platform)!=="win32"}function cn(){if(!we())throw v()}function un(e){try{return a.default.lstatSync(e),!1}catch(t){if(!g(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(h.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(g(t,"ENOENT"))return!0;throw t}}function g(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ee(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function te(e,t){return e.dev===t.dev&&e.ino===t.ino}function xr(e){Atomics.wait(vr,0,0,e)}function dn(e){try{return process.kill(e,0),!0}catch(t){return!g(t,"ESRCH")}}function Br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tn(e,t){let n=h.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&g(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()||!te(o,s))throw new Error("credential-store parent changed while it was being inspected");ee(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&h.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),c=a.default.fstatSync(i)),(c.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 C(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&&g(o,"ENOENT")?new E:o}if(!te(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 Q;if(ee(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 Dr(e,t){if(t.size>_e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(_e+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>_e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function nn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(g(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(g(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=C(e,t,n);return Dr(t,r)}finally{t!==null&&a.default.closeSync(t)}}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(i){if(g(i,"ENOENT")&&un(e))return;throw i}let n=a.default.fstatSync(t),r=C(e,t,n);N(e,r)}finally{t!==null&&a.default.closeSync(t)}fn(h.dirname(e))}function Ur(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(g(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 Q;ee(t,"credential-store replacement target")}function $r(e,t){for(let n=0;n<8;n+=1){let r=(0,it.randomBytes)(12).toString("hex"),i=h.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(g(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function pn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function fn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Fr(e,t){let n=Buffer.from(t,"utf8");if(n.length>_e)throw new Error("credential-store file exceeds the maximum supported size");let r=h.dirname(e),i=h.basename(e),o=null,s=null,c=!1;try{let u=$r(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((C(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");pn(o,n),a.default.fsyncSync(o),C(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ur(e),a.default.renameSync(s,e),c=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}fn(r)}function Mr(e){return h.join(h.dirname(e),`.${h.basename(e)}.lock`)}function Gr(e){return h.join(h.dirname(e),`.${h.basename(e)}.lock-recovery`)}function Kr(e,t){if(t.size>nt)return null;let n=Buffer.alloc(nt+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>nt)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()||!te(n,t))throw new Error("credential-store lock changed while it was being inspected");ee(n,"credential-store lock"),a.default.unlinkSync(e)}function on(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(g(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(g(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=C(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Kr(n,i);return{state:(o?.target===t&&o?!dn(o.pid):Date.now()-i.mtimeMs>=Pr)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Yr(e,t){for(let n=0;n<8;n+=1){let r=(0,it.randomBytes)(12).toString("hex"),i=h.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 c=a.default.fstatSync(s),u=C(i,s,c,{allowMultipleLinks:!0});return pn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(g(c,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Hr(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 g(r,"ENOENT")?new E:r}try{let r=a.default.fstatSync(n),i=C(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!te(i,t))throw new E;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function sn(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(g(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(g(r,"ENOENT"))return!1;throw r}throw n}return C(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function jr(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(g(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=C(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");xr(Rr)}function an(e){let t=h.dirname(e),n=h.basename(e),r=Mr(e),i=Gr(e),o=Yr(t,n),s=Date.now()+Cr,c=!1,u=!1,d=null,m;try{for(;d===null;)try{if(sn(i)){P(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Hr(r,o.stats),c=!0}catch(p){if(u&&!c){try{N(r,o.stats)}catch{}u=!1}if(p instanceof E){P(s,!1);continue}if(!g(p,"EEXIST"))throw p;let _;try{_=on(r,n)}catch(y){if(y instanceof E){P(s,!1);continue}throw y}if(_.state==="absent")continue;if(_.state==="stale"){let y;try{y=jr(i)}catch(A){if(A instanceof E){P(s,!1);continue}throw A}if(y!==null){try{let A;try{A=on(r,n)}catch(D){if(D instanceof E){P(s,!1);continue}throw D}A.state==="stale"&&N(r,A.stats)}finally{rt(y)}continue}}let T;try{T=sn(i)}catch(y){if(y instanceof E){P(s,!1);continue}throw y}P(s,T)}}catch(p){m=p}try{N(o.claimPath,o.stats)}catch(p){!g(p,"ENOENT")&&!c&&m===void 0&&(m=p)}if(m!==void 0)throw m;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function rt(e){try{N(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function qr(e,t){let n=Br(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 ln(e){let t=h.dirname(e),n=h.basename(e);for(let r of a.default.readdirSync(t)){let i=qr(r,n);if(i===null||dn(i))continue;let o=h.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(g(d,"ENOENT")||g(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!te(c,u))continue;try{ee(c,"credential-store orphan")}catch{continue}N(o,c)}catch(c){if(!g(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ne(e,t,n){if(!we()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw v();if(!tn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw v()}});let s=an(e);try{return ln(e),n({read:()=>nn(e),remove:()=>rn(e),write:()=>{throw v()}})}finally{rt(s)}}if(!t.createParent){let o=!1;try{o=un(e)}catch{throw v()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw v()}})}throw v()}if(!tn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=an(e);try{return ln(e),n({read:()=>nn(e),remove:()=>rn(e),write:o=>Fr(e,o)})}finally{rt(i)}}var ot="allscale-cli";function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hn(e){return ct(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function B(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function st(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Se(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var x,at=!1;function Wr(){return Ht()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Jr(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 zr(){if(x!==void 0)return x;if(Wr())return at=!1,x=null,x;try{x=require("keytar"),at=!1}catch(e){at=!Jr(e),x=null}return x}function mn(){let e=we()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function lt(e){try{return await e()}catch{throw mn()}}var ut=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await lt(()=>this.keytar.getPassword(ot,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw B("OS keychain")}if(!hn(r))throw B("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await lt(()=>this.keytar.setPassword(ot,t,JSON.stringify(n)))}async delete(t){await this.read(t),await lt(()=>this.keytar.deletePassword(ot,t))}},Vr="credentials.json",dt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??gn.join(pe(),Vr)}read(t){let n;try{n=t.read()}catch(i){throw ye(i)?st():B("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw B("plaintext file")}if(!ct(r)||!ct(r.profiles))throw B("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ye(r)?st():Se()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!hn(r))throw B("plaintext file");return r}}async get(t){try{return ne(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:B("plaintext file")}}async set(t,n){try{ne(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof l?r:Se()}}async delete(t){try{ne(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Se()}}async clearProfile(t){try{return ne(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:ye(n)?st():Se()}}};function _n(e){if(e.insecureStorage)return cn(),new dt(e.insecureFilePath);let t=zr();if(t)return new ut(t);throw mn()}async function yn(e,t){await e.get(t)}async function wn(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof l?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 l(r instanceof l?r.code:"storage.unavailable",`${i} ${o}`,r instanceof l?r.details:void 0)}}var Sn=w(require("crypto")),En=w(require("fs")),bn=w(require("path"));var Xr="key-id",Zr="x-allscale-cli-version",pt="cli-1",Qr="aScaLe_cli_obf_v1",ei="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function ti(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 ni=ti(ei,Qr),ri=`Bearer ${ni}`;function An(e,t){let n=$e(e);if(n!==null)return t.find(r=>$e(r.base)===n)}function ii(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=An(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 oi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?An(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():pt}if(!R(t[0].base))return pt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():pt}function si(){return"0.1.0"}function ai(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ee(e,t){let n=ii(t);if(!n)throw ai();let r=oi(t),i=Math.floor(Date.now()/1e3).toString(),o=Sn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Zr]:si()};return r.length>0&&(s[Xr]=r),s}function be(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ie=256*1024,re=class extends l{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Ae=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 ft(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 re(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,m=d===void 0?void 0:new Promise((p,_)=>{u=setTimeout(()=>{_(new Ae(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:_,value:T}=m?await Promise.race([p,m]):await p;if(_)break;if(c+=T.byteLength,c>t)throw o.cancel().catch(()=>{}),new re(e.status,t,n.oversizeKind);s.push(Buffer.from(T))}}catch(p){throw p instanceof Ae&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}async function gt(e,t){let n;try{n=await ft(e,t)}catch(r){if(r instanceof re)throw r;return{}}if(n.length===0)return{};try{return JSON.parse(n)}catch{return{}}}var cs=32*1024*1024,us=4*1024*1024;function li(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${Ft(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 ke(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}li(e.status,e.url)}}var kn=2014;function ci(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===kn||n===String(kn)}var ui=1e4;async function Le(e,t=ui){if(e.status>=200&&e.status<300)return"";try{return await ft(e,ie,{timeoutMs:t})}catch{return""}}function Te(e,t){if(!(e>=200&&e<300)&&ci(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}var _t=require("process");var di={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function Ln(e){if(typeof e=="string")return e;if(typeof e=="number")return di[e]??`user_type_${e}`}function ht(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 Tn=3100,pi=2090,fi=2001,gi=2092,L="allscale.io";function Oe(e){let t=e.lastIndexOf("@");return t===-1?"":e.slice(t+1).toLowerCase()}function Ie(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{}}function hi(e,t){return new l("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:Tn})}function mt(e,t,n,r,i){let o=Oe(e),s=o.endsWith(`.${L}`)?`@${L} subdomains are not whitelisted \u2014 use a bare @${L} address, or contact support / wait for the backend allowlist fix.`:`Use an @${L} address, or contact support / wait for the backend allowlist fix.`,c=i?`OTP delivery to '${o}' is not permitted on this environment \u2014 only @${L} addresses can receive a login code here. Re-run with an @${L} 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 @${L} is whitelisted.`;return new l(r,c,{status:t,recipient_domain:o,...n===void 0?{}:{backend_code:n},...i?{external_domain:!0,recovery_hint:s}:{}})}function mi(e,t){return new l("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 On(e){if(e.length===0)throw new l("input.invalid","An email address is required.");if(!/^[^\s@]+@[^\s@]+$/.test(e))throw new l("input.invalid",`'${e}' is not a valid email address. Pass a full address such as you@example.com.`)}function In(e){if(e)throw new l("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 _i=[{flows:["otp-send","cli-otp-send","otp-verify","password"],status:404,code:Tn,build:e=>hi(e.email,e.status)},{flows:["otp-send"],status:403,code:pi,when:e=>{let t=Oe(e.email);return t.length>0&&t!==L},build:e=>mt(e.email,e.status,e.backendCode,"input.invalid",!0)},{flows:["cli-otp-send"],status:403,code:gi,build:e=>new l("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:fi,build:e=>mi(e.status,e.backendCode)},{flows:["otp-verify"],status:400,code:7014,build:e=>new l("input.invalid","OTP rejected: the code may be incorrect, expired, already used, or locked after too many attempts. Request a new code and try again.",{status:e.status,backend_code:e.backendCode})},{flows:["otp-verify"],status:400,code:7531,build:e=>new l("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 l("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 Ce(e){if(e.backendCode!==void 0){for(let t of _i)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 yi="/api/v1/public/turnkey/cli/email-otps",wi="/api/v1/public/turnkey/email-otps",Rn=Symbol("cli-otp-route-missing");async function Pn(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=Ee(be(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 l("transport.network",`Network error contacting ${r}: ${s.message}`)}}async function vn(e){let t=await gt(e,ie);if(typeof t.data!="string"||t.data.length===0)throw new l("backend.internal","OTP send response did not include otp_id.",{body:JSON.stringify(t).slice(0,500)});return{otp_id:t.data}}async function Nn(e,t){let n=await Si(e,t);return n!==Rn?n:Ei(e,t)}async function Si(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await Pn(e,yi,n);await ke(r);let i=await Le(r);Te(r.status,i);let o=Ie(i),s=Ce({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return Rn;if(r.status===429)throw new l("rate_limited","OTP send throttled by the backend. Wait before retrying.",{status:429});if(r.status>=500)throw new l("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new l("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return vn(r)}async function Ei(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 Pn(e,wi,n);await ke(r);let i=await Le(r);Te(r.status,i);let o=Ie(i),s=Ce({flow:"otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404)throw new l("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 c=Oe(t.email),u=c.length>0&&c!==L;if(r.status===429)throw new l("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 l("backend.internal",`Backend returned ${r.status} when sending OTP.`,{status:r.status});if(r.status!==200)throw new l("input.invalid",`OTP send failed: HTTP ${r.status}`,{status:r.status,...o===void 0?{}:{backend_code:o}});return vn(r)}async function xn(e,t){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=Ee(be(r),e),s;try{s=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(U){throw new l("transport.network",`Network error contacting ${n}: ${U.message}`)}await ke(s);let c=await Le(s);Te(s.status,c);let u=Ie(c),d=Ce({flow:"otp-verify",status:s.status,backendCode:u,email:t.email});if(d)throw d;if(s.status===401||s.status===403)throw new l("auth.permission_denied","OTP rejected: the code may be incorrect, expired, already used, or locked after too many attempts. Request a new code and try again.",{status:s.status});if(s.status===404)throw new l("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 l("rate_limited","OTP verification throttled by the backend. Wait before retrying.",{status:429});if(s.status>=500)throw new l("backend.internal",`Backend returned ${s.status} during OTP auth.`,{status:s.status});if(s.status!==200){let U=u;throw new l("input.invalid",`OTP auth failed: HTTP ${s.status}`,{status:s.status,...U===void 0?{}:{backend_code:U}})}let p=(await gt(s,ie)).data??{},_=Ln(p.user_type)??"business",T=p.agent_key;if(typeof T!="string"||T.length===0)throw new l("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 y=p.scopes,A=Array.isArray(y)&&y.every(U=>typeof U=="string")?y:[],D=p.agent_key_expires_at,Ne=p.business_id,yt=ht(p.user?.email)??ht(t.email);return{user:p.user??{},user_type:_,scopes:A,tokens:{access_token:"",refresh_token:"",agent_key:T,...typeof D=="number"&&D>0?{agent_key_expires_at:D}:{},...A.length>0?{scopes:A}:{},...typeof Ne=="string"&&Ne.length>0?{business_id:Ne}:{},...yt===void 0?{}:{user_email:yt},user_type:_,api_base:e}}}var Re="ALLSCALE_OTP";function Bn(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[Re];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function Dn(e,t){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(t){let r=process.env[Re];return typeof r=="string"&&r.trim().length>0&&_t.stderr.write(`warning: --otp-stdin is set, so ${Re} is ignored (stdin takes precedence).
|
|
17
|
-
`),
|
|
18
|
-
`)
|
|
19
|
-
`)}catch(
|
|
20
|
-
`)
|
|
21
|
-
|
|
22
|
-
|
|
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 ${Z}
|
|
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 po="/api/v1/public/turnkey/cli/email-otps",fo="/api/v1/public/turnkey/email-otps",Vn=Symbol("cli-otp-route-missing");async function Xn(e,t,n){let r=new URL(t,e).toString(),i=JSON.stringify(n),o=xe(Ne(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 Zn(e){let t=await Pt(e,ce);if(typeof t.data!="string"||t.data.trim().length===0)throw new c("backend.internal","OTP send response did not include otp_id.",{body:Be(JSON.stringify(t))});return{otp_id:t.data}}async function Qn(e,t){let n=await go(e,t);return n!==Vn?n:ho(e,t)}async function go(e,t){let n={email:t.email};t.ui_language!==void 0&&(n.ui_language=t.ui_language);let r=await Xn(e,po,n);await $e(r);let i=await Ue(r);Fe(r.status,i);let o=ke(i),s=Te({flow:"cli-otp-send",status:r.status,backendCode:o,email:t.email});if(s)throw s;if(r.status===404&&o===void 0)return Vn;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 Zn(r)}async function ho(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 Xn(e,fo,n);await $e(r);let i=await Ue(r);Fe(r.status,i);let o=ke(i),s=Te({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=Ae(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?ft(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 Zn(r)}async function er(e,t){Le(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=xe(Ne(r),e),s;try{s=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i,redirect:"manual"})}catch(U){throw new c("transport.network",`Network error contacting ${n}: ${U.message}`)}await $e(s);let l=await Ue(s);Fe(s.status,l);let u=ke(l),d=mn(l),g=Te({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",gt(`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 U=u;throw new c("input.invalid",`OTP auth failed: HTTP ${s.status}`,{status:s.status,...U===void 0?{}:{backend_code:U}})}let w=(await Pt(s,ce)).data??{},A=qn(w.user_type)??"business",_=w.agent_key;if(typeof _!="string"||_.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 y=w.scopes,$=Array.isArray(y)&&y.every(U=>typeof U=="string")?y:[],Ke=w.agent_key_expires_at,Ye=w.business_id,Dt=xt(w.user?.email)??xt(t.email);return{user:w.user??{},user_type:A,scopes:$,tokens:{access_token:"",refresh_token:"",agent_key:_,...typeof Ke=="number"&&Ke>0?{agent_key_expires_at:Ke}:{},...$.length>0?{scopes:$}:{},...typeof Ye=="string"&&Ye.length>0?{business_id:Ye}:{},...Dt===void 0?{}:{user_email:Dt},user_type:A,api_base:e}}}var le="ALLSCALE_OTP";function tr(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[le];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function nr(e,t){if(typeof e=="string"&&e.trim().length>0)return Jn("--otp",le,"--otp-stdin"),e.trim();if(t){let r=process.env[le];return typeof r=="string"&&r.trim().length>0&&Bt.stderr.write(`warning: --otp-stdin is set, so ${le} is ignored (stdin takes precedence).
|
|
18
|
+
`),zn()}let n=process.env[le];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(process.stdin.isTTY)return Bt.stderr.write("OTP code: "),zn()}var mo=1024;async function zn(){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")>=mo)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 Ge=class e extends ne{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: "+ht(_t)+". "+(mt.size>0?ht(mt)+" \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. 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."}),...ne.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=t.email.trim();_n(n),Sn(!!t["no-existence-check"]),En(t.scopes);let r=this.resolveContext(t);if(!tr(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=Un({insecureStorage:r.insecureStorage});await Fn(o,r.profile);let s=t["otp-id"],l=s!==void 0,u=s?.trim()??"",d=!1;if(l&&Le(u),!l)try{u=(await Qn(r.apiBase,{email:n})).otp_id,d=!0,Me.stderr.write(`OTP sent to ${n}. otp_id=${u}. Check your inbox; the code is short-lived.
|
|
20
|
+
`)}catch(y){throw y instanceof c&&y.code==="rate_limited"&&y.details?.status===429?new c(y.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.",y.details):y}let g=await nr(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 er(r.apiBase,{email:n,otp_id:u,otp_code:g,otpIdFromSendLeg:d,scopes:t.scopes,device_label:t["device-label"]});await Mn(o,r.profile,p.tokens);let w=te(),A=pn(w,r.profile,{api_base:r.apiBase,user_type:_o(p.user_type),api_base_source:r.apiBaseSource});A.default||(A.default=r.profile),un(A),Me.stderr.write(`Saved tokens to ${o.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${r.profile}). Profile metadata: ${Se()}
|
|
21
|
+
`);let _=typeof p.tokens.agent_key_expires_at=="number"?new Date(p.tokens.agent_key_expires_at*1e3).toISOString():void 0;return Me.stderr.write(`Credential: scoped agent key. Scopes${p.scopes.length>0?` (${p.scopes.join(", ")})`:""} are checked by the backend on each request.
|
|
22
|
+
${_?`The key expires at ${_}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`${jt(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,..._?{agent_key_expires_at:_}:{}}}};function _o(e){return e==="business"||e==="employee"||e==="admin"?e:"business"}
|
|
23
24
|
//# sourceMappingURL=otp-login.js.map
|