@dplugin/core 2.0.4 → 2.0.5
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/index.cjs +2 -2
- package/dist/index.mjs +62 -50
- package/dist/index.umd.js +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M={apiBase:"",mode:"auto",loginUrl:"/login/",timeout:15e3,pollInterval:2e3,pollMax:5,enableAuth:!1,onError:null,onLogin:null,onLogout:null,nativeGuard:"warn"};function xe(e){return e&&Object.keys(M).forEach(t=>{e[t]!==void 0&&(M[t]=e[t])}),M}function I(){return M}const
|
|
2
|
-
`)}function $e(e,t,n){return[p(e),p(t.subject),p(t.ds),p(t.ts),n].join(".")}async function A(e,t,n){const o=n==="sso"?await ue():await Se();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await ze(o,Ze(e,t));return $e(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await A(N.BIZ,{method:qe,path:V(e),origin:K(),ds:n,ts:Date.now(),subject:t},"domain");return"dsign="+encodeURIComponent(o)}function K(){if(typeof location=="undefined")return"";if(location.origin)return location.origin.toLowerCase();try{return new URL(location.href).origin.toLowerCase()}catch(e){return""}}function Pe(e){const t=new Error(e);return t.code="KEY_MISSING",t}function Je(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:Qe(e),device_model:et(e),browser_name:tt(e),browser_version:nt(e),os_name:ot(e),os_version:rt(e)},n=i.ds;return n&&(t.device_id=n),t}function T(e,t){const n=e.match(t);return n?n[1]:""}function Qe(e){return/iPhone|iPad|iPod/.test(e)?"Apple":/Huawei|HONOR/i.test(e)?"Huawei":/Xiaomi|Redmi|POCO/i.test(e)?"Xiaomi":/OPPO|realme/i.test(e)?"OPPO":/vivo/i.test(e)?"vivo":/Samsung|SM-|SAMSUNG/i.test(e)?"Samsung":/Macintosh|Mac OS X/.test(e)?"Apple":""}function et(e){if(/iPhone/.test(e))return"iPhone";if(/iPad/.test(e))return"iPad";const t=e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);return t?t[1].trim():/Macintosh/.test(e)?"Mac":""}function tt(e){return/MicroMessenger/i.test(e)?"WeChat":/Edg[A-Za-z]*\//.test(e)?"Edge":/OPR\/|Opera/.test(e)?"Opera":/Firefox\//.test(e)?"Firefox":/Chrome\/|CriOS\//.test(e)?"Chrome":/Safari\//.test(e)?"Safari":""}function nt(e){return/MicroMessenger\/([\d.]+)/.test(e)?T(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?T(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?T(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?T(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?T(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?T(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?T(e,/Version\/([\d.]+)/):""}function ot(e){return/Windows NT/.test(e)?"Windows":/iPhone|iPad|iPod/.test(e)?"iOS":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/HarmonyOS/.test(e)?"HarmonyOS":/Linux/.test(e)?"Linux":""}function rt(e){if(/Windows NT 10\.0/.test(e))return"10/11";if(/Windows NT 6\.3/.test(e))return"8.1";if(/Windows NT 6\.1/.test(e))return"7";const t=e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);if(t)return t[1].replace(/_/g,".");if(/Android[ _]([\d.]+)/.test(e))return T(e,/Android[ _]([\d.]+)/);const n=e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);return n?n[1].replace(/_/g,"."):""}const w={SIGN:{VERIFY:"/api/unsafe/dplugin/login/s/verify",TOKEN:"/api/unsafe/dplugin/login/s/token",REFRESH:"/api/unsafe/dplugin/login/s/refresh"},COOKIE:{VERIFY:"/api/unsafe/dplugin/login/c/verify",TOKEN:"/api/unsafe/dplugin/login/c/token",REFRESH:"/api/unsafe/dplugin/login/c/refresh"},LOGOUT:"/api/safe/dplugin/login/logout"},it="dp_dvt",de=1800*1e3;let _=null,F=null,D=null,j=!1;function W(){return typeof location!="undefined"?location.href:""}function U(e){return new Promise(t=>setTimeout(t,e))}function st(){try{localStorage.setItem("token",i.access||"cookie")}catch(e){}}function z(){st();const e=I();typeof e.onLogin=="function"&&e.onLogin(L())}function P(e,t){return new E(e.code,e.message||t)}function ct(e,t,n){if(typeof document=="undefined")return;let o=e+"="+encodeURIComponent(t)+"; path=/; SameSite=Lax";o+="; max-age="+n,document.cookie=o}function L(){return{mode:ie(),loggedIn:q(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function q(){return b()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function R(e){const t=q();le();const n=I();if(t&&typeof n.onLogout=="function"&&n.onLogout(e||"expired"),j||!n.enableAuth||!n.loginUrl||typeof location=="undefined")return;j=!0;const o=n.loginUrl.includes("?")?"&":"?";location.href=n.loginUrl+o+"referer="+encodeURIComponent(location.href)}function Re(e,t){return D||(D=ut(e,t).then(n=>(D=null,n),n=>{throw D=null,at(n),n}),D)}function at(e){const t=I();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function ut(e,t){const n=I(),o=Je();if(b())return lt(e,t,o,n);const r=await ue(),s=await Se();try{return await ft(e,t,o,n)}catch(u){throw await he(ne.SSO,r),await he(ne.DOMAIN,s),u}}async function ft(e,t,n,o){const r=await Xe(),s=await te(r),u=await h(g(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw P(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw P(u,"登录失败");const f=await We(),d=await Te(f),l=await dt(c,o,d),y=await h(g(w.SIGN.TOKEN),{dsign:await A(N.TOKEN,{origin:K(),ts:Date.now(),subject:l.code,dna:d},"domain"),pk:await te(f)});if(y.code!==a.OK||!y.data)throw P(y,"登录失败");return i.sid=l.sid,i.ds=y.data.ds||l.ds,i.access=y.data.token,i.exp=Date.now()+de,j=!1,z(),L()}async function dt(e,t,n){const o=W(),r=Math.max(1,Number(t.pollMax)||5);for(let s=1;s<=r;s++){const u=i.ds||null,c=Date.now(),f=await A(N.VERIFY,{method:"POST",path:V(w.SIGN.VERIFY),origin:K(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let d;try{d=await h(g(w.SIGN.VERIFY),{dsign:f,dna:n,redirect:o})}catch(l){if((l.code===a.NETWORK||l.code===a.TIMEOUT)&&s<r){await U(t.pollInterval);continue}throw l}if(d.code===a.OK&&d.data)return d.data;if(d.code===a.PENDING){if(s<r){await U(t.pollInterval);continue}break}throw P(d,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function lt(e,t,n,o){const r=await h(g(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw P(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw P(r,"登录失败");return ct(it,s,300),await gt(o),await De(),i.cookie=!0,j=!1,z(),L()}async function gt(e){const t=W(),n=Math.max(1,Number(e.pollMax)||5);for(let o=1;o<=n;o++){let r;try{r=await h(g(w.COOKIE.VERIFY),{redirect:t})}catch(s){if((s.code===a.NETWORK||s.code===a.TIMEOUT)&&o<n){await U(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await U(e.pollInterval);continue}break}throw P(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function De(){const e=await h(g(w.COOKIE.TOKEN));if(e.code!==a.OK)throw P(e,"登录失败");return e}async function x(e){const t=!!(e&&e.force);return F||(F=(async()=>{try{return b()?await wt(t):await pt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{F=null}})()),F}async function wt(e){return!e&&i.cookie?!0:(await h(g(w.COOKIE.VERIFY),{redirect:W()})).code!==a.OK||(await De()).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,z(),!0)}async function ht(){if(!i.sid||!i.ds||!await ue())return!1;const t=i.ds,n=await Ve(ne.DOMAIN),o=await Te(n),r=W(),s=await A(N.VERIFY_SID,{method:"POST",path:V(w.SIGN.VERIFY),origin:K(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await h(g(w.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await h(g(w.SIGN.TOKEN),{dsign:await A(N.TOKEN,{origin:K(),ts:Date.now(),subject:u.data.code,dna:o},"domain"),pk:await te(n)});return c.code!==a.OK||!c.data?!1:(i.access=c.data.token,c.data.ds&&(i.ds=c.data.ds),i.exp=Date.now()+de,z(),!0)}async function pt(e){return!e&&i.access?!0:ht()}function ge(){return _||(_=(b()?Et():mt()).then(e=>(_=null,e),e=>{throw _=null,e})),_}async function Et(){const e=await h(g(w.COOKIE.REFRESH));if(e.code===a.OK)return!0;if(e.code===a.AUTH_EXPIRED)throw new O(e.message);if(e.code==="500"&&/重复/.test(e.message||""))return await U(800),!0;throw new E(e.code,e.message)}async function mt(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await A(N.BIZ,{method:"POST",path:V(w.SIGN.REFRESH),origin:K(),ds:t,ts:Date.now(),subject:e},"domain"),o=await h(g(w.SIGN.REFRESH,"dsign="+encodeURIComponent(n)));if(o.code===a.OK&&o.data)return i.access=o.data.token,o.data.ds&&(i.ds=o.data.ds),i.exp=Date.now()+de,i.access;const r=await Ot(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(o.message):new E(o.code,o.message)}function Ot(e,t){const n=Date.now()+t;return new Promise(o=>{const r=()=>{const s=i.access;if(s&&s!==e){o(s);return}if(Date.now()>=n){o(null);return}setTimeout(r,150)};r()})}async function Ne(){try{let t=await pe();t.code===a.AUTH_EXPIRED&&(await ge(),t=await pe())}catch(t){}le();const e=I();typeof e.onLogout=="function"&&e.onLogout("logout")}async function pe(){if(b())return h(g(w.LOGOUT));const e=await fe(w.LOGOUT,i.access,i.ds);return h(g(w.LOGOUT,e))}async function yt(e,t,n){const o=bt(t,n);return o.authed&&await Ae(),G(e,o.body,o.options,!1)}function bt(e,t){const n=t||{};return!(typeof FormData!="undefined"&&e instanceof FormData)&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&("data"in e||"noToken"in e||"loading"in e||"error"in e)?{body:e.data,options:Object.assign({},e,n),authed:e.noToken!==!0&&n.auth!==!1}:{body:e,options:n,authed:n.auth!==!1}}async function Ae(){if(b()){if(i.cookie||await x())return;throw R("expired"),new O}if(!i.access&&!await x())throw R("expired"),new O}async function G(e,t,n,o){const r=n.auth!==!1&&n.noToken!==!0,s=r&&!b();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(d){if(!o&&await x({force:!0}))return G(e,t,n,!0);throw R("expired"),new O}}const f=await h(g(e,u),t,n.timeout);if(f.code===a.OK)return f;if(r&&f.code===a.AUTH_EXPIRED&&!o){if(s&&c&&i.access!==c)return G(e,t,n,!0);try{await ge()}catch(d){throw d instanceof O&&R("expired"),d}return G(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(R("expired"),new O(f.message)):Ke(f)}function Ke(e){const t=new E(e.code,e.message),n=I();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function St(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ae(),re(e,t,n,o||{},!1)}async function re(e,t,n,o,r){let s="";if(!b())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await x({force:!0}))return re(e,t,n,o,!0);throw R("expired"),new O}const u=new FormData;Object.keys(n||{}).forEach(f=>{const d=n[f];d!=null&&u.append(f,d)}),u.append("file",t);const c=await h(g(e,s),u,o.timeout);if(c.code===a.OK)return c;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof O&&R("expired"),f}return re(e,t,n,o,!0)}throw Ke(c)}function It(e){const t=xe(e);if(Fe(),t.nativeGuard!=="off"){const n=_e();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const Tt={login:Re,logout:Ne,isLogin:q,getState:L,restore:x};exports.AuthError=O;exports.BizError=E;exports.CODE=a;exports.auth=Tt;exports.clear=le;exports.expire=R;exports.getMode=ie;exports.getState=L;exports.isAuthError=Me;exports.isLogin=q;exports.login=Re;exports.logout=Ne;exports.request=yt;exports.setup=It;exports.store=i;exports.upload=St;exports.verifyLogin=x;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M={apiBase:"",mode:"auto",loginUrl:"/login/",timeout:15e3,pollInterval:2e3,pollMax:5,enableAuth:!1,onError:null,onLogin:null,onLogout:null,nativeGuard:"warn"};function xe(e){return e&&Object.keys(M).forEach(t=>{e[t]!==void 0&&(M[t]=e[t])}),M}function I(){return M}const E=ke();function Z(e,t){if(typeof e!="function")return!1;let n;try{n=Function.prototype.toString.call(e)}catch(r){return!1}const o=/^function\s+([\w$]+)\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.exec(n);return o?o[1]===t:/\[native code\]/.test(n)&&!/^function\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.test(n)}function Ce(e){try{const t=e();return t&&typeof t.then=="function"&&Promise.resolve(t).catch(()=>{}),!1}catch(t){const n=String(t&&t.message||"");return!!t&&t.name==="TypeError"&&/argument|required|参数/i.test(n)}}function ke(){const e=globalThis,t=typeof e.window!="undefined"&&e.window&&typeof e.window.document!="undefined",n={fetch:null,idbOpen:null,subtle:null,pristine:{fetch:!1,idbOpen:!1,subtle:!1}};typeof e.fetch=="function"&&(n.pristine.fetch=Z(e.fetch,"fetch"),n.fetch=e.fetch.bind(e)),typeof e.indexedDB!="undefined"&&e.indexedDB&&typeof e.indexedDB.open=="function"&&(n.pristine.idbOpen=Z(e.indexedDB.open,"open")&&(!t||Ce(()=>e.indexedDB.open())),n.idbOpen=e.indexedDB.open.bind(e.indexedDB));const o=e.crypto&&e.crypto.subtle?e.crypto.subtle:null;if(o){const r=["generateKey","exportKey","importKey","sign","verify","digest"],s={};let u=!0;r.forEach(c=>{typeof o[c]=="function"&&(s[c]=o[c].bind(o),u=u&&Z(o[c],c))}),n.subtle=s,n.pristine.subtle=u}return n}function _e(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return E.fetch&&!E.pristine.fetch&&e.push("fetch"),E.idbOpen&&!E.pristine.idbOpen&&e.push("indexedDB.open"),E.subtle&&!E.pristine.subtle&&e.push("crypto.subtle"),e}const a={OK:"200",PENDING:"202",AUTH_EXPIRED:"500900",FORBIDDEN:"401001",CORS_DENIED:"403",API_NOT_FOUND:"404",NETWORK:"NETWORK",TIMEOUT:"TIMEOUT"};class m extends Error{constructor(t,n){super(n||"请求失败"),this.name="BizError",this.code=t}}class O extends m{constructor(t){super(a.AUTH_EXPIRED,t||"登录已失效"),this.name="AuthError"}}function Me(e){return e instanceof O||e&&e.code===a.AUTH_EXPIRED}const $="dplugin.access",J="dplugin.sid",we="dplugin.ds",Q="dplugin.exp",ee="dplugin.cookie",Ue="token";function Le(e){try{return localStorage.getItem(e)}catch(t){return null}}function me(e,t){try{t==null||t===""?localStorage.removeItem(e):localStorage.setItem(e,t)}catch(n){}}const Y={};function C(e){const t=Le(e);return t===null?Y[e]===void 0?null:Y[e]:t}function k(e,t){Y[e]=t,me(e,t)}const i={get access(){return C($)},set access(e){k($,e)},get sid(){return C(J)},set sid(e){k(J,e)},get ds(){return C(we)},set ds(e){k(we,e)},get exp(){const e=C(Q);return e?Number(e):0},set exp(e){k(Q,e?String(e):null)},get cookie(){return C(ee)==="1"},set cookie(e){k(ee,e?"1":null)},clear(){[$,J,Q,ee,Ue].forEach(e=>{Y[e]=null,me(e,null)})}};function g(e,t){const n=I().apiBase||"";let o=e;return/^https?:\/\//i.test(e)||(o=(n?n.replace(/\/+$/,""):"")+(e.startsWith("/")?e:"/"+e)),t&&(o+=(o.includes("?")?"&":"?")+t),o}function V(e){const t=g(e);if(/^https?:\/\//i.test(t))try{return new URL(t).pathname}catch(n){return t.split("?")[0]}try{return new URL(t,"http://localhost").pathname}catch(n){return t.split("?")[0]}}let S=null;function ve(e){try{const t=typeof location!="undefined"?location.href:void 0;return new URL(e||"",t).origin}catch(t){return null}}function Fe(){S=null}function ie(){if(S)return S;const e=I();if(e.mode==="sign"||e.mode==="cookie")return S=e.mode,S;const t=typeof location!="undefined"?location.origin:null;if(!t)return S="sign",S;const n=ve(e.apiBase||t);return S=n&&n===t?"cookie":"sign",S}function b(){return ie()==="cookie"}async function h(e,t,n){const o=I(),r=n||o.timeout,s=typeof AbortController!="undefined"?new AbortController:null,u=s?setTimeout(()=>s.abort(),r):null,c={method:"POST",credentials:b()?"same-origin":"omit",signal:s?s.signal:void 0};if(typeof FormData!="undefined"&&t instanceof FormData?c.body=t:t!=null&&(c.headers={"Content-Type":"text/plain"},c.body=JSON.stringify(t)),!E.fetch)throw new m(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await E.fetch(e,c)}catch(y){throw u&&clearTimeout(u),y&&y.name==="AbortError"?new m(a.TIMEOUT,"请求超时,请重试"):new m(a.NETWORK,"网络异常,请检查网络后重试")}u&&clearTimeout(u);const d=await f.text();let l=null;if(d)try{l=JSON.parse(d)}catch(y){l=null}if(!f.ok)throw new m(String(f.status),l&&l.message||d||"请求失败");if(!l||l.code===null||l.code===void 0)throw new m("500","响应格式异常");return l.code=String(l.code),l}const je="dplugin-auth",Ge=1,B="keys",se="sso",ce="domain",Ye={name:"ECDSA",namedCurve:"P-256"},Be={name:"ECDSA",hash:"SHA-256"},j=new Map;let v=null;function X(){if(!E.subtle){const e=typeof location!="undefined"&&location.origin?location.origin:"(未知 origin)";throw new Error("[dplugin/core] crypto.subtle 不存在:浏览器只在**安全上下文**里提供它(https、http://localhost、http://127.0.0.1、http://[::1]、file://);当前 origin="+e)}return E.subtle}function He(){return v||(v=new Promise(e=>{if(!E.idbOpen){e(null);return}let t;try{t=E.idbOpen(je,Ge)}catch(n){e(null);return}t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(B)||n.createObjectStore(B)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),v)}function Ee(e,t){return He().then(n=>n?new Promise(o=>{let r;try{r=n.transaction(B,e)}catch(c){o(null);return}const s=r.objectStore(B);let u=null;try{const c=t(s);c&&(c.onsuccess=()=>{u=c.result},c.onerror=()=>{u=null})}catch(c){u=null}r.oncomplete=()=>o(u),r.onerror=()=>o(null),r.onabort=()=>o(null)}):null)}function Oe(e){return j.has(e)?Promise.resolve(j.get(e)):Ee("readonly",t=>t.get(e)).then(t=>(t&&j.set(e,t),t||null))}function ye(e,t){return j.set(e,t),Ee("readwrite",n=>n.put(t,e)).then(()=>t)}async function ae(e){const n=await X().generateKey(Ye,!1,["sign","verify"]);return ye(e,n)}async function be(e){return Oe(e)}async function he(e,t){return t?ye(e,t):null}async function Ve(e){return await Oe(e)||ae(e)}function Xe(){return ae(se)}function We(){return ae(ce)}function ue(){return be(se)}function Se(){return be(ce)}async function te(e){const n=await X().exportKey("spki",e.publicKey);let o="";const r=new Uint8Array(n);for(let s=0;s<r.length;s++)o+=String.fromCharCode(r[s]);return btoa(o)}function Ie(e){const t=new Uint8Array(e);let n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ze(e,t){const o=await X().sign(Be,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=X(),n=await t.exportKey("spki",e.publicKey),o=await t.digest("SHA-256",n);return Ie(o)}const ne={SSO:se,DOMAIN:ce},oe="-",qe="POST",N={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function p(e){return e==null||e===""?oe:String(e)}function Ze(e,t){const n=p(t.origin);return[p(e),p(t.method),p(t.path),n===oe?oe:n.toLowerCase(),p(t.ds),p(t.ts),p(t.subject),p(t.dna),p(t.redirect)].join(`
|
|
2
|
+
`)}function $e(e,t,n){return[p(e),p(t.subject),p(t.ds),p(t.ts),n].join(".")}async function A(e,t,n){const o=n==="sso"?await ue():await Se();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await ze(o,Ze(e,t));return $e(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await A(N.BIZ,{method:qe,path:V(e),origin:K(),ds:n,ts:Date.now(),subject:t},"domain");return"dsign="+encodeURIComponent(o)}function K(){if(typeof location=="undefined")return"";if(location.origin)return location.origin.toLowerCase();try{return new URL(location.href).origin.toLowerCase()}catch(e){return""}}function Pe(e){const t=new Error(e);return t.code="KEY_MISSING",t}function Je(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:Qe(e),device_model:et(e),browser_name:tt(e),browser_version:nt(e),os_name:ot(e),os_version:rt(e)},n=i.ds;return n&&(t.device_id=n),t}function T(e,t){const n=e.match(t);return n?n[1]:""}function Qe(e){return/iPhone|iPad|iPod/.test(e)?"Apple":/Huawei|HONOR/i.test(e)?"Huawei":/Xiaomi|Redmi|POCO/i.test(e)?"Xiaomi":/OPPO|realme/i.test(e)?"OPPO":/vivo/i.test(e)?"vivo":/Samsung|SM-|SAMSUNG/i.test(e)?"Samsung":/Macintosh|Mac OS X/.test(e)?"Apple":""}function et(e){if(/iPhone/.test(e))return"iPhone";if(/iPad/.test(e))return"iPad";const t=e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);return t?t[1].trim():/Macintosh/.test(e)?"Mac":""}function tt(e){return/MicroMessenger/i.test(e)?"WeChat":/Edg[A-Za-z]*\//.test(e)?"Edge":/OPR\/|Opera/.test(e)?"Opera":/Firefox\//.test(e)?"Firefox":/Chrome\/|CriOS\//.test(e)?"Chrome":/Safari\//.test(e)?"Safari":""}function nt(e){return/MicroMessenger\/([\d.]+)/.test(e)?T(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?T(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?T(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?T(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?T(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?T(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?T(e,/Version\/([\d.]+)/):""}function ot(e){return/Windows NT/.test(e)?"Windows":/iPhone|iPad|iPod/.test(e)?"iOS":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/HarmonyOS/.test(e)?"HarmonyOS":/Linux/.test(e)?"Linux":""}function rt(e){if(/Windows NT 10\.0/.test(e))return"10/11";if(/Windows NT 6\.3/.test(e))return"8.1";if(/Windows NT 6\.1/.test(e))return"7";const t=e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);if(t)return t[1].replace(/_/g,".");if(/Android[ _]([\d.]+)/.test(e))return T(e,/Android[ _]([\d.]+)/);const n=e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);return n?n[1].replace(/_/g,"."):""}const w={SIGN:{VERIFY:"/api/unsafe/dplugin/login/s/verify",TOKEN:"/api/unsafe/dplugin/login/s/token",REFRESH:"/api/unsafe/dplugin/login/s/refresh"},COOKIE:{VERIFY:"/api/unsafe/dplugin/login/c/verify",TOKEN:"/api/unsafe/dplugin/login/c/token",REFRESH:"/api/unsafe/dplugin/login/c/refresh"},LOGOUT:"/api/safe/dplugin/login/logout"},it="dp_dvt",de=1800*1e3;let _=null,F=null,R=null,H=!1;function W(){return typeof location!="undefined"?location.href:""}function U(e){return new Promise(t=>setTimeout(t,e))}function st(){try{localStorage.setItem("token",i.access||"cookie")}catch(e){}}function z(){st();const e=I();typeof e.onLogin=="function"&&e.onLogin(L())}function P(e,t){return new m(e.code,e.message||t)}function ct(e,t,n){if(typeof document=="undefined")return;let o=e+"="+encodeURIComponent(t)+"; path=/; SameSite=Lax";o+="; max-age="+n,document.cookie=o}function L(){return{mode:ie(),loggedIn:q(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function q(){return b()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function D(e){const t=q();le();const n=I();if(t&&typeof n.onLogout=="function"&&n.onLogout(e||"expired"),H||!n.enableAuth||!n.loginUrl||typeof location=="undefined")return;H=!0;const o=n.loginUrl.includes("?")?"&":"?";location.href=n.loginUrl+o+"referer="+encodeURIComponent(location.href)}function De(e,t){return R||(R=ut(e,t).then(n=>(R=null,n),n=>{throw R=null,at(n),n}),R)}function at(e){const t=I();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function ut(e,t){const n=I(),o=Je();if(b())return lt(e,t,o,n);const r=await ue(),s=await Se();try{return await ft(e,t,o,n)}catch(u){throw await he(ne.SSO,r),await he(ne.DOMAIN,s),u}}async function ft(e,t,n,o){const r=await Xe(),s=await te(r),u=await h(g(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw P(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw P(u,"登录失败");const f=await We(),d=await Te(f),l=await dt(c,o,d),y=await h(g(w.SIGN.TOKEN),{dsign:await A(N.TOKEN,{origin:K(),ts:Date.now(),subject:l.code,dna:d},"domain"),pk:await te(f)});if(y.code!==a.OK||!y.data)throw P(y,"登录失败");return i.sid=l.sid,i.ds=y.data.ds||l.ds,i.access=y.data.token,i.exp=Date.now()+de,H=!1,z(),L()}async function dt(e,t,n){const o=W(),r=Math.max(1,Number(t.pollMax)||5);for(let s=1;s<=r;s++){const u=i.ds||null,c=Date.now(),f=await A(N.VERIFY,{method:"POST",path:V(w.SIGN.VERIFY),origin:K(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let d;try{d=await h(g(w.SIGN.VERIFY),{dsign:f,dna:n,redirect:o})}catch(l){if((l.code===a.NETWORK||l.code===a.TIMEOUT)&&s<r){await U(t.pollInterval);continue}throw l}if(d.code===a.OK&&d.data)return d.data;if(d.code===a.PENDING){if(s<r){await U(t.pollInterval);continue}break}throw P(d,"登录失败")}throw new m(a.AUTH_EXPIRED,"登录超时,请重试")}async function lt(e,t,n,o){const r=await h(g(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw P(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw P(r,"登录失败");return ct(it,s,300),await gt(o),await Re(),i.cookie=!0,H=!1,z(),L()}async function gt(e){const t=W(),n=Math.max(1,Number(e.pollMax)||5);for(let o=1;o<=n;o++){let r;try{r=await h(g(w.COOKIE.VERIFY),{redirect:t})}catch(s){if((s.code===a.NETWORK||s.code===a.TIMEOUT)&&o<n){await U(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await U(e.pollInterval);continue}break}throw P(r,"登录失败")}throw new m(a.AUTH_EXPIRED,"登录超时,请重试")}async function Re(){const e=await h(g(w.COOKIE.TOKEN));if(e.code!==a.OK)throw P(e,"登录失败");return e}async function x(e){const t=!!(e&&e.force);return F||(F=(async()=>{try{return b()?await wt(t):await pt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{F=null}})()),F}async function wt(e){return!e&&i.cookie?!0:(await h(g(w.COOKIE.VERIFY),{redirect:W()})).code!==a.OK||(await Re()).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,z(),!0)}async function ht(){if(!i.sid||!i.ds||!await ue())return!1;const t=i.ds,n=await Ve(ne.DOMAIN),o=await Te(n),r=W(),s=await A(N.VERIFY_SID,{method:"POST",path:V(w.SIGN.VERIFY),origin:K(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await h(g(w.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await h(g(w.SIGN.TOKEN),{dsign:await A(N.TOKEN,{origin:K(),ts:Date.now(),subject:u.data.code,dna:o},"domain"),pk:await te(n)});return c.code!==a.OK||!c.data?!1:(i.access=c.data.token,c.data.ds&&(i.ds=c.data.ds),i.exp=Date.now()+de,z(),!0)}async function pt(e){return!e&&i.access?!0:ht()}function ge(){return _||(_=(b()?mt():Et()).then(e=>(_=null,e),e=>{throw _=null,e})),_}async function mt(){const e=await h(g(w.COOKIE.REFRESH));if(e.code===a.OK)return!0;if(e.code===a.AUTH_EXPIRED)throw new O(e.message);if(e.code==="500"&&/重复/.test(e.message||""))return await U(800),!0;throw new m(e.code,e.message)}async function Et(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await A(N.BIZ,{method:"POST",path:V(w.SIGN.REFRESH),origin:K(),ds:t,ts:Date.now(),subject:e},"domain"),o=await h(g(w.SIGN.REFRESH,"dsign="+encodeURIComponent(n)));if(o.code===a.OK&&o.data)return i.access=o.data.token,o.data.ds&&(i.ds=o.data.ds),i.exp=Date.now()+de,i.access;const r=await Ot(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(o.message):new m(o.code,o.message)}function Ot(e,t){const n=Date.now()+t;return new Promise(o=>{const r=()=>{const s=i.access;if(s&&s!==e){o(s);return}if(Date.now()>=n){o(null);return}setTimeout(r,150)};r()})}async function Ne(){try{let t=await pe();t.code===a.AUTH_EXPIRED&&(await ge(),t=await pe())}catch(t){}le();const e=I();typeof e.onLogout=="function"&&e.onLogout("logout")}async function pe(){if(b())return h(g(w.LOGOUT));const e=await fe(w.LOGOUT,i.access,i.ds);return h(g(w.LOGOUT,e))}async function yt(e,t,n){const o=bt(t,n);return o.authed&&await Ae(),G(e,o.body,o.options,!1)}function bt(e,t){const n=t||{};return!(typeof FormData!="undefined"&&e instanceof FormData)&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&("data"in e||"noToken"in e||"loading"in e||"error"in e)?{body:e.data,options:Object.assign({},e,n),authed:e.noToken!==!0&&n.auth!==!1}:{body:e,options:n,authed:n.auth!==!1}}async function Ae(){if(b()){if(i.cookie||await x())return;throw D("expired"),new O}if(!i.access&&!await x())throw D("expired"),new O}async function G(e,t,n,o){const r=n.auth!==!1&&n.noToken!==!0,s=r&&!b();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(d){if(!o&&await x({force:!0}))return G(e,t,n,!0);throw D("expired"),new O}}const f=await h(g(e,u),t,n.timeout);if(f.code===a.OK)return f;if(r&&f.code===a.AUTH_EXPIRED&&!o){if(s&&c&&i.access!==c)return G(e,t,n,!0);try{await ge()}catch(d){throw d instanceof O&&D("expired"),d}return G(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(D("expired"),new O(f.message)):Ke(f)}function Ke(e){const t=new m(e.code,e.message),n=I();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function St(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ae(),re(e,t,n,o||{},!1)}async function re(e,t,n,o,r){let s="";if(!b())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await x({force:!0}))return re(e,t,n,o,!0);throw D("expired"),new O}const u=new FormData;Object.keys(n||{}).forEach(f=>{const d=n[f];d!=null&&u.append(f,d)}),u.append("file",t);const c=await h(g(e,s),u,o.timeout);if(c.code===a.OK)return c;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof O&&D("expired"),f}return re(e,t,n,o,!0)}throw Ke(c)}function It(e){const t=xe(e);if(Fe(),t.nativeGuard!=="off"){const n=_e();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const Tt={login:De,logout:Ne,isLogin:q,getState:L,restore:x,setAuthData(){},jump(){return Promise.reject(new Error("[dplugin/core] jump 已下线,请改为同源部署"))},jumpGenerate(){return Promise.reject(new Error("[dplugin/core] jumpGenerate 已下线"))}};exports.AuthError=O;exports.BizError=m;exports.CODE=a;exports.auth=Tt;exports.clear=le;exports.expire=D;exports.getMode=ie;exports.getState=L;exports.isAuthError=Me;exports.isLogin=q;exports.login=De;exports.logout=Ne;exports.request=yt;exports.setup=It;exports.store=i;exports.upload=St;exports.verifyLogin=x;
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.mjs
CHANGED
|
@@ -30,7 +30,7 @@ function Ke(e) {
|
|
|
30
30
|
function I() {
|
|
31
31
|
return _;
|
|
32
32
|
}
|
|
33
|
-
const m =
|
|
33
|
+
const m = xe();
|
|
34
34
|
function Z(e, t) {
|
|
35
35
|
if (typeof e != "function")
|
|
36
36
|
return !1;
|
|
@@ -43,7 +43,7 @@ function Z(e, t) {
|
|
|
43
43
|
const o = /^function\s+([\w$]+)\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.exec(n);
|
|
44
44
|
return o ? o[1] === t : /\[native code\]/.test(n) && !/^function\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.test(n);
|
|
45
45
|
}
|
|
46
|
-
function
|
|
46
|
+
function Ae(e) {
|
|
47
47
|
try {
|
|
48
48
|
const t = e();
|
|
49
49
|
return t && typeof t.then == "function" && Promise.resolve(t).catch(() => {
|
|
@@ -53,14 +53,14 @@ function xe(e) {
|
|
|
53
53
|
return !!t && t.name === "TypeError" && /argument|required|参数/i.test(n);
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
-
function
|
|
56
|
+
function xe() {
|
|
57
57
|
const e = globalThis, t = typeof e.window != "undefined" && e.window && typeof e.window.document != "undefined", n = {
|
|
58
58
|
fetch: null,
|
|
59
59
|
idbOpen: null,
|
|
60
60
|
subtle: null,
|
|
61
61
|
pristine: { fetch: !1, idbOpen: !1, subtle: !1 }
|
|
62
62
|
};
|
|
63
|
-
typeof e.fetch == "function" && (n.pristine.fetch = Z(e.fetch, "fetch"), n.fetch = e.fetch.bind(e)), typeof e.indexedDB != "undefined" && e.indexedDB && typeof e.indexedDB.open == "function" && (n.pristine.idbOpen = Z(e.indexedDB.open, "open") && (!t ||
|
|
63
|
+
typeof e.fetch == "function" && (n.pristine.fetch = Z(e.fetch, "fetch"), n.fetch = e.fetch.bind(e)), typeof e.indexedDB != "undefined" && e.indexedDB && typeof e.indexedDB.open == "function" && (n.pristine.idbOpen = Z(e.indexedDB.open, "open") && (!t || Ae(() => e.indexedDB.open())), n.idbOpen = e.indexedDB.open.bind(e.indexedDB));
|
|
64
64
|
const o = e.crypto && e.crypto.subtle ? e.crypto.subtle : null;
|
|
65
65
|
if (o) {
|
|
66
66
|
const r = ["generateKey", "exportKey", "importKey", "sign", "verify", "digest"], s = {};
|
|
@@ -115,7 +115,7 @@ function he(e, t) {
|
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
const G = {};
|
|
118
|
-
function
|
|
118
|
+
function x(e) {
|
|
119
119
|
const t = _e(e);
|
|
120
120
|
return t === null ? G[e] === void 0 ? null : G[e] : t;
|
|
121
121
|
}
|
|
@@ -124,26 +124,26 @@ function k(e, t) {
|
|
|
124
124
|
}
|
|
125
125
|
const i = {
|
|
126
126
|
get access() {
|
|
127
|
-
return
|
|
127
|
+
return x($);
|
|
128
128
|
},
|
|
129
129
|
set access(e) {
|
|
130
130
|
k($, e);
|
|
131
131
|
},
|
|
132
132
|
get sid() {
|
|
133
|
-
return
|
|
133
|
+
return x(q);
|
|
134
134
|
},
|
|
135
135
|
set sid(e) {
|
|
136
136
|
k(q, e);
|
|
137
137
|
},
|
|
138
138
|
get ds() {
|
|
139
|
-
return
|
|
139
|
+
return x(le);
|
|
140
140
|
},
|
|
141
141
|
set ds(e) {
|
|
142
142
|
k(le, e);
|
|
143
143
|
},
|
|
144
144
|
/** access 的到期时间(毫秒时间戳)。仅用于界面判断,不要拿它做提前续期 */
|
|
145
145
|
get exp() {
|
|
146
|
-
const e =
|
|
146
|
+
const e = x(J);
|
|
147
147
|
return e ? Number(e) : 0;
|
|
148
148
|
},
|
|
149
149
|
set exp(e) {
|
|
@@ -151,7 +151,7 @@ const i = {
|
|
|
151
151
|
},
|
|
152
152
|
/** cookie 模式:本地只记「可能已登录」,实际有效性由第一次请求的结果决定 */
|
|
153
153
|
get cookie() {
|
|
154
|
-
return
|
|
154
|
+
return x(Q) === "1";
|
|
155
155
|
},
|
|
156
156
|
set cookie(e) {
|
|
157
157
|
k(Q, e ? "1" : null);
|
|
@@ -173,7 +173,7 @@ function g(e, t) {
|
|
|
173
173
|
let o = e;
|
|
174
174
|
return /^https?:\/\//i.test(e) || (o = (n ? n.replace(/\/+$/, "") : "") + (e.startsWith("/") ? e : "/" + e)), t && (o += (o.includes("?") ? "&" : "?") + t), o;
|
|
175
175
|
}
|
|
176
|
-
function
|
|
176
|
+
function B(e) {
|
|
177
177
|
const t = g(e);
|
|
178
178
|
if (/^https?:\/\//i.test(t))
|
|
179
179
|
try {
|
|
@@ -244,9 +244,9 @@ async function h(e, t, n) {
|
|
|
244
244
|
throw new E("500", "响应格式异常");
|
|
245
245
|
return l.code = String(l.code), l;
|
|
246
246
|
}
|
|
247
|
-
const Le = "dplugin-auth", Fe = 1,
|
|
247
|
+
const Le = "dplugin-auth", Fe = 1, Y = "keys", re = "sso", ie = "domain", ve = { name: "ECDSA", namedCurve: "P-256" }, je = { name: "ECDSA", hash: "SHA-256" }, v = /* @__PURE__ */ new Map();
|
|
248
248
|
let L = null;
|
|
249
|
-
function
|
|
249
|
+
function V() {
|
|
250
250
|
if (!m.subtle) {
|
|
251
251
|
const e = typeof location != "undefined" && location.origin ? location.origin : "(未知 origin)";
|
|
252
252
|
throw new Error("[dplugin/core] crypto.subtle 不存在:浏览器只在**安全上下文**里提供它(https、http://localhost、http://127.0.0.1、http://[::1]、file://);当前 origin=" + e);
|
|
@@ -268,7 +268,7 @@ function Ge() {
|
|
|
268
268
|
}
|
|
269
269
|
t.onupgradeneeded = () => {
|
|
270
270
|
const n = t.result;
|
|
271
|
-
n.objectStoreNames.contains(
|
|
271
|
+
n.objectStoreNames.contains(Y) || n.createObjectStore(Y);
|
|
272
272
|
}, t.onsuccess = () => e(t.result), t.onerror = () => e(null), t.onblocked = () => e(null);
|
|
273
273
|
}), L);
|
|
274
274
|
}
|
|
@@ -276,12 +276,12 @@ function me(e, t) {
|
|
|
276
276
|
return Ge().then((n) => n ? new Promise((o) => {
|
|
277
277
|
let r;
|
|
278
278
|
try {
|
|
279
|
-
r = n.transaction(
|
|
279
|
+
r = n.transaction(Y, e);
|
|
280
280
|
} catch (c) {
|
|
281
281
|
o(null);
|
|
282
282
|
return;
|
|
283
283
|
}
|
|
284
|
-
const s = r.objectStore(
|
|
284
|
+
const s = r.objectStore(Y);
|
|
285
285
|
let a = null;
|
|
286
286
|
try {
|
|
287
287
|
const c = t(s);
|
|
@@ -303,7 +303,7 @@ function Oe(e, t) {
|
|
|
303
303
|
return v.set(e, t), me("readwrite", (n) => n.put(t, e)).then(() => t);
|
|
304
304
|
}
|
|
305
305
|
async function se(e) {
|
|
306
|
-
const n = await
|
|
306
|
+
const n = await V().generateKey(ve, !1, ["sign", "verify"]);
|
|
307
307
|
return Oe(e, n);
|
|
308
308
|
}
|
|
309
309
|
async function ye(e) {
|
|
@@ -312,13 +312,13 @@ async function ye(e) {
|
|
|
312
312
|
async function ge(e, t) {
|
|
313
313
|
return t ? Oe(e, t) : null;
|
|
314
314
|
}
|
|
315
|
-
async function
|
|
315
|
+
async function Ye(e) {
|
|
316
316
|
return await Ee(e) || se(e);
|
|
317
317
|
}
|
|
318
|
-
function
|
|
318
|
+
function He() {
|
|
319
319
|
return se(re);
|
|
320
320
|
}
|
|
321
|
-
function
|
|
321
|
+
function Be() {
|
|
322
322
|
return se(ie);
|
|
323
323
|
}
|
|
324
324
|
function ce() {
|
|
@@ -328,7 +328,7 @@ function be() {
|
|
|
328
328
|
return ye(ie);
|
|
329
329
|
}
|
|
330
330
|
async function ee(e) {
|
|
331
|
-
const n = await
|
|
331
|
+
const n = await V().exportKey("spki", e.publicKey);
|
|
332
332
|
let o = "";
|
|
333
333
|
const r = new Uint8Array(n);
|
|
334
334
|
for (let s = 0; s < r.length; s++)
|
|
@@ -342,12 +342,12 @@ function Se(e) {
|
|
|
342
342
|
n += String.fromCharCode(t[o]);
|
|
343
343
|
return btoa(n).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
344
344
|
}
|
|
345
|
-
async function
|
|
346
|
-
const o = await
|
|
345
|
+
async function Ve(e, t) {
|
|
346
|
+
const o = await V().sign(je, e.privateKey, new TextEncoder().encode(t));
|
|
347
347
|
return Se(o);
|
|
348
348
|
}
|
|
349
349
|
async function Ie(e) {
|
|
350
|
-
const t =
|
|
350
|
+
const t = V(), n = await t.exportKey("spki", e.publicKey), o = await t.digest("SHA-256", n);
|
|
351
351
|
return Se(o);
|
|
352
352
|
}
|
|
353
353
|
const te = {
|
|
@@ -384,7 +384,7 @@ async function K(e, t, n) {
|
|
|
384
384
|
const o = n === "sso" ? await ce() : await be();
|
|
385
385
|
if (!o)
|
|
386
386
|
throw Te(n === "sso" ? "缺少登录签名密钥" : "缺少业务签名密钥");
|
|
387
|
-
const r = await
|
|
387
|
+
const r = await Ve(o, We(e, t));
|
|
388
388
|
return ze(e, t, r);
|
|
389
389
|
}
|
|
390
390
|
async function ae(e, t, n) {
|
|
@@ -392,15 +392,15 @@ async function ae(e, t, n) {
|
|
|
392
392
|
throw Te("缺少 access 或 ds,无法签名");
|
|
393
393
|
const o = await K(N.BIZ, {
|
|
394
394
|
method: Xe,
|
|
395
|
-
path:
|
|
396
|
-
origin:
|
|
395
|
+
path: B(e),
|
|
396
|
+
origin: A(),
|
|
397
397
|
ds: n,
|
|
398
398
|
ts: Date.now(),
|
|
399
399
|
subject: t
|
|
400
400
|
}, "domain");
|
|
401
401
|
return "dsign=" + encodeURIComponent(o);
|
|
402
402
|
}
|
|
403
|
-
function
|
|
403
|
+
function A() {
|
|
404
404
|
if (typeof location == "undefined")
|
|
405
405
|
return "";
|
|
406
406
|
if (location.origin)
|
|
@@ -471,7 +471,7 @@ const w = {
|
|
|
471
471
|
},
|
|
472
472
|
LOGOUT: "/api/safe/dplugin/login/logout"
|
|
473
473
|
}, nt = "dp_dvt", ue = 1800 * 1e3;
|
|
474
|
-
let C = null, F = null, D = null,
|
|
474
|
+
let C = null, F = null, D = null, H = !1;
|
|
475
475
|
function X() {
|
|
476
476
|
return typeof location != "undefined" ? location.href : "";
|
|
477
477
|
}
|
|
@@ -517,9 +517,9 @@ function R(e) {
|
|
|
517
517
|
const t = fe();
|
|
518
518
|
Pe();
|
|
519
519
|
const n = I();
|
|
520
|
-
if (t && typeof n.onLogout == "function" && n.onLogout(e || "expired"),
|
|
520
|
+
if (t && typeof n.onLogout == "function" && n.onLogout(e || "expired"), H || !n.enableAuth || !n.loginUrl || typeof location == "undefined")
|
|
521
521
|
return;
|
|
522
|
-
|
|
522
|
+
H = !0;
|
|
523
523
|
const o = n.loginUrl.includes("?") ? "&" : "?";
|
|
524
524
|
location.href = n.loginUrl + o + "referer=" + encodeURIComponent(location.href);
|
|
525
525
|
}
|
|
@@ -548,15 +548,15 @@ async function ct(e, t) {
|
|
|
548
548
|
}
|
|
549
549
|
}
|
|
550
550
|
async function at(e, t, n, o) {
|
|
551
|
-
const r = await
|
|
551
|
+
const r = await He(), s = await ee(r), a = await h(g(e), Object.assign({}, t, { device: n, pk: s }));
|
|
552
552
|
if (a.code !== u.OK)
|
|
553
553
|
throw P(a, "登录失败");
|
|
554
554
|
const c = a.data && a.data.token;
|
|
555
555
|
if (!c)
|
|
556
556
|
throw P(a, "登录失败");
|
|
557
|
-
const f = await
|
|
557
|
+
const f = await Be(), d = await Ie(f), l = await ut(c, o, d), y = await h(g(w.SIGN.TOKEN), {
|
|
558
558
|
dsign: await K(N.TOKEN, {
|
|
559
|
-
origin:
|
|
559
|
+
origin: A(),
|
|
560
560
|
ts: Date.now(),
|
|
561
561
|
subject: l.code,
|
|
562
562
|
dna: d
|
|
@@ -565,15 +565,15 @@ async function at(e, t, n, o) {
|
|
|
565
565
|
});
|
|
566
566
|
if (y.code !== u.OK || !y.data)
|
|
567
567
|
throw P(y, "登录失败");
|
|
568
|
-
return i.sid = l.sid, i.ds = y.data.ds || l.ds, i.access = y.data.token, i.exp = Date.now() + ue,
|
|
568
|
+
return i.sid = l.sid, i.ds = y.data.ds || l.ds, i.access = y.data.token, i.exp = Date.now() + ue, H = !1, W(), z();
|
|
569
569
|
}
|
|
570
570
|
async function ut(e, t, n) {
|
|
571
571
|
const o = X(), r = Math.max(1, Number(t.pollMax) || 5);
|
|
572
572
|
for (let s = 1; s <= r; s++) {
|
|
573
573
|
const a = i.ds || null, c = Date.now(), f = await K(N.VERIFY, {
|
|
574
574
|
method: "POST",
|
|
575
|
-
path:
|
|
576
|
-
origin:
|
|
575
|
+
path: B(w.SIGN.VERIFY),
|
|
576
|
+
origin: A(),
|
|
577
577
|
ds: a,
|
|
578
578
|
ts: c,
|
|
579
579
|
subject: e,
|
|
@@ -610,7 +610,7 @@ async function ft(e, t, n, o) {
|
|
|
610
610
|
const s = r.data && r.data.token;
|
|
611
611
|
if (!s)
|
|
612
612
|
throw P(r, "登录失败");
|
|
613
|
-
return rt(nt, s, 300), await dt(o), await Re(), i.cookie = !0,
|
|
613
|
+
return rt(nt, s, 300), await dt(o), await Re(), i.cookie = !0, H = !1, W(), z();
|
|
614
614
|
}
|
|
615
615
|
async function dt(e) {
|
|
616
616
|
const t = X(), n = Math.max(1, Number(e.pollMax) || 5);
|
|
@@ -664,10 +664,10 @@ async function lt(e) {
|
|
|
664
664
|
async function gt() {
|
|
665
665
|
if (!i.sid || !i.ds || !await ce())
|
|
666
666
|
return !1;
|
|
667
|
-
const t = i.ds, n = await
|
|
667
|
+
const t = i.ds, n = await Ye(te.DOMAIN), o = await Ie(n), r = X(), s = await K(N.VERIFY_SID, {
|
|
668
668
|
method: "POST",
|
|
669
|
-
path:
|
|
670
|
-
origin:
|
|
669
|
+
path: B(w.SIGN.VERIFY),
|
|
670
|
+
origin: A(),
|
|
671
671
|
ds: t,
|
|
672
672
|
ts: Date.now(),
|
|
673
673
|
subject: i.sid,
|
|
@@ -678,7 +678,7 @@ async function gt() {
|
|
|
678
678
|
return !1;
|
|
679
679
|
const c = await h(g(w.SIGN.TOKEN), {
|
|
680
680
|
dsign: await K(N.TOKEN, {
|
|
681
|
-
origin:
|
|
681
|
+
origin: A(),
|
|
682
682
|
ts: Date.now(),
|
|
683
683
|
subject: a.data.code,
|
|
684
684
|
dna: o
|
|
@@ -711,8 +711,8 @@ async function pt() {
|
|
|
711
711
|
throw new O();
|
|
712
712
|
const n = await K(N.BIZ, {
|
|
713
713
|
method: "POST",
|
|
714
|
-
path:
|
|
715
|
-
origin:
|
|
714
|
+
path: B(w.SIGN.REFRESH),
|
|
715
|
+
origin: A(),
|
|
716
716
|
ds: t,
|
|
717
717
|
ts: Date.now(),
|
|
718
718
|
subject: e
|
|
@@ -760,7 +760,7 @@ async function we() {
|
|
|
760
760
|
}
|
|
761
761
|
async function bt(e, t, n) {
|
|
762
762
|
const o = Ot(t, n);
|
|
763
|
-
return o.authed && await De(),
|
|
763
|
+
return o.authed && await De(), j(e, o.body, o.options, !1);
|
|
764
764
|
}
|
|
765
765
|
function Ot(e, t) {
|
|
766
766
|
const n = t || {};
|
|
@@ -779,7 +779,7 @@ async function De() {
|
|
|
779
779
|
if (!i.access && !await M())
|
|
780
780
|
throw R("expired"), new O();
|
|
781
781
|
}
|
|
782
|
-
async function
|
|
782
|
+
async function j(e, t, n, o) {
|
|
783
783
|
const r = n.auth !== !1 && n.noToken !== !0, s = r && !b();
|
|
784
784
|
let a = "", c = null;
|
|
785
785
|
if (s) {
|
|
@@ -788,7 +788,7 @@ async function Y(e, t, n, o) {
|
|
|
788
788
|
a = await ae(e, c, i.ds);
|
|
789
789
|
} catch (d) {
|
|
790
790
|
if (!o && await M({ force: !0 }))
|
|
791
|
-
return
|
|
791
|
+
return j(e, t, n, !0);
|
|
792
792
|
throw R("expired"), new O();
|
|
793
793
|
}
|
|
794
794
|
}
|
|
@@ -797,13 +797,13 @@ async function Y(e, t, n, o) {
|
|
|
797
797
|
return f;
|
|
798
798
|
if (r && f.code === u.AUTH_EXPIRED && !o) {
|
|
799
799
|
if (s && c && i.access !== c)
|
|
800
|
-
return
|
|
800
|
+
return j(e, t, n, !0);
|
|
801
801
|
try {
|
|
802
802
|
await de();
|
|
803
803
|
} catch (d) {
|
|
804
804
|
throw d instanceof O && R("expired"), d;
|
|
805
805
|
}
|
|
806
|
-
return
|
|
806
|
+
return j(e, t, n, !0);
|
|
807
807
|
}
|
|
808
808
|
throw r && f.code === u.AUTH_EXPIRED ? (R("expired"), new O(f.message)) : Ne(f);
|
|
809
809
|
}
|
|
@@ -860,7 +860,19 @@ const Tt = {
|
|
|
860
860
|
isLogin: fe,
|
|
861
861
|
getState: z,
|
|
862
862
|
/** 页面加载时恢复登录态;返回是否已登录 */
|
|
863
|
-
restore: M
|
|
863
|
+
restore: M,
|
|
864
|
+
// ---------------- 兼容旧应用,不要在新代码里用 ----------------
|
|
865
|
+
/** 老代码在登录回调里调它落库;现在 login() 已经处理,这里空实现 */
|
|
866
|
+
setAuthData() {
|
|
867
|
+
},
|
|
868
|
+
/** 老协议跨域交接,后端接口已下线 */
|
|
869
|
+
jump() {
|
|
870
|
+
return Promise.reject(new Error("[dplugin/core] jump 已下线,请改为同源部署"));
|
|
871
|
+
},
|
|
872
|
+
/** 同上 */
|
|
873
|
+
jumpGenerate() {
|
|
874
|
+
return Promise.reject(new Error("[dplugin/core] jumpGenerate 已下线"));
|
|
875
|
+
}
|
|
864
876
|
};
|
|
865
877
|
export {
|
|
866
878
|
O as AuthError,
|
package/dist/index.umd.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(d,I){typeof exports=="object"&&typeof module!="undefined"?I(exports):typeof define=="function"&&define.amd?define(["exports"],I):(d=typeof globalThis!="undefined"?globalThis:d||self,I(d.DPluginCore={}))})(this,(function(d){"use strict";const I={apiBase:"",mode:"auto",loginUrl:"/login/",timeout:15e3,pollInterval:2e3,pollMax:5,enableAuth:!1,onError:null,onLogin:null,onLogout:null,nativeGuard:"warn"};function ke(e){return e&&Object.keys(I).forEach(t=>{e[t]!==void 0&&(I[t]=e[t])}),I}function T(){return I}const y=xe();function $(e,t){if(typeof e!="function")return!1;let n;try{n=Function.prototype.toString.call(e)}catch(r){return!1}const o=/^function\s+([\w$]+)\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.exec(n);return o?o[1]===t:/\[native code\]/.test(n)&&!/^function\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.test(n)}function _e(e){try{const t=e();return t&&typeof t.then=="function"&&Promise.resolve(t).catch(()=>{}),!1}catch(t){const n=String(t&&t.message||"");return!!t&&t.name==="TypeError"&&/argument|required|参数/i.test(n)}}function xe(){const e=globalThis,t=typeof e.window!="undefined"&&e.window&&typeof e.window.document!="undefined",n={fetch:null,idbOpen:null,subtle:null,pristine:{fetch:!1,idbOpen:!1,subtle:!1}};typeof e.fetch=="function"&&(n.pristine.fetch=$(e.fetch,"fetch"),n.fetch=e.fetch.bind(e)),typeof e.indexedDB!="undefined"&&e.indexedDB&&typeof e.indexedDB.open=="function"&&(n.pristine.idbOpen=$(e.indexedDB.open,"open")&&(!t||_e(()=>e.indexedDB.open())),n.idbOpen=e.indexedDB.open.bind(e.indexedDB));const o=e.crypto&&e.crypto.subtle?e.crypto.subtle:null;if(o){const r=["generateKey","exportKey","importKey","sign","verify","digest"],s={};let u=!0;r.forEach(c=>{typeof o[c]=="function"&&(s[c]=o[c].bind(o),u=u&&$(o[c],c))}),n.subtle=s,n.pristine.subtle=u}return n}function Me(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return y.fetch&&!y.pristine.fetch&&e.push("fetch"),y.idbOpen&&!y.pristine.idbOpen&&e.push("indexedDB.open"),y.subtle&&!y.pristine.subtle&&e.push("crypto.subtle"),e}const a={OK:"200",PENDING:"202",AUTH_EXPIRED:"500900",FORBIDDEN:"401001",CORS_DENIED:"403",API_NOT_FOUND:"404",NETWORK:"NETWORK",TIMEOUT:"TIMEOUT"};class
|
|
2
|
-
`)}function Je(e,t,n){return[m(e),m(t.subject),m(t.ds),m(t.ts),n].join(".")}async function K(e,t,n){const o=n==="sso"?await se():await Se();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await qe(o,$e(e,t));return Je(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await K(A.BIZ,{method:Ze,path:Y(e),origin:C(),ds:n,ts:Date.now(),subject:t},"domain");return"dsign="+encodeURIComponent(o)}function C(){if(typeof location=="undefined")return"";if(location.origin)return location.origin.toLowerCase();try{return new URL(location.href).origin.toLowerCase()}catch(e){return""}}function Pe(e){const t=new Error(e);return t.code="KEY_MISSING",t}function Qe(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:et(e),device_model:tt(e),browser_name:nt(e),browser_version:ot(e),os_name:rt(e),os_version:it(e)},n=i.ds;return n&&(t.device_id=n),t}function D(e,t){const n=e.match(t);return n?n[1]:""}function et(e){return/iPhone|iPad|iPod/.test(e)?"Apple":/Huawei|HONOR/i.test(e)?"Huawei":/Xiaomi|Redmi|POCO/i.test(e)?"Xiaomi":/OPPO|realme/i.test(e)?"OPPO":/vivo/i.test(e)?"vivo":/Samsung|SM-|SAMSUNG/i.test(e)?"Samsung":/Macintosh|Mac OS X/.test(e)?"Apple":""}function tt(e){if(/iPhone/.test(e))return"iPhone";if(/iPad/.test(e))return"iPad";const t=e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);return t?t[1].trim():/Macintosh/.test(e)?"Mac":""}function nt(e){return/MicroMessenger/i.test(e)?"WeChat":/Edg[A-Za-z]*\//.test(e)?"Edge":/OPR\/|Opera/.test(e)?"Opera":/Firefox\//.test(e)?"Firefox":/Chrome\/|CriOS\//.test(e)?"Chrome":/Safari\//.test(e)?"Safari":""}function ot(e){return/MicroMessenger\/([\d.]+)/.test(e)?D(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?D(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?D(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?D(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?D(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?D(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?D(e,/Version\/([\d.]+)/):""}function rt(e){return/Windows NT/.test(e)?"Windows":/iPhone|iPad|iPod/.test(e)?"iOS":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/HarmonyOS/.test(e)?"HarmonyOS":/Linux/.test(e)?"Linux":""}function it(e){if(/Windows NT 10\.0/.test(e))return"10/11";if(/Windows NT 6\.3/.test(e))return"8.1";if(/Windows NT 6\.1/.test(e))return"7";const t=e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);if(t)return t[1].replace(/_/g,".");if(/Android[ _]([\d.]+)/.test(e))return D(e,/Android[ _]([\d.]+)/);const n=e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);return n?n[1].replace(/_/g,"."):""}const p={SIGN:{VERIFY:"/api/unsafe/dplugin/login/s/verify",TOKEN:"/api/unsafe/dplugin/login/s/token",REFRESH:"/api/unsafe/dplugin/login/s/refresh"},COOKIE:{VERIFY:"/api/unsafe/dplugin/login/c/verify",TOKEN:"/api/unsafe/dplugin/login/c/token",REFRESH:"/api/unsafe/dplugin/login/c/refresh"},LOGOUT:"/api/safe/dplugin/login/logout"},st="dp_dvt",de=1800*1e3;let U=null,V=null,k=null,X=!1;function W(){return typeof location!="undefined"?location.href:""}function L(e){return new Promise(t=>setTimeout(t,e))}function ct(){try{localStorage.setItem("token",i.access||"cookie")}catch(e){}}function z(){ct();const e=T();typeof e.onLogin=="function"&&e.onLogin(v())}function R(e,t){return new E(e.code,e.message||t)}function at(e,t,n){if(typeof document=="undefined")return;let o=e+"="+encodeURIComponent(t)+"; path=/; SameSite=Lax";o+="; max-age="+n,document.cookie=o}function v(){return{mode:ne(),loggedIn:q(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function q(){return b()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function N(e){const t=q();le();const n=T();if(t&&typeof n.onLogout=="function"&&n.onLogout(e||"expired"),X||!n.enableAuth||!n.loginUrl||typeof location=="undefined")return;X=!0;const o=n.loginUrl.includes("?")?"&":"?";location.href=n.loginUrl+o+"referer="+encodeURIComponent(location.href)}function De(e,t){return k||(k=ft(e,t).then(n=>(k=null,n),n=>{throw k=null,ut(n),n}),k)}function ut(e){const t=T();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function ft(e,t){const n=T(),o=Qe();if(b())return gt(e,t,o,n);const r=await se(),s=await Se();try{return await dt(e,t,o,n)}catch(u){throw await be(ae.SSO,r),await be(ae.DOMAIN,s),u}}async function dt(e,t,n,o){const r=await We(),s=await ce(r),u=await w(h(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw R(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw R(u,"登录失败");const f=await ze(),l=await Te(f),g=await lt(c,o,l),S=await w(h(p.SIGN.TOKEN),{dsign:await K(A.TOKEN,{origin:C(),ts:Date.now(),subject:g.code,dna:l},"domain"),pk:await ce(f)});if(S.code!==a.OK||!S.data)throw R(S,"登录失败");return i.sid=g.sid,i.ds=S.data.ds||g.ds,i.access=S.data.token,i.exp=Date.now()+de,X=!1,z(),v()}async function lt(e,t,n){const o=W(),r=Math.max(1,Number(t.pollMax)||5);for(let s=1;s<=r;s++){const u=i.ds||null,c=Date.now(),f=await K(A.VERIFY,{method:"POST",path:Y(p.SIGN.VERIFY),origin:C(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let l;try{l=await w(h(p.SIGN.VERIFY),{dsign:f,dna:n,redirect:o})}catch(g){if((g.code===a.NETWORK||g.code===a.TIMEOUT)&&s<r){await L(t.pollInterval);continue}throw g}if(l.code===a.OK&&l.data)return l.data;if(l.code===a.PENDING){if(s<r){await L(t.pollInterval);continue}break}throw R(l,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function gt(e,t,n,o){const r=await w(h(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw R(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw R(r,"登录失败");return at(st,s,300),await ht(o),await Re(),i.cookie=!0,X=!1,z(),v()}async function ht(e){const t=W(),n=Math.max(1,Number(e.pollMax)||5);for(let o=1;o<=n;o++){let r;try{r=await w(h(p.COOKIE.VERIFY),{redirect:t})}catch(s){if((s.code===a.NETWORK||s.code===a.TIMEOUT)&&o<n){await L(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await L(e.pollInterval);continue}break}throw R(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function Re(){const e=await w(h(p.COOKIE.TOKEN));if(e.code!==a.OK)throw R(e,"登录失败");return e}async function _(e){const t=!!(e&&e.force);return V||(V=(async()=>{try{return b()?await wt(t):await Et(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{V=null}})()),V}async function wt(e){return!e&&i.cookie?!0:(await w(h(p.COOKIE.VERIFY),{redirect:W()})).code!==a.OK||(await Re()).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,z(),!0)}async function pt(){if(!i.sid||!i.ds||!await se())return!1;const t=i.ds,n=await Xe(ae.DOMAIN),o=await Te(n),r=W(),s=await K(A.VERIFY_SID,{method:"POST",path:Y(p.SIGN.VERIFY),origin:C(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await w(h(p.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await w(h(p.SIGN.TOKEN),{dsign:await K(A.TOKEN,{origin:C(),ts:Date.now(),subject:u.data.code,dna:o},"domain"),pk:await ce(n)});return c.code!==a.OK||!c.data?!1:(i.access=c.data.token,c.data.ds&&(i.ds=c.data.ds),i.exp=Date.now()+de,z(),!0)}async function Et(e){return!e&&i.access?!0:pt()}function ge(){return U||(U=(b()?mt():yt()).then(e=>(U=null,e),e=>{throw U=null,e})),U}async function mt(){const e=await w(h(p.COOKIE.REFRESH));if(e.code===a.OK)return!0;if(e.code===a.AUTH_EXPIRED)throw new O(e.message);if(e.code==="500"&&/重复/.test(e.message||""))return await L(800),!0;throw new E(e.code,e.message)}async function yt(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await K(A.BIZ,{method:"POST",path:Y(p.SIGN.REFRESH),origin:C(),ds:t,ts:Date.now(),subject:e},"domain"),o=await w(h(p.SIGN.REFRESH,"dsign="+encodeURIComponent(n)));if(o.code===a.OK&&o.data)return i.access=o.data.token,o.data.ds&&(i.ds=o.data.ds),i.exp=Date.now()+de,i.access;const r=await Ot(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(o.message):new E(o.code,o.message)}function Ot(e,t){const n=Date.now()+t;return new Promise(o=>{const r=()=>{const s=i.access;if(s&&s!==e){o(s);return}if(Date.now()>=n){o(null);return}setTimeout(r,150)};r()})}async function Ne(){try{let t=await Ae();t.code===a.AUTH_EXPIRED&&(await ge(),t=await Ae())}catch(t){}le();const e=T();typeof e.onLogout=="function"&&e.onLogout("logout")}async function Ae(){if(b())return w(h(p.LOGOUT));const e=await fe(p.LOGOUT,i.access,i.ds);return w(h(p.LOGOUT,e))}async function bt(e,t,n){const o=St(t,n);return o.authed&&await Ke(),Z(e,o.body,o.options,!1)}function St(e,t){const n=t||{};return!(typeof FormData!="undefined"&&e instanceof FormData)&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&("data"in e||"noToken"in e||"loading"in e||"error"in e)?{body:e.data,options:Object.assign({},e,n),authed:e.noToken!==!0&&n.auth!==!1}:{body:e,options:n,authed:n.auth!==!1}}async function Ke(){if(b()){if(i.cookie||await _())return;throw N("expired"),new O}if(!i.access&&!await _())throw N("expired"),new O}async function Z(e,t,n,o){const r=n.auth!==!1&&n.noToken!==!0,s=r&&!b();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(l){if(!o&&await _({force:!0}))return Z(e,t,n,!0);throw N("expired"),new O}}const f=await w(h(e,u),t,n.timeout);if(f.code===a.OK)return f;if(r&&f.code===a.AUTH_EXPIRED&&!o){if(s&&c&&i.access!==c)return Z(e,t,n,!0);try{await ge()}catch(l){throw l instanceof O&&N("expired"),l}return Z(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(N("expired"),new O(f.message)):Ce(f)}function Ce(e){const t=new E(e.code,e.message),n=T();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function It(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ke(),he(e,t,n,o||{},!1)}async function he(e,t,n,o,r){let s="";if(!b())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await _({force:!0}))return he(e,t,n,o,!0);throw N("expired"),new O}const u=new FormData;Object.keys(n||{}).forEach(f=>{const l=n[f];l!=null&&u.append(f,l)}),u.append("file",t);const c=await w(h(e,s),u,o.timeout);if(c.code===a.OK)return c;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof O&&N("expired"),f}return he(e,t,n,o,!0)}throw Ce(c)}function Tt(e){const t=ke(e);if(Ye(),t.nativeGuard!=="off"){const n=Me();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const Pt={login:De,logout:Ne,isLogin:q,getState:v,restore:_};d.AuthError=O,d.BizError=E,d.CODE=a,d.auth=Pt,d.clear=le,d.expire=N,d.getMode=ne,d.getState=v,d.isAuthError=Ue,d.isLogin=q,d.login=De,d.logout=Ne,d.request=bt,d.setup=Tt,d.store=i,d.upload=It,d.verifyLogin=_,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(d,I){typeof exports=="object"&&typeof module!="undefined"?I(exports):typeof define=="function"&&define.amd?define(["exports"],I):(d=typeof globalThis!="undefined"?globalThis:d||self,I(d.DPluginCore={}))})(this,(function(d){"use strict";const I={apiBase:"",mode:"auto",loginUrl:"/login/",timeout:15e3,pollInterval:2e3,pollMax:5,enableAuth:!1,onError:null,onLogin:null,onLogout:null,nativeGuard:"warn"};function ke(e){return e&&Object.keys(I).forEach(t=>{e[t]!==void 0&&(I[t]=e[t])}),I}function T(){return I}const y=xe();function $(e,t){if(typeof e!="function")return!1;let n;try{n=Function.prototype.toString.call(e)}catch(r){return!1}const o=/^function\s+([\w$]+)\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.exec(n);return o?o[1]===t:/\[native code\]/.test(n)&&!/^function\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.test(n)}function _e(e){try{const t=e();return t&&typeof t.then=="function"&&Promise.resolve(t).catch(()=>{}),!1}catch(t){const n=String(t&&t.message||"");return!!t&&t.name==="TypeError"&&/argument|required|参数/i.test(n)}}function xe(){const e=globalThis,t=typeof e.window!="undefined"&&e.window&&typeof e.window.document!="undefined",n={fetch:null,idbOpen:null,subtle:null,pristine:{fetch:!1,idbOpen:!1,subtle:!1}};typeof e.fetch=="function"&&(n.pristine.fetch=$(e.fetch,"fetch"),n.fetch=e.fetch.bind(e)),typeof e.indexedDB!="undefined"&&e.indexedDB&&typeof e.indexedDB.open=="function"&&(n.pristine.idbOpen=$(e.indexedDB.open,"open")&&(!t||_e(()=>e.indexedDB.open())),n.idbOpen=e.indexedDB.open.bind(e.indexedDB));const o=e.crypto&&e.crypto.subtle?e.crypto.subtle:null;if(o){const r=["generateKey","exportKey","importKey","sign","verify","digest"],s={};let u=!0;r.forEach(c=>{typeof o[c]=="function"&&(s[c]=o[c].bind(o),u=u&&$(o[c],c))}),n.subtle=s,n.pristine.subtle=u}return n}function Me(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return y.fetch&&!y.pristine.fetch&&e.push("fetch"),y.idbOpen&&!y.pristine.idbOpen&&e.push("indexedDB.open"),y.subtle&&!y.pristine.subtle&&e.push("crypto.subtle"),e}const a={OK:"200",PENDING:"202",AUTH_EXPIRED:"500900",FORBIDDEN:"401001",CORS_DENIED:"403",API_NOT_FOUND:"404",NETWORK:"NETWORK",TIMEOUT:"TIMEOUT"};class m extends Error{constructor(t,n){super(n||"请求失败"),this.name="BizError",this.code=t}}class O extends m{constructor(t){super(a.AUTH_EXPIRED,t||"登录已失效"),this.name="AuthError"}}function Ue(e){return e instanceof O||e&&e.code===a.AUTH_EXPIRED}const J="dplugin.access",Q="dplugin.sid",we="dplugin.ds",ee="dplugin.exp",te="dplugin.cookie",Le="token";function ve(e){try{return localStorage.getItem(e)}catch(t){return null}}function pe(e,t){try{t==null||t===""?localStorage.removeItem(e):localStorage.setItem(e,t)}catch(n){}}const F={};function x(e){const t=ve(e);return t===null?F[e]===void 0?null:F[e]:t}function M(e,t){F[e]=t,pe(e,t)}const i={get access(){return x(J)},set access(e){M(J,e)},get sid(){return x(Q)},set sid(e){M(Q,e)},get ds(){return x(we)},set ds(e){M(we,e)},get exp(){const e=x(ee);return e?Number(e):0},set exp(e){M(ee,e?String(e):null)},get cookie(){return x(te)==="1"},set cookie(e){M(te,e?"1":null)},clear(){[J,Q,ee,te,Le].forEach(e=>{F[e]=null,pe(e,null)})}};function h(e,t){const n=T().apiBase||"";let o=e;return/^https?:\/\//i.test(e)||(o=(n?n.replace(/\/+$/,""):"")+(e.startsWith("/")?e:"/"+e)),t&&(o+=(o.includes("?")?"&":"?")+t),o}function j(e){const t=h(e);if(/^https?:\/\//i.test(t))try{return new URL(t).pathname}catch(n){return t.split("?")[0]}try{return new URL(t,"http://localhost").pathname}catch(n){return t.split("?")[0]}}let P=null;function Fe(e){try{const t=typeof location!="undefined"?location.href:void 0;return new URL(e||"",t).origin}catch(t){return null}}function je(){P=null}function ne(){if(P)return P;const e=T();if(e.mode==="sign"||e.mode==="cookie")return P=e.mode,P;const t=typeof location!="undefined"?location.origin:null;if(!t)return P="sign",P;const n=Fe(e.apiBase||t);return P=n&&n===t?"cookie":"sign",P}function b(){return ne()==="cookie"}async function w(e,t,n){const o=T(),r=n||o.timeout,s=typeof AbortController!="undefined"?new AbortController:null,u=s?setTimeout(()=>s.abort(),r):null,c={method:"POST",credentials:b()?"same-origin":"omit",signal:s?s.signal:void 0};if(typeof FormData!="undefined"&&t instanceof FormData?c.body=t:t!=null&&(c.headers={"Content-Type":"text/plain"},c.body=JSON.stringify(t)),!y.fetch)throw new m(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await y.fetch(e,c)}catch(S){throw u&&clearTimeout(u),S&&S.name==="AbortError"?new m(a.TIMEOUT,"请求超时,请重试"):new m(a.NETWORK,"网络异常,请检查网络后重试")}u&&clearTimeout(u);const l=await f.text();let g=null;if(l)try{g=JSON.parse(l)}catch(S){g=null}if(!f.ok)throw new m(String(f.status),g&&g.message||l||"请求失败");if(!g||g.code===null||g.code===void 0)throw new m("500","响应格式异常");return g.code=String(g.code),g}const Ge="dplugin-auth",Ye=1,G="keys",oe="sso",re="domain",Be={name:"ECDSA",namedCurve:"P-256"},He={name:"ECDSA",hash:"SHA-256"},Y=new Map;let B=null;function H(){if(!y.subtle){const e=typeof location!="undefined"&&location.origin?location.origin:"(未知 origin)";throw new Error("[dplugin/core] crypto.subtle 不存在:浏览器只在**安全上下文**里提供它(https、http://localhost、http://127.0.0.1、http://[::1]、file://);当前 origin="+e)}return y.subtle}function Ve(){return B||(B=new Promise(e=>{if(!y.idbOpen){e(null);return}let t;try{t=y.idbOpen(Ge,Ye)}catch(n){e(null);return}t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(G)||n.createObjectStore(G)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),B)}function me(e,t){return Ve().then(n=>n?new Promise(o=>{let r;try{r=n.transaction(G,e)}catch(c){o(null);return}const s=r.objectStore(G);let u=null;try{const c=t(s);c&&(c.onsuccess=()=>{u=c.result},c.onerror=()=>{u=null})}catch(c){u=null}r.oncomplete=()=>o(u),r.onerror=()=>o(null),r.onabort=()=>o(null)}):null)}function Ee(e){return Y.has(e)?Promise.resolve(Y.get(e)):me("readonly",t=>t.get(e)).then(t=>(t&&Y.set(e,t),t||null))}function ye(e,t){return Y.set(e,t),me("readwrite",n=>n.put(t,e)).then(()=>t)}async function ie(e){const n=await H().generateKey(Be,!1,["sign","verify"]);return ye(e,n)}async function Oe(e){return Ee(e)}async function be(e,t){return t?ye(e,t):null}async function Xe(e){return await Ee(e)||ie(e)}function We(){return ie(oe)}function ze(){return ie(re)}function se(){return Oe(oe)}function Se(){return Oe(re)}async function ce(e){const n=await H().exportKey("spki",e.publicKey);let o="";const r=new Uint8Array(n);for(let s=0;s<r.length;s++)o+=String.fromCharCode(r[s]);return btoa(o)}function Ie(e){const t=new Uint8Array(e);let n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qe(e,t){const o=await H().sign(He,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=H(),n=await t.exportKey("spki",e.publicKey),o=await t.digest("SHA-256",n);return Ie(o)}const ae={SSO:oe,DOMAIN:re},ue="-",Ze="POST",A={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function E(e){return e==null||e===""?ue:String(e)}function $e(e,t){const n=E(t.origin);return[E(e),E(t.method),E(t.path),n===ue?ue:n.toLowerCase(),E(t.ds),E(t.ts),E(t.subject),E(t.dna),E(t.redirect)].join(`
|
|
2
|
+
`)}function Je(e,t,n){return[E(e),E(t.subject),E(t.ds),E(t.ts),n].join(".")}async function K(e,t,n){const o=n==="sso"?await se():await Se();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await qe(o,$e(e,t));return Je(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await K(A.BIZ,{method:Ze,path:j(e),origin:C(),ds:n,ts:Date.now(),subject:t},"domain");return"dsign="+encodeURIComponent(o)}function C(){if(typeof location=="undefined")return"";if(location.origin)return location.origin.toLowerCase();try{return new URL(location.href).origin.toLowerCase()}catch(e){return""}}function Pe(e){const t=new Error(e);return t.code="KEY_MISSING",t}function Qe(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:et(e),device_model:tt(e),browser_name:nt(e),browser_version:ot(e),os_name:rt(e),os_version:it(e)},n=i.ds;return n&&(t.device_id=n),t}function D(e,t){const n=e.match(t);return n?n[1]:""}function et(e){return/iPhone|iPad|iPod/.test(e)?"Apple":/Huawei|HONOR/i.test(e)?"Huawei":/Xiaomi|Redmi|POCO/i.test(e)?"Xiaomi":/OPPO|realme/i.test(e)?"OPPO":/vivo/i.test(e)?"vivo":/Samsung|SM-|SAMSUNG/i.test(e)?"Samsung":/Macintosh|Mac OS X/.test(e)?"Apple":""}function tt(e){if(/iPhone/.test(e))return"iPhone";if(/iPad/.test(e))return"iPad";const t=e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);return t?t[1].trim():/Macintosh/.test(e)?"Mac":""}function nt(e){return/MicroMessenger/i.test(e)?"WeChat":/Edg[A-Za-z]*\//.test(e)?"Edge":/OPR\/|Opera/.test(e)?"Opera":/Firefox\//.test(e)?"Firefox":/Chrome\/|CriOS\//.test(e)?"Chrome":/Safari\//.test(e)?"Safari":""}function ot(e){return/MicroMessenger\/([\d.]+)/.test(e)?D(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?D(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?D(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?D(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?D(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?D(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?D(e,/Version\/([\d.]+)/):""}function rt(e){return/Windows NT/.test(e)?"Windows":/iPhone|iPad|iPod/.test(e)?"iOS":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/HarmonyOS/.test(e)?"HarmonyOS":/Linux/.test(e)?"Linux":""}function it(e){if(/Windows NT 10\.0/.test(e))return"10/11";if(/Windows NT 6\.3/.test(e))return"8.1";if(/Windows NT 6\.1/.test(e))return"7";const t=e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);if(t)return t[1].replace(/_/g,".");if(/Android[ _]([\d.]+)/.test(e))return D(e,/Android[ _]([\d.]+)/);const n=e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);return n?n[1].replace(/_/g,"."):""}const p={SIGN:{VERIFY:"/api/unsafe/dplugin/login/s/verify",TOKEN:"/api/unsafe/dplugin/login/s/token",REFRESH:"/api/unsafe/dplugin/login/s/refresh"},COOKIE:{VERIFY:"/api/unsafe/dplugin/login/c/verify",TOKEN:"/api/unsafe/dplugin/login/c/token",REFRESH:"/api/unsafe/dplugin/login/c/refresh"},LOGOUT:"/api/safe/dplugin/login/logout"},st="dp_dvt",de=1800*1e3;let U=null,V=null,k=null,X=!1;function W(){return typeof location!="undefined"?location.href:""}function L(e){return new Promise(t=>setTimeout(t,e))}function ct(){try{localStorage.setItem("token",i.access||"cookie")}catch(e){}}function z(){ct();const e=T();typeof e.onLogin=="function"&&e.onLogin(v())}function R(e,t){return new m(e.code,e.message||t)}function at(e,t,n){if(typeof document=="undefined")return;let o=e+"="+encodeURIComponent(t)+"; path=/; SameSite=Lax";o+="; max-age="+n,document.cookie=o}function v(){return{mode:ne(),loggedIn:q(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function q(){return b()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function N(e){const t=q();le();const n=T();if(t&&typeof n.onLogout=="function"&&n.onLogout(e||"expired"),X||!n.enableAuth||!n.loginUrl||typeof location=="undefined")return;X=!0;const o=n.loginUrl.includes("?")?"&":"?";location.href=n.loginUrl+o+"referer="+encodeURIComponent(location.href)}function De(e,t){return k||(k=ft(e,t).then(n=>(k=null,n),n=>{throw k=null,ut(n),n}),k)}function ut(e){const t=T();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function ft(e,t){const n=T(),o=Qe();if(b())return gt(e,t,o,n);const r=await se(),s=await Se();try{return await dt(e,t,o,n)}catch(u){throw await be(ae.SSO,r),await be(ae.DOMAIN,s),u}}async function dt(e,t,n,o){const r=await We(),s=await ce(r),u=await w(h(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw R(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw R(u,"登录失败");const f=await ze(),l=await Te(f),g=await lt(c,o,l),S=await w(h(p.SIGN.TOKEN),{dsign:await K(A.TOKEN,{origin:C(),ts:Date.now(),subject:g.code,dna:l},"domain"),pk:await ce(f)});if(S.code!==a.OK||!S.data)throw R(S,"登录失败");return i.sid=g.sid,i.ds=S.data.ds||g.ds,i.access=S.data.token,i.exp=Date.now()+de,X=!1,z(),v()}async function lt(e,t,n){const o=W(),r=Math.max(1,Number(t.pollMax)||5);for(let s=1;s<=r;s++){const u=i.ds||null,c=Date.now(),f=await K(A.VERIFY,{method:"POST",path:j(p.SIGN.VERIFY),origin:C(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let l;try{l=await w(h(p.SIGN.VERIFY),{dsign:f,dna:n,redirect:o})}catch(g){if((g.code===a.NETWORK||g.code===a.TIMEOUT)&&s<r){await L(t.pollInterval);continue}throw g}if(l.code===a.OK&&l.data)return l.data;if(l.code===a.PENDING){if(s<r){await L(t.pollInterval);continue}break}throw R(l,"登录失败")}throw new m(a.AUTH_EXPIRED,"登录超时,请重试")}async function gt(e,t,n,o){const r=await w(h(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw R(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw R(r,"登录失败");return at(st,s,300),await ht(o),await Re(),i.cookie=!0,X=!1,z(),v()}async function ht(e){const t=W(),n=Math.max(1,Number(e.pollMax)||5);for(let o=1;o<=n;o++){let r;try{r=await w(h(p.COOKIE.VERIFY),{redirect:t})}catch(s){if((s.code===a.NETWORK||s.code===a.TIMEOUT)&&o<n){await L(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await L(e.pollInterval);continue}break}throw R(r,"登录失败")}throw new m(a.AUTH_EXPIRED,"登录超时,请重试")}async function Re(){const e=await w(h(p.COOKIE.TOKEN));if(e.code!==a.OK)throw R(e,"登录失败");return e}async function _(e){const t=!!(e&&e.force);return V||(V=(async()=>{try{return b()?await wt(t):await mt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{V=null}})()),V}async function wt(e){return!e&&i.cookie?!0:(await w(h(p.COOKIE.VERIFY),{redirect:W()})).code!==a.OK||(await Re()).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,z(),!0)}async function pt(){if(!i.sid||!i.ds||!await se())return!1;const t=i.ds,n=await Xe(ae.DOMAIN),o=await Te(n),r=W(),s=await K(A.VERIFY_SID,{method:"POST",path:j(p.SIGN.VERIFY),origin:C(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await w(h(p.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await w(h(p.SIGN.TOKEN),{dsign:await K(A.TOKEN,{origin:C(),ts:Date.now(),subject:u.data.code,dna:o},"domain"),pk:await ce(n)});return c.code!==a.OK||!c.data?!1:(i.access=c.data.token,c.data.ds&&(i.ds=c.data.ds),i.exp=Date.now()+de,z(),!0)}async function mt(e){return!e&&i.access?!0:pt()}function ge(){return U||(U=(b()?Et():yt()).then(e=>(U=null,e),e=>{throw U=null,e})),U}async function Et(){const e=await w(h(p.COOKIE.REFRESH));if(e.code===a.OK)return!0;if(e.code===a.AUTH_EXPIRED)throw new O(e.message);if(e.code==="500"&&/重复/.test(e.message||""))return await L(800),!0;throw new m(e.code,e.message)}async function yt(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await K(A.BIZ,{method:"POST",path:j(p.SIGN.REFRESH),origin:C(),ds:t,ts:Date.now(),subject:e},"domain"),o=await w(h(p.SIGN.REFRESH,"dsign="+encodeURIComponent(n)));if(o.code===a.OK&&o.data)return i.access=o.data.token,o.data.ds&&(i.ds=o.data.ds),i.exp=Date.now()+de,i.access;const r=await Ot(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(o.message):new m(o.code,o.message)}function Ot(e,t){const n=Date.now()+t;return new Promise(o=>{const r=()=>{const s=i.access;if(s&&s!==e){o(s);return}if(Date.now()>=n){o(null);return}setTimeout(r,150)};r()})}async function Ne(){try{let t=await Ae();t.code===a.AUTH_EXPIRED&&(await ge(),t=await Ae())}catch(t){}le();const e=T();typeof e.onLogout=="function"&&e.onLogout("logout")}async function Ae(){if(b())return w(h(p.LOGOUT));const e=await fe(p.LOGOUT,i.access,i.ds);return w(h(p.LOGOUT,e))}async function bt(e,t,n){const o=St(t,n);return o.authed&&await Ke(),Z(e,o.body,o.options,!1)}function St(e,t){const n=t||{};return!(typeof FormData!="undefined"&&e instanceof FormData)&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&("data"in e||"noToken"in e||"loading"in e||"error"in e)?{body:e.data,options:Object.assign({},e,n),authed:e.noToken!==!0&&n.auth!==!1}:{body:e,options:n,authed:n.auth!==!1}}async function Ke(){if(b()){if(i.cookie||await _())return;throw N("expired"),new O}if(!i.access&&!await _())throw N("expired"),new O}async function Z(e,t,n,o){const r=n.auth!==!1&&n.noToken!==!0,s=r&&!b();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(l){if(!o&&await _({force:!0}))return Z(e,t,n,!0);throw N("expired"),new O}}const f=await w(h(e,u),t,n.timeout);if(f.code===a.OK)return f;if(r&&f.code===a.AUTH_EXPIRED&&!o){if(s&&c&&i.access!==c)return Z(e,t,n,!0);try{await ge()}catch(l){throw l instanceof O&&N("expired"),l}return Z(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(N("expired"),new O(f.message)):Ce(f)}function Ce(e){const t=new m(e.code,e.message),n=T();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function It(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ke(),he(e,t,n,o||{},!1)}async function he(e,t,n,o,r){let s="";if(!b())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await _({force:!0}))return he(e,t,n,o,!0);throw N("expired"),new O}const u=new FormData;Object.keys(n||{}).forEach(f=>{const l=n[f];l!=null&&u.append(f,l)}),u.append("file",t);const c=await w(h(e,s),u,o.timeout);if(c.code===a.OK)return c;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof O&&N("expired"),f}return he(e,t,n,o,!0)}throw Ce(c)}function Tt(e){const t=ke(e);if(je(),t.nativeGuard!=="off"){const n=Me();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const Pt={login:De,logout:Ne,isLogin:q,getState:v,restore:_,setAuthData(){},jump(){return Promise.reject(new Error("[dplugin/core] jump 已下线,请改为同源部署"))},jumpGenerate(){return Promise.reject(new Error("[dplugin/core] jumpGenerate 已下线"))}};d.AuthError=O,d.BizError=m,d.CODE=a,d.auth=Pt,d.clear=le,d.expire=N,d.getMode=ne,d.getState=v,d.isAuthError=Ue,d.isLogin=q,d.login=De,d.logout=Ne,d.request=bt,d.setup=Tt,d.store=i,d.upload=It,d.verifyLogin=_,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
|
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|