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