@dplugin/core 2.0.10 → 2.0.12

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.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 Ce(e){return e&&Object.keys(I).forEach(t=>{e[t]!==void 0&&(I[t]=e[t])}),I}function T(){return I}const O=Me();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 Me(){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 Ue(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return O.fetch&&!O.pristine.fetch&&e.push("fetch"),O.idbOpen&&!O.pristine.idbOpen&&e.push("indexedDB.open"),O.subtle&&!O.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 E extends Error{constructor(t,n){super(n||"请求失败"),this.name="BizError",this.code=t}}class y extends E{constructor(t){super(a.AUTH_EXPIRED,t||"登录已失效"),this.name="AuthError"}}function xe(e){return e instanceof y||e&&e.code===a.AUTH_EXPIRED}const J="dplugin.access",Q="dplugin.sid",he="dplugin.ds",ee="dplugin.exp",te="dplugin.cookie";function ke(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 U(e){const t=ke(e);return t===null?F[e]===void 0?null:F[e]:t}function x(e,t){F[e]=t,pe(e,t)}const i={get access(){return U(J)},set access(e){x(J,e)},get sid(){return U(Q)},set sid(e){x(Q,e)},get ds(){return U(he)},set ds(e){x(he,e)},get exp(){const e=U(ee);return e?Number(e):0},set exp(e){x(ee,e?String(e):null)},get cookie(){return U(te)==="1"},set cookie(e){x(te,e?"1":null)},clear(){[J,Q,ee,te].forEach(e=>{F[e]=null,pe(e,null)})}};function w(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 H(e){const t=w(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 ve(e){try{const t=typeof location!="undefined"?location.href:void 0;return new URL(e||"",t).origin}catch(t){return null}}function Le(){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=ve(e.apiBase||t);return P=n&&n===t?"cookie":"sign",P}function b(){return ne()==="cookie"}async function h(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)),!O.fetch)throw new E(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await O.fetch(e,c)}catch(S){throw u&&clearTimeout(u),S&&S.name==="AbortError"?new E(a.TIMEOUT,"请求超时,请重试"):new E(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 E(String(f.status),g&&g.message||l||"请求失败");if(!g||g.code===null||g.code===void 0)throw new E("500","响应格式异常");return g.code=String(g.code),g}const Fe="dplugin-auth",He=1,B="keys",oe="sso",re="domain",Be={name:"ECDSA",namedCurve:"P-256"},Ge={name:"ECDSA",hash:"SHA-256"},G=new Map;let Y=null;function j(){if(!O.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 O.subtle}function Ye(){return Y||(Y=new Promise(e=>{if(!O.idbOpen){e(null);return}let t;try{t=O.idbOpen(Fe,He)}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)}),Y)}function Ee(e,t){return Ye().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 me(e){return G.has(e)?Promise.resolve(G.get(e)):Ee("readonly",t=>t.get(e)).then(t=>(t&&G.set(e,t),t||null))}function Oe(e,t){return G.set(e,t),Ee("readwrite",n=>n.put(t,e)).then(()=>t)}async function ie(e){const n=await j().generateKey(Be,!1,["sign","verify"]);return Oe(e,n)}async function ye(e){return me(e)}async function be(e,t){return t?Oe(e,t):null}async function je(e){return await me(e)||ie(e)}function Ve(){return ie(oe)}function Xe(){return ie(re)}function se(){return ye(oe)}function Se(){return ye(re)}async function ce(e){const n=await j().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 We(e,t){const o=await j().sign(Ge,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=j(),n=await t.exportKey("spki",e.publicKey),o=await t.digest("SHA-256",n);return Ie(o)}const ae={SSO:oe,DOMAIN:re},ue="-",qe="POST",A={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function m(e){return e==null||e===""?ue:String(e)}function ze(e,t){const n=m(t.origin);return[m(e),m(t.method),m(t.path),n===ue?ue:n.toLowerCase(),m(t.ds),m(t.ts),m(t.subject),m(t.dna),m(t.redirect)].join(`
2
- `)}function Ze(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 We(o,ze(e,t));return Ze(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await K(A.BIZ,{method:qe,path:H(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 $e(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:Je(e),device_model:Qe(e),browser_name:et(e),browser_version:tt(e),os_name:nt(e),os_version:ot(e)},n=i.ds;return n&&(t.device_id=n),t}function R(e,t){const n=e.match(t);return n?n[1]:""}function Je(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 Qe(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 et(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 tt(e){return/MicroMessenger\/([\d.]+)/.test(e)?R(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?R(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?R(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?R(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?R(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?R(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?R(e,/Version\/([\d.]+)/):""}function nt(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 ot(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 R(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"},de=1800*1e3;let k=null,V=null,_=null,X=!1;function W(){return typeof location!="undefined"?location.href:""}function v(e){return new Promise(t=>setTimeout(t,e))}function q(){const e=T();typeof e.onLogin=="function"&&e.onLogin(L())}function N(e,t){return new E(e.code,e.message||t)}function L(){return{mode:ne(),loggedIn:z(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function z(){return b()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function D(e){const t=z();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 Re(e,t){return _||(_=it(e,t).then(n=>(_=null,n),n=>{throw _=null,rt(n),n}),_)}function rt(e){const t=T();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function it(e,t){const n=T(),o=$e();if(b())return at(e,t,o,n);const r=await se(),s=await Se();try{return await st(e,t,o,n)}catch(u){throw await be(ae.SSO,r),await be(ae.DOMAIN,s),u}}async function st(e,t,n,o){const r=await Ve(),s=await ce(r),u=await h(w(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw N(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw N(u,"登录失败");const f=await Xe(),l=await Te(f),g=await ct(c,o,l),S=await h(w(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 N(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,q(),L()}async function ct(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:H(p.SIGN.VERIFY),origin:C(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let l;try{l=await h(w(p.SIGN.VERIFY),{dsign:f,dna:n,redirect:o})}catch(g){if((g.code===a.NETWORK||g.code===a.TIMEOUT)&&s<r){await v(t.pollInterval);continue}throw g}if(l.code===a.OK&&l.data)return l.data;if(l.code===a.PENDING){if(s<r){await v(t.pollInterval);continue}break}throw N(l,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function at(e,t,n,o){const r=await h(w(e),Object.assign({},t,{device:n}));if(r.code!==a.OK||!(r.data&&r.data.token))throw N(r,"登录失败");return await ut(o),i.cookie=!0,X=!1,q(),L()}async function ut(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(w(p.COOKIE.VERIFY),{redirect:t})}catch(s){if((s.code===a.NETWORK||s.code===a.TIMEOUT)&&o<n){await v(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await v(e.pollInterval);continue}break}throw N(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function M(e){const t=!!(e&&e.force);return V||(V=(async()=>{try{return b()?await ft(t):await lt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{V=null}})()),V}async function ft(e){return!e&&i.cookie?!0:(await h(w(p.COOKIE.VERIFY),{redirect:W()})).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,q(),!0)}async function dt(){if(!i.sid||!i.ds||!await se())return!1;const t=i.ds,n=await je(ae.DOMAIN),o=await Te(n),r=W(),s=await K(A.VERIFY_SID,{method:"POST",path:H(p.SIGN.VERIFY),origin:C(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await h(w(p.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await h(w(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,q(),!0)}async function lt(e){return!e&&i.access?!0:dt()}function ge(){return k||(k=(b()?gt():wt()).then(e=>(k=null,e),e=>{throw k=null,e})),k}async function gt(){const e=await h(w(p.COOKIE.TOKEN));if(e.code===a.OK)return!0;const t=await h(w(p.COOKIE.REFRESH));if(t.code===a.OK)return!0;if(t.code===a.AUTH_EXPIRED||e.code===a.AUTH_EXPIRED)throw new y(t.message||e.message);if(t.code==="500"&&/重复/.test(t.message||""))return await v(800),!0;throw new E(t.code,t.message)}async function wt(){const e=i.access,t=i.ds;if(!e||!t)throw new y;const n=await K(A.BIZ,{method:"POST",path:H(p.SIGN.REFRESH),origin:C(),ds:t,ts:Date.now(),subject:e},"domain"),o=await h(w(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 ht(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new y(o.message):new E(o.code,o.message)}function ht(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 De(){try{let t=await Ne();t.code===a.AUTH_EXPIRED&&(await ge(),t=await Ne())}catch(t){}le();const e=T();typeof e.onLogout=="function"&&e.onLogout("logout")}async function Ne(){if(b())return h(w(p.LOGOUT));const e=await fe(p.LOGOUT,i.access,i.ds);return h(w(p.LOGOUT,e))}async function pt(e,t,n){const o=n||{};return o.auth!==!1&&await Ae(),Z(e,t||{},o,!1)}async function Ae(){if(b()){if(i.cookie||await M())return;throw D("expired"),new y}if(!i.access&&!await M())throw D("expired"),new y}async function Z(e,t,n,o){const r=n.auth!==!1,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 M({force:!0}))return Z(e,t,n,!0);throw D("expired"),new y}}const f=await h(w(e,u),t,n.timeout);if(f.code===a.OK)return f.data;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 y&&D("expired"),l}return Z(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(D("expired"),new y(f.message)):Ke(f,n)}function Ke(e,t){const n=new E(e.code,e.message),o=T();return o.onError&&!(t&&t.silent)&&o.onError({code:e.code,message:e.message,error:n}),n}async function Et(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ae(),we(e,t,n,o||{},!1)}async function we(e,t,n,o,r){let s="";if(!b())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await M({force:!0}))return we(e,t,n,o,!0);throw D("expired"),new y}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 h(w(e,s),u,o.timeout);if(c.code===a.OK)return c.data;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof y&&D("expired"),f}return we(e,t,n,o,!0)}throw Ke(c,o)}function mt(e){const t=Ce(e);if(Le(),t.nativeGuard!=="off"){const n=Ue();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const Ot={login:Re,logout:De,isLogin:z,getState:L,restore:M};d.AuthError=y,d.BizError=E,d.CODE=a,d.auth=Ot,d.clear=le,d.expire=D,d.getMode=ne,d.getState=L,d.isAuthError=xe,d.isLogin=z,d.login=Re,d.logout=De,d.request=pt,d.setup=mt,d.store=i,d.upload=Et,d.verifyLogin=M,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 _e(e){return e&&Object.keys(I).forEach(t=>{e[t]!==void 0&&(I[t]=e[t])}),I}function T(){return I}const O=Me();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 Ue(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 Me(){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||Ue(()=>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 xe(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return O.fetch&&!O.pristine.fetch&&e.push("fetch"),O.idbOpen&&!O.pristine.idbOpen&&e.push("indexedDB.open"),O.subtle&&!O.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 E extends Error{constructor(t,n){super(n||"请求失败"),this.name="BizError",this.code=t}}class y extends E{constructor(t){super(a.AUTH_EXPIRED,t||"登录已失效"),this.name="AuthError"}}function ke(e){return e instanceof y||e&&e.code===a.AUTH_EXPIRED}const $="dplugin.access",J="dplugin.sid",he="dplugin.ds",Q="dplugin.exp",ee="dplugin.cookie";function Le(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 M(e){const t=Le(e);return t===null?F[e]===void 0?null:F[e]:t}function x(e,t){F[e]=t,pe(e,t)}const i={get access(){return M($)},set access(e){x($,e)},get sid(){return M(J)},set sid(e){x(J,e)},get ds(){return M(he)},set ds(e){x(he,e)},get exp(){const e=M(Q);return e?Number(e):0},set exp(e){x(Q,e?String(e):null)},get cookie(){return M(ee)==="1"},set cookie(e){x(ee,e?"1":null)},clear(){[$,J,Q,ee].forEach(e=>{F[e]=null,pe(e,null)})}};function w(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 H(e){const t=w(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 ve(e){try{const t=typeof location!="undefined"?location.href:void 0;return new URL(e||"",t).origin}catch(t){return null}}function Fe(){P=null}function te(){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=ve(e.apiBase||t);return P=n&&n===t?"cookie":"sign",P}function b(){return te()==="cookie"}async function h(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)),!O.fetch)throw new E(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await O.fetch(e,c)}catch(S){throw u&&clearTimeout(u),S&&S.name==="AbortError"?new E(a.TIMEOUT,"请求超时,请重试"):new E(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 E(String(f.status),g&&g.message||l||"请求失败");if(!g||g.code===null||g.code===void 0)throw new E("500","响应格式异常");return g.code=String(g.code),g}const He="dplugin-auth",Be=1,B="keys",ne="sso",oe="domain",Ge={name:"ECDSA",namedCurve:"P-256"},Ye={name:"ECDSA",hash:"SHA-256"},G=new Map;let Y=null;function j(){if(!O.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 O.subtle}function je(){return Y||(Y=new Promise(e=>{if(!O.idbOpen){e(null);return}let t;try{t=O.idbOpen(He,Be)}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)}),Y)}function Ee(e,t){return je().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 me(e){return G.has(e)?Promise.resolve(G.get(e)):Ee("readonly",t=>t.get(e)).then(t=>(t&&G.set(e,t),t||null))}function Oe(e,t){return G.set(e,t),Ee("readwrite",n=>n.put(t,e)).then(()=>t)}async function re(e){const n=await j().generateKey(Ge,!1,["sign","verify"]);return Oe(e,n)}async function ye(e){return me(e)}async function be(e,t){return t?Oe(e,t):null}async function Ve(e){return await me(e)||re(e)}function Xe(){return re(ne)}function We(){return re(oe)}function ie(){return ye(ne)}function Se(){return ye(oe)}async function se(e){const n=await j().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 j().sign(Ye,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=j(),n=await t.exportKey("spki",e.publicKey),o=await t.digest("SHA-256",n);return Ie(o)}const ce={SSO:ne,DOMAIN:oe},ae="-",ze="POST",N={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function m(e){return e==null||e===""?ae:String(e)}function Ze(e,t){const n=m(t.origin);return[m(e),m(t.method),m(t.path),n===ae?ae:n.toLowerCase(),m(t.ds),m(t.ts),m(t.subject),m(t.dna),m(t.redirect)].join(`
2
+ `)}function $e(e,t,n){return[m(e),m(t.subject),m(t.ds),m(t.ts),n].join(".")}async function A(e,t,n){const o=n==="sso"?await ie():await Se();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await qe(o,Ze(e,t));return $e(e,t,r)}async function ue(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await A(N.BIZ,{method:ze,path:H(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 R(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)?R(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?R(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?R(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?R(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?R(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?R(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?R(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 R(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"},fe=1800*1e3;let k=null,V=null,C=null,X=!1;function de(){return typeof location!="undefined"?location.href:""}function Re(){if(typeof location=="undefined")return"";try{const e=new URLSearchParams(location.search).get("referer");if(e)return decodeURIComponent(e)}catch(e){}return de()}function L(e){return new Promise(t=>setTimeout(t,e))}function W(){const e=T();typeof e.onLogin=="function"&&e.onLogin(v())}function _(e,t){return new E(e.code,e.message||t)}function v(){return{mode:te(),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=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 C||(C=st(e,t).then(n=>(C=null,n),n=>{throw C=null,it(n),n}),C)}function it(e){const t=T();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function st(e,t){const n=T(),o=Je();if(b())return ut(e,t,o,n);const r=await ie(),s=await Se();try{return await ct(e,t,o,n)}catch(u){throw await be(ce.SSO,r),await be(ce.DOMAIN,s),u}}async function ct(e,t,n,o){const r=await Xe(),s=await se(r),u=await h(w(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw _(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw _(u,"登录失败");const f=await We(),l=await Te(f),g=await at(c,o,l),S=await h(w(p.SIGN.TOKEN),{dsign:await A(N.TOKEN,{origin:K(),ts:Date.now(),subject:g.code,dna:l},"domain"),pk:await se(f)});if(S.code!==a.OK||!S.data)throw _(S,"登录失败");return i.sid=g.sid,i.ds=S.data.ds||g.ds,i.access=S.data.token,i.exp=Date.now()+fe,X=!1,W(),v()}async function at(e,t,n){const o=de(),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:H(p.SIGN.VERIFY),origin:K(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let l;try{l=await h(w(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 _(l,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function ut(e,t,n,o){const r=await h(w(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw _(r,"登录失败");return await ft(o),i.cookie=!0,X=!1,W(),v()}async function ft(e){const t=Re(),n=Math.max(1,Number(e.pollMax)||5);for(let o=1;o<=n;o++){let r;try{r=await h(w(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,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function U(e){const t=!!(e&&e.force);return V||(V=(async()=>{try{return b()?await dt(t):await gt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{V=null}})()),V}async function dt(e){return!e&&i.cookie?!0:(await h(w(p.COOKIE.VERIFY),{redirect:Re()})).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,W(),!0)}async function lt(){if(!i.sid||!i.ds||!await ie())return!1;const t=i.ds,n=await Ve(ce.DOMAIN),o=await Te(n),r=de(),s=await A(N.VERIFY_SID,{method:"POST",path:H(p.SIGN.VERIFY),origin:K(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await h(w(p.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await h(w(p.SIGN.TOKEN),{dsign:await A(N.TOKEN,{origin:K(),ts:Date.now(),subject:u.data.code,dna:o},"domain"),pk:await se(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()+fe,W(),!0)}async function gt(e){return!e&&i.access?!0:lt()}function ge(){return k||(k=(b()?wt():ht()).then(e=>(k=null,e),e=>{throw k=null,e})),k}async function wt(){const e=await h(w(p.COOKIE.TOKEN));if(e.code===a.OK)return!0;const t=await h(w(p.COOKIE.REFRESH));if(t.code===a.OK)return!0;if(t.code===a.AUTH_EXPIRED||e.code===a.AUTH_EXPIRED)throw new y(t.message||e.message);if(t.code==="500"&&/重复/.test(t.message||""))return await L(800),!0;throw new E(t.code,t.message)}async function ht(){const e=i.access,t=i.ds;if(!e||!t)throw new y;const n=await A(N.BIZ,{method:"POST",path:H(p.SIGN.REFRESH),origin:K(),ds:t,ts:Date.now(),subject:e},"domain"),o=await h(w(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()+fe,i.access;const r=await pt(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new y(o.message):new E(o.code,o.message)}function pt(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 h(w(p.LOGOUT));const e=await ue(p.LOGOUT,i.access,i.ds);return h(w(p.LOGOUT,e))}async function Et(e,t,n){const o=n||{};return o.auth!==!1&&await Ke(),z(e,t||{},o,!1)}async function Ke(){if(b()){if(i.cookie||await U())return;throw D("expired"),new y}if(!i.access&&!await U())throw D("expired"),new y}async function z(e,t,n,o){const r=n.auth!==!1,s=r&&!b();let u="",c=null;if(s){c=i.access;try{u=await ue(e,c,i.ds)}catch(l){if(!o&&await U({force:!0}))return z(e,t,n,!0);throw D("expired"),new y}}const f=await h(w(e,u),t,n.timeout);if(f.code===a.OK)return f.data;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 y&&D("expired"),l}return z(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(D("expired"),new y(f.message)):Ce(f,n)}function Ce(e,t){const n=new E(e.code,e.message),o=T();return o.onError&&!(t&&t.silent)&&o.onError({code:e.code,message:e.message,error:n}),n}async function mt(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ke(),we(e,t,n,o||{},!1)}async function we(e,t,n,o,r){let s="";if(!b())try{s=await ue(e,i.access,i.ds)}catch(f){if(!r&&await U({force:!0}))return we(e,t,n,o,!0);throw D("expired"),new y}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 h(w(e,s),u,o.timeout);if(c.code===a.OK)return c.data;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof y&&D("expired"),f}return we(e,t,n,o,!0)}throw Ce(c,o)}function Ot(e){const t=_e(e);if(Fe(),t.nativeGuard!=="off"){const n=xe();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const yt={login:De,logout:Ne,isLogin:q,getState:v,restore:U};d.AuthError=y,d.BizError=E,d.CODE=a,d.auth=yt,d.clear=le,d.expire=D,d.getMode=te,d.getState=v,d.isAuthError=ke,d.isLogin=q,d.login=De,d.logout=Ne,d.request=Et,d.setup=Ot,d.store=i,d.upload=mt,d.verifyLogin=U,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
3
3
  //# sourceMappingURL=index.umd.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dplugin/core",
3
- "version": "2.0.10",
3
+ "version": "2.0.12",
4
4
  "description": "DPlugin 前端登录与请求 SDK(同域 Cookie + 跨域 ECDSA 双模式)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",