@dplugin/core 2.0.4 → 2.0.6

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 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 E extends Error{constructor(t,n){super(n||"请求失败"),this.name="BizError",this.code=t}}class O extends E{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 Y(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 Ye(){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 E(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await y.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 Ge="dplugin-auth",Be=1,G="keys",oe="sso",re="domain",He={name:"ECDSA",namedCurve:"P-256"},je={name:"ECDSA",hash:"SHA-256"},B=new Map;let H=null;function j(){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 H||(H=new Promise(e=>{if(!y.idbOpen){e(null);return}let t;try{t=y.idbOpen(Ge,Be)}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)}),H)}function Ee(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 me(e){return B.has(e)?Promise.resolve(B.get(e)):Ee("readonly",t=>t.get(e)).then(t=>(t&&B.set(e,t),t||null))}function ye(e,t){return B.set(e,t),Ee("readwrite",n=>n.put(t,e)).then(()=>t)}async function ie(e){const n=await j().generateKey(He,!1,["sign","verify"]);return ye(e,n)}async function Oe(e){return me(e)}async function be(e,t){return t?ye(e,t):null}async function Xe(e){return await me(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 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(je,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="-",Ze="POST",A={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function m(e){return e==null||e===""?ue:String(e)}function $e(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 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 _e(e){return e&&Object.keys(I).forEach(t=>{e[t]!==void 0&&(I[t]=e[t])}),I}function T(){return I}const O=ke();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 xe(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=$(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||xe(()=>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 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 Ue(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 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 k(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 k(J)},set access(e){M(J,e)},get sid(){return k(Q)},set sid(e){M(Q,e)},get ds(){return k(he)},set ds(e){M(he,e)},get exp(){const e=k(ee);return e?Number(e):0},set exp(e){M(ee,e?String(e):null)},get cookie(){return k(te)==="1"},set cookie(e){M(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 B(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 Le(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 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=Le(e.apiBase||t);return P=n&&n===t?"cookie":"sign",P}function S(){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:S()?"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(b){throw u&&clearTimeout(u),b&&b.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(b){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 Be="dplugin-auth",Ge=1,G="keys",oe="sso",re="domain",He={name:"ECDSA",namedCurve:"P-256"},Ye={name:"ECDSA",hash:"SHA-256"},H=new Map;let Y=null;function V(){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 Ve(){return Y||(Y=new Promise(e=>{if(!O.idbOpen){e(null);return}let t;try{t=O.idbOpen(Be,Ge)}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)}),Y)}function Ee(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 me(e){return H.has(e)?Promise.resolve(H.get(e)):Ee("readonly",t=>t.get(e)).then(t=>(t&&H.set(e,t),t||null))}function Oe(e,t){return H.set(e,t),Ee("readwrite",n=>n.put(t,e)).then(()=>t)}async function ie(e){const n=await V().generateKey(He,!1,["sign","verify"]);return Oe(e,n)}async function ye(e){return me(e)}async function Se(e,t){return t?Oe(e,t):null}async function je(e){return await me(e)||ie(e)}function Xe(){return ie(oe)}function We(){return ie(re)}function se(){return ye(oe)}function be(){return ye(re)}async function ce(e){const n=await V().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 V().sign(Ye,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=V(),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",K={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 $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 se():await be();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await qe(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(K.BIZ,{method:ze,path:B(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 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"},it="dp_dvt",de=1800*1e3;let U=null,j=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 D(e,t){return new E(e.code,e.message||t)}function st(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:ne(),loggedIn:z(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function z(){return S()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function N(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 _||(_=at(e,t).then(n=>(_=null,n),n=>{throw _=null,ct(n),n}),_)}function ct(e){const t=T();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function at(e,t){const n=T(),o=Je();if(S())return dt(e,t,o,n);const r=await se(),s=await be();try{return await ut(e,t,o,n)}catch(u){throw await Se(ae.SSO,r),await Se(ae.DOMAIN,s),u}}async function ut(e,t,n,o){const r=await Xe(),s=await ce(r),u=await h(w(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw D(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw D(u,"登录失败");const f=await We(),l=await Te(f),g=await ft(c,o,l),b=await h(w(p.SIGN.TOKEN),{dsign:await A(K.TOKEN,{origin:C(),ts:Date.now(),subject:g.code,dna:l},"domain"),pk:await ce(f)});if(b.code!==a.OK||!b.data)throw D(b,"登录失败");return i.sid=g.sid,i.ds=b.data.ds||g.ds,i.access=b.data.token,i.exp=Date.now()+de,X=!1,q(),L()}async function ft(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(K.VERIFY,{method:"POST",path:B(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 D(l,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function dt(e,t,n,o){const r=await h(w(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw D(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw D(r,"登录失败");return st(it,s,300),await lt(o),await De(),i.cookie=!0,X=!1,q(),L()}async function lt(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 D(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function De(){const e=await h(w(p.COOKIE.TOKEN));if(e.code!==a.OK)throw D(e,"登录失败");return e}async function x(e){const t=!!(e&&e.force);return j||(j=(async()=>{try{return S()?await gt(t):await ht(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{j=null}})()),j}async function gt(e){return!e&&i.cookie?!0:(await h(w(p.COOKIE.VERIFY),{redirect:W()})).code!==a.OK||(await De()).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,q(),!0)}async function wt(){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 A(K.VERIFY_SID,{method:"POST",path:B(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 A(K.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 ht(e){return!e&&i.access?!0:wt()}function ge(){return U||(U=(S()?pt():Et()).then(e=>(U=null,e),e=>{throw U=null,e})),U}async function pt(){const e=await h(w(p.COOKIE.REFRESH));if(e.code===a.OK)return!0;if(e.code===a.AUTH_EXPIRED)throw new y(e.message);if(e.code==="500"&&/重复/.test(e.message||""))return await v(800),!0;throw new E(e.code,e.message)}async function Et(){const e=i.access,t=i.ds;if(!e||!t)throw new y;const n=await A(K.BIZ,{method:"POST",path:B(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 mt(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new y(o.message):new E(o.code,o.message)}function mt(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 Ke();t.code===a.AUTH_EXPIRED&&(await ge(),t=await Ke())}catch(t){}le();const e=T();typeof e.onLogout=="function"&&e.onLogout("logout")}async function Ke(){if(S())return h(w(p.LOGOUT));const e=await fe(p.LOGOUT,i.access,i.ds);return h(w(p.LOGOUT,e))}async function Ot(e,t,n){const o=n||{};return o.auth!==!1&&await Ae(),Z(e,t||{},o,!1)}async function Ae(){if(S()){if(i.cookie||await x())return;throw N("expired"),new y}if(!i.access&&!await x())throw N("expired"),new y}async function Z(e,t,n,o){const r=n.auth!==!1,s=r&&!S();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(l){if(!o&&await x({force:!0}))return Z(e,t,n,!0);throw N("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&&N("expired"),l}return Z(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(N("expired"),new y(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 yt(e,t,n,o){return(S()?!i.cookie:!i.access)&&await Ae(),we(e,t,n,o||{},!1)}async function we(e,t,n,o,r){let s="";if(!S())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await x({force:!0}))return we(e,t,n,o,!0);throw N("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&&N("expired"),f}return we(e,t,n,o,!0)}throw Ce(c)}function St(e){const t=_e(e);if(Fe(),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 bt={login:Re,logout:Ne,isLogin:z,getState:L,restore:x};d.AuthError=y,d.BizError=E,d.CODE=a,d.auth=bt,d.clear=le,d.expire=N,d.getMode=ne,d.getState=L,d.isAuthError=Ue,d.isLogin=z,d.login=Re,d.logout=Ne,d.request=Ot,d.setup=St,d.store=i,d.upload=yt,d.verifyLogin=x,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.4",
3
+ "version": "2.0.6",
4
4
  "description": "DPlugin 前端登录与请求 SDK(同域 Cookie + 跨域 ECDSA 双模式)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",