@picoxr/pico-auth-cli-cn 0.1.23 → 0.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/src/cli/main.js +43 -36
- package/dist/src/index.d.ts +8 -1
- package/dist/src/index.js +14 -14
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,6 +27,9 @@ pico-auth-cli-cn login
|
|
|
27
27
|
# Check the current status.
|
|
28
28
|
pico-auth-cli-cn status
|
|
29
29
|
|
|
30
|
+
# Read cached user information.
|
|
31
|
+
pico-auth-cli-cn userinfo
|
|
32
|
+
|
|
30
33
|
# Refresh the login state.
|
|
31
34
|
pico-auth-cli-cn refresh
|
|
32
35
|
|
|
@@ -62,5 +65,7 @@ that has expired requires a new login. Check installed `login --help` for suppor
|
|
|
62
65
|
organization.
|
|
63
66
|
- Do not share login codes, credentials, authorization headers, or request signatures.
|
|
64
67
|
- The CLI does not print access tokens, refresh tokens, or private keys in normal output.
|
|
68
|
+
- `userinfo` prints cached user profile fields. Treat its output as personal data and share it only
|
|
69
|
+
when appropriate.
|
|
65
70
|
- Signing out removes the local login state; it does not necessarily revoke authorization on other
|
|
66
71
|
devices or delete previously reported device information.
|
package/dist/src/cli/main.js
CHANGED
|
@@ -10,17 +10,17 @@
|
|
|
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
|
|
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
|
|
15
|
-
`),
|
|
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 yt,{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 O(t,e){return t instanceof c&&(e===void 0||t.kind===e)}var Bt="/passport/open/get_device_code/",jt="/passport/open/check_device_code/",zt="/passport/open/refresh_token/",W="/api/cli/v1/authorization/device/report",qt="Bearer",qe="X-Tt-Logid",Xt=1,Wt=6,Jt=7,Yt=10,Zt=10010,Qt=10002,Y=10003,er=10005,Z=10021,Je=10042,Ye=10043,tr=10044,rr=10046,nr=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=ir(e.scopes??[]);i&&n.set("scope",i);let o=await this.postForm(Bt,n,void 0,r),s=q(o,or);return {deviceCode:U(s,"device_code"),userCode:U(s,"user_code"),verificationUri:U(s,"verification_uri"),intervalMs:X(s,"interval")*1e3,expiresInMs:X(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(jt,n,void 0,r),o=q(i,sr),s=Xe(o);return ur(s),{accessToken:U(o,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:X(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(zt,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},r),o=q(i,ar),s=Xe(o);return {accessToken:U(o,"access_token"),refreshToken:s.refresh_token,expiresInMs:X(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?`${W}?${i}`:W,s=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);return {uid:Ze(s,"uid")}}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(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(qe)??""});try{return JSON.parse(a)}catch(l){throw new c({kind:"DECODE",description:"decode envelope",cause:l})}}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(d){throw new c({kind:"TRANSPORT",description:"do request",cause:d})}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(qe)??""});let u;try{u=JSON.parse(l);}catch(d){throw new c({kind:"DECODE",description:"decode response envelope",cause:d})}let p=Ae(u,"code");if(p!==void 0){if(p===0)return Qe(u.data)?u.data:{};throw new c({kind:"SERVER",errorCode:p,description:v(u,"em")??v(u,"et")??"device report failed",descUrl:v(u,"trace_id")??""})}return q(u,Q)}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 ir(t){return t.map(e=>e.trim()).filter(Boolean).join(",")}function q(t,e){let r=Qe(t.data)?t.data:{};if(We(t.message,"success"))return r;if(!We(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 or(t,e){switch(t){case Y:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case Z:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return Q(t,e)}}function sr(t,e){switch(t){case Jt:return new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case nr:return cr(t,e);case Y:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case Z:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return Q(t,e)}}function ar(t,e){switch(t){case Zt:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case Je:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case Ye:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case Y:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case Z:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case er:case Qt:case tr:case rr:case Wt:return new c({kind:"SERVER",errorCode:t,description:e});default:return Q(t,e)}}function cr(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 Q(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 Y:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case Z:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case Je:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case Ye:case Xt:case Yt:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});}return new c({kind:"SERVER",errorCode:t,description:e})}function Xe(t){return {access_token:v(t,"access_token"),refresh_token:v(t,"refresh_token"),token_type:v(t,"token_type"),expires_in:Ae(t,"expires_in")}}function ur(t){if(t.token_type!==qt)throw new c({kind:"SERVER",description:"unexpected token_type"})}function U(t,e){let r=v(t,e);if(r===void 0||r.trim()==="")throw new c({kind:"DECODE",description:`missing or empty ${e}`});return r}function Ze(t,e){let r=Ae(t,e);if(r===void 0||!Number.isFinite(r))throw new c({kind:"DECODE",description:`missing or invalid ${e}`});return r}function X(t,e){let r=Ze(t,e);if(r<=0)throw new c({kind:"DECODE",description:`invalid ${e}`});return r}function v(t,e){let r=t[e];return typeof r=="string"?r:void 0}function Ae(t,e){let r=t[e];return typeof r=="number"?r:void 0}function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function We(t,e){return typeof t=="string"&&t.toLowerCase()===e.toLowerCase()}var et="ecdsa-p256-sha256";var fr=16,ee=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:et,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(fr).toString("hex"),o=gr(e.signingMaterial),s=createHash("sha256").update(o).digest("base64"),a=[e.method,e.urlPath,s,n,i].join(`
|
|
15
|
+
`),l=mr(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:i}}};function gr(t){return t===void 0?new Uint8Array:typeof t=="string"?Buffer.from(t):t}function mr(t,e){let r=t.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
|
|
16
16
|
${r.join(`
|
|
17
17
|
`)}
|
|
18
18
|
-----END ${e}-----
|
|
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=`
|
|
19
|
+
`}var te=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 te(t,`${e}: ${wr(t)}`,r)}function E(t,e){return t instanceof te&&(e===void 0||t.code===e)}function wr(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 rt=1e6;function m(t){nt(t);let e={client_key:t.clientKey,device_code:I(t.deviceCode),user_code:I(t.userCode),verification_uri:I(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*rt),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:I(t.accessToken),refresh_token:I(t.refreshToken),session_id:I(t.sessionId),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(Er(e))}function k(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/rt,loginExpiresAt:tt(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,sessionId:e.session_id,tokenExpiresAt:tt(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 nt(r),r}function nt(t){if(!t.clientKey.trim())throw g("CORRUPT_RECORD","validate",new Error("client_key is required"))}function G(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 tt(t){if(t)return new Date(t)}function I(t){return t===void 0||t===""?void 0:t}function Er(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var ot=promisify(execFile),Ir=createRequire(import.meta.url),kr=9e4,Dr=5*6e4,Nr=100,re="pico-auth-cli-managed-v2",$="pico-auth-cli-managed-v3",D="pico-auth-cli-managed-v3-legacy-ambiguous",K=class{constructor(e,r,n=Lr){this.serviceName=e;this.account=r;this.runner=n;H(e,r);}serviceName;account;runner;withRefreshLock(e){return R(this.serviceName,`${this.account}.auth-refresh`,e)}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 A("load",r)}if(e===null)throw g("NOT_FOUND","load",new Error("auth record not found"));try{return k(e)}catch(r){throw E(r)?r:g("DECODE_FAILED","load",r)}}async save(e){let r;try{r=m(e);}catch(n){throw A("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw A("save",$r(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 A("delete",e)}}},xr={async getPassword(t,e){try{let{stdout:r}=await ot("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(at(r))return null;throw r}},async deletePassword(t,e){try{return await ot("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(at(r))return false;throw r}}},lt={getPassword:(t,e)=>Re().getPassword(t,e),setPassword:(t,e,r)=>Re().setPassword(t,e,r),deletePassword:(t,e)=>Re().deletePassword(t,e)},Te=class{constructor(e=lt,r=xr,n=R){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let o of [Se(r),Ce(r)]){let s=await this.managed.getPassword(e,o);if(s!==null)return s}let n=await this.managed.getPassword(e,ve(r));if(n===$||n===D)return null;let i=await this.managed.getPassword(e,Pe(r));return i!==null?i:await this.managed.getPassword(e,st(r))===re?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let i=Se(r),o=Ce(r),s=ve(r);await this.managed.setPassword(e,i,n),await ne(this.managed,e,i,n,"recovery"),await this.managed.setPassword(e,o,n),await ne(this.managed,e,o,n,"primary"),await this.managed.setPassword(e,s,$),await ne(this.managed,e,s,$,"state"),await this.managed.deletePassword(e,i).catch(()=>{}),await this.managed.deletePassword(e,Pe(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[Se(r),Ce(r),Pe(r)],i=await Promise.all(n.map(_=>this.managed.getPassword(e,_))),o=ve(r),s=await this.managed.getPassword(e,o),a=st(r),l=await this.managed.getPassword(e,a);if(!(i.some(_=>_!==null)||s===$||s===D||l===re))return this.legacy.deletePassword(e,r);let d=i[2]!==null&&l!==re||s===D?D:$;await this.managed.setPassword(e,o,d),await ne(this.managed,e,o,d,"state");let w=false,C;for(let _ of n)try{w=await this.managed.deletePassword(e,_)||w;}catch(Vt){C??=Vt;}if(C!==void 0)throw C;if(l===re)try{let _=await this.managed.deletePassword(e,r);w=_||w,(_||await this.managed.getPassword(e,r)===null)&&(w=await this.managed.deletePassword(e,a)||w);}catch(_){C??=_;}else if(d!==D)try{w=await this.legacy.deletePassword(e,r)||w;}catch(_){C??=_;}if(C!==void 0)throw C;return d===D||(w=await this.managed.deletePassword(e,o)||w),w})}},Lr=process.platform==="darwin"?new Te:lt;function Re(){return Ir("keytar")}function Pe(t){return `${t}.pico-auth-cli-recovery-v1`}function st(t){return `${t}.pico-auth-cli-managed-v2`}function Se(t){return `${t}.pico-auth-cli-recovery-v3`}function Ce(t){return `${t}.pico-auth-cli-payload-v3`}function ve(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(),l=Date.now()+kr;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(F(u)!=="EEXIST")throw u;if(await ht(o)&&await br(o))continue;if(Date.now()>=l)throw new Error("timed out waiting for the credential store lock");await new Promise(p=>setTimeout(p,Nr));}try{return await r()}finally{await Gr(o,s,a).catch(()=>{});}}async function ht(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"&&!Ur(n.pid)}catch{return Date.now()-e.mtimeMs>=Dr}}catch{return false}}async function br(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if(F(n)==="EEXIST")return false;throw n}try{if(!await ht(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(i){if(F(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 Ur(t){try{return process.kill(t,0),!0}catch(e){return F(e)==="EPERM"}}async function Gr(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if(F(n)!=="ENOENT")throw n}}function F(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"?t.code:void 0}async function ne(t,e,r,n,i){if(await t.getPassword(e,r)!==n)throw new Error(`macOS Keychain ${i} write verification failed`)}function H(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function at(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 $r(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=ct(t,"code"),s=ct(t,"exitCode");return o!==void 0&&Object.assign(i,{code:o}),s!==void 0&&Object.assign(i,{exitCode:s}),i}function ct(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var se=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;withRefreshLock(e){return R(this.path,"auth-refresh",e)}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):A("load",r)}try{return k(e)}catch(r){throw E(r)?r:g("DECODE_FAILED","load",r)}}async save(e){let r=m(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(()=>{}),A("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 A("delete",e)}}};function gt(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",G(t),`${G(e)}.json`)}function A(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 Oe=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 mt(t,e,r,n=process.env){return new Promise((i,o)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),a=[],l=[],u=false,p=d=>{u||(u=true,o(d));};s.stdout.on("data",d=>a.push(Buffer.from(d))),s.stderr.on("data",d=>l.push(Buffer.from(d))),s.once("error",p),s.stdin.once("error",p),s.once("close",d=>{if(u)return;u=true;let w={stdout:Buffer.concat(a).toString(),stderr:Buffer.concat(l).toString()};if(d===0){i(w);return}o(new Oe(t,d,w.stderr));}),s.stdin.end(r);})}var Wr=promisify(execFile),Jr="Software\\BytedAuthClient\\keychain",ae=class{constructor(e,r,n=Yr){this.serviceName=e;this.account=r;this.runner=n;H(e,r);}serviceName;account;runner;withRefreshLock(e){return R(this.serviceName,`${this.account}.auth-refresh`,e)}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 A("load",r)}if(e===void 0)throw g("NOT_FOUND","load",new Error("auth record not found"));try{return k(e)}catch(r){throw E(r)?r:g("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,m(e));}catch(r){throw A("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 A("delete",e)}}},Yr={async get(t,e){let r=Buffer.from(wt(t,e)).toString("base64"),n=`
|
|
20
20
|
$ErrorActionPreference = 'Stop'
|
|
21
21
|
Add-Type -AssemblyName System.Security
|
|
22
|
-
$path = '${
|
|
23
|
-
$name = '${
|
|
22
|
+
$path = '${N(ke(t))}'
|
|
23
|
+
$name = '${N(De(e))}'
|
|
24
24
|
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path)
|
|
25
25
|
if ($null -eq $key) { exit 3 }
|
|
26
26
|
try { $value = $key.GetValue($name, $null) } finally { $key.Dispose() }
|
|
@@ -30,20 +30,20 @@ $entropy = [Convert]::FromBase64String('${r}')
|
|
|
30
30
|
$plain = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
|
|
31
31
|
[Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))
|
|
32
32
|
exit 0
|
|
33
|
-
`,i=await
|
|
33
|
+
`,i=await Ie(n);return i.missing?void 0:i.stdout},async set(t,e,r){let n=Buffer.from(r,"utf8").toString("base64");await Ie(Qr(t,e),n);},async delete(t,e){let r=`
|
|
34
34
|
$ErrorActionPreference = 'Stop'
|
|
35
|
-
$path = '${
|
|
36
|
-
$name = '${
|
|
35
|
+
$path = '${N(ke(t))}'
|
|
36
|
+
$name = '${N(De(e))}'
|
|
37
37
|
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path, $true)
|
|
38
38
|
if ($null -ne $key) {
|
|
39
39
|
try { $key.DeleteValue($name, $false) } finally { $key.Dispose() }
|
|
40
40
|
}
|
|
41
41
|
exit 0
|
|
42
|
-
`;await
|
|
42
|
+
`;await Ie(r);}};function ke(t){return `${Jr}\\${G(t)}`}function Zr(t){return `HKCU:\\${ke(t)}`}function De(t){return Buffer.from(t,"utf8").toString("base64url")}function wt(t,e){return Buffer.concat([Buffer.from(t,"utf8"),Buffer.from([0]),Buffer.from(e,"utf8")])}function Qr(t,e){let r=Buffer.from(wt(t,e)).toString("base64");return `
|
|
43
43
|
$ErrorActionPreference = 'Stop'
|
|
44
44
|
Add-Type -AssemblyName System.Security
|
|
45
|
-
$path = '${
|
|
46
|
-
$name = '${
|
|
45
|
+
$path = '${N(Zr(t))}'
|
|
46
|
+
$name = '${N(De(e))}'
|
|
47
47
|
New-Item -Path $path -Force | Out-Null
|
|
48
48
|
$encodedValue = [Console]::In.ReadToEnd()
|
|
49
49
|
$plain = [Convert]::FromBase64String($encodedValue)
|
|
@@ -52,31 +52,36 @@ $cipher = [Security.Cryptography.ProtectedData]::Protect($plain, $entropy, [Secu
|
|
|
52
52
|
$encoded = [Convert]::ToBase64String($cipher)
|
|
53
53
|
Set-ItemProperty -Path $path -Name $name -Value $encoded
|
|
54
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(`${
|
|
57
|
-
`);}function
|
|
55
|
+
`}async function Ie(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await Wr("powershell.exe",r):await mt("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 N(t){return t.replace(/'/g,"''")}var en="byted_cli_user_token";function ce(t,e=en,r=process.platform){switch(H(t,e),r){case "darwin":return new K(t,e);case "win32":return new ae(t,e);default:return new Ne(new K(t,e),new se(gt(t,e)),n=>R(t,e,n),n=>R(t,`${e}.auth-session`,n))}}var Ne=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(!E(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(()=>{}),g("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var Et={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"},f=class extends Error{code;cause;pendingLogin;constructor(e,r=Et[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 f(t,Et[t],e)}var on=createRequire(import.meta.url),sn="CN",M=3e3;function At(){return {name:_t(yt.hostname()||"unknown",128),os:fn(process.platform),osVersion:_t(yt.release()||"",64),architecture:gn(process.arch),cliVersion:mn(),region:an()}}function an(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(xe(t.readMacOSLocale??dn,void 0));else if(e==="win32"){let i=cn(xe(t.readWindowsRegion??ln,void 0));if(i)return i}else e==="linux"&&n.push(...pn(xe(t.readLinuxLocales??hn,[])));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=un(i);if(o)return o}return sn}function cn(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function un(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 dn(){return Rt("/usr/bin/defaults",["read","-g","AppleLocale"])}function ln(){return Rt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function hn(){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 pn(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 Rt(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function xe(t,e){try{return t()}catch{return e}}function fn(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function gn(t){return t==="x64"?"x86_64":t}function mn(){for(let t of ["../../package.json","../../../package.json"])try{let e=on(t);if(typeof e.version=="string")return e.version}catch{}return ""}function _t(t,e){return t.length>e?t.slice(0,e):t}var yn="/passport/open/refresh_token/",Tt="Bearer ",Ge=365*24*60*60*1e3,le=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();}}},he=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 ee,o=r.store??ce(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:i,store:o,now:r.now??(()=>new Date),mutex:new le,deviceReportUrl:new URL(W,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:Rn(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 Le(this.core)}authorizer(){return new pe(this.core)}},Le=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 V(this.core.store);return St(a,this.core.now()),a?m(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 vt(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 V(this.core.store);if(St(a,this.core.now()),(a?m(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 ue(this.core.store);return this.checkLoginRecord(i,n,r)})}async checkPendingLogin(e){return this.core.mutex.run(async()=>{let r=await V(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=m(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 fe(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=vt(s);throw a.code==="LOGIN_PENDING"&&(await de(this.core.store,()=>$e(this.core.store,i,"LOGIN_SUPERSEDED")),e.verificationUri&&e.loginExpiresAt)?new f("LOGIN_PENDING",void 0,s,{verificationUri:e.verificationUri,expiresAt:new Date(e.loginExpiresAt)}):((a.code==="LOGIN_EXPIRED"||a.code==="LOGIN_DENIED")&&await fe(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,e.sessionId=randomUUID(),o.refreshToken&&(e.refreshToken=o.refreshToken),e.tokenExpiresAt=new Date(this.core.now().getTime()+o.expiresInMs),await kt(this.core.store,e,i,"LOGIN_SUPERSEDED"),await Ot(this.core,e,n),Ue(this.core.now(),e)}authorizer(){return new pe(this.core)}},pe=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 Ue(this.core.now(),r)}catch(r){if(r instanceof f&&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 Ue(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");It(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await x(this.core.store,()=>this.core.store.updateUserInfo(e));}catch(r){throw P(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await ue(this.core.store);return Nt(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await x(this.core.store,()=>this.core.store.delete());}catch(e){if(!E(e,"NOT_FOUND"))throw P(e)}})}async ensureActiveRecord(e,r){let n=await ue(this.core.store),i=m(n);if(!n.accessToken)throw h("NOT_LOGGED_IN");let o=this.core.now();if(Dt(o,n.tokenExpiresAt,e))return n;let s=async()=>{r?.throwIfAborted();let a=await ue(this.core.store);if(m(a)!==i){if(Pt(n,a,this.core.now(),e))return a;throw h("NOT_LOGGED_IN")}return this.refreshRecord(n,i,e,r)};try{return this.core.store.withRefreshLock?await this.core.store.withRefreshLock(s):await s()}catch(a){throw a instanceof f||r?.aborted?a:P(a)}}async reuseConcurrentRefresh(e,r){return de(this.core.store,async()=>{let n=await V(this.core.store);return n&&Pt(e,n,this.core.now(),r)?n:void 0})}async refreshRecord(e,r,n,i){if(!e.refreshToken||!e.deviceKey)throw await fe(this.core.store,r),h("NOT_LOGGED_IN");let o;try{o=this.core.signer.sign({method:"POST",urlPath:yn,signingMaterial:e.refreshToken},e.deviceKey);}catch(p){throw h("SIGN_FAILED",p)}let s,a=e.accessToken;try{s=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:e.refreshToken,pubKey:o.pubKey,reqSign:o.signature,reqTs:o.timestamp,reqNonce:o.nonce},i);}catch(p){i?.throwIfAborted();let d=await this.reuseConcurrentRefresh(e,n);if(d)return d;throw Pn(p)?(await fe(this.core.store,r),h("NOT_LOGGED_IN")):h("REFRESH_FAILED",p)}let l=be(e),u={...e};e.accessToken=s.accessToken,e.sessionId=l,s.refreshToken&&(e.refreshToken=s.refreshToken),e.tokenExpiresAt=new Date(this.core.now().getTime()+s.expiresInMs);try{await kt(this.core.store,e,r);}catch(p){if(!(p instanceof f)||p.code!=="NOT_LOGGED_IN")throw p;let d=await this.reuseConcurrentRefresh(u,n);if(d)return d;throw p}return a!==e.accessToken&&await Ot(this.core,e,i),e}};function be(t){return t.sessionId??createHash("sha256").update(JSON.stringify([t.clientKey,t.deviceKey,t.refreshToken])).digest("hex")}function Pt(t,e,r,n){return !!(t.refreshToken&&e.refreshToken&&e.accessToken&&be(t)===be(e)&&t.clientKey===e.clientKey&&JSON.stringify(t.deviceKey)===JSON.stringify(e.deviceKey)&&!e.deviceCode&&!e.loginContext&&e.tokenExpiresAt&&r<e.tokenExpiresAt&&Dt(r,e.tokenExpiresAt,n===Ge?0:n)&&(e.accessToken!==t.accessToken||e.refreshToken!==t.refreshToken||e.tokenExpiresAt?.getTime()!==t.tokenExpiresAt?.getTime()))}async function Ot(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{It(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=Tt+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((l,u)=>{s=setTimeout(()=>{i.abort(),u(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{let l=await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:At()},i.signal),a]);await x(t.store,async()=>{let u=await t.store.load();if(u.clientKey!==e.clientKey||u.accessToken!==e.accessToken)return;let p=_n(u.userInfo,l.uid);await t.store.save({...u,userInfo:p}),e.userInfo=p;});}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",o);}}function _n(t,e){return An(t)?{...t,uid:e}:{uid:e}}function An(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function It(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)}T(r,"Authorization",Tt+e.accessToken),T(r,"X-Pub-Key",s.pubKey),T(r,"X-Req-Sign",s.signature),T(r,"X-Req-Ts",s.timestamp),T(r,"X-Req-Nonce",s.nonce),T(r,"X-Req-Method",i),T(r,"X-Req-Path",o);}function Rn(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):M}async function ue(t){try{return await t.load()}catch(e){throw P(e)}}async function V(t){try{return await t.load()}catch(e){if(E(e,"NOT_FOUND"))return;throw P(e)}}function St(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 x(t,e)}catch(r){throw r instanceof f?r:P(r)}}async function kt(t,e,r,n="NOT_LOGGED_IN"){try{await x(t,async()=>{r!==void 0&&await $e(t,r,n),await t.save(e);});}catch(i){throw i instanceof f?i:P(i)}}async function fe(t,e,r="NOT_LOGGED_IN"){try{await x(t,async()=>{await $e(t,e,r),await t.delete();});}catch(n){if(n instanceof f)throw n;if(!E(n,"NOT_FOUND"))throw P(n)}}async function $e(t,e,r="NOT_LOGGED_IN"){let n=await V(t);if(!n||m(n)!==e)throw h(r)}var Ct=new WeakMap;async function x(t,e){if(t.withLock)return t.withLock(e);let r=Ct.get(t);return r||(r=new le,Ct.set(t,r)),r.run(e)}function P(t){return E(t,"NOT_FOUND")?h("NOT_LOGGED_IN",t):h("STORE_UNAVAILABLE",t)}function vt(t){return O(t,"AUTHORIZATION_PENDING")?h("LOGIN_PENDING",t):O(t,"ACCESS_DENIED")?h("LOGIN_DENIED",t):O(t,"EXPIRED_TOKEN")?h("LOGIN_EXPIRED",t):h("PROTOCOL_ERROR",t)}function Pn(t){return O(t,"EXPIRED_TOKEN")||O(t,"INVALID_GRANT")}function Dt(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Ue(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:Nt(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function T(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function Nt(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var xt=["pico_vibe_lab","pico_ai_sgs","user_info"],Lt="https://user.picoxr.com",vn=/^ppe_[A-Za-z0-9_-]+$/,bt={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:Lt,deviceReportTimeoutMs:M};function Ke(t={}){let e=t.ppeHeader?Tn(t.ppeHeader):void 0;return {...bt,scopes:Ut(xt,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function Tn(t){if(!vn.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 Ut(t,e){let r=new Set;for(let n of [...t,...e]){let i=n.trim();i&&r.add(i);}return [...r]}function Gt(t={},e={}){let r=Ke(t),n=e.store??ce(r.storeServiceName),i=new he(r,{...e,store:n});return {getStatus(o){return On(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(Ge,o)},injectAuth(o,s){return i.authorizer().inject(o,s)},logout(){return i.authorizer().logout()}}}async function On(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:In(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(E(n,"NOT_FOUND"))return {loggedIn:false};throw h("STORE_UNAVAILABLE",n)}}function In(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var kn=/^(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)$/i,Dn=/(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)(["'\s:=]+)(?:Bearer\s+)?([^"'\s,}]+)/gi;function L(t,e,r){if(t.json){t.stdout(`${JSON.stringify(S(r))}
|
|
56
|
+
`);return}for(let n of e)t.stdout(`${b(n)}
|
|
57
|
+
`);}function B(t,e){let r=S(e);if(t.json){t.stderr(`${JSON.stringify({ok:false,...r})}
|
|
58
58
|
`);return}t.stderr(`error=${r.code}
|
|
59
59
|
`),t.stderr(`message=${r.message}
|
|
60
60
|
`),t.stderr(`recoverable=${r.recoverable}
|
|
61
61
|
`),t.stderr(`action=${r.action}
|
|
62
62
|
`),r.stage&&t.stderr(`stage=${r.stage}
|
|
63
|
-
`);}function
|
|
63
|
+
`);}function $t(t,e,r={}){let n=S({event:e,...r});if(t.json){t.stderr(`${JSON.stringify({ok:true,verbose:n})}
|
|
64
64
|
`);return}let i=Object.entries(n).map(([o,s])=>`${o}=${String(s)}`).join(" ");t.stderr(`verbose ${i}
|
|
65
|
-
`);}function
|
|
66
|
-
`),0;let s=e.createClient??
|
|
67
|
-
`),0):await
|
|
65
|
+
`);}function S(t){if(Array.isArray(t))return t.map(e=>S(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]=kn.test(r)?"[REDACTED]":S(n);return e}return typeof t=="string"?b(t):t}function b(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(Dn,(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 Ln=1e3,bn=12e4,Ve=4,Be=2,Kt=3,Fe=5,je=6,Un=7,Gn=8,we={NOT_LOGGED_IN:{message:"You are not signed in.",action:"Run pico-auth-cli-cn login.",exitCode:Kt},LOGIN_PENDING:{message:"Authorization is not complete yet.",action:"Complete browser authorization, then rerun pico-auth-cli-cn login --resume <device_code>.",exitCode:Ve},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:Ve},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:Kt},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:Fe},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:Be},LOGIN_DENIED:{message:"Authorization was denied.",action:"Restart login and approve the PICO authorization request.",exitCode:Gn},LOGIN_EXPIRED:{message:"The sign-in request has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:Fe},TOKEN_EXPIRED:{message:"The session has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:Fe},REFRESH_FAILED:{message:"The session could not be refreshed.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:je},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:Un},PROTOCOL_ERROR:{message:"The PICO authentication service returned an unexpected response.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:je},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:Be}};async function Ft(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=Qn(t);if(i.json=o.global.json,!o.command||o.command==="--help"||o.command==="-h")return ai(r),0;if(o.command==="--version"||o.command==="-v")return r(`${(e.readVersion??ui)()}
|
|
66
|
+
`),0;let s=e.createClient??Gt;switch(o.command){case "login":return j(o.args)?(r(`${Ht()}
|
|
67
|
+
`),0):await $n(o.args,o.global,s,i,e);case "status":return j(o.args)?(r(`Usage:
|
|
68
68
|
pico-auth-cli-cn status [--json]
|
|
69
|
-
`),0):await
|
|
70
|
-
|
|
69
|
+
`),0):await Kn(o.args,o.global,s,i);case "userinfo":return j(o.args)?(r(`Usage:
|
|
70
|
+
pico-auth-cli-cn userinfo [--json]
|
|
71
|
+
`),0):await Fn(o.args,o.global,s,i);case "refresh":return j(o.args)?(r(`${ci()}
|
|
72
|
+
`),0):await Hn(o.args,o.global,s,i);case "logout":return j(o.args)?(r(`Usage:
|
|
71
73
|
pico-auth-cli-cn logout [--json]
|
|
72
|
-
`),0):await
|
|
73
|
-
`);let u=await
|
|
74
|
-
`),t.stdout(` ${
|
|
74
|
+
`),0):await Mn(o.args,o.global,s,i);default:throw new y(`unknown command: ${o.command}`)}}catch(o){return o instanceof z?(Wn(i,o.pendingLogin),Ve):o instanceof Ee?(B(i,ge("LOGIN_TIMEOUT",o.message,i.stage)),je):o instanceof y?(B(i,ge("INVALID_ARGUMENT",o.message,i.stage)),Be):o instanceof f?(B(i,ge(o.code,ni(o.code),i.stage)),ri(o)):(B(i,ge("UNKNOWN","An unexpected error occurred.",i.stage)),1)}}async function $n(t,e,r,n,i){let o=ei(t),s=r({scopes:o.scopes,ppeHeader:e.ppeHeader});if(o.resume){n.stage="collect_authorization";let d=await Vn(s,o.resume);return He(n,"login_resumed",d),0}if(o.resumePending){n.stage="collect_authorization";try{let d=await s.resumePendingLogin();return He(n,"login_resumed",d),0}catch(d){throw d instanceof f&&d.code==="LOGIN_PENDING"?new z(d.pendingLogin):d}}n.stage="read_local_state";let a=await s.getStatus();if(a.loggedIn&&!o.force)return me(e,n,"login_existing_state"),Xn(n,a),0;o.force&&(me(e,n,"login_force_clear"),await s.logout()),n.stage="create_login";let l=await s.startLogin();if(ze(l.verificationUri),me(e,n,"login_started",{verification_uri:l.verificationUri,expires_at:l.expiresAt}),o.noWait)return jn(n,l,e.ppeHeader),0;n.json||n.stdout(`Opening your browser to sign in to PICO...
|
|
75
|
+
`);let u=await Yn(l.verificationUri,e,n,i.openBrowser);Jn(n,l,u),n.stage="await_authorization";let p=await Bn(s,l,o.timeoutMs,i.sleep??si,i.now??(()=>new Date));return He(n,"authenticated",p),0}async function Kn(t,e,r,n){_e("status",t),n.stage="read_local_state";let o=await r({ppeHeader:e.ppeHeader}).getStatus();return ye(n,"status",o),0}async function Fn(t,e,r,n){_e("userinfo",t);let o=await r({ppeHeader:e.ppeHeader}).getStatus();return zn(n,o.identity),0}async function Hn(t,e,r,n){_e("refresh",t),n.stage="refresh_session";let o=await r({ppeHeader:e.ppeHeader}).refresh();return ye(n,"refreshed",o),0}async function Mn(t,e,r,n){return _e("logout",t),n.stage="clear_local_state",await r({ppeHeader:e.ppeHeader}).logout(),L(n,["Signed out successfully."],{ok:true,loggedOut:true}),0}async function Vn(t,e){try{return await t.resumeLogin(e)}catch(r){throw r instanceof f&&r.code==="LOGIN_PENDING"?new z(r.pendingLogin):r}}async function Bn(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 f&&s.code==="LOGIN_PENDING"){await n(Ln);continue}throw s}throw i().getTime()>=e.expiresAt.getTime()?new f("LOGIN_EXPIRED"):new Ee("Waiting for authorization timed out. The pending sign-in request was preserved.")}function jn(t,e,r){if(!t.json){t.stdout(`Sign-in request created. Open this page to sign in to PICO and authorize access:
|
|
76
|
+
`),t.stdout(` ${b(e.verificationUri)}
|
|
75
77
|
`),t.stdout(`Sign-in request expires at: ${e.expiresAt.toISOString()}
|
|
76
78
|
`),t.stdout(`After completing authorization in your browser, run:
|
|
77
79
|
`);let n=r?` --ppe_header=${r}`:"";t.stdout(` pico-auth-cli-cn${n} login --resume '${e.deviceCode}'
|
|
78
|
-
`);return}
|
|
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"),
|
|
80
|
+
`);return}L(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 ye(t,e,r){if(!t.json){if(e==="status"){qn(t,r);return}if(e==="refreshed"){t.stdout(`Session refreshed successfully.
|
|
81
|
+
`);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"),L(t,i,n);}function zn(t,e){let r=e??null;if(!t.json){if(r===null){t.stdout(`No cached user information.
|
|
82
|
+
`);return}t.stdout(`Cached user information:
|
|
83
|
+
`),t.stdout(`${JSON.stringify(S(r),null,2)}
|
|
84
|
+
`);return}L(t,[],{ok:true,user_info:r});}function qn(t,e){if(!e.loggedIn){if(e.loginExpiresAt){t.stdout(e.pending?`Status: Waiting for authorization.
|
|
80
85
|
`:`Status: Sign-in request expired.
|
|
81
86
|
`),t.stdout(`Request expires at: ${e.loginExpiresAt.toISOString()}
|
|
82
87
|
`),t.stdout(e.pending?`Complete browser authorization, then run pico-auth-cli-cn login --resume-pending.
|
|
@@ -86,19 +91,19 @@ exit 0
|
|
|
86
91
|
`);return}t.stdout(`Status: Signed in.
|
|
87
92
|
`),e.expiresAt&&t.stdout(`Expires at: ${e.expiresAt.toISOString()}
|
|
88
93
|
`),e.scopes?.length&&t.stdout(`Authorized scopes: ${e.scopes.join(", ")}
|
|
89
|
-
`);}function
|
|
94
|
+
`);}function He(t,e,r){if(t.json){ye(t,e,r);return}t.stdout(`
|
|
90
95
|
Signed in successfully.
|
|
91
|
-
`);}function
|
|
96
|
+
`);}function Xn(t,e){if(t.json){ye(t,"already_authenticated",e);return}t.stdout(`You are already signed in.
|
|
92
97
|
`),t.stdout(`To switch accounts, run pico-auth-cli-cn login --force.
|
|
93
|
-
`);}function
|
|
94
|
-
`),r&&t.stdout(`Sign-in page: ${
|
|
95
|
-
`);}function
|
|
98
|
+
`);}function Wn(t,e){let r;if(e)try{ze(e.verificationUri),r=e.verificationUri;}catch{}if(t.json){L(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.
|
|
99
|
+
`),r&&t.stdout(`Sign-in page: ${b(r)}
|
|
100
|
+
`);}function Jn(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(S(n))}
|
|
96
101
|
`);return}r?t.stdout(`The PICO sign-in page is open in your default browser.
|
|
97
102
|
`):t.stdout(`We couldn't open your browser automatically. Open the sign-in page below.
|
|
98
103
|
`),t.stdout(`Complete sign-in and authorization in your browser, then return here. The CLI will continue automatically.
|
|
99
|
-
`),t.stdout(`Sign-in page: ${
|
|
104
|
+
`),t.stdout(`Sign-in page: ${b(e.verificationUri)}
|
|
100
105
|
`),t.stdout(`Waiting for authorization. Keep this window open...
|
|
101
|
-
`);}async function
|
|
106
|
+
`);}async function Yn(t,e,r,n){ze(t);try{return n?(await n(t),!0):(await Zn(t),!0)}catch{return me(e,r,"browser_open_failed",{message:"The browser could not be opened automatically.",verification_uri:t}),false}}async function Zn(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 ze(t){let e;try{e=new URL(t);}catch(r){throw new f("INVALID_ARGUMENT","The verification URI returned by the authentication service is invalid.",r)}if(e.protocol!=="https:")throw new f("INVALID_ARGUMENT","The verification URI returned by the authentication service must use HTTPS.")}function Qn(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 y("--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 y("--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 ei(t){let e={force:false,noWait:false,resumePending:false,scopes:[],timeoutMs:bn};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=Me(t,++r,"--resume");break;case "--resume-pending":e.resumePending=true;break;case "--scope":e.scopes.push(Me(t,++r,"--scope"));break;case "--timeout":e.timeoutMs=ti(Me(t,++r,"--timeout"));break;case "--help":case "-h":throw new y(Ht());default:throw new y(`login: unknown option ${n}`)}}if(e.resume&&e.resumePending)throw new y("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 y("login resume options cannot be combined with --force, --no-wait, --scope, or --timeout");return e}function Me(t,e,r){let n=t[e];if(!n||n.startsWith("--"))throw new y(`${r} requires a value`);return n}function ti(t){let e=t.trim().match(/^(\d+)(ms|s|m)?$/);if(!e)throw new y(`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 y(`invalid duration: ${t}`);return o}function _e(t,e){if(e.length!==0)throw new y(`${t} does not accept arguments`)}function j(t){return t.includes("--help")||t.includes("-h")}function me(t,e,r,n){t.verbose&&$t(e,r,n);}function ri(t){return we[t.code].exitCode}function ge(t,e,r){let n=ii(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 ni(t){return we[t].message}function ii(t){let e=oi(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 oi(t){return Object.hasOwn(we,t)?we[t]:void 0}function si(t){return new Promise(e=>setTimeout(e,t))}function ai(t){t(`pico-auth-cli-cn
|
|
102
107
|
|
|
103
108
|
Usage:
|
|
104
109
|
pico-auth-cli-cn login [--force] [--scope <scope> ...]
|
|
@@ -106,6 +111,7 @@ Usage:
|
|
|
106
111
|
pico-auth-cli-cn login --resume <device_code>
|
|
107
112
|
pico-auth-cli-cn login --resume-pending
|
|
108
113
|
pico-auth-cli-cn status
|
|
114
|
+
pico-auth-cli-cn userinfo
|
|
109
115
|
pico-auth-cli-cn refresh
|
|
110
116
|
pico-auth-cli-cn logout
|
|
111
117
|
pico-auth-cli-cn --version
|
|
@@ -119,9 +125,10 @@ Global options:
|
|
|
119
125
|
Commands:
|
|
120
126
|
login Start or resume PICO device login.
|
|
121
127
|
status Read local authentication status without refreshing.
|
|
128
|
+
userinfo Read cached user information without refreshing.
|
|
122
129
|
refresh Refresh and validate the server-backed login state.
|
|
123
130
|
logout Clear local authentication state.
|
|
124
|
-
`);}function
|
|
131
|
+
`);}function Ht(){return `Usage:
|
|
125
132
|
pico-auth-cli-cn login [--force] [--scope <scope> ...] [--timeout 120s]
|
|
126
133
|
pico-auth-cli-cn login --no-wait [--force] [--scope <scope> ...]
|
|
127
134
|
pico-auth-cli-cn login --resume <device_code>
|
|
@@ -138,10 +145,10 @@ Options:
|
|
|
138
145
|
--timeout <duration> Time to wait for browser authorization. Default: 120s.
|
|
139
146
|
|
|
140
147
|
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
|
|
148
|
+
Local waiting timeout preserves that request. Resume it using the same region and PPE options.`}function ci(){return `Usage:
|
|
142
149
|
pico-auth-cli-cn refresh [--json]
|
|
143
150
|
|
|
144
151
|
Contacts the PICO authentication service and updates the stored login state.
|
|
145
152
|
After a business service reports NOT_LOGGED_IN, run refresh once and then run
|
|
146
153
|
pico-auth-cli-cn --json status. If Auth remains authenticated but the business service still
|
|
147
|
-
rejects the session, report the sanitized business error to the service support team.`}function
|
|
154
|
+
rejects the session, report the sanitized business error to the service support team.`}function ui(){let t=new URL("../../../package.json",import.meta.url);return JSON.parse(readFileSync(t,"utf8")).version??"0.0.0"}var z=class extends Error{constructor(r){super("authorization pending");this.pendingLogin=r;}pendingLogin},Ee=class extends Error{},y=class extends Error{};async function li(t=process.argv.slice(2)){return Ft(t)}function hi(){let t=process.argv[1];return t?realpathSync(fileURLToPath(import.meta.url))===realpathSync(t):false}hi()&&li().then(t=>{process.exitCode=t;}).catch(t=>{console.error(t instanceof Error?t.message:String(t)),process.exitCode=1;});export{li as main};
|
package/dist/src/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ interface ProtocolClient {
|
|
|
2
2
|
getDeviceCode(req: GetDeviceCodeRequest, signal?: AbortSignal): Promise<GetDeviceCodeResponse>;
|
|
3
3
|
checkDeviceCode(req: CheckDeviceCodeRequest, signal?: AbortSignal): Promise<CheckDeviceCodeResponse>;
|
|
4
4
|
refreshToken(req: RefreshTokenRequest, signal?: AbortSignal): Promise<RefreshTokenResponse>;
|
|
5
|
-
reportDeviceAuthorization(req: ReportDeviceAuthorizationRequest, signal?: AbortSignal): Promise<
|
|
5
|
+
reportDeviceAuthorization(req: ReportDeviceAuthorizationRequest, signal?: AbortSignal): Promise<ReportDeviceAuthorizationResponse>;
|
|
6
6
|
}
|
|
7
7
|
interface GetDeviceCodeRequest {
|
|
8
8
|
clientKey: string;
|
|
@@ -49,6 +49,9 @@ interface ReportDeviceAuthorizationRequest {
|
|
|
49
49
|
headers: Record<string, string>;
|
|
50
50
|
deviceInfo: DeviceInfo;
|
|
51
51
|
}
|
|
52
|
+
interface ReportDeviceAuthorizationResponse {
|
|
53
|
+
uid: number;
|
|
54
|
+
}
|
|
52
55
|
|
|
53
56
|
interface DeviceKey {
|
|
54
57
|
Algorithm: string;
|
|
@@ -81,6 +84,8 @@ interface AuthRecord {
|
|
|
81
84
|
loginContext?: LoginContext;
|
|
82
85
|
accessToken?: string;
|
|
83
86
|
refreshToken?: string;
|
|
87
|
+
/** Stable identity of a completed login, retained across token rotation. */
|
|
88
|
+
sessionId?: string;
|
|
84
89
|
tokenExpiresAt?: Date;
|
|
85
90
|
deviceKey?: DeviceKey;
|
|
86
91
|
userInfo?: unknown;
|
|
@@ -95,6 +100,8 @@ interface LoginContext {
|
|
|
95
100
|
interface AuthStore {
|
|
96
101
|
/** Serialize session checks and mutations across clients sharing this store. */
|
|
97
102
|
withLock?<T>(operation: () => Promise<T>): Promise<T>;
|
|
103
|
+
/** Coordinate token rotation without blocking login or logout mutations. */
|
|
104
|
+
withRefreshLock?<T>(operation: () => Promise<T>): Promise<T>;
|
|
98
105
|
load(): Promise<AuthRecord>;
|
|
99
106
|
save(record: AuthRecord): Promise<void>;
|
|
100
107
|
updateUserInfo(userInfo: unknown): Promise<void>;
|
package/dist/src/index.js
CHANGED
|
@@ -9,17 +9,17 @@
|
|
|
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
|
|
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
|
|
14
|
-
`),
|
|
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 Qe,{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 T(t,e){return t instanceof c&&(e===void 0||t.kind===e)}var wt="/passport/open/get_device_code/",yt="/passport/open/check_device_code/",At="/passport/open/refresh_token/",M="/api/cli/v1/authorization/device/report",Rt="Bearer",ve="X-Tt-Logid",_t=1,St=6,Pt=7,Ct=10,Tt=10010,vt=10002,B=10003,kt=10005,j=10021,Ie=10042,Oe=10043,Dt=10044,It=10046,Ot=1080,V=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=Nt(e.scopes??[]);o&&n.set("scope",o);let i=await this.postForm(wt,n,void 0,r),s=F(i,Lt);return {deviceCode:N(s,"device_code"),userCode:N(s,"user_code"),verificationUri:N(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 o=await this.postForm(yt,n,void 0,r),i=F(o,xt),s=ke(i);return Gt(s),{accessToken:N(i,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:H(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(At,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},r),i=F(o,bt),s=ke(i);return {accessToken:N(i,"access_token"),refreshToken:s.refresh_token,expiresInMs:H(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?`${M}?${o}`:M,s=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);return {uid:Ne(s,"uid")}}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(f){throw new c({kind:"TRANSPORT",description:"do request",cause:f})}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(ve)??""});try{return JSON.parse(a)}catch(f){throw new c({kind:"DECODE",description:"decode envelope",cause:f})}}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 f=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(ve)??""});let u;try{u=JSON.parse(f);}catch(h){throw new c({kind:"DECODE",description:"decode response envelope",cause:h})}let l=ce(u,"code");if(l!==void 0){if(l===0)return Le(u.data)?u.data:{};throw new c({kind:"SERVER",errorCode:l,description:P(u,"em")??P(u,"et")??"device report failed",descUrl:P(u,"trace_id")??""})}return F(u,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 Nt(t){return t.map(e=>e.trim()).filter(Boolean).join(",")}function F(t,e){let r=Le(t.data)?t.data:{};if(De(t.message,"success"))return r;if(!De(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 Lt(t,e){switch(t){case B:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case j:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return X(t,e)}}function xt(t,e){switch(t){case Pt:return new c({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case Ot:return Ut(t,e);case B:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case j:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return X(t,e)}}function bt(t,e){switch(t){case Tt:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case Ie:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case Oe:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case B:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case j:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case kt:case vt:case Dt:case It:case St:return new c({kind:"SERVER",errorCode:t,description:e});default:return X(t,e)}}function Ut(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 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 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 B:return new c({kind:"INVALID_CLIENT",errorCode:t,description:e});case j:return new c({kind:"ACCESS_DENIED",errorCode:t,description:e});case Ie:return new c({kind:"INVALID_GRANT",errorCode:t,description:e});case Oe:case _t:case Ct:return new c({kind:"EXPIRED_TOKEN",errorCode:t,description:e});}return new c({kind:"SERVER",errorCode:t,description:e})}function ke(t){return {access_token:P(t,"access_token"),refresh_token:P(t,"refresh_token"),token_type:P(t,"token_type"),expires_in:ce(t,"expires_in")}}function Gt(t){if(t.token_type!==Rt)throw new c({kind:"SERVER",description:"unexpected token_type"})}function N(t,e){let r=P(t,e);if(r===void 0||r.trim()==="")throw new c({kind:"DECODE",description:`missing or empty ${e}`});return r}function Ne(t,e){let r=ce(t,e);if(r===void 0||!Number.isFinite(r))throw new c({kind:"DECODE",description:`missing or invalid ${e}`});return r}function H(t,e){let r=Ne(t,e);if(r<=0)throw new c({kind:"DECODE",description:`invalid ${e}`});return r}function P(t,e){let r=t[e];return typeof r=="string"?r:void 0}function ce(t,e){let r=t[e];return typeof r=="number"?r:void 0}function Le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function De(t,e){return typeof t=="string"&&t.toLowerCase()===e.toLowerCase()}var xe="ecdsa-p256-sha256";var Mt=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:xe,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(Mt).toString("hex"),i=Vt(e.signingMaterial),s=createHash("sha256").update(i).digest("base64"),a=[e.method,e.urlPath,s,n,o].join(`
|
|
14
|
+
`),f=Bt(r.PrivateKeyBase64,"PRIVATE KEY"),u=sign("sha256",Buffer.from(a),{key:f,dsaEncoding:"der"});return {pubKey:r.PublicKeyBase64,signature:u.toString("base64"),timestamp:n,nonce:o}}};function Vt(t){return t===void 0?new Uint8Array:typeof t=="string"?Buffer.from(t):t}function Bt(t,e){let r=t.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
|
|
15
15
|
${r.join(`
|
|
16
16
|
`)}
|
|
17
17
|
-----END ${e}-----
|
|
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=`
|
|
18
|
+
`}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 p(t,e,r){return new q(t,`${e}: ${jt(t)}`,r)}function E(t,e){return t instanceof q&&(e===void 0||t.code===e)}function jt(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 Ue=1e6;function g(t){Ge(t);let e={client_key:t.clientKey,device_code:v(t.deviceCode),user_code:v(t.userCode),verification_uri:v(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*Ue),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:v(t.accessToken),refresh_token:v(t.refreshToken),session_id:v(t.sessionId),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(Xt(e))}function k(t){if(t.trim()==="")throw p("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(t);}catch(n){throw p("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/Ue,loginExpiresAt:be(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,sessionId:e.session_id,tokenExpiresAt:be(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 Ge(r),r}function Ge(t){if(!t.clientKey.trim())throw p("CORRUPT_RECORD","validate",new Error("client_key is required"))}function L(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 be(t){if(t)return new Date(t)}function v(t){return t===void 0||t===""?void 0:t}function Xt(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var $e=promisify(execFile),nr=createRequire(import.meta.url),or=9e4,ir=5*6e4,sr=100,J="pico-auth-cli-managed-v2",x="pico-auth-cli-managed-v3",D="pico-auth-cli-managed-v3-legacy-ambiguous",b=class{constructor(e,r,n=cr){this.serviceName=e;this.account=r;this.runner=n;G(e,r);}serviceName;account;runner;withRefreshLock(e){return R(this.serviceName,`${this.account}.auth-refresh`,e)}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 A("load",r)}if(e===null)throw p("NOT_FOUND","load",new Error("auth record not found"));try{return k(e)}catch(r){throw E(r)?r:p("DECODE_FAILED","load",r)}}async save(e){let r;try{r=g(e);}catch(n){throw A("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw A("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 A("delete",e)}}},ar={async getPassword(t,e){try{let{stdout:r}=await $e("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(He(r))return null;throw r}},async deletePassword(t,e){try{return await $e("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(He(r))return false;throw r}}},je={getPassword:(t,e)=>ue().getPassword(t,e),setPassword:(t,e,r)=>ue().setPassword(t,e,r),deletePassword:(t,e)=>ue().deletePassword(t,e)},pe=class{constructor(e=je,r=ar,n=R){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let i of [he(r),le(r)]){let s=await this.managed.getPassword(e,i);if(s!==null)return s}let n=await this.managed.getPassword(e,fe(r));if(n===x||n===D)return null;let o=await this.managed.getPassword(e,de(r));return o!==null?o:await this.managed.getPassword(e,Fe(r))===J?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let o=he(r),i=le(r),s=fe(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,x),await W(this.managed,e,s,x,"state"),await this.managed.deletePassword(e,o).catch(()=>{}),await this.managed.deletePassword(e,de(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[he(r),le(r),de(r)],o=await Promise.all(n.map(y=>this.managed.getPassword(e,y))),i=fe(r),s=await this.managed.getPassword(e,i),a=Fe(r),f=await this.managed.getPassword(e,a);if(!(o.some(y=>y!==null)||s===x||s===D||f===J))return this.legacy.deletePassword(e,r);let h=o[2]!==null&&f!==J||s===D?D:x;await this.managed.setPassword(e,i,h),await W(this.managed,e,i,h,"state");let m=false,S;for(let y of n)try{m=await this.managed.deletePassword(e,y)||m;}catch(Et){S??=Et;}if(S!==void 0)throw S;if(f===J)try{let y=await this.managed.deletePassword(e,r);m=y||m,(y||await this.managed.getPassword(e,r)===null)&&(m=await this.managed.deletePassword(e,a)||m);}catch(y){S??=y;}else if(h!==D)try{m=await this.legacy.deletePassword(e,r)||m;}catch(y){S??=y;}if(S!==void 0)throw S;return h===D||(m=await this.managed.deletePassword(e,i)||m),m})}},cr=process.platform==="darwin"?new pe:je;function ue(){return nr("keytar")}function de(t){return `${t}.pico-auth-cli-recovery-v1`}function Fe(t){return `${t}.pico-auth-cli-managed-v2`}function he(t){return `${t}.pico-auth-cli-recovery-v3`}function le(t){return `${t}.pico-auth-cli-payload-v3`}function fe(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 o=createHash("sha256").update(t).update("\0").update(e).digest("hex"),i=join(n,`${o}.lock`),s=join(i,"owner.json"),a=randomUUID(),f=Date.now()+or;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(U(u)!=="EEXIST")throw u;if(await Xe(i)&&await ur(i))continue;if(Date.now()>=f)throw new Error("timed out waiting for the credential store lock");await new Promise(l=>setTimeout(l,sr));}try{return await r()}finally{await hr(i,s,a).catch(()=>{});}}async function Xe(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"&&!dr(n.pid)}catch{return Date.now()-e.mtimeMs>=ir}}catch{return false}}async function ur(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if(U(n)==="EEXIST")return false;throw n}try{if(!await Xe(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(o){if(U(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 dr(t){try{return process.kill(t,0),!0}catch(e){return U(e)==="EPERM"}}async function hr(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if(U(n)!=="ENOENT")throw n}}function U(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 G(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function He(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,o=new Error(n),i=Me(t,"code"),s=Me(t,"exitCode");return i!==void 0&&Object.assign(o,{code:i}),s!==void 0&&Object.assign(o,{exitCode:s}),o}function Me(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var Q=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;withRefreshLock(e){return R(this.path,"auth-refresh",e)}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"?p("NOT_FOUND","load",r):A("load",r)}try{return k(e)}catch(r){throw E(r)?r:p("DECODE_FAILED","load",r)}}async save(e){let r=g(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(()=>{}),A("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 A("delete",e)}}};function Je(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",L(t),`${L(e)}.json`)}function A(t,e){let r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return r.includes("permission denied")||r.includes("access denied")?p("PERMISSION_DENIED",t,e):p("BACKEND_UNAVAILABLE",t,e)}var ge=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 We(t,e,r,n=process.env){return new Promise((o,i)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),a=[],f=[],u=false,l=h=>{u||(u=true,i(h));};s.stdout.on("data",h=>a.push(Buffer.from(h))),s.stderr.on("data",h=>f.push(Buffer.from(h))),s.once("error",l),s.stdin.once("error",l),s.once("close",h=>{if(u)return;u=true;let m={stdout:Buffer.concat(a).toString(),stderr:Buffer.concat(f).toString()};if(h===0){o(m);return}i(new ge(t,h,m.stderr));}),s.stdin.end(r);})}var Sr=promisify(execFile),Pr="Software\\BytedAuthClient\\keychain",ee=class{constructor(e,r,n=Cr){this.serviceName=e;this.account=r;this.runner=n;G(e,r);}serviceName;account;runner;withRefreshLock(e){return R(this.serviceName,`${this.account}.auth-refresh`,e)}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 A("load",r)}if(e===void 0)throw p("NOT_FOUND","load",new Error("auth record not found"));try{return k(e)}catch(r){throw E(r)?r:p("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,g(e));}catch(r){throw A("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 A("delete",e)}}},Cr={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 = '${
|
|
22
|
-
$name = '${
|
|
21
|
+
$path = '${I(Ee(t))}'
|
|
22
|
+
$name = '${I(we(e))}'
|
|
23
23
|
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path)
|
|
24
24
|
if ($null -eq $key) { exit 3 }
|
|
25
25
|
try { $value = $key.GetValue($name, $null) } finally { $key.Dispose() }
|
|
@@ -29,20 +29,20 @@ $entropy = [Convert]::FromBase64String('${r}')
|
|
|
29
29
|
$plain = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
|
|
30
30
|
[Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))
|
|
31
31
|
exit 0
|
|
32
|
-
`,o=await
|
|
32
|
+
`,o=await me(n);return o.missing?void 0:o.stdout},async set(t,e,r){let n=Buffer.from(r,"utf8").toString("base64");await me(vr(t,e),n);},async delete(t,e){let r=`
|
|
33
33
|
$ErrorActionPreference = 'Stop'
|
|
34
|
-
$path = '${
|
|
35
|
-
$name = '${
|
|
34
|
+
$path = '${I(Ee(t))}'
|
|
35
|
+
$name = '${I(we(e))}'
|
|
36
36
|
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($path, $true)
|
|
37
37
|
if ($null -ne $key) {
|
|
38
38
|
try { $key.DeleteValue($name, $false) } finally { $key.Dispose() }
|
|
39
39
|
}
|
|
40
40
|
exit 0
|
|
41
|
-
`;await
|
|
41
|
+
`;await me(r);}};function Ee(t){return `${Pr}\\${L(t)}`}function Tr(t){return `HKCU:\\${Ee(t)}`}function we(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 vr(t,e){let r=Buffer.from(Ze(t,e)).toString("base64");return `
|
|
42
42
|
$ErrorActionPreference = 'Stop'
|
|
43
43
|
Add-Type -AssemblyName System.Security
|
|
44
|
-
$path = '${
|
|
45
|
-
$name = '${
|
|
44
|
+
$path = '${I(Tr(t))}'
|
|
45
|
+
$name = '${I(we(e))}'
|
|
46
46
|
New-Item -Path $path -Force | Out-Null
|
|
47
47
|
$encodedValue = [Console]::In.ReadToEnd()
|
|
48
48
|
$plain = [Convert]::FromBase64String($encodedValue)
|
|
@@ -51,5 +51,5 @@ $cipher = [Security.Cryptography.ProtectedData]::Protect($plain, $entropy, [Secu
|
|
|
51
51
|
$encoded = [Convert]::ToBase64String($cipher)
|
|
52
52
|
Set-ItemProperty -Path $path -Name $name -Value $encoded
|
|
53
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{
|
|
54
|
+
`}async function me(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await Sr("powershell.exe",r):await We("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 kr="byted_cli_user_token";function te(t,e=kr,r=process.platform){switch(G(t,e),r){case "darwin":return new b(t,e);case "win32":return new ee(t,e);default:return new ye(new b(t,e),new Q(Je(t,e)),n=>R(t,e,n),n=>R(t,`${e}.auth-session`,n))}}var ye=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(!E(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(g(r)!==g(e))throw await this.primary.delete().catch(()=>{}),p("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var Ye={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"},w=class extends Error{code;cause;pendingLogin;constructor(e,r=Ye[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 w(t,Ye[t],e)}function Dr(t,e){return t instanceof w&&(e===void 0||t.code===e)}var Lr=createRequire(import.meta.url),xr="CN",K=3e3;function tt(){return {name:et(Qe.hostname()||"unknown",128),os:Mr(process.platform),osVersion:et(Qe.release()||"",64),architecture:Vr(process.arch),cliVersion:Br(),region:br()}}function br(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(Ae(t.readMacOSLocale??Kr,void 0));else if(e==="win32"){let o=Ur(Ae(t.readWindowsRegion??$r,void 0));if(o)return o}else e==="linux"&&n.push(...Hr(Ae(t.readLinuxLocales??Fr,[])));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=Gr(o);if(i)return i}return xr}function Ur(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function Gr(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 Kr(){return rt("/usr/bin/defaults",["read","-g","AppleLocale"])}function $r(){return rt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function Fr(){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 Hr(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 rt(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Ae(t,e){try{return t()}catch{return e}}function Mr(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function Vr(t){return t==="x64"?"x86_64":t}function Br(){for(let t of ["../../package.json","../../../package.json"])try{let e=Lr(t);if(typeof e.version=="string")return e.version}catch{}return ""}function et(t,e){return t.length>e?t.slice(0,e):t}var zr="/passport/open/refresh_token/",at="Bearer ",Pe=365*24*60*60*1e3,oe=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();}}},ie=class{core;constructor(e,r={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=r.protocol??new V({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),o=r.signer??new z,i=r.store??te(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:o,store:i,now:r.now??(()=>new Date),mutex:new oe,deviceReportUrl:new URL(M,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:Wr(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 Re(this.core)}authorizer(){return new se(this.core)}},Re=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let r=await ne(this.core.store,async()=>{let a=await $(this.core.store);return ot(a,this.core.now()),a?g(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 st(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 ne(this.core.store,async()=>{let a=await $(this.core.store);if(ot(a,this.core.now()),(a?g(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 re(this.core.store);return this.checkLoginRecord(o,n,r)})}async checkPendingLogin(e){return this.core.mutex.run(async()=>{let r=await $(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=g(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 ae(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=st(s);throw a.code==="LOGIN_PENDING"&&(await ne(this.core.store,()=>Ce(this.core.store,o,"LOGIN_SUPERSEDED")),e.verificationUri&&e.loginExpiresAt)?new w("LOGIN_PENDING",void 0,s,{verificationUri:e.verificationUri,expiresAt:new Date(e.loginExpiresAt)}):((a.code==="LOGIN_EXPIRED"||a.code==="LOGIN_DENIED")&&await ae(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,e.sessionId=randomUUID(),i.refreshToken&&(e.refreshToken=i.refreshToken),e.tokenExpiresAt=new Date(this.core.now().getTime()+i.expiresInMs),await dt(this.core.store,e,o,"LOGIN_SUPERSEDED"),await ct(this.core,e,n),Se(this.core.now(),e)}authorizer(){return new se(this.core)}},se=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 Se(this.core.now(),r)}catch(r){if(r instanceof w&&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 Se(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");ut(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await O(this.core.store,()=>this.core.store.updateUserInfo(e));}catch(r){throw _(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await re(this.core.store);return lt(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await O(this.core.store,()=>this.core.store.delete());}catch(e){if(!E(e,"NOT_FOUND"))throw _(e)}})}async ensureActiveRecord(e,r){let n=await re(this.core.store),o=g(n);if(!n.accessToken)throw d("NOT_LOGGED_IN");let i=this.core.now();if(ht(i,n.tokenExpiresAt,e))return n;let s=async()=>{r?.throwIfAborted();let a=await re(this.core.store);if(g(a)!==o){if(nt(n,a,this.core.now(),e))return a;throw d("NOT_LOGGED_IN")}return this.refreshRecord(n,o,e,r)};try{return this.core.store.withRefreshLock?await this.core.store.withRefreshLock(s):await s()}catch(a){throw a instanceof w||r?.aborted?a:_(a)}}async reuseConcurrentRefresh(e,r){return ne(this.core.store,async()=>{let n=await $(this.core.store);return n&&nt(e,n,this.core.now(),r)?n:void 0})}async refreshRecord(e,r,n,o){if(!e.refreshToken||!e.deviceKey)throw await ae(this.core.store,r),d("NOT_LOGGED_IN");let i;try{i=this.core.signer.sign({method:"POST",urlPath:zr,signingMaterial:e.refreshToken},e.deviceKey);}catch(l){throw d("SIGN_FAILED",l)}let s,a=e.accessToken;try{s=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:e.refreshToken,pubKey:i.pubKey,reqSign:i.signature,reqTs:i.timestamp,reqNonce:i.nonce},o);}catch(l){o?.throwIfAborted();let h=await this.reuseConcurrentRefresh(e,n);if(h)return h;throw Zr(l)?(await ae(this.core.store,r),d("NOT_LOGGED_IN")):d("REFRESH_FAILED",l)}let f=_e(e),u={...e};e.accessToken=s.accessToken,e.sessionId=f,s.refreshToken&&(e.refreshToken=s.refreshToken),e.tokenExpiresAt=new Date(this.core.now().getTime()+s.expiresInMs);try{await dt(this.core.store,e,r);}catch(l){if(!(l instanceof w)||l.code!=="NOT_LOGGED_IN")throw l;let h=await this.reuseConcurrentRefresh(u,n);if(h)return h;throw l}return a!==e.accessToken&&await ct(this.core,e,o),e}};function _e(t){return t.sessionId??createHash("sha256").update(JSON.stringify([t.clientKey,t.deviceKey,t.refreshToken])).digest("hex")}function nt(t,e,r,n){return !!(t.refreshToken&&e.refreshToken&&e.accessToken&&_e(t)===_e(e)&&t.clientKey===e.clientKey&&JSON.stringify(t.deviceKey)===JSON.stringify(e.deviceKey)&&!e.deviceCode&&!e.loginContext&&e.tokenExpiresAt&&r<e.tokenExpiresAt&&ht(r,e.tokenExpiresAt,n===Pe?0:n)&&(e.accessToken!==t.accessToken||e.refreshToken!==t.refreshToken||e.tokenExpiresAt?.getTime()!==t.tokenExpiresAt?.getTime()))}async function ct(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{ut(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=at+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((f,u)=>{s=setTimeout(()=>{o.abort(),u(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{let f=await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:tt()},o.signal),a]);await O(t.store,async()=>{let u=await t.store.load();if(u.clientKey!==e.clientKey||u.accessToken!==e.accessToken)return;let l=qr(u.userInfo,f.uid);await t.store.save({...u,userInfo:l}),e.userInfo=l;});}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",i);}}function qr(t,e){return Jr(t)?{...t,uid:e}:{uid:e}}function Jr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ut(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)}C(r,"Authorization",at+e.accessToken),C(r,"X-Pub-Key",s.pubKey),C(r,"X-Req-Sign",s.signature),C(r,"X-Req-Ts",s.timestamp),C(r,"X-Req-Nonce",s.nonce),C(r,"X-Req-Method",o),C(r,"X-Req-Path",i);}function Wr(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):K}async function re(t){try{return await t.load()}catch(e){throw _(e)}}async function $(t){try{return await t.load()}catch(e){if(E(e,"NOT_FOUND"))return;throw _(e)}}function ot(t,e){if(t?.deviceCode&&t.loginExpiresAt&&e.getTime()<t.loginExpiresAt.getTime())throw d("LOGIN_ALREADY_PENDING")}async function ne(t,e){try{return await O(t,e)}catch(r){throw r instanceof w?r:_(r)}}async function dt(t,e,r,n="NOT_LOGGED_IN"){try{await O(t,async()=>{r!==void 0&&await Ce(t,r,n),await t.save(e);});}catch(o){throw o instanceof w?o:_(o)}}async function ae(t,e,r="NOT_LOGGED_IN"){try{await O(t,async()=>{await Ce(t,e,r),await t.delete();});}catch(n){if(n instanceof w)throw n;if(!E(n,"NOT_FOUND"))throw _(n)}}async function Ce(t,e,r="NOT_LOGGED_IN"){let n=await $(t);if(!n||g(n)!==e)throw d(r)}var it=new WeakMap;async function O(t,e){if(t.withLock)return t.withLock(e);let r=it.get(t);return r||(r=new oe,it.set(t,r)),r.run(e)}function _(t){return E(t,"NOT_FOUND")?d("NOT_LOGGED_IN",t):d("STORE_UNAVAILABLE",t)}function st(t){return T(t,"AUTHORIZATION_PENDING")?d("LOGIN_PENDING",t):T(t,"ACCESS_DENIED")?d("LOGIN_DENIED",t):T(t,"EXPIRED_TOKEN")?d("LOGIN_EXPIRED",t):d("PROTOCOL_ERROR",t)}function Zr(t){return T(t,"EXPIRED_TOKEN")||T(t,"INVALID_GRANT")}function ht(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Se(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:lt(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function C(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function lt(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var ft=["pico_vibe_lab","pico_ai_sgs","user_info"],Yr=Object.freeze({}),pt="https://user.picoxr.com",Qr=Object.freeze({}),en=/^ppe_[A-Za-z0-9_-]+$/,gt={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:pt,deviceReportTimeoutMs:K};function Te(t={}){let e=t.ppeHeader?tn(t.ppeHeader):void 0;return {...gt,scopes:mt(ft,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function tn(t){if(!en.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 mt(t,e){let r=new Set;for(let n of [...t,...e]){let o=n.trim();o&&r.add(o);}return [...r]}function Ao(t={},e={}){let r=Te(t),n=e.store??te(r.storeServiceName),o=new ie(r,{...e,store:n});return {getStatus(i){return rn(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(Pe,i)},injectAuth(i,s){return o.authorizer().inject(i,s)},logout(){return o.authorizer().logout()}}}async function rn(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:nn(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(E(n,"NOT_FOUND"))return {loggedIn:false};throw d("STORE_UNAVAILABLE",n)}}function nn(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}
|
|
55
|
+
export{w as AuthError,K as DEFAULT_DEVICE_REPORT_TIMEOUT_MS,gt as PICO_AUTH_CONFIG,Yr as PICO_AUTH_HTTP_HEADERS,ft as PICO_DEFAULT_SCOPES,pt as PICO_DEVICE_REPORT_BASE_URL,Qr as PICO_DEVICE_REPORT_HTTP_HEADERS,Ao as createAuthClient,Te as createPicoAuthConfig,Dr as isAuthError,mt as mergeScopes};
|