@allscale/cli 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/commands/claim-link/claim.js +12 -12
- package/dist/commands/claim-link/create.js +26 -26
- package/dist/commands/claim-link/get.js +11 -11
- package/dist/commands/claim-link/list.js +10 -10
- package/dist/commands/claim-link/status.js +12 -12
- package/dist/commands/describe.js +3 -3
- package/dist/commands/device-login.js +20 -20
- package/dist/commands/invoice/get.js +11 -11
- package/dist/commands/invoice/list.js +11 -11
- package/dist/commands/invoice/pay.js +23 -23
- package/dist/commands/invoice/received.js +11 -11
- package/dist/commands/invoice/send.js +23 -23
- package/dist/commands/invoice/sent.js +10 -10
- package/dist/commands/invoice/update.js +11 -11
- package/dist/commands/operations.js +6 -6
- package/dist/commands/otp-login.js +14 -14
- package/dist/commands/otp-send.js +10 -10
- package/dist/commands/payout/send.js +4 -4
- package/dist/commands/payout/status.js +11 -11
- package/dist/commands/store/create.js +12 -12
- package/dist/commands/transaction/get.js +11 -11
- package/dist/commands/transaction/list.js +10 -10
- package/dist/commands/wallet/list.js +11 -11
- package/dist/commands/wallet/send.js +27 -27
- package/dist/index.js +13 -13
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -178,11 +178,15 @@ rather than treating this table as an exhaustive switch.
|
|
|
178
178
|
| `pairing_token_unrecognized` | `auth.no_token` / 4 | The backend returned 7511, but the CLI cannot authoritatively prove the window closed. The record may be unknown, evicted, or already consumed; a missing backend `Date` header also keeps this neutral classification. |
|
|
179
179
|
| `pairing_token_unrecognized_after_window_closed` | `auth.device_pairing_timeout` / 3 | With no unresolved transient failure, a poll returned 7511 and the backend's own clock was at or past the backend-minted `expires_at`. |
|
|
180
180
|
| `pairing_deadline_backend_ttl` | `auth.device_pairing_timeout` / 3 | With no unresolved transient failure, the poll loop stopped at an effective deadline selected from the backend's `expires_at`, rather than the CLI ceiling. This identifies the bound that fired; because the loop observes that bound with the local clock, it does not by itself prove what the backend clock says now. |
|
|
181
|
-
| `pairing_deadline_cli_ceiling` | `auth.device_pairing_timeout` / 3 | With no unresolved transient failure, the poll loop reached the CLI's own ceiling before `expires_at`; the pairing may still be live server-side,
|
|
181
|
+
| `pairing_deadline_cli_ceiling` | `auth.device_pairing_timeout` / 3 | With no unresolved transient failure, the poll loop reached the CLI's own ceiling before `expires_at`; the pairing may still be live server-side, but this process has stopped collecting results. Do not approve this code after the CLI stops. |
|
|
182
182
|
| `invalid_polling_token_after_transient_failure` | `backend.internal` / 9 | After an unresolved transient poll failure, a later poll returned 7511. The one-shot approval response may have been consumed and lost; `details.outcome_ambiguous` is `true`. |
|
|
183
183
|
| `transient_retry_budget_exhausted` | `backend.internal` / 9 | Retryable poll failures exhausted the bounded retry budget without a definitive pending response; `details.outcome_ambiguous` is `true`. |
|
|
184
184
|
| `pairing_deadline_elapsed_after_transient_failure` | `backend.internal` / 9 | The effective pairing deadline elapsed while a transient poll failure remained unresolved; `details.outcome_ambiguous` is `true`. |
|
|
185
185
|
|
|
186
|
+
The two `pairing_deadline_backend_ttl` / `pairing_deadline_cli_ceiling` errors
|
|
187
|
+
also include `details.polling_deadline_at`: the same ISO 8601 UTC timestamp
|
|
188
|
+
announced in the initial `device_authorization` stderr/sidecar event.
|
|
189
|
+
|
|
186
190
|
The single-attempt poll helper also uses six retry-only reasons internally.
|
|
187
191
|
`runDevicePairingLogin` catches these and either receives a later definitive
|
|
188
192
|
response or converts the terminal outcome into one of the three
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var h=A(require("fs")),
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}H=t,L=n,W=!0}var
|
|
1
|
+
"use strict";var hr=Object.create;var ue=Object.defineProperty;var gr=Object.getOwnPropertyDescriptor;var mr=Object.getOwnPropertyNames;var _r=Object.getPrototypeOf,yr=Object.prototype.hasOwnProperty;var wr=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},xt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of mr(t))!yr.call(e,i)&&i!==n&&ue(e,i,{get:()=>t[i],enumerable:!(r=gr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?hr(_r(e)):{},xt(t||!e||!e.__esModule?ue(n,"default",{value:e,enumerable:!0}):n,e)),Er=e=>xt(ue({},"__esModule",{value:!0}),e);var Ko={};wr(Ko,{default:()=>xe,requireSuccessfulClaim:()=>fr});module.exports=Er(Ko);var I=require("@oclif/core");var Pt="public",Bt="https://app.allscale.io";var $t=["https://app.allscale.io"];var $e="Override the API base URL (public builds accept only https://app.allscale.io)";var De="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Dt(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 Ut(e){return Dt(e)!==null}function Ue(e){let t=Dt(e);return t!==null&&$t.includes(t.origin)}function V(){return"".trim()||void 0}function C(){return"public"}function x(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Me(e){try{return new URL(e).origin}catch{return null}}function X(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Fe()}function Fe(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:u}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";i.push({base:s.trim(),key:c,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 br="device-login",Sr=/^[A-Za-z0-9._-]{1,64}$/;function qe(e){return Sr.test(e)?e:"<profile>"}function Z(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":qe(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function de(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Mt(e){let t=qe(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Z(e)}\` for headless automation.`}function Gt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${br} --profile ${qe(e)}\`.`}var Ar={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var kr=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 je(e){return(typeof e=="string"?e:String(e??"")).replace(kr,"")}var Lr=64;function Ge(e,t=new Map,n=0){if(typeof e=="string")return je(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Lr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Ge(c,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,c]of Object.entries(e))Object.defineProperty(o,s,{value:Ge(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(je(n)),this.code=t,this.details=r&&Ge(r),this.name="AllscaleError"}get exitCode(){return Ar[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Kt(e){if(e instanceof a)return e;if(e instanceof Error){if(Or(e)){let t=vr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var Tr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Ir=[/^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 Or(e){if(Cr(e))return!0;let t=e.name??"";return Tr.has(t)?t==="CLIError"?Ke(e,"parse")||Ft(e.message):!0:Ft(e.message)}function Cr(e){if(!Ke(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ke(e,"parse")}function Ft(e){return e?je(e).split(`
|
|
2
|
+
`).some(t=>Ir.some(n=>n.test(t.trim()))):!1}function Ke(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function vr(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 h=A(require("fs")),me=A(require("path")),Vt=A(require("crypto"));var Rr="...<truncated>",Nr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,xr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Je=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ye=String.raw`(?:proxy[_-]?)?authorization`,Pr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ye}"|'${Ye}'|${Ye})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Je}`,"gi"),Br=/\b(https?:\/\/)[^\s/?#]+@/gi,$r=String.raw`(?:[A-Za-z0-9]+[_-])*`,Dr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Yt=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)`,jt=Yt($r),Ur=Yt(Dr),Fr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${jt}"|'${jt}'|${Ur})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Je}`,"gi"),He=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,Mr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${He}"|'${He}'|${He})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Je}`,"g");function fe(e){return e.replace(Br,"$1<redacted>@").replace(Nr,"<redacted-jwt>").replace(Pr,"$1$2$3<redacted>").replace(Fr,"$1$2<redacted>").replace(Mr,"$1$2<redacted>").replace(xr,"Bearer <redacted>")}var Gr=/(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 Gr.test(t)}function Ht(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function he(e,t,n=Rr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let i=t-r,o="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>i)break;o+=c,s+=u}return`${o}${n}`}function S(e,t=16384){return he(Ht(fe(e)),t)}var We=100,Kr=8,qr=8*1024;function ge(){return{remaining:qr}}function ze(e,t){let n=Math.min(16384,t.remaining),r=he(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function q(e,t,n=0,r={}){if(n>Kr)return ze("<truncated>",t);if(typeof e=="string"){let i=fe(e);return ze(r.escapeControls?Ht(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,We),o=i.map(s=>q(s,t,n+1,r));return e.length>i.length&&o.push(ze(`<${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,c]of o.slice(0,We))i[s]=q(c,t,n+1,r);return o.length>We&&(i.output_truncated=!0),i}return e}var Ve=require("process");var Xe=!1;function Ze(e){Xe=e}function zt(){return Xe}var Wt="1";function Y(e,t){if(Xe){let n={...e};delete n.version;let r=ge(),i={event:n.event,...n},o=q(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Wt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Wt,event:o.event,output_truncated:!0})),Ve.stderr.write(`${s}
|
|
4
|
+
`)}else Ve.stderr.write(t)}var Jt="2",H=null,L=null,W=!1,Q=!1;function jr(){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=Vt.randomBytes(4).toString("hex");return me.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Qe=64*1024*1024,Yr=null;function et(e={}){if(e.quiet&&(Q=!0),W)return;let t=jr();if(!t)return;H=null;let n=null;try{if((Yr??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(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=h.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=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|i,384);let o=h.fstatSync(n),s=h.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=o.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}Q||Y({event:"sidecar_disabled",reason:"open_failed",detail:S(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${S(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}H=t,L=n,W=!0}var Hr=[/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 Wr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Hr.some(n=>n.test(t))}function Xt(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=zr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Wr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function zr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Jr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Xt(e.url)}:e}function Vr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=q(i,ge()),s=JSON.stringify({version:Jt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Jt,timestamp:t,type:r,output_truncated:!0})),s}function w(e){if(!W||!H||L===null)return;let t=Jr(e),n=Vr(t);try{if(h.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Qe){W=!1;try{h.closeSync(L)}catch{}L=null,Q||Y({event:"sidecar_disabled",reason:"size_limit",...H===null?{}:{path:S(H)},max_bytes:Qe},`${S(`[allscale] sidecar exceeded ${Qe} bytes; disabling it for the rest of this run. Rotate or remove ${H}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
6
|
`);return}h.appendFileSync(L,`${n}
|
|
7
|
-
`)}catch(r){if(W=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{
|
|
8
|
-
`)}catch{}}}var v=
|
|
9
|
-
The CLI default is now ${
|
|
7
|
+
`)}catch(r){if(W=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{Q||Y({event:"sidecar_disabled",reason:"write_failed",detail:S(r.message)},`${S(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var v=Xt;function Zt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function ee(){if(Q=!1,W=!1,L!==null){try{h.closeSync(L)}catch{}L=null}}function Qt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Zt()||!t}var te=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"]),Xr=new Set(Array.from(te).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Zr=Array.from(te).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Qr=new Set(["--otp-stdin","--password-stdin"]);function tt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(te.has(s)){t.push(`${s}=<redacted>`);continue}}}if(te.has(r)){t.push(r),n+1<e.length&&(te.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(Xr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Qr.has(r)?void 0:Zr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function en(e){w({type:"error",code:e.code,message:S(e.message)}),w({type:"command-end",ok:!1,exitCode:e.exitCode}),ee()}var ne=V()??Bt,J={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function P(e){return Ut(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function tn(){let e=process.env[J.TOKEN]?.trim();return e&&e.length>0?e:void 0}function nt(){let e=process.env[J.PROFILE]?.trim();return e&&e.length>0?e:void 0}function re(){let e=process.env[J.API_BASE]?.trim();return e&&e.length>0?e:void 0}function nn(){let e=process.env[J.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function rn(){let e=process.env[J.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function on(){let e=process.env[J.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function sn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(V()===void 0&&ne!==""&&"".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 ${ne} (production), but a saved profile wins over the default,
|
|
10
10
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
11
11
|
the old default rather than a deliberate choice.
|
|
12
12
|
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
|
-
To move to production, run: allscale device-login --api-base ${
|
|
14
|
-
`}var B=A(require("fs")),
|
|
15
|
-
`)}};var ci=/_(removed|cleared|count|total)$/i;function ui(e,t){return typeof t=="number"&&ci.test(e)}var di=new Set(cn);function fi(e,t){return e==="token_symbol"&&typeof t=="string"&&di.has(t)}var pi=new Set(hn);function hi(e,t){return e==="otp_reason"&&typeof t=="string"&&pi.has(t)}var we=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,we),r=n.map(i=>be(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,we))n[i]=fe(i)&&!ui(i,o)&&!fi(i,o)&&!hi(i,o)?"<redacted>":be(o,t+1);if(r.length>we){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-we} more keys`}return n}if(typeof e=="string"){let n=gi(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function gi(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 mi(e){let t=jt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function _i(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))}var gn=/^0x[0-9a-fA-F]{64}$/;var On=A(require("path"));var at=require("crypto"),a=A(require("fs")),y=A(require("path"));var Ee=1024*1024,yi=5e3,wi=20,bi=3e4,ot=4096,Ei=new Int32Array(new SharedArrayBuffer(4)),ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Se(e){return e instanceof ie}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Si=null;function U(){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 Ae(){return(Si??process.platform)!=="win32"}function An(){if(!Ae())throw U()}function kn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!_(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(y.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(_(t,"ENOENT"))return!0;throw t}}function _(e,t){return typeof e=="object"&&e!==null&&e.code===t}function oe(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function se(e,t){return e.dev===t.dev&&e.ino===t.ino}function Ai(e){Atomics.wait(Ei,0,0,e)}function Ln(e){try{return process.kill(e,0),!0}catch(t){return!_(t,"ESRCH")}}function ki(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mn(e,t){let n=y.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&_(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!se(o,s))throw new Error("credential-store parent changed while it was being inspected");oe(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&y.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 O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&_(o,"ENOENT")?new k:o}if(!se(n,i))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new ie;if(oe(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function Li(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function _n(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(_(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(_(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return Li(t,r)}finally{t!==null&&a.default.closeSync(t)}}function yn(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(_(i,"ENOENT")&&kn(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);F(e,r)}finally{t!==null&&a.default.closeSync(t)}In(y.dirname(e))}function Ti(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(_(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new ie;oe(t,"credential-store replacement target")}function Ii(e,t){for(let n=0;n<8;n+=1){let r=(0,at.randomBytes)(12).toString("hex"),i=y.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(_(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Tn(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 In(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 Oi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=y.dirname(e),i=y.basename(e),o=null,s=null,c=!1;try{let u=Ii(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Tn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Ti(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{}}In(r)}function Ci(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock`)}function vi(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock-recovery`)}function Ri(e,t){if(t.size>ot)return null;let n=Buffer.alloc(ot+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>ot)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 F(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");oe(n,"credential-store lock"),a.default.unlinkSync(e)}function wn(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(_(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 k}catch(d){if(_(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Ri(n,i);return{state:(o?.target===t&&o?!Ln(o.pid):Date.now()-i.mtimeMs>=bi)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function Ni(e,t){for(let n=0;n<8;n+=1){let r=(0,at.randomBytes)(12).toString("hex"),i=y.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=O(i,s,c,{allowMultipleLinks:!0});return Tn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(_(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 xi(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 _(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function bn(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(_(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(_(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Pi(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(_(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{F(e,n)}catch{}throw a.default.closeSync(t),r}}function D(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");Ai(wi)}function En(e){let t=y.dirname(e),n=y.basename(e),r=Ci(e),i=vi(e),o=Ni(t,n),s=Date.now()+yi,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(bn(i)){D(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=xi(r,o.stats),c=!0}catch(p){if(u&&!c){try{F(r,o.stats)}catch{}u=!1}if(p instanceof k){D(s,!1);continue}if(!_(p,"EEXIST"))throw p;let b;try{b=wn(r,n)}catch(m){if(m instanceof k){D(s,!1);continue}throw m}if(b.state==="absent")continue;if(b.state==="stale"){let m;try{m=Pi(i)}catch(E){if(E instanceof k){D(s,!1);continue}throw E}if(m!==null){try{let E;try{E=wn(r,n)}catch(N){if(N instanceof k){D(s,!1);continue}throw N}E.state==="stale"&&F(r,E.stats)}finally{st(m)}continue}}let g;try{g=bn(i)}catch(m){if(m instanceof k){D(s,!1);continue}throw m}D(s,g)}}catch(p){f=p}try{F(o.claimPath,o.stats)}catch(p){!_(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function st(e){try{F(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Bi(e,t){let n=ki(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 Sn(e){let t=y.dirname(e),n=y.basename(e);for(let r of a.default.readdirSync(t)){let i=Bi(r,n);if(i===null||Ln(i))continue;let o=y.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(_(d,"ENOENT")||_(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!se(c,u))continue;try{oe(c,"credential-store orphan")}catch{continue}F(o,c)}catch(c){if(!_(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!Ae()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw U();if(!mn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw U()}});let s=En(e);try{return Sn(e),n({read:()=>_n(e),remove:()=>yn(e),write:()=>{throw U()}})}finally{st(s)}}if(!t.createParent){let o=!1;try{o=kn(e)}catch{throw U()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw U()}})}throw U()}if(!mn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=En(e);try{return Sn(e),n({read:()=>_n(e),remove:()=>yn(e),write:o=>Oi(e,o)})}finally{st(i)}}var lt="allscale-cli";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cn(e){return ft(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(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 ct(){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 ke(){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 M,ut=!1;function $i(){return Qt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Di(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
|
|
16
|
-
`,1)[0]==="Cannot find module 'keytar'"}function Ui(){if(M!==void 0)return M;if($i())return ut=!1,M=null,M;try{M=require("keytar"),ut=!1}catch(e){ut=!Di(e),M=null}return M}var Fi="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function vn(){let e=Ae()?"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",`${Fi} `+e+" Never silently downgrade in production.")}async function dt(e){try{return await e()}catch{throw vn()}}var pt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await dt(()=>this.keytar.getPassword(lt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!Cn(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await dt(()=>this.keytar.setPassword(lt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await dt(()=>this.keytar.deletePassword(lt,t))}},Mi="credentials.json",ht=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??On.join(rt(),Mi)}read(t){let n;try{n=t.read()}catch(i){throw Se(i)?ct():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!ft(r)||!ft(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Se(r)?ct():ke()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Cn(r))throw G("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:G("plaintext file")}}async set(t,n){try{ae(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof l?r:ke()}}async delete(t){try{ae(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:ke()}}async clearProfile(t){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Se(n)?ct():ke()}}};function Rn(e){if(e.insecureStorage)return An(),new ht(e.insecureFilePath);let t=Ui();if(t)return new pt(t);throw vn()}var gt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Le(){return new gt}var Te="allscale_access_token",mt="allscale_refresh_token";function Nn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function _t(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function yt(e,t){return e.find(n=>n.name===t)?.value??null}var xn=A(require("crypto")),Pn=A(require("fs")),Bn=A(require("path"));var Gi="key-id",Ki="x-allscale-cli-version",wt="cli-1",qi="aScaLe_cli_obf_v1",ji="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Yi(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var Hi=Yi(ji,qi),$n=`Bearer ${Hi}`;function Dn(e,t){let n=Ue(e);if(n!==null)return t.find(r=>Ue(r.base)===n)}function Wi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=Dn(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function zi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?Dn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():wt}if(!x(t[0].base))return wt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():wt}function Ji(){return"1.0.4"}function Vi(){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 bt(e,t){let n=Wi(t);if(!n)throw Vi();let r=zi(t),i=Math.floor(Date.now()/1e3).toString(),o=xn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Ki]:Ji()};return r.length>0&&(s[Gi]=r),s}function Un(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Xi(e,t={}){let n;try{n=rn(me())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Dt(e)+(t.messageSuffix??""),{profile:e})}function Fn(e){if(e.profileExplicit){let t=Xi(e.profile);if(t)return t}return new l("auth.no_token",$t(e.profile))}var Zi=500,Qi=8,Mn=100;function Et(e,t=0){if(t>Qi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Mn),r=n.map(i=>Et(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,Mn))n[r]=fe(r)?"<redacted>":Et(i,t+1);return n}return e}function eo(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 Gn(e,t=Zi){let n=eo(e),r=n===void 0?de(e):JSON.stringify(Et(n));return pe(r,t)}var St=256*1024,Ie=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"}},Oe=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 At(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 Ie(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,b)=>{u=setTimeout(()=>{b(new Oe(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:b,value:g}=f?await Promise.race([p,f]):await p;if(b)break;if(c+=g.byteLength,c>t)throw o.cancel().catch(()=>{}),new Ie(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Oe&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var to="X-AllScale-Api-Key",no=3e4,ro=32*1024*1024,io=4*1024*1024;function oo(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function so(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function ao(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${v(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 Hn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ao(e.status,e.url)}}var Kn="--dns-result-order=ipv4first";async function Ce(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Kn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${Kn}`})}var K=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??no;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),ye(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=oo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new l("transport.timeout",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();an(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=Wn(t.path),u=s==="required"?!0:s==="none"?!1:uo(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw Fn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Un(t.body),f=!!o||!!r?.access_token;u&&f&&!this.opts.override&&_e(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),b=Date.now();w({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(E){throw new l("transport.network",`Network error contacting ${v(i)}: ${E instanceof Error?E.message:String(E)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-b}),u&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let E=await so(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!E.access_token,bodyForSig:d,tokens:E,extra:t.headers}),lr=Date.now();w({type:"request",method:t.method??"GET",url:i});let Ne;try{Ne=await fetch(i,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(xe){throw new l("transport.network",`Network error contacting ${v(i)} on refresh-retry: ${xe instanceof Error?xe.message:String(xe)}`)}return w({type:"response",status:Ne.status,durationMs:Date.now()-lr}),qn(Ne,{withMetadata:n.withMetadata,authBearing:u,responseKind:jn(t)})}return qn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!o,responseKind:jn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...bt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=$n;let i=t.tokens;if(i?.agent_key)return r[to]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=_t([{name:Te,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(_e(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${ue()}.`);if(_e(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=_t([{name:Te,value:t.access_token},{name:mt,value:t.refresh_token}]),i=bt("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(g){throw w({type:"refresh",ok:!1}),new l("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${v(n)} timed out after 10s with no response.`:`Network error during token refresh against ${v(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}w({type:"response",status:u.status,durationMs:0});try{await Hn(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await Ce(u);let m=await mo(u);await Ce(u,m),Jn(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ue()}.`,{status:u.status})}let d=Nn(u.headers),f=yt(d,Te),p=yt(d,mt);if(!f||!p)throw w({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let b={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,b),w({type:"refresh",ok:!0}),b}},lo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Wn(e){let t=e.split(/[?#]/,1)[0];return lo.some(n=>t===n||t.startsWith(`${n}/`))}var co=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function kt(e){let t=e.split(/[?#]/,1)[0];return co.some(n=>n.test(t))}function uo(e){return Wn(e)||kt(e)}async function qn(e,t={}){await Hn(e);let n=e.status>=200&&e.status<300;n||await Ce(e);let r=t.responseKind??"mutation",o=await At(e,n?r==="query"?ro:io:St,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ce(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=_o(s)??`HTTP ${e.status}`;if(Jn(e.status,s),ho(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function jn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var fo=2014,Yn=2004;function zn(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function po(e){return zn(e,fo)}function ho(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&zn(t,Yn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ue()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Yn})}var go=1e4;async function mo(e,t=go){if(e.status>=200&&e.status<300)return"";try{return await At(e,St,{timeoutMs:t})}catch{return""}}function Jn(e,t){if(!(e>=200&&e<300)&&po(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"?Gn(t):t})}function _o(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var yo=/^\/(api\/)?(v1\/)?public\//;function Lt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&yo.test(n),i=n&&kt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new K({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new K({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new K({apiBase:e.apiBase,tokenStore:Rn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new K({apiBase:e.apiBase,tokenStore:Le(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var wo=new Set;var bo=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"]),Vn=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"]),Xn=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Tt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var Eo=new Set(["cli_op:all"]),So=new Set([...Eo].map(Tt));var wa=new Set([...[...bo,...Vn,...wo].map(Tt),...Xn,...So]);var le=8100,Ao=new Set([le]),xa=new Set([...Ao,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Zn="/api/v1/public/claim-links";var ko=1e4,Lo="No Claim Link matches this claim token. The token did reach the backend \u2014 an empty or malformed one is refused locally, before anything is sent \u2014 and the public receiver endpoint answers the same way for every token that resolves to nothing, so it will not confirm whether a token exists. Re-check the claim link or URL you were given. An expired or already-claimed link is NOT this error: it still resolves, and comes back as a status snapshot or a 200 claim outcome.";function To(e){let t=e?.body;if(!t||typeof t!="object")return;let n=t.code;if(typeof n=="number")return n;if(typeof n=="string"&&/^[0-9]+$/.test(n))return Number(n)}function Qn(e){throw e instanceof l&&e.code==="not_found"&&To(e.details)===le?new l("not_found",Lo,{status:404,backend_code:le}):e}function er(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Zn}/${n}:claim`:`${Zn}/${n}`}function ve(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let i=t.trim();if(!i)throw new l("input.invalid","--claim-token is empty.");return It(i,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return It(Io(r),"--claim-url")}async function tr(e,t,n=ko){let r=e["claim-url"]?.trim();if(!r)return ve(e);let i;try{i=new URL(r)}catch{return ve(e)}let o=/^\/s\/([^/]+)\/?$/.exec(i.pathname);if(!o||e["claim-token"]!==void 0)return ve(e);R(t);let s=new URL(t).origin;if(i.origin!==s||i.username||i.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(o[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let b;try{b=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=b.headers.get("location");try{b.body?.cancel().catch(()=>{})}catch{}if(b.status!==302||!g)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:b.status});let m;try{m=new URL(g,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let E=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!E)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(E[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return It(N,"--claim-url")}function It(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function Io(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),i=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],o=i.endsWith(":claim")?i.slice(0,-6):i;try{return decodeURIComponent(o)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function nr(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function rr(e,t=""){let n=C()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var Oo=["claimed","not_claimable","expired","payout_pending","payout_failed"],Co=64,vo=128,Ro=/^[a-z][a-z0-9_]*$/,No=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function ir(e){return typeof e=="string"&&e.length>0&&e.length<=Co&&Ro.test(e)}function or(e){return typeof e=="string"&&e.length>0&&e.length<=vo&&No.test(e)}function sr(e){return typeof e=="string"&&gn.test(e)}function xo(e){let t={outcome_ambiguous:!0};if(typeof e!="object"||e===null)return t;let n=e;return ir(n.outcome)&&(t.outcome=n.outcome),or(n.claim_link_id)&&(t.claim_link_id=n.claim_link_id),n.claim_tx_hash===null?t.claim_tx_hash=null:sr(n.claim_tx_hash)&&(t.claim_tx_hash=n.claim_tx_hash),t}function Po(e){if(typeof e!="object"||e===null)return!1;let t=e;return ir(t.outcome)&&Oo.includes(t.outcome)&&or(t.claim_link_id)&&(t.claim_tx_hash===void 0||t.claim_tx_hash===null||sr(t.claim_tx_hash))}function ar(e){if(!Po(e))throw new l("backend.internal","Claim endpoint returned an invalid result; the claim outcome is unknown. Inspect the Claim Link before retrying.",xo(e));if(e.outcome==="claimed")return e;let t={outcome:e.outcome,claim_link_id:e.claim_link_id,claim_tx_hash:e.claim_tx_hash??null};throw e.outcome==="payout_pending"||e.outcome==="payout_failed"?new l("claim.payout_ambiguous",`Claim payout is ${e.outcome==="payout_pending"?"still pending":"not proven successful"}. Do not submit another claim; reconcile this Claim Link first.`,{...t,outcome_ambiguous:!0}):new l(e.outcome==="expired"?"claim.expired":"claim.not_claimable",e.outcome==="expired"?"Claim did not complete because this Claim Link has expired.":"Claim did not complete because this Claim Link is not claimable in its current state. Inspect its status before deciding whether to retry.",t)}var Re=class e extends re{static description="Claim a Claim Link. Path-A claims (no AllScale account sign-in) require --to; authenticated business receivers can use --to-wallet. Only an on-chain-proven claimed outcome exits 0.";static examples=[`$ allscale claim-link claim --claim-token claim-token-from-share-link --to ${it}`,"$ allscale claim-link claim --claim-url https://app.allscale.io/claim/claim-token-from-share-link --to-wallet"];static usage=rr("claim"," (--to <value> | --to-wallet)");static requiresInput=!0;static flags={"claim-token":$.Flags.string({helpGroup:"REQUIRED SOURCE (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":$.Flags.string({helpGroup:"REQUIRED SOURCE (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),to:$.Flags.string({helpGroup:"REQUIRED DESTINATION (ONE OF)",description:"Receiver EVM address for Path-A claims (no AllScale account sign-in). This does not make the transaction anonymous: network, request, compliance, and public blockchain data may still be processed or observable.",exclusive:["to-wallet"]}),"to-wallet":$.Flags.boolean({helpGroup:"REQUIRED DESTINATION (ONE OF)",description:"Claim into the authenticated receiver business's AllScale wallet for the link's chain. Requires login/token.",default:!1,exclusive:["to"]}),...re.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await tr(t,n.apiBase),i=er(r,"claim"),o,s;if(t["to-wallet"])o={},s="required";else{let d=t.to?.trim();if(!d)throw new l("input.invalid","Pass --to <0x address> or --to-wallet.");if(!un(d))throw new l("input.invalid",`--to is not a valid EVM address: '${d}' (expected 0x followed by 40 hex characters).`);if(fn(d))throw new l("input.invalid","--to must not be the zero or burn address; funds claimed to it cannot be recovered.");dn(d),o={receiver_address:d},s="none"}let u=await Lt(n,{pathHint:i,forceAuth:s==="required"}).request({method:"POST",path:i,body:o,auth:s}).catch(Qn);return ar(nr(u))}};0&&(module.exports={requireSuccessfulClaim});
|
|
13
|
+
To move to production, run: allscale device-login --api-base ${ne}
|
|
14
|
+
`}var B=A(require("fs")),an=A(require("os")),rt=A(require("path")),it=A(require("@iarna/toml"));var ni=".allscale",ri="config.toml";function ot(){return rt.join(an.homedir(),ni)}function ii(){return rt.join(ot(),ri)}function _e(){let e=ii();if(!B.existsSync(e))return{};let t=B.readFileSync(e,"utf-8");try{return it.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function ln(e){return Object.keys(e.profile??{}).sort()}function cn(e,t){return e.profile?.[t]}function un(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function R(e){if(!Ue(e))throw new a("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+De)}function ye(e,t){R(e);let n=P(e),r=typeof t=="string"?P(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function dn(e,t){let n=P(e),r=P(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function we(e){let t=si(e);if(t)throw new a("input.invalid",t.message)}function oi(){let e=V();if(e===void 0)return;let t=X();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function si(e){let t=oi();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,i=P(e),o=n.map(c=>P(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var fn=require("@noble/hashes/sha3");var pn=["USDT","USDC"];function hn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,fn.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let i=0;i<t.length;i+=1){let o=t[i];if(!/[a-fA-F]/.test(o))continue;let s=Number.parseInt(r[i],16)>=8;if(s&&o!==o.toUpperCase()||!s&&o!==o.toLowerCase())return!1}return!0}var st="0x1234567890abcdef1234567890abcdef12345678";function ai(e){return e.toLowerCase()===st}function gn(e,t="--to"){if(ai(e))throw new a("input.invalid",`${t} is the documentation example address; pass a destination address you control.`)}var li=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function mn(e){return li.has(e.toLowerCase())}var ci="unknown_otp_id",ui="invalid_code",di="expired_code";function fi(e){return`'${e.replace(/'/g,"'\\''")}'`}function _n(e){return`Run \`allscale otp-send --email ${fi(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var pi=new Map([[ci,(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. ${_n(t)}`],[ui,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.`],[di,(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. ${_n(t)}`]]);var yn=[...pi.keys()];var $=require("@oclif/core"),ie=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:C()==="public"}),"api-base":I.Flags.string({description:$e,helpGroup:"GLOBAL",hidden:C()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Ze(this.jsonEnabled()),et(),w({type:"session-start",command:this.id??"",argv:tt(this.argv)});let t=this.constructor;if(C()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("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 a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&re()!==void 0)throw new a("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=Qt(this.jsonEnabled()),r=this.argv.length===0&&!n&&Si(t)?this.config.findCommand(this.id??""):void 0;if(r){ee();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&&!on())throw this.argv.length>0&&await this.parse(),new a("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 w({type:"command-end",ok:!0}),ee(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||qt(i),{data:i})}catch(t){let n=Kt(t);en({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Ze(!1)}}resolveSessionApiBaseChain(t){let n=_e(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||nt()!==void 0,s=un(n,r,nt()),c=cn(n,s),u=C()==="public"&&re()!==void 0,d=i??(u?void 0:re()),f=d??c?.api_base??ne,p=sn({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,Y({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||R(n),n}resolveContext(t){if(C()==="public"){if(t.token!==void 0)throw new a("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 a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&re()!==void 0)throw new a("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:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(R(i),we(i)),{apiBase:i,profile:c,token:n??tn(),insecureStorage:r||nn(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${bi(t)}
|
|
15
|
+
`)}};var hi=/_(removed|cleared|count|total)$/i;function gi(e,t){return typeof t=="number"&&hi.test(e)}var mi=new Set(pn);function _i(e,t){return e==="token_symbol"&&typeof t=="string"&&mi.has(t)}var yi=new Set(yn);function wi(e,t){return e==="otp_reason"&&typeof t=="string"&&yi.has(t)}var Ee=100;function be(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ee),r=n.map(i=>be(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Ee))n[i]=pe(i)&&!gi(i,o)&&!_i(i,o)&&!wi(i,o)?"<redacted>":be(o,t+1);if(r.length>Ee){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ee} more keys`}return n}if(typeof e=="string"){let n=Ei(e);return n!==void 0?S(JSON.stringify(be(n,t+1))):S(e)}return e}function Ei(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function bi(e){let t=zt()?void 0:2,n=be(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:S(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Si(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))}var wn=/^0x[0-9a-fA-F]{64}$/;var Nn=A(require("path"));var ct=require("crypto"),l=A(require("fs")),y=A(require("path"));var Se=1024*1024,Ai=5e3,ki=20,Li=3e4,at=4096,Ti=new Int32Array(new SharedArrayBuffer(4)),oe=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ae(e){return e instanceof oe}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ii=null;function U(){return new a("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function ke(){return(Ii??process.platform)!=="win32"}function In(){if(!ke())throw U()}function On(e){try{return l.default.lstatSync(e),!1}catch(t){if(!_(t,"ENOENT"))throw t}try{let t=l.default.lstatSync(y.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(_(t,"ENOENT"))return!0;throw t}}function _(e,t){return typeof e=="object"&&e!==null&&e.code===t}function se(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ae(e,t){return e.dev===t.dev&&e.ino===t.ino}function Oi(e){Atomics.wait(Ti,0,0,e)}function Cn(e){try{return process.kill(e,0),!0}catch(t){return!_(t,"ESRCH")}}function Ci(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function En(e,t){let n=y.dirname(e);t&&l.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=l.default.lstatSync(n)}catch(o){if(!t&&_(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=l.default.openSync(n,l.default.constants.O_RDONLY|(l.default.constants.O_DIRECTORY??0)|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0));let o=l.default.fstatSync(i),s=l.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!ae(o,s))throw new Error("credential-store parent changed while it was being inspected");se(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&y.basename(n)===".allscale"&&(l.default.fchmodSync(i,448),c=l.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&l.default.closeSync(i)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=l.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&_(o,"ENOENT")?new k:o}if(!ae(n,i))throw r.retryOnPathChange?new k:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new oe;if(se(n,"credential-store file"),process.platform!=="win32"){l.default.fchmodSync(t,384);let o=l.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 vi(e,t){if(t.size>Se)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Se+1),r=0;for(;r<n.length;){let i=l.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Se)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function bn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(i){if(_(i,"ENOENT"))try{if(l.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(_(o,"ENOENT"))return null;throw o}throw i}let n=l.default.fstatSync(t),r=O(e,t,n);return vi(t,r)}finally{t!==null&&l.default.closeSync(t)}}function Sn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(i){if(_(i,"ENOENT")&&On(e))return;throw i}let n=l.default.fstatSync(t),r=O(e,t,n);F(e,r)}finally{t!==null&&l.default.closeSync(t)}Rn(y.dirname(e))}function Ri(e){let t;try{t=l.default.lstatSync(e)}catch(n){if(_(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new oe;se(t,"credential-store replacement target")}function Ni(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.randomBytes)(12).toString("hex"),i=y.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:l.default.openSync(i,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_WRONLY|(l.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(_(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function vn(e,t){let n=0;for(;n<t.length;){let r=l.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 Rn(e){if(process.platform==="win32")return;let t=null;try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_DIRECTORY??0)|(l.default.constants.O_NOFOLLOW??0)),l.default.fsyncSync(t)}catch{}finally{if(t!==null)try{l.default.closeSync(t)}catch{}}}function xi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Se)throw new Error("credential-store file exceeds the maximum supported size");let r=y.dirname(e),i=y.basename(e),o=null,s=null,c=!1;try{let u=Ni(r,i);o=u.fd,s=u.tempPath;let d=l.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");vn(o,n),l.default.fsyncSync(o),O(s,o,l.default.fstatSync(o));let p=o;o=null,l.default.closeSync(p),Ri(e),l.default.renameSync(s,e),c=!0}finally{if(o!==null)try{l.default.closeSync(o)}catch{}if(!c&&s!==null)try{l.default.unlinkSync(s)}catch{}}Rn(r)}function Pi(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock`)}function Bi(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock-recovery`)}function $i(e,t){if(t.size>at)return null;let n=Buffer.alloc(at+1),r=0;for(;r<n.length;){let o=l.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>at)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function F(e,t){let n=l.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ae(n,t))throw new Error("credential-store lock changed while it was being inspected");se(n,"credential-store lock"),l.default.unlinkSync(e)}function An(e,t){let n=null;try{try{n=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(u){if(_(u,"ENOENT"))try{let d=l.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(_(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=l.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=$i(n,i);return{state:(o?.target===t&&o?!Cn(o.pid):Date.now()-i.mtimeMs>=Li)?"stale":"active",stats:i}}finally{n!==null&&l.default.closeSync(n)}}function Di(e,t){for(let n=0;n<8;n+=1){let r=(0,ct.randomBytes)(12).toString("hex"),i=y.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=l.default.openSync(i,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_WRONLY|(l.default.constants.O_NOFOLLOW??0),384);let c=l.default.fstatSync(s),u=O(i,s,c,{allowMultipleLinks:!0});return vn(s,Buffer.from(JSON.stringify(o),"utf8")),l.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(_(c,"EEXIST"))continue;try{l.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&l.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ui(e,t){let n;try{n=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(r){throw _(r,"ENOENT")?new k:r}try{let r=l.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ae(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw l.default.closeSync(n),r}}function kn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(n){if(_(n,"ENOENT"))try{let r=l.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(_(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,l.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&l.default.closeSync(t)}}function Fi(e){let t;try{t=l.default.openSync(e,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_RDWR|(l.default.constants.O_NOFOLLOW??0),384)}catch(r){if(_(r,"EEXIST"))return null;throw r}let n=null;try{n=l.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{F(e,n)}catch{}throw l.default.closeSync(t),r}}function D(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");Oi(ki)}function Ln(e){let t=y.dirname(e),n=y.basename(e),r=Pi(e),i=Bi(e),o=Di(t,n),s=Date.now()+Ai,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(kn(i)){D(s,!0);continue}l.default.linkSync(o.claimPath,r),u=!0,d=Ui(r,o.stats),c=!0}catch(p){if(u&&!c){try{F(r,o.stats)}catch{}u=!1}if(p instanceof k){D(s,!1);continue}if(!_(p,"EEXIST"))throw p;let E;try{E=An(r,n)}catch(m){if(m instanceof k){D(s,!1);continue}throw m}if(E.state==="absent")continue;if(E.state==="stale"){let m;try{m=Fi(i)}catch(b){if(b instanceof k){D(s,!1);continue}throw b}if(m!==null){try{let b;try{b=An(r,n)}catch(N){if(N instanceof k){D(s,!1);continue}throw N}b.state==="stale"&&F(r,b.stats)}finally{lt(m)}continue}}let g;try{g=kn(i)}catch(m){if(m instanceof k){D(s,!1);continue}throw m}D(s,g)}}catch(p){f=p}try{F(o.claimPath,o.stats)}catch(p){!_(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function lt(e){try{F(e.lockPath,e.stats)}finally{l.default.closeSync(e.fd)}}function Mi(e,t){let n=Ci(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 Tn(e){let t=y.dirname(e),n=y.basename(e);for(let r of l.default.readdirSync(t)){let i=Mi(r,n);if(i===null||Cn(i))continue;let o=y.join(t,r),s=null;try{try{s=l.default.openSync(o,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(d){if(_(d,"ENOENT")||_(d,"ELOOP"))continue;throw d}let c=l.default.fstatSync(s),u=l.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!ae(c,u))continue;try{se(c,"credential-store orphan")}catch{continue}F(o,c)}catch(c){if(!_(c,"ENOENT"))throw c}finally{s!==null&&l.default.closeSync(s)}}}function le(e,t,n){if(!ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw U();if(!En(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw U()}});let s=Ln(e);try{return Tn(e),n({read:()=>bn(e),remove:()=>Sn(e),write:()=>{throw U()}})}finally{lt(s)}}if(!t.createParent){let o=!1;try{o=On(e)}catch{throw U()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw U()}})}throw U()}if(!En(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Ln(e);try{return Tn(e),n({read:()=>bn(e),remove:()=>Sn(e),write:o=>xi(e,o)})}finally{lt(i)}}var ut="allscale-cli";function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e){return ht(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(e){return new a("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 dt(){return new a("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Le(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var M,ft=!1;function Gi(){return rn()?"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 qi(){if(M!==void 0)return M;if(Gi())return ft=!1,M=null,M;try{M=require("keytar"),ft=!1}catch(e){ft=!Ki(e),M=null}return M}var ji="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Pn(){let e=ke()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new a("storage.unavailable",`${ji} `+e+" Never silently downgrade in production.")}async function pt(e){try{return await e()}catch{throw Pn()}}var gt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await pt(()=>this.keytar.getPassword(ut,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!xn(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await pt(()=>this.keytar.setPassword(ut,t,JSON.stringify(n)))}async delete(t){await this.read(t),await pt(()=>this.keytar.deletePassword(ut,t))}},Yi="credentials.json",mt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Nn.join(ot(),Yi)}read(t){let n;try{n=t.read()}catch(i){throw Ae(i)?dt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!ht(r)||!ht(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ae(r)?dt():Le()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!xn(r))throw G("plaintext file");return r}}async get(t){try{return le(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:G("plaintext file")}}async set(t,n){try{le(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 a?r:Le()}}async delete(t){try{le(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 a?n:Le()}}async clearProfile(t){try{return le(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 a?n:Ae(n)?dt():Le()}}};function Bn(e){if(e.insecureStorage)return In(),new mt(e.insecureFilePath);let t=qi();if(t)return new gt(t);throw Pn()}var _t=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Te(){return new _t}var Ie="allscale_access_token",yt="allscale_refresh_token";function $n(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function wt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Et(e,t){return e.find(n=>n.name===t)?.value??null}var Dn=A(require("crypto")),Un=A(require("fs")),Fn=A(require("path"));var Hi="key-id",Wi="x-allscale-cli-version",bt="cli-1",zi="aScaLe_cli_obf_v1",Ji="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Vi(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 Xi=Vi(Ji,zi),Mn=`Bearer ${Xi}`;function Gn(e,t){let n=Me(e);if(n!==null)return t.find(r=>Me(r.base)===n)}function Zi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=Gn(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Qi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?Gn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():bt}if(!x(t[0].base))return bt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():bt}function eo(){return"1.0.5"}function to(){return new a("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 St(e,t){let n=Zi(t);if(!n)throw to();let r=Qi(t),i=Math.floor(Date.now()/1e3).toString(),o=Dn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Wi]:eo()};return r.length>0&&(s[Hi]=r),s}function Kn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function no(e,t={}){let n;try{n=ln(_e())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",Gt(e)+(t.messageSuffix??""),{profile:e})}function qn(e){if(e.profileExplicit){let t=no(e.profile);if(t)return t}return new a("auth.no_token",Mt(e.profile))}var ro=new Set;var io=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"]),At=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"]),kt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Oe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function jn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var oo=new Set(["cli_op:all"]),so=new Set([...oo].map(Oe));var ua=new Set([...[...io,...At,...ro].map(Oe),...kt,...so]);var ao=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,lo=/is not available to API keys/i,Yn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Hn(e){if(typeof e!="string")return;let t=ao.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=lo.test(n),o=!i&&Yn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(u=>u.trim()).filter(u=>Yn.test(u));s=c.length>0?c:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Wn(e){if(kt.has(Oe(e)))return{kind:"ungrantable"};for(let t of At)if(jn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Lt(e,t,n,r){let i=Hn(e),o=i?.notAvailableToKeys===!0,s=i?.required??r?.scope,c=i?.granted,u=c===void 0?"":` This key holds ${c.length>0?c.join(", "):"no scopes"}.`;if(o||r?.ungrantableReason!==void 0){let d=r?.ungrantableReason!==void 0?`: ${r.ungrantableReason}`:"";return new a("auth.permission_denied",`${t} is not available to agent keys${d}. Re-authorizing will NOT help \u2014 no scope grants it.${u} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...n,missing_scopes:[],...c===void 0?{}:{granted_scopes:c},ungrantable:!0})}if(s!==void 0){let d=Wn(s),f=d.kind==="ungrantable"?`\`${s}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:d.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${Z()}\` with \`--scopes ${s}\`.`:`The browser approval screen does not offer \`${s}\`, so \`device-login\` cannot grant it \u2014 use \`${Z()}\` with \`--scopes ${s}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${s}\`, required by ${t}.${u} ${f}`,{...n,missing_scopes:[s],...c===void 0?{}:{granted_scopes:c},...d.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${t}.${u} Re-run \`allscale device-login\` (or \`${Z()}\`) and grant the required scope.`,n)}var co=500,uo=8,zn=100;function Tt(e,t=0){if(t>uo)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,zn),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);for(let[r,i]of Object.entries(e).slice(0,zn))n[r]=pe(r)?"<redacted>":Tt(i,t+1);return n}return e}function fo(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 Jn(e,t=co){let n=fo(e),r=n===void 0?fe(e):JSON.stringify(Tt(n));return he(r,t)}var It=256*1024,Ce=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},ve=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function Ot(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,E)=>{u=setTimeout(()=>{E(new ve(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:E,value:g}=f?await Promise.race([p,f]):await p;if(E)break;if(c+=g.byteLength,c>t)throw o.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof ve&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var po="X-AllScale-Api-Key",ho=3e4,go=32*1024*1024,mo=4*1024*1024;function _o(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function yo(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function wo(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${v(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 er(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}wo(e.status,e.url)}}var Vn="--dns-result-order=ipv4first";async function Re(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new a("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Vn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${Vn}`})}var K=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??ho;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),we(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=_o(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new a("transport.timeout",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();dn(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=tr(t.path),u=s==="required"?!0:s==="none"?!1:So(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw qn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Kn(t.body),f=!!o||!!r?.access_token;u&&f&&!this.opts.override&&ye(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),E=Date.now();w({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(b){throw new a("transport.network",`Network error contacting ${v(i)}: ${b instanceof Error?b.message:String(b)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-E}),u&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let b=await yo(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!b.access_token,bodyForSig:d,tokens:b,extra:t.headers}),pr=Date.now();w({type:"request",method:t.method??"GET",url:i});let Pe;try{Pe=await fetch(i,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Be){throw new a("transport.network",`Network error contacting ${v(i)} on refresh-retry: ${Be instanceof Error?Be.message:String(Be)}`)}return w({type:"response",status:Pe.status,durationMs:Date.now()-pr}),Xn(Pe,{withMetadata:n.withMetadata,authBearing:u,responseKind:Zn(t)})}return Xn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!o,responseKind:Zn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...St(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Mn;let i=t.tokens;if(i?.agent_key)return r[po]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=wt([{name:Ie,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(ye(this.opts.apiBase,n.api_base),n.agent_key)throw new a("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new a("auth.token_expired",`No refresh token available; log in again \u2014 ${de()}.`);if(ye(this.opts.apiBase,t.api_base),t.agent_key)throw new a("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=wt([{name:Ie,value:t.access_token},{name:yt,value:t.refresh_token}]),i=St("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(g){throw w({type:"refresh",ok:!1}),new a("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${v(n)} timed out after 10s with no response.`:`Network error during token refresh against ${v(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}w({type:"response",status:u.status,durationMs:0});try{await er(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await Re(u);let m=await Io(u);await Re(u,m),nr(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${de()}.`,{status:u.status})}let d=$n(u.headers),f=Et(d,Ie),p=Et(d,yt);if(!f||!p)throw w({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let E={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,E),w({type:"refresh",ok:!0}),E}},Eo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function tr(e){let t=e.split(/[?#]/,1)[0];return Eo.some(n=>t===n||t.startsWith(`${n}/`))}var bo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Ct(e){let t=e.split(/[?#]/,1)[0];return bo.some(n=>n.test(t))}function So(e){return tr(e)||Ct(e)}async function Xn(e,t={}){await er(e);let n=e.status>=200&&e.status<300;n||await Re(e);let r=t.responseKind??"mutation",o=await Ot(e,n?r==="query"?go:mo:It,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Re(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=Oo(s)??`HTTP ${e.status}`;if(nr(e.status,s),Lo(e.status,s,t),vt(s,2102))throw Lt(s.errors,"this API request",{status:e.status,backend_code:2102});if(e.status===401){if(t.agentKeyAuth)throw new a("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new a(u,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function Zn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Ao=2014,Qn=2004;function vt(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 ko(e){return vt(e,Ao)}function Lo(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&vt(t,Qn))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${de()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Qn})}var To=1e4;async function Io(e,t=To){if(e.status>=200&&e.status<300)return"";try{return await Ot(e,It,{timeoutMs:t})}catch{return""}}function nr(e,t){if(!(e>=200&&e<300)&&ko(t))throw new a("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"?Jn(t):t})}function Oo(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var Co=/^\/(api\/)?(v1\/)?public\//;function Rt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Co.test(n),i=n&&Ct(n),o=r&&!i&&!t.forceAuth;if(e.token)return new K({apiBase:e.apiBase,tokenStore:Te(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new K({apiBase:e.apiBase,tokenStore:Te(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new K({apiBase:e.apiBase,tokenStore:Bn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new K({apiBase:e.apiBase,tokenStore:Te(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var ce=8100,vo=new Set([ce]),Ka=new Set([...vo,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var rr="/api/v1/public/claim-links";var Ro=1e4,No="No Claim Link matches this claim token. The token did reach the backend \u2014 an empty or malformed one is refused locally, before anything is sent \u2014 and the public receiver endpoint answers the same way for every token that resolves to nothing, so it will not confirm whether a token exists. Re-check the claim link or URL you were given. An expired or already-claimed link is NOT this error: it still resolves, and comes back as a status snapshot or a 200 claim outcome.";function xo(e){let t=e?.body;if(!t||typeof t!="object")return;let n=t.code;if(typeof n=="number")return n;if(typeof n=="string"&&/^[0-9]+$/.test(n))return Number(n)}function ir(e){throw e instanceof a&&e.code==="not_found"&&xo(e.details)===ce?new a("not_found",No,{status:404,backend_code:ce}):e}function or(e,t){let n=encodeURIComponent(e);return t==="claim"?`${rr}/${n}:claim`:`${rr}/${n}`}function Ne(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new a("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let i=t.trim();if(!i)throw new a("input.invalid","--claim-token is empty.");return Nt(i,"--claim-token")}let r=n.trim();if(!r)throw new a("input.invalid","--claim-url is empty.");return Nt(Po(r),"--claim-url")}async function sr(e,t,n=Ro){let r=e["claim-url"]?.trim();if(!r)return Ne(e);let i;try{i=new URL(r)}catch{return Ne(e)}let o=/^\/s\/([^/]+)\/?$/.exec(i.pathname);if(!o||e["claim-token"]!==void 0)return Ne(e);R(t);let s=new URL(t).origin;if(i.origin!==s||i.username||i.password)throw new a("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(o[1])}catch{throw new a("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new a("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let E;try{E=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new a(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=E.headers.get("location");try{E.body?.cancel().catch(()=>{})}catch{}if(E.status!==302||!g)throw new a("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:E.status});let m;try{m=new URL(g,u)}catch{throw new a("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new a("transport.network","Claim short-link redirect did not stay on the configured API origin.");let b=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!b)throw new a("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(b[1])}catch{throw new a("transport.network","Claim short-link redirect contained a malformed token.")}return Nt(N,"--claim-url")}function Nt(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new a("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function Po(e){let t;try{t=new URL(e)}catch(s){throw new a("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new a("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),i=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],o=i.endsWith(":claim")?i.slice(0,-6):i;try{return decodeURIComponent(o)}catch{throw new a("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function ar(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new a("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function lr(e,t=""){let n=C()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var Bo=["claimed","not_claimable","expired","payout_pending","payout_failed"],$o=64,Do=128,Uo=/^[a-z][a-z0-9_]*$/,Fo=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function cr(e){return typeof e=="string"&&e.length>0&&e.length<=$o&&Uo.test(e)}function ur(e){return typeof e=="string"&&e.length>0&&e.length<=Do&&Fo.test(e)}function dr(e){return typeof e=="string"&&wn.test(e)}function Mo(e){let t={outcome_ambiguous:!0};if(typeof e!="object"||e===null)return t;let n=e;return cr(n.outcome)&&(t.outcome=n.outcome),ur(n.claim_link_id)&&(t.claim_link_id=n.claim_link_id),n.claim_tx_hash===null?t.claim_tx_hash=null:dr(n.claim_tx_hash)&&(t.claim_tx_hash=n.claim_tx_hash),t}function Go(e){if(typeof e!="object"||e===null)return!1;let t=e;return cr(t.outcome)&&Bo.includes(t.outcome)&&ur(t.claim_link_id)&&(t.claim_tx_hash===void 0||t.claim_tx_hash===null||dr(t.claim_tx_hash))}function fr(e){if(!Go(e))throw new a("backend.internal","Claim endpoint returned an invalid result; the claim outcome is unknown. Inspect the Claim Link before retrying.",Mo(e));if(e.outcome==="claimed")return e;let t={outcome:e.outcome,claim_link_id:e.claim_link_id,claim_tx_hash:e.claim_tx_hash??null};throw e.outcome==="payout_pending"||e.outcome==="payout_failed"?new a("claim.payout_ambiguous",`Claim payout is ${e.outcome==="payout_pending"?"still pending":"not proven successful"}. Do not submit another claim; reconcile this Claim Link first.`,{...t,outcome_ambiguous:!0}):new a(e.outcome==="expired"?"claim.expired":"claim.not_claimable",e.outcome==="expired"?"Claim did not complete because this Claim Link has expired.":"Claim did not complete because this Claim Link is not claimable in its current state. Inspect its status before deciding whether to retry.",t)}var xe=class e extends ie{static description="Claim a Claim Link. Path-A claims (no AllScale account sign-in) require --to; authenticated business receivers can use --to-wallet. Only an on-chain-proven claimed outcome exits 0.";static examples=[`$ allscale claim-link claim --claim-token claim-token-from-share-link --to ${st}`,"$ allscale claim-link claim --claim-url https://app.allscale.io/claim/claim-token-from-share-link --to-wallet"];static usage=lr("claim"," (--to <value> | --to-wallet)");static requiresInput=!0;static flags={"claim-token":$.Flags.string({helpGroup:"REQUIRED SOURCE (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":$.Flags.string({helpGroup:"REQUIRED SOURCE (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),to:$.Flags.string({helpGroup:"REQUIRED DESTINATION (ONE OF)",description:"Receiver EVM address for Path-A claims (no AllScale account sign-in). This does not make the transaction anonymous: network, request, compliance, and public blockchain data may still be processed or observable.",exclusive:["to-wallet"]}),"to-wallet":$.Flags.boolean({helpGroup:"REQUIRED DESTINATION (ONE OF)",description:"Claim into the authenticated receiver business's AllScale wallet for the link's chain. Requires login/token.",default:!1,exclusive:["to"]}),...ie.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await sr(t,n.apiBase),i=or(r,"claim"),o,s;if(t["to-wallet"])o={},s="required";else{let d=t.to?.trim();if(!d)throw new a("input.invalid","Pass --to <0x address> or --to-wallet.");if(!hn(d))throw new a("input.invalid",`--to is not a valid EVM address: '${d}' (expected 0x followed by 40 hex characters).`);if(mn(d))throw new a("input.invalid","--to must not be the zero or burn address; funds claimed to it cannot be recovered.");gn(d),o={receiver_address:d},s="none"}let u=await Rt(n,{pathHint:i,forceAuth:s==="required"}).request({method:"POST",path:i,body:o,auth:s}).catch(ir);return fr(ar(u))}};0&&(module.exports={requireSuccessfulClaim});
|
|
17
17
|
//# sourceMappingURL=claim.js.map
|