@picoxr/pico-auth-cli-cn 0.0.17 → 0.1.19
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 +1 -1
- package/package.json +1 -1
package/dist/src/cli/main.js
CHANGED
|
@@ -45,7 +45,7 @@ $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:=]+)([^"'\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 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))}
|
|
49
49
|
`);return}for(let n of e)t.stdout(`${M(n)}
|
|
50
50
|
`);}function F(t,e){let r=P(e);if(t.json){t.stderr(`${JSON.stringify({ok:false,...r})}
|
|
51
51
|
`);return}t.stderr(`error=${r.code}
|