@dplugin/core 2.0.2 → 2.0.4

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 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 Ae(e){return e&&Object.keys(M).forEach(t=>{e[t]!==void 0&&(M[t]=e[t])}),M}function R(){return M}const m=_e();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 _e(){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 ke(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return m.fetch&&!m.pristine.fetch&&e.push("fetch"),m.idbOpen&&!m.pristine.idbOpen&&e.push("indexedDB.open"),m.subtle&&!m.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 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";function Ue(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ee(e,t){try{t==null||t===""?localStorage.removeItem(e):localStorage.setItem(e,t)}catch(n){}}const H={};function C(e){const t=Ue(e);return t===null?H[e]===void 0?null:H[e]:t}function _(e,t){H[e]=t,Ee(e,t)}const i={get access(){return C($)},set access(e){_($,e)},get sid(){return C(J)},set sid(e){_(J,e)},get ds(){return C(we)},set ds(e){_(we,e)},get exp(){const e=C(Q);return e?Number(e):0},set exp(e){_(Q,e?String(e):null)},get cookie(){return C(ee)==="1"},set cookie(e){_(ee,e?"1":null)},clear(){[$,J,Q,ee].forEach(e=>{H[e]=null,Ee(e,null)})}};function g(e,t){const n=R().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=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 b=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(){b=null}function ie(){if(b)return b;const e=R();if(e.mode==="sign"||e.mode==="cookie")return b=e.mode,b;const t=typeof location!="undefined"?location.origin:null;if(!t)return b="sign",b;const n=ve(e.apiBase||t);return b=n&&n===t?"cookie":"sign",b}function S(){return ie()==="cookie"}async function h(e,t,n){const o=R(),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)),!m.fetch)throw new E(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await m.fetch(e,c)}catch(y){throw u&&clearTimeout(u),y&&y.name==="AbortError"?new E(a.TIMEOUT,"请求超时,请重试"):new E(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 E(String(f.status),l&&l.message||d||"请求失败");if(!l||l.code===null||l.code===void 0)throw new E("500","响应格式异常");return l.code=String(l.code),l}const Fe="dplugin-auth",Be=1,Y="keys",se="sso",ce="domain",Ge={name:"ECDSA",namedCurve:"P-256"},He={name:"ECDSA",hash:"SHA-256"},B=new Map;let L=null;function X(){if(!m.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 m.subtle}function Ye(){return L||(L=new Promise(e=>{if(!m.idbOpen){e(null);return}let t;try{t=m.idbOpen(Fe,Be)}catch(n){e(null);return}t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Y)||n.createObjectStore(Y)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),L)}function me(e,t){return Ye().then(n=>n?new Promise(o=>{let r;try{r=n.transaction(Y,e)}catch(c){o(null);return}const s=r.objectStore(Y);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 B.has(e)?Promise.resolve(B.get(e)):me("readonly",t=>t.get(e)).then(t=>(t&&B.set(e,t),t||null))}function ye(e,t){return B.set(e,t),me("readwrite",n=>n.put(t,e)).then(()=>t)}async function ae(e){const n=await X().generateKey(Ge,!1,["sign","verify"]);return ye(e,n)}async function Se(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 je(){return ae(se)}function Xe(){return ae(ce)}function ue(){return Se(se)}function be(){return Se(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 We(e,t){const o=await X().sign(He,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 Ze(e,t,n){return[p(e),p(t.subject),p(t.ds),p(t.ts),n].join(".")}async function x(e,t,n){const o=n==="sso"?await ue():await be();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 x(N.BIZ,{method:qe,path:j(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 $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 I(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)?I(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?I(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?I(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?I(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?I(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?I(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?I(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 I(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"},rt="dp_dvt",de=1800*1e3;let k=null,F=null,D=null,V=!1;function W(){return typeof location!="undefined"?location.href:""}function U(e){return new Promise(t=>setTimeout(t,e))}function q(){const e=R();typeof e.onLogin=="function"&&e.onLogin(v())}function T(e,t){return new E(e.code,e.message||t)}function it(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:ie(),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 P(e){const t=z();le();const n=R();if(t&&typeof n.onLogout=="function"&&n.onLogout(e||"expired"),V||!n.enableAuth||!n.loginUrl||typeof location=="undefined")return;V=!0;const o=n.loginUrl.includes("?")?"&":"?";location.href=n.loginUrl+o+"referer="+encodeURIComponent(location.href)}function Re(e,t){return D||(D=st(e,t).then(n=>(D=null,n),n=>{throw D=null,n}),D)}async function st(e,t){const n=R(),o=$e();if(S())return ut(e,t,o,n);const r=await ue(),s=await be();try{return await ct(e,t,o,n)}catch(u){throw await he(ne.SSO,r),await he(ne.DOMAIN,s),u}}async function ct(e,t,n,o){const r=await je(),s=await te(r),u=await h(g(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw T(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw T(u,"登录失败");const f=await Xe(),d=await Te(f),l=await at(c,o,d),y=await h(g(w.SIGN.TOKEN),{dsign:await x(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 T(y,"登录失败");return i.sid=l.sid,i.ds=y.data.ds||l.ds,i.access=y.data.token,i.exp=Date.now()+de,V=!1,q(),v()}async function at(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 x(N.VERIFY,{method:"POST",path:j(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 T(d,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function ut(e,t,n,o){const r=await h(g(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw T(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw T(r,"登录失败");return it(rt,s,300),await ft(o),await De(),i.cookie=!0,V=!1,q(),v()}async function ft(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 T(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function De(){const e=await h(g(w.COOKIE.TOKEN));if(e.code!==a.OK)throw T(e,"登录失败");return e}async function A(e){const t=!!(e&&e.force);return F||(F=(async()=>{try{return S()?await dt(t):await gt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{F=null}})()),F}async function dt(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,q(),!0)}async function lt(){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 x(N.VERIFY_SID,{method:"POST",path:j(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 x(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,q(),!0)}async function gt(e){return!e&&i.access?!0:lt()}function ge(){return k||(k=(S()?wt():ht()).then(e=>(k=null,e),e=>{throw k=null,e})),k}async function wt(){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 ht(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await x(N.BIZ,{method:"POST",path:j(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 pt(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(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 pe();t.code===a.AUTH_EXPIRED&&(await ge(),t=await pe())}catch(t){}le();const e=R();typeof e.onLogout=="function"&&e.onLogout("logout")}async function pe(){if(S())return h(g(w.LOGOUT));const e=await fe(w.LOGOUT,i.access,i.ds);return h(g(w.LOGOUT,e))}async function Et(e,t,n){const o=n||{};return o.auth!==!1&&await xe(),G(e,t||{},o,!1)}async function xe(){if(S()){if(i.cookie||await A())return;throw P("expired"),new O}if(!i.access&&!await A())throw P("expired"),new O}async function G(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(d){if(!o&&await A({force:!0}))return G(e,t,n,!0);throw P("expired"),new O}}const f=await h(g(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 G(e,t,n,!0);try{await ge()}catch(d){throw d instanceof O&&P("expired"),d}return G(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(P("expired"),new O(f.message)):Ke(f)}function Ke(e){const t=new E(e.code,e.message),n=R();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function mt(e,t,n,o){return(S()?!i.cookie:!i.access)&&await xe(),re(e,t,n,o||{},!1)}async function re(e,t,n,o,r){let s="";if(!S())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await A({force:!0}))return re(e,t,n,o,!0);throw P("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.data;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof O&&P("expired"),f}return re(e,t,n,o,!0)}throw Ke(c)}function Ot(e){const t=Ae(e);if(Le(),t.nativeGuard!=="off"){const n=ke();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:Re,logout:Ne,isLogin:z,getState:v,restore:A};exports.AuthError=O;exports.BizError=E;exports.CODE=a;exports.auth=yt;exports.clear=le;exports.expire=P;exports.getMode=ie;exports.getState=v;exports.isAuthError=Me;exports.isLogin=z;exports.login=Re;exports.logout=Ne;exports.request=Et;exports.setup=Ot;exports.store=i;exports.upload=mt;exports.verifyLogin=A;
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 m=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 m.fetch&&!m.pristine.fetch&&e.push("fetch"),m.idbOpen&&!m.pristine.idbOpen&&e.push("indexedDB.open"),m.subtle&&!m.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 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 Ee(e,t){try{t==null||t===""?localStorage.removeItem(e):localStorage.setItem(e,t)}catch(n){}}const B={};function C(e){const t=Le(e);return t===null?B[e]===void 0?null:B[e]:t}function k(e,t){B[e]=t,Ee(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=>{B[e]=null,Ee(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)),!m.fetch)throw new E(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await m.fetch(e,c)}catch(y){throw u&&clearTimeout(u),y&&y.name==="AbortError"?new E(a.TIMEOUT,"请求超时,请重试"):new E(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 E(String(f.status),l&&l.message||d||"请求失败");if(!l||l.code===null||l.code===void 0)throw new E("500","响应格式异常");return l.code=String(l.code),l}const Ye="dplugin-auth",Ge=1,H="keys",se="sso",ce="domain",Be={name:"ECDSA",namedCurve:"P-256"},He={name:"ECDSA",hash:"SHA-256"},Y=new Map;let v=null;function X(){if(!m.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 m.subtle}function je(){return v||(v=new Promise(e=>{if(!m.idbOpen){e(null);return}let t;try{t=m.idbOpen(Ye,Ge)}catch(n){e(null);return}t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(H)||n.createObjectStore(H)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),v)}function me(e,t){return je().then(n=>n?new Promise(o=>{let r;try{r=n.transaction(H,e)}catch(c){o(null);return}const s=r.objectStore(H);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 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 ae(e){const n=await X().generateKey(Be,!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(He,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,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;
3
3
  //# sourceMappingURL=index.cjs.map
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- const k = {
1
+ const _ = {
2
2
  // 接口前缀。'' = 同源;也可以是 https://api.company.com
3
3
  apiBase: "",
4
4
  // 运行模式:'auto' 按同源自动判定;'cookie' 强制同域 Cookie;'sign' 强制跨域签名
@@ -22,16 +22,16 @@ const k = {
22
22
  // 原生能力体检:'warn' 只告警 / 'error' 直接抛错 / 'off' 不检查
23
23
  nativeGuard: "warn"
24
24
  };
25
- function xe(e) {
26
- return e && Object.keys(k).forEach((t) => {
27
- e[t] !== void 0 && (k[t] = e[t]);
28
- }), k;
25
+ function Ke(e) {
26
+ return e && Object.keys(_).forEach((t) => {
27
+ e[t] !== void 0 && (_[t] = e[t]);
28
+ }), _;
29
29
  }
30
- function P() {
31
- return k;
30
+ function I() {
31
+ return _;
32
32
  }
33
- const E = Ae();
34
- function $(e, t) {
33
+ const m = Ae();
34
+ function Z(e, t) {
35
35
  if (typeof e != "function")
36
36
  return !1;
37
37
  let n;
@@ -43,7 +43,7 @@ function $(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 Ke(e) {
46
+ function xe(e) {
47
47
  try {
48
48
  const t = e();
49
49
  return t && typeof t.then == "function" && Promise.resolve(t).catch(() => {
@@ -60,22 +60,22 @@ function Ae() {
60
60
  subtle: null,
61
61
  pristine: { fetch: !1, idbOpen: !1, subtle: !1 }
62
62
  };
63
- 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 || Ke(() => e.indexedDB.open())), n.idbOpen = e.indexedDB.open.bind(e.indexedDB));
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 || xe(() => 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 = {};
67
67
  let a = !0;
68
68
  r.forEach((c) => {
69
- typeof o[c] == "function" && (s[c] = o[c].bind(o), a = a && $(o[c], c));
69
+ typeof o[c] == "function" && (s[c] = o[c].bind(o), a = a && Z(o[c], c));
70
70
  }), n.subtle = s, n.pristine.subtle = a;
71
71
  }
72
72
  return n;
73
73
  }
74
- function Ce() {
74
+ function ke() {
75
75
  if (typeof window == "undefined" || typeof window.document == "undefined")
76
76
  return [];
77
77
  const e = [];
78
- 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;
78
+ return m.fetch && !m.pristine.fetch && e.push("fetch"), m.idbOpen && !m.pristine.idbOpen && e.push("indexedDB.open"), m.subtle && !m.pristine.subtle && e.push("crypto.subtle"), e;
79
79
  }
80
80
  const u = {
81
81
  OK: "200",
@@ -87,20 +87,20 @@ const u = {
87
87
  NETWORK: "NETWORK",
88
88
  TIMEOUT: "TIMEOUT"
89
89
  };
90
- class m extends Error {
90
+ class E extends Error {
91
91
  constructor(t, n) {
92
92
  super(n || "请求失败"), this.name = "BizError", this.code = t;
93
93
  }
94
94
  }
95
- class O extends m {
95
+ class O extends E {
96
96
  constructor(t) {
97
97
  super(u.AUTH_EXPIRED, t || "登录已失效"), this.name = "AuthError";
98
98
  }
99
99
  }
100
- function pt(e) {
100
+ function yt(e) {
101
101
  return e instanceof O || e && e.code === u.AUTH_EXPIRED;
102
102
  }
103
- const q = "dplugin.access", z = "dplugin.sid", le = "dplugin.ds", J = "dplugin.exp", Q = "dplugin.cookie";
103
+ const $ = "dplugin.access", q = "dplugin.sid", le = "dplugin.ds", J = "dplugin.exp", Q = "dplugin.cookie", Ce = "token";
104
104
  function _e(e) {
105
105
  try {
106
106
  return localStorage.getItem(e);
@@ -114,32 +114,32 @@ function he(e, t) {
114
114
  } catch (n) {
115
115
  }
116
116
  }
117
- const H = {};
117
+ const G = {};
118
118
  function A(e) {
119
119
  const t = _e(e);
120
- return t === null ? H[e] === void 0 ? null : H[e] : t;
120
+ return t === null ? G[e] === void 0 ? null : G[e] : t;
121
121
  }
122
- function C(e, t) {
123
- H[e] = t, he(e, t);
122
+ function k(e, t) {
123
+ G[e] = t, he(e, t);
124
124
  }
125
125
  const i = {
126
126
  get access() {
127
- return A(q);
127
+ return A($);
128
128
  },
129
129
  set access(e) {
130
- C(q, e);
130
+ k($, e);
131
131
  },
132
132
  get sid() {
133
- return A(z);
133
+ return A(q);
134
134
  },
135
135
  set sid(e) {
136
- C(z, e);
136
+ k(q, e);
137
137
  },
138
138
  get ds() {
139
139
  return A(le);
140
140
  },
141
141
  set ds(e) {
142
- C(le, e);
142
+ k(le, e);
143
143
  },
144
144
  /** access 的到期时间(毫秒时间戳)。仅用于界面判断,不要拿它做提前续期 */
145
145
  get exp() {
@@ -147,14 +147,14 @@ const i = {
147
147
  return e ? Number(e) : 0;
148
148
  },
149
149
  set exp(e) {
150
- C(J, e ? String(e) : null);
150
+ k(J, e ? String(e) : null);
151
151
  },
152
152
  /** cookie 模式:本地只记「可能已登录」,实际有效性由第一次请求的结果决定 */
153
153
  get cookie() {
154
154
  return A(Q) === "1";
155
155
  },
156
156
  set cookie(e) {
157
- C(Q, e ? "1" : null);
157
+ k(Q, e ? "1" : null);
158
158
  },
159
159
  /**
160
160
  * 清登录态。
@@ -163,18 +163,18 @@ const i = {
163
163
  * 下次登录后端就会新建一条设备记录(common_login_device 无限膨胀)。
164
164
  */
165
165
  clear() {
166
- [q, z, J, Q].forEach((e) => {
167
- H[e] = null, he(e, null);
166
+ [$, q, J, Q, Ce].forEach((e) => {
167
+ G[e] = null, he(e, null);
168
168
  });
169
169
  }
170
170
  };
171
- function w(e, t) {
172
- const n = P().apiBase || "";
171
+ function g(e, t) {
172
+ const n = I().apiBase || "";
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
176
  function V(e) {
177
- const t = w(e);
177
+ const t = g(e);
178
178
  if (/^https?:\/\//i.test(t))
179
179
  try {
180
180
  return new URL(t).pathname;
@@ -187,8 +187,8 @@ function V(e) {
187
187
  return t.split("?")[0];
188
188
  }
189
189
  }
190
- let b = null;
191
- function ke(e) {
190
+ let S = null;
191
+ function Ue(e) {
192
192
  try {
193
193
  const t = typeof location != "undefined" ? location.href : void 0;
194
194
  return new URL(e || "", t).origin;
@@ -196,38 +196,38 @@ function ke(e) {
196
196
  return null;
197
197
  }
198
198
  }
199
- function Ue() {
200
- b = null;
199
+ function Me() {
200
+ S = null;
201
201
  }
202
202
  function pe() {
203
- if (b)
204
- return b;
205
- const e = P();
203
+ if (S)
204
+ return S;
205
+ const e = I();
206
206
  if (e.mode === "sign" || e.mode === "cookie")
207
- return b = e.mode, b;
207
+ return S = e.mode, S;
208
208
  const t = typeof location != "undefined" ? location.origin : null;
209
209
  if (!t)
210
- return b = "sign", b;
211
- const n = ke(e.apiBase || t);
212
- return b = n && n === t ? "cookie" : "sign", b;
210
+ return S = "sign", S;
211
+ const n = Ue(e.apiBase || t);
212
+ return S = n && n === t ? "cookie" : "sign", S;
213
213
  }
214
- function S() {
214
+ function b() {
215
215
  return pe() === "cookie";
216
216
  }
217
217
  async function h(e, t, n) {
218
- const o = P(), r = n || o.timeout, s = typeof AbortController != "undefined" ? new AbortController() : null, a = s ? setTimeout(() => s.abort(), r) : null, c = {
218
+ const o = I(), r = n || o.timeout, s = typeof AbortController != "undefined" ? new AbortController() : null, a = s ? setTimeout(() => s.abort(), r) : null, c = {
219
219
  method: "POST",
220
220
  // cookie 模式必须带上 Cookie(同源不涉及 CORS);sign 模式主动不带,减少暴露面
221
- credentials: S() ? "same-origin" : "omit",
221
+ credentials: b() ? "same-origin" : "omit",
222
222
  signal: s ? s.signal : void 0
223
223
  };
224
- 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)
225
- throw new m(u.NETWORK, "当前环境不支持 fetch");
224
+ if (typeof FormData != "undefined" && t instanceof FormData ? c.body = t : t != null && (c.headers = { "Content-Type": "text/plain" }, c.body = JSON.stringify(t)), !m.fetch)
225
+ throw new E(u.NETWORK, "当前环境不支持 fetch");
226
226
  let f;
227
227
  try {
228
- f = await E.fetch(e, c);
228
+ f = await m.fetch(e, c);
229
229
  } catch (y) {
230
- throw a && clearTimeout(a), y && y.name === "AbortError" ? new m(u.TIMEOUT, "请求超时,请重试") : new m(u.NETWORK, "网络异常,请检查网络后重试");
230
+ throw a && clearTimeout(a), y && y.name === "AbortError" ? new E(u.TIMEOUT, "请求超时,请重试") : new E(u.NETWORK, "网络异常,请检查网络后重试");
231
231
  }
232
232
  a && clearTimeout(a);
233
233
  const d = await f.text();
@@ -239,49 +239,49 @@ async function h(e, t, n) {
239
239
  l = null;
240
240
  }
241
241
  if (!f.ok)
242
- throw new m(String(f.status), l && l.message || d || "请求失败");
242
+ throw new E(String(f.status), l && l.message || d || "请求失败");
243
243
  if (!l || l.code === null || l.code === void 0)
244
- throw new m("500", "响应格式异常");
244
+ throw new E("500", "响应格式异常");
245
245
  return l.code = String(l.code), l;
246
246
  }
247
- const Me = "dplugin-auth", ve = 1, Y = "keys", re = "sso", ie = "domain", Le = { name: "ECDSA", namedCurve: "P-256" }, Fe = { name: "ECDSA", hash: "SHA-256" }, F = /* @__PURE__ */ new Map();
248
- let v = null;
247
+ const Le = "dplugin-auth", Fe = 1, H = "keys", re = "sso", ie = "domain", ve = { name: "ECDSA", namedCurve: "P-256" }, Ye = { name: "ECDSA", hash: "SHA-256" }, v = /* @__PURE__ */ new Map();
248
+ let L = null;
249
249
  function j() {
250
- if (!E.subtle) {
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);
253
253
  }
254
- return E.subtle;
254
+ return m.subtle;
255
255
  }
256
256
  function Ge() {
257
- return v || (v = new Promise((e) => {
258
- if (!E.idbOpen) {
257
+ return L || (L = new Promise((e) => {
258
+ if (!m.idbOpen) {
259
259
  e(null);
260
260
  return;
261
261
  }
262
262
  let t;
263
263
  try {
264
- t = E.idbOpen(Me, ve);
264
+ t = m.idbOpen(Le, Fe);
265
265
  } catch (n) {
266
266
  e(null);
267
267
  return;
268
268
  }
269
269
  t.onupgradeneeded = () => {
270
270
  const n = t.result;
271
- n.objectStoreNames.contains(Y) || n.createObjectStore(Y);
271
+ n.objectStoreNames.contains(H) || n.createObjectStore(H);
272
272
  }, t.onsuccess = () => e(t.result), t.onerror = () => e(null), t.onblocked = () => e(null);
273
- }), v);
273
+ }), L);
274
274
  }
275
- function Ee(e, t) {
275
+ 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(Y, e);
279
+ r = n.transaction(H, e);
280
280
  } catch (c) {
281
281
  o(null);
282
282
  return;
283
283
  }
284
- const s = r.objectStore(Y);
284
+ const s = r.objectStore(H);
285
285
  let a = null;
286
286
  try {
287
287
  const c = t(s);
@@ -296,35 +296,35 @@ function Ee(e, t) {
296
296
  r.oncomplete = () => o(a), r.onerror = () => o(null), r.onabort = () => o(null);
297
297
  }) : null);
298
298
  }
299
- function me(e) {
300
- return F.has(e) ? Promise.resolve(F.get(e)) : Ee("readonly", (t) => t.get(e)).then((t) => (t && F.set(e, t), t || null));
299
+ function Ee(e) {
300
+ return v.has(e) ? Promise.resolve(v.get(e)) : me("readonly", (t) => t.get(e)).then((t) => (t && v.set(e, t), t || null));
301
301
  }
302
302
  function Oe(e, t) {
303
- return F.set(e, t), Ee("readwrite", (n) => n.put(t, e)).then(() => t);
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 j().generateKey(Le, !1, ["sign", "verify"]);
306
+ const n = await j().generateKey(ve, !1, ["sign", "verify"]);
307
307
  return Oe(e, n);
308
308
  }
309
309
  async function ye(e) {
310
- return me(e);
310
+ return Ee(e);
311
311
  }
312
- async function we(e, t) {
312
+ async function ge(e, t) {
313
313
  return t ? Oe(e, t) : null;
314
314
  }
315
315
  async function He(e) {
316
- return await me(e) || se(e);
316
+ return await Ee(e) || se(e);
317
317
  }
318
- function Ye() {
318
+ function Be() {
319
319
  return se(re);
320
320
  }
321
- function Be() {
321
+ function Ve() {
322
322
  return se(ie);
323
323
  }
324
324
  function ce() {
325
325
  return ye(re);
326
326
  }
327
- function Se() {
327
+ function be() {
328
328
  return ye(ie);
329
329
  }
330
330
  async function ee(e) {
@@ -335,25 +335,25 @@ async function ee(e) {
335
335
  o += String.fromCharCode(r[s]);
336
336
  return btoa(o);
337
337
  }
338
- function be(e) {
338
+ function Se(e) {
339
339
  const t = new Uint8Array(e);
340
340
  let n = "";
341
341
  for (let o = 0; o < t.length; o++)
342
342
  n += String.fromCharCode(t[o]);
343
343
  return btoa(n).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
344
344
  }
345
- async function Ve(e, t) {
346
- const o = await j().sign(Fe, e.privateKey, new TextEncoder().encode(t));
347
- return be(o);
345
+ async function je(e, t) {
346
+ const o = await j().sign(Ye, e.privateKey, new TextEncoder().encode(t));
347
+ return Se(o);
348
348
  }
349
349
  async function Ie(e) {
350
350
  const t = j(), n = await t.exportKey("spki", e.publicKey), o = await t.digest("SHA-256", n);
351
- return be(o);
351
+ return Se(o);
352
352
  }
353
353
  const te = {
354
354
  SSO: re,
355
355
  DOMAIN: ie
356
- }, ne = "-", je = "POST", N = {
356
+ }, ne = "-", Xe = "POST", N = {
357
357
  BIZ: "BIZ",
358
358
  VERIFY: "VERIFY",
359
359
  VERIFY_SID: "VERIFY_SID",
@@ -362,7 +362,7 @@ const te = {
362
362
  function p(e) {
363
363
  return e == null || e === "" ? ne : String(e);
364
364
  }
365
- function Xe(e, t) {
365
+ function We(e, t) {
366
366
  const n = p(t.origin);
367
367
  return [
368
368
  p(e),
@@ -377,30 +377,30 @@ function Xe(e, t) {
377
377
  ].join(`
378
378
  `);
379
379
  }
380
- function We(e, t, n) {
380
+ function ze(e, t, n) {
381
381
  return [p(e), p(t.subject), p(t.ds), p(t.ts), n].join(".");
382
382
  }
383
- async function x(e, t, n) {
384
- const o = n === "sso" ? await ce() : await Se();
383
+ async function K(e, t, n) {
384
+ const o = n === "sso" ? await ce() : await be();
385
385
  if (!o)
386
386
  throw Te(n === "sso" ? "缺少登录签名密钥" : "缺少业务签名密钥");
387
- const r = await Ve(o, Xe(e, t));
388
- return We(e, t, r);
387
+ const r = await je(o, We(e, t));
388
+ return ze(e, t, r);
389
389
  }
390
390
  async function ae(e, t, n) {
391
391
  if (!t || !n)
392
392
  throw Te("缺少 access 或 ds,无法签名");
393
- const o = await x(N.BIZ, {
394
- method: je,
393
+ const o = await K(N.BIZ, {
394
+ method: Xe,
395
395
  path: V(e),
396
- origin: K(),
396
+ origin: x(),
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 K() {
403
+ function x() {
404
404
  if (typeof location == "undefined")
405
405
  return "";
406
406
  if (location.origin)
@@ -419,14 +419,14 @@ function Ze() {
419
419
  const e = typeof navigator != "undefined" && navigator.userAgent || "", t = {
420
420
  device_brand: $e(e),
421
421
  device_model: qe(e),
422
- browser_name: ze(e),
423
- browser_version: Je(e),
424
- os_name: Qe(e),
425
- os_version: et(e)
422
+ browser_name: Je(e),
423
+ browser_version: Qe(e),
424
+ os_name: et(e),
425
+ os_version: tt(e)
426
426
  }, n = i.ds;
427
427
  return n && (t.device_id = n), t;
428
428
  }
429
- function I(e, t) {
429
+ function T(e, t) {
430
430
  const n = e.match(t);
431
431
  return n ? n[1] : "";
432
432
  }
@@ -439,26 +439,26 @@ function qe(e) {
439
439
  const t = e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);
440
440
  return t ? t[1].trim() : /Macintosh/.test(e) ? "Mac" : "";
441
441
  }
442
- function ze(e) {
443
- 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" : "";
444
- }
445
442
  function Je(e) {
446
- return /MicroMessenger\/([\d.]+)/.test(e) ? I(e, /MicroMessenger\/([\d.]+)/) : /Edg[A-Za-z]*\/([\d.]+)/.test(e) ? I(e, /Edg[A-Za-z]*\/([\d.]+)/) : /OPR\/([\d.]+)/.test(e) ? I(e, /OPR\/([\d.]+)/) : /Firefox\/([\d.]+)/.test(e) ? I(e, /Firefox\/([\d.]+)/) : /CriOS\/([\d.]+)/.test(e) ? I(e, /CriOS\/([\d.]+)/) : /Chrome\/([\d.]+)/.test(e) ? I(e, /Chrome\/([\d.]+)/) : /Version\/([\d.]+).*Safari/.test(e) ? I(e, /Version\/([\d.]+)/) : "";
443
+ 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" : "";
447
444
  }
448
445
  function Qe(e) {
449
- 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" : "";
446
+ 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.]+)/) : "";
450
447
  }
451
448
  function et(e) {
449
+ 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" : "";
450
+ }
451
+ function tt(e) {
452
452
  if (/Windows NT 10\.0/.test(e)) return "10/11";
453
453
  if (/Windows NT 6\.3/.test(e)) return "8.1";
454
454
  if (/Windows NT 6\.1/.test(e)) return "7";
455
455
  const t = e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);
456
456
  if (t) return t[1].replace(/_/g, ".");
457
- if (/Android[ _]([\d.]+)/.test(e)) return I(e, /Android[ _]([\d.]+)/);
457
+ if (/Android[ _]([\d.]+)/.test(e)) return T(e, /Android[ _]([\d.]+)/);
458
458
  const n = e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);
459
459
  return n ? n[1].replace(/_/g, ".") : "";
460
460
  }
461
- const g = {
461
+ const w = {
462
462
  SIGN: {
463
463
  VERIFY: "/api/unsafe/dplugin/login/s/verify",
464
464
  TOKEN: "/api/unsafe/dplugin/login/s/token",
@@ -470,28 +470,35 @@ const g = {
470
470
  REFRESH: "/api/unsafe/dplugin/login/c/refresh"
471
471
  },
472
472
  LOGOUT: "/api/safe/dplugin/login/logout"
473
- }, tt = "dp_dvt", ue = 1800 * 1e3;
474
- let _ = null, L = null, D = null, B = !1;
473
+ }, nt = "dp_dvt", ue = 1800 * 1e3;
474
+ let C = null, F = null, D = null, B = !1;
475
475
  function X() {
476
476
  return typeof location != "undefined" ? location.href : "";
477
477
  }
478
478
  function U(e) {
479
479
  return new Promise((t) => setTimeout(t, e));
480
480
  }
481
+ function ot() {
482
+ try {
483
+ localStorage.setItem("token", i.access || "cookie");
484
+ } catch (e) {
485
+ }
486
+ }
481
487
  function W() {
482
- const e = P();
483
- typeof e.onLogin == "function" && e.onLogin(Z());
488
+ ot();
489
+ const e = I();
490
+ typeof e.onLogin == "function" && e.onLogin(z());
484
491
  }
485
- function T(e, t) {
486
- return new m(e.code, e.message || t);
492
+ function P(e, t) {
493
+ return new E(e.code, e.message || t);
487
494
  }
488
- function nt(e, t, n) {
495
+ function rt(e, t, n) {
489
496
  if (typeof document == "undefined")
490
497
  return;
491
498
  let o = e + "=" + encodeURIComponent(t) + "; path=/; SameSite=Lax";
492
499
  o += "; max-age=" + n, document.cookie = o;
493
500
  }
494
- function Z() {
501
+ function z() {
495
502
  return {
496
503
  mode: pe(),
497
504
  loggedIn: fe(),
@@ -501,7 +508,7 @@ function Z() {
501
508
  };
502
509
  }
503
510
  function fe() {
504
- return S() ? !!i.cookie : !!(i.access || i.sid);
511
+ return b() ? !!i.cookie : !!(i.access || i.sid);
505
512
  }
506
513
  function Pe() {
507
514
  i.clear();
@@ -509,39 +516,47 @@ function Pe() {
509
516
  function R(e) {
510
517
  const t = fe();
511
518
  Pe();
512
- const n = P();
519
+ const n = I();
513
520
  if (t && typeof n.onLogout == "function" && n.onLogout(e || "expired"), B || !n.enableAuth || !n.loginUrl || typeof location == "undefined")
514
521
  return;
515
522
  B = !0;
516
523
  const o = n.loginUrl.includes("?") ? "&" : "?";
517
524
  location.href = n.loginUrl + o + "referer=" + encodeURIComponent(location.href);
518
525
  }
519
- function ot(e, t) {
520
- return D || (D = rt(e, t).then((n) => (D = null, n), (n) => {
521
- throw D = null, n;
526
+ function it(e, t) {
527
+ return D || (D = ct(e, t).then((n) => (D = null, n), (n) => {
528
+ throw D = null, st(n), n;
522
529
  }), D);
523
530
  }
524
- async function rt(e, t) {
525
- const n = P(), o = Ze();
526
- if (S())
527
- return ct(e, t, o, n);
528
- const r = await ce(), s = await Se();
531
+ function st(e) {
532
+ const t = I();
533
+ typeof t.onError == "function" && t.onError({
534
+ code: e && e.code,
535
+ message: e && e.message,
536
+ error: e
537
+ });
538
+ }
539
+ async function ct(e, t) {
540
+ const n = I(), o = Ze();
541
+ if (b())
542
+ return ft(e, t, o, n);
543
+ const r = await ce(), s = await be();
529
544
  try {
530
- return await it(e, t, o, n);
545
+ return await at(e, t, o, n);
531
546
  } catch (a) {
532
- throw await we(te.SSO, r), await we(te.DOMAIN, s), a;
547
+ throw await ge(te.SSO, r), await ge(te.DOMAIN, s), a;
533
548
  }
534
549
  }
535
- async function it(e, t, n, o) {
536
- const r = await Ye(), s = await ee(r), a = await h(w(e), Object.assign({}, t, { device: n, pk: s }));
550
+ async function at(e, t, n, o) {
551
+ const r = await Be(), s = await ee(r), a = await h(g(e), Object.assign({}, t, { device: n, pk: s }));
537
552
  if (a.code !== u.OK)
538
- throw T(a, "登录失败");
553
+ throw P(a, "登录失败");
539
554
  const c = a.data && a.data.token;
540
555
  if (!c)
541
- throw T(a, "登录失败");
542
- const f = await Be(), d = await Ie(f), l = await st(c, o, d), y = await h(w(g.SIGN.TOKEN), {
543
- dsign: await x(N.TOKEN, {
544
- origin: K(),
556
+ throw P(a, "登录失败");
557
+ const f = await Ve(), d = await Ie(f), l = await ut(c, o, d), y = await h(g(w.SIGN.TOKEN), {
558
+ dsign: await K(N.TOKEN, {
559
+ origin: x(),
545
560
  ts: Date.now(),
546
561
  subject: l.code,
547
562
  dna: d
@@ -549,16 +564,16 @@ async function it(e, t, n, o) {
549
564
  pk: await ee(f)
550
565
  });
551
566
  if (y.code !== u.OK || !y.data)
552
- throw T(y, "登录失败");
553
- return i.sid = l.sid, i.ds = y.data.ds || l.ds, i.access = y.data.token, i.exp = Date.now() + ue, B = !1, W(), Z();
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, B = !1, W(), z();
554
569
  }
555
- async function st(e, t, n) {
570
+ async function ut(e, t, n) {
556
571
  const o = X(), r = Math.max(1, Number(t.pollMax) || 5);
557
572
  for (let s = 1; s <= r; s++) {
558
- const a = i.ds || null, c = Date.now(), f = await x(N.VERIFY, {
573
+ const a = i.ds || null, c = Date.now(), f = await K(N.VERIFY, {
559
574
  method: "POST",
560
- path: V(g.SIGN.VERIFY),
561
- origin: K(),
575
+ path: V(w.SIGN.VERIFY),
576
+ origin: x(),
562
577
  ds: a,
563
578
  ts: c,
564
579
  subject: e,
@@ -567,7 +582,7 @@ async function st(e, t, n) {
567
582
  }, "sso");
568
583
  let d;
569
584
  try {
570
- d = await h(w(g.SIGN.VERIFY), { dsign: f, dna: n, redirect: o });
585
+ d = await h(g(w.SIGN.VERIFY), { dsign: f, dna: n, redirect: o });
571
586
  } catch (l) {
572
587
  if ((l.code === u.NETWORK || l.code === u.TIMEOUT) && s < r) {
573
588
  await U(t.pollInterval);
@@ -584,25 +599,25 @@ async function st(e, t, n) {
584
599
  }
585
600
  break;
586
601
  }
587
- throw T(d, "登录失败");
602
+ throw P(d, "登录失败");
588
603
  }
589
- throw new m(u.AUTH_EXPIRED, "登录超时,请重试");
604
+ throw new E(u.AUTH_EXPIRED, "登录超时,请重试");
590
605
  }
591
- async function ct(e, t, n, o) {
592
- const r = await h(w(e), Object.assign({}, t, { device: n }));
606
+ async function ft(e, t, n, o) {
607
+ const r = await h(g(e), Object.assign({}, t, { device: n }));
593
608
  if (r.code !== u.OK)
594
- throw T(r, "登录失败");
609
+ throw P(r, "登录失败");
595
610
  const s = r.data && r.data.token;
596
611
  if (!s)
597
- throw T(r, "登录失败");
598
- return nt(tt, s, 300), await at(o), await Re(), i.cookie = !0, B = !1, W(), Z();
612
+ throw P(r, "登录失败");
613
+ return rt(nt, s, 300), await dt(o), await Re(), i.cookie = !0, B = !1, W(), z();
599
614
  }
600
- async function at(e) {
615
+ async function dt(e) {
601
616
  const t = X(), n = Math.max(1, Number(e.pollMax) || 5);
602
617
  for (let o = 1; o <= n; o++) {
603
618
  let r;
604
619
  try {
605
- r = await h(w(g.COOKIE.VERIFY), { redirect: t });
620
+ r = await h(g(w.COOKIE.VERIFY), { redirect: t });
606
621
  } catch (s) {
607
622
  if ((s.code === u.NETWORK || s.code === u.TIMEOUT) && o < n) {
608
623
  await U(e.pollInterval);
@@ -619,51 +634,51 @@ async function at(e) {
619
634
  }
620
635
  break;
621
636
  }
622
- throw T(r, "登录失败");
637
+ throw P(r, "登录失败");
623
638
  }
624
- throw new m(u.AUTH_EXPIRED, "登录超时,请重试");
639
+ throw new E(u.AUTH_EXPIRED, "登录超时,请重试");
625
640
  }
626
641
  async function Re() {
627
- const e = await h(w(g.COOKIE.TOKEN));
642
+ const e = await h(g(w.COOKIE.TOKEN));
628
643
  if (e.code !== u.OK)
629
- throw T(e, "登录失败");
644
+ throw P(e, "登录失败");
630
645
  return e;
631
646
  }
632
647
  async function M(e) {
633
648
  const t = !!(e && e.force);
634
- return L || (L = (async () => {
649
+ return F || (F = (async () => {
635
650
  try {
636
- return S() ? await ut(t) : await dt(t);
651
+ return b() ? await lt(t) : await wt(t);
637
652
  } catch (n) {
638
653
  if (n && (n.code === u.NETWORK || n.code === u.TIMEOUT))
639
654
  throw n;
640
655
  return !1;
641
656
  } finally {
642
- L = null;
657
+ F = null;
643
658
  }
644
- })()), L;
659
+ })()), F;
645
660
  }
646
- async function ut(e) {
647
- return !e && i.cookie ? !0 : (await h(w(g.COOKIE.VERIFY), { redirect: X() })).code !== u.OK || (await Re()).code !== u.OK ? (i.cookie = !1, !1) : (i.cookie = !0, W(), !0);
661
+ async function lt(e) {
662
+ return !e && i.cookie ? !0 : (await h(g(w.COOKIE.VERIFY), { redirect: X() })).code !== u.OK || (await Re()).code !== u.OK ? (i.cookie = !1, !1) : (i.cookie = !0, W(), !0);
648
663
  }
649
- async function ft() {
664
+ async function gt() {
650
665
  if (!i.sid || !i.ds || !await ce())
651
666
  return !1;
652
- const t = i.ds, n = await He(te.DOMAIN), o = await Ie(n), r = X(), s = await x(N.VERIFY_SID, {
667
+ const t = i.ds, n = await He(te.DOMAIN), o = await Ie(n), r = X(), s = await K(N.VERIFY_SID, {
653
668
  method: "POST",
654
- path: V(g.SIGN.VERIFY),
655
- origin: K(),
669
+ path: V(w.SIGN.VERIFY),
670
+ origin: x(),
656
671
  ds: t,
657
672
  ts: Date.now(),
658
673
  subject: i.sid,
659
674
  dna: o,
660
675
  redirect: r
661
- }, "sso"), a = await h(w(g.SIGN.VERIFY), { dsign: s, dna: o, redirect: r });
676
+ }, "sso"), a = await h(g(w.SIGN.VERIFY), { dsign: s, dna: o, redirect: r });
662
677
  if (a.code !== u.OK || !a.data)
663
678
  return !1;
664
- const c = await h(w(g.SIGN.TOKEN), {
665
- dsign: await x(N.TOKEN, {
666
- origin: K(),
679
+ const c = await h(g(w.SIGN.TOKEN), {
680
+ dsign: await K(N.TOKEN, {
681
+ origin: x(),
667
682
  ts: Date.now(),
668
683
  subject: a.data.code,
669
684
  dna: o
@@ -672,44 +687,44 @@ async function ft() {
672
687
  });
673
688
  return c.code !== u.OK || !c.data ? !1 : (i.access = c.data.token, c.data.ds && (i.ds = c.data.ds), i.exp = Date.now() + ue, W(), !0);
674
689
  }
675
- async function dt(e) {
676
- return !e && i.access ? !0 : ft();
690
+ async function wt(e) {
691
+ return !e && i.access ? !0 : gt();
677
692
  }
678
693
  function de() {
679
- return _ || (_ = (S() ? lt() : wt()).then((e) => (_ = null, e), (e) => {
680
- throw _ = null, e;
681
- })), _;
694
+ return C || (C = (b() ? ht() : pt()).then((e) => (C = null, e), (e) => {
695
+ throw C = null, e;
696
+ })), C;
682
697
  }
683
- async function lt() {
684
- const e = await h(w(g.COOKIE.REFRESH));
698
+ async function ht() {
699
+ const e = await h(g(w.COOKIE.REFRESH));
685
700
  if (e.code === u.OK)
686
701
  return !0;
687
702
  if (e.code === u.AUTH_EXPIRED)
688
703
  throw new O(e.message);
689
704
  if (e.code === "500" && /重复/.test(e.message || ""))
690
705
  return await U(800), !0;
691
- throw new m(e.code, e.message);
706
+ throw new E(e.code, e.message);
692
707
  }
693
- async function wt() {
708
+ async function pt() {
694
709
  const e = i.access, t = i.ds;
695
710
  if (!e || !t)
696
711
  throw new O();
697
- const n = await x(N.BIZ, {
712
+ const n = await K(N.BIZ, {
698
713
  method: "POST",
699
- path: V(g.SIGN.REFRESH),
700
- origin: K(),
714
+ path: V(w.SIGN.REFRESH),
715
+ origin: x(),
701
716
  ds: t,
702
717
  ts: Date.now(),
703
718
  subject: e
704
- }, "domain"), o = await h(w(g.SIGN.REFRESH, "dsign=" + encodeURIComponent(n)));
719
+ }, "domain"), o = await h(g(w.SIGN.REFRESH, "dsign=" + encodeURIComponent(n)));
705
720
  if (o.code === u.OK && o.data)
706
721
  return i.access = o.data.token, o.data.ds && (i.ds = o.data.ds), i.exp = Date.now() + ue, i.access;
707
- const r = await gt(e, 1200);
722
+ const r = await mt(e, 1200);
708
723
  if (r)
709
724
  return r;
710
- throw o.code === u.AUTH_EXPIRED ? new O(o.message) : new m(o.code, o.message);
725
+ throw o.code === u.AUTH_EXPIRED ? new O(o.message) : new E(o.code, o.message);
711
726
  }
712
- function gt(e, t) {
727
+ function mt(e, t) {
713
728
  const n = Date.now() + t;
714
729
  return new Promise((o) => {
715
730
  const r = () => {
@@ -727,28 +742,36 @@ function gt(e, t) {
727
742
  r();
728
743
  });
729
744
  }
730
- async function ht() {
745
+ async function Et() {
731
746
  try {
732
- let t = await ge();
733
- t.code === u.AUTH_EXPIRED && (await de(), t = await ge());
747
+ let t = await we();
748
+ t.code === u.AUTH_EXPIRED && (await de(), t = await we());
734
749
  } catch (t) {
735
750
  }
736
751
  Pe();
737
- const e = P();
752
+ const e = I();
738
753
  typeof e.onLogout == "function" && e.onLogout("logout");
739
754
  }
740
- async function ge() {
741
- if (S())
742
- return h(w(g.LOGOUT));
743
- const e = await ae(g.LOGOUT, i.access, i.ds);
744
- return h(w(g.LOGOUT, e));
755
+ async function we() {
756
+ if (b())
757
+ return h(g(w.LOGOUT));
758
+ const e = await ae(w.LOGOUT, i.access, i.ds);
759
+ return h(g(w.LOGOUT, e));
760
+ }
761
+ async function bt(e, t, n) {
762
+ const o = Ot(t, n);
763
+ return o.authed && await De(), Y(e, o.body, o.options, !1);
745
764
  }
746
- async function Et(e, t, n) {
747
- const o = n || {};
748
- return o.auth !== !1 && await De(), G(e, t || {}, o, !1);
765
+ function Ot(e, t) {
766
+ const n = t || {};
767
+ 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) ? {
768
+ body: e.data,
769
+ options: Object.assign({}, e, n),
770
+ authed: e.noToken !== !0 && n.auth !== !1
771
+ } : { body: e, options: n, authed: n.auth !== !1 };
749
772
  }
750
773
  async function De() {
751
- if (S()) {
774
+ if (b()) {
752
775
  if (i.cookie || await M())
753
776
  return;
754
777
  throw R("expired"), new O();
@@ -756,8 +779,8 @@ async function De() {
756
779
  if (!i.access && !await M())
757
780
  throw R("expired"), new O();
758
781
  }
759
- async function G(e, t, n, o) {
760
- const r = n.auth !== !1, s = r && !S();
782
+ async function Y(e, t, n, o) {
783
+ const r = n.auth !== !1 && n.noToken !== !0, s = r && !b();
761
784
  let a = "", c = null;
762
785
  if (s) {
763
786
  c = i.access;
@@ -765,35 +788,35 @@ async function G(e, t, n, o) {
765
788
  a = await ae(e, c, i.ds);
766
789
  } catch (d) {
767
790
  if (!o && await M({ force: !0 }))
768
- return G(e, t, n, !0);
791
+ return Y(e, t, n, !0);
769
792
  throw R("expired"), new O();
770
793
  }
771
794
  }
772
- const f = await h(w(e, a), t, n.timeout);
795
+ const f = await h(g(e, a), t, n.timeout);
773
796
  if (f.code === u.OK)
774
- return f.data;
797
+ return f;
775
798
  if (r && f.code === u.AUTH_EXPIRED && !o) {
776
799
  if (s && c && i.access !== c)
777
- return G(e, t, n, !0);
800
+ return Y(e, t, n, !0);
778
801
  try {
779
802
  await de();
780
803
  } catch (d) {
781
804
  throw d instanceof O && R("expired"), d;
782
805
  }
783
- return G(e, t, n, !0);
806
+ return Y(e, t, n, !0);
784
807
  }
785
808
  throw r && f.code === u.AUTH_EXPIRED ? (R("expired"), new O(f.message)) : Ne(f);
786
809
  }
787
810
  function Ne(e) {
788
- const t = new m(e.code, e.message), n = P();
811
+ const t = new E(e.code, e.message), n = I();
789
812
  return n.onError && n.onError({ code: e.code, message: e.message, error: t }), t;
790
813
  }
791
- async function mt(e, t, n, o) {
792
- return (S() ? !i.cookie : !i.access) && await De(), oe(e, t, n, o || {}, !1);
814
+ async function St(e, t, n, o) {
815
+ return (b() ? !i.cookie : !i.access) && await De(), oe(e, t, n, o || {}, !1);
793
816
  }
794
817
  async function oe(e, t, n, o, r) {
795
818
  let s = "";
796
- if (!S())
819
+ if (!b())
797
820
  try {
798
821
  s = await ae(e, i.access, i.ds);
799
822
  } catch (f) {
@@ -806,9 +829,9 @@ async function oe(e, t, n, o, r) {
806
829
  const d = n[f];
807
830
  d != null && a.append(f, d);
808
831
  }), a.append("file", t);
809
- const c = await h(w(e, s), a, o.timeout);
832
+ const c = await h(g(e, s), a, o.timeout);
810
833
  if (c.code === u.OK)
811
- return c.data;
834
+ return c;
812
835
  if (c.code === u.AUTH_EXPIRED && !r) {
813
836
  try {
814
837
  await de();
@@ -819,10 +842,10 @@ async function oe(e, t, n, o, r) {
819
842
  }
820
843
  throw Ne(c);
821
844
  }
822
- function Ot(e) {
823
- const t = xe(e);
824
- if (Ue(), t.nativeGuard !== "off") {
825
- const n = Ce();
845
+ function It(e) {
846
+ const t = Ke(e);
847
+ if (Me(), t.nativeGuard !== "off") {
848
+ const n = ke();
826
849
  if (n.length) {
827
850
  const o = "[dplugin/core] 这些原生能力在模块加载前已被替换:" + n.join(", ") + "(签名/请求可能被中间人截获,检查是否有脚本抢跑)";
828
851
  if (t.nativeGuard === "error")
@@ -831,31 +854,31 @@ function Ot(e) {
831
854
  }
832
855
  }
833
856
  }
834
- const yt = {
835
- login: ot,
836
- logout: ht,
857
+ const Tt = {
858
+ login: it,
859
+ logout: Et,
837
860
  isLogin: fe,
838
- getState: Z,
861
+ getState: z,
839
862
  /** 页面加载时恢复登录态;返回是否已登录 */
840
863
  restore: M
841
864
  };
842
865
  export {
843
866
  O as AuthError,
844
- m as BizError,
867
+ E as BizError,
845
868
  u as CODE,
846
- yt as auth,
869
+ Tt as auth,
847
870
  Pe as clear,
848
871
  R as expire,
849
872
  pe as getMode,
850
- Z as getState,
851
- pt as isAuthError,
873
+ z as getState,
874
+ yt as isAuthError,
852
875
  fe as isLogin,
853
- ot as login,
854
- ht as logout,
855
- Et as request,
856
- Ot as setup,
876
+ it as login,
877
+ Et as logout,
878
+ bt as request,
879
+ It as setup,
857
880
  i as store,
858
- mt as upload,
881
+ St as upload,
859
882
  M as verifyLogin
860
883
  };
861
884
  //# sourceMappingURL=index.mjs.map
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 _e(e){return e&&Object.keys(I).forEach(t=>{e[t]!==void 0&&(I[t]=e[t])}),I}function P(){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=P().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 T=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(){T=null}function ne(){if(T)return T;const e=P();if(e.mode==="sign"||e.mode==="cookie")return T=e.mode,T;const t=typeof location!="undefined"?location.origin:null;if(!t)return T="sign",T;const n=Le(e.apiBase||t);return T=n&&n===t?"cookie":"sign",T}function S(){return ne()==="cookie"}async function h(e,t,n){const o=P(),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=P();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=P();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 _||(_=ct(e,t).then(n=>(_=null,n),n=>{throw _=null,n}),_)}async function ct(e,t){const n=P(),o=Je();if(S())return ft(e,t,o,n);const r=await se(),s=await be();try{return await at(e,t,o,n)}catch(u){throw await Se(ae.SSO,r),await Se(ae.DOMAIN,s),u}}async function at(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 ut(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 ut(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 ft(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 dt(o),await De(),i.cookie=!0,X=!1,q(),L()}async function dt(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 lt(t):await wt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{j=null}})()),j}async function lt(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 gt(){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 wt(e){return!e&&i.access?!0:gt()}function ge(){return U||(U=(S()?ht():pt()).then(e=>(U=null,e),e=>{throw U=null,e})),U}async function ht(){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 pt(){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 Et(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new y(o.message):new E(o.code,o.message)}function Et(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=P();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 mt(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=P();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function Ot(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 yt(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 St={login:Re,logout:Ne,isLogin:z,getState:L,restore:x};d.AuthError=y,d.BizError=E,d.CODE=a,d.auth=St,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=mt,d.setup=yt,d.store=i,d.upload=Ot,d.verifyLogin=x,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 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"})}));
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.2",
3
+ "version": "2.0.4",
4
4
  "description": "DPlugin 前端登录与请求 SDK(同域 Cookie + 跨域 ECDSA 双模式)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",