@amaster.ai/auth-client 1.1.64 → 1.1.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -0
- package/dist/auth.d.cts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/oauth.d.cts +1 -1
- package/dist/oauth.d.ts +1 -1
- package/dist/permissions.d.cts +1 -1
- package/dist/permissions.d.ts +1 -1
- package/dist/sessions.d.cts +1 -1
- package/dist/sessions.d.ts +1 -1
- package/dist/{types-gL38Ysk-.d.cts → types-V9dnGh8N.d.cts} +1 -1
- package/dist/{types-gL38Ysk-.d.ts → types-V9dnGh8N.d.ts} +1 -1
- package/dist/user.d.cts +1 -1
- package/dist/user.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -19,8 +19,8 @@ import { createPermissionsModule } from './permissions.js';
|
|
|
19
19
|
import { createUserModule } from './user.js';
|
|
20
20
|
import { createOAuthModule } from './oauth.js';
|
|
21
21
|
import { createSessionsModule } from './sessions.js';
|
|
22
|
-
import { A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-
|
|
23
|
-
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, F as FeishuPublicConfig, L as LoginParams, e as LoginResponse, f as LoginType, M as MiniGetPhoneEvent, g as MiniGetPhoneParams, h as MiniLoginParams, i as MiniProgramLoginParams, k as MiniProgramPhoneParams, l as MiniProgramPhoneResponse, j as MiniProgramPlatform, O as OAuthBinding, m as OAuthLoginTicketResponse, n as OAuthProvider, P as Permission, o as PermissionDetail, R as RefreshTokenResponse, p as RegisterParams, q as RegisterResponse, r as RevokeAllSessionsResponse, s as Role, t as RoleDetail, S as SendCodeParams, u as SendCodeType, v as Session, w as SuccessResponse, U as UpdateMeParams, x as User } from './types-
|
|
22
|
+
import { A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-V9dnGh8N.js';
|
|
23
|
+
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, F as FeishuPublicConfig, L as LoginParams, e as LoginResponse, f as LoginType, M as MiniGetPhoneEvent, g as MiniGetPhoneParams, h as MiniLoginParams, i as MiniProgramLoginParams, k as MiniProgramPhoneParams, l as MiniProgramPhoneResponse, j as MiniProgramPlatform, O as OAuthBinding, m as OAuthLoginTicketResponse, n as OAuthProvider, P as Permission, o as PermissionDetail, R as RefreshTokenResponse, p as RegisterParams, q as RegisterResponse, r as RevokeAllSessionsResponse, s as Role, t as RoleDetail, S as SendCodeParams, u as SendCodeType, v as Session, w as SuccessResponse, U as UpdateMeParams, x as User } from './types-V9dnGh8N.js';
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Main Authentication Client
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {setMiniProgramRuntime,createHttpClient,getMiniProgramLogin,detectMiniProgramPlatform}from'@amaster.ai/http-client';var L=class{constructor(){this.events={};}on(t,r){this.events[t]||(this.events[t]=[]),this.events[t].push(r);}off(t,r){this.events[t]&&(this.events[t]=this.events[t].filter(n=>n!==r));}emit(t,...r){this.events[t]&&this.events[t].forEach(n=>{try{n(...r);}catch(i){console.error(`[AuthClient] Error in event handler for "${t}":`,i);}});}removeAllListeners(){this.events={};}};var f={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function ce(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;try{return Function("return this")()}catch{return}}function F(e){return ce()?.[e]}function de(){let e=F("wx"),t=F("tt");return e?.getStorageSync&&e?.setStorageSync&&e?.removeStorageSync?"wechat-miniprogram":t?.getStorageSync&&t?.setStorageSync&&t?.removeStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function K(){switch(de()){case "wechat-miniprogram":return $(F("wx"),"WeChat");case "douyin-miniprogram":return $(F("tt"),"Douyin");case "browser":return he();case "node":return ge()}}function he(){let e=window.localStorage;return {getItem(t){try{return e.getItem(t)}catch(r){return console.error("[AuthClient] Failed to get item from localStorage:",r),null}},setItem(t,r){try{e.setItem(t,r);}catch(n){console.error("[AuthClient] Failed to set item in localStorage:",n);}},removeItem(t){try{e.removeItem(t);}catch(r){console.error("[AuthClient] Failed to remove item from localStorage:",r);}},clear(){try{e.removeItem(f.ACCESS_TOKEN),e.removeItem(f.REFRESH_TOKEN),e.removeItem(f.USER);}catch(t){console.error("[AuthClient] Failed to clear localStorage:",t);}}}}function $(e,t){return {getItem(r){try{return e.getStorageSync(r)||null}catch(n){return console.error(`[AuthClient] Failed to get item from ${t} storage:`,n),null}},setItem(r,n){try{e.setStorageSync(r,n);}catch(i){console.error(`[AuthClient] Failed to set item in ${t} storage:`,i);}},removeItem(r){try{e.removeStorageSync(r);}catch(n){console.error(`[AuthClient] Failed to remove item from ${t} storage:`,n);}},clear(){try{e.removeStorageSync(f.ACCESS_TOKEN),e.removeStorageSync(f.REFRESH_TOKEN),e.removeStorageSync(f.USER);}catch(r){console.error(`[AuthClient] Failed to clear ${t} storage:`,r);}}}}function ge(){let e=new Map;return {getItem(t){return e.get(t)??null},setItem(t,r){e.set(t,r);},removeItem(t){e.delete(t);},clear(){e.clear();}}}function me(e){try{let t=e.split(".");if(t.length!==3)return null;let n=(t[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let i=decodeURIComponent(atob(n).split("").map(d=>"%"+("00"+d.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}if(typeof Buffer<"u"){let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}return null}catch(t){return console.error("[AuthClient] Failed to parse JWT token:",t),null}}var _=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(t){this.refreshCallback=t;}scheduleRefresh(t){this.clearSchedule(),!(t<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},t));}scheduleRefreshFromToken(t,r=300){let n=me(t);if(!n||!n.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let i=n.exp*1e3,d=Date.now(),m=i-d-r*1e3;m<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(m);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(t){console.error("[AuthClient] Token refresh failed:",t);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function D(e){return e&&typeof e=="object"&&("statusCode"in e||"status"in e)&&"data"in e?e.data:e}var U={transformResponse:D,logErrors:true};var fe="https://lf-scm-cn.feishucdn.com/lark/op/h5-js-sdk-1.5.44.js",N="amaster-feishu-h5-sdk";var B=null,E=null,M=null;function z(){if(!(typeof window>"u"))return window}function W(){return z()?.tt}function H(){return z()?.h5sdk}function j(){typeof window>"u"||B===window||(B=window,E=null,M=null);}function J(){if(typeof navigator>"u")return false;let e=W();return /Feishu|Lark/i.test(navigator.userAgent||"")||typeof e?.requestAccess=="function"||typeof e?.requestAuthCode=="function"}function pe(){return j(),typeof document>"u"?Promise.reject(new Error("Feishu H5 SDK is only available in a browser environment")):typeof H()?.ready=="function"?Promise.resolve():E||(E=new Promise((e,t)=>{let r=document.getElementById(N),n=!r;r||(r=document.createElement("script"),r.id=N,r.src=fe,r.async=true);let i=false,d,c,m=()=>{d&&clearInterval(d),c&&clearTimeout(c),r?.removeEventListener("load",g),r?.removeEventListener("error",A);},S=p=>{if(!i){if(i=true,m(),p){r?.remove(),t(p);return}e();}},y=()=>typeof H()?.ready=="function"?(S(),true):false,g=()=>{y();},A=()=>{S(new Error("Failed to load Feishu H5 SDK"));};r.addEventListener("load",g),r.addEventListener("error",A),d=setInterval(y,25),c=setTimeout(()=>{S(new Error("Timed out while loading Feishu H5 SDK"));},1e4),!y()&&n&&document.head.appendChild(r);}).catch(e=>{throw E=null,e}),E)}function ye(){return j(),M||(M=(async()=>{await pe();let e=H();if(typeof e?.ready!="function")throw new Error("Feishu H5 SDK loaded without exposing h5sdk.ready");return new Promise((t,r)=>{let n=false,i,d=(c,m)=>{n||(n=true,i&&clearTimeout(i),m?r(m):c?t(c):r(new Error("Feishu H5 SDK became ready without exposing the tt bridge")));};i=setTimeout(()=>{d(void 0,new Error("Timed out while waiting for Feishu H5 SDK ready"));},1e4),e.error?.(c=>d(void 0,new Error(x(c))));try{let c=e.ready?.(()=>d(W()));c&&typeof c.then=="function"&&c.catch(m=>{d(void 0,new Error(`Feishu H5 SDK ready failed: ${m instanceof Error?m.message:String(m)}`));});}catch(c){d(void 0,new Error(`Feishu H5 SDK ready failed: ${c instanceof Error?c.message:String(c)}`));}})})().catch(e=>{throw M=null,e}),M)}function x(e){return e.errString||e.message||`Feishu authorization failed${e.errno?` (${e.errno})`:""}`}function G(e,t){return typeof e.requestAuthCode!="function"?Promise.reject(new Error("The current Feishu client does not support requestAuthCode")):new Promise((r,n)=>{e.requestAuthCode?.({appId:t,success:i=>{i.code?r(i.code):n(new Error("Feishu requestAuthCode returned no code"));},fail:i=>n(new Error(x(i)))});})}async function Y(e){let t=await ye();return typeof t.requestAccess!="function"?G(t,e):new Promise((r,n)=>{t.requestAccess?.({appID:e,scopeList:[],success:i=>{i.code?r(i.code):n(new Error("Feishu requestAccess returned no code"));},fail:i=>{if(i.errno===103){G(t,e).then(r,n);return}n(new Error(x(i)));}});})}function Re(e){if(e.email)return "email";if(e.username)return "username";if(e.phone)return "phone"}function Ce(e){if(e.email)return "email";if(e.phone)return "phone"}function O(e){return e||(detectMiniProgramPlatform()??"wechat")}function q(e){return typeof e=="string"?{code:e,platform:O()}:{code:e.code,platform:O(e.platform)}}function V(e,t){return t==="douyin"?`/api/auth/miniprogram/douyin/${e}`:`/api/auth/miniprogram/${e}`}async function we(e){let t=O(e),r=getMiniProgramLogin(t),n=async i=>await new Promise((d,c)=>{let m=false,S=g=>{if(!m){if(m=true,typeof g?.code=="string"&&g.code){d(g.code);return}c(new Error("Mini Program login failed: missing code"));}},y=g=>{m||(m=true,c(new Error(`Mini Program login failed: ${g instanceof Error?g.message:String(g)}`)));};try{let g=i({success:S,fail:y});if(g&&typeof g.then=="function"){g.then(S,y);return}g&&typeof g=="object"&&"code"in g&&S(g);}catch(g){y(g);}});if(typeof r!="function")throw new Error(`Mini Program login API is not available for platform '${t}'`);return {code:await n(r),platform:t}}function ve(e){if(typeof e=="string")return q(e);let t="detail"in e&&e.detail&&typeof e.detail=="object"?e.detail:null,r=typeof t?.code=="string"&&t.code?t.code:typeof e.code=="string"&&e.code?e.code:void 0;return r?{code:r,platform:O(e.platform)}:null}function Ae(e){let t=new URLSearchParams(e);return t.get("access_token")||t.get("accessToken")}function ke(e){return new URLSearchParams(e).get("user")}function Q(e){if(typeof window>"u")return null;try{let t=e||new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let r=new URL(t,window.location.origin);return r.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${r.pathname}${r.search}${r.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var X={assign(e){window.location.assign(e);},replace(e){window.location.replace(e);}};function k(e,t){return t.handled?{...e,redirectHandled:true,redirectTarget:t.target}:e}function T(e,t){if(!e||typeof window>"u"||window.opener)return {handled:false};let r=Q(t);return r?(X.replace(r),{handled:true,target:r}):{handled:false}}function Z(e){let{http:t,onLoginSuccess:r,onLogout:n,autoRedirectAfterLogin:i,storage:d,clearAuth:c,onRefreshFailure:m}=e,S=new Map,y=null,g=o=>{let s=o.trim(),a=S.get(s);if(a)return a;let u=(async()=>{if(!s)return {data:null,error:{message:"OAuth login ticket is required",status:400},status:400};let h=await t.request({url:"/api/auth/oauth/ticket",method:"post",headers:{"Content-Type":"application/json"},data:{ticket:s}});if(!h.data?.accessToken)return {data:null,error:h.error||{message:"OAuth login ticket is invalid, expired, or already used",status:h.status||400},status:h.status||400};let v=d.getItem(f.ACCESS_TOKEN),C=h.data.accessToken;d.setItem(f.ACCESS_TOKEN,C);let w=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${C}`}});if(!w.data)return v?d.setItem(f.ACCESS_TOKEN,v):d.removeItem(f.ACCESS_TOKEN),{data:null,error:w.error||{message:"OAuth login succeeded but user information could not be loaded",status:w.status||500},status:w.status||500};r(w.data,C);let P=T(i,h.data.returnUrl);return {data:k({user:w.data,accessToken:C},P),error:null,status:200}})();return S.set(s,u),u},A=o=>{if(typeof window>"u")return;let s=Q(o)||"/",a=new URLSearchParams({return_url:s,callback_url:"/auth/callback"});X.assign(`/api/auth/oauth/feishu?${a.toString()}`);},p=async(o,s)=>{let a=await t.request({url:"/api/auth/oauth/feishu/code",method:"post",headers:{"Content-Type":"application/json"},data:{code:o}});if(a.data?.user&&a.data?.accessToken){r(a.data.user,a.data.accessToken);let u=T(i,s);a.data=k(a.data,u);}return a};return {async register(o){let s=await t.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:o});if(s.data?.user&&s.data?.accessToken){r(s.data.user,s.data.accessToken);let a=T(i);s.data=k(s.data,a);}return s},async login(o){let s=o.loginType||Re(o);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let a={...o,loginType:s},u=await t.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async loginWithCode(o){let s=o.loginType||Ce(o);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let a={...o,loginType:s},u=await t.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async sendCode(o){return t.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:o})},async getCaptcha(){return t.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(o,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}if(o==="feishu"){A(s);return}let a=s?`/api/auth/oauth/${o}?redirect_url=${encodeURIComponent(s)}`:`/api/auth/oauth/${o}`;window.location.href=a;},async loginWithFeishu(o){if(typeof window>"u")return {data:null,error:{message:"Feishu login is only available in a browser environment",status:400},status:400};if(!J())return A(o),null;let s=await t.request({url:"/api/auth/oauth/feishu/config",method:"get"});if(!s.data?.enabled||!s.data.appId)return {data:null,error:s.error||{message:"Feishu login is not configured for this application",status:s.status||400},status:s.status||400};try{let a=await Y(s.data.appId);return await p(a,o)}catch(a){return {data:null,error:{message:a instanceof Error?a.message:String(a),status:400},status:400}}},async loginWithFeishuCode(o,s){return p(o,s)},async exchangeOAuthLoginTicket(o){return g(o)},handleOAuthCallback(){return y||(y=(async()=>{if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let o=new URLSearchParams(window.location.search),s=o.get("oauth_error");if(s)return {data:null,error:{message:o.get("error_description")||`OAuth callback failed: ${s}`,status:400},status:400};let a=o.get("login_ticket");if(a){o.delete("login_ticket");let P=o.toString();return window.history.replaceState(null,"",`${window.location.pathname}${P?`?${P}`:""}${window.location.hash}`),g(a)}let u=window.location.hash.substring(1),h=Ae(u),v=ke(u);if(!h)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let C;if(v)C=JSON.parse(decodeURIComponent(v));else {d.setItem(f.ACCESS_TOKEN,h);let P=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${h}`}});if(!P.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:P.status||500},status:P.status||500};C=P.data;}if(r(C,h),window.history&&window.history.replaceState){let P=window.location.pathname+window.location.search;window.history.replaceState(null,"",P);}else window.location.hash="";let w=T(i);return {data:k({user:C,accessToken:h},w),error:null,status:200}}catch(o){return {data:null,error:{message:`OAuth callback failed: ${o instanceof Error?o.message:String(o)}`,status:400},status:400}}})(),y)},async loginWithMiniProgram(o){let{code:s,platform:a}=q(o),u=await t.request({url:V("login",a),method:"post",headers:{"Content-Type":"application/json"},data:{code:s}});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async miniLogin(o={}){try{let s=await we(o.platform);return await this.loginWithMiniProgram(s)}catch(s){return {data:null,error:{message:s instanceof Error?s.message:String(s),status:400},status:400}}},async getMiniProgramPhoneNumber(o){let{code:s,platform:a}=q(o),u=d.getItem(f.ACCESS_TOKEN);return u?t.request({url:V("phone",a),method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},data:{code:s}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async miniGetPhone(o){let s=ve(o);return s?this.getMiniProgramPhoneNumber(s):{data:null,error:{message:"Unable to resolve mini-program phone code from input",status:400},status:400}},async logout(){let o=d.getItem("amaster_access_token"),s=await t.request({url:"/api/auth/logout",method:"post",headers:o?{Authorization:`Bearer ${o}`}:void 0});return c(),n(),s},async refreshToken(){let o=await t.request({url:"/api/auth/refresh",method:"post"});return o.data?.accessToken?d.setItem("amaster_access_token",o.data.accessToken):(o.status===401||o.status===403)&&m?.(o),o}}}function ee(e){let{getCurrentUser:t}=e;return {hasRole(r){let n=t();return n?.isSuperAdmin?true:!n||!n.roles?false:n.roles.includes(r)},hasPermission(r,n){let i=t();if(i?.isSuperAdmin)return true;if(!i||!i.permissions)return false;let d=`${r}.${n}`;return i.permissions.includes(d)},hasAnyPermission(r){return r.some(({resource:n,action:i})=>this.hasPermission(n,i))},hasAllPermissions(r){return r.every(({resource:n,action:i})=>this.hasPermission(n,i))}}}function te(e){let{http:t,storage:r,onUserUpdate:n,onAuthFailure:i}=e;return {async getMe(){let d=r.getItem("amaster_access_token");if(!d)return {data:null,error:{message:"Not authenticated",status:401},status:401};let c=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${d}`}});return c.data?n(c.data):(c.status===401||c.status===403)&&i?.(c),c},async updateMe(d){let c=r.getItem("amaster_access_token");if(!c)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await t.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:d});return m.data&&n(m.data),m},async changePassword(d){let c=r.getItem("amaster_access_token");return c?t.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:d}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function re(e){let{http:t,storage:r}=e;return {async getOAuthBindings(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(n){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${n}/bind`;},async unbindOAuth(n){let i=r.getItem("amaster_access_token");return i?t.request({url:`/api/auth/oauth/${n}/unbind`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function ne(e){let{http:t,storage:r}=e;return {async getSession(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(n){let i=r.getItem("amaster_access_token");return i?n?t.request({url:`/api/auth/sessions/${n}`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Me(e={},t){let{baseURL:r,headers:n,onTokenExpired:i,onUnauthorized:d,autoHandleOAuthCallback:c=true,autoRedirectAfterLogin:m=true,runtime:S}=e;S&&setMiniProgramRuntime(S);let y=t||createHttpClient({...U,baseURL:r,headers:n,runtime:S}),A=300,p=K(),o=new L,s=new _,a=null,u=false;try{let l=p.getItem(f.USER);l&&(a=JSON.parse(l));}catch(l){console.error("[AuthClient] Failed to load user from storage:",l);}let h;function v(l,R){u||(u=true,I(),l==="tokenExpired"&&(o.emit("tokenExpired",R?.error),i?.()),o.emit("unauthorized",R?.error),o.emit("logout"));}s.setRefreshCallback(async()=>{let l=await h.refreshToken();if(l.data){if((await h.getMe()).error)return;o.emit("tokenRefreshed",l.data.accessToken);}else v("tokenExpired",l);});function C(l,R){u=false,p.setItem(f.ACCESS_TOKEN,R),p.setItem(f.USER,JSON.stringify(l)),a=l,s.scheduleRefreshFromToken(R,A),o.emit("login",l);}function w(l){a=l,p.setItem(f.USER,JSON.stringify(l));}function P(){o.emit("logout");}function I(){p.clear(),a=null,s.clearSchedule();}function oe(){return a}let se=Z({http:y,onLoginSuccess:C,onLogout:P,autoRedirectAfterLogin:m,storage:p,clearAuth:I,onRefreshFailure:l=>v("tokenExpired",l)}),ie=ee({getCurrentUser:oe}),ae=te({http:y,storage:p,onUserUpdate:w,onAuthFailure:l=>v("unauthorized",l)}),ue=re({http:y,storage:p}),le=ne({http:y,storage:p});if(h={...se,...ie,...ae,...ue,...le,on(l,R){o.on(l,R);},off(l,R){o.off(l,R);},isAuthenticated(){return !!p.getItem(f.ACCESS_TOKEN)},getAccessToken(){return p.getItem(f.ACCESS_TOKEN)},setAccessToken(l){u=false,p.setItem(f.ACCESS_TOKEN,l),s.scheduleRefreshFromToken(l,A);},clearAuth:I},h.on("unauthorized",()=>{d?.();}),h.isAuthenticated()&&h.getMe().then(l=>{l.error&&console.warn("[AuthClient] Failed to sync user info on init:",l.error);}).catch(l=>{console.warn("[AuthClient] Failed to sync user info on init:",l);}),c&&typeof window<"u"){let l=window.location.hash,R=new URLSearchParams(window.location.search);(R.has("login_ticket")||R.has("oauth_error")||l&&(l.includes("access_token")||l.includes("accessToken")))&&h.handleOAuthCallback().then(b=>{b.error&&console.error("[AuthClient] Auto OAuth callback failed:",b.error);}).catch(b=>{console.error("[AuthClient] Auto OAuth callback error:",b);});}return h}
|
|
2
|
-
export{Me as createAuthClient,U as defaultHttpClientOptions,
|
|
1
|
+
import {setMiniProgramRuntime,createHttpClient,getMiniProgramLogin,detectMiniProgramPlatform}from'@amaster.ai/http-client';var L=class{constructor(){this.events={};}on(t,r){this.events[t]||(this.events[t]=[]),this.events[t].push(r);}off(t,r){this.events[t]&&(this.events[t]=this.events[t].filter(n=>n!==r));}emit(t,...r){this.events[t]&&this.events[t].forEach(n=>{try{n(...r);}catch(i){console.error(`[AuthClient] Error in event handler for "${t}":`,i);}});}removeAllListeners(){this.events={};}};var f={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function ce(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;try{return Function("return this")()}catch{return}}function _(e){return ce()?.[e]}function de(){let e=_("wx"),t=_("tt");return e?.getStorageSync&&e?.setStorageSync&&e?.removeStorageSync?"wechat-miniprogram":t?.getStorageSync&&t?.setStorageSync&&t?.removeStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function D(){switch(de()){case "wechat-miniprogram":return K(_("wx"),"WeChat");case "douyin-miniprogram":return K(_("tt"),"Douyin");case "browser":return he();case "node":return ge()}}function he(){let e=window.localStorage;return {getItem(t){try{return e.getItem(t)}catch(r){return console.error("[AuthClient] Failed to get item from localStorage:",r),null}},setItem(t,r){try{e.setItem(t,r);}catch(n){console.error("[AuthClient] Failed to set item in localStorage:",n);}},removeItem(t){try{e.removeItem(t);}catch(r){console.error("[AuthClient] Failed to remove item from localStorage:",r);}},clear(){try{e.removeItem(f.ACCESS_TOKEN),e.removeItem(f.REFRESH_TOKEN),e.removeItem(f.USER);}catch(t){console.error("[AuthClient] Failed to clear localStorage:",t);}}}}function K(e,t){return {getItem(r){try{return e.getStorageSync(r)||null}catch(n){return console.error(`[AuthClient] Failed to get item from ${t} storage:`,n),null}},setItem(r,n){try{e.setStorageSync(r,n);}catch(i){console.error(`[AuthClient] Failed to set item in ${t} storage:`,i);}},removeItem(r){try{e.removeStorageSync(r);}catch(n){console.error(`[AuthClient] Failed to remove item from ${t} storage:`,n);}},clear(){try{e.removeStorageSync(f.ACCESS_TOKEN),e.removeStorageSync(f.REFRESH_TOKEN),e.removeStorageSync(f.USER);}catch(r){console.error(`[AuthClient] Failed to clear ${t} storage:`,r);}}}}function ge(){let e=new Map;return {getItem(t){return e.get(t)??null},setItem(t,r){e.set(t,r);},removeItem(t){e.delete(t);},clear(){e.clear();}}}function me(e){try{let t=e.split(".");if(t.length!==3)return null;let n=(t[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let i=decodeURIComponent(atob(n).split("").map(d=>"%"+("00"+d.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}if(typeof Buffer<"u"){let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}return null}catch(t){return console.error("[AuthClient] Failed to parse JWT token:",t),null}}var F=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(t){this.refreshCallback=t;}scheduleRefresh(t){this.clearSchedule(),!(t<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},t));}scheduleRefreshFromToken(t,r=300){let n=me(t);if(!n||!n.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let i=n.exp*1e3,d=Date.now(),m=i-d-r*1e3;m<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(m);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(t){console.error("[AuthClient] Token refresh failed:",t);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function N(e){return e&&typeof e=="object"&&("statusCode"in e||"status"in e)&&"data"in e?e.data:e}var U={transformResponse:N,logErrors:true};var fe="https://lf-scm-cn.feishucdn.com/lark/op/h5-js-sdk-1.5.44.js",B="amaster-feishu-h5-sdk";var G=null,E=null,M=null;function W(){if(!(typeof window>"u"))return window}function j(){return W()?.tt}function H(){return W()?.h5sdk}function J(){typeof window>"u"||G===window||(G=window,E=null,M=null);}function Y(){if(typeof navigator>"u")return false;let e=j();return /Feishu|Lark/i.test(navigator.userAgent||"")||typeof e?.requestAccess=="function"||typeof e?.requestAuthCode=="function"}function pe(){return J(),typeof document>"u"?Promise.reject(new Error("Feishu H5 SDK is only available in a browser environment")):typeof H()?.ready=="function"?Promise.resolve():E||(E=new Promise((e,t)=>{let r=document.getElementById(B),n=!r;r||(r=document.createElement("script"),r.id=B,r.src=fe,r.async=true);let i=false,d,c,m=()=>{d&&clearInterval(d),c&&clearTimeout(c),r?.removeEventListener("load",g),r?.removeEventListener("error",A);},P=p=>{if(!i){if(i=true,m(),p){r?.remove(),t(p);return}e();}},y=()=>typeof H()?.ready=="function"?(P(),true):false,g=()=>{y();},A=()=>{P(new Error("Failed to load Feishu H5 SDK"));};r.addEventListener("load",g),r.addEventListener("error",A),d=setInterval(y,25),c=setTimeout(()=>{P(new Error("Timed out while loading Feishu H5 SDK"));},1e4),!y()&&n&&document.head.appendChild(r);}).catch(e=>{throw E=null,e}),E)}function ye(){return J(),M||(M=(async()=>{await pe();let e=H();if(typeof e?.ready!="function")throw new Error("Feishu H5 SDK loaded without exposing h5sdk.ready");return new Promise((t,r)=>{let n=false,i,d=(c,m)=>{n||(n=true,i&&clearTimeout(i),m?r(m):c?t(c):r(new Error("Feishu H5 SDK became ready without exposing the tt bridge")));};i=setTimeout(()=>{d(void 0,new Error("Timed out while waiting for Feishu H5 SDK ready"));},1e4),e.error?.(c=>d(void 0,new Error(x(c))));try{let c=e.ready?.(()=>d(j()));c&&typeof c.then=="function"&&c.catch(m=>{d(void 0,new Error(`Feishu H5 SDK ready failed: ${m instanceof Error?m.message:String(m)}`));});}catch(c){d(void 0,new Error(`Feishu H5 SDK ready failed: ${c instanceof Error?c.message:String(c)}`));}})})().catch(e=>{throw M=null,e}),M)}function x(e){return e.errString||e.message||`Feishu authorization failed${e.errno?` (${e.errno})`:""}`}function z(e,t){return typeof e.requestAuthCode!="function"?Promise.reject(new Error("The current Feishu client does not support requestAuthCode")):new Promise((r,n)=>{e.requestAuthCode?.({appId:t,success:i=>{i.code?r(i.code):n(new Error("Feishu requestAuthCode returned no code"));},fail:i=>n(new Error(x(i)))});})}async function Q(e){let t=await ye();return typeof t.requestAccess!="function"?z(t,e):new Promise((r,n)=>{t.requestAccess?.({appID:e,scopeList:[],success:i=>{i.code?r(i.code):n(new Error("Feishu requestAccess returned no code"));},fail:i=>{if(i.errno===103){z(t,e).then(r,n);return}n(new Error(x(i)));}});})}function Re(e){if(e.email)return "email";if(e.username)return "username";if(e.phone)return "phone"}function we(e){if(e.email)return "email";if(e.phone)return "phone"}function O(e){return e||(detectMiniProgramPlatform()??"wechat")}function q(e){return typeof e=="string"?{code:e,platform:O()}:{code:e.code,platform:O(e.platform)}}function V(e,t){return t==="douyin"?`/api/auth/miniprogram/douyin/${e}`:`/api/auth/miniprogram/${e}`}async function Ce(e){let t=O(e),r=getMiniProgramLogin(t),n=async i=>await new Promise((d,c)=>{let m=false,P=g=>{if(!m){if(m=true,typeof g?.code=="string"&&g.code){d(g.code);return}c(new Error("Mini Program login failed: missing code"));}},y=g=>{m||(m=true,c(new Error(`Mini Program login failed: ${g instanceof Error?g.message:String(g)}`)));};try{let g=i({success:P,fail:y});if(g&&typeof g.then=="function"){g.then(P,y);return}g&&typeof g=="object"&&"code"in g&&P(g);}catch(g){y(g);}});if(typeof r!="function")throw new Error(`Mini Program login API is not available for platform '${t}'`);return {code:await n(r),platform:t}}function ve(e){if(typeof e=="string")return q(e);let t="detail"in e&&e.detail&&typeof e.detail=="object"?e.detail:null,r=typeof t?.code=="string"&&t.code?t.code:typeof e.code=="string"&&e.code?e.code:void 0;return r?{code:r,platform:O(e.platform)}:null}function Ae(e){let t=new URLSearchParams(e);return t.get("access_token")||t.get("accessToken")}function ke(e){return new URLSearchParams(e).get("user")}function X(e){if(typeof window>"u")return null;try{let t=e||new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let r=new URL(t,window.location.origin);return r.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${r.pathname}${r.search}${r.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var $={assign(e){window.location.assign(e);},replace(e){window.location.replace(e);}};function k(e,t){return t.handled?{...e,redirectHandled:true,redirectTarget:t.target}:e}function T(e,t){if(!e||typeof window>"u"||window.opener)return {handled:false};let r=X(t);return r?($.replace(r),{handled:true,target:r}):{handled:false}}function Z(e){let{http:t,onLoginSuccess:r,onLogout:n,autoRedirectAfterLogin:i,storage:d,clearAuth:c,onRefreshFailure:m}=e,P=new Map,y=null,g=o=>{let s=o.trim(),a=P.get(s);if(a)return a;let u=(async()=>{if(!s)return {data:null,error:{message:"OAuth login ticket is required",status:400},status:400};let h=await t.request({url:"/api/auth/oauth/ticket",method:"post",headers:{"Content-Type":"application/json"},data:{ticket:s}});if(!h.data?.accessToken)return {data:null,error:h.error||{message:"OAuth login ticket is invalid, expired, or already used",status:h.status||400},status:h.status||400};let w=d.getItem(f.ACCESS_TOKEN),R=h.data.accessToken;d.setItem(f.ACCESS_TOKEN,R);let S=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${R}`}});if(!S.data)return w?d.setItem(f.ACCESS_TOKEN,w):d.removeItem(f.ACCESS_TOKEN),{data:null,error:S.error||{message:"OAuth login succeeded but user information could not be loaded",status:S.status||500},status:S.status||500};r(S.data,R);let C=T(i,h.data.returnUrl);return {data:k({user:S.data,accessToken:R},C),error:null,status:200}})();return P.set(s,u),u},A=o=>{if(typeof window>"u")return;let s=X(o)||"/",a=new URLSearchParams({return_url:s,callback_url:"/auth/callback"});$.assign(`/api/auth/oauth/feishu?${a.toString()}`);},p=async(o,s)=>{let a=await t.request({url:"/api/auth/oauth/feishu/code",method:"post",headers:{"Content-Type":"application/json"},data:{code:o}});if(a.data?.user&&a.data?.accessToken){r(a.data.user,a.data.accessToken);let u=T(i,s);a.data=k(a.data,u);}return a};return {async register(o){let s=await t.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:o});if(s.data?.user&&s.data?.accessToken){r(s.data.user,s.data.accessToken);let a=T(i);s.data=k(s.data,a);}return s},async login(o){let s=o.loginType||Re(o);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let a={...o,loginType:s},u=await t.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async loginWithCode(o){let s=o.loginType||we(o);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let a={...o,loginType:s},u=await t.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async sendCode(o){return t.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:o})},async getCaptcha(){return t.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(o,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}if(o==="feishu"){A(s);return}let a=new URLSearchParams;if(s&&a.set("redirect_uri",s),o==="wecom"){if(s){let S=new URL(s,window.location.origin);S.origin===window.location.origin&&(S.searchParams.delete("oauth_error"),S.searchParams.delete("error_description"),a.set("redirect_uri",S.pathname+S.search+S.hash));}let w=new URLSearchParams(window.location.search);w.delete("oauth_error"),w.delete("error_description");let R=w.toString();a.set("error_redirect_uri",`${window.location.pathname}${R?`?${R}`:""}`);}let u=a.toString(),h=`/api/auth/oauth/${o}${u?`?${u}`:""}`;$.assign(h);},async loginWithFeishu(o){if(typeof window>"u")return {data:null,error:{message:"Feishu login is only available in a browser environment",status:400},status:400};if(!Y())return A(o),null;let s=await t.request({url:"/api/auth/oauth/feishu/config",method:"get"});if(!s.data?.enabled||!s.data.appId)return {data:null,error:s.error||{message:"Feishu login is not configured for this application",status:s.status||400},status:s.status||400};try{let a=await Q(s.data.appId);return await p(a,o)}catch(a){return {data:null,error:{message:a instanceof Error?a.message:String(a),status:400},status:400}}},async loginWithFeishuCode(o,s){return p(o,s)},async exchangeOAuthLoginTicket(o){return g(o)},handleOAuthCallback(){return y||(y=(async()=>{if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let o=new URLSearchParams(window.location.search),s=o.get("oauth_error");if(s)return {data:null,error:{message:o.get("error_description")||`OAuth callback failed: ${s}`,status:400},status:400};let a=o.get("login_ticket");if(a){o.delete("login_ticket");let C=o.toString();return window.history.replaceState(null,"",`${window.location.pathname}${C?`?${C}`:""}${window.location.hash}`),g(a)}let u=window.location.hash.substring(1),h=Ae(u),w=ke(u);if(!h)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let R;if(w)R=JSON.parse(decodeURIComponent(w));else {d.setItem(f.ACCESS_TOKEN,h);let C=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${h}`}});if(!C.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:C.status||500},status:C.status||500};R=C.data;}if(r(R,h),window.history&&window.history.replaceState){let C=window.location.pathname+window.location.search;window.history.replaceState(null,"",C);}else window.location.hash="";let S=T(i);return {data:k({user:R,accessToken:h},S),error:null,status:200}}catch(o){return {data:null,error:{message:`OAuth callback failed: ${o instanceof Error?o.message:String(o)}`,status:400},status:400}}})(),y)},async loginWithMiniProgram(o){let{code:s,platform:a}=q(o),u=await t.request({url:V("login",a),method:"post",headers:{"Content-Type":"application/json"},data:{code:s}});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async miniLogin(o={}){try{let s=await Ce(o.platform);return await this.loginWithMiniProgram(s)}catch(s){return {data:null,error:{message:s instanceof Error?s.message:String(s),status:400},status:400}}},async getMiniProgramPhoneNumber(o){let{code:s,platform:a}=q(o),u=d.getItem(f.ACCESS_TOKEN);return u?t.request({url:V("phone",a),method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},data:{code:s}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async miniGetPhone(o){let s=ve(o);return s?this.getMiniProgramPhoneNumber(s):{data:null,error:{message:"Unable to resolve mini-program phone code from input",status:400},status:400}},async logout(){let o=d.getItem("amaster_access_token"),s=await t.request({url:"/api/auth/logout",method:"post",headers:o?{Authorization:`Bearer ${o}`}:void 0});return c(),n(),s},async refreshToken(){let o=await t.request({url:"/api/auth/refresh",method:"post"});return o.data?.accessToken?d.setItem("amaster_access_token",o.data.accessToken):(o.status===401||o.status===403)&&m?.(o),o}}}function ee(e){let{getCurrentUser:t}=e;return {hasRole(r){let n=t();return n?.isSuperAdmin?true:!n||!n.roles?false:n.roles.includes(r)},hasPermission(r,n){let i=t();if(i?.isSuperAdmin)return true;if(!i||!i.permissions)return false;let d=`${r}.${n}`;return i.permissions.includes(d)},hasAnyPermission(r){return r.some(({resource:n,action:i})=>this.hasPermission(n,i))},hasAllPermissions(r){return r.every(({resource:n,action:i})=>this.hasPermission(n,i))}}}function te(e){let{http:t,storage:r,onUserUpdate:n,onAuthFailure:i}=e;return {async getMe(){let d=r.getItem("amaster_access_token");if(!d)return {data:null,error:{message:"Not authenticated",status:401},status:401};let c=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${d}`}});return c.data?n(c.data):(c.status===401||c.status===403)&&i?.(c),c},async updateMe(d){let c=r.getItem("amaster_access_token");if(!c)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await t.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:d});return m.data&&n(m.data),m},async changePassword(d){let c=r.getItem("amaster_access_token");return c?t.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:d}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function re(e){let{http:t,storage:r}=e;return {async getOAuthBindings(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(n){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${n}/bind`;},async unbindOAuth(n){let i=r.getItem("amaster_access_token");return i?t.request({url:`/api/auth/oauth/${n}/unbind`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function ne(e){let{http:t,storage:r}=e;return {async getSession(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(n){let i=r.getItem("amaster_access_token");return i?n?t.request({url:`/api/auth/sessions/${n}`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Me(e={},t){let{baseURL:r,headers:n,onTokenExpired:i,onUnauthorized:d,autoHandleOAuthCallback:c=true,autoRedirectAfterLogin:m=true,runtime:P}=e;P&&setMiniProgramRuntime(P);let y=t||createHttpClient({...U,baseURL:r,headers:n,runtime:P}),A=300,p=D(),o=new L,s=new F,a=null,u=false;try{let l=p.getItem(f.USER);l&&(a=JSON.parse(l));}catch(l){console.error("[AuthClient] Failed to load user from storage:",l);}let h;function w(l,v){u||(u=true,I(),l==="tokenExpired"&&(o.emit("tokenExpired",v?.error),i?.()),o.emit("unauthorized",v?.error),o.emit("logout"));}s.setRefreshCallback(async()=>{let l=await h.refreshToken();if(l.data){if((await h.getMe()).error)return;o.emit("tokenRefreshed",l.data.accessToken);}else w("tokenExpired",l);});function R(l,v){u=false,p.setItem(f.ACCESS_TOKEN,v),p.setItem(f.USER,JSON.stringify(l)),a=l,s.scheduleRefreshFromToken(v,A),o.emit("login",l);}function S(l){a=l,p.setItem(f.USER,JSON.stringify(l));}function C(){o.emit("logout");}function I(){p.clear(),a=null,s.clearSchedule();}function oe(){return a}let se=Z({http:y,onLoginSuccess:R,onLogout:C,autoRedirectAfterLogin:m,storage:p,clearAuth:I,onRefreshFailure:l=>w("tokenExpired",l)}),ie=ee({getCurrentUser:oe}),ae=te({http:y,storage:p,onUserUpdate:S,onAuthFailure:l=>w("unauthorized",l)}),ue=re({http:y,storage:p}),le=ne({http:y,storage:p});if(h={...se,...ie,...ae,...ue,...le,on(l,v){o.on(l,v);},off(l,v){o.off(l,v);},isAuthenticated(){return !!p.getItem(f.ACCESS_TOKEN)},getAccessToken(){return p.getItem(f.ACCESS_TOKEN)},setAccessToken(l){u=false,p.setItem(f.ACCESS_TOKEN,l),s.scheduleRefreshFromToken(l,A);},clearAuth:I},h.on("unauthorized",()=>{d?.();}),h.isAuthenticated()&&h.getMe().then(l=>{l.error&&console.warn("[AuthClient] Failed to sync user info on init:",l.error);}).catch(l=>{console.warn("[AuthClient] Failed to sync user info on init:",l);}),c&&typeof window<"u"){let l=window.location.hash,v=new URLSearchParams(window.location.search);(v.has("login_ticket")||v.has("oauth_error")||l&&(l.includes("access_token")||l.includes("accessToken")))&&h.handleOAuthCallback().then(b=>{b.error&&console.error("[AuthClient] Auto OAuth callback failed:",b.error);}).catch(b=>{console.error("[AuthClient] Auto OAuth callback error:",b);});}return h}
|
|
2
|
+
export{Me as createAuthClient,U as defaultHttpClientOptions,N as transformAmasterResponse};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|