@picoxr/pico-auth-cli-cn 0.1.20 → 0.1.23

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 CHANGED
@@ -36,6 +36,19 @@ pico-auth-cli-cn logout
36
36
 
37
37
  Use `--json` when machine-readable output is required.
38
38
 
39
+ For browser authorization that continues across Agent turns, create one request with
40
+ `login --no-wait`. After approval, run `login --resume-pending` to collect its result from local
41
+ state, or use `login --resume '<device_code>'` with the original handle. Keep the same region and
42
+ options. `status` does not collect browser authorization.
43
+
44
+ New requests retain their region and request options. A resume with different options returns
45
+ `LOGIN_CONTEXT_MISMATCH` before contacting the service and preserves the request. Legacy pending
46
+ records do not contain this context, so keep their original options when resuming.
47
+
48
+ An unexpired pending request is preserved when another login is attempted. A local waiting timeout
49
+ also preserves it; resume that request instead of opening a second authorization flow. A request
50
+ that has expired requires a new login. Check installed `login --help` for supported recovery options.
51
+
39
52
  ## Data, Privacy, and Security
40
53
 
41
54
  - After a successful sign-in, and after a refresh changes the access token, the CLI makes a
@@ -10,34 +10,40 @@
10
10
  * from PICO.
11
11
  */
12
12
 
