@dplugin/core 2.0.11 → 2.1.0

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 U={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(U).forEach(t=>{e[t]!==void 0&&(U[t]=e[t])}),U}function I(){return U}const m=Ce();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 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 Ce(){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||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&&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";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 G={};function C(e){const t=Ue(e);return t===null?G[e]===void 0?null:G[e]:t}function _(e,t){G[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=>{G[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 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 S=null;function ke(e){try{const t=typeof location!="undefined"?location.href:void 0;return new URL(e||"",t).origin}catch(t){return null}}function ve(){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=ke(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 Le="dplugin-auth",Fe=1,Y="keys",se="sso",ce="domain",He={name:"ECDSA",namedCurve:"P-256"},Be={name:"ECDSA",hash:"SHA-256"},H=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 Ge(){return L||(L=new Promise(e=>{if(!m.idbOpen){e(null);return}let t;try{t=m.idbOpen(Le,Fe)}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 Ge().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 H.has(e)?Promise.resolve(H.get(e)):me("readonly",t=>t.get(e)).then(t=>(t&&H.set(e,t),t||null))}function ye(e,t){return H.set(e,t),me("readwrite",n=>n.put(t,e)).then(()=>t)}async function ae(e){const n=await X().generateKey(He,!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 Ye(e){return await Oe(e)||ae(e)}function Ve(){return ae(se)}function je(){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 Xe(e,t){const o=await X().sign(Be,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=X(),n=await t.exportKey("spki",e.publicKey),o=await t.digest("SHA-256",n);return Ie(o)}const ne={SSO:se,DOMAIN:ce},oe="-",We="POST",N={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function p(e){return e==null||e===""?oe:String(e)}function qe(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 A(e,t,n){const o=n==="sso"?await ue():await Se();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await Xe(o,qe(e,t));return ze(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await A(N.BIZ,{method:We,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 Ze(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:$e(e),device_model:Je(e),browser_name:Qe(e),browser_version:et(e),os_name:tt(e),os_version:nt(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 $e(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 Je(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 Qe(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 et(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 tt(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 nt(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"},de=1800*1e3;let M=null,F=null,R=null,V=!1;function W(){return typeof location!="undefined"?location.href:""}function k(e){return new Promise(t=>setTimeout(t,e))}function q(){const e=I();typeof e.onLogin=="function"&&e.onLogin(v())}function D(e,t){return new E(e.code,e.message||t)}function v(){return{mode:ie(),loggedIn:z(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function z(){return b()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function P(e){const t=z();le();const n=I();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 R||(R=rt(e,t).then(n=>(R=null,n),n=>{throw R=null,ot(n),n}),R)}function ot(e){const t=I();typeof t.onError=="function"&&t.onError({code:e&&e.code,message:e&&e.message,error:e})}async function rt(e,t){const n=I(),o=Ze();if(b())return ct(e,t,o,n);const r=await ue(),s=await Se();try{return await it(e,t,o,n)}catch(u){throw await he(ne.SSO,r),await he(ne.DOMAIN,s),u}}async function it(e,t,n,o){const r=await Ve(),s=await te(r),u=await h(g(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 je(),d=await Te(f),l=await st(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 D(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 st(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: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 k(t.pollInterval);continue}throw l}if(d.code===a.OK&&d.data)return d.data;if(d.code===a.PENDING){if(s<r){await k(t.pollInterval);continue}break}throw D(d,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function ct(e,t,n,o){const r=await h(g(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw D(r,"登录失败");return await at(o),i.cookie=!0,V=!1,q(),v()}async function at(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 k(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await k(e.pollInterval);continue}break}throw D(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function x(e){const t=!!(e&&e.force);return F||(F=(async()=>{try{return b()?await ut(t):await dt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{F=null}})()),F}async function ut(e){return!e&&i.cookie?!0:(await h(g(w.COOKIE.VERIFY),{redirect:W()})).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,q(),!0)}async function ft(){if(!i.sid||!i.ds||!await ue())return!1;const t=i.ds,n=await Ye(ne.DOMAIN),o=await Te(n),r=W(),s=await A(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 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,q(),!0)}async function dt(e){return!e&&i.access?!0:ft()}function ge(){return M||(M=(b()?lt():gt()).then(e=>(M=null,e),e=>{throw M=null,e})),M}async function lt(){const e=await h(g(w.COOKIE.TOKEN));if(e.code===a.OK)return!0;const t=await h(g(w.COOKIE.REFRESH));if(t.code===a.OK)return!0;if(t.code===a.AUTH_EXPIRED||e.code===a.AUTH_EXPIRED)throw new O(t.message||e.message);if(t.code==="500"&&/重复/.test(t.message||""))return await k(800),!0;throw new E(t.code,t.message)}async function gt(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await A(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 wt(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(o.message):new E(o.code,o.message)}function wt(e,t){const n=Date.now()+t;return new Promise(o=>{const r=()=>{const s=i.access;if(s&&s!==e){o(s);return}if(Date.now()>=n){o(null);return}setTimeout(r,150)};r()})}async function De(){try{let t=await 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 ht(e,t,n){const o=n||{};return o.auth!==!1&&await Ne(),B(e,t||{},o,!1)}async function Ne(){if(b()){if(i.cookie||await x())return;throw P("expired"),new O}if(!i.access&&!await x())throw P("expired"),new O}async function B(e,t,n,o){const r=n.auth!==!1,s=r&&!b();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(d){if(!o&&await x({force:!0}))return B(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 B(e,t,n,!0);try{await ge()}catch(d){throw d instanceof O&&P("expired"),d}return B(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(P("expired"),new O(f.message)):Ae(f,n)}function Ae(e,t){const n=new E(e.code,e.message),o=I();return o.onError&&!(t&&t.silent)&&o.onError({code:e.code,message:e.message,error:n}),n}async function pt(e,t,n,o){return(b()?!i.cookie:!i.access)&&await Ne(),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 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 Ae(c,o)}function Et(e){const t=Ke(e);if(ve(),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 mt={login:Re,logout:De,isLogin:z,getState:v,restore:x};exports.AuthError=O;exports.BizError=E;exports.CODE=a;exports.auth=mt;exports.clear=le;exports.expire=P;exports.getMode=ie;exports.getState=v;exports.isAuthError=Me;exports.isLogin=z;exports.login=Re;exports.logout=De;exports.request=ht;exports.setup=Et;exports.store=i;exports.upload=pt;exports.verifyLogin=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I={apiBase:"",mode:"auto",loginUrl:"/login/",timeout:15e3,pollInterval:2e3,pollMax:5,enableAuth:!1,onError:null,onLogin:null,onLogout:null,nativeGuard:"error"};function ie(e){return e&&Object.keys(I).forEach(n=>{e[n]!==void 0&&(I[n]=e[n])}),I}function y(){return I}const a=se();function B(e,n){if(typeof e!="function")return!1;let t;try{t=Function.prototype.toString.call(e)}catch(i){return!1}const r=/^function\s+([\w$]+)\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.exec(t);return r?r[1]===n:/\[native code\]/.test(t)&&!/^function\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.test(t)}function oe(e){try{const n=e();return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),!1}catch(n){const t=String(n&&n.message||"");return!!n&&n.name==="TypeError"&&/argument|required|参数/i.test(t)}}function se(){const e=globalThis,n=typeof e.window!="undefined"&&e.window&&typeof e.window.document!="undefined",t={fetch:null,idbOpen:null,subtle:null,pristine:{fetch:!1,idbOpen:!1,subtle:!1}};typeof e.fetch=="function"&&(t.pristine.fetch=B(e.fetch,"fetch"),t.fetch=e.fetch.bind(e)),typeof e.indexedDB!="undefined"&&e.indexedDB&&typeof e.indexedDB.open=="function"&&(t.pristine.idbOpen=B(e.indexedDB.open,"open")&&(!n||oe(()=>e.indexedDB.open())),t.idbOpen=e.indexedDB.open.bind(e.indexedDB));const r=e.crypto&&e.crypto.subtle?e.crypto.subtle:null;if(r){const i=["generateKey","exportKey","importKey","sign","verify","digest"],o={};let s=!0;i.forEach(c=>{typeof r[c]=="function"&&(o[c]=r[c].bind(r),s=s&&B(r[c],c))}),t.subtle=o,t.pristine.subtle=s}return t}function ce(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return a.fetch&&!a.pristine.fetch&&e.push("fetch"),a.idbOpen&&!a.pristine.idbOpen&&e.push("indexedDB.open"),a.subtle&&!a.pristine.subtle&&e.push("crypto.subtle"),e}const f={OK:"200",LOGIN_PENDING:"202",LOGIN_TIMEOUT:"g.login.timeout",NETWORK:"NETWORK",TIMEOUT:"TIMEOUT"};class h extends Error{constructor(n,t){super(t||"请求失败"),this.name="BizError",this.code=n}}class ue extends h{constructor(n){super(f.LOGIN_TIMEOUT,n||"登录已失效"),this.name="AuthError"}}const V="dp.token",U="dp.sid",Z="dp.ds";function ae(e){try{return localStorage.getItem(e)}catch(n){return null}}function Q(e,n){try{n==null||n===""?localStorage.removeItem(e):localStorage.setItem(e,n)}catch(t){}}const M={};function F(e){const n=ae(e);return n===null?M[e]===void 0?null:M[e]:n}function j(e,n){M[e]=n,Q(e,n)}const u={get token(){return F(V)},set token(e){j(V,e)},get sid(){return F(U)},set sid(e){j(U,e)},get ds(){return F(Z)},set ds(e){j(Z,e)},clear(){[V,U].forEach(e=>{M[e]=null,Q(e,null)})}},fe="dplugin",le=1,x="keys",de={name:"ECDSA",namedCurve:"P-256"},ge={name:"ECDSA",hash:"SHA-256"},D=new Map;let K=null;function v(){if(!a.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 a.subtle}function he(){return K||(K=new Promise(e=>{if(!a.idbOpen){e(null);return}let n;try{n=a.idbOpen(fe,le)}catch(t){e(null);return}n.onupgradeneeded=()=>{const t=n.result;t.objectStoreNames.contains(x)||t.createObjectStore(x)},n.onsuccess=()=>e(n.result),n.onerror=()=>e(null),n.onblocked=()=>e(null)}),K)}function ee(e,n){return he().then(t=>t?new Promise(r=>{let i;try{i=t.transaction(x,e)}catch(c){r(null);return}const o=i.objectStore(x);let s=null;try{const c=n(o);c&&(c.onsuccess=()=>{s=c.result},c.onerror=()=>{s=null})}catch(c){s=null}i.oncomplete=()=>r(s),i.onerror=()=>r(null),i.onabort=()=>r(null)}):null)}async function P(e){return D.has(e)?Promise.resolve(D.get(e)):ee("readonly",n=>n.get(e)).then(n=>(n&&D.set(e,n),n||null))}function ne(e){const n=new Uint8Array(e);let t="";for(let r=0;r<n.length;r++)t+=String.fromCharCode(n[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function te(e){let n=await P(e);return n||(n=await v().generateKey(de,!1,["sign","verify"]),D.set(e,n),ee("readwrite",r=>r.put(n,e)).then(()=>n))}function pe(){return te("sso")}function we(){return te("domain")}async function me(){return await P("sso")}async function Oe(){return await P("domain")}async function ye(){let e=await P("domain");const n=v(),t=await n.exportKey("spki",e.publicKey),r=await n.digest("SHA-256",t);return ne(r)}async function Y(e){let n=await P(e);const r=await v().exportKey("spki",n.publicKey);let i="";const o=new Uint8Array(r);for(let s=0;s<o.length;s++)i+=String.fromCharCode(o[s]);return btoa(i)}async function Ee(e,n){const r=await v().sign(ge,e.privateKey,new TextEncoder().encode(n));return ne(r)}const Se="-",_={BIZ:"BIZ",VTT:"VTT",VSD:"VSD",TOK:"TOK"};function O(e){return e==null||e===""?Se:String(e)}function be(e,n){const t=O(n.origin);return[e,n.method,n.path,t.toLowerCase(),O(n.ds),n.ts,O(n.token),O(n.dna),O(n.redirect)].join(`
2
+ `)}function Te(e,n,t){return[e,O(n.token),O(n.ds),n.ts,t].join(".")}function ke(e){const n=new Error(e);return n.code="KEY_MISSING",n}async function A(e,n,t){const r=t==="sso"?await me():await Oe();if(!r)throw ke(t==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");let i=n.path.indexOf("?");i>0&&(n.path=n.path.substring(0,i));const o=await Ee(r,be(e,n));return Te(e,n,o)}let g=null;function Ie(e){try{const n=typeof location!="undefined"?location.href:void 0;return new URL(e||"",n).origin}catch(n){return null}}function Pe(){g=null}function Ne(){if(g)return g;const e=y();if(e.mode==="sign"||e.mode==="cookie")return g=e.mode,g;const n=typeof location!="undefined"?location.origin:null;if(!n)return g="sign",g;const t=Ie(e.apiBase||n);return g=t&&t===n?"cookie":"sign",g}function E(){return Ne()==="cookie"}function Re(e,n){let t=y();throw t.onError&&n.showError&&t.onError({code:e.code,message:e.message}),new h(e.code,e.message)}let C,$=null;function Ke(){return C||(C=Promise.resolve().then(()=>$()).finally(()=>{C=null})),C}async function Ce(e,n,t,r,i){const o=y(),s=i||o.timeout,c=typeof AbortController!="undefined"?new AbortController:null,N=c?setTimeout(()=>c.abort(),s):null,m={method:n};if(e?m.credentials="same-origin":m.credentials="omit",m.signal=c?c.signal:void 0,typeof FormData!="undefined"&&r instanceof FormData?m.body=r:r!=null&&(m.headers={"Content-Type":"text/plain"},m.body=JSON.stringify(r)),!a.fetch)throw new h(f.NETWORK,"当前环境不支持 fetch");let R;try{R=await a.fetch(t,m)}catch(L){throw N&&clearTimeout(N),L&&L.name==="AbortError"?new h(f.TIMEOUT,"请求超时,请重试"):new h(f.NETWORK,"网络异常,请检查网络后重试")}N&&clearTimeout(N);const G=await R.text();let d=null;if(G)try{d=JSON.parse(G)}catch(L){d=null}if(!R.ok)throw new h(String(R.status),d&&d.message||G||"请求失败");if(!d||d.code===null||d.code===void 0)throw new h("500","响应格式异常");return d.code=String(d.code),d}async function l(e,n=null,t=null){const r=t||{};r.method||(r.method="POST"),r.showError=r.showError!==!1;let i=!0;/^https?:\/\/.+$/.test(e)?e.indexOf(y().apiBase)===-1&&(i=!1):e=y().apiBase+e,i&&!E()&&(i=!1);let o=e;if(!i&&u.ds&&u.token){let c=await A(_.BIZ,{method:r.method,path:new URL(e,location.href).pathname,ds:u.ds,ts:Date.now(),token:u.token},"domain");o.indexOf("?")>0?o=o+"&dsign="+c:o=o+"?dsign="+c}const s=await Ce(i,r.method,o,n,r.timeout);return s.code===f.LOGIN_TIMEOUT&&!r.skipRefresh&&$&&await Ke()?l(e,n,Object.assign({},r,{skipRefresh:!0})):(/^2.+/.test(s.code)||Re(s,r),s)}async function De(e,n,t,r){const i=new FormData;return Object.keys(t||{}).forEach(o=>{const s=t[o];s!=null&&i.append(o,s)}),i.append("file",n),l(e,i,r)}function Me(e){$=e}function xe(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",n={device_brand:_e(e),device_model:Ae(e),browser_name:ve(e),browser_version:Ge(e),os_name:Le(e),os_version:Be(e)},t=u.ds;return t&&(n.device_id=t),n}function w(e,n){const t=e.match(n);return t?t[1]:""}function _e(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 Ae(e){if(/iPhone/.test(e))return"iPhone";if(/iPad/.test(e))return"iPad";const n=e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);return n?n[1].trim():/Macintosh/.test(e)?"Mac":""}function ve(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 Ge(e){return/MicroMessenger\/([\d.]+)/.test(e)?w(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?w(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?w(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?w(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?w(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?w(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?w(e,/Version\/([\d.]+)/):""}function Le(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 Be(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 n=e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);if(n)return n[1].replace(/_/g,".");if(/Android[ _]([\d.]+)/.test(e))return w(e,/Android[ _]([\d.]+)/);const t=e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);return t?t[1].replace(/_/g,"."):""}function re(){if(location.origin)return location.origin.toLowerCase();try{return new URL(location.href).origin.toLowerCase()}catch(e){return""}}let H,q;function W(e){const n=typeof location!="undefined"&&location.search||"";return(!H||q!==n)&&(q=n,H=new URLSearchParams(n)),H.get(e)}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"};Me(Ze);function Ve(e){return new Promise(n=>setTimeout(n,e))}let S=null;async function Ue(e,n){if(S)return S;const t=xe();return S=(E()?Fe(e,n,t):je(e,n,t)).finally(()=>{S=null}),S}async function Fe(e,n,t){let r=await l(e,Object.assign({},n,{device:t}));return await z(r.data,!0,!0)}async function je(e,n,t){await pe();const r=await Y("sso"),i=await l(e,Object.assign({},n,{device:t,pk:r}));return await z(i.data,!0,!0)}let b;async function z(e,n=!1,t=!1){return b||(b=He(e,n,t).finally(()=>{b=null}),b)}async function He(e,n,t){if(e||(e={}),t){let r=y(),i;for(let o=0;o<r.pollMax;o++){if(i=E()?await X(e,n):await J(e,n),i.code!==f.LOGIN_PENDING)return i;await Ve(r.pollInterval)}return i}else return E()?await X(e,n):await J(e,n)}async function X(e,n){return await l(p.COOKIE.VERIFY,{redirect:W("referer")},{skipRefresh:!0,showError:n})}async function J(e,n){let t={method:"POST",path:p.SIGN.VERIFY,origin:re(),ts:Date.now(),ds:u.ds,dna:W("dna"),redirect:W("referer")},r;if(e&&e.token)t.token=e.token,r=await A(_.VTT,t,"sso");else{if(!u.sid||!u.ds)throw new h(f.LOGIN_TIMEOUT,"未登录");t.token=u.sid,r=await A(_.VSD,t,"sso")}const i=await l(p.SIGN.VERIFY,{dsign:r,dna:t.dna,redirect:t.redirect},{skipRefresh:!0,showError:n});return i.code===f.OK&&(u.token=i.data.token,i.data.ds&&(u.ds=i.data.ds)),i}let T;async function We(e){return T||(T=Ye(e).finally(()=>{T=null}),T)}async function Ye(e){return E()?await $e():await ze(e)}async function $e(e){return await l(p.COOKIE.TOKEN,null,{skipRefresh:!0})}async function ze(e){let n={method:"POST",path:p.SIGN.TOKEN,origin:re(),ts:Date.now(),ds:u.ds},t;if(e&&e.code)n.token=e.code,t=await A(_.TOK,n,"domain");else throw new h(f.LOGIN_TIMEOUT,"未登录");let r=await Y("domain");const i=await l(p.SIGN.TOKEN,{dsign:t,pk:r},{skipRefresh:!0});return i.code===f.OK&&(u.token=i.data.token,i.data.ds&&(u.ds=i.data.ds)),i}let k;async function Ze(){return k||(k=qe().finally(()=>{k=null}),k)}async function qe(){return E()?await Xe():await Je()}async function Xe(){return await l(p.COOKIE.REFRESH,null,{skipRefresh:!0,showError:!1})}async function Je(){const e=u.token,n=u.ds;if(!e||!n)throw new ue;const t=await l(p.SIGN.REFRESH,null,{skipRefresh:!0,showError:!1});return t.code===f.OK&&(t.data.ds&&(u.ds=t.data.ds),u.token=t.data.token),t}async function Qe(){(await l(p.LOGOUT)).code===f.OK&&u.clear()}function en(e){const n=ie(e);if(Pe(),n.nativeGuard!=="off"){const t=ce();if(t.length){const r="[dplugin/core] 这些原生能力在模块加载前已被替换:"+t.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(n.nativeGuard==="error")throw new Error(r);typeof console!="undefined"&&console.warn(r)}}}exports.createDomainPair=we;exports.getDna=ye;exports.getPublicKey=Y;exports.login=Ue;exports.logout=Qe;exports.request=l;exports.setup=en;exports.token=We;exports.upload=De;exports.verify=z;
3
3
  //# sourceMappingURL=index.cjs.map