@koishi-ce/plugin-auth 1.1.2 → 1.1.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/README.md +2 -2
- package/dist/index.js +1 -1
- package/dist/style.css +1 -1
- package/lib/index.d.ts +46 -44
- package/lib/index.mjs +155 -158
- package/package.json +2 -2
- package/src/__tests__/helpers.ts +272 -0
- package/src/__tests__/intercept.test.ts +102 -0
- package/src/__tests__/login.test.ts +237 -0
- package/src/__tests__/user-events.test.ts +189 -0
- package/src/__tests__/verification.test.ts +122 -0
- package/src/crypto.ts +77 -0
- package/src/index.ts +19 -374
- package/src/login.ts +243 -0
- package/src/types.ts +52 -0
- package/src/__tests__/index.test.ts +0 -797
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
- **平台验证码**:`login/platform`,网页生成 6 位验证码,用户把验证码发给任意机器人完成登录(同时可绑定平台账号,支持私聊一步、群聊两步);
|
|
11
11
|
- **令牌续期**:`login/token`,已保存的登录令牌静默续期,页面刷新自动执行。
|
|
12
12
|
|
|
13
|
-
密码哈希采用 PBKDF2-HMAC-SHA256(600k 轮,OWASP 2023
|
|
13
|
+
密码哈希采用 PBKDF2-HMAC-SHA256(600k 轮,OWASP 2023 建议);仅接受该格式,历史无盐 SHA-256 哈希不再兼容(存量旧哈希账户须重置密码)。
|
|
14
14
|
|
|
15
15
|
## 配置项
|
|
16
16
|
|
|
@@ -64,7 +64,7 @@ Console user authentication for Koishi, ported from `plugins/auth` of the upstre
|
|
|
64
64
|
- **Platform verification code** (`login/platform`) — the web page shows a 6-digit code; the user sends it to any bot to log in (optionally binding the platform account; one step in private chat, two steps in groups).
|
|
65
65
|
- **Token renewal** (`login/token`) — saved tokens renew silently; page refreshes do this automatically.
|
|
66
66
|
|
|
67
|
-
Password hashing uses PBKDF2-HMAC-SHA256 (600k iterations, OWASP 2023); legacy unsalted SHA-256 hashes are
|
|
67
|
+
Password hashing uses PBKDF2-HMAC-SHA256 (600k iterations, OWASP 2023); only that format is accepted — legacy unsalted SHA-256 hashes are no longer compatible (affected accounts must reset their password).
|
|
68
68
|
|
|
69
69
|
## Configuration
|
|
70
70
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Schema as e,deepEqual as t,icons as n,message as r,pick as i,router as a,send as o,store as s,useConfig as c,useStorage as l}from"@koishi-ce/client";import{Fragment as u,computed as d,createBlock as f,createCommentVNode as p,createElementBlock as m,createElementVNode as h,createTextVNode as g,createVNode as _,defineComponent as v,h as y,isRef as b,openBlock as x,ref as S,renderList as C,resolveComponent as w,toDisplayString as T,unref as E,watch as D,withCtx as O,withKeys as k,withModifiers as A}from"vue";import{useRouter as j}from"vue-router";var M=l(`auth`,2,()=>({authType:0})),N=S(!1),P=S(!1),F={class:`login-form text-center`},ee={key:0},te={key:1},I={class:`hint`},L={class:`token`},R={class:`control`},z={key:0},B={key:1},V={key:0,class:`error`},H={class:`control`},U={key:0,class:`error`},W={class:`control`},G=v({__name:`login-form`,setup(e){let t=S(),n=S(),r=S(!1),i=0;async function a(){let e=Date.now();if(e<i)return;let{platform:r,userId:a}=M.value;if(r&&a){i=e+1e3;try{n.value=await o(`login/platform`,r,a)}catch(e){t.value=e.message}}}async function c(){let{name:e,password:n}=M.value;try{await o(`login/password`,e,n)}catch(e){t.value=e.message}}let l=j();function d(){s.user?N.value=!1:l.back()}return(e,i)=>{let o=w(`k-button`),l=w(`k-tab`),f=w(`k-icon`),v=w(`el-input`);return x(),m(`div`,F,[n.value?(x(),m(u,{key:0},[E(s).user?(x(),m(`h1`,ee,[...i[7]||=[h(`span`,null,`平台账户绑定`,-1)]])):(x(),m(`h1`,te,[...i[8]||=[h(`span`,null,`平台账户登录`,-1)]])),h(`p`,I,`欢迎你,`+T(n.value.name||`Koishi 用户`)+`!`,1),i[10]||=h(`p`,{class:`hint`},`请用上述账号将下面的验证码发送给任意正在运行的机器人`,-1),h(`p`,L,T(n.value.token),1),h(`div`,R,[_(o,{onClick:i[0]||=e=>n.value.token=null},{default:O(()=>[...i[9]||=[g(`返回上一步`,-1)]]),_:1})])],64)):(x(),m(u,{key:1},[E(s).user?(x(),m(`h1`,z,[...i[11]||=[h(`span`,null,`平台账户绑定`,-1)]])):(x(),m(`h1`,B,[_(l,{data:[`用户密码登录`,`平台账户登录`],modelValue:E(M).authType,"onUpdate:modelValue":i[1]||=e=>E(M).authType=e},null,8,[`modelValue`])])),E(s).user||E(M).authType===1?(x(),m(u,{key:2},[_(v,{placeholder:`平台名`,modelValue:E(M).platform,"onUpdate:modelValue":i[2]||=e=>E(M).platform=e},{prefix:O(()=>[_(f,{name:`at`})]),_:1},8,[`modelValue`]),_(v,{placeholder:`账号`,modelValue:E(M).userId,"onUpdate:modelValue":i[3]||=e=>E(M).userId=e,onKeypress:k(A(a,[`stop`]),[`enter`])},{prefix:O(()=>[_(f,{name:`user`})]),_:1},8,[`modelValue`,`onKeypress`]),t.value?(x(),m(`p`,V,T(t.value),1)):p(`v-if`,!0),h(`div`,H,[_(o,{onClick:d},{default:O(()=>[...i[12]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:a},{default:O(()=>[...i[13]||=[g(`获取验证码`,-1)]]),_:1})])],64)):(x(),m(u,{key:3},[_(v,{placeholder:`用户名`,modelValue:E(M).name,"onUpdate:modelValue":i[4]||=e=>E(M).name=e},{prefix:O(()=>[_(f,{name:`user`})]),_:1},8,[`modelValue`]),_(v,{placeholder:`密码`,modelValue:E(M).password,"onUpdate:modelValue":i[6]||=e=>E(M).password=e,onKeypress:k(A(c,[`stop`]),[`enter`]),type:r.value?`text`:`password`},{prefix:O(()=>[_(f,{name:`lock`})]),suffix:O(()=>[_(f,{name:r.value?`eye`:`eye-slash`,onClick:i[5]||=e=>r.value=!r.value},null,8,[`name`])]),_:1},8,[`modelValue`,`onKeypress`,`type`]),t.value?(x(),m(`p`,U,T(t.value),1)):p(`v-if`,!0),h(`div`,W,[_(o,{onClick:d},{default:O(()=>[...i[14]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:c},{default:O(()=>[...i[15]||=[g(`登录`,-1)]]),_:1})])],64))],64))])}}}),K=v({__name:`bind-dialog`,setup(e){return(e,t)=>{let n=w(`el-dialog`);return x(),f(n,{center:``,modelValue:E(N),"onUpdate:modelValue":t[0]||=e=>b(N)?N.value=e:null,class:`bind-dialog`},{default:O(()=>[_(G)]),_:1},8,[`modelValue`])}}}),q=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},J={},Y={class:`k-icon k-icon-at`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function X(e,t){return x(),m(`svg`,Y,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M256 8C118.941 8 8 118.919 8 256c0 137.059 110.919 248 248 248 48.154 0 95.342-14.14 135.408-40.223 12.005-7.815 14.625-24.288 5.552-35.372l-10.177-12.433c-7.671-9.371-21.179-11.667-31.373-5.129C325.92 429.757 291.314 440 256 440c-101.458 0-184-82.542-184-184S154.542 72 256 72c100.139 0 184 57.619 184 160 0 38.786-21.093 79.742-58.17 83.693-17.349-.454-16.91-12.857-13.476-30.024l23.433-121.11C394.653 149.75 383.308 136 368.225 136h-44.981a13.518 13.518 0 0 0-13.432 11.993l-.01.092c-14.697-17.901-40.448-21.775-59.971-21.775-74.58 0-137.831 62.234-137.831 151.46 0 65.303 36.785 105.87 96 105.87 26.984 0 57.369-15.637 74.991-38.333 9.522 34.104 40.613 34.103 70.71 34.103C462.609 379.41 504 307.798 504 232 504 95.653 394.023 8 256 8zm-21.68 304.43c-22.249 0-36.07-15.623-36.07-40.771 0-44.993 30.779-72.729 58.63-72.729 22.292 0 35.601 15.241 35.601 40.77 0 45.061-33.875 72.73-58.161 72.73z`},null,-1)]])}var Z=q(J,[[`render`,X]]),Q={},ne={class:`k-icon check`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function re(e,t){return x(),m(`svg`,ne,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M438.6 105.4C451.1 117.9 451.1 138.1 438.6 150.6L182.6 406.6C170.1 419.1 149.9 419.1 137.4 406.6L9.372 278.6C-3.124 266.1-3.124 245.9 9.372 233.4C21.87 220.9 42.13 220.9 54.63 233.4L159.1 338.7L393.4 105.4C405.9 92.88 426.1 92.88 438.6 105.4H438.6z`},null,-1)]])}var ie=q(Q,[[`render`,re]]),ae={},oe={class:`k-icon k-icon-lock`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function se(e,t){return x(),m(`svg`,oe,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z`},null,-1)]])}var ce=q(ae,[[`render`,se]]),le={},ue={class:`k-icon k-icon-sign-in`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function de(e,t){return x(),m(`svg`,ue,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M384 256c0-8.188-3.125-16.38-9.375-22.62l-128-128C237.5 96.22 223.7 93.47 211.8 98.44C199.8 103.4 192 115.1 192 128v64H48C21.49 192 0 213.5 0 240v32C0 298.5 21.49 320 48 320H192v64c0 12.94 7.797 24.62 19.75 29.56c11.97 4.969 25.72 2.219 34.88-6.938l128-128C380.9 272.4 384 264.2 384 256zM224 384V288H48C39.18 288 32 280.8 32 272v-32C32 231.2 39.18 224 48 224H224L223.1 128l128 128L224 384zM432 32h-96C327.2 32 320 39.16 320 48S327.2 64 336 64h96C458.5 64 480 85.53 480 112v288c0 26.47-21.53 48-48 48h-96c-8.844 0-16 7.156-16 16s7.156 16 16 16h96c44.13 0 80-35.88 80-80v-288C512 67.88 476.1 32 432 32z`},null,-1)]])}var fe=q(le,[[`render`,de]]),pe={},me={class:`k-icon k-icon-sign-out`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function he(e,t){return x(),m(`svg`,me,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M176 448h-96C53.53 448 32 426.5 32 400v-288C32 85.53 53.53 64 80 64h96C184.8 64 192 56.84 192 48S184.8 32 176 32h-96C35.88 32 0 67.88 0 112v288C0 444.1 35.88 480 80 480h96C184.8 480 192 472.8 192 464S184.8 448 176 448zM502.6 233.4l-128-128c-9.156-9.156-22.91-11.91-34.88-6.938C327.8 103.4 320 115.1 320 128l.0918 63.1L176 192C149.5 192 128 213.5 128 240v32C128 298.5 149.5 320 176 320l144.1-.001L320 384c0 12.94 7.797 24.62 19.75 29.56c11.97 4.969 25.72 2.219 34.88-6.938l128-128C508.9 272.4 512 264.2 512 256S508.9 239.6 502.6 233.4zM352 384V288H176C167.2 288 160 280.8 160 272v-32C160 231.2 167.2 224 176 224H352l-.0039-96l128 128L352 384z`},null,-1)]])}var ge=q(pe,[[`render`,he]]),_e={},ve={class:`k-icon`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function ye(e,t){return x(),m(`svg`,ve,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M256 0C114.6 0 0 114.6 0 256s114.6 256 256 256s256-114.6 256-256S397.4 0 256 0zM256 480c-47.24 0-91.04-14.78-127.2-39.84C132.9 390.9 173.8 352 224 352h64c50.25 0 91.14 38.94 95.21 88.16C347 465.2 303.2 480 256 480zM411.7 416.7C397.6 361.3 347.7 320 288 320H224c-59.73 0-109.6 41.3-123.7 96.72C58.27 375.1 32 319 32 256c0-123.5 100.5-224 224-224s224 100.5 224 224C480 319 453.7 375.1 411.7 416.7zM256 128C211.8 128 176 163.8 176 208C176 252.2 211.8 288 256 288s80-35.82 80-80C336 163.8 300.2 128 256 128zM256 256C229.5 256 208 234.5 208 208S229.5 160 256 160s48 21.53 48 48S282.5 256 256 256z`},null,-1)]])}var be=q(_e,[[`render`,ye]]),$=v({__name:`login`,setup(e){return(e,t)=>{let n=w(`k-card`),r=w(`k-layout`);return x(),f(r,{main:`darker page-login`},{default:O(()=>[_(n,null,{default:O(()=>[_(G)]),_:1})]),_:1})}}}),xe={class:`k-schema-header`},Se={class:`header`},Ce={class:`left`},we={class:`right`},Te=v({__name:`profile`,setup(t){let n={platform:`平台账户`,password:`用户密码`},i=S({}),a=d(()=>e.object({name:e.string().description(`用户名`).default(M.value.name),password:e.string().role(`secret`).description(`密码`).default(M.value.password)}).description(`基本资料`));async function c(){return s.user=null,delete M.value.id,delete M.value.token,delete M.value.expiredAt,o(`user/logout`)}async function l(){try{await o(`user/update`,i.value),r.success(`修改成功!`),Object.assign(M.value,i.value),Object.assign(s.user,i.value),i.value={}}catch(e){r.error(e.message)}}let v=d(()=>s.user?.bindings.filter(e=>s.user.id===e.bid)),y=d(()=>[{icon:`check`,label:`应用更改`,disabled:!i.value||!Object.keys(i.value).length,action:l},{type:`danger`,icon:`sign-out`,label:`退出登录`,action:c}]);return(e,t)=>{let r=w(`k-form`),c=w(`el-button`),l=w(`k-content`),d=w(`k-layout`);return x(),f(d,{main:`page-profile`,menu:y.value},{default:O(()=>[_(l,null,{default:O(()=>[_(r,{schema:a.value,modelValue:i.value,"onUpdate:modelValue":t[0]||=e=>i.value=e},null,8,[`schema`,`modelValue`]),h(`h2`,xe,[t[3]||=g(` 平台绑定 `,-1),_(c,{solid:``,class:`right`,onClick:t[1]||=e=>N.value=!0},{default:O(()=>[...t[2]||=[g(`添加`,-1)]]),_:1})]),(x(!0),m(u,null,C(E(s).user.bindings,({platform:e,pid:n,bid:r})=>(x(),m(`div`,{class:`k-schema-item`,key:`${e}:${n}`},[h(`div`,Se,[h(`div`,Ce,T(e)+` (`+T(n)+`)`,1),h(`div`,we,[v.value.length>1||r!==E(s).user.id?(x(),f(c,{key:0,onClick:A(t=>E(o)(`user/unbind`,e,n),[`stop`,`prevent`])},{default:O(()=>[...t[4]||=[g(`解绑`,-1)]]),_:1},8,[`onClick`])):p(`v-if`,!0)])])]))),128)),t[6]||=h(`h2`,{class:`k-schema-header`},`登录历史`,-1),h(`ul`,null,[(x(!0),m(u,null,C(E(s).user.tokens,({inc:e,type:r,createdAt:i,lastUsedAt:a,address:s,userAgent:l})=>(x(),m(`li`,{key:e},[h(`div`,null,`登录类型:`+T(n[r]),1),h(`div`,null,`登录时间:`+T(i),1),h(`div`,null,`最后访问:`+T(a),1),h(`div`,null,`IP 地址:`+T(s),1),h(`div`,null,`客户端:`+T(l),1),h(`div`,null,[_(c,{onClick:t=>E(o)(`user/delete-token`,e)},{default:O(()=>[...t[5]||=[g(`移除会话`,-1)]]),_:1},8,[`onClick`])])]))),128))])]),_:1})]),_:1},8,[`menu`])}}}),Ee=q(v({__name:`sync-dialog`,setup(e){let t=c();async function n(e){if(M.value.sync=!!e,P.value=!1,e){if(e===`download`){t.value=s.user.config;return}try{await o(`user/update`,{config:t.value})}catch(e){r.error(e.message)}}}return(e,r)=>{let i=w(`el-button`),a=w(`el-button-group`),o=w(`el-dialog`);return x(),f(o,{class:`sync-dialog`,onClose:r[3]||=e=>E(t).sync??=!1,"show-close":!1,"close-on-click-modal":!1,"close-on-press-escape":!1,modelValue:E(P),"onUpdate:modelValue":r[4]||=e=>b(P)?P.value=e:null},{default:O(()=>[r[8]||=h(`p`,{class:`text-center`},`检测到你本地的配置与云端不同步,是否同步配置?`,-1),_(a,{class:`text-center`},{default:O(()=>[_(i,{onClick:r[0]||=e=>n(`upload`)},{default:O(()=>[...r[5]||=[g(`上传当前配置`,-1)]]),_:1}),_(i,{onClick:r[1]||=e=>n(`download`)},{default:O(()=>[...r[6]||=[g(`下载云端配置`,-1)]]),_:1}),_(i,{onClick:r[2]||=e=>n()},{default:O(()=>[...r[7]||=[g(`关闭配置同步`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`])}}}),[[`__scopeId`,`data-v-440ef018`]]);n.register(`at`,Z),n.register(`check`,ie),n.register(`lock`,ce),n.register(`sign-in`,fe),n.register(`sign-out`,ge),n.register(`user-full`,be);var De=n=>{let{token:l,id:u,expiredAt:d}=M.value;l&&u!==void 0&&d!==void 0&&d>Date.now()&&o(`login/token`,u,l).catch(e=>r.error(e.message)),n.on(`activity`,e=>{let t=e.authority??0;return t>0&&(!s.user||s.user.authority<t)}),n.scope.disposables.push(a.beforeEach(e=>{let{activity:t}=e.meta;if(t){if((t.authority||(t.fields??[]).includes(`user`))&&!s.user)return history.state.forward===`/login`?`/`:`/login`;if(t.authority&&s.user&&t.authority>s.user.authority)return r.error(`权限不足。`),!1}})),n.page({path:`/login`,name:`登录`,icon:`sign-in`,position:`bottom`,order:500,disabled:()=>!!s.user,component:$}),n.page({path:`/profile`,name:`用户资料`,icon:`user-full`,fields:[`user`],position:`bottom`,order:500,component:Te}),n.slot({type:`global`,component:K}),n.slot({type:`global`,component:Ee}),n.settings({id:`user`,title:`用户设置`,component:v(()=>()=>y(w(`k-form`),{schema:e.object({sync:e.boolean().description(`在多个客户端间同步设置。`)}).description(`同步设置`),initial:M.value,modelValue:M.value,"onUpdate:modelValue":e=>M.value=e}))});let f=c();function p(){s.user&&(t(s.user.config,f.value)||(P.value=!0))}n.on(`dispose`,D(f,async e=>{e&&s.user&&M.value.sync&&await o(`user/update`,{config:e})},{deep:!0})),n.on(`dispose`,D(()=>M.value.sync,async e=>{e&&s.user&&p()})),n.on(`dispose`,D(()=>s.user,(e,t)=>{if(N.value=!1,!e)return a.push(`/login`);if(M.value.sync&&p(),t)return;Object.assign(M.value,i(e,[`id`,`name`,`token`,`expiredAt`])),r.success(`欢迎回来,${e.name||`Koishi 用户`}!`);let n=a.currentRoute.value.redirectedFrom;n&&!n.path.startsWith(`/login`)?a.push(n):a.push(`/profile`)}))};export{De as default};
|
|
1
|
+
import{Schema as e,deepEqual as t,icons as n,message as r,pick as i,router as a,send as o,store as s,useConfig as c,useStorage as l}from"@koishi-ce/client";import{Fragment as u,computed as d,createBlock as f,createCommentVNode as p,createElementBlock as m,createElementVNode as h,createTextVNode as g,createVNode as _,defineComponent as v,h as y,isRef as b,openBlock as x,ref as S,renderList as C,resolveComponent as w,toDisplayString as T,unref as E,watch as D,withCtx as O,withKeys as k,withModifiers as A}from"vue";import{useRouter as j}from"vue-router";var M=l(`auth`,2,()=>({authType:0})),N=S(!1),P=S(!1),F={class:`login-form text-center`},ee={key:0},te={key:1},I={class:`hint`},L={class:`token`},R={class:`control`},z={key:0},B={key:1},V={key:0,class:`error`},H={class:`control`},U={key:0,class:`error`},W={class:`control`},G=v({__name:`login-form`,setup(e){let t=S(),n=S(),r=S(!1),i=0;async function a(){let e=Date.now();if(e<i)return;let{platform:r,userId:a}=M.value;if(r&&a){i=e+1e3;try{n.value=await o(`login/platform`,r,a)}catch(e){t.value=e instanceof Error?e.message:String(e)}}}async function c(){let{name:e,password:n}=M.value;if(e&&n)try{await o(`login/password`,e,n)}catch(e){t.value=e instanceof Error?e.message:String(e)}}let l=j();function d(){s.user?N.value=!1:l.back()}return(e,i)=>{let o=w(`k-button`),l=w(`k-tab`),f=w(`k-icon`),v=w(`el-input`);return x(),m(`div`,F,[n.value?(x(),m(u,{key:0},[E(s).user?(x(),m(`h1`,ee,[...i[7]||=[h(`span`,null,`平台账户绑定`,-1)]])):(x(),m(`h1`,te,[...i[8]||=[h(`span`,null,`平台账户登录`,-1)]])),h(`p`,I,`欢迎你,`+T(n.value.name||`Koishi 用户`)+`!`,1),i[10]||=h(`p`,{class:`hint`},`请用上述账号将下面的验证码发送给任意正在运行的机器人`,-1),h(`p`,L,T(n.value.token),1),h(`div`,R,[_(o,{onClick:i[0]||=e=>n.value.token=``},{default:O(()=>[...i[9]||=[g(`返回上一步`,-1)]]),_:1})])],64)):(x(),m(u,{key:1},[E(s).user?(x(),m(`h1`,z,[...i[11]||=[h(`span`,null,`平台账户绑定`,-1)]])):(x(),m(`h1`,B,[_(l,{data:[`用户密码登录`,`平台账户登录`],modelValue:E(M).authType,"onUpdate:modelValue":i[1]||=e=>E(M).authType=e},null,8,[`modelValue`])])),E(s).user||E(M).authType===1?(x(),m(u,{key:2},[_(v,{placeholder:`平台名`,modelValue:E(M).platform,"onUpdate:modelValue":i[2]||=e=>E(M).platform=e},{prefix:O(()=>[_(f,{name:`at`})]),_:1},8,[`modelValue`]),_(v,{placeholder:`账号`,modelValue:E(M).userId,"onUpdate:modelValue":i[3]||=e=>E(M).userId=e,onKeypress:k(A(a,[`stop`]),[`enter`])},{prefix:O(()=>[_(f,{name:`user`})]),_:1},8,[`modelValue`,`onKeypress`]),t.value?(x(),m(`p`,V,T(t.value),1)):p(`v-if`,!0),h(`div`,H,[_(o,{onClick:d},{default:O(()=>[...i[12]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:a},{default:O(()=>[...i[13]||=[g(`获取验证码`,-1)]]),_:1})])],64)):(x(),m(u,{key:3},[_(v,{placeholder:`用户名`,modelValue:E(M).name,"onUpdate:modelValue":i[4]||=e=>E(M).name=e},{prefix:O(()=>[_(f,{name:`user`})]),_:1},8,[`modelValue`]),_(v,{placeholder:`密码`,modelValue:E(M).password,"onUpdate:modelValue":i[6]||=e=>E(M).password=e,onKeypress:k(A(c,[`stop`]),[`enter`]),type:r.value?`text`:`password`},{prefix:O(()=>[_(f,{name:`lock`})]),suffix:O(()=>[_(f,{name:r.value?`eye`:`eye-slash`,onClick:i[5]||=e=>r.value=!r.value},null,8,[`name`])]),_:1},8,[`modelValue`,`onKeypress`,`type`]),t.value?(x(),m(`p`,U,T(t.value),1)):p(`v-if`,!0),h(`div`,W,[_(o,{onClick:d},{default:O(()=>[...i[14]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:c},{default:O(()=>[...i[15]||=[g(`登录`,-1)]]),_:1})])],64))],64))])}}}),K=v({__name:`bind-dialog`,setup(e){return(e,t)=>{let n=w(`el-dialog`);return x(),f(n,{center:``,modelValue:E(N),"onUpdate:modelValue":t[0]||=e=>b(N)?N.value=e:null,class:`bind-dialog`},{default:O(()=>[_(G)]),_:1},8,[`modelValue`])}}}),q=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},J={},Y={class:`k-icon k-icon-at`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function X(e,t){return x(),m(`svg`,Y,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M256 8C118.941 8 8 118.919 8 256c0 137.059 110.919 248 248 248 48.154 0 95.342-14.14 135.408-40.223 12.005-7.815 14.625-24.288 5.552-35.372l-10.177-12.433c-7.671-9.371-21.179-11.667-31.373-5.129C325.92 429.757 291.314 440 256 440c-101.458 0-184-82.542-184-184S154.542 72 256 72c100.139 0 184 57.619 184 160 0 38.786-21.093 79.742-58.17 83.693-17.349-.454-16.91-12.857-13.476-30.024l23.433-121.11C394.653 149.75 383.308 136 368.225 136h-44.981a13.518 13.518 0 0 0-13.432 11.993l-.01.092c-14.697-17.901-40.448-21.775-59.971-21.775-74.58 0-137.831 62.234-137.831 151.46 0 65.303 36.785 105.87 96 105.87 26.984 0 57.369-15.637 74.991-38.333 9.522 34.104 40.613 34.103 70.71 34.103C462.609 379.41 504 307.798 504 232 504 95.653 394.023 8 256 8zm-21.68 304.43c-22.249 0-36.07-15.623-36.07-40.771 0-44.993 30.779-72.729 58.63-72.729 22.292 0 35.601 15.241 35.601 40.77 0 45.061-33.875 72.73-58.161 72.73z`},null,-1)]])}var Z=q(J,[[`render`,X]]),Q={},ne={class:`k-icon check`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function re(e,t){return x(),m(`svg`,ne,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M438.6 105.4C451.1 117.9 451.1 138.1 438.6 150.6L182.6 406.6C170.1 419.1 149.9 419.1 137.4 406.6L9.372 278.6C-3.124 266.1-3.124 245.9 9.372 233.4C21.87 220.9 42.13 220.9 54.63 233.4L159.1 338.7L393.4 105.4C405.9 92.88 426.1 92.88 438.6 105.4H438.6z`},null,-1)]])}var ie=q(Q,[[`render`,re]]),ae={},oe={class:`k-icon k-icon-lock`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function se(e,t){return x(),m(`svg`,oe,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z`},null,-1)]])}var ce=q(ae,[[`render`,se]]),le={},ue={class:`k-icon k-icon-sign-in`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function de(e,t){return x(),m(`svg`,ue,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M384 256c0-8.188-3.125-16.38-9.375-22.62l-128-128C237.5 96.22 223.7 93.47 211.8 98.44C199.8 103.4 192 115.1 192 128v64H48C21.49 192 0 213.5 0 240v32C0 298.5 21.49 320 48 320H192v64c0 12.94 7.797 24.62 19.75 29.56c11.97 4.969 25.72 2.219 34.88-6.938l128-128C380.9 272.4 384 264.2 384 256zM224 384V288H48C39.18 288 32 280.8 32 272v-32C32 231.2 39.18 224 48 224H224L223.1 128l128 128L224 384zM432 32h-96C327.2 32 320 39.16 320 48S327.2 64 336 64h96C458.5 64 480 85.53 480 112v288c0 26.47-21.53 48-48 48h-96c-8.844 0-16 7.156-16 16s7.156 16 16 16h96c44.13 0 80-35.88 80-80v-288C512 67.88 476.1 32 432 32z`},null,-1)]])}var fe=q(le,[[`render`,de]]),pe={},me={class:`k-icon k-icon-sign-out`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function he(e,t){return x(),m(`svg`,me,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M176 448h-96C53.53 448 32 426.5 32 400v-288C32 85.53 53.53 64 80 64h96C184.8 64 192 56.84 192 48S184.8 32 176 32h-96C35.88 32 0 67.88 0 112v288C0 444.1 35.88 480 80 480h96C184.8 480 192 472.8 192 464S184.8 448 176 448zM502.6 233.4l-128-128c-9.156-9.156-22.91-11.91-34.88-6.938C327.8 103.4 320 115.1 320 128l.0918 63.1L176 192C149.5 192 128 213.5 128 240v32C128 298.5 149.5 320 176 320l144.1-.001L320 384c0 12.94 7.797 24.62 19.75 29.56c11.97 4.969 25.72 2.219 34.88-6.938l128-128C508.9 272.4 512 264.2 512 256S508.9 239.6 502.6 233.4zM352 384V288H176C167.2 288 160 280.8 160 272v-32C160 231.2 167.2 224 176 224H352l-.0039-96l128 128L352 384z`},null,-1)]])}var ge=q(pe,[[`render`,he]]),_e={},ve={class:`k-icon`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function ye(e,t){return x(),m(`svg`,ve,[...t[0]||=[h(`path`,{fill:`currentColor`,d:`M256 0C114.6 0 0 114.6 0 256s114.6 256 256 256s256-114.6 256-256S397.4 0 256 0zM256 480c-47.24 0-91.04-14.78-127.2-39.84C132.9 390.9 173.8 352 224 352h64c50.25 0 91.14 38.94 95.21 88.16C347 465.2 303.2 480 256 480zM411.7 416.7C397.6 361.3 347.7 320 288 320H224c-59.73 0-109.6 41.3-123.7 96.72C58.27 375.1 32 319 32 256c0-123.5 100.5-224 224-224s224 100.5 224 224C480 319 453.7 375.1 411.7 416.7zM256 128C211.8 128 176 163.8 176 208C176 252.2 211.8 288 256 288s80-35.82 80-80C336 163.8 300.2 128 256 128zM256 256C229.5 256 208 234.5 208 208S229.5 160 256 160s48 21.53 48 48S282.5 256 256 256z`},null,-1)]])}var be=q(_e,[[`render`,ye]]),$=v({__name:`login`,setup(e){return(e,t)=>{let n=w(`k-card`),r=w(`k-layout`);return x(),f(r,{main:`darker page-login`},{default:O(()=>[_(n,null,{default:O(()=>[_(G)]),_:1})]),_:1})}}}),xe={class:`k-schema-header`},Se={class:`header`},Ce={class:`left`},we={class:`right`},Te=v({__name:`profile`,setup(t){let n={platform:`平台账户`,password:`用户密码`,token:`令牌续期`},i=S({}),a=d(()=>e.object({name:e.string().description(`用户名`).default(M.value.name??``),password:e.string().role(`secret`).description(`密码`).default(M.value.password??``)}).description(`基本资料`));async function c(){return delete s.user,delete M.value.id,delete M.value.token,delete M.value.expiredAt,o(`user/logout`)}async function l(){try{await o(`user/update`,i.value),r.success(`修改成功!`),Object.assign(M.value,i.value),s.user&&Object.assign(s.user,i.value),i.value={}}catch(e){r.error(e instanceof Error?e.message:String(e))}}let v=d(()=>{let e=s.user;return e?.bindings.filter(t=>e.id===t.bid)??[]}),y=d(()=>[{icon:`check`,label:`应用更改`,disabled:!i.value||!Object.keys(i.value).length,action:l},{type:`danger`,icon:`sign-out`,label:`退出登录`,action:c}]);return(e,t)=>{let r=w(`k-form`),c=w(`el-button`),l=w(`k-content`),d=w(`k-layout`);return x(),f(d,{main:`page-profile`,menu:y.value},{default:O(()=>[_(l,null,{default:O(()=>[_(r,{schema:a.value,modelValue:i.value,"onUpdate:modelValue":t[0]||=e=>i.value=e},null,8,[`schema`,`modelValue`]),h(`h2`,xe,[t[3]||=g(` 平台绑定 `,-1),_(c,{solid:``,class:`right`,onClick:t[1]||=e=>N.value=!0},{default:O(()=>[...t[2]||=[g(`添加`,-1)]]),_:1})]),(x(!0),m(u,null,C(E(s).user?.bindings??[],({platform:e,pid:n,bid:r})=>(x(),m(`div`,{class:`k-schema-item`,key:`${e}:${n}`},[h(`div`,Se,[h(`div`,Ce,T(e)+` (`+T(n)+`)`,1),h(`div`,we,[v.value.length>1||r!==E(s).user?.id?(x(),f(c,{key:0,onClick:A(t=>E(o)(`user/unbind`,e,n),[`stop`,`prevent`])},{default:O(()=>[...t[4]||=[g(`解绑`,-1)]]),_:1},8,[`onClick`])):p(`v-if`,!0)])])]))),128)),t[6]||=h(`h2`,{class:`k-schema-header`},`登录历史`,-1),h(`ul`,null,[(x(!0),m(u,null,C(E(s).user?.tokens??[],({inc:e,type:r,createdAt:i,lastUsedAt:a,address:s,userAgent:l})=>(x(),m(`li`,{key:e},[h(`div`,null,`登录类型:`+T(n[r]),1),h(`div`,null,`登录时间:`+T(i),1),h(`div`,null,`最后访问:`+T(a),1),h(`div`,null,`IP 地址:`+T(s),1),h(`div`,null,`客户端:`+T(l),1),h(`div`,null,[_(c,{onClick:t=>E(o)(`user/delete-token`,e)},{default:O(()=>[...t[5]||=[g(`移除会话`,-1)]]),_:1},8,[`onClick`])])]))),128))])]),_:1})]),_:1},8,[`menu`])}}}),Ee=q(v({__name:`sync-dialog`,setup(e){let t=c();async function n(e){if(M.value.sync=!!e,P.value=!1,e){if(e===`download`){if(!s.user)return;t.value=s.user.config;return}try{await o(`user/update`,{config:t.value})}catch(e){r.error(e instanceof Error?e.message:String(e))}}}return(e,r)=>{let i=w(`el-button`),a=w(`el-button-group`),o=w(`el-dialog`);return x(),f(o,{class:`sync-dialog`,onClose:r[3]||=e=>E(t).sync??=!1,"show-close":!1,"close-on-click-modal":!1,"close-on-press-escape":!1,modelValue:E(P),"onUpdate:modelValue":r[4]||=e=>b(P)?P.value=e:null},{default:O(()=>[r[8]||=h(`p`,{class:`text-center`},`检测到你本地的配置与云端不同步,是否同步配置?`,-1),_(a,{class:`text-center`},{default:O(()=>[_(i,{onClick:r[0]||=e=>n(`upload`)},{default:O(()=>[...r[5]||=[g(`上传当前配置`,-1)]]),_:1}),_(i,{onClick:r[1]||=e=>n(`download`)},{default:O(()=>[...r[6]||=[g(`下载云端配置`,-1)]]),_:1}),_(i,{onClick:r[2]||=e=>n()},{default:O(()=>[...r[7]||=[g(`关闭配置同步`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`])}}}),[[`__scopeId`,`data-v-61c950af`]]);n.register(`at`,Z),n.register(`check`,ie),n.register(`lock`,ce),n.register(`sign-in`,fe),n.register(`sign-out`,ge),n.register(`user-full`,be);var De=n=>{let{token:l,id:u,expiredAt:d}=M.value;l&&u!==void 0&&d!==void 0&&d>Date.now()&&o(`login/token`,u,l).catch(e=>r.error(e.message)),n.on(`activity`,e=>{let t=e.authority??0;return t>0&&(!s.user||s.user.authority<t)}),n.scope.disposables.push(a.beforeEach(e=>{let{activity:t}=e.meta;if(t){if((t.authority||(t.fields??[]).includes(`user`))&&!s.user)return history.state.forward===`/login`?`/`:`/login`;if(t.authority&&s.user&&t.authority>s.user.authority)return r.error(`权限不足。`),!1}})),n.page({path:`/login`,name:`登录`,icon:`sign-in`,position:`bottom`,order:500,disabled:()=>!!s.user,component:$}),n.page({path:`/profile`,name:`用户资料`,icon:`user-full`,fields:[`user`],position:`bottom`,order:500,component:Te}),n.slot({type:`global`,component:K}),n.slot({type:`global`,component:Ee}),n.settings({id:`user`,title:`用户设置`,component:v(()=>()=>y(w(`k-form`),{schema:e.object({sync:e.boolean().description(`在多个客户端间同步设置。`)}).description(`同步设置`),initial:M.value,modelValue:M.value,"onUpdate:modelValue":e=>M.value=e}))});let f=c();function p(){s.user&&(t(s.user.config,f.value)||(P.value=!0))}n.on(`dispose`,D(f,async e=>{e&&s.user&&M.value.sync&&await o(`user/update`,{config:e})},{deep:!0})),n.on(`dispose`,D(()=>M.value.sync,async e=>{e&&s.user&&p()})),n.on(`dispose`,D(()=>s.user,(e,t)=>{if(N.value=!1,!e)return a.push(`/login`);if(M.value.sync&&p(),t)return;Object.assign(M.value,i(e,[`id`,`name`,`token`,`expiredAt`])),r.success(`欢迎回来,${e.name||`Koishi 用户`}!`);let n=a.currentRoute.value.redirectedFrom;n&&!n.path.startsWith(`/login`)?a.push(n):a.push(`/profile`)}))};export{De as default};
|
package/dist/style.css
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
.login-form h1{cursor:default;margin:2.5rem auto;font-size:1.5rem}.login-form .token{font-weight:700}.login-form .el-input{margin:1rem auto;display:block}.login-form .el-input__wrapper{width:400px}.login-form .control{margin:2.5rem auto}.login-form .k-button{width:8rem;margin:0 1rem}.page-login{flex-direction:column;justify-content:center;align-items:center;display:flex}.page-login .k-card{flex-direction:column;justify-content:center;width:600px;margin:0;display:flex}.page-login .k-card .k-card-body{padding:3rem 0!important}.page-profile h1{margin:1.5rem 0;font-size:1.375rem;line-height:2rem}.page-profile .el-button.right{float:right}.el-button-group.text-center[data-v-
|
|
1
|
+
.login-form h1{cursor:default;margin:2.5rem auto;font-size:1.5rem}.login-form .token{font-weight:700}.login-form .el-input{margin:1rem auto;display:block}.login-form .el-input__wrapper{width:400px}.login-form .control{margin:2.5rem auto}.login-form .k-button{width:8rem;margin:0 1rem}.page-login{flex-direction:column;justify-content:center;align-items:center;display:flex}.page-login .k-card{flex-direction:column;justify-content:center;width:600px;margin:0;display:flex}.page-login .k-card .k-card-body{padding:3rem 0!important}.page-profile h1{margin:1.5rem 0;font-size:1.375rem;line-height:2rem}.page-profile .el-button.right{float:right}.el-button-group.text-center[data-v-61c950af]{justify-content:center;display:flex}.block{display:block}.h1{height:.25rem}.h2{height:.5rem}.flex{display:flex}.text-center{text-align:center}
|
|
2
2
|
/*$vite$:1*/
|
package/lib/index.d.ts
CHANGED
|
@@ -1,40 +1,8 @@
|
|
|
1
1
|
import { Binding, Context, Schema, Service, User } from "@koishi-ce/koishi";
|
|
2
2
|
import { Client, DataService } from "@koishi-ce/console";
|
|
3
|
-
//#region src/
|
|
4
|
-
declare module "@koishi-ce/koishi" {
|
|
5
|
-
interface Context {
|
|
6
|
-
auth: AuthService;
|
|
7
|
-
}
|
|
8
|
-
interface User {
|
|
9
|
-
password: string;
|
|
10
|
-
/** 客户端控制台配置的 JSON 快照(内容仅由浏览器端解释,服务端透传;建表初始为 null) */
|
|
11
|
-
config: object | null;
|
|
12
|
-
}
|
|
13
|
-
interface Tables {
|
|
14
|
-
token: LoginToken;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
declare module "@koishi-ce/console" {
|
|
18
|
-
interface Client {
|
|
19
|
-
auth?: Auth | undefined;
|
|
20
|
-
}
|
|
21
|
-
namespace Console {
|
|
22
|
-
interface Services {
|
|
23
|
-
user: DataService<AuthData>;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
interface Events {
|
|
27
|
-
"login/platform"(this: Client, platform: string, pid: string): Promise<UserLogin>;
|
|
28
|
-
"login/password"(this: Client, name: string, password: string): void;
|
|
29
|
-
"login/token"(this: Client, id: number, token: string): void;
|
|
30
|
-
"user/delete-token"(this: Client, inc: number): void;
|
|
31
|
-
"user/unbind"(this: Client, platform: string, pid: string): void;
|
|
32
|
-
"user/update"(this: Client, data: UserUpdate): void;
|
|
33
|
-
"user/logout"(this: Client): void;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
3
|
+
//#region src/types.d.ts
|
|
36
4
|
/** token 表记录:一次登录会话的令牌及其来源信息。 */
|
|
37
|
-
|
|
5
|
+
interface LoginToken {
|
|
38
6
|
/** 自增主键(删除指定会话用) */
|
|
39
7
|
inc: number;
|
|
40
8
|
/** 所属用户 id */
|
|
@@ -53,7 +21,7 @@ export interface LoginToken {
|
|
|
53
21
|
address: string;
|
|
54
22
|
}
|
|
55
23
|
/** 下发到客户端的登录态(user 数据服务的单条形态,不含 tokens/bindings 明细)。 */
|
|
56
|
-
|
|
24
|
+
type Auth = Pick<LoginToken, "token" | "expiredAt"> & Pick<User, "id" | "name" | "authority" | "config">;
|
|
57
25
|
/** user 数据服务下发给客户端的完整鉴权数据:登录态 + 会话列表 + 绑定列表。 */
|
|
58
26
|
interface AuthData extends Auth {
|
|
59
27
|
tokens: Omit<LoginToken, "token" | "id">[];
|
|
@@ -61,19 +29,55 @@ interface AuthData extends Auth {
|
|
|
61
29
|
}
|
|
62
30
|
/** 登录方式:平台验证码 / 用户密码 / 已存令牌续期。 */
|
|
63
31
|
type LoginType = "platform" | "password" | "token";
|
|
32
|
+
/** login/platform 事件的返回值:待登录用户信息 + 一次性验证码及其过期时间。 */
|
|
33
|
+
interface UserLogin extends Pick<User, "id" | "name"> {
|
|
34
|
+
token: string;
|
|
35
|
+
expiredAt: number;
|
|
36
|
+
}
|
|
37
|
+
/** user/update 事件允许修改的用户字段。 */
|
|
38
|
+
type UserUpdate = Partial<Pick<User, "name" | "password" | "config">>;
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/crypto.d.ts
|
|
64
41
|
/**
|
|
65
42
|
* 生成指定长度的随机令牌字符串。
|
|
66
43
|
* @param length 令牌长度,默认 40
|
|
67
44
|
* @returns 从字符表随机取字符拼接成的字符串
|
|
68
45
|
*/
|
|
69
46
|
export declare function randomId(length?: number): string;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/index.d.ts
|
|
49
|
+
declare module "@koishi-ce/koishi" {
|
|
50
|
+
interface Context {
|
|
51
|
+
auth: AuthService;
|
|
52
|
+
}
|
|
53
|
+
interface User {
|
|
54
|
+
password: string;
|
|
55
|
+
/** 客户端控制台配置的 JSON 快照(内容仅由浏览器端解释,服务端透传;建表初始为 null) */
|
|
56
|
+
config: object | null;
|
|
57
|
+
}
|
|
58
|
+
interface Tables {
|
|
59
|
+
token: LoginToken;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
declare module "@koishi-ce/console" {
|
|
63
|
+
interface Client {
|
|
64
|
+
auth?: Auth | undefined;
|
|
65
|
+
}
|
|
66
|
+
namespace Console {
|
|
67
|
+
interface Services {
|
|
68
|
+
user: DataService<AuthData>;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
interface Events {
|
|
72
|
+
"login/platform"(this: Client, platform: string, pid: string): Promise<UserLogin>;
|
|
73
|
+
"login/password"(this: Client, name: string, password: string): void;
|
|
74
|
+
"login/token"(this: Client, id: number, token: string): void;
|
|
75
|
+
"user/delete-token"(this: Client, inc: number): void;
|
|
76
|
+
"user/unbind"(this: Client, platform: string, pid: string): void;
|
|
77
|
+
"user/update"(this: Client, data: UserUpdate): void;
|
|
78
|
+
"user/logout"(this: Client): void;
|
|
79
|
+
}
|
|
74
80
|
}
|
|
75
|
-
/** user/update 事件允许修改的用户字段。 */
|
|
76
|
-
export type UserUpdate = Partial<Pick<User, "name" | "password" | "config">>;
|
|
77
81
|
/**
|
|
78
82
|
* 鉴权服务:维护控制台客户端的登录态。
|
|
79
83
|
*
|
|
@@ -104,8 +108,6 @@ declare class AuthService extends Service {
|
|
|
104
108
|
* 过期时长由 authTokenExpire 配置决定。
|
|
105
109
|
*/
|
|
106
110
|
createToken(client: Client, type: LoginType, user: Pick<User, "id" | "name" | "authority" | "config">): Promise<void>;
|
|
107
|
-
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
108
|
-
initLogin(): void;
|
|
109
111
|
}
|
|
110
112
|
declare namespace AuthService {
|
|
111
113
|
interface Admin {
|
|
@@ -120,4 +122,4 @@ declare namespace AuthService {
|
|
|
120
122
|
}
|
|
121
123
|
}
|
|
122
124
|
//#endregion
|
|
123
|
-
export { AuthService as default };
|
|
125
|
+
export { type Auth, type LoginToken, type UserLogin, type UserUpdate, AuthService as default };
|
package/lib/index.mjs
CHANGED
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
import { createHash, pbkdf2Sync, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
|
2
1
|
import { resolve } from "node:path";
|
|
3
2
|
import { Schema, Service, Time, omit } from "@koishi-ce/koishi";
|
|
4
3
|
import zhCN from "./assets/zh-CN-DChWGTwa.yml";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* auth 插件(服务端):控制台登录鉴权。
|
|
8
|
-
*
|
|
9
|
-
* 向应用注入 ctx.auth 服务(AuthService):扩展 user 表的 password 字段
|
|
10
|
-
* 并建立 token 会话表,支持用户密码 / 平台验证码 / 已存令牌三种登录方式,
|
|
11
|
-
* 维护每个 WebSocket 客户端的登录态(client.auth),并按登录用户的权限
|
|
12
|
-
* 拦截 console 事件。浏览器端对应实现在 ../client/(登录页、个人资料页、
|
|
13
|
-
* 配置同步对话框)。
|
|
14
|
-
*/
|
|
4
|
+
import { pbkdf2Sync, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
|
5
|
+
//#region src/crypto.ts
|
|
15
6
|
const letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
16
7
|
/**
|
|
17
8
|
* 生成指定长度的随机令牌字符串。
|
|
@@ -38,23 +29,161 @@ function toHash(password) {
|
|
|
38
29
|
/**
|
|
39
30
|
* 校验明文密码与库中存储是否匹配。
|
|
40
31
|
*
|
|
41
|
-
*
|
|
42
|
-
* -
|
|
43
|
-
* - 64 位十六进制旧格式:历史上无盐 SHA-256,仅用于校验(命中后由调用方
|
|
44
|
-
* 透明升级为 PBKDF2),同样以恒定时间比较。
|
|
32
|
+
* 仅接受 `pbkdf2$...` 格式:按存储的盐与迭代次数重派生,恒定时间比较;
|
|
33
|
+
* 其余形态(含历史上游遗留的无盐 SHA-256 十六进制)一律不匹配。
|
|
45
34
|
*/
|
|
46
35
|
function verifyPassword(password, stored) {
|
|
47
|
-
if (stored.startsWith("pbkdf2$"))
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
36
|
+
if (!stored.startsWith("pbkdf2$")) return false;
|
|
37
|
+
const [, rounds, saltHex, dkHex] = stored.split("$");
|
|
38
|
+
if (!rounds || !saltHex || !dkHex) return false;
|
|
39
|
+
const expected = Buffer.from(dkHex, "hex");
|
|
40
|
+
const actual = pbkdf2Sync(password, Buffer.from(saltHex, "hex"), Number(rounds), expected.length, "sha256");
|
|
41
|
+
return timingSafeEqual(actual, expected);
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/login.ts
|
|
45
|
+
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
46
|
+
function initLogin(auth) {
|
|
47
|
+
const self = auth;
|
|
48
|
+
const { ctx, config } = auth;
|
|
49
|
+
const states = {};
|
|
50
|
+
ctx.console.addListener("login/password", async function(name, password) {
|
|
51
|
+
const [user] = await ctx.database.get("user", { name }, [
|
|
52
|
+
"password",
|
|
53
|
+
"name",
|
|
54
|
+
"id",
|
|
55
|
+
"authority",
|
|
56
|
+
"config"
|
|
57
|
+
]);
|
|
58
|
+
if (!user?.password || !verifyPassword(password, user.password)) throw new Error("用户名或密码错误。");
|
|
59
|
+
await self.createToken(this, "password", omit(user, ["password"]));
|
|
60
|
+
});
|
|
61
|
+
ctx.console.addListener("login/token", async function(aid, token) {
|
|
62
|
+
const [data] = await ctx.database.get("token", {
|
|
63
|
+
id: aid,
|
|
64
|
+
token
|
|
65
|
+
}, ["expiredAt"]);
|
|
66
|
+
if (!data || data.expiredAt <= Date.now()) throw new Error("令牌已失效。");
|
|
67
|
+
const [user] = await ctx.database.get("user", { id: aid }, [
|
|
68
|
+
"id",
|
|
69
|
+
"name",
|
|
70
|
+
"authority",
|
|
71
|
+
"config"
|
|
72
|
+
]);
|
|
73
|
+
if (!user) throw new Error("用户不存在。");
|
|
74
|
+
await ctx.database.set("token", { token }, { lastUsedAt: /* @__PURE__ */ new Date() });
|
|
75
|
+
await self.setAuth(this, {
|
|
76
|
+
...user,
|
|
77
|
+
...data,
|
|
78
|
+
token
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
ctx.console.addListener("login/platform", async function(platform, userId) {
|
|
82
|
+
const user = await ctx.database.getUser(platform, userId, ["id", "name"]);
|
|
83
|
+
if (!user) throw new Error("找不到此账户。");
|
|
84
|
+
if (this.auth?.id === user.id) throw new Error("你已经绑定了此账户。");
|
|
85
|
+
const key = `${platform}:${userId}`;
|
|
86
|
+
const token = String(randomInt(0, 1e6)).padStart(6, "0");
|
|
87
|
+
const expiredAt = Date.now() + config.loginTokenExpire;
|
|
88
|
+
states[key] = [
|
|
89
|
+
token,
|
|
90
|
+
expiredAt,
|
|
91
|
+
this
|
|
92
|
+
];
|
|
93
|
+
const listener = () => {
|
|
94
|
+
delete states[key];
|
|
95
|
+
dispose();
|
|
96
|
+
this.socket.removeEventListener("close", dispose);
|
|
97
|
+
};
|
|
98
|
+
const dispose = ctx.setTimeout(() => {
|
|
99
|
+
const state = states[key];
|
|
100
|
+
if (state && state[1] >= Date.now()) listener();
|
|
101
|
+
}, config.loginTokenExpire);
|
|
102
|
+
this.socket.addEventListener("close", listener);
|
|
103
|
+
return {
|
|
104
|
+
id: user.id,
|
|
105
|
+
name: user.name,
|
|
106
|
+
token,
|
|
107
|
+
expiredAt
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
ctx.middleware(async (session, next) => {
|
|
111
|
+
const state = states[session.uid];
|
|
112
|
+
if (!state || state[0] !== session.stripped.content) return next();
|
|
113
|
+
const { platform, userId: pid } = session;
|
|
114
|
+
if (!pid) return next();
|
|
115
|
+
if (state[2].auth) {
|
|
116
|
+
await ctx.database.set("binding", {
|
|
117
|
+
platform,
|
|
118
|
+
pid
|
|
119
|
+
}, { aid: state[2].auth.id });
|
|
120
|
+
return self.setAuth(state[2], state[2].auth);
|
|
121
|
+
} else {
|
|
122
|
+
const user = await session.observeUser([
|
|
123
|
+
"id",
|
|
124
|
+
"name",
|
|
125
|
+
"authority",
|
|
126
|
+
"config"
|
|
127
|
+
]);
|
|
128
|
+
return self.createToken(state[2], "platform", user);
|
|
129
|
+
}
|
|
130
|
+
}, true);
|
|
131
|
+
ctx.on("console/intercept", async (client, listener) => {
|
|
132
|
+
if (!listener.authority) return false;
|
|
133
|
+
if (!client.auth) return true;
|
|
134
|
+
if (client.auth.expiredAt <= Date.now()) return true;
|
|
135
|
+
if (client.auth.authority < listener.authority) return true;
|
|
136
|
+
return false;
|
|
137
|
+
});
|
|
138
|
+
ctx.console.addListener("user/delete-token", async function(inc) {
|
|
139
|
+
if (!this.auth) throw new Error("请先登录。");
|
|
140
|
+
const [data] = await ctx.database.get("token", {
|
|
141
|
+
id: this.auth.id,
|
|
142
|
+
inc
|
|
143
|
+
});
|
|
144
|
+
if (!data) throw new Error("令牌不存在。");
|
|
145
|
+
await ctx.database.remove("token", { inc });
|
|
146
|
+
await self.setAuth(this);
|
|
147
|
+
});
|
|
148
|
+
ctx.console.addListener("user/logout", async function() {
|
|
149
|
+
if (this.auth) await ctx.database.remove("token", { token: this.auth.token });
|
|
150
|
+
await self.setAuth(this, void 0);
|
|
151
|
+
});
|
|
152
|
+
ctx.console.addListener("user/update", async function(data) {
|
|
153
|
+
if (!this.auth) throw new Error("请先登录。");
|
|
154
|
+
if (data.password) data.password = toHash(data.password);
|
|
155
|
+
await ctx.database.set("user", { id: this.auth.id }, data);
|
|
156
|
+
Object.assign(this.auth, data);
|
|
157
|
+
await self.setAuth(this, void 0, true);
|
|
158
|
+
});
|
|
159
|
+
ctx.console.addListener("user/unbind", async function(platform, pid) {
|
|
160
|
+
if (!this.auth) throw new Error("请先登录。");
|
|
161
|
+
const bindings = await ctx.database.get("binding", { aid: this.auth.id });
|
|
162
|
+
const binding = bindings.find((item) => item.platform === platform && item.pid === pid);
|
|
163
|
+
if (!binding) throw new Error("绑定不存在。");
|
|
164
|
+
if (binding.aid !== binding.bid) await ctx.database.set("binding", {
|
|
165
|
+
platform,
|
|
166
|
+
pid
|
|
167
|
+
}, { aid: binding.bid });
|
|
168
|
+
else if (bindings.filter((item) => item.aid === item.bid).length === 1) throw new Error("无法解除绑定。");
|
|
169
|
+
else await ctx.database.remove("binding", {
|
|
170
|
+
platform,
|
|
171
|
+
pid
|
|
172
|
+
});
|
|
173
|
+
await self.setAuth(this);
|
|
174
|
+
});
|
|
57
175
|
}
|
|
176
|
+
//#endregion
|
|
177
|
+
//#region src/index.ts
|
|
178
|
+
/**
|
|
179
|
+
* auth 插件(服务端):控制台登录鉴权。
|
|
180
|
+
*
|
|
181
|
+
* 向应用注入 ctx.auth 服务(AuthService):扩展 user 表的 password 字段
|
|
182
|
+
* 并建立 token 会话表,支持用户密码 / 平台验证码 / 已存令牌三种登录方式,
|
|
183
|
+
* 维护每个 WebSocket 客户端的登录态(client.auth),并按登录用户的权限
|
|
184
|
+
* 拦截 console 事件。浏览器端对应实现在 ../client/(登录页、个人资料页、
|
|
185
|
+
* 配置同步对话框)。
|
|
186
|
+
*/
|
|
58
187
|
/**
|
|
59
188
|
* 鉴权服务:维护控制台客户端的登录态。
|
|
60
189
|
*
|
|
@@ -105,7 +234,7 @@ var AuthService = class AuthService extends Service {
|
|
|
105
234
|
dev: resolve(import.meta.dir, "../client/index.ts"),
|
|
106
235
|
prod: resolve(import.meta.dir, "../dist")
|
|
107
236
|
});
|
|
108
|
-
|
|
237
|
+
initLogin(this);
|
|
109
238
|
}
|
|
110
239
|
/** 启动时按配置确保管理员账户(id = 0)存在。 */
|
|
111
240
|
async start() {
|
|
@@ -189,138 +318,6 @@ var AuthService = class AuthService extends Service {
|
|
|
189
318
|
token
|
|
190
319
|
});
|
|
191
320
|
}
|
|
192
|
-
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
193
|
-
initLogin() {
|
|
194
|
-
const self = this;
|
|
195
|
-
const { ctx, config } = this;
|
|
196
|
-
const states = {};
|
|
197
|
-
ctx.console.addListener("login/password", async function(name, password) {
|
|
198
|
-
const [user] = await ctx.database.get("user", { name }, [
|
|
199
|
-
"password",
|
|
200
|
-
"name",
|
|
201
|
-
"id",
|
|
202
|
-
"authority",
|
|
203
|
-
"config"
|
|
204
|
-
]);
|
|
205
|
-
if (!user?.password || !verifyPassword(password, user.password)) throw new Error("用户名或密码错误。");
|
|
206
|
-
if (!user.password.startsWith("pbkdf2$")) await ctx.database.set("user", user.id, { password: toHash(password) });
|
|
207
|
-
await self.createToken(this, "password", omit(user, ["password"]));
|
|
208
|
-
});
|
|
209
|
-
ctx.console.addListener("login/token", async function(aid, token) {
|
|
210
|
-
const [data] = await ctx.database.get("token", {
|
|
211
|
-
id: aid,
|
|
212
|
-
token
|
|
213
|
-
}, ["expiredAt"]);
|
|
214
|
-
if (!data || data.expiredAt <= Date.now()) throw new Error("令牌已失效。");
|
|
215
|
-
const [user] = await ctx.database.get("user", { id: aid }, [
|
|
216
|
-
"id",
|
|
217
|
-
"name",
|
|
218
|
-
"authority",
|
|
219
|
-
"config"
|
|
220
|
-
]);
|
|
221
|
-
if (!user) throw new Error("用户不存在。");
|
|
222
|
-
await ctx.database.set("token", { token }, { lastUsedAt: /* @__PURE__ */ new Date() });
|
|
223
|
-
await self.setAuth(this, {
|
|
224
|
-
...user,
|
|
225
|
-
...data,
|
|
226
|
-
token
|
|
227
|
-
});
|
|
228
|
-
});
|
|
229
|
-
ctx.console.addListener("login/platform", async function(platform, userId) {
|
|
230
|
-
const user = await ctx.database.getUser(platform, userId, ["id", "name"]);
|
|
231
|
-
if (!user) throw new Error("找不到此账户。");
|
|
232
|
-
if (this.auth?.id === user.id) throw new Error("你已经绑定了此账户。");
|
|
233
|
-
const key = `${platform}:${userId}`;
|
|
234
|
-
const token = String(randomInt(0, 1e6)).padStart(6, "0");
|
|
235
|
-
const expiredAt = Date.now() + config.loginTokenExpire;
|
|
236
|
-
states[key] = [
|
|
237
|
-
token,
|
|
238
|
-
expiredAt,
|
|
239
|
-
this
|
|
240
|
-
];
|
|
241
|
-
const listener = () => {
|
|
242
|
-
delete states[key];
|
|
243
|
-
dispose();
|
|
244
|
-
this.socket.removeEventListener("close", dispose);
|
|
245
|
-
};
|
|
246
|
-
const dispose = ctx.setTimeout(() => {
|
|
247
|
-
const state = states[key];
|
|
248
|
-
if (state && state[1] >= Date.now()) listener();
|
|
249
|
-
}, config.loginTokenExpire);
|
|
250
|
-
this.socket.addEventListener("close", listener);
|
|
251
|
-
return {
|
|
252
|
-
id: user.id,
|
|
253
|
-
name: user.name,
|
|
254
|
-
token,
|
|
255
|
-
expiredAt
|
|
256
|
-
};
|
|
257
|
-
});
|
|
258
|
-
ctx.middleware(async (session, next) => {
|
|
259
|
-
const state = states[session.uid];
|
|
260
|
-
if (!state || state[0] !== session.stripped.content) return next();
|
|
261
|
-
const { platform, userId: pid } = session;
|
|
262
|
-
if (!pid) return next();
|
|
263
|
-
if (state[2].auth) {
|
|
264
|
-
await ctx.database.set("binding", {
|
|
265
|
-
platform,
|
|
266
|
-
pid
|
|
267
|
-
}, { aid: state[2].auth.id });
|
|
268
|
-
return self.setAuth(state[2], state[2].auth);
|
|
269
|
-
} else {
|
|
270
|
-
const user = await session.observeUser([
|
|
271
|
-
"id",
|
|
272
|
-
"name",
|
|
273
|
-
"authority",
|
|
274
|
-
"config"
|
|
275
|
-
]);
|
|
276
|
-
return self.createToken(state[2], "platform", user);
|
|
277
|
-
}
|
|
278
|
-
}, true);
|
|
279
|
-
ctx.on("console/intercept", async (client, listener) => {
|
|
280
|
-
if (!listener.authority) return false;
|
|
281
|
-
if (!client.auth) return true;
|
|
282
|
-
if (client.auth.expiredAt <= Date.now()) return true;
|
|
283
|
-
if (client.auth.authority < listener.authority) return true;
|
|
284
|
-
return false;
|
|
285
|
-
});
|
|
286
|
-
ctx.console.addListener("user/delete-token", async function(inc) {
|
|
287
|
-
if (!this.auth) throw new Error("请先登录。");
|
|
288
|
-
const [data] = await ctx.database.get("token", {
|
|
289
|
-
id: this.auth.id,
|
|
290
|
-
inc
|
|
291
|
-
});
|
|
292
|
-
if (!data) throw new Error("令牌不存在。");
|
|
293
|
-
await ctx.database.remove("token", { inc });
|
|
294
|
-
await self.setAuth(this);
|
|
295
|
-
});
|
|
296
|
-
ctx.console.addListener("user/logout", async function() {
|
|
297
|
-
if (this.auth) await ctx.database.remove("token", { token: this.auth.token });
|
|
298
|
-
await self.setAuth(this, void 0);
|
|
299
|
-
});
|
|
300
|
-
ctx.console.addListener("user/update", async function(data) {
|
|
301
|
-
if (!this.auth) throw new Error("请先登录。");
|
|
302
|
-
if (data.password) data.password = toHash(data.password);
|
|
303
|
-
await ctx.database.set("user", { id: this.auth.id }, data);
|
|
304
|
-
Object.assign(this.auth, data);
|
|
305
|
-
await self.setAuth(this, void 0, true);
|
|
306
|
-
});
|
|
307
|
-
ctx.console.addListener("user/unbind", async function(platform, pid) {
|
|
308
|
-
if (!this.auth) throw new Error("请先登录。");
|
|
309
|
-
const bindings = await ctx.database.get("binding", { aid: this.auth.id });
|
|
310
|
-
const binding = bindings.find((item) => item.platform === platform && item.pid === pid);
|
|
311
|
-
if (!binding) throw new Error("绑定不存在。");
|
|
312
|
-
if (binding.aid !== binding.bid) await ctx.database.set("binding", {
|
|
313
|
-
platform,
|
|
314
|
-
pid
|
|
315
|
-
}, { aid: binding.bid });
|
|
316
|
-
else if (bindings.filter((item) => item.aid === item.bid).length === 1) throw new Error("无法解除绑定。");
|
|
317
|
-
else await ctx.database.remove("binding", {
|
|
318
|
-
platform,
|
|
319
|
-
pid
|
|
320
|
-
});
|
|
321
|
-
await self.setAuth(this);
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
321
|
};
|
|
325
322
|
//#endregion
|
|
326
323
|
export { AuthService as default, randomId };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@koishi-ce/plugin-auth",
|
|
3
3
|
"description": "Console User Authentication",
|
|
4
|
-
"version": "1.1.
|
|
4
|
+
"version": "1.1.4",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.mjs",
|
|
7
7
|
"typings": "lib/index.d.ts",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"@koishi-ce/koishi": "^1.0.0"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
|
-
"@koishi-ce/plugin-database-memory": "^1.1.
|
|
57
|
+
"@koishi-ce/plugin-database-memory": "^1.1.1",
|
|
58
58
|
"@koishi-ce/client": "^1.3.0",
|
|
59
59
|
"vue": "^3.5.12",
|
|
60
60
|
"vue-router": "^5.2.0"
|