13
- import {realpathSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {execFile,spawn,execFileSync}from'child_process';import {createHash,randomUUID,randomBytes,generateKeyPairSync,sign}from'crypto';import {mkdir,writeFile,rm,stat,readFile,open,rename}from'fs/promises';import {join,dirname}from'path';import at,{userInfo,tmpdir}from'os';import {createRequire}from'module';import {promisify}from'util';
14
- var a=class extends Error{kind;errorCode;description;descUrl;cause;constructor(e){super(e.description||e.kind.toLowerCase()),this.name="ProtocolError",this.kind=e.kind,this.errorCode=e.errorCode??0,this.description=e.description??"",this.descUrl=e.descUrl??"",this.cause=e.cause;}};function C(t,e){return t instanceof a&&(e===void 0||t.kind===e)}var kt="/passport/open/get_device_code/",Dt="/passport/open/check_device_code/",Nt="/passport/open/refresh_token/",B="/api/cli/v1/authorization/device/report",Lt="Bearer",$e="X-Tt-Logid",xt=1,bt=6,Ut=7,$t=10,Gt=10010,Kt=10002,z=10003,Ft=10005,q=10021,Fe=10042,Me=10043,Mt=10044,Vt=10046,Ht=1080,j=class{baseUrl;deviceReportBaseUrl;aid;headers;deviceReportHttpHeaders;userAgent;constructor(e){if(!e.baseUrl.trim())throw new Error("protocol: base url is required");if(this.baseUrl=new URL(e.baseUrl),!this.baseUrl.protocol||!this.baseUrl.host)throw new Error("protocol: base url must include scheme and host");if(this.deviceReportBaseUrl=new URL(e.deviceReportBaseUrl??e.baseUrl),!this.deviceReportBaseUrl.protocol||!this.deviceReportBaseUrl.host)throw new Error("protocol: device report base url must include scheme and host");this.aid=e.aid,this.headers={...e.headers??{}},this.deviceReportHttpHeaders={...e.deviceReportHttpHeaders??{}},this.userAgent=e.userAgent;}async getDeviceCode(e,r){let n=new URLSearchParams;n.set("client_key",e.clientKey),n.set("pub_key",e.pubKey);let i=Bt(e.scopes??[]);i&&n.set("scope",i);let o=await this.postForm(kt,n,void 0,r),s=V(o,jt);return {deviceCode:k(s,"device_code"),userCode:k(s,"user_code"),verificationUri:k(s,"verification_uri"),intervalMs:H(s,"interval")*1e3,expiresInMs:H(s,"expires_in")*1e3}}async checkDeviceCode(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("device_code",e.deviceCode);let i=await this.postForm(Dt,n,void 0,r),o=V(i,zt),s=Ge(o);return Wt(s),{accessToken:k(o,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:H(o,"expires_in")*1e3}}async refreshToken(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("client_key",e.clientKey),n.set("grant_type","refresh_token"),n.set("refresh_token",e.refreshToken);let i=await this.postForm(Nt,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},r),o=V(i,qt),s=Ge(o);return {accessToken:k(o,"access_token"),refreshToken:s.refresh_token,expiresInMs:H(o,"expires_in")*1e3}}async reportDeviceAuthorization(e,r){let n=new URLSearchParams;e.deviceInfo.cliVersion&&n.set("cli_version",e.deviceInfo.cliVersion),e.deviceInfo.architecture&&n.set("architecture",e.deviceInfo.architecture);let i=n.toString(),o=i?`${B}?${i}`:B;await this.postJson(o,{device_info:{name:e.deviceInfo.name,os:e.deviceInfo.os,os_version:e.deviceInfo.osVersion,region:e.deviceInfo.region}},{...this.deviceReportHttpHeaders,...e.headers},r,this.deviceReportBaseUrl);}async postForm(e,r,n,i){let o=this.resolve(e),s;try{s=await fetch(o,{method:"POST",body:r,signal:i,headers:{...this.headers,...n??{},"Content-Type":"application/x-www-form-urlencoded",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(u){throw new a({kind:"TRANSPORT",description:"do request",cause:u})}let c=await s.text();if(s.status!==200)throw new a({kind:"SERVER",errorCode:s.status,description:s.statusText||`unexpected http status ${s.status}`,descUrl:s.headers.get($e)??""});try{return JSON.parse(c)}catch(u){throw new a({kind:"DECODE",description:"decode envelope",cause:u})}}async postJson(e,r,n,i,o=this.baseUrl){let s=this.resolve(e,o),c;try{c=await fetch(s,{method:"POST",body:JSON.stringify(r),signal:i,headers:{...this.headers,...n??{},"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(p){throw new a({kind:"TRANSPORT",description:"do request",cause:p})}let u=await c.text();if(c.status!==200)throw new a({kind:"SERVER",errorCode:c.status,description:c.statusText||`unexpected http status ${c.status}`,descUrl:c.headers.get($e)??""});let d;try{d=JSON.parse(u);}catch(p){throw new a({kind:"DECODE",description:"decode response envelope",cause:p})}let A=fe(d,"code");if(A!==void 0){if(A===0)return;throw new a({kind:"SERVER",errorCode:A,description:S(d,"em")??S(d,"et")??"device report failed",descUrl:S(d,"trace_id")??""})}V(d,X);}resolve(e,r=this.baseUrl){let n=new URL(e,r);return this.aid!==void 0&&this.aid!==0&&n.searchParams.set("aid",String(this.aid)),n.toString()}};function Bt(t){return t.map(e=>e.trim()).filter(Boolean).join(",")}function V(t,e){let r=Zt(t.data)?t.data:{};if(Ke(t.message,"success"))return r;if(!Ke(t.message,"error"))throw new a({kind:"SERVER",description:"unexpected response message"});let n=typeof r.error_code=="number"?r.error_code:0,i=typeof r.code=="number"?r.code:0,o=typeof r.description=="string"?r.description:String(t.message??"error"),s=e(n||i,o),c=typeof r.desc_url=="string"?r.desc_url:"";throw c?new a({kind:s.kind,errorCode:s.errorCode,description:s.description,descUrl:c,cause:s.cause}):s}function jt(t,e){switch(t){case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return X(t,e)}}function zt(t,e){switch(t){case Ut:return new a({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case Ht:return Xt(t,e);case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return X(t,e)}}function qt(t,e){switch(t){case Gt:return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case Fe:return new a({kind:"INVALID_GRANT",errorCode:t,description:e});case Me:return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});case Ft:case Kt:case Mt:case Vt:case bt:return new a({kind:"SERVER",errorCode:t,description:e});default:return X(t,e)}}function Xt(t,e){let r=e.toLowerCase().trim();return r.includes("\u53D6\u6D88\u6388\u6743")?new a({kind:"ACCESS_DENIED",errorCode:t,description:e}):r.includes("\u5931\u6548")||r.includes("\u8FC7\u671F")?new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e}):new a({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e})}function X(t,e){switch(e.toLowerCase().trim()){case "authorization_pending":case "\u7528\u6237\u5C1A\u672A\u5B8C\u6210\u6388\u6743\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":case "\u8F6E\u8BE2\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":return new a({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case "expired_token":case "device_code \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u5728 cli \u53D1\u8D77\u767B\u5F55":case "token \u5DF2\u8FC7\u671F":case "\u4F1A\u8BDD\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":case "\u6570\u636E\u4E0D\u5B58\u5728":return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case "access_denied":case "\u7528\u6237\u5DF2\u53D6\u6D88\u6388\u6743":return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});case "invalid_grant":case "\u975E\u6CD5 token":return new a({kind:"INVALID_GRANT",errorCode:t,description:e});case "invalid_client":case "\u914D\u7F6E\u65E0\u6548":return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});}switch(t){case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});case Fe:return new a({kind:"INVALID_GRANT",errorCode:t,description:e});case Me:case xt:case $t:return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});}return new a({kind:"SERVER",errorCode:t,description:e})}function Ge(t){return {access_token:S(t,"access_token"),refresh_token:S(t,"refresh_token"),token_type:S(t,"token_type"),expires_in:fe(t,"expires_in")}}function Wt(t){if(t.token_type!==Lt)throw new a({kind:"SERVER",description:"unexpected token_type"})}function k(t,e){let r=S(t,e);if(r===void 0||r.trim()==="")throw new a({kind:"DECODE",description:`missing or empty ${e}`});return r}function Jt(t,e){let r=fe(t,e);if(r===void 0||!Number.isFinite(r))throw new a({kind:"DECODE",description:`missing or invalid ${e}`});return r}function H(t,e){let r=Jt(t,e);if(r<=0)throw new a({kind:"DECODE",description:`invalid ${e}`});return r}function S(t,e){let r=t[e];return typeof r=="string"?r:void 0}function fe(t,e){let r=t[e];return typeof r=="number"?r:void 0}function Zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ke(t,e){return typeof t=="string"&&t.toLowerCase()===e.toLowerCase()}var Ve="ecdsa-p256-sha256";var rr=16,W=class{constructor(e=()=>new Date,r=randomBytes){this.now=e;this.random=r;}now;random;generateDeviceKey(){let{publicKey:e,privateKey:r}=generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return {Algorithm:Ve,PublicKeyBase64:Buffer.from(e).toString("base64"),PrivateKeyBase64:Buffer.from(r).toString("base64")}}sign(e,r){if(!e.urlPath||!e.urlPath.startsWith("/"))throw new Error("signer: invalid url path");let n=String(Math.floor(this.now().getTime()/1e3)),i=this.random(rr).toString("hex"),o=nr(e.signingMaterial),s=createHash("sha256").update(o).digest("base64"),c=[e.method,e.urlPath,s,n,i].join(`
15
- `),u=or(r.PrivateKeyBase64,"PRIVATE KEY"),d=sign("sha256",Buffer.from(c),{key:u,dsaEncoding:"der"});return {pubKey:r.PublicKeyBase64,signature:d.toString("base64"),timestamp:n,nonce:i}}};function nr(t){return t===void 0?new Uint8Array:typeof t=="string"?Buffer.from(t):t}function or(t,e){let r=t.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
13
+ import {realpathSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {execFile,spawn,execFileSync}from'child_process';import {createHash,randomUUID,randomBytes,generateKeyPairSync,sign}from'crypto';import {mkdir,writeFile,rm,stat,readFile,open,rename}from'fs/promises';import {join,dirname}from'path';import ft,{tmpdir,userInfo}from'os';import {createRequire}from'module';import {promisify}from'util';
14
+ var c=class extends Error{kind;errorCode;description;descUrl;cause;constructor(e){super(e.description||e.kind.toLowerCase()),this.name="ProtocolError",this.kind=e.kind,this.errorCode=e.errorCode??0,this.description=e.description??"",this.descUrl=e.descUrl??"",this.cause=e.cause;}};function T(t,e){return t instanceof c&&(e===void 0||t.kind===e)}var $t="/passport/open/get_device_code/",Kt="/passport/open/check_device_code/",Mt="/passport/open/refresh_token/",q="/api/cli/v1/authorization/device/report",Ft="Bearer",je="X-Tt-Logid",Ht=1,Vt=6,Bt=7,jt=10,zt=10010,qt=10002,W=10003,Xt=10005,J=10021,Xe=10042,We=10043,Wt=10044,Jt=10046,Yt=1080,X=class{baseUrl;deviceReportBaseUrl;aid;headers;deviceReportHttpHeaders;userAgent;constructor(e){if(!e.baseUrl.trim())throw new Error("protocol: base url is required");if(this.baseUrl=new URL(e.baseUrl),!this.baseUrl.protocol||!this.baseUrl.host)throw new Error("protocol: base url must include scheme and host");if(this.deviceReportBaseUrl=new URL(e.deviceReportBaseUrl??e.baseUrl),!this.deviceReportBaseUrl.protocol||!this.deviceReportBaseUrl.host)throw new Error("protocol: device report base url must include scheme and host");this.aid=e.aid,this.headers={...e.headers??{}},this.deviceReportHttpHeaders={...e.deviceReportHttpHeaders??{}},this.userAgent=e.userAgent;}async getDeviceCode(e,r){let n=new URLSearchParams;n.set("client_key",e.clientKey),n.set("pub_key",e.pubKey);let i=Zt(e.scopes??[]);i&&n.set("scope",i);let o=await this.postForm($t,n,void 0,r),s=j(o,Qt);return {deviceCode:x(s,"device_code"),userCode:x(s,"user_code"),verificationUri:x(s,"verification_uri"),intervalMs:z(s,"interval")*1e3,expiresInMs:z(s,"expires_in")*1e3}}async checkDeviceCode(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("device_code",e.deviceCode);let i=await this.postForm(Kt,n,void 0,r),o=j(i,er),s=ze(o);return nr(s),{accessToken:x(o,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:z(o,"expires_in")*1e3}}async refreshToken(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("client_key",e.clientKey),n.set("grant_type","refresh_token"),n.set("refresh_token",e.refreshToken);let i=await this.postForm(Mt,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},r),o=j(i,tr),s=ze(o);return {accessToken:x(o,"access_token"),refreshToken:s.refresh_token,expiresInMs:z(o,"expires_in")*1e3}}async reportDeviceAuthorization(e,r){let n=new URLSearchParams;e.deviceInfo.cliVersion&&n.set("cli_version",e.deviceInfo.cliVersion),e.deviceInfo.architecture&&n.set("architecture",e.deviceInfo.architecture);let i=n.toString(),o=i?`${q}?${i}`:q;await this.postJson(o,{device_info:{name:e.deviceInfo.name,os:e.deviceInfo.os,os_version:e.deviceInfo.osVersion,region:e.deviceInfo.region}},{...this.deviceReportHttpHeaders,...e.headers},r,this.deviceReportBaseUrl);}async postForm(e,r,n,i){let o=this.resolve(e),s;try{s=await fetch(o,{method:"POST",body:r,signal:i,headers:{...this.headers,...n??{},"Content-Type":"application/x-www-form-urlencoded",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(d){throw new c({kind:"TRANSPORT",description:"do request",cause:d})}let a=await s.text();if(s.status!==200)throw new c({kind:"SERVER",errorCode:s.status,description:s.statusText||`unexpected http status ${s.status}`,descUrl:s.headers.get(je)??""});try{return JSON.parse(a)}catch(d){throw new c({kind:"DECODE",description:"decode envelope",cause:d})}}async postJson(e,r,n,i,o=this.baseUrl){let s=this.resolve(e,o),a;try{a=await fetch(s,{method:"POST",body:JSON.stringify(r),signal:i,headers:{...this.headers,...n??{},"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(l){throw new c({kind:"TRANSPORT",description:"do request",cause:l})}let d=await a.text();if(a.status!==200)throw new c({kind:"SERVER",errorCode:a.status,description:a.statusText||`unexpected http status ${a.status}`,descUrl:a.headers.get(je)??""});let u;try{u=JSON.parse(d);}catch(l){throw new c({kind:"DECODE",description:"decode response envelope",cause:l})}let A=we(u,"code");if(A!==void 0){if(A===0)return;throw new c({kind:"SERVER",errorCode:A,description:C(u,"em")??C(u,"et")??"device report failed",descUrl:C(u,"trace_id")??""})}j(u,Y);}resolve(e,r=this.baseUrl){let n=new URL(e,r);return this.aid!==void 0&&this.aid!==0&&n.searchParams.set("aid",String(this.aid)),n.toString()}};function Zt(t){return t.map(e=>e.trim()).filter(Boolean).join(",")}function j(t,e){let r=or(t.data)?t.data:{};if(qe(t.message,"success"))return r;if(!qe(t.message,"error"))throw new c({kind:"SERVER",description:"unexpected response message"});let n=typeof r.error_code=="number"?r.error_code:0,i=typeof r.code=="number"?r.code:0,o=typeof r.description=="string"?r.description:String(t.message??"error"),s=e(n||i,o),a=typeof r.desc_url=="string"?r.desc_url:"";throw a?new c({kind:s.kind,errorCode:s.errorCode,description:s.description,descUrl:a,cause:s.cause}):s}function Qt(t,e){switch(t){case W:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case J:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return Y(t,e)}}function er(t,e){switch(t){case Bt:return new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case Yt:return rr(t,e);case W:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case J:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return Y(t,e)}}function tr(t,e){switch(t){case zt:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case Xe:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case We:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case W:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case J:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case Xt:case qt:case Wt:case Jt:case Vt:return new c({kind:"SERVER",errorCode:t,description:e});default:return Y(t,e)}}function rr(t,e){let r=e.toLowerCase().trim();return r.includes("\u53D6\u6D88\u6388\u6743")?new c({kind:"ACCESS_DENIED",errorCode:t,description:e}):r.includes("\u5931\u6548")||r.includes("\u8FC7\u671F")?new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e}):new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e})}function Y(t,e){switch(e.toLowerCase().trim()){case "authorization_pending":case "\u7528\u6237\u5C1A\u672A\u5B8C\u6210\u6388\u6743\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":case "\u8F6E\u8BE2\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":return new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case "expired_token":case "device_code \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u5728 cli \u53D1\u8D77\u767B\u5F55":case "token \u5DF2\u8FC7\u671F":case "\u4F1A\u8BDD\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":case "\u6570\u636E\u4E0D\u5B58\u5728":return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case "access_denied":case "\u7528\u6237\u5DF2\u53D6\u6D88\u6388\u6743":return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case "invalid_grant":case "\u975E\u6CD5 token":return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case "invalid_client":case "\u914D\u7F6E\u65E0\u6548":return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});}switch(t){case W:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case J:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case Xe:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case We:case Ht:case jt:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});}return new c({kind:"SERVER",errorCode:t,description:e})}function ze(t){return {access_token:C(t,"access_token"),refresh_token:C(t,"refresh_token"),token_type:C(t,"token_type"),expires_in:we(t,"expires_in")}}function nr(t){if(t.token_type!==Ft)throw new c({kind:"SERVER",description:"unexpected token_type"})}function x(t,e){let r=C(t,e);if(r===void 0||r.trim()==="")throw new c({kind:"DECODE",description:`missing or empty ${e}`});return r}function ir(t,e){let r=we(t,e);if(r===void 0||!Number.isFinite(r))throw new c({kind:"DECODE",description:`missing or invalid ${e}`});return r}function z(t,e){let r=ir(t,e);if(r<=0)throw new c({kind:"DECODE",description:`invalid ${e}`});return r}function C(t,e){let r=t[e];return typeof r=="string"?r:void 0}function we(t,e){let r=t[e];return typeof r=="number"?r:void 0}function or(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qe(t,e){return typeof t=="string"&&t.toLowerCase()===e.toLowerCase()}var Je="ecdsa-p256-sha256";var dr=16,Z=class{constructor(e=()=>new Date,r=randomBytes){this.now=e;this.random=r;}now;random;generateDeviceKey(){let{publicKey:e,privateKey:r}=generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return {Algorithm:Je,PublicKeyBase64:Buffer.from(e).toString("base64"),PrivateKeyBase64:Buffer.from(r).toString("base64")}}sign(e,r){if(!e.urlPath||!e.urlPath.startsWith("/"))throw new Error("signer: invalid url path");let n=String(Math.floor(this.now().getTime()/1e3)),i=this.random(dr).toString("hex"),o=lr(e.signingMaterial),s=createHash("sha256").update(o).digest("base64"),a=[e.method,e.urlPath,s,n,i].join(`
15
+ `),d=hr(r.PrivateKeyBase64,"PRIVATE KEY"),u=sign("sha256",Buffer.from(a),{key:d,dsaEncoding:"der"});return {pubKey:r.PublicKeyBase64,signature:u.toString("base64"),timestamp:n,nonce:i}}};function lr(t){return t===void 0?new Uint8Array:typeof t=="string"?Buffer.from(t):t}function hr(t,e){let r=t.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
16
16
  ${r.join(`
17
17
  `)}
18
18
  -----END ${e}-----
19
- `}var J=class extends Error{code;cause;constructor(e,r,n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="StoreError",this.code=e,this.cause=n;}};function h(t,e,r){return new J(t,`${e}: ${ir(t)}`,r)}function m(t,e){return t instanceof J&&(e===void 0||t.code===e)}function ir(t){switch(t){case "NOT_FOUND":return "store: not found";case "CORRUPT_RECORD":return "store: corrupt record";case "BACKEND_UNAVAILABLE":return "store: backend unavailable";case "PERMISSION_DENIED":return "store: permission denied";case "ENCODE_FAILED":return "store: encode failed";case "DECODE_FAILED":return "store: decode failed"}}var Be=1e6;function _(t){je(t);let e={client_key:t.clientKey,device_code:D(t.deviceCode),user_code:D(t.userCode),verification_uri:D(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*Be),login_expires_at:t.loginExpiresAt?.toISOString(),access_token:D(t.accessToken),refresh_token:D(t.refreshToken),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(sr(e))}function O(t){if(t.trim()==="")throw h("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(t);}catch(n){throw h("DECODE_FAILED","load",n)}let r={clientKey:e.client_key??"",deviceCode:e.device_code,userCode:e.user_code,verificationUri:e.verification_uri,intervalMs:e.interval===void 0?void 0:e.interval/Be,loginExpiresAt:He(e.login_expires_at),accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:He(e.token_expires_at),deviceKey:e.device_key,userInfo:e.user_info,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):void 0};return je(r),r}function je(t){if(!t.clientKey.trim())throw h("CORRUPT_RECORD","validate",new Error("client_key is required"))}function N(t){let e=t.trim();if(e==="")return "_";let r="";for(let n of e)/^[A-Za-z0-9._-]$/.test(n)?r+=n:r+="_";return r||"_"}function He(t){if(t)return new Date(t)}function D(t){return t===void 0||t===""?void 0:t}function sr(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var Z=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;async load(){let e;try{e=await readFile(this.path,"utf8");}catch(r){throw r?.code==="ENOENT"?h("NOT_FOUND","load",r):y("load",r)}try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){let r=_(e),n=dirname(this.path);await mkdir(n,{recursive:true,mode:448});let i=join(n,`${randomBytes(8).toString("hex")}.tmp`);try{await writeFile(i,r,{mode:384}),await rename(i,this.path);}catch(o){throw await rm(i,{force:true}).catch(()=>{}),y("save",o)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await rm(this.path,{force:!0});}catch(e){throw y("delete",e)}}};function Xe(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",N(t),`${N(e)}.json`)}function y(t,e){let r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return r.includes("permission denied")||r.includes("access denied")?h("PERMISSION_DENIED",t,e):h("BACKEND_UNAVAILABLE",t,e)}var Je=promisify(execFile),Sr=createRequire(import.meta.url),Pr=9e4,vr=5*6e4,Cr=100,Y="pico-auth-cli-managed-v2",L="pico-auth-cli-managed-v3",T="pico-auth-cli-managed-v3-legacy-ambiguous",x=class{constructor(e,r,n=Tr){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;async load(){let e;try{e=await this.runner.getPassword(this.serviceName,this.account);}catch(r){throw y("load",r)}if(e===null)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){let r;try{r=_(e);}catch(n){throw y("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw y("save",Nr(n,r))}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.deletePassword(this.serviceName,this.account);}catch(e){throw y("delete",e)}}},Or={async getPassword(t,e){try{let{stdout:r}=await Je("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(Ye(r))return null;throw r}},async deletePassword(t,e){try{return await Je("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(Ye(r))return false;throw r}}},rt={getPassword:(t,e)=>ge().getPassword(t,e),setPassword:(t,e,r)=>ge().setPassword(t,e,r),deletePassword:(t,e)=>ge().deletePassword(t,e)},Ae=class{constructor(e=rt,r=Or,n=_e){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let o of [we(r),Ee(r)]){let s=await this.managed.getPassword(e,o);if(s!==null)return s}let n=await this.managed.getPassword(e,ye(r));if(n===L||n===T)return null;let i=await this.managed.getPassword(e,me(r));return i!==null?i:await this.managed.getPassword(e,Ze(r))===Y?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let i=we(r),o=Ee(r),s=ye(r);await this.managed.setPassword(e,i,n),await Q(this.managed,e,i,n,"recovery"),await this.managed.setPassword(e,o,n),await Q(this.managed,e,o,n,"primary"),await this.managed.setPassword(e,s,L),await Q(this.managed,e,s,L,"state"),await this.managed.deletePassword(e,i).catch(()=>{}),await this.managed.deletePassword(e,me(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[we(r),Ee(r),me(r)],i=await Promise.all(n.map(E=>this.managed.getPassword(e,E))),o=ye(r),s=await this.managed.getPassword(e,o),c=Ze(r),u=await this.managed.getPassword(e,c);if(!(i.some(E=>E!==null)||s===L||s===T||u===Y))return this.legacy.deletePassword(e,r);let p=i[2]!==null&&u!==Y||s===T?T:L;await this.managed.setPassword(e,o,p),await Q(this.managed,e,o,p,"state");let f=false,R;for(let E of n)try{f=await this.managed.deletePassword(e,E)||f;}catch(It){R??=It;}if(R!==void 0)throw R;if(u===Y)try{let E=await this.managed.deletePassword(e,r);f=E||f,(E||await this.managed.getPassword(e,r)===null)&&(f=await this.managed.deletePassword(e,c)||f);}catch(E){R??=E;}else if(p!==T)try{f=await this.legacy.deletePassword(e,r)||f;}catch(E){R??=E;}if(R!==void 0)throw R;return p===T||(f=await this.managed.deletePassword(e,o)||f),f})}},Tr=process.platform==="darwin"?new Ae:rt;function ge(){return Sr("keytar")}function me(t){return `${t}.pico-auth-cli-recovery-v1`}function Ze(t){return `${t}.pico-auth-cli-managed-v2`}function we(t){return `${t}.pico-auth-cli-recovery-v3`}function Ee(t){return `${t}.pico-auth-cli-payload-v3`}function ye(t){return `${t}.pico-auth-cli-state-v3`}async function _e(t,e,r){let n=join("/tmp",`pico-auth-cli-keychain-locks-${userInfo().uid}`);await mkdir(n,{recursive:true,mode:448});let i=createHash("sha256").update(t).update("\0").update(e).digest("hex"),o=join(n,`${i}.lock`),s=join(o,"owner.json"),c=randomUUID(),u=Date.now()+Pr;for(;;)try{await mkdir(o,{mode:448});try{await writeFile(s,JSON.stringify({pid:process.pid,token:c,createdAt:Date.now()}),{flag:"wx",mode:384});}catch(d){throw await rm(o,{recursive:!0,force:!0}).catch(()=>{}),d}break}catch(d){if(b(d)!=="EEXIST")throw d;if(await nt(o)&&await Ir(o))continue;if(Date.now()>=u)throw new Error("timed out waiting for the macOS Keychain write lock");await new Promise(A=>setTimeout(A,Cr));}try{return await r()}finally{await Dr(o,s,c).catch(()=>{});}}async function nt(t){try{let e=await stat(t);try{let r=await readFile(join(t,"owner.json"),"utf8"),n=JSON.parse(r);return typeof n.pid=="number"&&!kr(n.pid)}catch{return Date.now()-e.mtimeMs>=vr}}catch{return false}}async function Ir(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if(b(n)==="EEXIST")return false;throw n}try{if(!await nt(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(i){if(b(i)==="ENOENT")return !0;throw i}return await rm(n,{recursive:!0,force:!0}),!0}finally{await r.close().catch(()=>{}),await rm(e,{force:true}).catch(()=>{});}}function kr(t){try{return process.kill(t,0),!0}catch(e){return b(e)==="EPERM"}}async function Dr(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if(b(n)!=="ENOENT")throw n}}function b(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"?t.code:void 0}async function Q(t,e,r,n,i){if(await t.getPassword(e,r)!==n)throw new Error(`macOS Keychain ${i} write verification failed`)}function U(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function Ye(t){let e=t instanceof Error?t.message:String(t);return e.includes("could not be found")||e.includes("The specified item could not be found")}function Nr(t,e){let r=t instanceof Error?t.message:String(t),n=r.includes(e)?r.split(e).join("[REDACTED]"):r,i=new Error(n),o=Qe(t,"code"),s=Qe(t,"exitCode");return o!==void 0&&Object.assign(i,{code:o}),s!==void 0&&Object.assign(i,{exitCode:s}),i}function Qe(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var Re=class extends Error{code;exitCode;stderr;constructor(e,r,n){let i=n.trim();super(`${e} exited with code ${r??"unknown"}${i?`: ${i}`:""}`),this.name="CommandExecutionError",this.code=r,this.exitCode=r,this.stderr=n;}};function ot(t,e,r,n=process.env){return new Promise((i,o)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),c=[],u=[],d=false,A=p=>{d||(d=true,o(p));};s.stdout.on("data",p=>c.push(Buffer.from(p))),s.stderr.on("data",p=>u.push(Buffer.from(p))),s.once("error",A),s.stdin.once("error",A),s.once("close",p=>{if(d)return;d=true;let f={stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(u).toString()};if(p===0){i(f);return}o(new Re(t,p,f.stderr));}),s.stdin.end(r);})}var Ur=promisify(execFile),$r="Software\\BytedAuthClient\\keychain",re=class{constructor(e,r,n=Gr){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;async load(){let e;try{e=await this.runner.get(this.serviceName,this.account);}catch(r){throw y("load",r)}if(e===void 0)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,_(e));}catch(r){throw y("save",r)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.delete(this.serviceName,this.account);}catch(e){throw y("delete",e)}}},Gr={async get(t,e){let r=Buffer.from(it(t,e)).toString("base64"),n=`
19
+ `}var Q=class extends Error{code;cause;constructor(e,r,n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="StoreError",this.code=e,this.cause=n;}};function g(t,e,r){return new Q(t,`${e}: ${pr(t)}`,r)}function m(t,e){return t instanceof Q&&(e===void 0||t.code===e)}function pr(t){switch(t){case "NOT_FOUND":return "store: not found";case "CORRUPT_RECORD":return "store: corrupt record";case "BACKEND_UNAVAILABLE":return "store: backend unavailable";case "PERMISSION_DENIED":return "store: permission denied";case "ENCODE_FAILED":return "store: encode failed";case "DECODE_FAILED":return "store: decode failed"}}var Ze=1e6;function E(t){Qe(t);let e={client_key:t.clientKey,device_code:L(t.deviceCode),user_code:L(t.userCode),verification_uri:L(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*Ze),login_expires_at:t.loginExpiresAt?.toISOString(),login_context:t.loginContext?{base_url:t.loginContext.baseUrl,aid:t.loginContext.aid,ppe_header:t.loginContext.ppeHeader}:void 0,access_token:L(t.accessToken),refresh_token:L(t.refreshToken),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(gr(e))}function I(t){if(t.trim()==="")throw g("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(t);}catch(n){throw g("DECODE_FAILED","load",n)}let r={clientKey:e.client_key??"",deviceCode:e.device_code,userCode:e.user_code,verificationUri:e.verification_uri,intervalMs:e.interval===void 0?void 0:e.interval/Ze,loginExpiresAt:Ye(e.login_expires_at),loginContext:e.login_context?{baseUrl:e.login_context.base_url,aid:e.login_context.aid,ppeHeader:e.login_context.ppe_header}:void 0,accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:Ye(e.token_expires_at),deviceKey:e.device_key,userInfo:e.user_info,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):void 0};return Qe(r),r}function Qe(t){if(!t.clientKey.trim())throw g("CORRUPT_RECORD","validate",new Error("client_key is required"))}function b(t){let e=t.trim();if(e==="")return "_";let r="";for(let n of e)/^[A-Za-z0-9._-]$/.test(n)?r+=n:r+="_";return r||"_"}function Ye(t){if(t)return new Date(t)}function L(t){return t===void 0||t===""?void 0:t}function gr(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var tt=promisify(execFile),Pr=createRequire(import.meta.url),vr=9e4,Or=5*6e4,Tr=100,ee="pico-auth-cli-managed-v2",U="pico-auth-cli-managed-v3",k="pico-auth-cli-managed-v3-legacy-ambiguous",G=class{constructor(e,r,n=kr){this.serviceName=e;this.account=r;this.runner=n;K(e,r);}serviceName;account;runner;withLock(e){return R(this.serviceName,`${this.account}.auth-session`,e)}async load(){let e;try{e=await this.runner.getPassword(this.serviceName,this.account);}catch(r){throw _("load",r)}if(e===null)throw g("NOT_FOUND","load",new Error("auth record not found"));try{return I(e)}catch(r){throw m(r)?r:g("DECODE_FAILED","load",r)}}async save(e){let r;try{r=E(e);}catch(n){throw _("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw _("save",Lr(n,r))}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.deletePassword(this.serviceName,this.account);}catch(e){throw _("delete",e)}}},Ir={async getPassword(t,e){try{let{stdout:r}=await tt("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(nt(r))return null;throw r}},async deletePassword(t,e){try{return await tt("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(nt(r))return false;throw r}}},at={getPassword:(t,e)=>ye().getPassword(t,e),setPassword:(t,e,r)=>ye().setPassword(t,e,r),deletePassword:(t,e)=>ye().deletePassword(t,e)},Ce=class{constructor(e=at,r=Ir,n=R){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let o of [Ae(r),Re(r)]){let s=await this.managed.getPassword(e,o);if(s!==null)return s}let n=await this.managed.getPassword(e,Se(r));if(n===U||n===k)return null;let i=await this.managed.getPassword(e,_e(r));return i!==null?i:await this.managed.getPassword(e,rt(r))===ee?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let i=Ae(r),o=Re(r),s=Se(r);await this.managed.setPassword(e,i,n),await te(this.managed,e,i,n,"recovery"),await this.managed.setPassword(e,o,n),await te(this.managed,e,o,n,"primary"),await this.managed.setPassword(e,s,U),await te(this.managed,e,s,U,"state"),await this.managed.deletePassword(e,i).catch(()=>{}),await this.managed.deletePassword(e,_e(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[Ae(r),Re(r),_e(r)],i=await Promise.all(n.map(y=>this.managed.getPassword(e,y))),o=Se(r),s=await this.managed.getPassword(e,o),a=rt(r),d=await this.managed.getPassword(e,a);if(!(i.some(y=>y!==null)||s===U||s===k||d===ee))return this.legacy.deletePassword(e,r);let l=i[2]!==null&&d!==ee||s===k?k:U;await this.managed.setPassword(e,o,l),await te(this.managed,e,o,l,"state");let f=false,S;for(let y of n)try{f=await this.managed.deletePassword(e,y)||f;}catch(Gt){S??=Gt;}if(S!==void 0)throw S;if(d===ee)try{let y=await this.managed.deletePassword(e,r);f=y||f,(y||await this.managed.getPassword(e,r)===null)&&(f=await this.managed.deletePassword(e,a)||f);}catch(y){S??=y;}else if(l!==k)try{f=await this.legacy.deletePassword(e,r)||f;}catch(y){S??=y;}if(S!==void 0)throw S;return l===k||(f=await this.managed.deletePassword(e,o)||f),f})}},kr=process.platform==="darwin"?new Ce:at;function ye(){return Pr("keytar")}function _e(t){return `${t}.pico-auth-cli-recovery-v1`}function rt(t){return `${t}.pico-auth-cli-managed-v2`}function Ae(t){return `${t}.pico-auth-cli-recovery-v3`}function Re(t){return `${t}.pico-auth-cli-payload-v3`}function Se(t){return `${t}.pico-auth-cli-state-v3`}async function R(t,e,r){let n=join(process.platform==="win32"?tmpdir():"/tmp",`pico-auth-cli-keychain-locks-${userInfo().uid}`);await mkdir(n,{recursive:true,mode:448});let i=createHash("sha256").update(t).update("\0").update(e).digest("hex"),o=join(n,`${i}.lock`),s=join(o,"owner.json"),a=randomUUID(),d=Date.now()+vr;for(;;)try{await mkdir(o,{mode:448});try{await writeFile(s,JSON.stringify({pid:process.pid,token:a,createdAt:Date.now()}),{flag:"wx",mode:384});}catch(u){throw await rm(o,{recursive:!0,force:!0}).catch(()=>{}),u}break}catch(u){if($(u)!=="EEXIST")throw u;if(await ct(o)&&await Dr(o))continue;if(Date.now()>=d)throw new Error("timed out waiting for the credential store lock");await new Promise(A=>setTimeout(A,Tr));}try{return await r()}finally{await xr(o,s,a).catch(()=>{});}}async function ct(t){try{let e=await stat(t);try{let r=await readFile(join(t,"owner.json"),"utf8"),n=JSON.parse(r);return typeof n.pid=="number"&&!Nr(n.pid)}catch{return Date.now()-e.mtimeMs>=Or}}catch{return false}}async function Dr(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if($(n)==="EEXIST")return false;throw n}try{if(!await ct(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(i){if($(i)==="ENOENT")return !0;throw i}return await rm(n,{recursive:!0,force:!0}),!0}finally{await r.close().catch(()=>{}),await rm(e,{force:true}).catch(()=>{});}}function Nr(t){try{return process.kill(t,0),!0}catch(e){return $(e)==="EPERM"}}async function xr(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if($(n)!=="ENOENT")throw n}}function $(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"?t.code:void 0}async function te(t,e,r,n,i){if(await t.getPassword(e,r)!==n)throw new Error(`macOS Keychain ${i} write verification failed`)}function K(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function nt(t){let e=t instanceof Error?t.message:String(t);return e.includes("could not be found")||e.includes("The specified item could not be found")}function Lr(t,e){let r=t instanceof Error?t.message:String(t),n=r.includes(e)?r.split(e).join("[REDACTED]"):r,i=new Error(n),o=it(t,"code"),s=it(t,"exitCode");return o!==void 0&&Object.assign(i,{code:o}),s!==void 0&&Object.assign(i,{exitCode:s}),i}function it(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var ie=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;withLock(e){return R(this.path,"auth-session",e)}async load(){let e;try{e=await readFile(this.path,"utf8");}catch(r){throw r?.code==="ENOENT"?g("NOT_FOUND","load",r):_("load",r)}try{return I(e)}catch(r){throw m(r)?r:g("DECODE_FAILED","load",r)}}async save(e){let r=E(e),n=dirname(this.path);await mkdir(n,{recursive:true,mode:448});let i=join(n,`${randomBytes(8).toString("hex")}.tmp`);try{await writeFile(i,r,{mode:384}),await rename(i,this.path);}catch(o){throw await rm(i,{force:true}).catch(()=>{}),_("save",o)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await rm(this.path,{force:!0});}catch(e){throw _("delete",e)}}};function lt(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",b(t),`${b(e)}.json`)}function _(t,e){let r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return r.includes("permission denied")||r.includes("access denied")?g("PERMISSION_DENIED",t,e):g("BACKEND_UNAVAILABLE",t,e)}var Pe=class extends Error{code;exitCode;stderr;constructor(e,r,n){let i=n.trim();super(`${e} exited with code ${r??"unknown"}${i?`: ${i}`:""}`),this.name="CommandExecutionError",this.code=r,this.exitCode=r,this.stderr=n;}};function ht(t,e,r,n=process.env){return new Promise((i,o)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),a=[],d=[],u=false,A=l=>{u||(u=true,o(l));};s.stdout.on("data",l=>a.push(Buffer.from(l))),s.stderr.on("data",l=>d.push(Buffer.from(l))),s.once("error",A),s.stdin.once("error",A),s.once("close",l=>{if(u)return;u=true;let f={stdout:Buffer.concat(a).toString(),stderr:Buffer.concat(d).toString()};if(l===0){i(f);return}o(new Pe(t,l,f.stderr));}),s.stdin.end(r);})}var jr=promisify(execFile),zr="Software\\BytedAuthClient\\keychain",oe=class{constructor(e,r,n=qr){this.serviceName=e;this.account=r;this.runner=n;K(e,r);}serviceName;account;runner;withLock(e){return R(this.serviceName,`${this.account}.auth-session`,e)}async load(){let e;try{e=await this.runner.get(this.serviceName,this.account);}catch(r){throw _("load",r)}if(e===void 0)throw g("NOT_FOUND","load",new Error("auth record not found"));try{return I(e)}catch(r){throw m(r)?r:g("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,E(e));}catch(r){throw _("save",r)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.delete(this.serviceName,this.account);}catch(e){throw _("delete",e)}}},qr={async get(t,e){let r=Buffer.from(pt(t,e)).toString("base64"),n=`
20
20
  $ErrorActionPreference = 'Stop'
21
21
  Add-Type -AssemblyName System.Security
22
- $path = '${I(Pe(t))}'
23
- $name = '${I(ve(e))}'
24
- if (-not (Test-Path $path)) { exit 3 }
25
- $item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
26
- if ($null -eq $item -or $null -eq $item.$name) { exit 3 }
27
- $cipher = [Convert]::FromBase64String($item.$name)
22
+ $path = '${D(Oe(t))}'
23
+ $name = '${D(Te(e))}'
24
+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path)
25
+ if ($null -eq $key) { exit 3 }
26
+ try { $value = $key.GetValue($name, $null) } finally { $key.Dispose() }
27
+ if ($null -eq $value) { exit 3 }
28
+ $cipher = [Convert]::FromBase64String($value)
28
29
  $entropy = [Convert]::FromBase64String('${r}')
29
30
  $plain = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
30
31
  [Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))
31
- `,i=await Se(n);return i.missing?void 0:i.stdout},async set(t,e,r){let n=Buffer.from(r,"utf8").toString("base64");await Se(Fr(t,e),n);},async delete(t,e){let r=`
32
+ exit 0
33
+ `,i=await ve(n);return i.missing?void 0:i.stdout},async set(t,e,r){let n=Buffer.from(r,"utf8").toString("base64");await ve(Wr(t,e),n);},async delete(t,e){let r=`
32
34
  $ErrorActionPreference = 'Stop'
33
- $path = '${I(Pe(t))}'
34
- $name = '${I(ve(e))}'
35
- if (Test-Path $path) { Remove-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue }
36
- `;await Se(r);}};function Kr(t){return `${$r}\\${N(t)}`}function Pe(t){return `HKCU:\\${Kr(t)}`}function ve(t){return Buffer.from(t,"utf8").toString("base64url")}function it(t,e){return Buffer.concat([Buffer.from(t,"utf8"),Buffer.from([0]),Buffer.from(e,"utf8")])}function Fr(t,e){let r=Buffer.from(it(t,e)).toString("base64");return `
35
+ $path = '${D(Oe(t))}'
36
+ $name = '${D(Te(e))}'
37
+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path, $true)
38
+ if ($null -ne $key) {
39
+ try { $key.DeleteValue($name, $false) } finally { $key.Dispose() }
40
+ }
41
+ exit 0
42
+ `;await ve(r);}};function Oe(t){return `${zr}\\${b(t)}`}function Xr(t){return `HKCU:\\${Oe(t)}`}function Te(t){return Buffer.from(t,"utf8").toString("base64url")}function pt(t,e){return Buffer.concat([Buffer.from(t,"utf8"),Buffer.from([0]),Buffer.from(e,"utf8")])}function Wr(t,e){let r=Buffer.from(pt(t,e)).toString("base64");return `
37
43
  $ErrorActionPreference = 'Stop'
38
44
  Add-Type -AssemblyName System.Security
39
- $path = '${I(Pe(t))}'
40
- $name = '${I(ve(e))}'
45
+ $path = '${D(Xr(t))}'
46
+ $name = '${D(Te(e))}'
41
47
  New-Item -Path $path -Force | Out-Null
42
48
  $encodedValue = [Console]::In.ReadToEnd()
43
49
  $plain = [Convert]::FromBase64String($encodedValue)
@@ -45,51 +51,60 @@ $entropy = [Convert]::FromBase64String('${r}')
45
51
  $cipher = [Security.Cryptography.ProtectedData]::Protect($plain, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
46
52
  $encoded = [Convert]::ToBase64String($cipher)
47
53
  Set-ItemProperty -Path $path -Name $name -Value $encoded
48
- `}async function Se(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await Ur("powershell.exe",r):await ot("powershell.exe",r,e);return {stdout:n,missing:!1}}catch(r){if(r?.code===3||r?.exitCode===3)return {stdout:"",missing:true};throw r}}function I(t){return t.replace(/'/g,"''")}var Mr="byted_cli_user_token";function ne(t,e=Mr,r=process.platform){switch(U(t,e),r){case "darwin":return new x(t,e);case "win32":return new re(t,e);default:return new Ce(new x(t,e),new Z(Xe(t,e)),n=>_e(t,e,n))}}var Ce=class{constructor(e,r,n=async i=>i()){this.primary=e;this.legacy=r;this.runExclusive=n;}primary;legacy;runExclusive;async load(){return this.runExclusive(()=>this.loadExclusive())}async save(e){await this.runExclusive(async()=>{await this.persistAndVerify(e),await this.legacy.delete();});}async updateUserInfo(e){await this.runExclusive(async()=>{let r=await this.loadExclusive();r.userInfo=e,await this.persistAndVerify(r),await this.legacy.delete();});}async delete(){await this.runExclusive(async()=>{let e;for(let r of [this.primary,this.legacy])try{await r.delete();}catch(n){e??=n;}if(e!==void 0)throw e});}async loadExclusive(){try{let r=await this.primary.load();return await this.legacy.delete(),r}catch(r){if(!m(r,"NOT_FOUND"))throw r}let e=await this.legacy.load();return await this.persistAndVerify(e),await this.legacy.delete(),e}async persistAndVerify(e){await this.primary.save(e);let r=await this.primary.load();if(_(r)!==_(e))throw await this.primary.delete().catch(()=>{}),h("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var st={NOT_LOGGED_IN:"authsdk: not logged in",LOGIN_PENDING:"authsdk: login pending",LOGIN_DENIED:"authsdk: login denied",LOGIN_EXPIRED:"authsdk: login expired",TOKEN_EXPIRED:"authsdk: token expired",REFRESH_FAILED:"authsdk: refresh failed",SIGN_FAILED:"authsdk: sign failed",STORE_UNAVAILABLE:"authsdk: store unavailable",PROTOCOL_ERROR:"authsdk: protocol error",INVALID_ARGUMENT:"authsdk: invalid argument"},g=class extends Error{code;cause;constructor(e,r=st[e],n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="AuthError",this.code=e,this.cause=n;}};function l(t,e){return new g(t,st[t],e)}var jr=createRequire(import.meta.url),zr="CN",$=3e3;function ut(){return {name:ct(at.hostname()||"unknown",128),os:en(process.platform),osVersion:ct(at.release()||"",64),architecture:tn(process.arch),cliVersion:rn(),region:qr()}}function qr(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(Oe(t.readMacOSLocale??Jr,void 0));else if(e==="win32"){let i=Xr(Oe(t.readWindowsRegion??Zr,void 0));if(i)return i}else e==="linux"&&n.push(...Qr(Oe(t.readLinuxLocales??Yr,[])));n.push(r.LC_ALL,r.LC_MESSAGES,r.LANG,r.LANGUAGE,t.intlLocale??Intl.DateTimeFormat().resolvedOptions().locale);for(let i of n){let o=Wr(i);if(o)return o}return zr}function Xr(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function Wr(t){if(!t)return;let e=t.trim(),r=e.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(.*)$/);if(r&&(e=r[1].trim()),e=e.replace(/^["']|["']$/g,""),e=e.split(":",1)[0].split(/[.@]/,1)[0].replaceAll("_","-"),!(!e||/^(?:C|POSIX)$/i.test(e)))try{let n=new Intl.Locale(e).region?.toUpperCase();return n&&/^[A-Z]{2}$/.test(n)?n:void 0}catch{return}}function Jr(){return dt("/usr/bin/defaults",["read","-g","AppleLocale"])}function Zr(){return dt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function Yr(){let t=[];for(let e of ["/etc/locale.conf","/etc/default/locale"])try{for(let r of readFileSync(e,"utf8").split(/\r?\n/)){let n=r.trim();/^(?:LC_ALL|LC_MESSAGES|LANG|LANGUAGE)=/.test(n)&&t.push(n);}}catch{}return t}function Qr(t){let e=["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"],r=[];for(let n of e)r.push(...t.filter(i=>i?.trim().startsWith(`${n}=`)));return r.push(...t.filter(n=>!n?.includes("="))),r}function dt(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Oe(t,e){try{return t()}catch{return e}}function en(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function tn(t){return t==="x64"?"x86_64":t}function rn(){for(let t of ["../../package.json","../../../package.json"])try{let e=jr(t);if(typeof e.version=="string")return e.version}catch{}return ""}function ct(t,e){return t.length>e?t.slice(0,e):t}var nn="/passport/open/refresh_token/",lt="Bearer ",Te=class{current=Promise.resolve();async run(e){let r=this.current,n;this.current=new Promise(i=>{n=i;}),await r;try{return await e()}finally{n();}}},oe=class{core;constructor(e,r={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=r.protocol??new j({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),i=r.signer??new W,o=r.store??ne(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:i,store:o,now:r.now??(()=>new Date),mutex:new Te,deviceReportUrl:new URL(B,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:on(e.deviceReportTimeoutMs)};}authenticator(){return new Ie(this.core)}authorizer(){return new ie(this.core)}},Ie=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let r=this.core.signer.generateDeviceKey(),n=await this.core.protocol.getDeviceCode({clientKey:this.core.clientKey,scopes:this.core.scopes,pubKey:r.PublicKeyBase64},e),i=new Date(this.core.now().getTime()+n.expiresInMs),o={clientKey:this.core.clientKey,deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,loginExpiresAt:i,deviceKey:r,scopes:[...this.core.scopes]};return await De(this.core.store,o),{deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,expiresAt:i}})}async checkLogin(e,r){let n=e.trim();if(!n)throw new Error("authsdk: device_code is required");return this.core.mutex.run(async()=>{let i=await ke(this.core.store);if(!i.deviceCode||!i.loginExpiresAt)throw l("NOT_LOGGED_IN");if(i.deviceCode!==n)throw l("INVALID_ARGUMENT",new Error("device_code does not match pending login state"));if(this.core.now().getTime()>=i.loginExpiresAt.getTime())throw await se(this.core.store),l("LOGIN_EXPIRED");let o;try{o=await this.core.protocol.checkDeviceCode({deviceCode:n},r);}catch(s){let c=sn(s);throw c.code==="LOGIN_EXPIRED"&&await se(this.core.store),c}return i.deviceCode=void 0,i.userCode=void 0,i.verificationUri=void 0,i.intervalMs=void 0,i.loginExpiresAt=void 0,i.accessToken=o.accessToken,o.refreshToken&&(i.refreshToken=o.refreshToken),i.tokenExpiresAt=new Date(this.core.now().getTime()+o.expiresInMs),await De(this.core.store,i),await pt(this.core,i,r),Ne(this.core.now(),i)})}authorizer(){return new ie(this.core)}},ie=class{constructor(e){this.core=e;}core;async state(e){return this.core.mutex.run(async()=>{try{let r=await this.ensureActiveRecord(0,e);return Ne(this.core.now(),r)}catch(r){if(r instanceof g&&r.code==="NOT_LOGGED_IN")return {loggedIn:false};throw r}})}async refresh(e=0,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(Math.max(0,e),r);return Ne(this.core.now(),n)})}async inject(e,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(0,r);if(!n.accessToken||!n.deviceKey)throw l("NOT_LOGGED_IN");ht(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await this.core.store.updateUserInfo(e);}catch(r){throw G(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await ke(this.core.store);return ft(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await this.core.store.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw G(e)}})}async ensureActiveRecord(e,r){let n=await ke(this.core.store);if(!n.accessToken)throw l("NOT_LOGGED_IN");let i=this.core.now();if(cn(i,n.tokenExpiresAt,e))return n;if(!n.refreshToken||!n.deviceKey)throw await se(this.core.store),l("NOT_LOGGED_IN");let o;try{o=this.core.signer.sign({method:"POST",urlPath:nn,signingMaterial:n.refreshToken},n.deviceKey);}catch(u){throw l("SIGN_FAILED",u)}let s,c=n.accessToken;try{s=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:n.refreshToken,pubKey:o.pubKey,reqSign:o.signature,reqTs:o.timestamp,reqNonce:o.nonce},r);}catch(u){throw an(u)?(await se(this.core.store),l("NOT_LOGGED_IN")):l("REFRESH_FAILED",u)}return n.accessToken=s.accessToken,s.refreshToken&&(n.refreshToken=s.refreshToken),n.tokenExpiresAt=new Date(this.core.now().getTime()+s.expiresInMs),await De(this.core.store,n),c!==n.accessToken&&await pt(this.core,n,r),n}};async function pt(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{ht(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=lt+e.accessToken;}catch{return}let i=new AbortController,o=()=>i.abort(r?.reason);r?.aborted?o():r?.addEventListener("abort",o,{once:true});let s,c=new Promise((u,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:ut()},i.signal),c]);}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",o);}}function ht(t,e,r){if(!e.accessToken||!e.deviceKey)throw l("NOT_LOGGED_IN");let n=new URL(String(r.url)),i=r.method.trim().toUpperCase(),o=n.pathname||"/",s;try{s=t.signer.sign({method:i,urlPath:o,signingMaterial:e.accessToken},e.deviceKey);}catch(c){throw l("SIGN_FAILED",c)}P(r,"Authorization",lt+e.accessToken),P(r,"X-Pub-Key",s.pubKey),P(r,"X-Req-Sign",s.signature),P(r,"X-Req-Ts",s.timestamp),P(r,"X-Req-Nonce",s.nonce),P(r,"X-Req-Method",i),P(r,"X-Req-Path",o);}function on(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):$}async function ke(t){try{return await t.load()}catch(e){throw G(e)}}async function De(t,e){try{await t.save(e);}catch(r){throw G(r)}}async function se(t){try{await t.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw G(e)}}function G(t){return m(t,"NOT_FOUND")?l("NOT_LOGGED_IN",t):l("STORE_UNAVAILABLE",t)}function sn(t){return C(t,"AUTHORIZATION_PENDING")?l("LOGIN_PENDING",t):C(t,"ACCESS_DENIED")?l("LOGIN_DENIED",t):C(t,"EXPIRED_TOKEN")?l("LOGIN_EXPIRED",t):l("PROTOCOL_ERROR",t)}function an(t){return C(t,"EXPIRED_TOKEN")||C(t,"INVALID_GRANT")}function cn(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Ne(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:ft(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function P(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function ft(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var gt=["pico_vibe_lab","pico_ai_sgs","user_info"],mt="https://user.picoxr.com",ln=/^ppe_[A-Za-z0-9_-]+$/,wt={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:mt,deviceReportTimeoutMs:$};function Le(t={}){let e=t.ppeHeader?pn(t.ppeHeader):void 0;return {...wt,scopes:Et(gt,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function pn(t){if(!ln.test(t))throw new TypeError("ppeHeader must match ppe_[A-Za-z0-9_-]+");return Object.freeze({"X-TT-Env":t,"X-Use-PPE":"1"})}function Et(t,e){let r=new Set;for(let n of [...t,...e]){let i=n.trim();i&&r.add(i);}return [...r]}var hn=365*24*60*60*1e3;function yt(t={},e={}){let r=Le(t),n=e.store??ne(r.storeServiceName),i=new oe(r,{...e,store:n});return {getStatus(o){return fn(n,o)},startLogin(o={}){return i.authenticator().newLoginFlow(o.signal)},resumeLogin(o,s){return i.authenticator().checkLogin(o,s)},ensureAuthenticated(o){return i.authorizer().refresh(0,o)},refresh(o){return i.authorizer().refresh(hn,o)},injectAuth(o,s){return i.authorizer().inject(o,s)},logout(){return i.authorizer().logout()}}}async function fn(t,e){e?.throwIfAborted();try{let r=await t.load(),n=Date.now();return {loggedIn:!!r.accessToken&&(r.tokenExpiresAt===void 0||n<r.tokenExpiresAt.getTime()),expiresAt:r.tokenExpiresAt,identity:gn(r.userInfo),scopes:r.scopes?[...r.scopes]:void 0}}catch(r){if(m(r,"NOT_FOUND"))return {loggedIn:false};throw l("STORE_UNAVAILABLE",r)}}function gn(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var mn=/^(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)$/i,wn=/(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)(["'\s:=]+)(?:Bearer\s+)?([^"'\s,}]+)/gi;function K(t,e,r){if(t.json){t.stdout(`${JSON.stringify(v(r))}
49
- `);return}for(let n of e)t.stdout(`${M(n)}
50
- `);}function F(t,e){let r=v(e);if(t.json){t.stderr(`${JSON.stringify({ok:false,...r})}
54
+ exit 0
55
+ `}async function ve(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await jr("powershell.exe",r):await ht("powershell.exe",r,e);return {stdout:n,missing:!1}}catch(r){if(r?.code===3||r?.exitCode===3)return {stdout:"",missing:true};throw r}}function D(t){return t.replace(/'/g,"''")}var Jr="byted_cli_user_token";function se(t,e=Jr,r=process.platform){switch(K(t,e),r){case "darwin":return new G(t,e);case "win32":return new oe(t,e);default:return new Ie(new G(t,e),new ie(lt(t,e)),n=>R(t,e,n),n=>R(t,`${e}.auth-session`,n))}}var Ie=class{constructor(e,r,n=async o=>o(),i){this.primary=e;this.legacy=r;this.runExclusive=n;this.withLock=i;}primary;legacy;runExclusive;withLock;async load(){return this.runExclusive(()=>this.loadExclusive())}async save(e){await this.runExclusive(async()=>{await this.persistAndVerify(e),await this.legacy.delete();});}async updateUserInfo(e){await this.runExclusive(async()=>{let r=await this.loadExclusive();r.userInfo=e,await this.persistAndVerify(r),await this.legacy.delete();});}async delete(){await this.runExclusive(async()=>{let e;for(let r of [this.primary,this.legacy])try{await r.delete();}catch(n){e??=n;}if(e!==void 0)throw e});}async loadExclusive(){try{let r=await this.primary.load();return await this.legacy.delete(),r}catch(r){if(!m(r,"NOT_FOUND"))throw r}let e=await this.legacy.load();return await this.persistAndVerify(e),await this.legacy.delete(),e}async persistAndVerify(e){await this.primary.save(e);let r=await this.primary.load();if(E(r)!==E(e))throw await this.primary.delete().catch(()=>{}),g("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var gt={NOT_LOGGED_IN:"authsdk: not logged in",LOGIN_PENDING:"authsdk: login pending",LOGIN_ALREADY_PENDING:"authsdk: a login request is already pending",LOGIN_NOT_PENDING:"authsdk: no pending login request",LOGIN_SUPERSEDED:"authsdk: login request was replaced",LOGIN_CONTEXT_MISMATCH:"authsdk: login request belongs to a different region or PPE environment",LOGIN_DENIED:"authsdk: login denied",LOGIN_EXPIRED:"authsdk: login expired",TOKEN_EXPIRED:"authsdk: token expired",REFRESH_FAILED:"authsdk: refresh failed",SIGN_FAILED:"authsdk: sign failed",STORE_UNAVAILABLE:"authsdk: store unavailable",PROTOCOL_ERROR:"authsdk: protocol error",INVALID_ARGUMENT:"authsdk: invalid argument"},p=class extends Error{code;cause;pendingLogin;constructor(e,r=gt[e],n,i){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="AuthError",this.code=e,this.cause=n,this.pendingLogin=i;}};function h(t,e){return new p(t,gt[t],e)}var en=createRequire(import.meta.url),tn="CN",M=3e3;function Et(){return {name:mt(ft.hostname()||"unknown",128),os:dn(process.platform),osVersion:mt(ft.release()||"",64),architecture:ln(process.arch),cliVersion:hn(),region:rn()}}function rn(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(ke(t.readMacOSLocale??sn,void 0));else if(e==="win32"){let i=nn(ke(t.readWindowsRegion??an,void 0));if(i)return i}else e==="linux"&&n.push(...un(ke(t.readLinuxLocales??cn,[])));n.push(r.LC_ALL,r.LC_MESSAGES,r.LANG,r.LANGUAGE,t.intlLocale??Intl.DateTimeFormat().resolvedOptions().locale);for(let i of n){let o=on(i);if(o)return o}return tn}function nn(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function on(t){if(!t)return;let e=t.trim(),r=e.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(.*)$/);if(r&&(e=r[1].trim()),e=e.replace(/^["']|["']$/g,""),e=e.split(":",1)[0].split(/[.@]/,1)[0].replaceAll("_","-"),!(!e||/^(?:C|POSIX)$/i.test(e)))try{let n=new Intl.Locale(e).region?.toUpperCase();return n&&/^[A-Z]{2}$/.test(n)?n:void 0}catch{return}}function sn(){return wt("/usr/bin/defaults",["read","-g","AppleLocale"])}function an(){return wt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function cn(){let t=[];for(let e of ["/etc/locale.conf","/etc/default/locale"])try{for(let r of readFileSync(e,"utf8").split(/\r?\n/)){let n=r.trim();/^(?:LC_ALL|LC_MESSAGES|LANG|LANGUAGE)=/.test(n)&&t.push(n);}}catch{}return t}function un(t){let e=["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"],r=[];for(let n of e)r.push(...t.filter(i=>i?.trim().startsWith(`${n}=`)));return r.push(...t.filter(n=>!n?.includes("="))),r}function wt(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function ke(t,e){try{return t()}catch{return e}}function dn(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function ln(t){return t==="x64"?"x86_64":t}function hn(){for(let t of ["../../package.json","../../../package.json"])try{let e=en(t);if(typeof e.version=="string")return e.version}catch{}return ""}function mt(t,e){return t.length>e?t.slice(0,e):t}var pn="/passport/open/refresh_token/",Rt="Bearer ",ce=class{current=Promise.resolve();async run(e){let r=this.current,n;this.current=new Promise(i=>{n=i;}),await r;try{return await e()}finally{n();}}},ue=class{core;constructor(e,r={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=r.protocol??new X({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),i=r.signer??new Z,o=r.store??se(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:i,store:o,now:r.now??(()=>new Date),mutex:new ce,deviceReportUrl:new URL(q,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:gn(e.deviceReportTimeoutMs),loginContext:{baseUrl:new URL(e.baseUrl).toString(),aid:e.aid||void 0,ppeHeader:Object.entries(e.customHttpHeaders??{}).find(([s])=>s.toLowerCase()==="x-tt-env")?.[1]}};}authenticator(){return new Ne(this.core)}authorizer(){return new de(this.core)}},Ne=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let r=await De(this.core.store,async()=>{let a=await ae(this.core.store);return yt(a,this.core.now()),a?E(a):void 0}),n=this.core.signer.generateDeviceKey(),i=await this.core.protocol.getDeviceCode({clientKey:this.core.clientKey,scopes:this.core.scopes,pubKey:n.PublicKeyBase64},e).catch(a=>{throw At(a)}),o=new Date(this.core.now().getTime()+i.expiresInMs),s={clientKey:this.core.clientKey,deviceCode:i.deviceCode,userCode:i.userCode,verificationUri:i.verificationUri,intervalMs:i.intervalMs,loginExpiresAt:o,loginContext:{...this.core.loginContext},deviceKey:n,scopes:[...this.core.scopes]};return await De(this.core.store,async()=>{let a=await ae(this.core.store);if(yt(a,this.core.now()),(a?E(a):void 0)!==r)throw h("LOGIN_SUPERSEDED");await this.core.store.save(s);}),{deviceCode:i.deviceCode,userCode:i.userCode,verificationUri:i.verificationUri,intervalMs:i.intervalMs,expiresAt:o}})}async checkLogin(e,r){let n=e.trim();if(!n)throw new Error("authsdk: device_code is required");return this.core.mutex.run(async()=>{let i=await xe(this.core.store);return this.checkLoginRecord(i,n,r)})}async checkPendingLogin(e){return this.core.mutex.run(async()=>{let r=await ae(this.core.store);if(!r?.deviceCode||!r.loginExpiresAt)throw h("LOGIN_NOT_PENDING");return this.checkLoginRecord(r,r.deviceCode,e)})}async checkLoginRecord(e,r,n){let i=E(e);if(!e.deviceCode||!e.loginExpiresAt)throw h("NOT_LOGGED_IN");if(e.deviceCode!==r)throw h("LOGIN_SUPERSEDED");if(e.loginContext&&(e.loginContext.baseUrl!==this.core.loginContext.baseUrl||e.loginContext.aid!==this.core.loginContext.aid||e.loginContext.ppeHeader!==this.core.loginContext.ppeHeader))throw h("LOGIN_CONTEXT_MISMATCH");if(this.core.now().getTime()>=e.loginExpiresAt.getTime())throw await le(this.core.store,i,"LOGIN_SUPERSEDED"),h("LOGIN_EXPIRED");let o;try{o=await this.core.protocol.checkDeviceCode({deviceCode:r},n);}catch(s){let a=At(s);throw a.code==="LOGIN_PENDING"&&(await De(this.core.store,()=>be(this.core.store,i,"LOGIN_SUPERSEDED")),e.verificationUri&&e.loginExpiresAt)?new p("LOGIN_PENDING",void 0,s,{verificationUri:e.verificationUri,expiresAt:new Date(e.loginExpiresAt)}):((a.code==="LOGIN_EXPIRED"||a.code==="LOGIN_DENIED")&&await le(this.core.store,i,"LOGIN_SUPERSEDED"),a)}return e.deviceCode=void 0,e.userCode=void 0,e.verificationUri=void 0,e.intervalMs=void 0,e.loginExpiresAt=void 0,e.loginContext=void 0,e.accessToken=o.accessToken,o.refreshToken&&(e.refreshToken=o.refreshToken),e.tokenExpiresAt=new Date(this.core.now().getTime()+o.expiresInMs),await Pt(this.core.store,e,i,"LOGIN_SUPERSEDED"),await St(this.core,e,n),Le(this.core.now(),e)}authorizer(){return new de(this.core)}},de=class{constructor(e){this.core=e;}core;async state(e){return this.core.mutex.run(async()=>{try{let r=await this.ensureActiveRecord(0,e);return Le(this.core.now(),r)}catch(r){if(r instanceof p&&r.code==="NOT_LOGGED_IN")return {loggedIn:false};throw r}})}async refresh(e=0,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(Math.max(0,e),r);return Le(this.core.now(),n)})}async inject(e,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(0,r);if(!n.accessToken||!n.deviceKey)throw h("NOT_LOGGED_IN");Ct(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await F(this.core.store,()=>this.core.store.updateUserInfo(e));}catch(r){throw v(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await xe(this.core.store);return vt(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await F(this.core.store,()=>this.core.store.delete());}catch(e){if(!m(e,"NOT_FOUND"))throw v(e)}})}async ensureActiveRecord(e,r){let n=await xe(this.core.store),i=E(n);if(!n.accessToken)throw h("NOT_LOGGED_IN");let o=this.core.now();if(mn(o,n.tokenExpiresAt,e))return n;if(!n.refreshToken||!n.deviceKey)throw await le(this.core.store,i),h("NOT_LOGGED_IN");let s;try{s=this.core.signer.sign({method:"POST",urlPath:pn,signingMaterial:n.refreshToken},n.deviceKey);}catch(u){throw h("SIGN_FAILED",u)}let a,d=n.accessToken;try{a=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:n.refreshToken,pubKey:s.pubKey,reqSign:s.signature,reqTs:s.timestamp,reqNonce:s.nonce},r);}catch(u){throw fn(u)?(await le(this.core.store,i),h("NOT_LOGGED_IN")):h("REFRESH_FAILED",u)}return n.accessToken=a.accessToken,a.refreshToken&&(n.refreshToken=a.refreshToken),n.tokenExpiresAt=new Date(this.core.now().getTime()+a.expiresInMs),await Pt(this.core.store,n,i),d!==n.accessToken&&await St(this.core,n,r),n}};async function St(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{Ct(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=Rt+e.accessToken;}catch{return}let i=new AbortController,o=()=>i.abort(r?.reason);r?.aborted?o():r?.addEventListener("abort",o,{once:true});let s,a=new Promise((d,u)=>{s=setTimeout(()=>{i.abort(),u(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:Et()},i.signal),a]);}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",o);}}function Ct(t,e,r){if(!e.accessToken||!e.deviceKey)throw h("NOT_LOGGED_IN");let n=new URL(String(r.url)),i=r.method.trim().toUpperCase(),o=n.pathname||"/",s;try{s=t.signer.sign({method:i,urlPath:o,signingMaterial:e.accessToken},e.deviceKey);}catch(a){throw h("SIGN_FAILED",a)}P(r,"Authorization",Rt+e.accessToken),P(r,"X-Pub-Key",s.pubKey),P(r,"X-Req-Sign",s.signature),P(r,"X-Req-Ts",s.timestamp),P(r,"X-Req-Nonce",s.nonce),P(r,"X-Req-Method",i),P(r,"X-Req-Path",o);}function gn(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):M}async function xe(t){try{return await t.load()}catch(e){throw v(e)}}async function ae(t){try{return await t.load()}catch(e){if(m(e,"NOT_FOUND"))return;throw v(e)}}function yt(t,e){if(t?.deviceCode&&t.loginExpiresAt&&e.getTime()<t.loginExpiresAt.getTime())throw h("LOGIN_ALREADY_PENDING")}async function De(t,e){try{return await F(t,e)}catch(r){throw r instanceof p?r:v(r)}}async function Pt(t,e,r,n="NOT_LOGGED_IN"){try{await F(t,async()=>{r!==void 0&&await be(t,r,n),await t.save(e);});}catch(i){throw i instanceof p?i:v(i)}}async function le(t,e,r="NOT_LOGGED_IN"){try{await F(t,async()=>{await be(t,e,r),await t.delete();});}catch(n){if(n instanceof p)throw n;if(!m(n,"NOT_FOUND"))throw v(n)}}async function be(t,e,r="NOT_LOGGED_IN"){let n=await ae(t);if(!n||E(n)!==e)throw h(r)}var _t=new WeakMap;async function F(t,e){if(t.withLock)return t.withLock(e);let r=_t.get(t);return r||(r=new ce,_t.set(t,r)),r.run(e)}function v(t){return m(t,"NOT_FOUND")?h("NOT_LOGGED_IN",t):h("STORE_UNAVAILABLE",t)}function At(t){return T(t,"AUTHORIZATION_PENDING")?h("LOGIN_PENDING",t):T(t,"ACCESS_DENIED")?h("LOGIN_DENIED",t):T(t,"EXPIRED_TOKEN")?h("LOGIN_EXPIRED",t):h("PROTOCOL_ERROR",t)}function fn(t){return T(t,"EXPIRED_TOKEN")||T(t,"INVALID_GRANT")}function mn(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Le(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:vt(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function P(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function vt(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var Ot=["pico_vibe_lab","pico_ai_sgs","user_info"],Tt="https://user.picoxr.com",yn=/^ppe_[A-Za-z0-9_-]+$/,It={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:Tt,deviceReportTimeoutMs:M};function Ue(t={}){let e=t.ppeHeader?_n(t.ppeHeader):void 0;return {...It,scopes:kt(Ot,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function _n(t){if(!yn.test(t))throw new TypeError("ppeHeader must match ppe_[A-Za-z0-9_-]+");return Object.freeze({"X-TT-Env":t,"X-Use-PPE":"1"})}function kt(t,e){let r=new Set;for(let n of [...t,...e]){let i=n.trim();i&&r.add(i);}return [...r]}var An=365*24*60*60*1e3;function Dt(t={},e={}){let r=Ue(t),n=e.store??se(r.storeServiceName),i=new ue(r,{...e,store:n});return {getStatus(o){return Rn(n,e.now??(()=>new Date),o)},startLogin(o={}){return i.authenticator().newLoginFlow(o.signal)},resumeLogin(o,s){return i.authenticator().checkLogin(o,s)},resumePendingLogin(o){return i.authenticator().checkPendingLogin(o)},ensureAuthenticated(o){return i.authorizer().refresh(0,o)},refresh(o){return i.authorizer().refresh(An,o)},injectAuth(o,s){return i.authorizer().inject(o,s)},logout(){return i.authorizer().logout()}}}async function Rn(t,e,r){r?.throwIfAborted();try{let n=await t.load(),i=e().getTime();return {loggedIn:!!n.accessToken&&(n.tokenExpiresAt===void 0||i<n.tokenExpiresAt.getTime()),expiresAt:n.tokenExpiresAt,identity:Sn(n.userInfo),scopes:n.scopes?[...n.scopes]:void 0,...n.deviceCode&&n.loginExpiresAt?{pending:i<n.loginExpiresAt.getTime(),loginExpiresAt:new Date(n.loginExpiresAt)}:{}}}catch(n){if(m(n,"NOT_FOUND"))return {loggedIn:false};throw h("STORE_UNAVAILABLE",n)}}function Sn(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var Cn=/^(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)$/i,Pn=/(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)(["'\s:=]+)(?:Bearer\s+)?([^"'\s,}]+)/gi;function H(t,e,r){if(t.json){t.stdout(`${JSON.stringify(O(r))}
56
+ `);return}for(let n of e)t.stdout(`${N(n)}
57
+ `);}function V(t,e){let r=O(e);if(t.json){t.stderr(`${JSON.stringify({ok:false,...r})}
51
58
  `);return}t.stderr(`error=${r.code}
52
59
  `),t.stderr(`message=${r.message}
53
60
  `),t.stderr(`recoverable=${r.recoverable}
54
61
  `),t.stderr(`action=${r.action}
55
- `);}function At(t,e,r={}){let n=v({event:e,...r});if(t.json){t.stderr(`${JSON.stringify({ok:true,verbose:n})}
62
+ `),r.stage&&t.stderr(`stage=${r.stage}
63
+ `);}function Nt(t,e,r={}){let n=O({event:e,...r});if(t.json){t.stderr(`${JSON.stringify({ok:true,verbose:n})}
56
64
  `);return}let i=Object.entries(n).map(([o,s])=>`${o}=${String(s)}`).join(" ");t.stderr(`verbose ${i}
57
- `);}function v(t){if(Array.isArray(t))return t.map(e=>v(e));if(t instanceof Date)return t.toISOString();if(t&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=mn.test(r)?"[REDACTED]":v(n);return e}return typeof t=="string"?M(t):t}function M(t){return t.replace(/("(?:access_token|refresh_token|accessToken|refreshToken|device_key|deviceKey|PrivateKeyBase64|privateKey|Authorization(?:-act)?|X-Req-Sign|reqSign|signature)"\s*:\s*)\{[^}]*\}/gi,'$1"[REDACTED]"').replace(/("(?:access_token|refresh_token|accessToken|refreshToken|device_key|deviceKey|PrivateKeyBase64|privateKey|Authorization(?:-act)?|X-Req-Sign|reqSign|signature)"\s*:\s*")([^"]*)(")/gi,"$1[REDACTED]$3").replace(wn,(e,r,n)=>`${r}${n}[REDACTED]`).replace(/([?&](?:access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|x-req-sign)=)([^&#\s]+)/gi,(e,r)=>`${r}[REDACTED]`)}var An=1e3,_n=12e4,St=4,Pt=2,Rn=3,_t=5,be=6,Sn=7,Pn=8,de={NOT_LOGGED_IN:{message:"You are not signed in.",action:"Run pico-auth-cli-cn login.",exitCode:Rn},LOGIN_PENDING:{message:"Authorization is not complete yet.",action:"Complete browser authorization, then rerun pico-auth-cli-cn login --resume <device_code>.",exitCode:St},LOGIN_DENIED:{message:"Authorization was denied.",action:"Restart login and approve the PICO authorization request.",exitCode:Pn},LOGIN_EXPIRED:{message:"The sign-in request has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:_t},TOKEN_EXPIRED:{message:"The session has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:_t},REFRESH_FAILED:{message:"The session could not be refreshed.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:be},SIGN_FAILED:{message:"The request could not be signed.",action:"Contact the pico-auth-cli-cn maintainer with the sanitized error details.",exitCode:1},STORE_UNAVAILABLE:{message:"The local credential store is unavailable.",action:"Check local credential store permissions, then run pico-auth-cli-cn status. Do not refresh or logout while storage access is unavailable.",exitCode:Sn},PROTOCOL_ERROR:{message:"The PICO authentication service returned an unexpected response.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:be},INVALID_ARGUMENT:{message:"The command contains an invalid argument.",action:"Run pico-auth-cli-cn --help or the subcommand help and retry with valid arguments.",exitCode:Pt}};async function vt(t,e={}){let r=e.stdout??(o=>process.stdout.write(o)),n=e.stderr??(o=>process.stderr.write(o)),i={json:t.includes("--json"),stdout:r,stderr:n};try{let o=Gn(t);if(i.json=o.global.json,!o.command||o.command==="--help"||o.command==="-h")return zn(r),0;if(o.command==="--version"||o.command==="-v")return r(`${(e.readVersion??Xn)()}
58
- `),0;let s=e.createClient??yt;switch(o.command){case "login":return ae(o.args)?(r(`${Ot()}
59
- `),0):await vn(o.args,o.global,s,i,e);case "status":return ae(o.args)?(r(`Usage:
65
+ `);}function O(t){if(Array.isArray(t))return t.map(e=>O(e));if(t instanceof Date)return t.toISOString();if(t&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=Cn.test(r)?"[REDACTED]":O(n);return e}return typeof t=="string"?N(t):t}function N(t){return t.replace(/("(?:access_token|refresh_token|accessToken|refreshToken|device_key|deviceKey|PrivateKeyBase64|privateKey|Authorization(?:-act)?|X-Req-Sign|reqSign|signature)"\s*:\s*)\{[^}]*\}/gi,'$1"[REDACTED]"').replace(/("(?:access_token|refresh_token|accessToken|refreshToken|device_key|deviceKey|PrivateKeyBase64|privateKey|Authorization(?:-act)?|X-Req-Sign|reqSign|signature)"\s*:\s*")([^"]*)(")/gi,"$1[REDACTED]$3").replace(Pn,(e,r,n)=>`${r}${n}[REDACTED]`).replace(/([?&](?:access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|x-req-sign)=)([^&#\s]+)/gi,(e,r)=>`${r}[REDACTED]`)}var Tn=1e3,In=12e4,Me=4,Fe=2,xt=3,Ge=5,He=6,kn=7,Dn=8,fe={NOT_LOGGED_IN:{message:"You are not signed in.",action:"Run pico-auth-cli-cn login.",exitCode:xt},LOGIN_PENDING:{message:"Authorization is not complete yet.",action:"Complete browser authorization, then rerun pico-auth-cli-cn login --resume <device_code>.",exitCode:Me},LOGIN_ALREADY_PENDING:{message:"A sign-in request is already pending. It has been preserved.",action:"Complete the existing browser authorization, then run pico-auth-cli-cn login --resume-pending.",exitCode:Me},LOGIN_NOT_PENDING:{message:"There is no pending sign-in request to resume.",action:"Run pico-auth-cli-cn status, then start login if you are not signed in.",exitCode:xt},LOGIN_SUPERSEDED:{message:"This sign-in request no longer matches the local login state.",action:"Run pico-auth-cli-cn status. If a request is pending, continue it with login --resume-pending.",exitCode:Ge},LOGIN_CONTEXT_MISMATCH:{message:"The pending sign-in request belongs to a different region or PPE environment. It has been preserved.",action:"Resume with the same region and --ppe_header options used to create the request. Check status before starting another login.",exitCode:Fe},LOGIN_DENIED:{message:"Authorization was denied.",action:"Restart login and approve the PICO authorization request.",exitCode:Dn},LOGIN_EXPIRED:{message:"The sign-in request has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:Ge},TOKEN_EXPIRED:{message:"The session has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:Ge},REFRESH_FAILED:{message:"The session could not be refreshed.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:He},SIGN_FAILED:{message:"The request could not be signed.",action:"Contact the pico-auth-cli-cn maintainer with the sanitized error details.",exitCode:1},STORE_UNAVAILABLE:{message:"The local credential store is unavailable.",action:"Check local credential store permissions, then run pico-auth-cli-cn status. Do not refresh or logout while storage access is unavailable.",exitCode:kn},PROTOCOL_ERROR:{message:"The PICO authentication service returned an unexpected response.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:He},INVALID_ARGUMENT:{message:"The command contains an invalid argument.",action:"Run pico-auth-cli-cn --help or the subcommand help and retry with valid arguments.",exitCode:Fe}};async function Lt(t,e={}){let r=e.stdout??(o=>process.stdout.write(o)),n=e.stderr??(o=>process.stderr.write(o)),i={json:t.includes("--json"),stdout:r,stderr:n,stage:"command_validation"};try{let o=jn(t);if(i.json=o.global.json,!o.command||o.command==="--help"||o.command==="-h")return Qn(r),0;if(o.command==="--version"||o.command==="-v")return r(`${(e.readVersion??ti)()}
66
+ `),0;let s=e.createClient??Dt;switch(o.command){case "login":return he(o.args)?(r(`${bt()}
67
+ `),0):await Nn(o.args,o.global,s,i,e);case "status":return he(o.args)?(r(`Usage:
60
68
  pico-auth-cli-cn status [--json]
61
- `),0):await Cn(o.args,o.global,s,i);case "refresh":return ae(o.args)?(r(`${qn()}
62
- `),0):await On(o.args,o.global,s,i);case "logout":return ae(o.args)?(r(`Usage:
69
+ `),0):await xn(o.args,o.global,s,i);case "refresh":return he(o.args)?(r(`${ei()}
70
+ `),0):await Ln(o.args,o.global,s,i);case "logout":return he(o.args)?(r(`Usage:
63
71
  pico-auth-cli-cn logout [--json]
64
- `),0):await Tn(o.args,o.global,s,i);default:throw new w(`unknown command: ${o.command}`)}}catch(o){return o instanceof le?(xn(i),St):o instanceof pe?(F(i,ce("LOGIN_TIMEOUT",o.message)),be):o instanceof w?(F(i,ce("INVALID_ARGUMENT",o.message)),Pt):o instanceof g?(F(i,ce(o.code,Vn(o.code))),Mn(o)):(F(i,ce("UNKNOWN","An unexpected error occurred.")),1)}}async function vn(t,e,r,n,i){let o=Kn(t),s=r({scopes:o.scopes,ppeHeader:e.ppeHeader});if(o.resume){let p=await In(s,o.resume);return Rt(n,"login_resumed",p),0}let c=await s.getStatus();if(c.loggedIn&&!o.force)return ue(e,n,"login_existing_state"),Ln(n,c),0;o.force&&(ue(e,n,"login_force_clear"),await s.logout());let u=await s.startLogin();if(Ct(u.verificationUri),ue(e,n,"login_started",{verification_uri:u.verificationUri,expires_at:u.expiresAt}),o.noWait)return Dn(n,u,e.ppeHeader),0;n.json||n.stdout(`Opening your browser to sign in to PICO...
65
- `);let d=await Un(u.verificationUri,e,n,i.openBrowser);bn(n,u,d);let A=await kn(s,u,o.timeoutMs,i.sleep??jn,i.now??(()=>new Date));return Rt(n,"authenticated",A),0}async function Cn(t,e,r,n){Ue("status",t);let o=await r({ppeHeader:e.ppeHeader}).getStatus();return he(n,"status",o),0}async function On(t,e,r,n){Ue("refresh",t);let i=r({ppeHeader:e.ppeHeader});try{let o=await i.refresh();return he(n,"refreshed",o),0}catch(o){throw o instanceof g&&o.code==="NOT_LOGGED_IN"&&await i.logout(),o}}async function Tn(t,e,r,n){return Ue("logout",t),await r({ppeHeader:e.ppeHeader}).logout(),K(n,["Signed out successfully."],{ok:true,loggedOut:true}),0}async function In(t,e){try{return await t.resumeLogin(e)}catch(r){throw r instanceof g&&r.code==="LOGIN_PENDING"?new le:(r instanceof g&&r.code==="LOGIN_EXPIRED"&&await t.logout(),r)}}async function kn(t,e,r,n,i){let o=Math.min(i().getTime()+r,e.expiresAt.getTime());for(;i().getTime()<o;)try{return await t.resumeLogin(e.deviceCode)}catch(s){if(s instanceof g&&s.code==="LOGIN_PENDING"){await n(An);continue}throw s instanceof g&&s.code==="LOGIN_EXPIRED"&&await t.logout(),s}throw await t.logout(),new pe("Sign-in timed out. The local state for this attempt was cleared.")}function Dn(t,e,r){if(!t.json){t.stdout(`Sign-in request created. Open this page to sign in to PICO and authorize access:
66
- `),t.stdout(` ${M(e.verificationUri)}
72
+ `),0):await bn(o.args,o.global,s,i);default:throw new w(`unknown command: ${o.command}`)}}catch(o){return o instanceof B?(Fn(i,o.pendingLogin),Me):o instanceof me?(V(i,pe("LOGIN_TIMEOUT",o.message,i.stage)),He):o instanceof w?(V(i,pe("INVALID_ARGUMENT",o.message,i.stage)),Fe):o instanceof p?(V(i,pe(o.code,Wn(o.code),i.stage)),Xn(o)):(V(i,pe("UNKNOWN","An unexpected error occurred.",i.stage)),1)}}async function Nn(t,e,r,n,i){let o=zn(t),s=r({scopes:o.scopes,ppeHeader:e.ppeHeader});if(o.resume){n.stage="collect_authorization";let l=await Un(s,o.resume);return $e(n,"login_resumed",l),0}if(o.resumePending){n.stage="collect_authorization";try{let l=await s.resumePendingLogin();return $e(n,"login_resumed",l),0}catch(l){throw l instanceof p&&l.code==="LOGIN_PENDING"?new B(l.pendingLogin):l}}n.stage="read_local_state";let a=await s.getStatus();if(a.loggedIn&&!o.force)return ge(e,n,"login_existing_state"),Mn(n,a),0;o.force&&(ge(e,n,"login_force_clear"),await s.logout()),n.stage="create_login";let d=await s.startLogin();if(Ve(d.verificationUri),ge(e,n,"login_started",{verification_uri:d.verificationUri,expires_at:d.expiresAt}),o.noWait)return $n(n,d,e.ppeHeader),0;n.json||n.stdout(`Opening your browser to sign in to PICO...
73
+ `);let u=await Vn(d.verificationUri,e,n,i.openBrowser);Hn(n,d,u),n.stage="await_authorization";let A=await Gn(s,d,o.timeoutMs,i.sleep??Zn,i.now??(()=>new Date));return $e(n,"authenticated",A),0}async function xn(t,e,r,n){Be("status",t),n.stage="read_local_state";let o=await r({ppeHeader:e.ppeHeader}).getStatus();return Ee(n,"status",o),0}async function Ln(t,e,r,n){Be("refresh",t),n.stage="refresh_session";let o=await r({ppeHeader:e.ppeHeader}).refresh();return Ee(n,"refreshed",o),0}async function bn(t,e,r,n){return Be("logout",t),n.stage="clear_local_state",await r({ppeHeader:e.ppeHeader}).logout(),H(n,["Signed out successfully."],{ok:true,loggedOut:true}),0}async function Un(t,e){try{return await t.resumeLogin(e)}catch(r){throw r instanceof p&&r.code==="LOGIN_PENDING"?new B(r.pendingLogin):r}}async function Gn(t,e,r,n,i){let o=Math.min(i().getTime()+r,e.expiresAt.getTime());for(;i().getTime()<o;)try{return await t.resumeLogin(e.deviceCode)}catch(s){if(s instanceof p&&s.code==="LOGIN_PENDING"){await n(Tn);continue}throw s}throw i().getTime()>=e.expiresAt.getTime()?new p("LOGIN_EXPIRED"):new me("Waiting for authorization timed out. The pending sign-in request was preserved.")}function $n(t,e,r){if(!t.json){t.stdout(`Sign-in request created. Open this page to sign in to PICO and authorize access:
74
+ `),t.stdout(` ${N(e.verificationUri)}
67
75
  `),t.stdout(`Sign-in request expires at: ${e.expiresAt.toISOString()}
68
76
  `),t.stdout(`After completing authorization in your browser, run:
69
77
  `);let n=r?` --ppe_header=${r}`:"";t.stdout(` pico-auth-cli-cn${n} login --resume '${e.deviceCode}'
70
- `);return}K(t,[`device_code=${e.deviceCode}`,`verification_uri=${e.verificationUri}`,`expires_at=${e.expiresAt.toISOString()}`],{ok:true,device_code:e.deviceCode,user_code:e.userCode,verification_uri:e.verificationUri,expires_at:e.expiresAt});}function he(t,e,r){if(!t.json){if(e==="status"){Nn(t,r);return}if(e==="refreshed"){t.stdout(`Session refreshed successfully.
71
- `);return}}let n={ok:true,status:e,authenticated:r.loggedIn},i=[`status=${e}`,`authenticated=${r.loggedIn}`];r.identity!==void 0&&(n.identity=r.identity),r.scopes!==void 0&&(n.scopes=r.scopes,i.push(`scopes=${r.scopes.join(",")}`)),r.expiresAt&&(n.expires_at=r.expiresAt,i.push(`expires_at=${r.expiresAt.toISOString()}`)),r.loggedIn||(n.reason=r.expiresAt?"expired":"not_logged_in",i.push(`reason=${n.reason}`)),K(t,i,n);}function Nn(t,e){if(!e.loggedIn){t.stdout(e.expiresAt?`Status: Expired.
78
+ `);return}H(t,[`device_code=${e.deviceCode}`,`verification_uri=${e.verificationUri}`,`expires_at=${e.expiresAt.toISOString()}`],{ok:true,device_code:e.deviceCode,user_code:e.userCode,verification_uri:e.verificationUri,expires_at:e.expiresAt});}function Ee(t,e,r){if(!t.json){if(e==="status"){Kn(t,r);return}if(e==="refreshed"){t.stdout(`Session refreshed successfully.
79
+ `);return}}let n={ok:true,status:e,authenticated:r.loggedIn},i=[`status=${e}`,`authenticated=${r.loggedIn}`];r.identity!==void 0&&(n.identity=r.identity),r.scopes!==void 0&&(n.scopes=r.scopes,i.push(`scopes=${r.scopes.join(",")}`)),r.expiresAt&&(n.expires_at=r.expiresAt,i.push(`expires_at=${r.expiresAt.toISOString()}`)),r.loggedIn||(n.reason=r.pending?"authorization_pending":r.loginExpiresAt?"login_expired":r.expiresAt?"expired":"not_logged_in",i.push(`reason=${n.reason}`)),r.loginExpiresAt&&(n.pending=r.pending===true,n.expires_at=r.loginExpiresAt,n.recoverable=r.pending===true,n.action=r.pending?"Complete browser authorization, then run pico-auth-cli-cn login --resume-pending.":"Run pico-auth-cli-cn login to start a new sign-in request.",n.stage=r.pending?"await_authorization":"login_expired"),H(t,i,n);}function Kn(t,e){if(!e.loggedIn){if(e.loginExpiresAt){t.stdout(e.pending?`Status: Waiting for authorization.
80
+ `:`Status: Sign-in request expired.
81
+ `),t.stdout(`Request expires at: ${e.loginExpiresAt.toISOString()}
82
+ `),t.stdout(e.pending?`Complete browser authorization, then run pico-auth-cli-cn login --resume-pending.
83
+ `:`Run pico-auth-cli-cn login to start a new request.
84
+ `);return}t.stdout(e.expiresAt?`Status: Expired.
72
85
  `:`Status: Signed out.
73
86
  `);return}t.stdout(`Status: Signed in.
74
87
  `),e.expiresAt&&t.stdout(`Expires at: ${e.expiresAt.toISOString()}
75
88
  `),e.scopes?.length&&t.stdout(`Authorized scopes: ${e.scopes.join(", ")}
76
- `);}function Rt(t,e,r){if(t.json){he(t,e,r);return}t.stdout(`
89
+ `);}function $e(t,e,r){if(t.json){Ee(t,e,r);return}t.stdout(`
77
90
  Signed in successfully.
78
- `);}function Ln(t,e){if(t.json){he(t,"already_authenticated",e);return}t.stdout(`You are already signed in.
91
+ `);}function Mn(t,e){if(t.json){Ee(t,"already_authenticated",e);return}t.stdout(`You are already signed in.
79
92
  `),t.stdout(`To switch accounts, run pico-auth-cli-cn login --force.
80
- `);}function xn(t){if(t.json){K(t,[],{ok:true,status:"pending"});return}t.stdout(`Authorization is not complete yet. Finish it in your browser, then run the same login --resume command again.
81
- `);}function bn(t,e,r){let n={ok:true,status:"login_started",verification_uri:e.verificationUri,user_code:e.userCode,expires_at:e.expiresAt.toISOString()};if(t.json){t.stderr(`${JSON.stringify(v(n))}
93
+ `);}function Fn(t,e){let r;if(e)try{Ve(e.verificationUri),r=e.verificationUri;}catch{}if(t.json){H(t,[],{ok:true,status:"pending",recoverable:true,action:"Complete browser authorization, then resume the same request with login --resume-pending or its original --resume handle.",stage:"await_authorization",...r&&e?{verification_uri:r,expires_at:e.expiresAt}:{}});return}t.stdout(`Authorization is not complete yet. Finish it in your browser, then run the same login --resume command again.
94
+ `),r&&t.stdout(`Sign-in page: ${N(r)}
95
+ `);}function Hn(t,e,r){let n={ok:true,status:"login_started",verification_uri:e.verificationUri,user_code:e.userCode,expires_at:e.expiresAt.toISOString()};if(t.json){t.stderr(`${JSON.stringify(O(n))}
82
96
  `);return}r?t.stdout(`The PICO sign-in page is open in your default browser.
83
97
  `):t.stdout(`We couldn't open your browser automatically. Open the sign-in page below.
84
98
  `),t.stdout(`Complete sign-in and authorization in your browser, then return here. The CLI will continue automatically.
85
- `),t.stdout(`Sign-in page: ${M(e.verificationUri)}
99
+ `),t.stdout(`Sign-in page: ${N(e.verificationUri)}
86
100
  `),t.stdout(`Waiting for authorization. Keep this window open...
87
- `);}async function Un(t,e,r,n){Ct(t);try{return n?(await n(t),!0):(await $n(t),!0)}catch{return ue(e,r,"browser_open_failed",{message:"The browser could not be opened automatically.",verification_uri:t}),false}}async function $n(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];await new Promise((n,i)=>{let o=spawn(e,r,{stdio:"ignore",detached:true});o.once("error",i),o.once("spawn",()=>{o.unref(),n();});});}function Ct(t){let e;try{e=new URL(t);}catch(r){throw new g("INVALID_ARGUMENT","The verification URI returned by the authentication service is invalid.",r)}if(e.protocol!=="https:")throw new g("INVALID_ARGUMENT","The verification URI returned by the authentication service must use HTTPS.")}function Gn(t){let e={json:false,verbose:false},r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(i==="--json"){e.json=true;continue}if(i==="--verbose"){e.verbose=true;continue}if(i==="--ppe_header")throw new w("--ppe_header requires a value in the form --ppe_header=ppe_xxx");if(i.startsWith("--ppe_header=")){let o=i.slice(13);if(!/^ppe_[A-Za-z0-9_-]+$/.test(o))throw new w("--ppe_header must match ppe_[A-Za-z0-9_-]+");e.ppeHeader=o;continue}r.push(i);}return {command:r[0],args:r.slice(1),global:e}}function Kn(t){let e={force:false,noWait:false,scopes:[],timeoutMs:_n};for(let r=0;r<t.length;r+=1){let n=t[r];switch(n){case "--force":e.force=true;break;case "--no-wait":e.noWait=true;break;case "--resume":e.resume=xe(t,++r,"--resume");break;case "--scope":e.scopes.push(xe(t,++r,"--scope"));break;case "--timeout":e.timeoutMs=Fn(xe(t,++r,"--timeout"));break;case "--help":case "-h":throw new w(Ot());default:throw new w(`login: unknown option ${n}`)}}if(e.resume&&(e.force||e.noWait||e.scopes.length>0))throw new w("login --resume cannot be combined with --force, --no-wait, or --scope");return e}function xe(t,e,r){let n=t[e];if(!n||n.startsWith("--"))throw new w(`${r} requires a value`);return n}function Fn(t){let e=t.trim().match(/^(\d+)(ms|s|m)?$/);if(!e)throw new w(`invalid duration: ${t}`);let r=Number(e[1]),n=e[2]??"ms",o=r*(n==="m"?6e4:n==="s"?1e3:1);if(!Number.isSafeInteger(o)||o<=0)throw new w(`invalid duration: ${t}`);return o}function Ue(t,e){if(e.length!==0)throw new w(`${t} does not accept arguments`)}function ae(t){return t.includes("--help")||t.includes("-h")}function ue(t,e,r,n){t.verbose&&At(e,r,n);}function Mn(t){return de[t.code].exitCode}function ce(t,e){let r=Hn(t);return {code:t,message:e,recoverable:r!=="Contact the pico-auth-cli-cn maintainer with the sanitized error details.",action:r}}function Vn(t){return de[t].message}function Hn(t){let e=Bn(t);return e?e.action:t==="LOGIN_TIMEOUT"?"Retry pico-auth-cli-cn login when ready to complete browser authorization.":"Contact the pico-auth-cli-cn maintainer with the sanitized error details."}function Bn(t){return Object.hasOwn(de,t)?de[t]:void 0}function jn(t){return new Promise(e=>setTimeout(e,t))}function zn(t){t(`pico-auth-cli-cn
101
+ `);}async function Vn(t,e,r,n){Ve(t);try{return n?(await n(t),!0):(await Bn(t),!0)}catch{return ge(e,r,"browser_open_failed",{message:"The browser could not be opened automatically.",verification_uri:t}),false}}async function Bn(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];await new Promise((n,i)=>{let o=spawn(e,r,{stdio:"ignore",detached:true});o.once("error",i),o.once("spawn",()=>{o.unref(),n();});});}function Ve(t){let e;try{e=new URL(t);}catch(r){throw new p("INVALID_ARGUMENT","The verification URI returned by the authentication service is invalid.",r)}if(e.protocol!=="https:")throw new p("INVALID_ARGUMENT","The verification URI returned by the authentication service must use HTTPS.")}function jn(t){let e={json:false,verbose:false},r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(i==="--json"){e.json=true;continue}if(i==="--verbose"){e.verbose=true;continue}if(i==="--ppe_header")throw new w("--ppe_header requires a value in the form --ppe_header=ppe_xxx");if(i.startsWith("--ppe_header=")){let o=i.slice(13);if(!/^ppe_[A-Za-z0-9_-]+$/.test(o))throw new w("--ppe_header must match ppe_[A-Za-z0-9_-]+");e.ppeHeader=o;continue}r.push(i);}return {command:r[0],args:r.slice(1),global:e}}function zn(t){let e={force:false,noWait:false,resumePending:false,scopes:[],timeoutMs:In};for(let r=0;r<t.length;r+=1){let n=t[r];switch(n){case "--force":e.force=true;break;case "--no-wait":e.noWait=true;break;case "--resume":e.resume=Ke(t,++r,"--resume");break;case "--resume-pending":e.resumePending=true;break;case "--scope":e.scopes.push(Ke(t,++r,"--scope"));break;case "--timeout":e.timeoutMs=qn(Ke(t,++r,"--timeout"));break;case "--help":case "-h":throw new w(bt());default:throw new w(`login: unknown option ${n}`)}}if(e.resume&&e.resumePending)throw new w("login --resume and --resume-pending cannot be combined");if((e.resume||e.resumePending)&&(e.force||e.noWait||e.scopes.length>0||t.includes("--timeout")))throw new w("login resume options cannot be combined with --force, --no-wait, --scope, or --timeout");return e}function Ke(t,e,r){let n=t[e];if(!n||n.startsWith("--"))throw new w(`${r} requires a value`);return n}function qn(t){let e=t.trim().match(/^(\d+)(ms|s|m)?$/);if(!e)throw new w(`invalid duration: ${t}`);let r=Number(e[1]),n=e[2]??"ms",o=r*(n==="m"?6e4:n==="s"?1e3:1);if(!Number.isSafeInteger(o)||o<=0)throw new w(`invalid duration: ${t}`);return o}function Be(t,e){if(e.length!==0)throw new w(`${t} does not accept arguments`)}function he(t){return t.includes("--help")||t.includes("-h")}function ge(t,e,r,n){t.verbose&&Nt(e,r,n);}function Xn(t){return fe[t.code].exitCode}function pe(t,e,r){let n=Jn(t);return {code:t,message:e,recoverable:n!=="Contact the pico-auth-cli-cn maintainer with the sanitized error details.",action:n,stage:r}}function Wn(t){return fe[t].message}function Jn(t){let e=Yn(t);return e?e.action:t==="LOGIN_TIMEOUT"?"Complete browser authorization, then run pico-auth-cli-cn login --resume-pending using the same region and PPE options.":"Contact the pico-auth-cli-cn maintainer with the sanitized error details."}function Yn(t){return Object.hasOwn(fe,t)?fe[t]:void 0}function Zn(t){return new Promise(e=>setTimeout(e,t))}function Qn(t){t(`pico-auth-cli-cn
88
102
 
89
103
  Usage:
90
104
  pico-auth-cli-cn login [--force] [--scope <scope> ...]
91
105
  pico-auth-cli-cn login --no-wait [--force] [--scope <scope> ...]
92
106
  pico-auth-cli-cn login --resume <device_code>
107
+ pico-auth-cli-cn login --resume-pending
93
108
  pico-auth-cli-cn status
94
109
  pico-auth-cli-cn refresh
95
110
  pico-auth-cli-cn logout
@@ -106,10 +121,11 @@ Commands:
106
121
  status Read local authentication status without refreshing.
107
122
  refresh Refresh and validate the server-backed login state.
108
123
  logout Clear local authentication state.
109
- `);}function Ot(){return `Usage:
124
+ `);}function bt(){return `Usage:
110
125
  pico-auth-cli-cn login [--force] [--scope <scope> ...] [--timeout 120s]
111
126
  pico-auth-cli-cn login --no-wait [--force] [--scope <scope> ...]
112
127
  pico-auth-cli-cn login --resume <device_code>
128
+ pico-auth-cli-cn login --resume-pending
113
129
 
114
130
  By default, opens your browser for PICO sign-in and authorization, then waits for the result in this terminal.
115
131
 
@@ -117,11 +133,15 @@ Options:
117
133
  --force Clear the current local session and sign in again.
118
134
  --no-wait Create a sign-in request and return without opening a browser or waiting.
119
135
  --resume <device_code> Continue a sign-in request created with --no-wait.
136
+ --resume-pending Resume the request stored locally without supplying its handle.
120
137
  --scope <scope> Request an additional authorization scope. May be specified multiple times.
121
- --timeout <duration> Time to wait for browser authorization. Default: 120s.`}function qn(){return `Usage:
138
+ --timeout <duration> Time to wait for browser authorization. Default: 120s.
139
+
140
+ An unexpired pending request is preserved; another login returns LOGIN_ALREADY_PENDING.
141
+ Local waiting timeout preserves that request. Resume it using the same region and PPE options.`}function ei(){return `Usage:
122
142
  pico-auth-cli-cn refresh [--json]
123
143
 
124
144
  Contacts the PICO authentication service and updates the stored login state.
125
145
  After a business service reports NOT_LOGGED_IN, run refresh once and then run
126
146
  pico-auth-cli-cn --json status. If Auth remains authenticated but the business service still
127
- rejects the session, report the sanitized business error to the service support team.`}function Xn(){let t=new URL("../../../package.json",import.meta.url);return JSON.parse(readFileSync(t,"utf8")).version??"0.0.0"}var le=class extends Error{constructor(){super("authorization pending");}},pe=class extends Error{},w=class extends Error{};async function Jn(t=process.argv.slice(2)){return vt(t)}function Zn(){let t=process.argv[1];return t?realpathSync(fileURLToPath(import.meta.url))===realpathSync(t):false}Zn()&&Jn().then(t=>{process.exitCode=t;}).catch(t=>{console.error(t instanceof Error?t.message:String(t)),process.exitCode=1;});export{Jn as main};
147
+ rejects the session, report the sanitized business error to the service support team.`}function ti(){let t=new URL("../../../package.json",import.meta.url);return JSON.parse(readFileSync(t,"utf8")).version??"0.0.0"}var B=class extends Error{constructor(r){super("authorization pending");this.pendingLogin=r;}pendingLogin},me=class extends Error{},w=class extends Error{};async function ni(t=process.argv.slice(2)){return Lt(t)}function ii(){let t=process.argv[1];return t?realpathSync(fileURLToPath(import.meta.url))===realpathSync(t):false}ii()&&ni().then(t=>{process.exitCode=t;}).catch(t=>{console.error(t instanceof Error?t.message:String(t)),process.exitCode=1;});export{ni as main};
@@ -78,6 +78,7 @@ interface AuthRecord {
78
78
  verificationUri?: string;
79
79
  intervalMs?: number;
80
80
  loginExpiresAt?: Date;
81
+ loginContext?: LoginContext;
81
82
  accessToken?: string;
82
83
  refreshToken?: string;
83
84
  tokenExpiresAt?: Date;
@@ -85,8 +86,15 @@ interface AuthRecord {
85
86
  userInfo?: unknown;
86
87
  scopes?: string[];
87
88
  }
89
+ interface LoginContext {
90
+ baseUrl: string;
91
+ aid?: number;
92
+ ppeHeader?: string;
93
+ }
88
94
 
89
95
  interface AuthStore {
96
+ /** Serialize session checks and mutations across clients sharing this store. */
97
+ withLock?<T>(operation: () => Promise<T>): Promise<T>;
90
98
  load(): Promise<AuthRecord>;
91
99
  save(record: AuthRecord): Promise<void>;
92
100
  updateUserInfo(userInfo: unknown): Promise<void>;
@@ -119,6 +127,8 @@ interface LoginFlow {
119
127
  }
120
128
  interface AuthStateView {
121
129
  loggedIn: boolean;
130
+ pending?: boolean;
131
+ loginExpiresAt?: Date;
122
132
  expiresAt?: Date;
123
133
  identity?: unknown;
124
134
  scopes?: string[];
@@ -149,11 +159,18 @@ interface PicoAuthClientOptions {
149
159
  declare function createPicoAuthConfig(options?: PicoAuthClientOptions): AuthClientConfig;
150
160
  declare function mergeScopes(defaultScopes: readonly string[], extraScopes: readonly string[]): string[];
151
161
 
152
- type AuthErrorCode = 'NOT_LOGGED_IN' | 'LOGIN_PENDING' | 'LOGIN_DENIED' | 'LOGIN_EXPIRED' | 'TOKEN_EXPIRED' | 'REFRESH_FAILED' | 'SIGN_FAILED' | 'STORE_UNAVAILABLE' | 'PROTOCOL_ERROR' | 'INVALID_ARGUMENT';
162
+ type AuthErrorCode = 'NOT_LOGGED_IN' | 'LOGIN_PENDING' | 'LOGIN_ALREADY_PENDING' | 'LOGIN_NOT_PENDING' | 'LOGIN_SUPERSEDED' | 'LOGIN_CONTEXT_MISMATCH' | 'LOGIN_DENIED' | 'LOGIN_EXPIRED' | 'TOKEN_EXPIRED' | 'REFRESH_FAILED' | 'SIGN_FAILED' | 'STORE_UNAVAILABLE' | 'PROTOCOL_ERROR' | 'INVALID_ARGUMENT';
153
163
  declare class AuthError extends Error {
154
164
  readonly code: AuthErrorCode;
155
165
  readonly cause?: unknown;
156
- constructor(code: AuthErrorCode, message?: string, cause?: unknown);
166
+ readonly pendingLogin?: {
167
+ verificationUri: string;
168
+ expiresAt: Date;
169
+ };
170
+ constructor(code: AuthErrorCode, message?: string, cause?: unknown, pendingLogin?: {
171
+ verificationUri: string;
172
+ expiresAt: Date;
173
+ });
157
174
  }
158
175
  declare function isAuthError(error: unknown, code?: AuthErrorCode): error is AuthError;
159
176
 
@@ -163,6 +180,7 @@ interface PicoAuthClient {
163
180
  getStatus(signal?: AbortSignal): Promise<AuthStateView>;
164
181
  startLogin(options?: StartLoginOptions): Promise<LoginFlow>;
165
182
  resumeLogin(deviceCode: string, signal?: AbortSignal): Promise<AuthStateView>;
183
+ resumePendingLogin(signal?: AbortSignal): Promise<AuthStateView>;
166
184
  refresh(signal?: AbortSignal): Promise<AuthStateView>;
167
185
  ensureAuthenticated(signal?: AbortSignal): Promise<AuthStateView>;
168
186
  injectAuth(request: AuthRequestLike, signal?: AbortSignal): Promise<void>;
package/dist/src/index.js CHANGED
@@ -9,40 +9,47 @@
9
9
  * from PICO.
10
10
  */
11
11
 
12
- import {createHash,randomUUID,randomBytes,generateKeyPairSync,sign}from'crypto';import {mkdir,writeFile,rm,stat,readFile,open,rename}from'fs/promises';import {join,dirname}from'path';import ze,{userInfo,tmpdir}from'os';import {execFile,spawn,execFileSync}from'child_process';import {createRequire}from'module';import {promisify}from'util';import {readFileSync}from'fs';
13
- var a=class extends Error{kind;errorCode;description;descUrl;cause;constructor(e){super(e.description||e.kind.toLowerCase()),this.name="ProtocolError",this.kind=e.kind,this.errorCode=e.errorCode??0,this.description=e.description??"",this.descUrl=e.descUrl??"",this.cause=e.cause;}};function P(r,e){return r instanceof a&&(e===void 0||r.kind===e)}var ir="/passport/open/get_device_code/",sr="/passport/open/check_device_code/",ar="/passport/open/refresh_token/",G="/api/cli/v1/authorization/device/report",cr="Bearer",_e="X-Tt-Logid",ur=1,dr=6,lr=7,fr=10,hr=10010,pr=10002,M=10003,mr=10005,H=10021,ve=10042,Ce=10043,gr=10044,Er=10046,wr=1080,F=class{baseUrl;deviceReportBaseUrl;aid;headers;deviceReportHttpHeaders;userAgent;constructor(e){if(!e.baseUrl.trim())throw new Error("protocol: base url is required");if(this.baseUrl=new URL(e.baseUrl),!this.baseUrl.protocol||!this.baseUrl.host)throw new Error("protocol: base url must include scheme and host");if(this.deviceReportBaseUrl=new URL(e.deviceReportBaseUrl??e.baseUrl),!this.deviceReportBaseUrl.protocol||!this.deviceReportBaseUrl.host)throw new Error("protocol: device report base url must include scheme and host");this.aid=e.aid,this.headers={...e.headers??{}},this.deviceReportHttpHeaders={...e.deviceReportHttpHeaders??{}},this.userAgent=e.userAgent;}async getDeviceCode(e,t){let n=new URLSearchParams;n.set("client_key",e.clientKey),n.set("pub_key",e.pubKey);let o=yr(e.scopes??[]);o&&n.set("scope",o);let i=await this.postForm(ir,n,void 0,t),s=K(i,Ar);return {deviceCode:k(s,"device_code"),userCode:k(s,"user_code"),verificationUri:k(s,"verification_uri"),intervalMs:$(s,"interval")*1e3,expiresInMs:$(s,"expires_in")*1e3}}async checkDeviceCode(e,t){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("device_code",e.deviceCode);let o=await this.postForm(sr,n,void 0,t),i=K(o,Rr),s=Se(i);return Pr(s),{accessToken:k(i,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:$(i,"expires_in")*1e3}}async refreshToken(e,t){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("client_key",e.clientKey),n.set("grant_type","refresh_token"),n.set("refresh_token",e.refreshToken);let o=await this.postForm(ar,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},t),i=K(o,_r),s=Se(i);return {accessToken:k(i,"access_token"),refreshToken:s.refresh_token,expiresInMs:$(i,"expires_in")*1e3}}async reportDeviceAuthorization(e,t){let n=new URLSearchParams;e.deviceInfo.cliVersion&&n.set("cli_version",e.deviceInfo.cliVersion),e.deviceInfo.architecture&&n.set("architecture",e.deviceInfo.architecture);let o=n.toString(),i=o?`${G}?${o}`:G;await this.postJson(i,{device_info:{name:e.deviceInfo.name,os:e.deviceInfo.os,os_version:e.deviceInfo.osVersion,region:e.deviceInfo.region}},{...this.deviceReportHttpHeaders,...e.headers},t,this.deviceReportBaseUrl);}async postForm(e,t,n,o){let i=this.resolve(e),s;try{s=await fetch(i,{method:"POST",body:t,signal:o,headers:{...this.headers,...n??{},"Content-Type":"application/x-www-form-urlencoded",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(u){throw new a({kind:"TRANSPORT",description:"do request",cause:u})}let c=await s.text();if(s.status!==200)throw new a({kind:"SERVER",errorCode:s.status,description:s.statusText||`unexpected http status ${s.status}`,descUrl:s.headers.get(_e)??""});try{return JSON.parse(c)}catch(u){throw new a({kind:"DECODE",description:"decode envelope",cause:u})}}async postJson(e,t,n,o,i=this.baseUrl){let s=this.resolve(e,i),c;try{c=await fetch(s,{method:"POST",body:JSON.stringify(t),signal:o,headers:{...this.headers,...n??{},"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(f){throw new a({kind:"TRANSPORT",description:"do request",cause:f})}let u=await c.text();if(c.status!==200)throw new a({kind:"SERVER",errorCode:c.status,description:c.statusText||`unexpected http status ${c.status}`,descUrl:c.headers.get(_e)??""});let d;try{d=JSON.parse(u);}catch(f){throw new a({kind:"DECODE",description:"decode response envelope",cause:f})}let w=te(d,"code");if(w!==void 0){if(w===0)return;throw new a({kind:"SERVER",errorCode:w,description:R(d,"em")??R(d,"et")??"device report failed",descUrl:R(d,"trace_id")??""})}K(d,B);}resolve(e,t=this.baseUrl){let n=new URL(e,t);return this.aid!==void 0&&this.aid!==0&&n.searchParams.set("aid",String(this.aid)),n.toString()}};function yr(r){return r.map(e=>e.trim()).filter(Boolean).join(",")}function K(r,e){let t=Cr(r.data)?r.data:{};if(Pe(r.message,"success"))return t;if(!Pe(r.message,"error"))throw new a({kind:"SERVER",description:"unexpected response message"});let n=typeof t.error_code=="number"?t.error_code:0,o=typeof t.code=="number"?t.code:0,i=typeof t.description=="string"?t.description:String(r.message??"error"),s=e(n||o,i),c=typeof t.desc_url=="string"?t.desc_url:"";throw c?new a({kind:s.kind,errorCode:s.errorCode,description:s.description,descUrl:c,cause:s.cause}):s}function Ar(r,e){switch(r){case M:return new a({kind:"INVALID_CLIENT",errorCode:r,description:e});case H:return new a({kind:"ACCESS_DENIED",errorCode:r,description:e});default:return B(r,e)}}function Rr(r,e){switch(r){case lr:return new a({kind:"AUTHORIZATION_PENDING",errorCode:r,description:e});case wr:return Sr(r,e);case M:return new a({kind:"INVALID_CLIENT",errorCode:r,description:e});case H:return new a({kind:"ACCESS_DENIED",errorCode:r,description:e});default:return B(r,e)}}function _r(r,e){switch(r){case hr:return new a({kind:"EXPIRED_TOKEN",errorCode:r,description:e});case ve:return new a({kind:"INVALID_GRANT",errorCode:r,description:e});case Ce:return new a({kind:"EXPIRED_TOKEN",errorCode:r,description:e});case M:return new a({kind:"INVALID_CLIENT",errorCode:r,description:e});case H:return new a({kind:"ACCESS_DENIED",errorCode:r,description:e});case mr:case pr:case gr:case Er:case dr:return new a({kind:"SERVER",errorCode:r,description:e});default:return B(r,e)}}function Sr(r,e){let t=e.toLowerCase().trim();return t.includes("\u53D6\u6D88\u6388\u6743")?new a({kind:"ACCESS_DENIED",errorCode:r,description:e}):t.includes("\u5931\u6548")||t.includes("\u8FC7\u671F")?new a({kind:"EXPIRED_TOKEN",errorCode:r,description:e}):new a({kind:"AUTHORIZATION_PENDING",errorCode:r,description:e})}function B(r,e){switch(e.toLowerCase().trim()){case "authorization_pending":case "\u7528\u6237\u5C1A\u672A\u5B8C\u6210\u6388\u6743\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":case "\u8F6E\u8BE2\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":return new a({kind:"AUTHORIZATION_PENDING",errorCode:r,description:e});case "expired_token":case "device_code \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u5728 cli \u53D1\u8D77\u767B\u5F55":case "token \u5DF2\u8FC7\u671F":case "\u4F1A\u8BDD\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":case "\u6570\u636E\u4E0D\u5B58\u5728":return new a({kind:"EXPIRED_TOKEN",errorCode:r,description:e});case "access_denied":case "\u7528\u6237\u5DF2\u53D6\u6D88\u6388\u6743":return new a({kind:"ACCESS_DENIED",errorCode:r,description:e});case "invalid_grant":case "\u975E\u6CD5 token":return new a({kind:"INVALID_GRANT",errorCode:r,description:e});case "invalid_client":case "\u914D\u7F6E\u65E0\u6548":return new a({kind:"INVALID_CLIENT",errorCode:r,description:e});}switch(r){case M:return new a({kind:"INVALID_CLIENT",errorCode:r,description:e});case H:return new a({kind:"ACCESS_DENIED",errorCode:r,description:e});case ve:return new a({kind:"INVALID_GRANT",errorCode:r,description:e});case Ce:case ur:case fr:return new a({kind:"EXPIRED_TOKEN",errorCode:r,description:e});}return new a({kind:"SERVER",errorCode:r,description:e})}function Se(r){return {access_token:R(r,"access_token"),refresh_token:R(r,"refresh_token"),token_type:R(r,"token_type"),expires_in:te(r,"expires_in")}}function Pr(r){if(r.token_type!==cr)throw new a({kind:"SERVER",description:"unexpected token_type"})}function k(r,e){let t=R(r,e);if(t===void 0||t.trim()==="")throw new a({kind:"DECODE",description:`missing or empty ${e}`});return t}function vr(r,e){let t=te(r,e);if(t===void 0||!Number.isFinite(t))throw new a({kind:"DECODE",description:`missing or invalid ${e}`});return t}function $(r,e){let t=vr(r,e);if(t<=0)throw new a({kind:"DECODE",description:`invalid ${e}`});return t}function R(r,e){let t=r[e];return typeof t=="string"?t:void 0}function te(r,e){let t=r[e];return typeof t=="number"?t:void 0}function Cr(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Pe(r,e){return typeof r=="string"&&r.toLowerCase()===e.toLowerCase()}var Te="ecdsa-p256-sha256";var Or=16,V=class{constructor(e=()=>new Date,t=randomBytes){this.now=e;this.random=t;}now;random;generateDeviceKey(){let{publicKey:e,privateKey:t}=generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return {Algorithm:Te,PublicKeyBase64:Buffer.from(e).toString("base64"),PrivateKeyBase64:Buffer.from(t).toString("base64")}}sign(e,t){if(!e.urlPath||!e.urlPath.startsWith("/"))throw new Error("signer: invalid url path");let n=String(Math.floor(this.now().getTime()/1e3)),o=this.random(Or).toString("hex"),i=Nr(e.signingMaterial),s=createHash("sha256").update(i).digest("base64"),c=[e.method,e.urlPath,s,n,o].join(`
14
- `),u=Lr(t.PrivateKeyBase64,"PRIVATE KEY"),d=sign("sha256",Buffer.from(c),{key:u,dsaEncoding:"der"});return {pubKey:t.PublicKeyBase64,signature:d.toString("base64"),timestamp:n,nonce:o}}};function Nr(r){return r===void 0?new Uint8Array:typeof r=="string"?Buffer.from(r):r}function Lr(r,e){let t=r.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
15
- ${t.join(`
12
+ import {createHash,randomUUID,randomBytes,generateKeyPairSync,sign}from'crypto';import {mkdir,writeFile,rm,stat,readFile,open,rename}from'fs/promises';import {join,dirname}from'path';import We,{tmpdir,userInfo}from'os';import {execFile,spawn,execFileSync}from'child_process';import {createRequire}from'module';import {promisify}from'util';import {readFileSync}from'fs';
13
+ var c=class extends Error{kind;errorCode;description;descUrl;cause;constructor(e){super(e.description||e.kind.toLowerCase()),this.name="ProtocolError",this.kind=e.kind,this.errorCode=e.errorCode??0,this.description=e.description??"",this.descUrl=e.descUrl??"",this.cause=e.cause;}};function v(t,e){return t instanceof c&&(e===void 0||t.kind===e)}var ht="/passport/open/get_device_code/",ft="/passport/open/check_device_code/",pt="/passport/open/refresh_token/",F="/api/cli/v1/authorization/device/report",gt="Bearer",Ce="X-Tt-Logid",mt=1,Et=6,wt=7,yt=10,At=10010,_t=10002,V=10003,Rt=10005,B=10021,De=10042,ke=10043,St=10044,Pt=10046,Ct=1080,H=class{baseUrl;deviceReportBaseUrl;aid;headers;deviceReportHttpHeaders;userAgent;constructor(e){if(!e.baseUrl.trim())throw new Error("protocol: base url is required");if(this.baseUrl=new URL(e.baseUrl),!this.baseUrl.protocol||!this.baseUrl.host)throw new Error("protocol: base url must include scheme and host");if(this.deviceReportBaseUrl=new URL(e.deviceReportBaseUrl??e.baseUrl),!this.deviceReportBaseUrl.protocol||!this.deviceReportBaseUrl.host)throw new Error("protocol: device report base url must include scheme and host");this.aid=e.aid,this.headers={...e.headers??{}},this.deviceReportHttpHeaders={...e.deviceReportHttpHeaders??{}},this.userAgent=e.userAgent;}async getDeviceCode(e,r){let n=new URLSearchParams;n.set("client_key",e.clientKey),n.set("pub_key",e.pubKey);let o=vt(e.scopes??[]);o&&n.set("scope",o);let i=await this.postForm(ht,n,void 0,r),s=$(i,Tt);return {deviceCode:I(s,"device_code"),userCode:I(s,"user_code"),verificationUri:I(s,"verification_uri"),intervalMs:M(s,"interval")*1e3,expiresInMs:M(s,"expires_in")*1e3}}async checkDeviceCode(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("device_code",e.deviceCode);let o=await this.postForm(ft,n,void 0,r),i=$(o,Dt),s=ve(i);return Ot(s),{accessToken:I(i,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:M(i,"expires_in")*1e3}}async refreshToken(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("client_key",e.clientKey),n.set("grant_type","refresh_token"),n.set("refresh_token",e.refreshToken);let o=await this.postForm(pt,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},r),i=$(o,kt),s=ve(i);return {accessToken:I(i,"access_token"),refreshToken:s.refresh_token,expiresInMs:M(i,"expires_in")*1e3}}async reportDeviceAuthorization(e,r){let n=new URLSearchParams;e.deviceInfo.cliVersion&&n.set("cli_version",e.deviceInfo.cliVersion),e.deviceInfo.architecture&&n.set("architecture",e.deviceInfo.architecture);let o=n.toString(),i=o?`${F}?${o}`:F;await this.postJson(i,{device_info:{name:e.deviceInfo.name,os:e.deviceInfo.os,os_version:e.deviceInfo.osVersion,region:e.deviceInfo.region}},{...this.deviceReportHttpHeaders,...e.headers},r,this.deviceReportBaseUrl);}async postForm(e,r,n,o){let i=this.resolve(e),s;try{s=await fetch(i,{method:"POST",body:r,signal:o,headers:{...this.headers,...n??{},"Content-Type":"application/x-www-form-urlencoded",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(l){throw new c({kind:"TRANSPORT",description:"do request",cause:l})}let a=await s.text();if(s.status!==200)throw new c({kind:"SERVER",errorCode:s.status,description:s.statusText||`unexpected http status ${s.status}`,descUrl:s.headers.get(Ce)??""});try{return JSON.parse(a)}catch(l){throw new c({kind:"DECODE",description:"decode envelope",cause:l})}}async postJson(e,r,n,o,i=this.baseUrl){let s=this.resolve(e,i),a;try{a=await fetch(s,{method:"POST",body:JSON.stringify(r),signal:o,headers:{...this.headers,...n??{},"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(h){throw new c({kind:"TRANSPORT",description:"do request",cause:h})}let l=await a.text();if(a.status!==200)throw new c({kind:"SERVER",errorCode:a.status,description:a.statusText||`unexpected http status ${a.status}`,descUrl:a.headers.get(Ce)??""});let u;try{u=JSON.parse(l);}catch(h){throw new c({kind:"DECODE",description:"decode response envelope",cause:h})}let A=se(u,"code");if(A!==void 0){if(A===0)return;throw new c({kind:"SERVER",errorCode:A,description:S(u,"em")??S(u,"et")??"device report failed",descUrl:S(u,"trace_id")??""})}$(u,j);}resolve(e,r=this.baseUrl){let n=new URL(e,r);return this.aid!==void 0&&this.aid!==0&&n.searchParams.set("aid",String(this.aid)),n.toString()}};function vt(t){return t.map(e=>e.trim()).filter(Boolean).join(",")}function $(t,e){let r=Lt(t.data)?t.data:{};if(Te(t.message,"success"))return r;if(!Te(t.message,"error"))throw new c({kind:"SERVER",description:"unexpected response message"});let n=typeof r.error_code=="number"?r.error_code:0,o=typeof r.code=="number"?r.code:0,i=typeof r.description=="string"?r.description:String(t.message??"error"),s=e(n||o,i),a=typeof r.desc_url=="string"?r.desc_url:"";throw a?new c({kind:s.kind,errorCode:s.errorCode,description:s.description,descUrl:a,cause:s.cause}):s}function Tt(t,e){switch(t){case V:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case B:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return j(t,e)}}function Dt(t,e){switch(t){case wt:return new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case Ct:return It(t,e);case V:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case B:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return j(t,e)}}function kt(t,e){switch(t){case At:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case De:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case ke:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case V:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case B:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case Rt:case _t:case St:case Pt:case Et:return new c({kind:"SERVER",errorCode:t,description:e});default:return j(t,e)}}function It(t,e){let r=e.toLowerCase().trim();return r.includes("\u53D6\u6D88\u6388\u6743")?new c({kind:"ACCESS_DENIED",errorCode:t,description:e}):r.includes("\u5931\u6548")||r.includes("\u8FC7\u671F")?new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e}):new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e})}function j(t,e){switch(e.toLowerCase().trim()){case "authorization_pending":case "\u7528\u6237\u5C1A\u672A\u5B8C\u6210\u6388\u6743\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":case "\u8F6E\u8BE2\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":return new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case "expired_token":case "device_code \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u5728 cli \u53D1\u8D77\u767B\u5F55":case "token \u5DF2\u8FC7\u671F":case "\u4F1A\u8BDD\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":case "\u6570\u636E\u4E0D\u5B58\u5728":return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case "access_denied":case "\u7528\u6237\u5DF2\u53D6\u6D88\u6388\u6743":return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case "invalid_grant":case "\u975E\u6CD5 token":return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case "invalid_client":case "\u914D\u7F6E\u65E0\u6548":return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});}switch(t){case V:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case B:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case De:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case ke:case mt:case yt:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});}return new c({kind:"SERVER",errorCode:t,description:e})}function ve(t){return {access_token:S(t,"access_token"),refresh_token:S(t,"refresh_token"),token_type:S(t,"token_type"),expires_in:se(t,"expires_in")}}function Ot(t){if(t.token_type!==gt)throw new c({kind:"SERVER",description:"unexpected token_type"})}function I(t,e){let r=S(t,e);if(r===void 0||r.trim()==="")throw new c({kind:"DECODE",description:`missing or empty ${e}`});return r}function Nt(t,e){let r=se(t,e);if(r===void 0||!Number.isFinite(r))throw new c({kind:"DECODE",description:`missing or invalid ${e}`});return r}function M(t,e){let r=Nt(t,e);if(r<=0)throw new c({kind:"DECODE",description:`invalid ${e}`});return r}function S(t,e){let r=t[e];return typeof r=="string"?r:void 0}function se(t,e){let r=t[e];return typeof r=="number"?r:void 0}function Lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Te(t,e){return typeof t=="string"&&t.toLowerCase()===e.toLowerCase()}var Ie="ecdsa-p256-sha256";var Kt=16,X=class{constructor(e=()=>new Date,r=randomBytes){this.now=e;this.random=r;}now;random;generateDeviceKey(){let{publicKey:e,privateKey:r}=generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return {Algorithm:Ie,PublicKeyBase64:Buffer.from(e).toString("base64"),PrivateKeyBase64:Buffer.from(r).toString("base64")}}sign(e,r){if(!e.urlPath||!e.urlPath.startsWith("/"))throw new Error("signer: invalid url path");let n=String(Math.floor(this.now().getTime()/1e3)),o=this.random(Kt).toString("hex"),i=$t(e.signingMaterial),s=createHash("sha256").update(i).digest("base64"),a=[e.method,e.urlPath,s,n,o].join(`
14
+ `),l=Mt(r.PrivateKeyBase64,"PRIVATE KEY"),u=sign("sha256",Buffer.from(a),{key:l,dsaEncoding:"der"});return {pubKey:r.PublicKeyBase64,signature:u.toString("base64"),timestamp:n,nonce:o}}};function $t(t){return t===void 0?new Uint8Array:typeof t=="string"?Buffer.from(t):t}function Mt(t,e){let r=t.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
15
+ ${r.join(`
16
16
  `)}
17
17
  -----END ${e}-----
18
- `}var j=class extends Error{code;cause;constructor(e,t,n){super(n instanceof Error?`${t}: ${n.message}`:t),this.name="StoreError",this.code=e,this.cause=n;}};function h(r,e,t){return new j(r,`${e}: ${xr(r)}`,t)}function m(r,e){return r instanceof j&&(e===void 0||r.code===e)}function xr(r){switch(r){case "NOT_FOUND":return "store: not found";case "CORRUPT_RECORD":return "store: corrupt record";case "BACKEND_UNAVAILABLE":return "store: backend unavailable";case "PERMISSION_DENIED":return "store: permission denied";case "ENCODE_FAILED":return "store: encode failed";case "DECODE_FAILED":return "store: decode failed"}}var De=1e6;function y(r){Ie(r);let e={client_key:r.clientKey,device_code:D(r.deviceCode),user_code:D(r.userCode),verification_uri:D(r.verificationUri),interval:r.intervalMs===void 0?void 0:Math.trunc(r.intervalMs*De),login_expires_at:r.loginExpiresAt?.toISOString(),access_token:D(r.accessToken),refresh_token:D(r.refreshToken),token_expires_at:r.tokenExpiresAt?.toISOString(),device_key:r.deviceKey,user_info:r.userInfo,scopes:r.scopes};return JSON.stringify(br(e))}function v(r){if(r.trim()==="")throw h("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(r);}catch(n){throw h("DECODE_FAILED","load",n)}let t={clientKey:e.client_key??"",deviceCode:e.device_code,userCode:e.user_code,verificationUri:e.verification_uri,intervalMs:e.interval===void 0?void 0:e.interval/De,loginExpiresAt:ke(e.login_expires_at),accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:ke(e.token_expires_at),deviceKey:e.device_key,userInfo:e.user_info,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):void 0};return Ie(t),t}function Ie(r){if(!r.clientKey.trim())throw h("CORRUPT_RECORD","validate",new Error("client_key is required"))}function I(r){let e=r.trim();if(e==="")return "_";let t="";for(let n of e)/^[A-Za-z0-9._-]$/.test(n)?t+=n:t+="_";return t||"_"}function ke(r){if(r)return new Date(r)}function D(r){return r===void 0||r===""?void 0:r}function br(r){let e={};for(let[t,n]of Object.entries(r))n!==void 0&&(e[t]=n);return e}var z=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;async load(){let e;try{e=await readFile(this.path,"utf8");}catch(t){throw t?.code==="ENOENT"?h("NOT_FOUND","load",t):E("load",t)}try{return v(e)}catch(t){throw m(t)?t:h("DECODE_FAILED","load",t)}}async save(e){let t=y(e),n=dirname(this.path);await mkdir(n,{recursive:true,mode:448});let o=join(n,`${randomBytes(8).toString("hex")}.tmp`);try{await writeFile(o,t,{mode:384}),await rename(o,this.path);}catch(i){throw await rm(o,{force:true}).catch(()=>{}),E("save",i)}}async updateUserInfo(e){let t=await this.load();t.userInfo=e,await this.save(t);}async delete(){try{await rm(this.path,{force:!0});}catch(e){throw E("delete",e)}}};function Le(r,e,t=process.env.HOME||tmpdir()){return join(t||".",".local","share",I(r),`${I(e)}.json`)}function E(r,e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("permission denied")||t.includes("access denied")?h("PERMISSION_DENIED",r,e):h("BACKEND_UNAVAILABLE",r,e)}var be=promisify(execFile),Yr=createRequire(import.meta.url),Qr=9e4,et=5*6e4,rt=100,X="pico-auth-cli-managed-v2",O="pico-auth-cli-managed-v3",C="pico-auth-cli-managed-v3-legacy-ambiguous",N=class{constructor(e,t,n=nt){this.serviceName=e;this.account=t;this.runner=n;x(e,t);}serviceName;account;runner;async load(){let e;try{e=await this.runner.getPassword(this.serviceName,this.account);}catch(t){throw E("load",t)}if(e===null)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return v(e)}catch(t){throw m(t)?t:h("DECODE_FAILED","load",t)}}async save(e){let t;try{t=y(e);}catch(n){throw E("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,t);}catch(n){throw E("save",at(n,t))}}async updateUserInfo(e){let t=await this.load();t.userInfo=e,await this.save(t);}async delete(){try{await this.runner.deletePassword(this.serviceName,this.account);}catch(e){throw E("delete",e)}}},tt={async getPassword(r,e){try{let{stdout:t}=await be("security",["find-generic-password","-s",r,"-a",e,"-w"]);return t.trimEnd()}catch(t){if(Ke(t))return null;throw t}},async deletePassword(r,e){try{return await be("security",["delete-generic-password","-s",r,"-a",e]),!0}catch(t){if(Ke(t))return false;throw t}}},Me={getPassword:(r,e)=>ne().getPassword(r,e),setPassword:(r,e,t)=>ne().setPassword(r,e,t),deletePassword:(r,e)=>ne().deletePassword(r,e)},ce=class{constructor(e=Me,t=tt,n=ue){this.managed=e;this.legacy=t;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,t){for(let i of [ie(t),se(t)]){let s=await this.managed.getPassword(e,i);if(s!==null)return s}let n=await this.managed.getPassword(e,ae(t));if(n===O||n===C)return null;let o=await this.managed.getPassword(e,oe(t));return o!==null?o:await this.managed.getPassword(e,Ue(t))===X?this.managed.getPassword(e,t):this.legacy.getPassword(e,t)}async setPassword(e,t,n){await this.runExclusive(e,t,async()=>{let o=ie(t),i=se(t),s=ae(t);await this.managed.setPassword(e,o,n),await q(this.managed,e,o,n,"recovery"),await this.managed.setPassword(e,i,n),await q(this.managed,e,i,n,"primary"),await this.managed.setPassword(e,s,O),await q(this.managed,e,s,O,"state"),await this.managed.deletePassword(e,o).catch(()=>{}),await this.managed.deletePassword(e,oe(t)).catch(()=>{});});}async deletePassword(e,t){return this.runExclusive(e,t,async()=>{let n=[ie(t),se(t),oe(t)],o=await Promise.all(n.map(g=>this.managed.getPassword(e,g))),i=ae(t),s=await this.managed.getPassword(e,i),c=Ue(t),u=await this.managed.getPassword(e,c);if(!(o.some(g=>g!==null)||s===O||s===C||u===X))return this.legacy.deletePassword(e,t);let f=o[2]!==null&&u!==X||s===C?C:O;await this.managed.setPassword(e,i,f),await q(this.managed,e,i,f,"state");let p=false,A;for(let g of n)try{p=await this.managed.deletePassword(e,g)||p;}catch(or){A??=or;}if(A!==void 0)throw A;if(u===X)try{let g=await this.managed.deletePassword(e,t);p=g||p,(g||await this.managed.getPassword(e,t)===null)&&(p=await this.managed.deletePassword(e,c)||p);}catch(g){A??=g;}else if(f!==C)try{p=await this.legacy.deletePassword(e,t)||p;}catch(g){A??=g;}if(A!==void 0)throw A;return f===C||(p=await this.managed.deletePassword(e,i)||p),p})}},nt=process.platform==="darwin"?new ce:Me;function ne(){return Yr("keytar")}function oe(r){return `${r}.pico-auth-cli-recovery-v1`}function Ue(r){return `${r}.pico-auth-cli-managed-v2`}function ie(r){return `${r}.pico-auth-cli-recovery-v3`}function se(r){return `${r}.pico-auth-cli-payload-v3`}function ae(r){return `${r}.pico-auth-cli-state-v3`}async function ue(r,e,t){let n=join("/tmp",`pico-auth-cli-keychain-locks-${userInfo().uid}`);await mkdir(n,{recursive:true,mode:448});let o=createHash("sha256").update(r).update("\0").update(e).digest("hex"),i=join(n,`${o}.lock`),s=join(i,"owner.json"),c=randomUUID(),u=Date.now()+Qr;for(;;)try{await mkdir(i,{mode:448});try{await writeFile(s,JSON.stringify({pid:process.pid,token:c,createdAt:Date.now()}),{flag:"wx",mode:384});}catch(d){throw await rm(i,{recursive:!0,force:!0}).catch(()=>{}),d}break}catch(d){if(L(d)!=="EEXIST")throw d;if(await He(i)&&await ot(i))continue;if(Date.now()>=u)throw new Error("timed out waiting for the macOS Keychain write lock");await new Promise(w=>setTimeout(w,rt));}try{return await t()}finally{await st(i,s,c).catch(()=>{});}}async function He(r){try{let e=await stat(r);try{let t=await readFile(join(r,"owner.json"),"utf8"),n=JSON.parse(t);return typeof n.pid=="number"&&!it(n.pid)}catch{return Date.now()-e.mtimeMs>=et}}catch{return false}}async function ot(r){let e=`${r}.reaper`,t;try{t=await open(e,"wx",384);}catch(n){if(L(n)==="EEXIST")return false;throw n}try{if(!await He(r))return !1;let n=`${r}.stale-${randomUUID()}`;try{await rename(r,n);}catch(o){if(L(o)==="ENOENT")return !0;throw o}return await rm(n,{recursive:!0,force:!0}),!0}finally{await t.close().catch(()=>{}),await rm(e,{force:true}).catch(()=>{});}}function it(r){try{return process.kill(r,0),!0}catch(e){return L(e)==="EPERM"}}async function st(r,e,t){try{JSON.parse(await readFile(e,"utf8")).token===t&&await rm(r,{recursive:!0,force:!0});}catch(n){if(L(n)!=="ENOENT")throw n}}function L(r){if(!(typeof r!="object"||r===null||!("code"in r)))return typeof r.code=="string"?r.code:void 0}async function q(r,e,t,n,o){if(await r.getPassword(e,t)!==n)throw new Error(`macOS Keychain ${o} write verification failed`)}function x(r,e){if(!r.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function Ke(r){let e=r instanceof Error?r.message:String(r);return e.includes("could not be found")||e.includes("The specified item could not be found")}function at(r,e){let t=r instanceof Error?r.message:String(r),n=t.includes(e)?t.split(e).join("[REDACTED]"):t,o=new Error(n),i=$e(r,"code"),s=$e(r,"exitCode");return i!==void 0&&Object.assign(o,{code:i}),s!==void 0&&Object.assign(o,{exitCode:s}),o}function $e(r,e){if(typeof r!="object"||r===null||!(e in r))return;let t=r[e];return typeof t=="number"?t:void 0}var de=class extends Error{code;exitCode;stderr;constructor(e,t,n){let o=n.trim();super(`${e} exited with code ${t??"unknown"}${o?`: ${o}`:""}`),this.name="CommandExecutionError",this.code=t,this.exitCode=t,this.stderr=n;}};function Be(r,e,t,n=process.env){return new Promise((o,i)=>{let s=spawn(r,e,{env:n,stdio:["pipe","pipe","pipe"]}),c=[],u=[],d=false,w=f=>{d||(d=true,i(f));};s.stdout.on("data",f=>c.push(Buffer.from(f))),s.stderr.on("data",f=>u.push(Buffer.from(f))),s.once("error",w),s.stdin.once("error",w),s.once("close",f=>{if(d)return;d=true;let p={stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(u).toString()};if(f===0){o(p);return}i(new de(r,f,p.stderr));}),s.stdin.end(t);})}var lt=promisify(execFile),ft="Software\\BytedAuthClient\\keychain",Z=class{constructor(e,t,n=ht){this.serviceName=e;this.account=t;this.runner=n;x(e,t);}serviceName;account;runner;async load(){let e;try{e=await this.runner.get(this.serviceName,this.account);}catch(t){throw E("load",t)}if(e===void 0)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return v(e)}catch(t){throw m(t)?t:h("DECODE_FAILED","load",t)}}async save(e){try{await this.runner.set(this.serviceName,this.account,y(e));}catch(t){throw E("save",t)}}async updateUserInfo(e){let t=await this.load();t.userInfo=e,await this.save(t);}async delete(){try{await this.runner.delete(this.serviceName,this.account);}catch(e){throw E("delete",e)}}},ht={async get(r,e){let t=Buffer.from(Ve(r,e)).toString("base64"),n=`
18
+ `}var z=class extends Error{code;cause;constructor(e,r,n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="StoreError",this.code=e,this.cause=n;}};function f(t,e,r){return new z(t,`${e}: ${Ft(t)}`,r)}function g(t,e){return t instanceof z&&(e===void 0||t.code===e)}function Ft(t){switch(t){case "NOT_FOUND":return "store: not found";case "CORRUPT_RECORD":return "store: corrupt record";case "BACKEND_UNAVAILABLE":return "store: backend unavailable";case "PERMISSION_DENIED":return "store: permission denied";case "ENCODE_FAILED":return "store: encode failed";case "DECODE_FAILED":return "store: decode failed"}}var Ne=1e6;function m(t){Le(t);let e={client_key:t.clientKey,device_code:O(t.deviceCode),user_code:O(t.userCode),verification_uri:O(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*Ne),login_expires_at:t.loginExpiresAt?.toISOString(),login_context:t.loginContext?{base_url:t.loginContext.baseUrl,aid:t.loginContext.aid,ppe_header:t.loginContext.ppeHeader}:void 0,access_token:O(t.accessToken),refresh_token:O(t.refreshToken),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(Ht(e))}function T(t){if(t.trim()==="")throw f("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(t);}catch(n){throw f("DECODE_FAILED","load",n)}let r={clientKey:e.client_key??"",deviceCode:e.device_code,userCode:e.user_code,verificationUri:e.verification_uri,intervalMs:e.interval===void 0?void 0:e.interval/Ne,loginExpiresAt:Oe(e.login_expires_at),loginContext:e.login_context?{baseUrl:e.login_context.base_url,aid:e.login_context.aid,ppeHeader:e.login_context.ppe_header}:void 0,accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:Oe(e.token_expires_at),deviceKey:e.device_key,userInfo:e.user_info,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):void 0};return Le(r),r}function Le(t){if(!t.clientKey.trim())throw f("CORRUPT_RECORD","validate",new Error("client_key is required"))}function N(t){let e=t.trim();if(e==="")return "_";let r="";for(let n of e)/^[A-Za-z0-9._-]$/.test(n)?r+=n:r+="_";return r||"_"}function Oe(t){if(t)return new Date(t)}function O(t){return t===void 0||t===""?void 0:t}function Ht(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var be=promisify(execFile),Qt=createRequire(import.meta.url),er=9e4,tr=5*6e4,rr=100,q="pico-auth-cli-managed-v2",L="pico-auth-cli-managed-v3",D="pico-auth-cli-managed-v3-legacy-ambiguous",x=class{constructor(e,r,n=or){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;withLock(e){return _(this.serviceName,`${this.account}.auth-session`,e)}async load(){let e;try{e=await this.runner.getPassword(this.serviceName,this.account);}catch(r){throw w("load",r)}if(e===null)throw f("NOT_FOUND","load",new Error("auth record not found"));try{return T(e)}catch(r){throw g(r)?r:f("DECODE_FAILED","load",r)}}async save(e){let r;try{r=m(e);}catch(n){throw w("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw w("save",cr(n,r))}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.deletePassword(this.serviceName,this.account);}catch(e){throw w("delete",e)}}},nr={async getPassword(t,e){try{let{stdout:r}=await be("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(Ge(r))return null;throw r}},async deletePassword(t,e){try{return await be("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(Ge(r))return false;throw r}}},Fe={getPassword:(t,e)=>ae().getPassword(t,e),setPassword:(t,e,r)=>ae().setPassword(t,e,r),deletePassword:(t,e)=>ae().deletePassword(t,e)},he=class{constructor(e=Fe,r=nr,n=_){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let i of [ue(r),de(r)]){let s=await this.managed.getPassword(e,i);if(s!==null)return s}let n=await this.managed.getPassword(e,le(r));if(n===L||n===D)return null;let o=await this.managed.getPassword(e,ce(r));return o!==null?o:await this.managed.getPassword(e,Ue(r))===q?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let o=ue(r),i=de(r),s=le(r);await this.managed.setPassword(e,o,n),await W(this.managed,e,o,n,"recovery"),await this.managed.setPassword(e,i,n),await W(this.managed,e,i,n,"primary"),await this.managed.setPassword(e,s,L),await W(this.managed,e,s,L,"state"),await this.managed.deletePassword(e,o).catch(()=>{}),await this.managed.deletePassword(e,ce(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[ue(r),de(r),ce(r)],o=await Promise.all(n.map(E=>this.managed.getPassword(e,E))),i=le(r),s=await this.managed.getPassword(e,i),a=Ue(r),l=await this.managed.getPassword(e,a);if(!(o.some(E=>E!==null)||s===L||s===D||l===q))return this.legacy.deletePassword(e,r);let h=o[2]!==null&&l!==q||s===D?D:L;await this.managed.setPassword(e,i,h),await W(this.managed,e,i,h,"state");let p=false,R;for(let E of n)try{p=await this.managed.deletePassword(e,E)||p;}catch(lt){R??=lt;}if(R!==void 0)throw R;if(l===q)try{let E=await this.managed.deletePassword(e,r);p=E||p,(E||await this.managed.getPassword(e,r)===null)&&(p=await this.managed.deletePassword(e,a)||p);}catch(E){R??=E;}else if(h!==D)try{p=await this.legacy.deletePassword(e,r)||p;}catch(E){R??=E;}if(R!==void 0)throw R;return h===D||(p=await this.managed.deletePassword(e,i)||p),p})}},or=process.platform==="darwin"?new he:Fe;function ae(){return Qt("keytar")}function ce(t){return `${t}.pico-auth-cli-recovery-v1`}function Ue(t){return `${t}.pico-auth-cli-managed-v2`}function ue(t){return `${t}.pico-auth-cli-recovery-v3`}function de(t){return `${t}.pico-auth-cli-payload-v3`}function le(t){return `${t}.pico-auth-cli-state-v3`}async function _(t,e,r){let n=join(process.platform==="win32"?tmpdir():"/tmp",`pico-auth-cli-keychain-locks-${userInfo().uid}`);await mkdir(n,{recursive:true,mode:448});let o=createHash("sha256").update(t).update("\0").update(e).digest("hex"),i=join(n,`${o}.lock`),s=join(i,"owner.json"),a=randomUUID(),l=Date.now()+er;for(;;)try{await mkdir(i,{mode:448});try{await writeFile(s,JSON.stringify({pid:process.pid,token:a,createdAt:Date.now()}),{flag:"wx",mode:384});}catch(u){throw await rm(i,{recursive:!0,force:!0}).catch(()=>{}),u}break}catch(u){if(b(u)!=="EEXIST")throw u;if(await He(i)&&await ir(i))continue;if(Date.now()>=l)throw new Error("timed out waiting for the credential store lock");await new Promise(A=>setTimeout(A,rr));}try{return await r()}finally{await ar(i,s,a).catch(()=>{});}}async function He(t){try{let e=await stat(t);try{let r=await readFile(join(t,"owner.json"),"utf8"),n=JSON.parse(r);return typeof n.pid=="number"&&!sr(n.pid)}catch{return Date.now()-e.mtimeMs>=tr}}catch{return false}}async function ir(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if(b(n)==="EEXIST")return false;throw n}try{if(!await He(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(o){if(b(o)==="ENOENT")return !0;throw o}return await rm(n,{recursive:!0,force:!0}),!0}finally{await r.close().catch(()=>{}),await rm(e,{force:true}).catch(()=>{});}}function sr(t){try{return process.kill(t,0),!0}catch(e){return b(e)==="EPERM"}}async function ar(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if(b(n)!=="ENOENT")throw n}}function b(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"?t.code:void 0}async function W(t,e,r,n,o){if(await t.getPassword(e,r)!==n)throw new Error(`macOS Keychain ${o} write verification failed`)}function U(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function Ge(t){let e=t instanceof Error?t.message:String(t);return e.includes("could not be found")||e.includes("The specified item could not be found")}function cr(t,e){let r=t instanceof Error?t.message:String(t),n=r.includes(e)?r.split(e).join("[REDACTED]"):r,o=new Error(n),i=Ke(t,"code"),s=Ke(t,"exitCode");return i!==void 0&&Object.assign(o,{code:i}),s!==void 0&&Object.assign(o,{exitCode:s}),o}function Ke(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var Y=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;withLock(e){return _(this.path,"auth-session",e)}async load(){let e;try{e=await readFile(this.path,"utf8");}catch(r){throw r?.code==="ENOENT"?f("NOT_FOUND","load",r):w("load",r)}try{return T(e)}catch(r){throw g(r)?r:f("DECODE_FAILED","load",r)}}async save(e){let r=m(e),n=dirname(this.path);await mkdir(n,{recursive:true,mode:448});let o=join(n,`${randomBytes(8).toString("hex")}.tmp`);try{await writeFile(o,r,{mode:384}),await rename(o,this.path);}catch(i){throw await rm(o,{force:true}).catch(()=>{}),w("save",i)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await rm(this.path,{force:!0});}catch(e){throw w("delete",e)}}};function je(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",N(t),`${N(e)}.json`)}function w(t,e){let r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return r.includes("permission denied")||r.includes("access denied")?f("PERMISSION_DENIED",t,e):f("BACKEND_UNAVAILABLE",t,e)}var fe=class extends Error{code;exitCode;stderr;constructor(e,r,n){let o=n.trim();super(`${e} exited with code ${r??"unknown"}${o?`: ${o}`:""}`),this.name="CommandExecutionError",this.code=r,this.exitCode=r,this.stderr=n;}};function Xe(t,e,r,n=process.env){return new Promise((o,i)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),a=[],l=[],u=false,A=h=>{u||(u=true,i(h));};s.stdout.on("data",h=>a.push(Buffer.from(h))),s.stderr.on("data",h=>l.push(Buffer.from(h))),s.once("error",A),s.stdin.once("error",A),s.once("close",h=>{if(u)return;u=true;let p={stdout:Buffer.concat(a).toString(),stderr:Buffer.concat(l).toString()};if(h===0){o(p);return}i(new fe(t,h,p.stderr));}),s.stdin.end(r);})}var yr=promisify(execFile),Ar="Software\\BytedAuthClient\\keychain",Q=class{constructor(e,r,n=_r){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;withLock(e){return _(this.serviceName,`${this.account}.auth-session`,e)}async load(){let e;try{e=await this.runner.get(this.serviceName,this.account);}catch(r){throw w("load",r)}if(e===void 0)throw f("NOT_FOUND","load",new Error("auth record not found"));try{return T(e)}catch(r){throw g(r)?r:f("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,m(e));}catch(r){throw w("save",r)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.delete(this.serviceName,this.account);}catch(e){throw w("delete",e)}}},_r={async get(t,e){let r=Buffer.from(ze(t,e)).toString("base64"),n=`
19
19
  $ErrorActionPreference = 'Stop'
20
20
  Add-Type -AssemblyName System.Security
21
- $path = '${T(fe(r))}'
22
- $name = '${T(he(e))}'
23
- if (-not (Test-Path $path)) { exit 3 }
24
- $item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
25
- if ($null -eq $item -or $null -eq $item.$name) { exit 3 }
26
- $cipher = [Convert]::FromBase64String($item.$name)
27
- $entropy = [Convert]::FromBase64String('${t}')
21
+ $path = '${k(ge(t))}'
22
+ $name = '${k(me(e))}'
23
+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path)
24
+ if ($null -eq $key) { exit 3 }
25
+ try { $value = $key.GetValue($name, $null) } finally { $key.Dispose() }
26
+ if ($null -eq $value) { exit 3 }
27
+ $cipher = [Convert]::FromBase64String($value)
28
+ $entropy = [Convert]::FromBase64String('${r}')
28
29
  $plain = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
29
30
  [Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))
30
- `,o=await le(n);return o.missing?void 0:o.stdout},async set(r,e,t){let n=Buffer.from(t,"utf8").toString("base64");await le(mt(r,e),n);},async delete(r,e){let t=`
31
+ exit 0
32
+ `,o=await pe(n);return o.missing?void 0:o.stdout},async set(t,e,r){let n=Buffer.from(r,"utf8").toString("base64");await pe(Sr(t,e),n);},async delete(t,e){let r=`
31
33
  $ErrorActionPreference = 'Stop'
32
- $path = '${T(fe(r))}'
33
- $name = '${T(he(e))}'
34
- if (Test-Path $path) { Remove-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue }
35
- `;await le(t);}};function pt(r){return `${ft}\\${I(r)}`}function fe(r){return `HKCU:\\${pt(r)}`}function he(r){return Buffer.from(r,"utf8").toString("base64url")}function Ve(r,e){return Buffer.concat([Buffer.from(r,"utf8"),Buffer.from([0]),Buffer.from(e,"utf8")])}function mt(r,e){let t=Buffer.from(Ve(r,e)).toString("base64");return `
34
+ $path = '${k(ge(t))}'
35
+ $name = '${k(me(e))}'
36
+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path, $true)
37
+ if ($null -ne $key) {
38
+ try { $key.DeleteValue($name, $false) } finally { $key.Dispose() }
39
+ }
40
+ exit 0
41
+ `;await pe(r);}};function ge(t){return `${Ar}\\${N(t)}`}function Rr(t){return `HKCU:\\${ge(t)}`}function me(t){return Buffer.from(t,"utf8").toString("base64url")}function ze(t,e){return Buffer.concat([Buffer.from(t,"utf8"),Buffer.from([0]),Buffer.from(e,"utf8")])}function Sr(t,e){let r=Buffer.from(ze(t,e)).toString("base64");return `
36
42
  $ErrorActionPreference = 'Stop'
37
43
  Add-Type -AssemblyName System.Security
38
- $path = '${T(fe(r))}'
39
- $name = '${T(he(e))}'
44
+ $path = '${k(Rr(t))}'
45
+ $name = '${k(me(e))}'
40
46
  New-Item -Path $path -Force | Out-Null
41
47
  $encodedValue = [Console]::In.ReadToEnd()
42
48
  $plain = [Convert]::FromBase64String($encodedValue)
43
- $entropy = [Convert]::FromBase64String('${t}')
49
+ $entropy = [Convert]::FromBase64String('${r}')
44
50
  $cipher = [Security.Cryptography.ProtectedData]::Protect($plain, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
45
51
  $encoded = [Convert]::ToBase64String($cipher)
46
52
  Set-ItemProperty -Path $path -Name $name -Value $encoded
47
- `}async function le(r,e){try{let t=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",r],{stdout:n}=e===void 0?await lt("powershell.exe",t):await Be("powershell.exe",t,e);return {stdout:n,missing:!1}}catch(t){if(t?.code===3||t?.exitCode===3)return {stdout:"",missing:true};throw t}}function T(r){return r.replace(/'/g,"''")}var gt="byted_cli_user_token";function Y(r,e=gt,t=process.platform){switch(x(r,e),t){case "darwin":return new N(r,e);case "win32":return new Z(r,e);default:return new pe(new N(r,e),new z(Le(r,e)),n=>ue(r,e,n))}}var pe=class{constructor(e,t,n=async o=>o()){this.primary=e;this.legacy=t;this.runExclusive=n;}primary;legacy;runExclusive;async load(){return this.runExclusive(()=>this.loadExclusive())}async save(e){await this.runExclusive(async()=>{await this.persistAndVerify(e),await this.legacy.delete();});}async updateUserInfo(e){await this.runExclusive(async()=>{let t=await this.loadExclusive();t.userInfo=e,await this.persistAndVerify(t),await this.legacy.delete();});}async delete(){await this.runExclusive(async()=>{let e;for(let t of [this.primary,this.legacy])try{await t.delete();}catch(n){e??=n;}if(e!==void 0)throw e});}async loadExclusive(){try{let t=await this.primary.load();return await this.legacy.delete(),t}catch(t){if(!m(t,"NOT_FOUND"))throw t}let e=await this.legacy.load();return await this.persistAndVerify(e),await this.legacy.delete(),e}async persistAndVerify(e){await this.primary.save(e);let t=await this.primary.load();if(y(t)!==y(e))throw await this.primary.delete().catch(()=>{}),h("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var je={NOT_LOGGED_IN:"authsdk: not logged in",LOGIN_PENDING:"authsdk: login pending",LOGIN_DENIED:"authsdk: login denied",LOGIN_EXPIRED:"authsdk: login expired",TOKEN_EXPIRED:"authsdk: token expired",REFRESH_FAILED:"authsdk: refresh failed",SIGN_FAILED:"authsdk: sign failed",STORE_UNAVAILABLE:"authsdk: store unavailable",PROTOCOL_ERROR:"authsdk: protocol error",INVALID_ARGUMENT:"authsdk: invalid argument"},_=class extends Error{code;cause;constructor(e,t=je[e],n){super(n instanceof Error?`${t}: ${n.message}`:t),this.name="AuthError",this.code=e,this.cause=n;}};function l(r,e){return new _(r,je[r],e)}function Et(r,e){return r instanceof _&&(e===void 0||r.code===e)}var Rt=createRequire(import.meta.url),_t="CN",b=3e3;function qe(){return {name:Xe(ze.hostname()||"unknown",128),os:It(process.platform),osVersion:Xe(ze.release()||"",64),architecture:Ot(process.arch),cliVersion:Nt(),region:St()}}function St(r={}){let e=r.platform??process.platform,t=r.environment??process.env,n=[];if(e==="darwin")n.push(me(r.readMacOSLocale??Ct,void 0));else if(e==="win32"){let o=Pt(me(r.readWindowsRegion??Tt,void 0));if(o)return o}else e==="linux"&&n.push(...Dt(me(r.readLinuxLocales??kt,[])));n.push(t.LC_ALL,t.LC_MESSAGES,t.LANG,t.LANGUAGE,r.intlLocale??Intl.DateTimeFormat().resolvedOptions().locale);for(let o of n){let i=vt(o);if(i)return i}return _t}function Pt(r){let e=r?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function vt(r){if(!r)return;let e=r.trim(),t=e.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(.*)$/);if(t&&(e=t[1].trim()),e=e.replace(/^["']|["']$/g,""),e=e.split(":",1)[0].split(/[.@]/,1)[0].replaceAll("_","-"),!(!e||/^(?:C|POSIX)$/i.test(e)))try{let n=new Intl.Locale(e).region?.toUpperCase();return n&&/^[A-Z]{2}$/.test(n)?n:void 0}catch{return}}function Ct(){return Je("/usr/bin/defaults",["read","-g","AppleLocale"])}function Tt(){return Je("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function kt(){let r=[];for(let e of ["/etc/locale.conf","/etc/default/locale"])try{for(let t of readFileSync(e,"utf8").split(/\r?\n/)){let n=t.trim();/^(?:LC_ALL|LC_MESSAGES|LANG|LANGUAGE)=/.test(n)&&r.push(n);}}catch{}return r}function Dt(r){let e=["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"],t=[];for(let n of e)t.push(...r.filter(o=>o?.trim().startsWith(`${n}=`)));return t.push(...r.filter(n=>!n?.includes("="))),t}function Je(r,e){try{return execFileSync(r,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function me(r,e){try{return r()}catch{return e}}function It(r){switch(r){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return r}}function Ot(r){return r==="x64"?"x86_64":r}function Nt(){for(let r of ["../../package.json","../../../package.json"])try{let e=Rt(r);if(typeof e.version=="string")return e.version}catch{}return ""}function Xe(r,e){return r.length>e?r.slice(0,e):r}var Lt="/passport/open/refresh_token/",We="Bearer ",ge=class{current=Promise.resolve();async run(e){let t=this.current,n;this.current=new Promise(o=>{n=o;}),await t;try{return await e()}finally{n();}}},Q=class{core;constructor(e,t={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=t.protocol??new F({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),o=t.signer??new V,i=t.store??Y(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:o,store:i,now:t.now??(()=>new Date),mutex:new ge,deviceReportUrl:new URL(G,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:xt(e.deviceReportTimeoutMs)};}authenticator(){return new Ee(this.core)}authorizer(){return new ee(this.core)}},Ee=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let t=this.core.signer.generateDeviceKey(),n=await this.core.protocol.getDeviceCode({clientKey:this.core.clientKey,scopes:this.core.scopes,pubKey:t.PublicKeyBase64},e),o=new Date(this.core.now().getTime()+n.expiresInMs),i={clientKey:this.core.clientKey,deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,loginExpiresAt:o,deviceKey:t,scopes:[...this.core.scopes]};return await ye(this.core.store,i),{deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,expiresAt:o}})}async checkLogin(e,t){let n=e.trim();if(!n)throw new Error("authsdk: device_code is required");return this.core.mutex.run(async()=>{let o=await we(this.core.store);if(!o.deviceCode||!o.loginExpiresAt)throw l("NOT_LOGGED_IN");if(o.deviceCode!==n)throw l("INVALID_ARGUMENT",new Error("device_code does not match pending login state"));if(this.core.now().getTime()>=o.loginExpiresAt.getTime())throw await re(this.core.store),l("LOGIN_EXPIRED");let i;try{i=await this.core.protocol.checkDeviceCode({deviceCode:n},t);}catch(s){let c=bt(s);throw c.code==="LOGIN_EXPIRED"&&await re(this.core.store),c}return o.deviceCode=void 0,o.userCode=void 0,o.verificationUri=void 0,o.intervalMs=void 0,o.loginExpiresAt=void 0,o.accessToken=i.accessToken,i.refreshToken&&(o.refreshToken=i.refreshToken),o.tokenExpiresAt=new Date(this.core.now().getTime()+i.expiresInMs),await ye(this.core.store,o),await Ze(this.core,o,t),Ae(this.core.now(),o)})}authorizer(){return new ee(this.core)}},ee=class{constructor(e){this.core=e;}core;async state(e){return this.core.mutex.run(async()=>{try{let t=await this.ensureActiveRecord(0,e);return Ae(this.core.now(),t)}catch(t){if(t instanceof _&&t.code==="NOT_LOGGED_IN")return {loggedIn:false};throw t}})}async refresh(e=0,t){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(Math.max(0,e),t);return Ae(this.core.now(),n)})}async inject(e,t){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(0,t);if(!n.accessToken||!n.deviceKey)throw l("NOT_LOGGED_IN");Ye(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await this.core.store.updateUserInfo(e);}catch(t){throw U(t)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await we(this.core.store);return Qe(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await this.core.store.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw U(e)}})}async ensureActiveRecord(e,t){let n=await we(this.core.store);if(!n.accessToken)throw l("NOT_LOGGED_IN");let o=this.core.now();if(Kt(o,n.tokenExpiresAt,e))return n;if(!n.refreshToken||!n.deviceKey)throw await re(this.core.store),l("NOT_LOGGED_IN");let i;try{i=this.core.signer.sign({method:"POST",urlPath:Lt,signingMaterial:n.refreshToken},n.deviceKey);}catch(u){throw l("SIGN_FAILED",u)}let s,c=n.accessToken;try{s=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:n.refreshToken,pubKey:i.pubKey,reqSign:i.signature,reqTs:i.timestamp,reqNonce:i.nonce},t);}catch(u){throw Ut(u)?(await re(this.core.store),l("NOT_LOGGED_IN")):l("REFRESH_FAILED",u)}return n.accessToken=s.accessToken,s.refreshToken&&(n.refreshToken=s.refreshToken),n.tokenExpiresAt=new Date(this.core.now().getTime()+s.expiresInMs),await ye(this.core.store,n),c!==n.accessToken&&await Ze(this.core,n,t),n}};async function Ze(r,e,t){if(!e.accessToken||!e.deviceKey)return;let n={};try{Ye(r,e,{method:"POST",url:r.deviceReportUrl,headers:n}),n["Authorization-act"]=We+e.accessToken;}catch{return}let o=new AbortController,i=()=>o.abort(t?.reason);t?.aborted?i():t?.addEventListener("abort",i,{once:true});let s,c=new Promise((u,d)=>{s=setTimeout(()=>{o.abort(),d(new Error("device report timed out"));},r.deviceReportTimeoutMs);});try{await Promise.race([r.protocol.reportDeviceAuthorization({headers:n,deviceInfo:qe()},o.signal),c]);}catch{}finally{s&&clearTimeout(s),t?.removeEventListener("abort",i);}}function Ye(r,e,t){if(!e.accessToken||!e.deviceKey)throw l("NOT_LOGGED_IN");let n=new URL(String(t.url)),o=t.method.trim().toUpperCase(),i=n.pathname||"/",s;try{s=r.signer.sign({method:o,urlPath:i,signingMaterial:e.accessToken},e.deviceKey);}catch(c){throw l("SIGN_FAILED",c)}S(t,"Authorization",We+e.accessToken),S(t,"X-Pub-Key",s.pubKey),S(t,"X-Req-Sign",s.signature),S(t,"X-Req-Ts",s.timestamp),S(t,"X-Req-Nonce",s.nonce),S(t,"X-Req-Method",o),S(t,"X-Req-Path",i);}function xt(r){return r!==void 0&&Number.isFinite(r)&&r>0?Math.floor(r):b}async function we(r){try{return await r.load()}catch(e){throw U(e)}}async function ye(r,e){try{await r.save(e);}catch(t){throw U(t)}}async function re(r){try{await r.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw U(e)}}function U(r){return m(r,"NOT_FOUND")?l("NOT_LOGGED_IN",r):l("STORE_UNAVAILABLE",r)}function bt(r){return P(r,"AUTHORIZATION_PENDING")?l("LOGIN_PENDING",r):P(r,"ACCESS_DENIED")?l("LOGIN_DENIED",r):P(r,"EXPIRED_TOKEN")?l("LOGIN_EXPIRED",r):l("PROTOCOL_ERROR",r)}function Ut(r){return P(r,"EXPIRED_TOKEN")||P(r,"INVALID_GRANT")}function Kt(r,e,t){return e?t===0?r.getTime()<e.getTime():r.getTime()+t<=e.getTime():t===0}function Ae(r,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||r.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:Qe(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function S(r,e,t){if(r.headers instanceof Headers){r.headers.set(e,t);return}r.headers||(r.headers={}),r.headers[e]=t;}function Qe(r){return r==null?r:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}var er=["pico_vibe_lab","pico_ai_sgs","user_info"],$t=Object.freeze({}),rr="https://user.picoxr.com",Gt=Object.freeze({}),Ft=/^ppe_[A-Za-z0-9_-]+$/,tr={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:rr,deviceReportTimeoutMs:b};function Re(r={}){let e=r.ppeHeader?Mt(r.ppeHeader):void 0;return {...tr,scopes:nr(er,r.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function Mt(r){if(!Ft.test(r))throw new TypeError("ppeHeader must match ppe_[A-Za-z0-9_-]+");return Object.freeze({"X-TT-Env":r,"X-Use-PPE":"1"})}function nr(r,e){let t=new Set;for(let n of [...r,...e]){let o=n.trim();o&&t.add(o);}return [...t]}var Ht=365*24*60*60*1e3;function no(r={},e={}){let t=Re(r),n=e.store??Y(t.storeServiceName),o=new Q(t,{...e,store:n});return {getStatus(i){return Bt(n,i)},startLogin(i={}){return o.authenticator().newLoginFlow(i.signal)},resumeLogin(i,s){return o.authenticator().checkLogin(i,s)},ensureAuthenticated(i){return o.authorizer().refresh(0,i)},refresh(i){return o.authorizer().refresh(Ht,i)},injectAuth(i,s){return o.authorizer().inject(i,s)},logout(){return o.authorizer().logout()}}}async function Bt(r,e){e?.throwIfAborted();try{let t=await r.load(),n=Date.now();return {loggedIn:!!t.accessToken&&(t.tokenExpiresAt===void 0||n<t.tokenExpiresAt.getTime()),expiresAt:t.tokenExpiresAt,identity:Vt(t.userInfo),scopes:t.scopes?[...t.scopes]:void 0}}catch(t){if(m(t,"NOT_FOUND"))return {loggedIn:false};throw l("STORE_UNAVAILABLE",t)}}function Vt(r){return r==null?r:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}
48
- export{_ as AuthError,b as DEFAULT_DEVICE_REPORT_TIMEOUT_MS,tr as PICO_AUTH_CONFIG,$t as PICO_AUTH_HTTP_HEADERS,er as PICO_DEFAULT_SCOPES,rr as PICO_DEVICE_REPORT_BASE_URL,Gt as PICO_DEVICE_REPORT_HTTP_HEADERS,no as createAuthClient,Re as createPicoAuthConfig,Et as isAuthError,nr as mergeScopes};
53
+ exit 0
54
+ `}async function pe(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await yr("powershell.exe",r):await Xe("powershell.exe",r,e);return {stdout:n,missing:!1}}catch(r){if(r?.code===3||r?.exitCode===3)return {stdout:"",missing:true};throw r}}function k(t){return t.replace(/'/g,"''")}var Pr="byted_cli_user_token";function ee(t,e=Pr,r=process.platform){switch(U(t,e),r){case "darwin":return new x(t,e);case "win32":return new Q(t,e);default:return new Ee(new x(t,e),new Y(je(t,e)),n=>_(t,e,n),n=>_(t,`${e}.auth-session`,n))}}var Ee=class{constructor(e,r,n=async i=>i(),o){this.primary=e;this.legacy=r;this.runExclusive=n;this.withLock=o;}primary;legacy;runExclusive;withLock;async load(){return this.runExclusive(()=>this.loadExclusive())}async save(e){await this.runExclusive(async()=>{await this.persistAndVerify(e),await this.legacy.delete();});}async updateUserInfo(e){await this.runExclusive(async()=>{let r=await this.loadExclusive();r.userInfo=e,await this.persistAndVerify(r),await this.legacy.delete();});}async delete(){await this.runExclusive(async()=>{let e;for(let r of [this.primary,this.legacy])try{await r.delete();}catch(n){e??=n;}if(e!==void 0)throw e});}async loadExclusive(){try{let r=await this.primary.load();return await this.legacy.delete(),r}catch(r){if(!g(r,"NOT_FOUND"))throw r}let e=await this.legacy.load();return await this.persistAndVerify(e),await this.legacy.delete(),e}async persistAndVerify(e){await this.primary.save(e);let r=await this.primary.load();if(m(r)!==m(e))throw await this.primary.delete().catch(()=>{}),f("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var qe={NOT_LOGGED_IN:"authsdk: not logged in",LOGIN_PENDING:"authsdk: login pending",LOGIN_ALREADY_PENDING:"authsdk: a login request is already pending",LOGIN_NOT_PENDING:"authsdk: no pending login request",LOGIN_SUPERSEDED:"authsdk: login request was replaced",LOGIN_CONTEXT_MISMATCH:"authsdk: login request belongs to a different region or PPE environment",LOGIN_DENIED:"authsdk: login denied",LOGIN_EXPIRED:"authsdk: login expired",TOKEN_EXPIRED:"authsdk: token expired",REFRESH_FAILED:"authsdk: refresh failed",SIGN_FAILED:"authsdk: sign failed",STORE_UNAVAILABLE:"authsdk: store unavailable",PROTOCOL_ERROR:"authsdk: protocol error",INVALID_ARGUMENT:"authsdk: invalid argument"},y=class extends Error{code;cause;pendingLogin;constructor(e,r=qe[e],n,o){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="AuthError",this.code=e,this.cause=n,this.pendingLogin=o;}};function d(t,e){return new y(t,qe[t],e)}function Cr(t,e){return t instanceof y&&(e===void 0||t.code===e)}var kr=createRequire(import.meta.url),Ir="CN",G=3e3;function Ze(){return {name:Je(We.hostname()||"unknown",128),os:Kr(process.platform),osVersion:Je(We.release()||"",64),architecture:$r(process.arch),cliVersion:Mr(),region:Or()}}function Or(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(we(t.readMacOSLocale??xr,void 0));else if(e==="win32"){let o=Nr(we(t.readWindowsRegion??br,void 0));if(o)return o}else e==="linux"&&n.push(...Gr(we(t.readLinuxLocales??Ur,[])));n.push(r.LC_ALL,r.LC_MESSAGES,r.LANG,r.LANGUAGE,t.intlLocale??Intl.DateTimeFormat().resolvedOptions().locale);for(let o of n){let i=Lr(o);if(i)return i}return Ir}function Nr(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function Lr(t){if(!t)return;let e=t.trim(),r=e.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(.*)$/);if(r&&(e=r[1].trim()),e=e.replace(/^["']|["']$/g,""),e=e.split(":",1)[0].split(/[.@]/,1)[0].replaceAll("_","-"),!(!e||/^(?:C|POSIX)$/i.test(e)))try{let n=new Intl.Locale(e).region?.toUpperCase();return n&&/^[A-Z]{2}$/.test(n)?n:void 0}catch{return}}function xr(){return Ye("/usr/bin/defaults",["read","-g","AppleLocale"])}function br(){return Ye("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function Ur(){let t=[];for(let e of ["/etc/locale.conf","/etc/default/locale"])try{for(let r of readFileSync(e,"utf8").split(/\r?\n/)){let n=r.trim();/^(?:LC_ALL|LC_MESSAGES|LANG|LANGUAGE)=/.test(n)&&t.push(n);}}catch{}return t}function Gr(t){let e=["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"],r=[];for(let n of e)r.push(...t.filter(o=>o?.trim().startsWith(`${n}=`)));return r.push(...t.filter(n=>!n?.includes("="))),r}function Ye(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function we(t,e){try{return t()}catch{return e}}function Kr(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function $r(t){return t==="x64"?"x86_64":t}function Mr(){for(let t of ["../../package.json","../../../package.json"])try{let e=kr(t);if(typeof e.version=="string")return e.version}catch{}return ""}function Je(t,e){return t.length>e?t.slice(0,e):t}var Fr="/passport/open/refresh_token/",rt="Bearer ",re=class{current=Promise.resolve();async run(e){let r=this.current,n;this.current=new Promise(o=>{n=o;}),await r;try{return await e()}finally{n();}}},ne=class{core;constructor(e,r={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=r.protocol??new H({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),o=r.signer??new X,i=r.store??ee(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:o,store:i,now:r.now??(()=>new Date),mutex:new re,deviceReportUrl:new URL(F,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:Hr(e.deviceReportTimeoutMs),loginContext:{baseUrl:new URL(e.baseUrl).toString(),aid:e.aid||void 0,ppeHeader:Object.entries(e.customHttpHeaders??{}).find(([s])=>s.toLowerCase()==="x-tt-env")?.[1]}};}authenticator(){return new Ae(this.core)}authorizer(){return new oe(this.core)}},Ae=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let r=await ye(this.core.store,async()=>{let a=await te(this.core.store);return Qe(a,this.core.now()),a?m(a):void 0}),n=this.core.signer.generateDeviceKey(),o=await this.core.protocol.getDeviceCode({clientKey:this.core.clientKey,scopes:this.core.scopes,pubKey:n.PublicKeyBase64},e).catch(a=>{throw tt(a)}),i=new Date(this.core.now().getTime()+o.expiresInMs),s={clientKey:this.core.clientKey,deviceCode:o.deviceCode,userCode:o.userCode,verificationUri:o.verificationUri,intervalMs:o.intervalMs,loginExpiresAt:i,loginContext:{...this.core.loginContext},deviceKey:n,scopes:[...this.core.scopes]};return await ye(this.core.store,async()=>{let a=await te(this.core.store);if(Qe(a,this.core.now()),(a?m(a):void 0)!==r)throw d("LOGIN_SUPERSEDED");await this.core.store.save(s);}),{deviceCode:o.deviceCode,userCode:o.userCode,verificationUri:o.verificationUri,intervalMs:o.intervalMs,expiresAt:i}})}async checkLogin(e,r){let n=e.trim();if(!n)throw new Error("authsdk: device_code is required");return this.core.mutex.run(async()=>{let o=await _e(this.core.store);return this.checkLoginRecord(o,n,r)})}async checkPendingLogin(e){return this.core.mutex.run(async()=>{let r=await te(this.core.store);if(!r?.deviceCode||!r.loginExpiresAt)throw d("LOGIN_NOT_PENDING");return this.checkLoginRecord(r,r.deviceCode,e)})}async checkLoginRecord(e,r,n){let o=m(e);if(!e.deviceCode||!e.loginExpiresAt)throw d("NOT_LOGGED_IN");if(e.deviceCode!==r)throw d("LOGIN_SUPERSEDED");if(e.loginContext&&(e.loginContext.baseUrl!==this.core.loginContext.baseUrl||e.loginContext.aid!==this.core.loginContext.aid||e.loginContext.ppeHeader!==this.core.loginContext.ppeHeader))throw d("LOGIN_CONTEXT_MISMATCH");if(this.core.now().getTime()>=e.loginExpiresAt.getTime())throw await ie(this.core.store,o,"LOGIN_SUPERSEDED"),d("LOGIN_EXPIRED");let i;try{i=await this.core.protocol.checkDeviceCode({deviceCode:r},n);}catch(s){let a=tt(s);throw a.code==="LOGIN_PENDING"&&(await ye(this.core.store,()=>Se(this.core.store,o,"LOGIN_SUPERSEDED")),e.verificationUri&&e.loginExpiresAt)?new y("LOGIN_PENDING",void 0,s,{verificationUri:e.verificationUri,expiresAt:new Date(e.loginExpiresAt)}):((a.code==="LOGIN_EXPIRED"||a.code==="LOGIN_DENIED")&&await ie(this.core.store,o,"LOGIN_SUPERSEDED"),a)}return e.deviceCode=void 0,e.userCode=void 0,e.verificationUri=void 0,e.intervalMs=void 0,e.loginExpiresAt=void 0,e.loginContext=void 0,e.accessToken=i.accessToken,i.refreshToken&&(e.refreshToken=i.refreshToken),e.tokenExpiresAt=new Date(this.core.now().getTime()+i.expiresInMs),await it(this.core.store,e,o,"LOGIN_SUPERSEDED"),await nt(this.core,e,n),Re(this.core.now(),e)}authorizer(){return new oe(this.core)}},oe=class{constructor(e){this.core=e;}core;async state(e){return this.core.mutex.run(async()=>{try{let r=await this.ensureActiveRecord(0,e);return Re(this.core.now(),r)}catch(r){if(r instanceof y&&r.code==="NOT_LOGGED_IN")return {loggedIn:false};throw r}})}async refresh(e=0,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(Math.max(0,e),r);return Re(this.core.now(),n)})}async inject(e,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(0,r);if(!n.accessToken||!n.deviceKey)throw d("NOT_LOGGED_IN");ot(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await K(this.core.store,()=>this.core.store.updateUserInfo(e));}catch(r){throw C(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await _e(this.core.store);return st(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await K(this.core.store,()=>this.core.store.delete());}catch(e){if(!g(e,"NOT_FOUND"))throw C(e)}})}async ensureActiveRecord(e,r){let n=await _e(this.core.store),o=m(n);if(!n.accessToken)throw d("NOT_LOGGED_IN");let i=this.core.now();if(Br(i,n.tokenExpiresAt,e))return n;if(!n.refreshToken||!n.deviceKey)throw await ie(this.core.store,o),d("NOT_LOGGED_IN");let s;try{s=this.core.signer.sign({method:"POST",urlPath:Fr,signingMaterial:n.refreshToken},n.deviceKey);}catch(u){throw d("SIGN_FAILED",u)}let a,l=n.accessToken;try{a=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:n.refreshToken,pubKey:s.pubKey,reqSign:s.signature,reqTs:s.timestamp,reqNonce:s.nonce},r);}catch(u){throw Vr(u)?(await ie(this.core.store,o),d("NOT_LOGGED_IN")):d("REFRESH_FAILED",u)}return n.accessToken=a.accessToken,a.refreshToken&&(n.refreshToken=a.refreshToken),n.tokenExpiresAt=new Date(this.core.now().getTime()+a.expiresInMs),await it(this.core.store,n,o),l!==n.accessToken&&await nt(this.core,n,r),n}};async function nt(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{ot(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=rt+e.accessToken;}catch{return}let o=new AbortController,i=()=>o.abort(r?.reason);r?.aborted?i():r?.addEventListener("abort",i,{once:true});let s,a=new Promise((l,u)=>{s=setTimeout(()=>{o.abort(),u(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:Ze()},o.signal),a]);}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",i);}}function ot(t,e,r){if(!e.accessToken||!e.deviceKey)throw d("NOT_LOGGED_IN");let n=new URL(String(r.url)),o=r.method.trim().toUpperCase(),i=n.pathname||"/",s;try{s=t.signer.sign({method:o,urlPath:i,signingMaterial:e.accessToken},e.deviceKey);}catch(a){throw d("SIGN_FAILED",a)}P(r,"Authorization",rt+e.accessToken),P(r,"X-Pub-Key",s.pubKey),P(r,"X-Req-Sign",s.signature),P(r,"X-Req-Ts",s.timestamp),P(r,"X-Req-Nonce",s.nonce),P(r,"X-Req-Method",o),P(r,"X-Req-Path",i);}function Hr(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):G}async function _e(t){try{return await t.load()}catch(e){throw C(e)}}async function te(t){try{return await t.load()}catch(e){if(g(e,"NOT_FOUND"))return;throw C(e)}}function Qe(t,e){if(t?.deviceCode&&t.loginExpiresAt&&e.getTime()<t.loginExpiresAt.getTime())throw d("LOGIN_ALREADY_PENDING")}async function ye(t,e){try{return await K(t,e)}catch(r){throw r instanceof y?r:C(r)}}async function it(t,e,r,n="NOT_LOGGED_IN"){try{await K(t,async()=>{r!==void 0&&await Se(t,r,n),await t.save(e);});}catch(o){throw o instanceof y?o:C(o)}}async function ie(t,e,r="NOT_LOGGED_IN"){try{await K(t,async()=>{await Se(t,e,r),await t.delete();});}catch(n){if(n instanceof y)throw n;if(!g(n,"NOT_FOUND"))throw C(n)}}async function Se(t,e,r="NOT_LOGGED_IN"){let n=await te(t);if(!n||m(n)!==e)throw d(r)}var et=new WeakMap;async function K(t,e){if(t.withLock)return t.withLock(e);let r=et.get(t);return r||(r=new re,et.set(t,r)),r.run(e)}function C(t){return g(t,"NOT_FOUND")?d("NOT_LOGGED_IN",t):d("STORE_UNAVAILABLE",t)}function tt(t){return v(t,"AUTHORIZATION_PENDING")?d("LOGIN_PENDING",t):v(t,"ACCESS_DENIED")?d("LOGIN_DENIED",t):v(t,"EXPIRED_TOKEN")?d("LOGIN_EXPIRED",t):d("PROTOCOL_ERROR",t)}function Vr(t){return v(t,"EXPIRED_TOKEN")||v(t,"INVALID_GRANT")}function Br(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Re(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:st(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function P(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function st(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var at=["pico_vibe_lab","pico_ai_sgs","user_info"],jr=Object.freeze({}),ct="https://user.picoxr.com",Xr=Object.freeze({}),zr=/^ppe_[A-Za-z0-9_-]+$/,ut={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:ct,deviceReportTimeoutMs:G};function Pe(t={}){let e=t.ppeHeader?qr(t.ppeHeader):void 0;return {...ut,scopes:dt(at,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function qr(t){if(!zr.test(t))throw new TypeError("ppeHeader must match ppe_[A-Za-z0-9_-]+");return Object.freeze({"X-TT-Env":t,"X-Use-PPE":"1"})}function dt(t,e){let r=new Set;for(let n of [...t,...e]){let o=n.trim();o&&r.add(o);}return [...r]}var Wr=365*24*60*60*1e3;function fo(t={},e={}){let r=Pe(t),n=e.store??ee(r.storeServiceName),o=new ne(r,{...e,store:n});return {getStatus(i){return Jr(n,e.now??(()=>new Date),i)},startLogin(i={}){return o.authenticator().newLoginFlow(i.signal)},resumeLogin(i,s){return o.authenticator().checkLogin(i,s)},resumePendingLogin(i){return o.authenticator().checkPendingLogin(i)},ensureAuthenticated(i){return o.authorizer().refresh(0,i)},refresh(i){return o.authorizer().refresh(Wr,i)},injectAuth(i,s){return o.authorizer().inject(i,s)},logout(){return o.authorizer().logout()}}}async function Jr(t,e,r){r?.throwIfAborted();try{let n=await t.load(),o=e().getTime();return {loggedIn:!!n.accessToken&&(n.tokenExpiresAt===void 0||o<n.tokenExpiresAt.getTime()),expiresAt:n.tokenExpiresAt,identity:Zr(n.userInfo),scopes:n.scopes?[...n.scopes]:void 0,...n.deviceCode&&n.loginExpiresAt?{pending:o<n.loginExpiresAt.getTime(),loginExpiresAt:new Date(n.loginExpiresAt)}:{}}}catch(n){if(g(n,"NOT_FOUND"))return {loggedIn:false};throw d("STORE_UNAVAILABLE",n)}}function Zr(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}
55
+ export{y as AuthError,G as DEFAULT_DEVICE_REPORT_TIMEOUT_MS,ut as PICO_AUTH_CONFIG,jr as PICO_AUTH_HTTP_HEADERS,at as PICO_DEFAULT_SCOPES,ct as PICO_DEVICE_REPORT_BASE_URL,Xr as PICO_DEVICE_REPORT_HTTP_HEADERS,fo as createAuthClient,Pe as createPicoAuthConfig,Cr as isAuthError,dt as mergeScopes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picoxr/pico-auth-cli-cn",
3
- "version": "0.1.20",
3
+ "version": "0.1.23",
4
4
  "description": "PICO authentication command-line interface.",
5
5
  "type": "module",
6
6
  "bin": {