@picoxr/pico-auth-cli-cn 0.1.19 → 0.1.20
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/dist/src/cli/main.js +21 -23
- package/package.json +1 -1
package/dist/src/cli/main.js
CHANGED
|
@@ -11,16 +11,16 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import {realpathSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {execFile,spawn,execFileSync}from'child_process';import {createHash,randomUUID,randomBytes,generateKeyPairSync,sign}from'crypto';import {mkdir,writeFile,rm,stat,readFile,open,rename}from'fs/promises';import {join,dirname}from'path';import at,{userInfo,tmpdir}from'os';import {createRequire}from'module';import {promisify}from'util';
|
|
14
|
-
var a=class extends Error{kind;errorCode;description;descUrl;cause;constructor(e){super(e.description||e.kind.toLowerCase()),this.name="ProtocolError",this.kind=e.kind,this.errorCode=e.errorCode??0,this.description=e.description??"",this.descUrl=e.descUrl??"",this.cause=e.cause;}};function
|
|
14
|
+
var a=class extends Error{kind;errorCode;description;descUrl;cause;constructor(e){super(e.description||e.kind.toLowerCase()),this.name="ProtocolError",this.kind=e.kind,this.errorCode=e.errorCode??0,this.description=e.description??"",this.descUrl=e.descUrl??"",this.cause=e.cause;}};function C(t,e){return t instanceof a&&(e===void 0||t.kind===e)}var kt="/passport/open/get_device_code/",Dt="/passport/open/check_device_code/",Nt="/passport/open/refresh_token/",B="/api/cli/v1/authorization/device/report",Lt="Bearer",$e="X-Tt-Logid",xt=1,bt=6,Ut=7,$t=10,Gt=10010,Kt=10002,z=10003,Ft=10005,q=10021,Fe=10042,Me=10043,Mt=10044,Vt=10046,Ht=1080,j=class{baseUrl;deviceReportBaseUrl;aid;headers;deviceReportHttpHeaders;userAgent;constructor(e){if(!e.baseUrl.trim())throw new Error("protocol: base url is required");if(this.baseUrl=new URL(e.baseUrl),!this.baseUrl.protocol||!this.baseUrl.host)throw new Error("protocol: base url must include scheme and host");if(this.deviceReportBaseUrl=new URL(e.deviceReportBaseUrl??e.baseUrl),!this.deviceReportBaseUrl.protocol||!this.deviceReportBaseUrl.host)throw new Error("protocol: device report base url must include scheme and host");this.aid=e.aid,this.headers={...e.headers??{}},this.deviceReportHttpHeaders={...e.deviceReportHttpHeaders??{}},this.userAgent=e.userAgent;}async getDeviceCode(e,r){let n=new URLSearchParams;n.set("client_key",e.clientKey),n.set("pub_key",e.pubKey);let i=Bt(e.scopes??[]);i&&n.set("scope",i);let o=await this.postForm(kt,n,void 0,r),s=V(o,jt);return {deviceCode:k(s,"device_code"),userCode:k(s,"user_code"),verificationUri:k(s,"verification_uri"),intervalMs:H(s,"interval")*1e3,expiresInMs:H(s,"expires_in")*1e3}}async checkDeviceCode(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("device_code",e.deviceCode);let i=await this.postForm(Dt,n,void 0,r),o=V(i,zt),s=Ge(o);return Wt(s),{accessToken:k(o,"access_token"),refreshToken:s.refresh_token??"",expiresInMs:H(o,"expires_in")*1e3}}async refreshToken(e,r){let n=new URLSearchParams;this.aid!==void 0&&this.aid!==0&&n.set("aid",String(this.aid)),n.set("client_key",e.clientKey),n.set("grant_type","refresh_token"),n.set("refresh_token",e.refreshToken);let i=await this.postForm(Nt,n,{"X-Pub-Key":e.pubKey,"X-Req-Sign":e.reqSign,"X-Req-Ts":e.reqTs,"X-Req-Nonce":e.reqNonce},r),o=V(i,qt),s=Ge(o);return {accessToken:k(o,"access_token"),refreshToken:s.refresh_token,expiresInMs:H(o,"expires_in")*1e3}}async reportDeviceAuthorization(e,r){let n=new URLSearchParams;e.deviceInfo.cliVersion&&n.set("cli_version",e.deviceInfo.cliVersion),e.deviceInfo.architecture&&n.set("architecture",e.deviceInfo.architecture);let i=n.toString(),o=i?`${B}?${i}`:B;await this.postJson(o,{device_info:{name:e.deviceInfo.name,os:e.deviceInfo.os,os_version:e.deviceInfo.osVersion,region:e.deviceInfo.region}},{...this.deviceReportHttpHeaders,...e.headers},r,this.deviceReportBaseUrl);}async postForm(e,r,n,i){let o=this.resolve(e),s;try{s=await fetch(o,{method:"POST",body:r,signal:i,headers:{...this.headers,...n??{},"Content-Type":"application/x-www-form-urlencoded",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(u){throw new a({kind:"TRANSPORT",description:"do request",cause:u})}let c=await s.text();if(s.status!==200)throw new a({kind:"SERVER",errorCode:s.status,description:s.statusText||`unexpected http status ${s.status}`,descUrl:s.headers.get($e)??""});try{return JSON.parse(c)}catch(u){throw new a({kind:"DECODE",description:"decode envelope",cause:u})}}async postJson(e,r,n,i,o=this.baseUrl){let s=this.resolve(e,o),c;try{c=await fetch(s,{method:"POST",body:JSON.stringify(r),signal:i,headers:{...this.headers,...n??{},"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}});}catch(p){throw new a({kind:"TRANSPORT",description:"do request",cause:p})}let u=await c.text();if(c.status!==200)throw new a({kind:"SERVER",errorCode:c.status,description:c.statusText||`unexpected http status ${c.status}`,descUrl:c.headers.get($e)??""});let d;try{d=JSON.parse(u);}catch(p){throw new a({kind:"DECODE",description:"decode response envelope",cause:p})}let A=fe(d,"code");if(A!==void 0){if(A===0)return;throw new a({kind:"SERVER",errorCode:A,description:S(d,"em")??S(d,"et")??"device report failed",descUrl:S(d,"trace_id")??""})}V(d,X);}resolve(e,r=this.baseUrl){let n=new URL(e,r);return this.aid!==void 0&&this.aid!==0&&n.searchParams.set("aid",String(this.aid)),n.toString()}};function Bt(t){return t.map(e=>e.trim()).filter(Boolean).join(",")}function V(t,e){let r=Zt(t.data)?t.data:{};if(Ke(t.message,"success"))return r;if(!Ke(t.message,"error"))throw new a({kind:"SERVER",description:"unexpected response message"});let n=typeof r.error_code=="number"?r.error_code:0,i=typeof r.code=="number"?r.code:0,o=typeof r.description=="string"?r.description:String(t.message??"error"),s=e(n||i,o),c=typeof r.desc_url=="string"?r.desc_url:"";throw c?new a({kind:s.kind,errorCode:s.errorCode,description:s.description,descUrl:c,cause:s.cause}):s}function jt(t,e){switch(t){case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return X(t,e)}}function zt(t,e){switch(t){case Ut:return new a({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case Ht:return Xt(t,e);case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});default:return X(t,e)}}function qt(t,e){switch(t){case Gt:return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case Fe:return new a({kind:"INVALID_GRANT",errorCode:t,description:e});case Me:return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});case Ft:case Kt:case Mt:case Vt:case bt:return new a({kind:"SERVER",errorCode:t,description:e});default:return X(t,e)}}function Xt(t,e){let r=e.toLowerCase().trim();return r.includes("\u53D6\u6D88\u6388\u6743")?new a({kind:"ACCESS_DENIED",errorCode:t,description:e}):r.includes("\u5931\u6548")||r.includes("\u8FC7\u671F")?new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e}):new a({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e})}function X(t,e){switch(e.toLowerCase().trim()){case "authorization_pending":case "\u7528\u6237\u5C1A\u672A\u5B8C\u6210\u6388\u6743\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":case "\u8F6E\u8BE2\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":return new a({kind:"AUTHORIZATION_PENDING",errorCode:t,description:e});case "expired_token":case "device_code \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u5728 cli \u53D1\u8D77\u767B\u5F55":case "token \u5DF2\u8FC7\u671F":case "\u4F1A\u8BDD\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":case "\u6570\u636E\u4E0D\u5B58\u5728":return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});case "access_denied":case "\u7528\u6237\u5DF2\u53D6\u6D88\u6388\u6743":return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});case "invalid_grant":case "\u975E\u6CD5 token":return new a({kind:"INVALID_GRANT",errorCode:t,description:e});case "invalid_client":case "\u914D\u7F6E\u65E0\u6548":return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});}switch(t){case z:return new a({kind:"INVALID_CLIENT",errorCode:t,description:e});case q:return new a({kind:"ACCESS_DENIED",errorCode:t,description:e});case Fe:return new a({kind:"INVALID_GRANT",errorCode:t,description:e});case Me:case xt:case $t:return new a({kind:"EXPIRED_TOKEN",errorCode:t,description:e});}return new a({kind:"SERVER",errorCode:t,description:e})}function Ge(t){return {access_token:S(t,"access_token"),refresh_token:S(t,"refresh_token"),token_type:S(t,"token_type"),expires_in:fe(t,"expires_in")}}function Wt(t){if(t.token_type!==Lt)throw new a({kind:"SERVER",description:"unexpected token_type"})}function k(t,e){let r=S(t,e);if(r===void 0||r.trim()==="")throw new a({kind:"DECODE",description:`missing or empty ${e}`});return r}function Jt(t,e){let r=fe(t,e);if(r===void 0||!Number.isFinite(r))throw new a({kind:"DECODE",description:`missing or invalid ${e}`});return r}function H(t,e){let r=Jt(t,e);if(r<=0)throw new a({kind:"DECODE",description:`invalid ${e}`});return r}function S(t,e){let r=t[e];return typeof r=="string"?r:void 0}function fe(t,e){let r=t[e];return typeof r=="number"?r:void 0}function Zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ke(t,e){return typeof t=="string"&&t.toLowerCase()===e.toLowerCase()}var Ve="ecdsa-p256-sha256";var rr=16,W=class{constructor(e=()=>new Date,r=randomBytes){this.now=e;this.random=r;}now;random;generateDeviceKey(){let{publicKey:e,privateKey:r}=generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return {Algorithm:Ve,PublicKeyBase64:Buffer.from(e).toString("base64"),PrivateKeyBase64:Buffer.from(r).toString("base64")}}sign(e,r){if(!e.urlPath||!e.urlPath.startsWith("/"))throw new Error("signer: invalid url path");let n=String(Math.floor(this.now().getTime()/1e3)),i=this.random(rr).toString("hex"),o=nr(e.signingMaterial),s=createHash("sha256").update(o).digest("base64"),c=[e.method,e.urlPath,s,n,i].join(`
|
|
15
15
|
`),u=or(r.PrivateKeyBase64,"PRIVATE KEY"),d=sign("sha256",Buffer.from(c),{key:u,dsaEncoding:"der"});return {pubKey:r.PublicKeyBase64,signature:d.toString("base64"),timestamp:n,nonce:i}}};function nr(t){return t===void 0?new Uint8Array:typeof t=="string"?Buffer.from(t):t}function or(t,e){let r=t.match(/.{1,64}/g)??[];return `-----BEGIN ${e}-----
|
|
16
16
|
${r.join(`
|
|
17
17
|
`)}
|
|
18
18
|
-----END ${e}-----
|
|
19
|
-
`}var J=class extends Error{code;cause;constructor(e,r,n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="StoreError",this.code=e,this.cause=n;}};function h(t,e,r){return new J(t,`${e}: ${ir(t)}`,r)}function m(t,e){return t instanceof J&&(e===void 0||t.code===e)}function ir(t){switch(t){case "NOT_FOUND":return "store: not found";case "CORRUPT_RECORD":return "store: corrupt record";case "BACKEND_UNAVAILABLE":return "store: backend unavailable";case "PERMISSION_DENIED":return "store: permission denied";case "ENCODE_FAILED":return "store: encode failed";case "DECODE_FAILED":return "store: decode failed"}}var Be=1e6;function _(t){je(t);let e={client_key:t.clientKey,device_code:D(t.deviceCode),user_code:D(t.userCode),verification_uri:D(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*Be),login_expires_at:t.loginExpiresAt?.toISOString(),access_token:D(t.accessToken),refresh_token:D(t.refreshToken),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(sr(e))}function O(t){if(t.trim()==="")throw h("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(t);}catch(n){throw h("DECODE_FAILED","load",n)}let r={clientKey:e.client_key??"",deviceCode:e.device_code,userCode:e.user_code,verificationUri:e.verification_uri,intervalMs:e.interval===void 0?void 0:e.interval/Be,loginExpiresAt:He(e.login_expires_at),accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:He(e.token_expires_at),deviceKey:e.device_key,userInfo:e.user_info,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):void 0};return je(r),r}function je(t){if(!t.clientKey.trim())throw h("CORRUPT_RECORD","validate",new Error("client_key is required"))}function N(t){let e=t.trim();if(e==="")return "_";let r="";for(let n of e)/^[A-Za-z0-9._-]$/.test(n)?r+=n:r+="_";return r||"_"}function He(t){if(t)return new Date(t)}function D(t){return t===void 0||t===""?void 0:t}function sr(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var Z=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;async load(){let e;try{e=await readFile(this.path,"utf8");}catch(r){throw r?.code==="ENOENT"?h("NOT_FOUND","load",r):y("load",r)}try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){let r=_(e),n=dirname(this.path);await mkdir(n,{recursive:true,mode:448});let i=join(n,`${randomBytes(8).toString("hex")}.tmp`);try{await writeFile(i,r,{mode:384}),await rename(i,this.path);}catch(o){throw await rm(i,{force:true}).catch(()=>{}),y("save",o)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await rm(this.path,{force:!0});}catch(e){throw y("delete",e)}}};function Xe(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",N(t),`${N(e)}.json`)}function y(t,e){let r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return r.includes("permission denied")||r.includes("access denied")?h("PERMISSION_DENIED",t,e):h("BACKEND_UNAVAILABLE",t,e)}var Je=promisify(execFile),Sr=createRequire(import.meta.url),Cr=9e4,Pr=5*6e4,vr=100,Y="pico-auth-cli-managed-v2",L="pico-auth-cli-managed-v3",T="pico-auth-cli-managed-v3-legacy-ambiguous",x=class{constructor(e,r,n=Tr){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;async load(){let e;try{e=await this.runner.getPassword(this.serviceName,this.account);}catch(r){throw y("load",r)}if(e===null)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){let r;try{r=_(e);}catch(n){throw y("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw y("save",Nr(n,r))}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.deletePassword(this.serviceName,this.account);}catch(e){throw y("delete",e)}}},Or={async getPassword(t,e){try{let{stdout:r}=await Je("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(Ye(r))return null;throw r}},async deletePassword(t,e){try{return await Je("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(Ye(r))return false;throw r}}},rt={getPassword:(t,e)=>ge().getPassword(t,e),setPassword:(t,e,r)=>ge().setPassword(t,e,r),deletePassword:(t,e)=>ge().deletePassword(t,e)},Ae=class{constructor(e=rt,r=Or,n=_e){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let o of [we(r),Ee(r)]){let s=await this.managed.getPassword(e,o);if(s!==null)return s}let n=await this.managed.getPassword(e,ye(r));if(n===L||n===T)return null;let i=await this.managed.getPassword(e,me(r));return i!==null?i:await this.managed.getPassword(e,Ze(r))===Y?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let i=we(r),o=Ee(r),s=ye(r);await this.managed.setPassword(e,i,n),await Q(this.managed,e,i,n,"recovery"),await this.managed.setPassword(e,o,n),await Q(this.managed,e,o,n,"primary"),await this.managed.setPassword(e,s,L),await Q(this.managed,e,s,L,"state"),await this.managed.deletePassword(e,i).catch(()=>{}),await this.managed.deletePassword(e,me(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[we(r),Ee(r),me(r)],i=await Promise.all(n.map(E=>this.managed.getPassword(e,E))),o=ye(r),s=await this.managed.getPassword(e,o),c=Ze(r),u=await this.managed.getPassword(e,c);if(!(i.some(E=>E!==null)||s===L||s===T||u===Y))return this.legacy.deletePassword(e,r);let p=i[2]!==null&&u!==Y||s===T?T:L;await this.managed.setPassword(e,o,p),await Q(this.managed,e,o,p,"state");let f=false,R;for(let E of n)try{f=await this.managed.deletePassword(e,E)||f;}catch(It){R??=It;}if(R!==void 0)throw R;if(u===Y)try{let E=await this.managed.deletePassword(e,r);f=E||f,(E||await this.managed.getPassword(e,r)===null)&&(f=await this.managed.deletePassword(e,c)||f);}catch(E){R??=E;}else if(p!==T)try{f=await this.legacy.deletePassword(e,r)||f;}catch(E){R??=E;}if(R!==void 0)throw R;return p===T||(f=await this.managed.deletePassword(e,o)||f),f})}},Tr=process.platform==="darwin"?new Ae:rt;function ge(){return Sr("keytar")}function me(t){return `${t}.pico-auth-cli-recovery-v1`}function Ze(t){return `${t}.pico-auth-cli-managed-v2`}function we(t){return `${t}.pico-auth-cli-recovery-v3`}function Ee(t){return `${t}.pico-auth-cli-payload-v3`}function ye(t){return `${t}.pico-auth-cli-state-v3`}async function _e(t,e,r){let n=join("/tmp",`pico-auth-cli-keychain-locks-${userInfo().uid}`);await mkdir(n,{recursive:true,mode:448});let i=createHash("sha256").update(t).update("\0").update(e).digest("hex"),o=join(n,`${i}.lock`),s=join(o,"owner.json"),c=randomUUID(),u=Date.now()+Cr;for(;;)try{await mkdir(o,{mode:448});try{await writeFile(s,JSON.stringify({pid:process.pid,token:c,createdAt:Date.now()}),{flag:"wx",mode:384});}catch(d){throw await rm(o,{recursive:!0,force:!0}).catch(()=>{}),d}break}catch(d){if(b(d)!=="EEXIST")throw d;if(await nt(o)&&await Ir(o))continue;if(Date.now()>=u)throw new Error("timed out waiting for the macOS Keychain write lock");await new Promise(A=>setTimeout(A,vr));}try{return await r()}finally{await Dr(o,s,c).catch(()=>{});}}async function nt(t){try{let e=await stat(t);try{let r=await readFile(join(t,"owner.json"),"utf8"),n=JSON.parse(r);return typeof n.pid=="number"&&!kr(n.pid)}catch{return Date.now()-e.mtimeMs>=Pr}}catch{return false}}async function Ir(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if(b(n)==="EEXIST")return false;throw n}try{if(!await nt(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(i){if(b(i)==="ENOENT")return !0;throw i}return await rm(n,{recursive:!0,force:!0}),!0}finally{await r.close().catch(()=>{}),await rm(e,{force:true}).catch(()=>{});}}function kr(t){try{return process.kill(t,0),!0}catch(e){return b(e)==="EPERM"}}async function Dr(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if(b(n)!=="ENOENT")throw n}}function b(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"?t.code:void 0}async function Q(t,e,r,n,i){if(await t.getPassword(e,r)!==n)throw new Error(`macOS Keychain ${i} write verification failed`)}function U(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function Ye(t){let e=t instanceof Error?t.message:String(t);return e.includes("could not be found")||e.includes("The specified item could not be found")}function Nr(t,e){let r=t instanceof Error?t.message:String(t),n=r.includes(e)?r.split(e).join("[REDACTED]"):r,i=new Error(n),o=Qe(t,"code"),s=Qe(t,"exitCode");return o!==void 0&&Object.assign(i,{code:o}),s!==void 0&&Object.assign(i,{exitCode:s}),i}function Qe(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var Re=class extends Error{code;exitCode;stderr;constructor(e,r,n){let i=n.trim();super(`${e} exited with code ${r??"unknown"}${i?`: ${i}`:""}`),this.name="CommandExecutionError",this.code=r,this.exitCode=r,this.stderr=n;}};function ot(t,e,r,n=process.env){return new Promise((i,o)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),c=[],u=[],d=false,A=p=>{d||(d=true,o(p));};s.stdout.on("data",p=>c.push(Buffer.from(p))),s.stderr.on("data",p=>u.push(Buffer.from(p))),s.once("error",A),s.stdin.once("error",A),s.once("close",p=>{if(d)return;d=true;let f={stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(u).toString()};if(p===0){i(f);return}o(new Re(t,p,f.stderr));}),s.stdin.end(r);})}var Ur=promisify(execFile),$r="Software\\BytedAuthClient\\keychain",re=class{constructor(e,r,n=Gr){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;async load(){let e;try{e=await this.runner.get(this.serviceName,this.account);}catch(r){throw y("load",r)}if(e===void 0)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,_(e));}catch(r){throw y("save",r)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.delete(this.serviceName,this.account);}catch(e){throw y("delete",e)}}},Gr={async get(t,e){let r=Buffer.from(it(t,e)).toString("base64"),n=`
|
|
19
|
+
`}var J=class extends Error{code;cause;constructor(e,r,n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="StoreError",this.code=e,this.cause=n;}};function h(t,e,r){return new J(t,`${e}: ${ir(t)}`,r)}function m(t,e){return t instanceof J&&(e===void 0||t.code===e)}function ir(t){switch(t){case "NOT_FOUND":return "store: not found";case "CORRUPT_RECORD":return "store: corrupt record";case "BACKEND_UNAVAILABLE":return "store: backend unavailable";case "PERMISSION_DENIED":return "store: permission denied";case "ENCODE_FAILED":return "store: encode failed";case "DECODE_FAILED":return "store: decode failed"}}var Be=1e6;function _(t){je(t);let e={client_key:t.clientKey,device_code:D(t.deviceCode),user_code:D(t.userCode),verification_uri:D(t.verificationUri),interval:t.intervalMs===void 0?void 0:Math.trunc(t.intervalMs*Be),login_expires_at:t.loginExpiresAt?.toISOString(),access_token:D(t.accessToken),refresh_token:D(t.refreshToken),token_expires_at:t.tokenExpiresAt?.toISOString(),device_key:t.deviceKey,user_info:t.userInfo,scopes:t.scopes};return JSON.stringify(sr(e))}function O(t){if(t.trim()==="")throw h("CORRUPT_RECORD","load",new Error("empty auth record"));let e;try{e=JSON.parse(t);}catch(n){throw h("DECODE_FAILED","load",n)}let r={clientKey:e.client_key??"",deviceCode:e.device_code,userCode:e.user_code,verificationUri:e.verification_uri,intervalMs:e.interval===void 0?void 0:e.interval/Be,loginExpiresAt:He(e.login_expires_at),accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:He(e.token_expires_at),deviceKey:e.device_key,userInfo:e.user_info,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):void 0};return je(r),r}function je(t){if(!t.clientKey.trim())throw h("CORRUPT_RECORD","validate",new Error("client_key is required"))}function N(t){let e=t.trim();if(e==="")return "_";let r="";for(let n of e)/^[A-Za-z0-9._-]$/.test(n)?r+=n:r+="_";return r||"_"}function He(t){if(t)return new Date(t)}function D(t){return t===void 0||t===""?void 0:t}function sr(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}var Z=class{constructor(e){this.path=e;if(!e.trim())throw new Error("path is required")}path;async load(){let e;try{e=await readFile(this.path,"utf8");}catch(r){throw r?.code==="ENOENT"?h("NOT_FOUND","load",r):y("load",r)}try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){let r=_(e),n=dirname(this.path);await mkdir(n,{recursive:true,mode:448});let i=join(n,`${randomBytes(8).toString("hex")}.tmp`);try{await writeFile(i,r,{mode:384}),await rename(i,this.path);}catch(o){throw await rm(i,{force:true}).catch(()=>{}),y("save",o)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await rm(this.path,{force:!0});}catch(e){throw y("delete",e)}}};function Xe(t,e,r=process.env.HOME||tmpdir()){return join(r||".",".local","share",N(t),`${N(e)}.json`)}function y(t,e){let r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return r.includes("permission denied")||r.includes("access denied")?h("PERMISSION_DENIED",t,e):h("BACKEND_UNAVAILABLE",t,e)}var Je=promisify(execFile),Sr=createRequire(import.meta.url),Pr=9e4,vr=5*6e4,Cr=100,Y="pico-auth-cli-managed-v2",L="pico-auth-cli-managed-v3",T="pico-auth-cli-managed-v3-legacy-ambiguous",x=class{constructor(e,r,n=Tr){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;async load(){let e;try{e=await this.runner.getPassword(this.serviceName,this.account);}catch(r){throw y("load",r)}if(e===null)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){let r;try{r=_(e);}catch(n){throw y("save",n)}try{await this.runner.setPassword(this.serviceName,this.account,r);}catch(n){throw y("save",Nr(n,r))}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.deletePassword(this.serviceName,this.account);}catch(e){throw y("delete",e)}}},Or={async getPassword(t,e){try{let{stdout:r}=await Je("security",["find-generic-password","-s",t,"-a",e,"-w"]);return r.trimEnd()}catch(r){if(Ye(r))return null;throw r}},async deletePassword(t,e){try{return await Je("security",["delete-generic-password","-s",t,"-a",e]),!0}catch(r){if(Ye(r))return false;throw r}}},rt={getPassword:(t,e)=>ge().getPassword(t,e),setPassword:(t,e,r)=>ge().setPassword(t,e,r),deletePassword:(t,e)=>ge().deletePassword(t,e)},Ae=class{constructor(e=rt,r=Or,n=_e){this.managed=e;this.legacy=r;this.runExclusive=n;}managed;legacy;runExclusive;async getPassword(e,r){for(let o of [we(r),Ee(r)]){let s=await this.managed.getPassword(e,o);if(s!==null)return s}let n=await this.managed.getPassword(e,ye(r));if(n===L||n===T)return null;let i=await this.managed.getPassword(e,me(r));return i!==null?i:await this.managed.getPassword(e,Ze(r))===Y?this.managed.getPassword(e,r):this.legacy.getPassword(e,r)}async setPassword(e,r,n){await this.runExclusive(e,r,async()=>{let i=we(r),o=Ee(r),s=ye(r);await this.managed.setPassword(e,i,n),await Q(this.managed,e,i,n,"recovery"),await this.managed.setPassword(e,o,n),await Q(this.managed,e,o,n,"primary"),await this.managed.setPassword(e,s,L),await Q(this.managed,e,s,L,"state"),await this.managed.deletePassword(e,i).catch(()=>{}),await this.managed.deletePassword(e,me(r)).catch(()=>{});});}async deletePassword(e,r){return this.runExclusive(e,r,async()=>{let n=[we(r),Ee(r),me(r)],i=await Promise.all(n.map(E=>this.managed.getPassword(e,E))),o=ye(r),s=await this.managed.getPassword(e,o),c=Ze(r),u=await this.managed.getPassword(e,c);if(!(i.some(E=>E!==null)||s===L||s===T||u===Y))return this.legacy.deletePassword(e,r);let p=i[2]!==null&&u!==Y||s===T?T:L;await this.managed.setPassword(e,o,p),await Q(this.managed,e,o,p,"state");let f=false,R;for(let E of n)try{f=await this.managed.deletePassword(e,E)||f;}catch(It){R??=It;}if(R!==void 0)throw R;if(u===Y)try{let E=await this.managed.deletePassword(e,r);f=E||f,(E||await this.managed.getPassword(e,r)===null)&&(f=await this.managed.deletePassword(e,c)||f);}catch(E){R??=E;}else if(p!==T)try{f=await this.legacy.deletePassword(e,r)||f;}catch(E){R??=E;}if(R!==void 0)throw R;return p===T||(f=await this.managed.deletePassword(e,o)||f),f})}},Tr=process.platform==="darwin"?new Ae:rt;function ge(){return Sr("keytar")}function me(t){return `${t}.pico-auth-cli-recovery-v1`}function Ze(t){return `${t}.pico-auth-cli-managed-v2`}function we(t){return `${t}.pico-auth-cli-recovery-v3`}function Ee(t){return `${t}.pico-auth-cli-payload-v3`}function ye(t){return `${t}.pico-auth-cli-state-v3`}async function _e(t,e,r){let n=join("/tmp",`pico-auth-cli-keychain-locks-${userInfo().uid}`);await mkdir(n,{recursive:true,mode:448});let i=createHash("sha256").update(t).update("\0").update(e).digest("hex"),o=join(n,`${i}.lock`),s=join(o,"owner.json"),c=randomUUID(),u=Date.now()+Pr;for(;;)try{await mkdir(o,{mode:448});try{await writeFile(s,JSON.stringify({pid:process.pid,token:c,createdAt:Date.now()}),{flag:"wx",mode:384});}catch(d){throw await rm(o,{recursive:!0,force:!0}).catch(()=>{}),d}break}catch(d){if(b(d)!=="EEXIST")throw d;if(await nt(o)&&await Ir(o))continue;if(Date.now()>=u)throw new Error("timed out waiting for the macOS Keychain write lock");await new Promise(A=>setTimeout(A,Cr));}try{return await r()}finally{await Dr(o,s,c).catch(()=>{});}}async function nt(t){try{let e=await stat(t);try{let r=await readFile(join(t,"owner.json"),"utf8"),n=JSON.parse(r);return typeof n.pid=="number"&&!kr(n.pid)}catch{return Date.now()-e.mtimeMs>=vr}}catch{return false}}async function Ir(t){let e=`${t}.reaper`,r;try{r=await open(e,"wx",384);}catch(n){if(b(n)==="EEXIST")return false;throw n}try{if(!await nt(t))return !1;let n=`${t}.stale-${randomUUID()}`;try{await rename(t,n);}catch(i){if(b(i)==="ENOENT")return !0;throw i}return await rm(n,{recursive:!0,force:!0}),!0}finally{await r.close().catch(()=>{}),await rm(e,{force:true}).catch(()=>{});}}function kr(t){try{return process.kill(t,0),!0}catch(e){return b(e)==="EPERM"}}async function Dr(t,e,r){try{JSON.parse(await readFile(e,"utf8")).token===r&&await rm(t,{recursive:!0,force:!0});}catch(n){if(b(n)!=="ENOENT")throw n}}function b(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"?t.code:void 0}async function Q(t,e,r,n,i){if(await t.getPassword(e,r)!==n)throw new Error(`macOS Keychain ${i} write verification failed`)}function U(t,e){if(!t.trim())throw new Error("service_name is required");if(!e.trim())throw new Error("account is required")}function Ye(t){let e=t instanceof Error?t.message:String(t);return e.includes("could not be found")||e.includes("The specified item could not be found")}function Nr(t,e){let r=t instanceof Error?t.message:String(t),n=r.includes(e)?r.split(e).join("[REDACTED]"):r,i=new Error(n),o=Qe(t,"code"),s=Qe(t,"exitCode");return o!==void 0&&Object.assign(i,{code:o}),s!==void 0&&Object.assign(i,{exitCode:s}),i}function Qe(t,e){if(typeof t!="object"||t===null||!(e in t))return;let r=t[e];return typeof r=="number"?r:void 0}var Re=class extends Error{code;exitCode;stderr;constructor(e,r,n){let i=n.trim();super(`${e} exited with code ${r??"unknown"}${i?`: ${i}`:""}`),this.name="CommandExecutionError",this.code=r,this.exitCode=r,this.stderr=n;}};function ot(t,e,r,n=process.env){return new Promise((i,o)=>{let s=spawn(t,e,{env:n,stdio:["pipe","pipe","pipe"]}),c=[],u=[],d=false,A=p=>{d||(d=true,o(p));};s.stdout.on("data",p=>c.push(Buffer.from(p))),s.stderr.on("data",p=>u.push(Buffer.from(p))),s.once("error",A),s.stdin.once("error",A),s.once("close",p=>{if(d)return;d=true;let f={stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(u).toString()};if(p===0){i(f);return}o(new Re(t,p,f.stderr));}),s.stdin.end(r);})}var Ur=promisify(execFile),$r="Software\\BytedAuthClient\\keychain",re=class{constructor(e,r,n=Gr){this.serviceName=e;this.account=r;this.runner=n;U(e,r);}serviceName;account;runner;async load(){let e;try{e=await this.runner.get(this.serviceName,this.account);}catch(r){throw y("load",r)}if(e===void 0)throw h("NOT_FOUND","load",new Error("auth record not found"));try{return O(e)}catch(r){throw m(r)?r:h("DECODE_FAILED","load",r)}}async save(e){try{await this.runner.set(this.serviceName,this.account,_(e));}catch(r){throw y("save",r)}}async updateUserInfo(e){let r=await this.load();r.userInfo=e,await this.save(r);}async delete(){try{await this.runner.delete(this.serviceName,this.account);}catch(e){throw y("delete",e)}}},Gr={async get(t,e){let r=Buffer.from(it(t,e)).toString("base64"),n=`
|
|
20
20
|
$ErrorActionPreference = 'Stop'
|
|
21
21
|
Add-Type -AssemblyName System.Security
|
|
22
|
-
$path = '${I(
|
|
23
|
-
$name = '${I(
|
|
22
|
+
$path = '${I(Pe(t))}'
|
|
23
|
+
$name = '${I(ve(e))}'
|
|
24
24
|
if (-not (Test-Path $path)) { exit 3 }
|
|
25
25
|
$item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue
|
|
26
26
|
if ($null -eq $item -or $null -eq $item.$name) { exit 3 }
|
|
@@ -30,14 +30,14 @@ $plain = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $entropy, [Se
|
|
|
30
30
|
[Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))
|
|
31
31
|
`,i=await Se(n);return i.missing?void 0:i.stdout},async set(t,e,r){let n=Buffer.from(r,"utf8").toString("base64");await Se(Fr(t,e),n);},async delete(t,e){let r=`
|
|
32
32
|
$ErrorActionPreference = 'Stop'
|
|
33
|
-
$path = '${I(
|
|
34
|
-
$name = '${I(
|
|
33
|
+
$path = '${I(Pe(t))}'
|
|
34
|
+
$name = '${I(ve(e))}'
|
|
35
35
|
if (Test-Path $path) { Remove-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue }
|
|
36
|
-
`;await Se(r);}};function Kr(t){return `${$r}\\${N(t)}`}function
|
|
36
|
+
`;await Se(r);}};function Kr(t){return `${$r}\\${N(t)}`}function Pe(t){return `HKCU:\\${Kr(t)}`}function ve(t){return Buffer.from(t,"utf8").toString("base64url")}function it(t,e){return Buffer.concat([Buffer.from(t,"utf8"),Buffer.from([0]),Buffer.from(e,"utf8")])}function Fr(t,e){let r=Buffer.from(it(t,e)).toString("base64");return `
|
|
37
37
|
$ErrorActionPreference = 'Stop'
|
|
38
38
|
Add-Type -AssemblyName System.Security
|
|
39
|
-
$path = '${I(
|
|
40
|
-
$name = '${I(
|
|
39
|
+
$path = '${I(Pe(t))}'
|
|
40
|
+
$name = '${I(ve(e))}'
|
|
41
41
|
New-Item -Path $path -Force | Out-Null
|
|
42
42
|
$encodedValue = [Console]::In.ReadToEnd()
|
|
43
43
|
$plain = [Convert]::FromBase64String($encodedValue)
|
|
@@ -45,30 +45,29 @@ $entropy = [Convert]::FromBase64String('${r}')
|
|
|
45
45
|
$cipher = [Security.Cryptography.ProtectedData]::Protect($plain, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
|
|
46
46
|
$encoded = [Convert]::ToBase64String($cipher)
|
|
47
47
|
Set-ItemProperty -Path $path -Name $name -Value $encoded
|
|
48
|
-
`}async function Se(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await Ur("powershell.exe",r):await ot("powershell.exe",r,e);return {stdout:n,missing:!1}}catch(r){if(r?.code===3||r?.exitCode===3)return {stdout:"",missing:true};throw r}}function I(t){return t.replace(/'/g,"''")}var Mr="byted_cli_user_token";function ne(t,e=Mr,r=process.platform){switch(U(t,e),r){case "darwin":return new x(t,e);case "win32":return new re(t,e);default:return new ve(new x(t,e),new Z(Xe(t,e)),n=>_e(t,e,n))}}var ve=class{constructor(e,r,n=async i=>i()){this.primary=e;this.legacy=r;this.runExclusive=n;}primary;legacy;runExclusive;async load(){return this.runExclusive(()=>this.loadExclusive())}async save(e){await this.runExclusive(async()=>{await this.persistAndVerify(e),await this.legacy.delete();});}async updateUserInfo(e){await this.runExclusive(async()=>{let r=await this.loadExclusive();r.userInfo=e,await this.persistAndVerify(r),await this.legacy.delete();});}async delete(){await this.runExclusive(async()=>{let e;for(let r of [this.primary,this.legacy])try{await r.delete();}catch(n){e??=n;}if(e!==void 0)throw e});}async loadExclusive(){try{let r=await this.primary.load();return await this.legacy.delete(),r}catch(r){if(!m(r,"NOT_FOUND"))throw r}let e=await this.legacy.load();return await this.persistAndVerify(e),await this.legacy.delete(),e}async persistAndVerify(e){await this.primary.save(e);let r=await this.primary.load();if(_(r)!==_(e))throw await this.primary.delete().catch(()=>{}),h("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var st={NOT_LOGGED_IN:"authsdk: not logged in",LOGIN_PENDING:"authsdk: login pending",LOGIN_DENIED:"authsdk: login denied",LOGIN_EXPIRED:"authsdk: login expired",TOKEN_EXPIRED:"authsdk: token expired",REFRESH_FAILED:"authsdk: refresh failed",SIGN_FAILED:"authsdk: sign failed",STORE_UNAVAILABLE:"authsdk: store unavailable",PROTOCOL_ERROR:"authsdk: protocol error",INVALID_ARGUMENT:"authsdk: invalid argument"},g=class extends Error{code;cause;constructor(e,r=st[e],n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="AuthError",this.code=e,this.cause=n;}};function l(t,e){return new g(t,st[t],e)}var jr=createRequire(import.meta.url),zr="CN",$=3e3;function ut(){return {name:ct(at.hostname()||"unknown",128),os:en(process.platform),osVersion:ct(at.release()||"",64),architecture:tn(process.arch),cliVersion:rn(),region:qr()}}function qr(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(Oe(t.readMacOSLocale??Jr,void 0));else if(e==="win32"){let i=Xr(Oe(t.readWindowsRegion??Zr,void 0));if(i)return i}else e==="linux"&&n.push(...Qr(Oe(t.readLinuxLocales??Yr,[])));n.push(r.LC_ALL,r.LC_MESSAGES,r.LANG,r.LANGUAGE,t.intlLocale??Intl.DateTimeFormat().resolvedOptions().locale);for(let i of n){let o=Wr(i);if(o)return o}return zr}function Xr(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function Wr(t){if(!t)return;let e=t.trim(),r=e.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(.*)$/);if(r&&(e=r[1].trim()),e=e.replace(/^["']|["']$/g,""),e=e.split(":",1)[0].split(/[.@]/,1)[0].replaceAll("_","-"),!(!e||/^(?:C|POSIX)$/i.test(e)))try{let n=new Intl.Locale(e).region?.toUpperCase();return n&&/^[A-Z]{2}$/.test(n)?n:void 0}catch{return}}function Jr(){return dt("/usr/bin/defaults",["read","-g","AppleLocale"])}function Zr(){return dt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function Yr(){let t=[];for(let e of ["/etc/locale.conf","/etc/default/locale"])try{for(let r of readFileSync(e,"utf8").split(/\r?\n/)){let n=r.trim();/^(?:LC_ALL|LC_MESSAGES|LANG|LANGUAGE)=/.test(n)&&t.push(n);}}catch{}return t}function Qr(t){let e=["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"],r=[];for(let n of e)r.push(...t.filter(i=>i?.trim().startsWith(`${n}=`)));return r.push(...t.filter(n=>!n?.includes("="))),r}function dt(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Oe(t,e){try{return t()}catch{return e}}function en(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function tn(t){return t==="x64"?"x86_64":t}function rn(){for(let t of ["../../package.json","../../../package.json"])try{let e=jr(t);if(typeof e.version=="string")return e.version}catch{}return ""}function ct(t,e){return t.length>e?t.slice(0,e):t}var nn="/passport/open/refresh_token/",lt="Bearer ",Te=class{current=Promise.resolve();async run(e){let r=this.current,n;this.current=new Promise(i=>{n=i;}),await r;try{return await e()}finally{n();}}},oe=class{core;constructor(e,r={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=r.protocol??new j({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),i=r.signer??new W,o=r.store??ne(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:i,store:o,now:r.now??(()=>new Date),mutex:new Te,deviceReportUrl:new URL(B,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:on(e.deviceReportTimeoutMs)};}authenticator(){return new Ie(this.core)}authorizer(){return new ie(this.core)}},Ie=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let r=this.core.signer.generateDeviceKey(),n=await this.core.protocol.getDeviceCode({clientKey:this.core.clientKey,scopes:this.core.scopes,pubKey:r.PublicKeyBase64},e),i=new Date(this.core.now().getTime()+n.expiresInMs),o={clientKey:this.core.clientKey,deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,loginExpiresAt:i,deviceKey:r,scopes:[...this.core.scopes]};return await De(this.core.store,o),{deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,expiresAt:i}})}async checkLogin(e,r){let n=e.trim();if(!n)throw new Error("authsdk: device_code is required");return this.core.mutex.run(async()=>{let i=await ke(this.core.store);if(!i.deviceCode||!i.loginExpiresAt)throw l("NOT_LOGGED_IN");if(i.deviceCode!==n)throw l("INVALID_ARGUMENT",new Error("device_code does not match pending login state"));if(this.core.now().getTime()>=i.loginExpiresAt.getTime())throw await se(this.core.store),l("LOGIN_EXPIRED");let o;try{o=await this.core.protocol.checkDeviceCode({deviceCode:n},r);}catch(s){let c=sn(s);throw c.code==="LOGIN_EXPIRED"&&await se(this.core.store),c}return i.deviceCode=void 0,i.userCode=void 0,i.verificationUri=void 0,i.intervalMs=void 0,i.loginExpiresAt=void 0,i.accessToken=o.accessToken,o.refreshToken&&(i.refreshToken=o.refreshToken),i.tokenExpiresAt=new Date(this.core.now().getTime()+o.expiresInMs),await De(this.core.store,i),await pt(this.core,i,r),Ne(this.core.now(),i)})}authorizer(){return new ie(this.core)}},ie=class{constructor(e){this.core=e;}core;async state(e){return this.core.mutex.run(async()=>{try{let r=await this.ensureActiveRecord(0,e);return Ne(this.core.now(),r)}catch(r){if(r instanceof g&&r.code==="NOT_LOGGED_IN")return {loggedIn:false};throw r}})}async refresh(e=0,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(Math.max(0,e),r);return Ne(this.core.now(),n)})}async inject(e,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(0,r);if(!n.accessToken||!n.deviceKey)throw l("NOT_LOGGED_IN");ht(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await this.core.store.updateUserInfo(e);}catch(r){throw G(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await ke(this.core.store);return ft(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await this.core.store.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw G(e)}})}async ensureActiveRecord(e,r){let n=await ke(this.core.store);if(!n.accessToken)throw l("NOT_LOGGED_IN");let i=this.core.now();if(cn(i,n.tokenExpiresAt,e))return n;if(!n.refreshToken||!n.deviceKey)throw await se(this.core.store),l("NOT_LOGGED_IN");let o;try{o=this.core.signer.sign({method:"POST",urlPath:nn,signingMaterial:n.refreshToken},n.deviceKey);}catch(u){throw l("SIGN_FAILED",u)}let s,c=n.accessToken;try{s=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:n.refreshToken,pubKey:o.pubKey,reqSign:o.signature,reqTs:o.timestamp,reqNonce:o.nonce},r);}catch(u){throw an(u)?(await se(this.core.store),l("NOT_LOGGED_IN")):l("REFRESH_FAILED",u)}return n.accessToken=s.accessToken,s.refreshToken&&(n.refreshToken=s.refreshToken),n.tokenExpiresAt=new Date(this.core.now().getTime()+s.expiresInMs),await De(this.core.store,n),c!==n.accessToken&&await pt(this.core,n,r),n}};async function pt(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{ht(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=lt+e.accessToken;}catch{return}let i=new AbortController,o=()=>i.abort(r?.reason);r?.aborted?o():r?.addEventListener("abort",o,{once:true});let s,c=new Promise((u,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:ut()},i.signal),c]);}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",o);}}function ht(t,e,r){if(!e.accessToken||!e.deviceKey)throw l("NOT_LOGGED_IN");let n=new URL(String(r.url)),i=r.method.trim().toUpperCase(),o=n.pathname||"/",s;try{s=t.signer.sign({method:i,urlPath:o,signingMaterial:e.accessToken},e.deviceKey);}catch(c){throw l("SIGN_FAILED",c)}C(r,"Authorization",lt+e.accessToken),C(r,"X-Pub-Key",s.pubKey),C(r,"X-Req-Sign",s.signature),C(r,"X-Req-Ts",s.timestamp),C(r,"X-Req-Nonce",s.nonce),C(r,"X-Req-Method",i),C(r,"X-Req-Path",o);}function on(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):$}async function ke(t){try{return await t.load()}catch(e){throw G(e)}}async function De(t,e){try{await t.save(e);}catch(r){throw G(r)}}async function se(t){try{await t.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw G(e)}}function G(t){return m(t,"NOT_FOUND")?l("NOT_LOGGED_IN",t):l("STORE_UNAVAILABLE",t)}function sn(t){return v(t,"AUTHORIZATION_PENDING")?l("LOGIN_PENDING",t):v(t,"ACCESS_DENIED")?l("LOGIN_DENIED",t):v(t,"EXPIRED_TOKEN")?l("LOGIN_EXPIRED",t):l("PROTOCOL_ERROR",t)}function an(t){return v(t,"EXPIRED_TOKEN")||v(t,"INVALID_GRANT")}function cn(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Ne(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:ft(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function C(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function ft(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var gt=["pico_vibe_lab","pico_ai_sgs","user_info"],mt="https://user.picoxr.com",ln=/^ppe_[A-Za-z0-9_-]+$/,wt={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:mt,deviceReportTimeoutMs:$};function Le(t={}){let e=t.ppeHeader?pn(t.ppeHeader):void 0;return {...wt,scopes:Et(gt,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function pn(t){if(!ln.test(t))throw new TypeError("ppeHeader must match ppe_[A-Za-z0-9_-]+");return Object.freeze({"X-TT-Env":t,"X-Use-PPE":"1"})}function Et(t,e){let r=new Set;for(let n of [...t,...e]){let i=n.trim();i&&r.add(i);}return [...r]}var hn=365*24*60*60*1e3;function yt(t={},e={}){let r=Le(t),n=e.store??ne(r.storeServiceName),i=new oe(r,{...e,store:n});return {getStatus(o){return fn(n,o)},startLogin(o={}){return i.authenticator().newLoginFlow(o.signal)},resumeLogin(o,s){return i.authenticator().checkLogin(o,s)},ensureAuthenticated(o){return i.authorizer().refresh(0,o)},refresh(o){return i.authorizer().refresh(hn,o)},injectAuth(o,s){return i.authorizer().inject(o,s)},logout(){return i.authorizer().logout()}}}async function fn(t,e){e?.throwIfAborted();try{let r=await t.load(),n=Date.now();return {loggedIn:!!r.accessToken&&(r.tokenExpiresAt===void 0||n<r.tokenExpiresAt.getTime()),expiresAt:r.tokenExpiresAt,identity:gn(r.userInfo),scopes:r.scopes?[...r.scopes]:void 0}}catch(r){if(m(r,"NOT_FOUND"))return {loggedIn:false};throw l("STORE_UNAVAILABLE",r)}}function gn(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var mn=/^(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)$/i,wn=/(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)(["'\s:=]+)(?:Bearer\s+)?([^"'\s,}]+)/gi;function K(t,e,r){if(t.json){t.stdout(`${JSON.stringify(P(r))}
|
|
48
|
+
`}async function Se(t,e){try{let r=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",t],{stdout:n}=e===void 0?await Ur("powershell.exe",r):await ot("powershell.exe",r,e);return {stdout:n,missing:!1}}catch(r){if(r?.code===3||r?.exitCode===3)return {stdout:"",missing:true};throw r}}function I(t){return t.replace(/'/g,"''")}var Mr="byted_cli_user_token";function ne(t,e=Mr,r=process.platform){switch(U(t,e),r){case "darwin":return new x(t,e);case "win32":return new re(t,e);default:return new Ce(new x(t,e),new Z(Xe(t,e)),n=>_e(t,e,n))}}var Ce=class{constructor(e,r,n=async i=>i()){this.primary=e;this.legacy=r;this.runExclusive=n;}primary;legacy;runExclusive;async load(){return this.runExclusive(()=>this.loadExclusive())}async save(e){await this.runExclusive(async()=>{await this.persistAndVerify(e),await this.legacy.delete();});}async updateUserInfo(e){await this.runExclusive(async()=>{let r=await this.loadExclusive();r.userInfo=e,await this.persistAndVerify(r),await this.legacy.delete();});}async delete(){await this.runExclusive(async()=>{let e;for(let r of [this.primary,this.legacy])try{await r.delete();}catch(n){e??=n;}if(e!==void 0)throw e});}async loadExclusive(){try{let r=await this.primary.load();return await this.legacy.delete(),r}catch(r){if(!m(r,"NOT_FOUND"))throw r}let e=await this.legacy.load();return await this.persistAndVerify(e),await this.legacy.delete(),e}async persistAndVerify(e){await this.primary.save(e);let r=await this.primary.load();if(_(r)!==_(e))throw await this.primary.delete().catch(()=>{}),h("BACKEND_UNAVAILABLE","save",new Error("credential migration verification failed"))}};var st={NOT_LOGGED_IN:"authsdk: not logged in",LOGIN_PENDING:"authsdk: login pending",LOGIN_DENIED:"authsdk: login denied",LOGIN_EXPIRED:"authsdk: login expired",TOKEN_EXPIRED:"authsdk: token expired",REFRESH_FAILED:"authsdk: refresh failed",SIGN_FAILED:"authsdk: sign failed",STORE_UNAVAILABLE:"authsdk: store unavailable",PROTOCOL_ERROR:"authsdk: protocol error",INVALID_ARGUMENT:"authsdk: invalid argument"},g=class extends Error{code;cause;constructor(e,r=st[e],n){super(n instanceof Error?`${r}: ${n.message}`:r),this.name="AuthError",this.code=e,this.cause=n;}};function l(t,e){return new g(t,st[t],e)}var jr=createRequire(import.meta.url),zr="CN",$=3e3;function ut(){return {name:ct(at.hostname()||"unknown",128),os:en(process.platform),osVersion:ct(at.release()||"",64),architecture:tn(process.arch),cliVersion:rn(),region:qr()}}function qr(t={}){let e=t.platform??process.platform,r=t.environment??process.env,n=[];if(e==="darwin")n.push(Oe(t.readMacOSLocale??Jr,void 0));else if(e==="win32"){let i=Xr(Oe(t.readWindowsRegion??Zr,void 0));if(i)return i}else e==="linux"&&n.push(...Qr(Oe(t.readLinuxLocales??Yr,[])));n.push(r.LC_ALL,r.LC_MESSAGES,r.LANG,r.LANGUAGE,t.intlLocale??Intl.DateTimeFormat().resolvedOptions().locale);for(let i of n){let o=Wr(i);if(o)return o}return zr}function Xr(t){let e=t?.trim().toUpperCase();return e&&/^[A-Z]{2}$/.test(e)?e:void 0}function Wr(t){if(!t)return;let e=t.trim(),r=e.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(.*)$/);if(r&&(e=r[1].trim()),e=e.replace(/^["']|["']$/g,""),e=e.split(":",1)[0].split(/[.@]/,1)[0].replaceAll("_","-"),!(!e||/^(?:C|POSIX)$/i.test(e)))try{let n=new Intl.Locale(e).region?.toUpperCase();return n&&/^[A-Z]{2}$/.test(n)?n:void 0}catch{return}}function Jr(){return dt("/usr/bin/defaults",["read","-g","AppleLocale"])}function Zr(){return dt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-ItemPropertyValue -LiteralPath 'HKCU:\\Control Panel\\International\\Geo' -Name Name"])}function Yr(){let t=[];for(let e of ["/etc/locale.conf","/etc/default/locale"])try{for(let r of readFileSync(e,"utf8").split(/\r?\n/)){let n=r.trim();/^(?:LC_ALL|LC_MESSAGES|LANG|LANGUAGE)=/.test(n)&&t.push(n);}}catch{}return t}function Qr(t){let e=["LC_ALL","LC_MESSAGES","LANG","LANGUAGE"],r=[];for(let n of e)r.push(...t.filter(i=>i?.trim().startsWith(`${n}=`)));return r.push(...t.filter(n=>!n?.includes("="))),r}function dt(t,e){try{return execFileSync(t,e,{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Oe(t,e){try{return t()}catch{return e}}function en(t){switch(t){case "darwin":return "macOS";case "win32":return "Windows";case "linux":return "Linux";default:return t}}function tn(t){return t==="x64"?"x86_64":t}function rn(){for(let t of ["../../package.json","../../../package.json"])try{let e=jr(t);if(typeof e.version=="string")return e.version}catch{}return ""}function ct(t,e){return t.length>e?t.slice(0,e):t}var nn="/passport/open/refresh_token/",lt="Bearer ",Te=class{current=Promise.resolve();async run(e){let r=this.current,n;this.current=new Promise(i=>{n=i;}),await r;try{return await e()}finally{n();}}},oe=class{core;constructor(e,r={}){if(!e.clientKey.trim())throw new Error("authsdk: client_key is required");let n=r.protocol??new j({baseUrl:e.baseUrl,aid:e.aid,headers:e.customHttpHeaders,deviceReportBaseUrl:e.deviceReportBaseUrl,deviceReportHttpHeaders:e.deviceReportHttpHeaders}),i=r.signer??new W,o=r.store??ne(e.storeServiceName);this.core={clientKey:e.clientKey.trim(),scopes:[...e.scopes??[]],protocol:n,signer:i,store:o,now:r.now??(()=>new Date),mutex:new Te,deviceReportUrl:new URL(B,e.deviceReportBaseUrl??e.baseUrl).toString(),deviceReportTimeoutMs:on(e.deviceReportTimeoutMs)};}authenticator(){return new Ie(this.core)}authorizer(){return new ie(this.core)}},Ie=class{constructor(e){this.core=e;}core;async newLoginFlow(e){return this.core.mutex.run(async()=>{let r=this.core.signer.generateDeviceKey(),n=await this.core.protocol.getDeviceCode({clientKey:this.core.clientKey,scopes:this.core.scopes,pubKey:r.PublicKeyBase64},e),i=new Date(this.core.now().getTime()+n.expiresInMs),o={clientKey:this.core.clientKey,deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,loginExpiresAt:i,deviceKey:r,scopes:[...this.core.scopes]};return await De(this.core.store,o),{deviceCode:n.deviceCode,userCode:n.userCode,verificationUri:n.verificationUri,intervalMs:n.intervalMs,expiresAt:i}})}async checkLogin(e,r){let n=e.trim();if(!n)throw new Error("authsdk: device_code is required");return this.core.mutex.run(async()=>{let i=await ke(this.core.store);if(!i.deviceCode||!i.loginExpiresAt)throw l("NOT_LOGGED_IN");if(i.deviceCode!==n)throw l("INVALID_ARGUMENT",new Error("device_code does not match pending login state"));if(this.core.now().getTime()>=i.loginExpiresAt.getTime())throw await se(this.core.store),l("LOGIN_EXPIRED");let o;try{o=await this.core.protocol.checkDeviceCode({deviceCode:n},r);}catch(s){let c=sn(s);throw c.code==="LOGIN_EXPIRED"&&await se(this.core.store),c}return i.deviceCode=void 0,i.userCode=void 0,i.verificationUri=void 0,i.intervalMs=void 0,i.loginExpiresAt=void 0,i.accessToken=o.accessToken,o.refreshToken&&(i.refreshToken=o.refreshToken),i.tokenExpiresAt=new Date(this.core.now().getTime()+o.expiresInMs),await De(this.core.store,i),await pt(this.core,i,r),Ne(this.core.now(),i)})}authorizer(){return new ie(this.core)}},ie=class{constructor(e){this.core=e;}core;async state(e){return this.core.mutex.run(async()=>{try{let r=await this.ensureActiveRecord(0,e);return Ne(this.core.now(),r)}catch(r){if(r instanceof g&&r.code==="NOT_LOGGED_IN")return {loggedIn:false};throw r}})}async refresh(e=0,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(Math.max(0,e),r);return Ne(this.core.now(),n)})}async inject(e,r){return this.core.mutex.run(async()=>{let n=await this.ensureActiveRecord(0,r);if(!n.accessToken||!n.deviceKey)throw l("NOT_LOGGED_IN");ht(this.core,n,e);})}async updateUserInfo(e){return this.core.mutex.run(async()=>{try{await this.core.store.updateUserInfo(e);}catch(r){throw G(r)}})}async userInfo(){return this.core.mutex.run(async()=>{let e=await ke(this.core.store);return ft(e.userInfo)})}async logout(){return this.core.mutex.run(async()=>{try{await this.core.store.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw G(e)}})}async ensureActiveRecord(e,r){let n=await ke(this.core.store);if(!n.accessToken)throw l("NOT_LOGGED_IN");let i=this.core.now();if(cn(i,n.tokenExpiresAt,e))return n;if(!n.refreshToken||!n.deviceKey)throw await se(this.core.store),l("NOT_LOGGED_IN");let o;try{o=this.core.signer.sign({method:"POST",urlPath:nn,signingMaterial:n.refreshToken},n.deviceKey);}catch(u){throw l("SIGN_FAILED",u)}let s,c=n.accessToken;try{s=await this.core.protocol.refreshToken({clientKey:this.core.clientKey,refreshToken:n.refreshToken,pubKey:o.pubKey,reqSign:o.signature,reqTs:o.timestamp,reqNonce:o.nonce},r);}catch(u){throw an(u)?(await se(this.core.store),l("NOT_LOGGED_IN")):l("REFRESH_FAILED",u)}return n.accessToken=s.accessToken,s.refreshToken&&(n.refreshToken=s.refreshToken),n.tokenExpiresAt=new Date(this.core.now().getTime()+s.expiresInMs),await De(this.core.store,n),c!==n.accessToken&&await pt(this.core,n,r),n}};async function pt(t,e,r){if(!e.accessToken||!e.deviceKey)return;let n={};try{ht(t,e,{method:"POST",url:t.deviceReportUrl,headers:n}),n["Authorization-act"]=lt+e.accessToken;}catch{return}let i=new AbortController,o=()=>i.abort(r?.reason);r?.aborted?o():r?.addEventListener("abort",o,{once:true});let s,c=new Promise((u,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("device report timed out"));},t.deviceReportTimeoutMs);});try{await Promise.race([t.protocol.reportDeviceAuthorization({headers:n,deviceInfo:ut()},i.signal),c]);}catch{}finally{s&&clearTimeout(s),r?.removeEventListener("abort",o);}}function ht(t,e,r){if(!e.accessToken||!e.deviceKey)throw l("NOT_LOGGED_IN");let n=new URL(String(r.url)),i=r.method.trim().toUpperCase(),o=n.pathname||"/",s;try{s=t.signer.sign({method:i,urlPath:o,signingMaterial:e.accessToken},e.deviceKey);}catch(c){throw l("SIGN_FAILED",c)}P(r,"Authorization",lt+e.accessToken),P(r,"X-Pub-Key",s.pubKey),P(r,"X-Req-Sign",s.signature),P(r,"X-Req-Ts",s.timestamp),P(r,"X-Req-Nonce",s.nonce),P(r,"X-Req-Method",i),P(r,"X-Req-Path",o);}function on(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):$}async function ke(t){try{return await t.load()}catch(e){throw G(e)}}async function De(t,e){try{await t.save(e);}catch(r){throw G(r)}}async function se(t){try{await t.delete();}catch(e){if(!m(e,"NOT_FOUND"))throw G(e)}}function G(t){return m(t,"NOT_FOUND")?l("NOT_LOGGED_IN",t):l("STORE_UNAVAILABLE",t)}function sn(t){return C(t,"AUTHORIZATION_PENDING")?l("LOGIN_PENDING",t):C(t,"ACCESS_DENIED")?l("LOGIN_DENIED",t):C(t,"EXPIRED_TOKEN")?l("LOGIN_EXPIRED",t):l("PROTOCOL_ERROR",t)}function an(t){return C(t,"EXPIRED_TOKEN")||C(t,"INVALID_GRANT")}function cn(t,e,r){return e?r===0?t.getTime()<e.getTime():t.getTime()+r<=e.getTime():r===0}function Ne(t,e){return {loggedIn:!!e.accessToken&&(e.tokenExpiresAt===void 0||t.getTime()<e.tokenExpiresAt.getTime()),expiresAt:e.tokenExpiresAt,identity:ft(e.userInfo),scopes:e.scopes?[...e.scopes]:void 0}}function P(t,e,r){if(t.headers instanceof Headers){t.headers.set(e,r);return}t.headers||(t.headers={}),t.headers[e]=r;}function ft(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var gt=["pico_vibe_lab","pico_ai_sgs","user_info"],mt="https://user.picoxr.com",ln=/^ppe_[A-Za-z0-9_-]+$/,wt={clientKey:"pk5r7bo5smkyen3r",baseUrl:"https://matrix-cn.picovr.com",aid:305817,storeServiceName:"pico-auth-cli",deviceReportBaseUrl:mt,deviceReportTimeoutMs:$};function Le(t={}){let e=t.ppeHeader?pn(t.ppeHeader):void 0;return {...wt,scopes:Et(gt,t.scopes??[]),...e?{customHttpHeaders:{...e},deviceReportHttpHeaders:{...e}}:{}}}function pn(t){if(!ln.test(t))throw new TypeError("ppeHeader must match ppe_[A-Za-z0-9_-]+");return Object.freeze({"X-TT-Env":t,"X-Use-PPE":"1"})}function Et(t,e){let r=new Set;for(let n of [...t,...e]){let i=n.trim();i&&r.add(i);}return [...r]}var hn=365*24*60*60*1e3;function yt(t={},e={}){let r=Le(t),n=e.store??ne(r.storeServiceName),i=new oe(r,{...e,store:n});return {getStatus(o){return fn(n,o)},startLogin(o={}){return i.authenticator().newLoginFlow(o.signal)},resumeLogin(o,s){return i.authenticator().checkLogin(o,s)},ensureAuthenticated(o){return i.authorizer().refresh(0,o)},refresh(o){return i.authorizer().refresh(hn,o)},injectAuth(o,s){return i.authorizer().inject(o,s)},logout(){return i.authorizer().logout()}}}async function fn(t,e){e?.throwIfAborted();try{let r=await t.load(),n=Date.now();return {loggedIn:!!r.accessToken&&(r.tokenExpiresAt===void 0||n<r.tokenExpiresAt.getTime()),expiresAt:r.tokenExpiresAt,identity:gn(r.userInfo),scopes:r.scopes?[...r.scopes]:void 0}}catch(r){if(m(r,"NOT_FOUND"))return {loggedIn:false};throw l("STORE_UNAVAILABLE",r)}}function gn(t){return t==null?t:typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var mn=/^(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)$/i,wn=/(access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|privatekeybase64|x-req-sign|req[_-]?sign|signature)(["'\s:=]+)(?:Bearer\s+)?([^"'\s,}]+)/gi;function K(t,e,r){if(t.json){t.stdout(`${JSON.stringify(v(r))}
|
|
49
49
|
`);return}for(let n of e)t.stdout(`${M(n)}
|
|
50
|
-
`);}function F(t,e){let r=
|
|
50
|
+
`);}function F(t,e){let r=v(e);if(t.json){t.stderr(`${JSON.stringify({ok:false,...r})}
|
|
51
51
|
`);return}t.stderr(`error=${r.code}
|
|
52
52
|
`),t.stderr(`message=${r.message}
|
|
53
53
|
`),t.stderr(`recoverable=${r.recoverable}
|
|
54
54
|
`),t.stderr(`action=${r.action}
|
|
55
|
-
`);}function At(t,e,r={}){let n=
|
|
55
|
+
`);}function At(t,e,r={}){let n=v({event:e,...r});if(t.json){t.stderr(`${JSON.stringify({ok:true,verbose:n})}
|
|
56
56
|
`);return}let i=Object.entries(n).map(([o,s])=>`${o}=${String(s)}`).join(" ");t.stderr(`verbose ${i}
|
|
57
|
-
`);}function
|
|
57
|
+
`);}function v(t){if(Array.isArray(t))return t.map(e=>v(e));if(t instanceof Date)return t.toISOString();if(t&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=mn.test(r)?"[REDACTED]":v(n);return e}return typeof t=="string"?M(t):t}function M(t){return t.replace(/("(?:access_token|refresh_token|accessToken|refreshToken|device_key|deviceKey|PrivateKeyBase64|privateKey|Authorization(?:-act)?|X-Req-Sign|reqSign|signature)"\s*:\s*)\{[^}]*\}/gi,'$1"[REDACTED]"').replace(/("(?:access_token|refresh_token|accessToken|refreshToken|device_key|deviceKey|PrivateKeyBase64|privateKey|Authorization(?:-act)?|X-Req-Sign|reqSign|signature)"\s*:\s*")([^"]*)(")/gi,"$1[REDACTED]$3").replace(wn,(e,r,n)=>`${r}${n}[REDACTED]`).replace(/([?&](?:access[_-]?token|refresh[_-]?token|authorization(?:-act)?|device[_-]?key|private[_-]?key|x-req-sign)=)([^&#\s]+)/gi,(e,r)=>`${r}[REDACTED]`)}var An=1e3,_n=12e4,St=4,Pt=2,Rn=3,_t=5,be=6,Sn=7,Pn=8,de={NOT_LOGGED_IN:{message:"You are not signed in.",action:"Run pico-auth-cli-cn login.",exitCode:Rn},LOGIN_PENDING:{message:"Authorization is not complete yet.",action:"Complete browser authorization, then rerun pico-auth-cli-cn login --resume <device_code>.",exitCode:St},LOGIN_DENIED:{message:"Authorization was denied.",action:"Restart login and approve the PICO authorization request.",exitCode:Pn},LOGIN_EXPIRED:{message:"The sign-in request has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:_t},TOKEN_EXPIRED:{message:"The session has expired.",action:"Restart login with pico-auth-cli-cn login.",exitCode:_t},REFRESH_FAILED:{message:"The session could not be refreshed.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:be},SIGN_FAILED:{message:"The request could not be signed.",action:"Contact the pico-auth-cli-cn maintainer with the sanitized error details.",exitCode:1},STORE_UNAVAILABLE:{message:"The local credential store is unavailable.",action:"Check local credential store permissions, then run pico-auth-cli-cn status. Do not refresh or logout while storage access is unavailable.",exitCode:Sn},PROTOCOL_ERROR:{message:"The PICO authentication service returned an unexpected response.",action:"Retry the command after checking network or PICO OAuth service availability.",exitCode:be},INVALID_ARGUMENT:{message:"The command contains an invalid argument.",action:"Run pico-auth-cli-cn --help or the subcommand help and retry with valid arguments.",exitCode:Pt}};async function vt(t,e={}){let r=e.stdout??(o=>process.stdout.write(o)),n=e.stderr??(o=>process.stderr.write(o)),i={json:t.includes("--json"),stdout:r,stderr:n};try{let o=Gn(t);if(i.json=o.global.json,!o.command||o.command==="--help"||o.command==="-h")return zn(r),0;if(o.command==="--version"||o.command==="-v")return r(`${(e.readVersion??Xn)()}
|
|
58
58
|
`),0;let s=e.createClient??yt;switch(o.command){case "login":return ae(o.args)?(r(`${Ot()}
|
|
59
|
-
`),0):await
|
|
59
|
+
`),0):await vn(o.args,o.global,s,i,e);case "status":return ae(o.args)?(r(`Usage:
|
|
60
60
|
pico-auth-cli-cn status [--json]
|
|
61
|
-
`),0):await
|
|
61
|
+
`),0):await Cn(o.args,o.global,s,i);case "refresh":return ae(o.args)?(r(`${qn()}
|
|
62
62
|
`),0):await On(o.args,o.global,s,i);case "logout":return ae(o.args)?(r(`Usage:
|
|
63
63
|
pico-auth-cli-cn logout [--json]
|
|
64
|
-
`),0):await Tn(o.args,o.global,s,i);default:throw new w(`unknown command: ${o.command}`)}}catch(o){return o instanceof le?(xn(i),St):o instanceof pe?(F(i,ce("LOGIN_TIMEOUT",o.message)),be):o instanceof w?(F(i,ce("INVALID_ARGUMENT",o.message)),
|
|
65
|
-
`);let d=await Un(u.verificationUri,e,n,i.openBrowser);bn(n,u,d);let A=await kn(s,u,o.timeoutMs,i.sleep??jn,i.now??(()=>new Date));return Rt(n,"authenticated",A),0}async function
|
|
64
|
+
`),0):await Tn(o.args,o.global,s,i);default:throw new w(`unknown command: ${o.command}`)}}catch(o){return o instanceof le?(xn(i),St):o instanceof pe?(F(i,ce("LOGIN_TIMEOUT",o.message)),be):o instanceof w?(F(i,ce("INVALID_ARGUMENT",o.message)),Pt):o instanceof g?(F(i,ce(o.code,Vn(o.code))),Mn(o)):(F(i,ce("UNKNOWN","An unexpected error occurred.")),1)}}async function vn(t,e,r,n,i){let o=Kn(t),s=r({scopes:o.scopes,ppeHeader:e.ppeHeader});if(o.resume){let p=await In(s,o.resume);return Rt(n,"login_resumed",p),0}let c=await s.getStatus();if(c.loggedIn&&!o.force)return ue(e,n,"login_existing_state"),Ln(n,c),0;o.force&&(ue(e,n,"login_force_clear"),await s.logout());let u=await s.startLogin();if(Ct(u.verificationUri),ue(e,n,"login_started",{verification_uri:u.verificationUri,expires_at:u.expiresAt}),o.noWait)return Dn(n,u,e.ppeHeader),0;n.json||n.stdout(`Opening your browser to sign in to PICO...
|
|
65
|
+
`);let d=await Un(u.verificationUri,e,n,i.openBrowser);bn(n,u,d);let A=await kn(s,u,o.timeoutMs,i.sleep??jn,i.now??(()=>new Date));return Rt(n,"authenticated",A),0}async function Cn(t,e,r,n){Ue("status",t);let o=await r({ppeHeader:e.ppeHeader}).getStatus();return he(n,"status",o),0}async function On(t,e,r,n){Ue("refresh",t);let i=r({ppeHeader:e.ppeHeader});try{let o=await i.refresh();return he(n,"refreshed",o),0}catch(o){throw o instanceof g&&o.code==="NOT_LOGGED_IN"&&await i.logout(),o}}async function Tn(t,e,r,n){return Ue("logout",t),await r({ppeHeader:e.ppeHeader}).logout(),K(n,["Signed out successfully."],{ok:true,loggedOut:true}),0}async function In(t,e){try{return await t.resumeLogin(e)}catch(r){throw r instanceof g&&r.code==="LOGIN_PENDING"?new le:(r instanceof g&&r.code==="LOGIN_EXPIRED"&&await t.logout(),r)}}async function kn(t,e,r,n,i){let o=Math.min(i().getTime()+r,e.expiresAt.getTime());for(;i().getTime()<o;)try{return await t.resumeLogin(e.deviceCode)}catch(s){if(s instanceof g&&s.code==="LOGIN_PENDING"){await n(An);continue}throw s instanceof g&&s.code==="LOGIN_EXPIRED"&&await t.logout(),s}throw await t.logout(),new pe("Sign-in timed out. The local state for this attempt was cleared.")}function Dn(t,e,r){if(!t.json){t.stdout(`Sign-in request created. Open this page to sign in to PICO and authorize access:
|
|
66
66
|
`),t.stdout(` ${M(e.verificationUri)}
|
|
67
|
-
`),t.stdout(`Authorization code (if prompted): ${e.userCode}
|
|
68
67
|
`),t.stdout(`Sign-in request expires at: ${e.expiresAt.toISOString()}
|
|
69
68
|
`),t.stdout(`After completing authorization in your browser, run:
|
|
70
69
|
`);let n=r?` --ppe_header=${r}`:"";t.stdout(` pico-auth-cli-cn${n} login --resume '${e.deviceCode}'
|
|
71
|
-
`);return}K(t,[`device_code=${e.deviceCode}`,`
|
|
70
|
+
`);return}K(t,[`device_code=${e.deviceCode}`,`verification_uri=${e.verificationUri}`,`expires_at=${e.expiresAt.toISOString()}`],{ok:true,device_code:e.deviceCode,user_code:e.userCode,verification_uri:e.verificationUri,expires_at:e.expiresAt});}function he(t,e,r){if(!t.json){if(e==="status"){Nn(t,r);return}if(e==="refreshed"){t.stdout(`Session refreshed successfully.
|
|
72
71
|
`);return}}let n={ok:true,status:e,authenticated:r.loggedIn},i=[`status=${e}`,`authenticated=${r.loggedIn}`];r.identity!==void 0&&(n.identity=r.identity),r.scopes!==void 0&&(n.scopes=r.scopes,i.push(`scopes=${r.scopes.join(",")}`)),r.expiresAt&&(n.expires_at=r.expiresAt,i.push(`expires_at=${r.expiresAt.toISOString()}`)),r.loggedIn||(n.reason=r.expiresAt?"expired":"not_logged_in",i.push(`reason=${n.reason}`)),K(t,i,n);}function Nn(t,e){if(!e.loggedIn){t.stdout(e.expiresAt?`Status: Expired.
|
|
73
72
|
`:`Status: Signed out.
|
|
74
73
|
`);return}t.stdout(`Status: Signed in.
|
|
@@ -79,14 +78,13 @@ Signed in successfully.
|
|
|
79
78
|
`);}function Ln(t,e){if(t.json){he(t,"already_authenticated",e);return}t.stdout(`You are already signed in.
|
|
80
79
|
`),t.stdout(`To switch accounts, run pico-auth-cli-cn login --force.
|
|
81
80
|
`);}function xn(t){if(t.json){K(t,[],{ok:true,status:"pending"});return}t.stdout(`Authorization is not complete yet. Finish it in your browser, then run the same login --resume command again.
|
|
82
|
-
`);}function bn(t,e,r){let n={ok:true,status:"login_started",verification_uri:e.verificationUri,user_code:e.userCode,expires_at:e.expiresAt.toISOString()};if(t.json){t.stderr(`${JSON.stringify(
|
|
81
|
+
`);}function bn(t,e,r){let n={ok:true,status:"login_started",verification_uri:e.verificationUri,user_code:e.userCode,expires_at:e.expiresAt.toISOString()};if(t.json){t.stderr(`${JSON.stringify(v(n))}
|
|
83
82
|
`);return}r?t.stdout(`The PICO sign-in page is open in your default browser.
|
|
84
83
|
`):t.stdout(`We couldn't open your browser automatically. Open the sign-in page below.
|
|
85
84
|
`),t.stdout(`Complete sign-in and authorization in your browser, then return here. The CLI will continue automatically.
|
|
86
85
|
`),t.stdout(`Sign-in page: ${M(e.verificationUri)}
|
|
87
|
-
`),t.stdout(`Authorization code (if prompted): ${e.userCode}
|
|
88
86
|
`),t.stdout(`Waiting for authorization. Keep this window open...
|
|
89
|
-
`);}async function Un(t,e,r,n){
|
|
87
|
+
`);}async function Un(t,e,r,n){Ct(t);try{return n?(await n(t),!0):(await $n(t),!0)}catch{return ue(e,r,"browser_open_failed",{message:"The browser could not be opened automatically.",verification_uri:t}),false}}async function $n(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];await new Promise((n,i)=>{let o=spawn(e,r,{stdio:"ignore",detached:true});o.once("error",i),o.once("spawn",()=>{o.unref(),n();});});}function Ct(t){let e;try{e=new URL(t);}catch(r){throw new g("INVALID_ARGUMENT","The verification URI returned by the authentication service is invalid.",r)}if(e.protocol!=="https:")throw new g("INVALID_ARGUMENT","The verification URI returned by the authentication service must use HTTPS.")}function Gn(t){let e={json:false,verbose:false},r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(i==="--json"){e.json=true;continue}if(i==="--verbose"){e.verbose=true;continue}if(i==="--ppe_header")throw new w("--ppe_header requires a value in the form --ppe_header=ppe_xxx");if(i.startsWith("--ppe_header=")){let o=i.slice(13);if(!/^ppe_[A-Za-z0-9_-]+$/.test(o))throw new w("--ppe_header must match ppe_[A-Za-z0-9_-]+");e.ppeHeader=o;continue}r.push(i);}return {command:r[0],args:r.slice(1),global:e}}function Kn(t){let e={force:false,noWait:false,scopes:[],timeoutMs:_n};for(let r=0;r<t.length;r+=1){let n=t[r];switch(n){case "--force":e.force=true;break;case "--no-wait":e.noWait=true;break;case "--resume":e.resume=xe(t,++r,"--resume");break;case "--scope":e.scopes.push(xe(t,++r,"--scope"));break;case "--timeout":e.timeoutMs=Fn(xe(t,++r,"--timeout"));break;case "--help":case "-h":throw new w(Ot());default:throw new w(`login: unknown option ${n}`)}}if(e.resume&&(e.force||e.noWait||e.scopes.length>0))throw new w("login --resume cannot be combined with --force, --no-wait, or --scope");return e}function xe(t,e,r){let n=t[e];if(!n||n.startsWith("--"))throw new w(`${r} requires a value`);return n}function Fn(t){let e=t.trim().match(/^(\d+)(ms|s|m)?$/);if(!e)throw new w(`invalid duration: ${t}`);let r=Number(e[1]),n=e[2]??"ms",o=r*(n==="m"?6e4:n==="s"?1e3:1);if(!Number.isSafeInteger(o)||o<=0)throw new w(`invalid duration: ${t}`);return o}function Ue(t,e){if(e.length!==0)throw new w(`${t} does not accept arguments`)}function ae(t){return t.includes("--help")||t.includes("-h")}function ue(t,e,r,n){t.verbose&&At(e,r,n);}function Mn(t){return de[t.code].exitCode}function ce(t,e){let r=Hn(t);return {code:t,message:e,recoverable:r!=="Contact the pico-auth-cli-cn maintainer with the sanitized error details.",action:r}}function Vn(t){return de[t].message}function Hn(t){let e=Bn(t);return e?e.action:t==="LOGIN_TIMEOUT"?"Retry pico-auth-cli-cn login when ready to complete browser authorization.":"Contact the pico-auth-cli-cn maintainer with the sanitized error details."}function Bn(t){return Object.hasOwn(de,t)?de[t]:void 0}function jn(t){return new Promise(e=>setTimeout(e,t))}function zn(t){t(`pico-auth-cli-cn
|
|
90
88
|
|
|
91
89
|
Usage:
|
|
92
90
|
pico-auth-cli-cn login [--force] [--scope <scope> ...]
|
|
@@ -126,4 +124,4 @@ Options:
|
|
|
126
124
|
Contacts the PICO authentication service and updates the stored login state.
|
|
127
125
|
After a business service reports NOT_LOGGED_IN, run refresh once and then run
|
|
128
126
|
pico-auth-cli-cn --json status. If Auth remains authenticated but the business service still
|
|
129
|
-
rejects the session, report the sanitized business error to the service support team.`}function Xn(){let t=new URL("../../../package.json",import.meta.url);return JSON.parse(readFileSync(t,"utf8")).version??"0.0.0"}var le=class extends Error{constructor(){super("authorization pending");}},pe=class extends Error{},w=class extends Error{};async function Jn(t=process.argv.slice(2)){return
|
|
127
|
+
rejects the session, report the sanitized business error to the service support team.`}function Xn(){let t=new URL("../../../package.json",import.meta.url);return JSON.parse(readFileSync(t,"utf8")).version??"0.0.0"}var le=class extends Error{constructor(){super("authorization pending");}},pe=class extends Error{},w=class extends Error{};async function Jn(t=process.argv.slice(2)){return vt(t)}function Zn(){let t=process.argv[1];return t?realpathSync(fileURLToPath(import.meta.url))===realpathSync(t):false}Zn()&&Jn().then(t=>{process.exitCode=t;}).catch(t=>{console.error(t instanceof Error?t.message:String(t)),process.exitCode=1;});export{Jn as main};
|