@koishi-ce/plugin-auth 1.1.6 → 1.1.7
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.js +1 -1
- package/lib/index.d.ts +2 -8
- package/lib/index.mjs +79 -46
- package/package.json +4 -4
- package/src/__tests__/crypto.test.ts +66 -0
- package/src/__tests__/helpers.ts +4 -0
- package/src/__tests__/login.test.ts +5 -24
- package/src/__tests__/user-events.test.ts +84 -7
- package/src/__tests__/verification.test.ts +152 -42
- package/src/crypto.ts +30 -11
- package/src/index.ts +6 -4
- package/src/login.ts +125 -35
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,markRaw as x,openBlock as S,ref as C,renderList as w,resolveComponent as T,toDisplayString as E,unref as D,watch as O,withCtx as k,withKeys as A,withModifiers as j}from"vue";import{useRouter as M}from"vue-router";var N={class:`k-icon k-icon-at`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function ee(e,t){return S(),m(`svg`,N,[...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 te=x({name:`k-at`,render:ee}),ne={class:`k-icon check`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function P(e,t){return S(),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 F=x({name:`k-check`,render:P}),I={class:`k-icon k-icon-lock`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function L(e,t){return S(),m(`svg`,I,[...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 R=x({name:`k-lock`,render:L}),z={class:`k-icon k-icon-sign-in`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function B(e,t){return S(),m(`svg`,z,[...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 V=x({name:`k-sign-in`,render:B}),H={class:`k-icon k-icon-sign-out`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function U(e,t){return S(),m(`svg`,H,[...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 W=x({name:`k-sign-out`,render:U}),G={class:`k-icon`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function K(e,t){return S(),m(`svg`,G,[...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 q=x({name:`k-user-full`,render:K}),J=l(`auth`,2,()=>({authType:0})),Y=C(!1),X=C(!1),Z={class:`login-form text-center`},re={key:0},ie={key:1},ae={class:`hint`},oe={class:`token`},se={class:`control`},ce={key:0},le={key:1},ue={key:0,class:`error`},de={class:`control`},fe={key:0,class:`error`},pe={class:`control`},Q=v({__name:`login-form`,setup(e){let t=C(),n=C(),r=C(!1),i=0;async function a(){let e=Date.now();if(e<i)return;let{platform:r,userId:a}=J.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}=J.value;if(e&&n)try{await o(`login/password`,e,n)}catch(e){t.value=e instanceof Error?e.message:String(e)}}let l=M();function d(){s.user?Y.value=!1:l.back()}return(e,i)=>{let o=T(`k-button`),l=T(`k-tab`),f=T(`k-icon`),v=T(`el-input`);return S(),m(`div`,Z,[n.value?(S(),m(u,{key:0},[D(s).user?(S(),m(`h1`,re,[...i[7]||=[h(`span`,null,`平台账户绑定`,-1)]])):(S(),m(`h1`,ie,[...i[8]||=[h(`span`,null,`平台账户登录`,-1)]])),h(`p`,ae,`欢迎你,`+E(n.value.name||`Koishi 用户`)+`!`,1),i[10]||=h(`p`,{class:`hint`},`请用上述账号将下面的验证码发送给任意正在运行的机器人`,-1),h(`p`,oe,E(n.value.token),1),h(`div`,se,[_(o,{onClick:i[0]||=e=>n.value.token=``},{default:k(()=>[...i[9]||=[g(`返回上一步`,-1)]]),_:1})])],64)):(S(),m(u,{key:1},[D(s).user?(S(),m(`h1`,ce,[...i[11]||=[h(`span`,null,`平台账户绑定`,-1)]])):(S(),m(`h1`,le,[_(l,{data:[`用户密码登录`,`平台账户登录`],modelValue:D(J).authType,"onUpdate:modelValue":i[1]||=e=>D(J).authType=e},null,8,[`modelValue`])])),D(s).user||D(J).authType===1?(S(),m(u,{key:2},[_(v,{placeholder:`平台名`,modelValue:D(J).platform,"onUpdate:modelValue":i[2]||=e=>D(J).platform=e},{prefix:k(()=>[_(f,{name:`at`})]),_:1},8,[`modelValue`]),_(v,{placeholder:`账号`,modelValue:D(J).userId,"onUpdate:modelValue":i[3]||=e=>D(J).userId=e,onKeypress:A(j(a,[`stop`]),[`enter`])},{prefix:k(()=>[_(f,{name:`user`})]),_:1},8,[`modelValue`,`onKeypress`]),t.value?(S(),m(`p`,ue,E(t.value),1)):p(`v-if`,!0),h(`div`,de,[_(o,{onClick:d},{default:k(()=>[...i[12]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:a},{default:k(()=>[...i[13]||=[g(`获取验证码`,-1)]]),_:1})])],64)):(S(),m(u,{key:3},[_(v,{placeholder:`用户名`,modelValue:D(J).name,"onUpdate:modelValue":i[4]||=e=>D(J).name=e},{prefix:k(()=>[_(f,{name:`user`})]),_:1},8,[`modelValue`]),_(v,{placeholder:`密码`,modelValue:D(J).password,"onUpdate:modelValue":i[6]||=e=>D(J).password=e,onKeypress:A(j(c,[`stop`]),[`enter`]),type:r.value?`text`:`password`},{prefix:k(()=>[_(f,{name:`lock`})]),suffix:k(()=>[_(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?(S(),m(`p`,fe,E(t.value),1)):p(`v-if`,!0),h(`div`,pe,[_(o,{onClick:d},{default:k(()=>[...i[14]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:c},{default:k(()=>[...i[15]||=[g(`登录`,-1)]]),_:1})])],64))],64))])}}}),$=v({__name:`bind-dialog`,setup(e){return(e,t)=>{let n=T(`el-dialog`);return S(),f(n,{center:``,modelValue:D(Y),"onUpdate:modelValue":t[0]||=e=>b(Y)?Y.value=e:null,class:`bind-dialog`},{default:k(()=>[_(Q)]),_:1},8,[`modelValue`])}}}),me=v({__name:`login`,setup(e){return(e,t)=>{let n=T(`k-card`),r=T(`k-layout`);return S(),f(r,{main:`darker page-login`},{default:k(()=>[_(n,null,{default:k(()=>[_(Q)]),_:1})]),_:1})}}}),he={class:`k-schema-header`},ge={class:`header`},_e={class:`left`},ve={class:`right`},ye=v({__name:`profile`,setup(t){let n={platform:`平台账户`,password:`用户密码`,token:`令牌续期`},i=C({}),a=d(()=>e.object({name:e.string().description(`用户名`).default(J.value.name??``),password:e.string().role(`secret`).description(`密码`).default(J.value.password??``)}).description(`基本资料`));async function c(){return delete s.user,delete J.value.id,delete J.value.token,delete J.value.expiredAt,o(`user/logout`)}async function l(){try{await o(`user/update`,i.value),r.success(`修改成功!`),Object.assign(J.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=T(`k-form`),c=T(`el-button`),l=T(`k-content`),d=T(`k-layout`);return S(),f(d,{main:`page-profile`,menu:y.value},{default:k(()=>[_(l,null,{default:k(()=>[_(r,{schema:a.value,modelValue:i.value,"onUpdate:modelValue":t[0]||=e=>i.value=e},null,8,[`schema`,`modelValue`]),h(`h2`,he,[t[3]||=g(` 平台绑定 `,-1),_(c,{solid:``,class:`right`,onClick:t[1]||=e=>Y.value=!0},{default:k(()=>[...t[2]||=[g(`添加`,-1)]]),_:1})]),(S(!0),m(u,null,w(D(s).user?.bindings??[],({platform:e,pid:n,bid:r})=>(S(),m(`div`,{class:`k-schema-item`,key:`${e}:${n}`},[h(`div`,ge,[h(`div`,_e,E(e)+` (`+E(n)+`)`,1),h(`div`,ve,[v.value.length>1||r!==D(s).user?.id?(S(),f(c,{key:0,onClick:j(t=>D(o)(`user/unbind`,e,n),[`stop`,`prevent`])},{default:k(()=>[...t[4]||=[g(`解绑`,-1)]]),_:1},8,[`onClick`])):p(`v-if`,!0)])])]))),128)),t[6]||=h(`h2`,{class:`k-schema-header`},`登录历史`,-1),h(`ul`,null,[(S(!0),m(u,null,w(D(s).user?.tokens??[],({inc:e,type:r,createdAt:i,lastUsedAt:a,address:s,userAgent:l})=>(S(),m(`li`,{key:e},[h(`div`,null,`登录类型:`+E(n[r]),1),h(`div`,null,`登录时间:`+E(i),1),h(`div`,null,`最后访问:`+E(a),1),h(`div`,null,`IP 地址:`+E(s),1),h(`div`,null,`客户端:`+E(l),1),h(`div`,null,[_(c,{onClick:t=>D(o)(`user/delete-token`,e)},{default:k(()=>[...t[5]||=[g(`移除会话`,-1)]]),_:1},8,[`onClick`])])]))),128))])]),_:1})]),_:1},8,[`menu`])}}}),be=((e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n})(v({__name:`sync-dialog`,setup(e){let t=c();async function n(e){if(J.value.sync=!!e,X.value=!1,e){if(e===`download`){if(!s.user)return;t.value=s.user.config}else try{await o(`user/update`,{config:t.value})}catch(e){r.error(e instanceof Error?e.message:String(e))}}}return(e,r)=>{let i=T(`el-button`),a=T(`el-button-group`),o=T(`el-dialog`);return S(),f(o,{class:`sync-dialog`,onClose:r[3]||=e=>D(t).sync??=!1,"show-close":!1,"close-on-click-modal":!1,"close-on-press-escape":!1,modelValue:D(X),"onUpdate:modelValue":r[4]||=e=>b(X)?X.value=e:null},{default:k(()=>[r[8]||=h(`p`,{class:`text-center`},`检测到你本地的配置与云端不同步,是否同步配置?`,-1),_(a,{class:`text-center`},{default:k(()=>[_(i,{onClick:r[0]||=e=>n(`upload`)},{default:k(()=>[...r[5]||=[g(`上传当前配置`,-1)]]),_:1}),_(i,{onClick:r[1]||=e=>n(`download`)},{default:k(()=>[...r[6]||=[g(`下载云端配置`,-1)]]),_:1}),_(i,{onClick:r[2]||=e=>n()},{default:k(()=>[...r[7]||=[g(`关闭配置同步`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`])}}}),[[`__scopeId`,`data-v-61c950af`]]);n.register(`at`,te),n.register(`check`,F),n.register(`lock`,R),n.register(`sign-in`,V),n.register(`sign-out`,W),n.register(`user-full`,q);var xe=n=>{let{token:l,id:u,expiredAt:d}=J.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:me}),n.page({path:`/profile`,name:`用户资料`,icon:`user-full`,fields:[`user`],position:`bottom`,order:500,component:ye}),n.slot({type:`global`,component:$}),n.slot({type:`global`,component:be}),n.settings({id:`user`,title:`用户设置`,component:v(()=>()=>y(T(`k-form`),{schema:e.object({sync:e.boolean().description(`在多个客户端间同步设置。`)}).description(`同步设置`),initial:J.value,modelValue:J.value,"onUpdate:modelValue":e=>J.value=e}))});let f=c();function p(){s.user&&(t(s.user.config,f.value)||(X.value=!0))}n.on(`dispose`,O(f,async e=>{e&&s.user&&J.value.sync&&await o(`user/update`,{config:e})},{deep:!0})),n.on(`dispose`,O(()=>J.value.sync,async e=>{e&&s.user&&p()})),n.on(`dispose`,O(()=>s.user,(e,t)=>{if(Y.value=!1,!e)return a.push(`/login`);if(J.value.sync&&p(),t)return;Object.assign(J.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{xe 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,markRaw as x,onBeforeUnmount as S,openBlock as C,ref as w,renderList as T,resolveComponent as E,toDisplayString as D,unref as O,watch as k,withCtx as A,withKeys as j,withModifiers as M}from"vue";import{useRouter as N}from"vue-router";var ee={class:`k-icon k-icon-at`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function te(e,t){return C(),m(`svg`,ee,[...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 ne=x({name:`k-at`,render:te}),re={class:`k-icon check`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function ie(e,t){return C(),m(`svg`,re,[...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 P=x({name:`k-check`,render:ie}),F={class:`k-icon k-icon-lock`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 448 512`};function I(e,t){return C(),m(`svg`,F,[...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 L=x({name:`k-lock`,render:I}),R={class:`k-icon k-icon-sign-in`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function z(e,t){return C(),m(`svg`,R,[...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 B=x({name:`k-sign-in`,render:z}),V={class:`k-icon k-icon-sign-out`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function H(e,t){return C(),m(`svg`,V,[...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 U=x({name:`k-sign-out`,render:H}),W={class:`k-icon`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`};function G(e,t){return C(),m(`svg`,W,[...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 K=x({name:`k-user-full`,render:G}),q=l(`auth`,2,()=>({authType:0}));function J(){delete q.value.password}J();function Y(){J(),delete q.value.id,delete q.value.token,delete q.value.expiredAt}var X=w(!1),Z=w(!1),ae={class:`login-form text-center`},oe={key:0},se={key:1},ce={class:`hint`},le={class:`token`},ue={class:`control`},de={key:0},fe={key:1},pe={key:0,class:`error`},me={class:`control`},Q={key:0,class:`error`},he={class:`control`},$=v({__name:`login-form`,setup(e){let t=w(),n=w(),r=w(!1),i=w(``);S(()=>{i.value=``});let a=0;async function c(){let e=Date.now();if(e<a)return;let{platform:r,userId:i}=q.value;if(r&&i){a=e+1e3;try{n.value=await o(`login/platform`,r,i)}catch(e){t.value=e instanceof Error?e.message:String(e)}}}async function l(){let{name:e}=q.value;if(e&&i.value)try{await o(`login/password`,e,i.value),i.value=``}catch(e){t.value=e instanceof Error?e.message:String(e)}}let d=N();function f(){s.user?X.value=!1:d.back()}return(e,a)=>{let o=E(`k-button`),d=E(`k-tab`),v=E(`k-icon`),y=E(`el-input`);return C(),m(`div`,ae,[n.value?(C(),m(u,{key:0},[O(s).user?(C(),m(`h1`,oe,[...a[7]||=[h(`span`,null,`平台账户绑定`,-1)]])):(C(),m(`h1`,se,[...a[8]||=[h(`span`,null,`平台账户登录`,-1)]])),h(`p`,ce,`欢迎你,`+D(n.value.name||`Koishi 用户`)+`!`,1),a[10]||=h(`p`,{class:`hint`},`请用上述账号将下面的验证码发送给任意正在运行的机器人`,-1),h(`p`,le,D(n.value.token),1),h(`div`,ue,[_(o,{onClick:a[0]||=e=>n.value.token=``},{default:A(()=>[...a[9]||=[g(`返回上一步`,-1)]]),_:1})])],64)):(C(),m(u,{key:1},[O(s).user?(C(),m(`h1`,de,[...a[11]||=[h(`span`,null,`平台账户绑定`,-1)]])):(C(),m(`h1`,fe,[_(d,{data:[`用户密码登录`,`平台账户登录`],modelValue:O(q).authType,"onUpdate:modelValue":a[1]||=e=>O(q).authType=e},null,8,[`modelValue`])])),O(s).user||O(q).authType===1?(C(),m(u,{key:2},[_(y,{placeholder:`平台名`,modelValue:O(q).platform,"onUpdate:modelValue":a[2]||=e=>O(q).platform=e},{prefix:A(()=>[_(v,{name:`at`})]),_:1},8,[`modelValue`]),_(y,{placeholder:`账号`,modelValue:O(q).userId,"onUpdate:modelValue":a[3]||=e=>O(q).userId=e,onKeypress:j(M(c,[`stop`]),[`enter`])},{prefix:A(()=>[_(v,{name:`user`})]),_:1},8,[`modelValue`,`onKeypress`]),t.value?(C(),m(`p`,pe,D(t.value),1)):p(`v-if`,!0),h(`div`,me,[_(o,{onClick:f},{default:A(()=>[...a[12]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:c},{default:A(()=>[...a[13]||=[g(`获取验证码`,-1)]]),_:1})])],64)):(C(),m(u,{key:3},[_(y,{placeholder:`用户名`,modelValue:O(q).name,"onUpdate:modelValue":a[4]||=e=>O(q).name=e},{prefix:A(()=>[_(v,{name:`user`})]),_:1},8,[`modelValue`]),_(y,{placeholder:`密码`,modelValue:i.value,"onUpdate:modelValue":a[6]||=e=>i.value=e,onKeypress:j(M(l,[`stop`]),[`enter`]),type:r.value?`text`:`password`},{prefix:A(()=>[_(v,{name:`lock`})]),suffix:A(()=>[_(v,{name:r.value?`eye`:`eye-slash`,onClick:a[5]||=e=>r.value=!r.value},null,8,[`name`])]),_:1},8,[`modelValue`,`onKeypress`,`type`]),t.value?(C(),m(`p`,Q,D(t.value),1)):p(`v-if`,!0),h(`div`,he,[_(o,{onClick:f},{default:A(()=>[...a[14]||=[g(`返回`,-1)]]),_:1}),_(o,{onClick:l},{default:A(()=>[...a[15]||=[g(`登录`,-1)]]),_:1})])],64))],64))])}}}),ge=v({__name:`bind-dialog`,setup(e){return(e,t)=>{let n=E(`el-dialog`);return C(),f(n,{center:``,modelValue:O(X),"onUpdate:modelValue":t[0]||=e=>b(X)?X.value=e:null,class:`bind-dialog`},{default:A(()=>[_($)]),_:1},8,[`modelValue`])}}}),_e=v({__name:`login`,setup(e){return(e,t)=>{let n=E(`k-card`),r=E(`k-layout`);return C(),f(r,{main:`darker page-login`},{default:A(()=>[_(n,null,{default:A(()=>[_($)]),_:1})]),_:1})}}}),ve={class:`k-schema-header`},ye={class:`header`},be={class:`left`},xe={class:`right`},Se=v({__name:`profile`,setup(t){let n={platform:`平台账户`,password:`用户密码`,token:`令牌续期`},i=w({}),a=d(()=>e.object({name:e.string().description(`用户名`).default(q.value.name??``),password:e.string().role(`secret`).description(`密码`).default(``)}).description(`基本资料`));async function c(){return delete s.user,i.value={},Y(),o(`user/logout`)}async function l(){let e=s.user,{name:t,password:n}=i.value;try{if(await o(`user/update`,{...t===void 0?{}:{name:t},...n?{password:n}:{}}),s.user!==e)return;r.success(`修改成功!`),t!==void 0&&(q.value.name=t,e&&(e.name=t)),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=E(`k-form`),c=E(`el-button`),l=E(`k-content`),d=E(`k-layout`);return C(),f(d,{main:`page-profile`,menu:y.value},{default:A(()=>[_(l,null,{default:A(()=>[_(r,{schema:a.value,modelValue:i.value,"onUpdate:modelValue":t[0]||=e=>i.value=e},null,8,[`schema`,`modelValue`]),h(`h2`,ve,[t[3]||=g(` 平台绑定 `,-1),_(c,{solid:``,class:`right`,onClick:t[1]||=e=>X.value=!0},{default:A(()=>[...t[2]||=[g(`添加`,-1)]]),_:1})]),(C(!0),m(u,null,T(O(s).user?.bindings??[],({platform:e,pid:n,bid:r})=>(C(),m(`div`,{class:`k-schema-item`,key:`${e}:${n}`},[h(`div`,ye,[h(`div`,be,D(e)+` (`+D(n)+`)`,1),h(`div`,xe,[v.value.length>1||r!==O(s).user?.id?(C(),f(c,{key:0,onClick:M(t=>O(o)(`user/unbind`,e,n),[`stop`,`prevent`])},{default:A(()=>[...t[4]||=[g(`解绑`,-1)]]),_:1},8,[`onClick`])):p(`v-if`,!0)])])]))),128)),t[6]||=h(`h2`,{class:`k-schema-header`},`登录历史`,-1),h(`ul`,null,[(C(!0),m(u,null,T(O(s).user?.tokens??[],({inc:e,type:r,createdAt:i,lastUsedAt:a,address:s,userAgent:l})=>(C(),m(`li`,{key:e},[h(`div`,null,`登录类型:`+D(n[r]),1),h(`div`,null,`登录时间:`+D(i),1),h(`div`,null,`最后访问:`+D(a),1),h(`div`,null,`IP 地址:`+D(s),1),h(`div`,null,`客户端:`+D(l),1),h(`div`,null,[_(c,{onClick:t=>O(o)(`user/delete-token`,e)},{default:A(()=>[...t[5]||=[g(`移除会话`,-1)]]),_:1},8,[`onClick`])])]))),128))])]),_:1})]),_:1},8,[`menu`])}}}),Ce=((e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n})(v({__name:`sync-dialog`,setup(e){let t=c();async function n(e){if(q.value.sync=!!e,Z.value=!1,e){if(e===`download`){if(!s.user)return;t.value=s.user.config}else try{await o(`user/update`,{config:t.value})}catch(e){r.error(e instanceof Error?e.message:String(e))}}}return(e,r)=>{let i=E(`el-button`),a=E(`el-button-group`),o=E(`el-dialog`);return C(),f(o,{class:`sync-dialog`,onClose:r[3]||=e=>O(t).sync??=!1,"show-close":!1,"close-on-click-modal":!1,"close-on-press-escape":!1,modelValue:O(Z),"onUpdate:modelValue":r[4]||=e=>b(Z)?Z.value=e:null},{default:A(()=>[r[8]||=h(`p`,{class:`text-center`},`检测到你本地的配置与云端不同步,是否同步配置?`,-1),_(a,{class:`text-center`},{default:A(()=>[_(i,{onClick:r[0]||=e=>n(`upload`)},{default:A(()=>[...r[5]||=[g(`上传当前配置`,-1)]]),_:1}),_(i,{onClick:r[1]||=e=>n(`download`)},{default:A(()=>[...r[6]||=[g(`下载云端配置`,-1)]]),_:1}),_(i,{onClick:r[2]||=e=>n()},{default:A(()=>[...r[7]||=[g(`关闭配置同步`,-1)]]),_:1})]),_:1})]),_:1},8,[`modelValue`])}}}),[[`__scopeId`,`data-v-61c950af`]]);n.register(`at`,ne),n.register(`check`,P),n.register(`lock`,L),n.register(`sign-in`,B),n.register(`sign-out`,U),n.register(`user-full`,K);var we=n=>{let{token:l,id:u,expiredAt:d}=q.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:_e}),n.page({path:`/profile`,name:`用户资料`,icon:`user-full`,fields:[`user`],position:`bottom`,order:500,component:Se}),n.slot({type:`global`,component:ge}),n.slot({type:`global`,component:Ce}),n.settings({id:`user`,title:`用户设置`,component:v(()=>()=>y(E(`k-form`),{schema:e.object({sync:e.boolean().description(`在多个客户端间同步设置。`)}).description(`同步设置`),initial:q.value,modelValue:q.value,"onUpdate:modelValue":e=>q.value=e}))});let f=c();function p(){s.user&&(t(s.user.config,f.value)||(Z.value=!0))}n.on(`dispose`,k(f,async e=>{e&&s.user&&q.value.sync&&await o(`user/update`,{config:e})},{deep:!0})),n.on(`dispose`,k(()=>q.value.sync,async e=>{e&&s.user&&p()})),n.on(`dispose`,k(()=>s.user,(e,t)=>{if(X.value=!1,!e)return a.push(`/login`);if(q.value.sync&&p(),t)return;Object.assign(q.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{we as default};
|
package/lib/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Binding, Context, Schema, Service, User } from "@koishi-ce/koishi";
|
|
2
2
|
import { Client, DataService } from "@koishi-ce/console";
|
|
3
|
-
//#region src/types.d.ts
|
|
4
3
|
/** token 表记录:一次登录会话的令牌及其来源信息。 */
|
|
5
4
|
interface LoginToken {
|
|
6
5
|
/** 自增主键(删除指定会话用) */
|
|
@@ -36,16 +35,12 @@ interface UserLogin extends Pick<User, "id" | "name"> {
|
|
|
36
35
|
}
|
|
37
36
|
/** user/update 事件允许修改的用户字段。 */
|
|
38
37
|
type UserUpdate = Partial<Pick<User, "name" | "password" | "config">>;
|
|
39
|
-
//#endregion
|
|
40
|
-
//#region src/crypto.d.ts
|
|
41
38
|
/**
|
|
42
39
|
* 生成指定长度的随机令牌字符串。
|
|
43
40
|
* @param length 令牌长度,默认 40
|
|
44
41
|
* @returns 从字符表随机取字符拼接成的字符串
|
|
45
42
|
*/
|
|
46
43
|
export declare function randomId(length?: number): string;
|
|
47
|
-
//#endregion
|
|
48
|
-
//#region src/index.d.ts
|
|
49
44
|
declare module "@koishi-ce/koishi" {
|
|
50
45
|
interface Context {
|
|
51
46
|
auth: AuthService;
|
|
@@ -97,11 +92,11 @@ declare class AuthService extends Service {
|
|
|
97
92
|
/**
|
|
98
93
|
* 设置客户端登录态并全量下发 user 数据。
|
|
99
94
|
* @param client 目标 WebSocket 客户端
|
|
100
|
-
* @param auth
|
|
95
|
+
* @param auth 新登录态,缺省沿用 client.auth,传 null 清除登录态
|
|
101
96
|
* @param passive 为 true 时只写 client.auth,不推送数据也不刷新
|
|
102
97
|
* (已登录状态下修改资料后仅同步本地时使用)
|
|
103
98
|
*/
|
|
104
|
-
setAuth(client: Client, auth?: Auth | undefined, passive?: boolean): Promise<void>;
|
|
99
|
+
setAuth(client: Client, auth?: Auth | null | undefined, passive?: boolean): Promise<void>;
|
|
105
100
|
/**
|
|
106
101
|
* 为用户签发新令牌并立即让客户端登录。
|
|
107
102
|
* 从 WebSocket 升级请求中提取 User-Agent 与来源 IP 一并落库,
|
|
@@ -121,5 +116,4 @@ declare namespace AuthService {
|
|
|
121
116
|
loginTokenExpire: number;
|
|
122
117
|
}
|
|
123
118
|
}
|
|
124
|
-
//#endregion
|
|
125
119
|
export { type Auth, type LoginToken, type UserLogin, type UserUpdate, AuthService as default };
|
package/lib/index.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
2
|
import { Schema, Service, Time, omit } from "@koishi-ce/koishi";
|
|
3
3
|
import zhCN from "./assets/zh-CN-DChWGTwa.yml";
|
|
4
|
-
import {
|
|
5
|
-
|
|
4
|
+
import { pbkdf2, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
// src/crypto.ts
|
|
6
7
|
const letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
7
8
|
/**
|
|
8
9
|
* 生成指定长度的随机令牌字符串。
|
|
@@ -20,10 +21,11 @@ function randomId(length = 40) {
|
|
|
20
21
|
}
|
|
21
22
|
/** PBKDF2-HMAC-SHA256 迭代次数(OWASP 2023 建议 600k;登录低频,开销可接受) */
|
|
22
23
|
const PBKDF2_ROUNDS = 6e5;
|
|
24
|
+
const deriveKey = promisify(pbkdf2);
|
|
23
25
|
/** 新格式密码哈希:`pbkdf2$<rounds>$<salt-hex>$<dk-hex>`(加盐 + 慢哈希)。 */
|
|
24
|
-
function toHash(password) {
|
|
26
|
+
async function toHash(password) {
|
|
25
27
|
const salt = randomBytes(16);
|
|
26
|
-
const dk =
|
|
28
|
+
const dk = await deriveKey(password, salt, PBKDF2_ROUNDS, 32, "sha256");
|
|
27
29
|
return `pbkdf2$${PBKDF2_ROUNDS}$${salt.toString("hex")}$${dk.toString("hex")}`;
|
|
28
30
|
}
|
|
29
31
|
/**
|
|
@@ -32,21 +34,24 @@ function toHash(password) {
|
|
|
32
34
|
* 仅接受 `pbkdf2$...` 格式:按存储的盐与迭代次数重派生,恒定时间比较;
|
|
33
35
|
* 其余形态(含历史上游遗留的无盐 SHA-256 十六进制)一律不匹配。
|
|
34
36
|
*/
|
|
35
|
-
function verifyPassword(password, stored) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
async function verifyPassword(password, stored) {
|
|
38
|
+
const [format, rounds, saltHex, dkHex, extra] = stored.split("$");
|
|
39
|
+
if (format !== "pbkdf2" || extra !== void 0 || !rounds || !/^[0-9]+$/.test(rounds) || !saltHex || !/^[0-9a-f]{32}$/i.test(saltHex) || !dkHex || !/^[0-9a-f]{64}$/i.test(dkHex)) return false;
|
|
40
|
+
const iterations = Number(rounds);
|
|
41
|
+
if (!Number.isInteger(iterations) || iterations < 1 || iterations > 2147483647) return false;
|
|
39
42
|
const expected = Buffer.from(dkHex, "hex");
|
|
40
|
-
const actual =
|
|
43
|
+
const actual = await deriveKey(password, Buffer.from(saltHex, "hex"), iterations, expected.length, "sha256");
|
|
41
44
|
return timingSafeEqual(actual, expected);
|
|
42
45
|
}
|
|
43
|
-
|
|
44
|
-
//#region src/login.ts
|
|
46
|
+
// src/login.ts
|
|
45
47
|
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
46
48
|
function initLogin(auth) {
|
|
47
49
|
const self = auth;
|
|
48
50
|
const { ctx, config } = auth;
|
|
49
|
-
const states =
|
|
51
|
+
const states = /* @__PURE__ */ new Map();
|
|
52
|
+
ctx.on("dispose", () => {
|
|
53
|
+
for (const state of states.values()) state.dispose();
|
|
54
|
+
});
|
|
50
55
|
ctx.console.addListener("login/password", async function(name, password) {
|
|
51
56
|
const [user] = await ctx.database.get("user", { name }, [
|
|
52
57
|
"password",
|
|
@@ -55,7 +60,7 @@ function initLogin(auth) {
|
|
|
55
60
|
"authority",
|
|
56
61
|
"config"
|
|
57
62
|
]);
|
|
58
|
-
if (!user?.password || !verifyPassword(password, user.password)) throw new Error("用户名或密码错误。");
|
|
63
|
+
if (!user?.password || !await verifyPassword(password, user.password)) throw new Error("用户名或密码错误。");
|
|
59
64
|
await self.createToken(this, "password", omit(user, ["password"]));
|
|
60
65
|
});
|
|
61
66
|
ctx.console.addListener("login/token", async function(aid, token) {
|
|
@@ -79,27 +84,38 @@ function initLogin(auth) {
|
|
|
79
84
|
});
|
|
80
85
|
});
|
|
81
86
|
ctx.console.addListener("login/platform", async function(platform, userId) {
|
|
87
|
+
const binding = this.auth;
|
|
82
88
|
const user = await ctx.database.getUser(platform, userId, ["id", "name"]);
|
|
83
89
|
if (!user) throw new Error("找不到此账户。");
|
|
84
|
-
if (this.
|
|
90
|
+
if (ctx.console.clients[this.id] !== this || this.auth !== binding || binding && binding.expiredAt <= Date.now()) throw new Error("登录状态已失效。");
|
|
91
|
+
if (binding?.id === user.id) throw new Error("你已经绑定了此账户。");
|
|
85
92
|
const key = `${platform}:${userId}`;
|
|
93
|
+
const now = Date.now();
|
|
94
|
+
const previous = states.get(key);
|
|
95
|
+
if (!binding && previous?.binding && previous.expiredAt > now && previous.binding.expiredAt > now && previous.client.auth === previous.binding) throw new Error("此平台账户正在等待绑定验证。");
|
|
96
|
+
previous?.dispose();
|
|
86
97
|
const token = String(randomInt(0, 1e6)).padStart(6, "0");
|
|
87
|
-
const expiredAt =
|
|
88
|
-
|
|
89
|
-
token,
|
|
90
|
-
expiredAt,
|
|
91
|
-
this
|
|
92
|
-
];
|
|
98
|
+
const expiredAt = now + config.loginTokenExpire;
|
|
99
|
+
let cancelTimeout;
|
|
93
100
|
const listener = () => {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
this.socket.removeEventListener("close",
|
|
101
|
+
if (states.get(key)?.dispose === listener) states.delete(key);
|
|
102
|
+
cancelTimeout?.();
|
|
103
|
+
this.socket.removeEventListener("close", listener);
|
|
97
104
|
};
|
|
98
|
-
const
|
|
99
|
-
const
|
|
100
|
-
if (
|
|
101
|
-
|
|
105
|
+
const expire = () => {
|
|
106
|
+
const remaining = expiredAt - Date.now();
|
|
107
|
+
if (remaining <= 0) listener();
|
|
108
|
+
else cancelTimeout = ctx.setTimeout(expire, Math.min(remaining, 2147483647));
|
|
109
|
+
};
|
|
110
|
+
states.set(key, {
|
|
111
|
+
token,
|
|
112
|
+
expiredAt,
|
|
113
|
+
client: this,
|
|
114
|
+
binding,
|
|
115
|
+
dispose: listener
|
|
116
|
+
});
|
|
102
117
|
this.socket.addEventListener("close", listener);
|
|
118
|
+
expire();
|
|
103
119
|
return {
|
|
104
120
|
id: user.id,
|
|
105
121
|
name: user.name,
|
|
@@ -108,16 +124,23 @@ function initLogin(auth) {
|
|
|
108
124
|
};
|
|
109
125
|
});
|
|
110
126
|
ctx.middleware(async (session, next) => {
|
|
111
|
-
const state = states
|
|
112
|
-
if (!state
|
|
127
|
+
const state = states.get(session.uid);
|
|
128
|
+
if (!state) return next();
|
|
129
|
+
const now = Date.now();
|
|
130
|
+
const { binding, client } = state;
|
|
131
|
+
if (state.expiredAt <= now || client.auth !== binding || binding && binding.expiredAt <= now) {
|
|
132
|
+
state.dispose();
|
|
133
|
+
return next();
|
|
134
|
+
}
|
|
113
135
|
const { platform, userId: pid } = session;
|
|
114
|
-
if (!pid) return next();
|
|
115
|
-
|
|
136
|
+
if (!pid || state.token !== session.stripped.content) return next();
|
|
137
|
+
state.dispose();
|
|
138
|
+
if (binding) {
|
|
116
139
|
await ctx.database.set("binding", {
|
|
117
140
|
platform,
|
|
118
141
|
pid
|
|
119
|
-
}, { aid:
|
|
120
|
-
return self.setAuth(
|
|
142
|
+
}, { aid: binding.id });
|
|
143
|
+
if (client.auth === binding) return self.setAuth(client, binding);
|
|
121
144
|
} else {
|
|
122
145
|
const user = await session.observeUser([
|
|
123
146
|
"id",
|
|
@@ -125,7 +148,7 @@ function initLogin(auth) {
|
|
|
125
148
|
"authority",
|
|
126
149
|
"config"
|
|
127
150
|
]);
|
|
128
|
-
return self.createToken(
|
|
151
|
+
if (client.auth === binding && ctx.console.clients[client.id] === client) return self.createToken(client, "platform", user);
|
|
129
152
|
}
|
|
130
153
|
}, true);
|
|
131
154
|
ctx.on("console/intercept", async (client, listener) => {
|
|
@@ -147,14 +170,25 @@ function initLogin(auth) {
|
|
|
147
170
|
});
|
|
148
171
|
ctx.console.addListener("user/logout", async function() {
|
|
149
172
|
if (this.auth) await ctx.database.remove("token", { token: this.auth.token });
|
|
150
|
-
await self.setAuth(this,
|
|
173
|
+
await self.setAuth(this, null);
|
|
151
174
|
});
|
|
152
175
|
ctx.console.addListener("user/update", async function(data) {
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
|
|
156
|
-
Object.
|
|
157
|
-
|
|
176
|
+
const current = this.auth;
|
|
177
|
+
if (!current) throw new Error("请先登录。");
|
|
178
|
+
if (!data || typeof data !== "object") throw new Error("资料必须是普通对象。");
|
|
179
|
+
const prototype = Object.getPrototypeOf(data);
|
|
180
|
+
if (prototype !== Object.prototype && prototype !== null) throw new Error("资料必须是普通对象。");
|
|
181
|
+
const fields = data;
|
|
182
|
+
const { name, password, config } = fields;
|
|
183
|
+
const profile = {};
|
|
184
|
+
if (Object.hasOwn(fields, "name") && typeof name === "string") profile.name = name;
|
|
185
|
+
if (Object.hasOwn(fields, "config") && typeof config === "object") profile.config = config;
|
|
186
|
+
const update = { ...profile };
|
|
187
|
+
if (Object.hasOwn(fields, "password") && typeof password === "string" && password) update.password = await toHash(password);
|
|
188
|
+
if (!Object.keys(update).length) throw new Error("没有可更新的资料字段。");
|
|
189
|
+
if (this.auth !== current) throw new Error("登录状态已失效。");
|
|
190
|
+
await ctx.database.set("user", { id: current.id }, update);
|
|
191
|
+
Object.assign(current, profile);
|
|
158
192
|
});
|
|
159
193
|
ctx.console.addListener("user/unbind", async function(platform, pid) {
|
|
160
194
|
if (!this.auth) throw new Error("请先登录。");
|
|
@@ -173,8 +207,7 @@ function initLogin(auth) {
|
|
|
173
207
|
await self.setAuth(this);
|
|
174
208
|
});
|
|
175
209
|
}
|
|
176
|
-
|
|
177
|
-
//#region src/index.ts
|
|
210
|
+
// src/index.ts
|
|
178
211
|
/**
|
|
179
212
|
* auth 插件(服务端):控制台登录鉴权。
|
|
180
213
|
*
|
|
@@ -246,19 +279,19 @@ var AuthService = class AuthService extends Service {
|
|
|
246
279
|
id: 0,
|
|
247
280
|
name: username,
|
|
248
281
|
authority: 5,
|
|
249
|
-
password: toHash(password),
|
|
282
|
+
password: await toHash(password),
|
|
250
283
|
createdAt: /* @__PURE__ */ new Date()
|
|
251
284
|
}]);
|
|
252
285
|
}
|
|
253
286
|
/**
|
|
254
287
|
* 设置客户端登录态并全量下发 user 数据。
|
|
255
288
|
* @param client 目标 WebSocket 客户端
|
|
256
|
-
* @param auth
|
|
289
|
+
* @param auth 新登录态,缺省沿用 client.auth,传 null 清除登录态
|
|
257
290
|
* @param passive 为 true 时只写 client.auth,不推送数据也不刷新
|
|
258
291
|
* (已登录状态下修改资料后仅同步本地时使用)
|
|
259
292
|
*/
|
|
260
293
|
async setAuth(client, auth = client.auth, passive = false) {
|
|
261
|
-
client.auth = auth;
|
|
294
|
+
client.auth = auth ?? void 0;
|
|
262
295
|
if (passive) return;
|
|
263
296
|
if (auth) {
|
|
264
297
|
const bindings = await this.ctx.database.get("binding", { aid: auth.id });
|
|
@@ -268,6 +301,7 @@ var AuthService = class AuthService extends Service {
|
|
|
268
301
|
delete login.id;
|
|
269
302
|
delete login.token;
|
|
270
303
|
});
|
|
304
|
+
if (client.auth !== auth) return;
|
|
271
305
|
client.send({
|
|
272
306
|
type: "data",
|
|
273
307
|
body: {
|
|
@@ -319,5 +353,4 @@ var AuthService = class AuthService extends Service {
|
|
|
319
353
|
});
|
|
320
354
|
}
|
|
321
355
|
};
|
|
322
|
-
//#endregion
|
|
323
356
|
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.7",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"build:client": "bun ../../../packages/web/builder/src/bin.ts build ."
|
|
@@ -58,9 +58,9 @@
|
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@koishi-ce/plugin-database-memory": "^1.1.2",
|
|
61
|
-
"@koishi-ce/client": "^1.4.
|
|
62
|
-
"vue": "^3.5.
|
|
63
|
-
"vue-router": "^5.
|
|
61
|
+
"@koishi-ce/client": "^1.4.5",
|
|
62
|
+
"vue": "^3.5.45",
|
|
63
|
+
"vue-router": "^5.5.1"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@koishi-ce/console": "^1.1.1"
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Copyright (c) 2026-present Koishi-CE contributors.
|
|
3
|
+
|
|
4
|
+
import { describe, expect, it } from "bun:test";
|
|
5
|
+
import { pbkdf2Sync } from "node:crypto";
|
|
6
|
+
import { toHash, verifyPassword } from "../crypto.ts";
|
|
7
|
+
|
|
8
|
+
describe("密码哈希", () => {
|
|
9
|
+
it("异步生成带随机盐的哈希,并可校验正确和错误的密码", async () => {
|
|
10
|
+
const password = "测试密码";
|
|
11
|
+
const pending = toHash(password);
|
|
12
|
+
expect(pending).toBeInstanceOf(Promise);
|
|
13
|
+
const stored = await pending;
|
|
14
|
+
expect(stored).toMatch(
|
|
15
|
+
/^pbkdf2\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/,
|
|
16
|
+
);
|
|
17
|
+
expect(await toHash(password)).not.toBe(stored);
|
|
18
|
+
const verified = verifyPassword(password, stored);
|
|
19
|
+
expect(verified).toBeInstanceOf(Promise);
|
|
20
|
+
expect(await verified).toBe(true);
|
|
21
|
+
expect(await verifyPassword("密码错误", stored)).toBe(
|
|
22
|
+
false,
|
|
23
|
+
);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("兼容此前同步实现写入的 PBKDF2 记录", async () => {
|
|
27
|
+
const salt = Buffer.alloc(16, 0x42);
|
|
28
|
+
const dk = pbkdf2Sync(
|
|
29
|
+
"原有密码",
|
|
30
|
+
salt,
|
|
31
|
+
600_000,
|
|
32
|
+
32,
|
|
33
|
+
"sha256",
|
|
34
|
+
);
|
|
35
|
+
const stored = `pbkdf2$600000$${salt.toString("hex")}$${dk.toString("hex")}`;
|
|
36
|
+
expect(await verifyPassword("原有密码", stored)).toBe(
|
|
37
|
+
true,
|
|
38
|
+
);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("拒绝超出范围的迭代次数和畸形哈希", async () => {
|
|
42
|
+
const salt = "42".repeat(16);
|
|
43
|
+
const dk = "00".repeat(32);
|
|
44
|
+
for (const rounds of [
|
|
45
|
+
"0",
|
|
46
|
+
"-1",
|
|
47
|
+
"1.5",
|
|
48
|
+
"1e3",
|
|
49
|
+
"NaN",
|
|
50
|
+
"2147483648",
|
|
51
|
+
]) {
|
|
52
|
+
expect(
|
|
53
|
+
await verifyPassword(
|
|
54
|
+
"密码",
|
|
55
|
+
`pbkdf2$${rounds}$${salt}$${dk}`,
|
|
56
|
+
),
|
|
57
|
+
).toBe(false);
|
|
58
|
+
}
|
|
59
|
+
expect(
|
|
60
|
+
await verifyPassword(
|
|
61
|
+
"密码",
|
|
62
|
+
`pbkdf2$600000$${salt}$zz`,
|
|
63
|
+
),
|
|
64
|
+
).toBe(false);
|
|
65
|
+
});
|
|
66
|
+
});
|
package/src/__tests__/helpers.ts
CHANGED
|
@@ -9,12 +9,9 @@ import {
|
|
|
9
9
|
expect,
|
|
10
10
|
it,
|
|
11
11
|
} from "bun:test";
|
|
12
|
-
import {
|
|
13
|
-
createHash,
|
|
14
|
-
pbkdf2Sync,
|
|
15
|
-
randomBytes,
|
|
16
|
-
} from "node:crypto";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
17
13
|
import { Time } from "@koishi-ce/koishi";
|
|
14
|
+
import { toHash } from "../crypto.ts";
|
|
18
15
|
import {
|
|
19
16
|
app,
|
|
20
17
|
loginAdmin,
|
|
@@ -98,17 +95,9 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
98
95
|
expect(row?.password).toBe(legacy);
|
|
99
96
|
client.close();
|
|
100
97
|
|
|
101
|
-
//
|
|
102
|
-
const salt = randomBytes(16);
|
|
103
|
-
const dk = pbkdf2Sync(
|
|
104
|
-
"admin-pass",
|
|
105
|
-
salt,
|
|
106
|
-
600_000,
|
|
107
|
-
32,
|
|
108
|
-
"sha256",
|
|
109
|
-
);
|
|
98
|
+
// 还原为合法管理员密码供后续用例使用。
|
|
110
99
|
await app.database.set("user", 0, {
|
|
111
|
-
password:
|
|
100
|
+
password: await toHash("admin-pass"),
|
|
112
101
|
});
|
|
113
102
|
});
|
|
114
103
|
|
|
@@ -146,16 +135,8 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
146
135
|
empty.close();
|
|
147
136
|
|
|
148
137
|
// 还原为合法管理员密码(与插件同格式的 PBKDF2 哈希)供后续用例使用
|
|
149
|
-
const salt = randomBytes(16);
|
|
150
|
-
const dk = pbkdf2Sync(
|
|
151
|
-
"admin-pass",
|
|
152
|
-
salt,
|
|
153
|
-
600_000,
|
|
154
|
-
32,
|
|
155
|
-
"sha256",
|
|
156
|
-
);
|
|
157
138
|
await app.database.set("user", 0, {
|
|
158
|
-
password:
|
|
139
|
+
password: await toHash("admin-pass"),
|
|
159
140
|
});
|
|
160
141
|
});
|
|
161
142
|
});
|
|
@@ -55,7 +55,7 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
55
55
|
admin.close();
|
|
56
56
|
});
|
|
57
57
|
|
|
58
|
-
it("user/logout
|
|
58
|
+
it("user/logout 删除当前令牌并清除登录态", async () => {
|
|
59
59
|
const admin = await loginAdmin();
|
|
60
60
|
const token = admin.client.auth?.token;
|
|
61
61
|
const response = await admin.call("user/logout", []);
|
|
@@ -65,12 +65,8 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
65
65
|
token: token!,
|
|
66
66
|
});
|
|
67
67
|
expect(row).toBeUndefined();
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
// 故当前行为是重发 user 数据而非下发 null;此处按实际行为断言
|
|
71
|
-
expect(admin.client.auth?.id).toBe(0);
|
|
72
|
-
const data = admin.lastUserData();
|
|
73
|
-
expect(data?.name).toBe("root");
|
|
68
|
+
expect(admin.client.auth).toBeUndefined();
|
|
69
|
+
expect(admin.lastUserData()).toBeNull();
|
|
74
70
|
admin.close();
|
|
75
71
|
});
|
|
76
72
|
|
|
@@ -82,6 +78,15 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
82
78
|
anonymous.close();
|
|
83
79
|
});
|
|
84
80
|
|
|
81
|
+
it("清除会话后丢弃正在读取的旧登录态", async () => {
|
|
82
|
+
const admin = await loginAdmin();
|
|
83
|
+
const refresh = app.auth.setAuth(admin.client);
|
|
84
|
+
await app.auth.setAuth(admin.client, null);
|
|
85
|
+
await refresh;
|
|
86
|
+
expect(admin.lastUserData()).toBeNull();
|
|
87
|
+
admin.close();
|
|
88
|
+
});
|
|
89
|
+
|
|
85
90
|
it("user/update 修改资料(密码加哈希、配置透传)", async () => {
|
|
86
91
|
const anonymous = new TestClient(service());
|
|
87
92
|
expect(
|
|
@@ -104,6 +109,12 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
104
109
|
expect(response.error).toBeUndefined();
|
|
105
110
|
// passive 更新:本地登录态同步但不推送数据
|
|
106
111
|
expect(admin.client.auth?.name).toBe("renamed");
|
|
112
|
+
expect(admin.client.auth?.config).toEqual({
|
|
113
|
+
theme: "dark",
|
|
114
|
+
});
|
|
115
|
+
expect(admin.client.auth).not.toHaveProperty(
|
|
116
|
+
"password",
|
|
117
|
+
);
|
|
107
118
|
const [row] = await app.database.get("user", {
|
|
108
119
|
id: 0,
|
|
109
120
|
});
|
|
@@ -115,6 +126,72 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
115
126
|
admin.close();
|
|
116
127
|
});
|
|
117
128
|
|
|
129
|
+
it("user/update 拒绝畸形资料并过滤受保护字段", async () => {
|
|
130
|
+
const client = new TestClient(service());
|
|
131
|
+
const grant = await client.call("login/platform", [
|
|
132
|
+
"mock",
|
|
133
|
+
"111",
|
|
134
|
+
]);
|
|
135
|
+
const { token } = grant.value as { token: string };
|
|
136
|
+
await app.mock.client("111").receive(token);
|
|
137
|
+
expect(client.client.auth).toMatchObject({
|
|
138
|
+
id: aliceId,
|
|
139
|
+
authority: 2,
|
|
140
|
+
});
|
|
141
|
+
const [original] = await app.database.get(
|
|
142
|
+
"user",
|
|
143
|
+
aliceId,
|
|
144
|
+
);
|
|
145
|
+
if (!original) throw new Error("缺少测试账户。");
|
|
146
|
+
|
|
147
|
+
for (const value of [null, [], "资料"]) {
|
|
148
|
+
expect(
|
|
149
|
+
(await client.call("user/update", [value])).error,
|
|
150
|
+
).toContain("资料必须是普通对象");
|
|
151
|
+
}
|
|
152
|
+
expect(
|
|
153
|
+
(
|
|
154
|
+
await client.call("user/update", [
|
|
155
|
+
{
|
|
156
|
+
id: bobId,
|
|
157
|
+
authority: 5,
|
|
158
|
+
password: "",
|
|
159
|
+
name: 3,
|
|
160
|
+
config: false,
|
|
161
|
+
},
|
|
162
|
+
])
|
|
163
|
+
).error,
|
|
164
|
+
).toContain("没有可更新的资料字段");
|
|
165
|
+
expect(
|
|
166
|
+
await app.database.get("user", aliceId),
|
|
167
|
+
).toEqual([original]);
|
|
168
|
+
|
|
169
|
+
expect(
|
|
170
|
+
(
|
|
171
|
+
await client.call("user/update", [
|
|
172
|
+
{
|
|
173
|
+
name: "Alice",
|
|
174
|
+
config: null,
|
|
175
|
+
id: bobId,
|
|
176
|
+
authority: 5,
|
|
177
|
+
},
|
|
178
|
+
])
|
|
179
|
+
).error,
|
|
180
|
+
).toBeUndefined();
|
|
181
|
+
expect(
|
|
182
|
+
await app.database.get("user", aliceId),
|
|
183
|
+
).toEqual([
|
|
184
|
+
{ ...original, name: "Alice", config: null },
|
|
185
|
+
]);
|
|
186
|
+
expect(client.client.auth).toMatchObject({
|
|
187
|
+
id: aliceId,
|
|
188
|
+
authority: 2,
|
|
189
|
+
name: "Alice",
|
|
190
|
+
config: null,
|
|
191
|
+
});
|
|
192
|
+
client.close();
|
|
193
|
+
});
|
|
194
|
+
|
|
118
195
|
it("user/unbind 解绑平台账号的三种分支", async () => {
|
|
119
196
|
const anonymous = new TestClient(service());
|
|
120
197
|
expect(
|
|
@@ -8,11 +8,13 @@ import {
|
|
|
8
8
|
describe,
|
|
9
9
|
expect,
|
|
10
10
|
it,
|
|
11
|
+
spyOn,
|
|
11
12
|
} from "bun:test";
|
|
12
|
-
import type {
|
|
13
|
+
import type { UserLogin } from "@koishi-ce/plugin-auth";
|
|
13
14
|
import {
|
|
14
15
|
aliceId,
|
|
15
16
|
app,
|
|
17
|
+
loginAdmin,
|
|
16
18
|
service,
|
|
17
19
|
startApp,
|
|
18
20
|
stopApp,
|
|
@@ -23,6 +25,18 @@ import {
|
|
|
23
25
|
beforeAll(startApp);
|
|
24
26
|
afterAll(stopApp);
|
|
25
27
|
|
|
28
|
+
async function requestChallenge(
|
|
29
|
+
client: TestClient,
|
|
30
|
+
pid = "111",
|
|
31
|
+
) {
|
|
32
|
+
const response = await client.call("login/platform", [
|
|
33
|
+
"mock",
|
|
34
|
+
pid,
|
|
35
|
+
]);
|
|
36
|
+
expect(response.error).toBeUndefined();
|
|
37
|
+
return response.value as UserLogin;
|
|
38
|
+
}
|
|
39
|
+
|
|
26
40
|
describe("@koishi-ce/plugin-auth", () => {
|
|
27
41
|
describe("平台验证码登录", () => {
|
|
28
42
|
it("账户不存在或已绑定同一账户时拒绝", async () => {
|
|
@@ -36,7 +50,9 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
36
50
|
).error,
|
|
37
51
|
).toContain("找不到此账户");
|
|
38
52
|
|
|
39
|
-
|
|
53
|
+
const { token } = await requestChallenge(client);
|
|
54
|
+
await app.mock.client("111").receive(token);
|
|
55
|
+
expect(client.client.auth?.id).toBe(aliceId);
|
|
40
56
|
expect(
|
|
41
57
|
(
|
|
42
58
|
await client.call("login/platform", [
|
|
@@ -48,75 +64,169 @@ describe("@koishi-ce/plugin-auth", () => {
|
|
|
48
64
|
client.close();
|
|
49
65
|
});
|
|
50
66
|
|
|
51
|
-
it("
|
|
67
|
+
it("仅消费一次验证码,登录后移除关闭监听器", async () => {
|
|
52
68
|
const client = new TestClient(service());
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
expect(result.error).toBeUndefined();
|
|
58
|
-
expect(result.value).toMatchObject({
|
|
69
|
+
const initialListeners =
|
|
70
|
+
client.socket.closeListenerCount;
|
|
71
|
+
const challenge = await requestChallenge(client);
|
|
72
|
+
expect(challenge).toMatchObject({
|
|
59
73
|
id: aliceId,
|
|
60
74
|
name: "alice",
|
|
61
75
|
});
|
|
62
|
-
const
|
|
63
|
-
.token;
|
|
76
|
+
const { token: code } = challenge;
|
|
64
77
|
expect(code).toMatch(/^\d{6}$/);
|
|
78
|
+
expect(client.socket.closeListenerCount).toBe(
|
|
79
|
+
initialListeners + 1,
|
|
80
|
+
);
|
|
65
81
|
|
|
66
82
|
// 无关消息不消费验证码状态
|
|
67
83
|
const bot = app.mock.client("999", "888");
|
|
68
84
|
await bot.receive("hello-world");
|
|
69
85
|
|
|
70
|
-
|
|
86
|
+
const previous = await app.database.get("token", {
|
|
87
|
+
id: aliceId,
|
|
88
|
+
});
|
|
71
89
|
const user = app.mock.client("111");
|
|
72
|
-
await
|
|
73
|
-
|
|
90
|
+
await Promise.all([
|
|
91
|
+
user.receive(code),
|
|
92
|
+
user.receive(code),
|
|
93
|
+
]);
|
|
74
94
|
expect(client.client.auth?.id).toBe(aliceId);
|
|
75
|
-
|
|
76
|
-
expect(
|
|
95
|
+
expect(client.lastUserData()?.name).toBe("alice");
|
|
96
|
+
expect(client.socket.closeListenerCount).toBe(
|
|
97
|
+
initialListeners,
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
await client.call("user/logout", []);
|
|
101
|
+
await user.receive(code);
|
|
102
|
+
expect(client.client.auth).toBeUndefined();
|
|
103
|
+
expect(
|
|
104
|
+
await app.database.get("token", { id: aliceId }),
|
|
105
|
+
).toEqual(previous);
|
|
77
106
|
client.close();
|
|
78
107
|
});
|
|
79
108
|
|
|
80
|
-
it("
|
|
81
|
-
const client =
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
109
|
+
it("匿名客户端无法覆盖进行中的账号绑定", async () => {
|
|
110
|
+
const client = await loginAdmin();
|
|
111
|
+
const guest = new TestClient(service());
|
|
112
|
+
const initialListeners =
|
|
113
|
+
client.socket.closeListenerCount;
|
|
114
|
+
const { token } = await requestChallenge(
|
|
115
|
+
client,
|
|
86
116
|
"222",
|
|
87
|
-
|
|
88
|
-
expect(
|
|
89
|
-
|
|
90
|
-
|
|
117
|
+
);
|
|
118
|
+
expect(
|
|
119
|
+
(
|
|
120
|
+
await guest.call("login/platform", [
|
|
121
|
+
"mock",
|
|
122
|
+
"222",
|
|
123
|
+
])
|
|
124
|
+
).error,
|
|
125
|
+
).toContain("正在等待绑定验证");
|
|
91
126
|
|
|
92
127
|
const user = app.mock.client("222");
|
|
93
|
-
await user.receive(
|
|
94
|
-
await tick();
|
|
128
|
+
await user.receive(token);
|
|
95
129
|
const [binding] = await app.database.get("binding", {
|
|
96
130
|
platform: "mock",
|
|
97
131
|
pid: "222",
|
|
98
132
|
});
|
|
99
|
-
expect(binding?.aid).toBe(
|
|
133
|
+
expect(binding?.aid).toBe(client.client.auth?.id);
|
|
134
|
+
expect(client.socket.closeListenerCount).toBe(
|
|
135
|
+
initialListeners,
|
|
136
|
+
);
|
|
137
|
+
expect(guest.client.auth).toBeUndefined();
|
|
138
|
+
await app.database.set(
|
|
139
|
+
"binding",
|
|
140
|
+
{ platform: "mock", pid: "222" },
|
|
141
|
+
{ aid: binding!.bid },
|
|
142
|
+
);
|
|
143
|
+
guest.close();
|
|
100
144
|
client.close();
|
|
101
145
|
});
|
|
102
146
|
|
|
103
|
-
it("
|
|
104
|
-
|
|
105
|
-
|
|
147
|
+
it("定时器尚未执行时也会拒绝并清理已过期验证码", async () => {
|
|
148
|
+
const client = new TestClient(service());
|
|
149
|
+
const initialListeners =
|
|
150
|
+
client.socket.closeListenerCount;
|
|
151
|
+
const { token, expiredAt } =
|
|
152
|
+
await requestChallenge(client);
|
|
153
|
+
const now = spyOn(Date, "now").mockReturnValue(
|
|
154
|
+
expiredAt,
|
|
155
|
+
);
|
|
156
|
+
try {
|
|
157
|
+
await app.mock.client("111").receive(token);
|
|
158
|
+
expect(client.client.auth).toBeUndefined();
|
|
159
|
+
expect(client.socket.closeListenerCount).toBe(
|
|
160
|
+
initialListeners,
|
|
161
|
+
);
|
|
162
|
+
} finally {
|
|
163
|
+
now.mockRestore();
|
|
164
|
+
client.close();
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it("超时后主动移除状态与关闭监听器", async () => {
|
|
106
169
|
const keep = app.auth.config.loginTokenExpire;
|
|
107
|
-
app.auth.config.loginTokenExpire = 50;
|
|
108
170
|
const client = new TestClient(service());
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
171
|
+
const initialListeners =
|
|
172
|
+
client.socket.closeListenerCount;
|
|
173
|
+
app.auth.config.loginTokenExpire = 100;
|
|
174
|
+
try {
|
|
175
|
+
const { token } = await requestChallenge(client);
|
|
176
|
+
await tick(150);
|
|
177
|
+
expect(client.socket.closeListenerCount).toBe(
|
|
178
|
+
initialListeners,
|
|
179
|
+
);
|
|
180
|
+
await app.mock.client("111").receive(token);
|
|
181
|
+
expect(client.client.auth).toBeUndefined();
|
|
182
|
+
} finally {
|
|
183
|
+
app.auth.config.loginTokenExpire = keep;
|
|
184
|
+
client.close();
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("替换验证码后,旧连接关闭和旧的到期时间均不影响新状态", async () => {
|
|
189
|
+
const previous = new TestClient(service());
|
|
190
|
+
const current = new TestClient(service());
|
|
191
|
+
const previousListeners =
|
|
192
|
+
previous.socket.closeListenerCount;
|
|
193
|
+
const currentListeners =
|
|
194
|
+
current.socket.closeListenerCount;
|
|
195
|
+
const keep = app.auth.config.loginTokenExpire;
|
|
196
|
+
app.auth.config.loginTokenExpire = 150;
|
|
197
|
+
try {
|
|
198
|
+
await requestChallenge(previous);
|
|
199
|
+
} finally {
|
|
200
|
+
app.auth.config.loginTokenExpire = keep;
|
|
201
|
+
}
|
|
202
|
+
expect(previous.socket.closeListenerCount).toBe(
|
|
203
|
+
previousListeners + 1,
|
|
204
|
+
);
|
|
205
|
+
const { token } = await requestChallenge(current);
|
|
206
|
+
expect(previous.socket.closeListenerCount).toBe(
|
|
207
|
+
previousListeners,
|
|
208
|
+
);
|
|
209
|
+
previous.close();
|
|
210
|
+
await tick(200);
|
|
211
|
+
await app.mock.client("111").receive(token);
|
|
212
|
+
expect(current.client.auth?.id).toBe(aliceId);
|
|
213
|
+
expect(current.socket.closeListenerCount).toBe(
|
|
214
|
+
currentListeners,
|
|
117
215
|
);
|
|
216
|
+
current.close();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("连接关闭时清理未经验证的验证码", async () => {
|
|
220
|
+
const client = new TestClient(service());
|
|
221
|
+
const initialListeners =
|
|
222
|
+
client.socket.closeListenerCount;
|
|
223
|
+
const { token } = await requestChallenge(client);
|
|
118
224
|
client.close();
|
|
119
|
-
|
|
225
|
+
expect(client.socket.closeListenerCount).toBe(
|
|
226
|
+
initialListeners,
|
|
227
|
+
);
|
|
228
|
+
await app.mock.client("111").receive(token);
|
|
229
|
+
expect(client.client.auth).toBeUndefined();
|
|
120
230
|
});
|
|
121
231
|
});
|
|
122
232
|
});
|
package/src/crypto.ts
CHANGED
|
@@ -6,10 +6,11 @@
|
|
|
6
6
|
// 本仓分歧(E 类,勿回移):上游监听器内联保留的旧版无盐 SHA-256 密码兼容校验已在本仓移除——CE 全新安装一律 pbkdf2$ 格式,旧格式不可达(2026-09-13 用户拍板)。
|
|
7
7
|
|
|
8
8
|
import {
|
|
9
|
-
|
|
9
|
+
pbkdf2,
|
|
10
10
|
randomBytes,
|
|
11
11
|
timingSafeEqual,
|
|
12
12
|
} from "node:crypto";
|
|
13
|
+
import { promisify } from "node:util";
|
|
13
14
|
|
|
14
15
|
// 随机令牌的字符表(数字 + 大小写字母)
|
|
15
16
|
const letters =
|
|
@@ -37,11 +38,12 @@ export function randomId(length = 40) {
|
|
|
37
38
|
|
|
38
39
|
/** PBKDF2-HMAC-SHA256 迭代次数(OWASP 2023 建议 600k;登录低频,开销可接受) */
|
|
39
40
|
const PBKDF2_ROUNDS = 600_000;
|
|
41
|
+
const deriveKey = promisify(pbkdf2);
|
|
40
42
|
|
|
41
43
|
/** 新格式密码哈希:`pbkdf2$<rounds>$<salt-hex>$<dk-hex>`(加盐 + 慢哈希)。 */
|
|
42
|
-
export function toHash(password: string) {
|
|
44
|
+
export async function toHash(password: string) {
|
|
43
45
|
const salt = randomBytes(16);
|
|
44
|
-
const dk =
|
|
46
|
+
const dk = await deriveKey(
|
|
45
47
|
password,
|
|
46
48
|
salt,
|
|
47
49
|
PBKDF2_ROUNDS,
|
|
@@ -57,21 +59,38 @@ export function toHash(password: string) {
|
|
|
57
59
|
* 仅接受 `pbkdf2$...` 格式:按存储的盐与迭代次数重派生,恒定时间比较;
|
|
58
60
|
* 其余形态(含历史上游遗留的无盐 SHA-256 十六进制)一律不匹配。
|
|
59
61
|
*/
|
|
60
|
-
export function verifyPassword(
|
|
62
|
+
export async function verifyPassword(
|
|
61
63
|
password: string,
|
|
62
64
|
stored: string,
|
|
63
|
-
): boolean {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (
|
|
65
|
+
): Promise<boolean> {
|
|
66
|
+
const [format, rounds, saltHex, dkHex, extra] =
|
|
67
|
+
stored.split("$");
|
|
68
|
+
if (
|
|
69
|
+
format !== "pbkdf2" ||
|
|
70
|
+
extra !== undefined ||
|
|
71
|
+
!rounds ||
|
|
72
|
+
!/^[0-9]+$/.test(rounds) ||
|
|
73
|
+
!saltHex ||
|
|
74
|
+
!/^[0-9a-f]{32}$/i.test(saltHex) ||
|
|
75
|
+
!dkHex ||
|
|
76
|
+
!/^[0-9a-f]{64}$/i.test(dkHex)
|
|
77
|
+
)
|
|
78
|
+
return false;
|
|
79
|
+
const iterations = Number(rounds);
|
|
80
|
+
// node:crypto 的迭代次数必须能表示为正的 32 位有符号整数。
|
|
81
|
+
if (
|
|
82
|
+
!Number.isInteger(iterations) ||
|
|
83
|
+
iterations < 1 ||
|
|
84
|
+
iterations > 0x7fffffff
|
|
85
|
+
)
|
|
86
|
+
return false;
|
|
67
87
|
const expected = Buffer.from(dkHex, "hex");
|
|
68
|
-
const actual =
|
|
88
|
+
const actual = await deriveKey(
|
|
69
89
|
password,
|
|
70
90
|
Buffer.from(saltHex, "hex"),
|
|
71
|
-
|
|
91
|
+
iterations,
|
|
72
92
|
expected.length,
|
|
73
93
|
"sha256",
|
|
74
94
|
);
|
|
75
|
-
// 长度已按 expected.length 派生,恒定时间比较不会抛错
|
|
76
95
|
return timingSafeEqual(actual, expected);
|
|
77
96
|
}
|
package/src/index.ts
CHANGED
|
@@ -201,7 +201,7 @@ class AuthService extends Service {
|
|
|
201
201
|
id: 0,
|
|
202
202
|
name: username,
|
|
203
203
|
authority: 5,
|
|
204
|
-
password: toHash(password),
|
|
204
|
+
password: await toHash(password),
|
|
205
205
|
createdAt: new Date(),
|
|
206
206
|
},
|
|
207
207
|
]);
|
|
@@ -210,16 +210,16 @@ class AuthService extends Service {
|
|
|
210
210
|
/**
|
|
211
211
|
* 设置客户端登录态并全量下发 user 数据。
|
|
212
212
|
* @param client 目标 WebSocket 客户端
|
|
213
|
-
* @param auth
|
|
213
|
+
* @param auth 新登录态,缺省沿用 client.auth,传 null 清除登录态
|
|
214
214
|
* @param passive 为 true 时只写 client.auth,不推送数据也不刷新
|
|
215
215
|
* (已登录状态下修改资料后仅同步本地时使用)
|
|
216
216
|
*/
|
|
217
217
|
async setAuth(
|
|
218
218
|
client: Client,
|
|
219
|
-
auth = client.auth,
|
|
219
|
+
auth: Auth | null | undefined = client.auth,
|
|
220
220
|
passive = false,
|
|
221
221
|
) {
|
|
222
|
-
client.auth = auth;
|
|
222
|
+
client.auth = auth ?? undefined;
|
|
223
223
|
if (passive) return;
|
|
224
224
|
if (auth) {
|
|
225
225
|
const bindings = await this.ctx.database.get(
|
|
@@ -238,6 +238,8 @@ class AuthService extends Service {
|
|
|
238
238
|
delete (login as Partial<LoginToken>).id;
|
|
239
239
|
delete (login as Partial<LoginToken>).token;
|
|
240
240
|
});
|
|
241
|
+
// 查询期间若已登出或切换会话,旧的登录态不可再下发。
|
|
242
|
+
if (client.auth !== auth) return;
|
|
241
243
|
client.send({
|
|
242
244
|
type: "data",
|
|
243
245
|
body: {
|
package/src/login.ts
CHANGED
|
@@ -9,6 +9,15 @@ import type { Client } from "@koishi-ce/console";
|
|
|
9
9
|
import { type Context, omit } from "@koishi-ce/koishi";
|
|
10
10
|
import { toHash, verifyPassword } from "./crypto.ts";
|
|
11
11
|
import type AuthService from "./index.ts";
|
|
12
|
+
import type { Auth, UserUpdate } from "./types.ts";
|
|
13
|
+
|
|
14
|
+
interface PlatformChallenge {
|
|
15
|
+
token: string;
|
|
16
|
+
expiredAt: number;
|
|
17
|
+
client: Client;
|
|
18
|
+
binding: Auth | undefined;
|
|
19
|
+
dispose: () => void;
|
|
20
|
+
}
|
|
12
21
|
|
|
13
22
|
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
14
23
|
export function initLogin(auth: AuthService) {
|
|
@@ -19,10 +28,10 @@ export function initLogin(auth: AuthService) {
|
|
|
19
28
|
const { ctx, config } = auth as AuthService & {
|
|
20
29
|
ctx: Context;
|
|
21
30
|
};
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
31
|
+
const states = new Map<string, PlatformChallenge>();
|
|
32
|
+
ctx.on("dispose", () => {
|
|
33
|
+
for (const state of states.values()) state.dispose();
|
|
34
|
+
});
|
|
26
35
|
|
|
27
36
|
// 用户密码登录:校验通过后签发新令牌
|
|
28
37
|
ctx.console.addListener(
|
|
@@ -35,7 +44,7 @@ export function initLogin(auth: AuthService) {
|
|
|
35
44
|
);
|
|
36
45
|
if (
|
|
37
46
|
!user?.password ||
|
|
38
|
-
!verifyPassword(password, user.password)
|
|
47
|
+
!(await verifyPassword(password, user.password))
|
|
39
48
|
)
|
|
40
49
|
throw new Error("用户名或密码错误。");
|
|
41
50
|
await self.createToken(
|
|
@@ -83,36 +92,68 @@ export function initLogin(auth: AuthService) {
|
|
|
83
92
|
ctx.console.addListener(
|
|
84
93
|
"login/platform",
|
|
85
94
|
async function (platform, userId) {
|
|
95
|
+
const binding = this.auth;
|
|
86
96
|
const user = await ctx.database.getUser(
|
|
87
97
|
platform,
|
|
88
98
|
userId,
|
|
89
99
|
["id", "name"],
|
|
90
100
|
);
|
|
91
101
|
if (!user) throw new Error("找不到此账户。");
|
|
92
|
-
if (
|
|
102
|
+
if (
|
|
103
|
+
ctx.console.clients[this.id] !== this ||
|
|
104
|
+
this.auth !== binding ||
|
|
105
|
+
(binding && binding.expiredAt <= Date.now())
|
|
106
|
+
)
|
|
107
|
+
throw new Error("登录状态已失效。");
|
|
108
|
+
if (binding?.id === user.id)
|
|
93
109
|
throw new Error("你已经绑定了此账户。");
|
|
94
110
|
|
|
95
111
|
const key = `${platform}:${userId}`;
|
|
112
|
+
const now = Date.now();
|
|
113
|
+
const previous = states.get(key);
|
|
114
|
+
if (
|
|
115
|
+
!binding &&
|
|
116
|
+
previous?.binding &&
|
|
117
|
+
previous.expiredAt > now &&
|
|
118
|
+
previous.binding.expiredAt > now &&
|
|
119
|
+
previous.client.auth === previous.binding
|
|
120
|
+
)
|
|
121
|
+
throw new Error("此平台账户正在等待绑定验证。");
|
|
122
|
+
previous?.dispose();
|
|
123
|
+
|
|
96
124
|
// 固定 6 位数字验证码(padStart 补零);原 Math.random 实现
|
|
97
125
|
// 在短小数串时不足 6 位,且非 CSPRNG
|
|
98
126
|
const token = String(
|
|
99
127
|
randomInt(0, 1_000_000),
|
|
100
128
|
).padStart(6, "0");
|
|
101
|
-
const expiredAt =
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
// 客户端断开或验证码超时即作废本次登录状态
|
|
129
|
+
const expiredAt = now + config.loginTokenExpire;
|
|
130
|
+
let cancelTimeout: (() => void) | undefined;
|
|
131
|
+
// 仅删除本次请求的状态,后续请求即使使用同一账户也相互独立。
|
|
106
132
|
const listener = () => {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
133
|
+
if (states.get(key)?.dispose === listener)
|
|
134
|
+
states.delete(key);
|
|
135
|
+
cancelTimeout?.();
|
|
136
|
+
this.socket.removeEventListener("close", listener);
|
|
110
137
|
};
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
114
|
-
|
|
138
|
+
const expire = () => {
|
|
139
|
+
const remaining = expiredAt - Date.now();
|
|
140
|
+
if (remaining <= 0) listener();
|
|
141
|
+
// 定时器延时超出 32 位有符号整数时会被缩短,长时效需要分段等待。
|
|
142
|
+
else
|
|
143
|
+
cancelTimeout = ctx.setTimeout(
|
|
144
|
+
expire,
|
|
145
|
+
Math.min(remaining, 0x7fffffff),
|
|
146
|
+
);
|
|
147
|
+
};
|
|
148
|
+
states.set(key, {
|
|
149
|
+
token,
|
|
150
|
+
expiredAt,
|
|
151
|
+
client: this,
|
|
152
|
+
binding,
|
|
153
|
+
dispose: listener,
|
|
154
|
+
});
|
|
115
155
|
this.socket.addEventListener("close", listener);
|
|
156
|
+
expire();
|
|
116
157
|
|
|
117
158
|
return {
|
|
118
159
|
id: user.id,
|
|
@@ -126,21 +167,32 @@ export function initLogin(auth: AuthService) {
|
|
|
126
167
|
// 平台账户登录(第二步):前置中间件捕获用户发给机器人的验证码——
|
|
127
168
|
// 客户端已登录则把该平台账号绑定到当前用户,否则为平台对应用户签发令牌
|
|
128
169
|
ctx.middleware(async (session, next) => {
|
|
129
|
-
const state = states
|
|
130
|
-
if (!state
|
|
170
|
+
const state = states.get(session.uid);
|
|
171
|
+
if (!state) return next();
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
const { binding, client } = state;
|
|
174
|
+
if (
|
|
175
|
+
state.expiredAt <= now ||
|
|
176
|
+
client.auth !== binding ||
|
|
177
|
+
(binding && binding.expiredAt <= now)
|
|
178
|
+
) {
|
|
179
|
+
state.dispose();
|
|
131
180
|
return next();
|
|
132
181
|
}
|
|
133
182
|
|
|
134
183
|
const { platform, userId: pid } = session;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
184
|
+
if (!pid || state.token !== session.stripped.content)
|
|
185
|
+
return next();
|
|
186
|
+
// 在任何异步操作前消费验证码,避免并发验证或重放。
|
|
187
|
+
state.dispose();
|
|
188
|
+
if (binding) {
|
|
138
189
|
await ctx.database.set(
|
|
139
190
|
"binding",
|
|
140
191
|
{ platform, pid },
|
|
141
|
-
{ aid:
|
|
192
|
+
{ aid: binding.id },
|
|
142
193
|
);
|
|
143
|
-
|
|
194
|
+
if (client.auth === binding)
|
|
195
|
+
return self.setAuth(client, binding);
|
|
144
196
|
} else {
|
|
145
197
|
const user = await session.observeUser([
|
|
146
198
|
"id",
|
|
@@ -148,8 +200,14 @@ export function initLogin(auth: AuthService) {
|
|
|
148
200
|
"authority",
|
|
149
201
|
"config",
|
|
150
202
|
]);
|
|
151
|
-
|
|
203
|
+
if (
|
|
204
|
+
client.auth === binding &&
|
|
205
|
+
ctx.console.clients[client.id] === client
|
|
206
|
+
) {
|
|
207
|
+
return self.createToken(client, "platform", user);
|
|
208
|
+
}
|
|
152
209
|
}
|
|
210
|
+
return;
|
|
153
211
|
}, true);
|
|
154
212
|
|
|
155
213
|
// 拦截带 authority 要求的 console 事件:未登录、令牌过期或
|
|
@@ -185,23 +243,55 @@ export function initLogin(auth: AuthService) {
|
|
|
185
243
|
token: this.auth.token,
|
|
186
244
|
});
|
|
187
245
|
}
|
|
188
|
-
await self.setAuth(this,
|
|
246
|
+
await self.setAuth(this, null);
|
|
189
247
|
});
|
|
190
248
|
|
|
191
249
|
// 修改用户资料(用户名 / 密码 / 配置),密码先哈希再落库
|
|
192
250
|
ctx.console.addListener(
|
|
193
251
|
"user/update",
|
|
194
|
-
async function (data) {
|
|
195
|
-
|
|
196
|
-
if (
|
|
197
|
-
|
|
252
|
+
async function (data: unknown) {
|
|
253
|
+
const current = this.auth;
|
|
254
|
+
if (!current) throw new Error("请先登录。");
|
|
255
|
+
if (!data || typeof data !== "object")
|
|
256
|
+
throw new Error("资料必须是普通对象。");
|
|
257
|
+
const prototype: unknown =
|
|
258
|
+
Object.getPrototypeOf(data);
|
|
259
|
+
if (
|
|
260
|
+
prototype !== Object.prototype &&
|
|
261
|
+
prototype !== null
|
|
262
|
+
)
|
|
263
|
+
throw new Error("资料必须是普通对象。");
|
|
264
|
+
const fields = data as Record<string, unknown>;
|
|
265
|
+
const { name, password, config } = fields;
|
|
266
|
+
const profile: Omit<UserUpdate, "password"> = {};
|
|
267
|
+
if (
|
|
268
|
+
Object.hasOwn(fields, "name") &&
|
|
269
|
+
typeof name === "string"
|
|
270
|
+
)
|
|
271
|
+
profile.name = name;
|
|
272
|
+
if (
|
|
273
|
+
Object.hasOwn(fields, "config") &&
|
|
274
|
+
typeof config === "object"
|
|
275
|
+
)
|
|
276
|
+
profile.config = config;
|
|
277
|
+
const update: UserUpdate = { ...profile };
|
|
278
|
+
if (
|
|
279
|
+
Object.hasOwn(fields, "password") &&
|
|
280
|
+
typeof password === "string" &&
|
|
281
|
+
password
|
|
282
|
+
) {
|
|
283
|
+
update.password = await toHash(password);
|
|
284
|
+
}
|
|
285
|
+
if (!Object.keys(update).length)
|
|
286
|
+
throw new Error("没有可更新的资料字段。");
|
|
287
|
+
if (this.auth !== current)
|
|
288
|
+
throw new Error("登录状态已失效。");
|
|
198
289
|
await ctx.database.set(
|
|
199
290
|
"user",
|
|
200
|
-
{ id:
|
|
201
|
-
|
|
291
|
+
{ id: current.id },
|
|
292
|
+
update,
|
|
202
293
|
);
|
|
203
|
-
Object.assign(
|
|
204
|
-
await self.setAuth(this, undefined, true);
|
|
294
|
+
Object.assign(current, profile);
|
|
205
295
|
},
|
|
206
296
|
);
|
|
207
297
|
|