diff --git a/README.md b/README.md index 4f48ff8..634564b 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,9 @@ 界面复用 [Tabler](https://tabler.io/admin-template) 免费开源版(@tabler/core 1.6.1),CSS/JS 全部在本机提供;MIT 原文见 licenses/Tabler-MIT.txt。青龙已有独立部署准备和 CLI,尚未接通业务,本次不启动它或复制其内部源码。 -工作台账号、群组设置和原 PDF 记录保存在 `%LOCALAPPDATA%\OrderNotificationAutomation\dashboard\state.sqlite`;业务日历、异常、连接与监管草稿保存在同级 `workspace` 目录的 SQLite 数据库中。邮箱、模板版本、原邮件、收信游标和测试发送记录保存在 `mail\mail.sqlite`,密码、原邮件和完整正文附件加密保存。BPM 会话与托管账号加密保存在 `bpm-sessions/accounts.sqlite`,旧 `.enc` 会话按读取迁移;主密钥经 Windows 当前运行用户 DPAPI 保护。数据留在运行机本地磁盘,不放项目所在的 Z: 共享盘。备份前停止服务并保护整个本地状态目录。旧版 `dashboard\state.json` 会首次导入 SQLite 并原样保留为迁移备份;后续以 `state.sqlite` 为准。工作台登录有效期为 30 天,每日活动自动续期;令牌哈希保存在 `dashboard\auth.sqlite`,服务重启后继续有效,退出登录立即撤销。已保存的 BPM 会话在同一 Windows 运行账号下恢复。 +工作台账号、群组设置和原 PDF 记录保存在 `%LOCALAPPDATA%\OrderNotificationAutomation\dashboard\state.sqlite`;业务日历、异常、连接与监管草稿保存在同级 `workspace` 目录的 SQLite 数据库中。邮箱、模板版本、原邮件、收信游标和测试发送记录保存在 `mail\mail.sqlite`,密码、原邮件和完整正文附件加密保存。BPM 会话与托管账号加密保存在 `bpm-sessions/accounts.sqlite`,旧 `.enc` 会话按读取迁移;主密钥经 Windows 当前运行用户 DPAPI 保护。数据留在运行机本地磁盘,不放项目所在的 Z: 共享盘。备份前停止服务并保护整个本地状态目录。旧版 `dashboard\state.json` 会首次导入 SQLite 并原样保留为迁移备份;后续以 `state.sqlite` 为准。所有成员可从右上角“修改密码”维护个人密码(须验证当前密码,12–128位、两次输入一致且不得沿用原密码)。管理员可在“团队账号”验证自己的当前密码后重置其他成员密码;自己的密码使用个人入口修改。改密或重置会使该账号全部旧登录失效,关闭关联的临时BPM登录窗口,并写入不含密码的操作记录。改密成功后需重新登录,其他成员会话不受影响。 + +工作台登录有效期为 30 天,每日活动自动续期;令牌哈希保存在 `dashboard\auth.sqlite`,服务重启后继续有效,退出登录立即撤销。已保存的 BPM 会话在同一 Windows 运行账号下恢复。 ## 邮箱与邮件模板 diff --git a/docs/deployment.md b/docs/deployment.md index 0671ae2..2ea6ba9 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -28,7 +28,7 @@ Web 默认监听 `0.0.0.0:18766`,PDF 扩展桥接仅监听 `127.0.0.1:18765` 备份先停止服务,再备份整个状态目录及业务输出目录;SQLite 的 WAL 文件与数据库必须保持一致。备份包含敏感数据,需限制访问及加密保存。密钥由 Windows DPAPI 绑定运行身份,单独复制 SQLite 或加密文件无法保证跨机器恢复;迁移前验证恢复条件,必要时重新登录及录入渠道凭据。 -升级前备份,安装锁定依赖后再启动。Git 仓库不含运行数据库、凭据、Cookie、日志或业务输出,克隆源码不会同步这些数据,也不会恢复已有登录状态。`scripts/preview.cjs` 仅供隔离开发验证,正式启动使用 `npm start`。 +升级前备份,安装锁定依赖后再启动。Git 仓库不含运行数据库、凭据、Cookie、日志或业务输出,克隆源码不会同步这些数据,也不会恢复已有登录状态。演示启动脚本与免登录入口已移除,正式启动使用 `npm start`。 ## 开发与发布检查 @@ -38,3 +38,9 @@ Web 默认监听 `0.0.0.0:18766`,PDF 扩展桥接仅监听 `127.0.0.1:18765` - 使用 HTTPS 与 Git Credential Manager 访问私有仓库,不把密码或令牌写进远端 URL。 最新扫描验证范围及历史测试结果见 [扫描验证](bpm-scan-verification-2026-10-16.md) 和 [验证历史](verification.md)。 + +## 工作台密码维护 + +所有角色均可使用右上角“修改密码”入口,输入当前密码、新密码和确认密码。新密码需12–128位且与原密码不同。管理员在“团队账号”选择其他成员的“重置密码”,以管理员当前密码验证身份;管理员自己的密码使用个人入口修改。连续10次当前密码验证失败将限制15分钟。 + +成功改密会在同一次状态提交中保存加盐密码哈希、递增密码版本并记录审计,随后清理该账号的登录会话和临时BPM登录窗口。每次认证均核对会话密码版本,即使清理记录失败或服务重启,旧会话也不能继续使用。原会话表会自动补充版本字段,未改密的已有登录继续有效。操作记录与接口响应不含密码或密码哈希。 diff --git a/docs/verification.md b/docs/verification.md index 416e530..905b29b 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -134,3 +134,11 @@ - 移除演示启动脚本、npm 命令、免登录接口和按钮;旧演示 cookie 不能认证。演示服务已停止,演示数据移至本机恢复目录;正式配置及15类规则草稿保留。 - 正式邮箱管理可进入只读历史查询;只读邮箱不列入发信邮箱管理或模板发信选择。 - 相关认证、权限、工作台、规则和邮件回归16项通过,0失败;git diff --check通过。正式18765/18766健康,18776/18786无监听。 + +## 2026-10-19 账号密码维护 + +- 所有角色均可通过右上角“修改密码”维护自己的密码;管理员可在团队账号中重置其他成员密码,两种操作均验证操作者当前密码。账号界面及密码校验分别拆为独立模块。 +- 密码哈希、持久化密码版本及审计原子更新;目标账号全部旧会话失效,重启后仍生效。密码接口响应不写 cookie,避免延迟响应覆盖其他标签页的新登录;排队中的已撤销 BPM 登录操作也会被阻止。 +- 相关回归74项通过,0失败、0跳过:`node --test --test-concurrency=2 "tests/app/*.test.cjs" "tests/dashboard/*.test.cjs" tests/workspace/workspace-http.test.cjs tests/bpm/bpm-http.test.cjs tests/bpm/bpm-session.test.cjs`。覆盖角色权限、密码校验及限流、会话撤销、并发响应、浏览器操作与移动端;未运行整个仓库测试集。 +- 独立审查发现的排队 BPM 登录撤销与延迟密码响应覆盖 cookie 问题均已修复,并经回归及复核确认。一次未限制并发的运行遇到 BPM 临时目录权限初始化失败,按仓库并发参数重新运行后全部通过。 +- 正式服务已备份并重启,18765/18766健康;状态指纹核对确认原账号、密码及配置未改变,既有会话迁移成功。正式个人账号页截图:`output/verification/formal-account-password.png`;未在真实账号上提交密码修改。 diff --git a/src/app/assets.cjs b/src/app/assets.cjs index 30e1de8..69681c3 100644 --- a/src/app/assets.cjs +++ b/src/app/assets.cjs @@ -5,6 +5,7 @@ function createAssets(){ const assets={ '/':{path:path.join(webRoot,'index.html'),type:'text/html'}, '/app.js':{path:path.join(webRoot,'app.js'),type:'text/javascript'}, + '/account.js':{path:path.join(webRoot,'modules/account/view.js'),type:'text/javascript'}, '/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'}, '/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'}, '/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'}, diff --git a/src/modules/bpm/session-manager.cjs b/src/modules/bpm/session-manager.cjs index c377add..17c1ef4 100644 --- a/src/modules/bpm/session-manager.cjs +++ b/src/modules/bpm/session-manager.cjs @@ -1,6 +1,7 @@ 'use strict'; const fs = require('node:fs'); const path = require('node:path'); +const crypto = require('node:crypto'); const { BpmVault } = require('../../platform/security/vault.cjs'); const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs'); const { BpmListClient } = require('./list-client.cjs'); @@ -37,7 +38,7 @@ class BpmSessionManager { } this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions())); this.probe = probe || this.defaultProbe.bind(this); - this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.stopped = false; + this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.revokedSessionHashes=new Set(); this.stopped = false; } allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } } vault() { return this._vault ||= new BpmVault({ stateDir: this.stateDir }); } @@ -139,6 +140,7 @@ class BpmSessionManager { authorize(connection, principal) { if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。'); if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403); + if(this.revokedSessionHashes.has(crypto.createHash('sha256').update(principal.sessionId).digest('hex')))throw error('工作台登录已失效,请重新登录。',401); if (this.stopped) throw error('BPM 服务正在关闭。',503); if (connection.status === 'disabled' || this.disabled.has(connection.id)) throw error('此 BPM 连接已停用。',409); } @@ -271,6 +273,7 @@ class BpmSessionManager { this.authorize(connection,principal); if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403); await this.fillSavedAccount(lease); + this.authorize(connection,principal); return lease; } catch (cause) { await this.closeLease(connection.id); throw safe(cause); } } @@ -278,6 +281,7 @@ class BpmSessionManager { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=this.sessions.has(connection.id) ? await this.getLease(connection.id,principal,true) : await this.create(connection,principal); + this.authorize(connection,principal); return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host }; }); } @@ -393,6 +397,11 @@ class BpmSessionManager { } async close(id,principal) { return this.run(id,async()=>{ if (!this.sessions.has(id)) return {active:false}; await this.getLease(id,principal,false,true); await this.closeLease(id); return {active:false}; }); } async releaseSession(sessionId) { await Promise.all([...this.sessions.values()].filter(lease=>lease.sessionId===sessionId).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id)))); } + async releaseSessionHashes(hashes) { + const revoked=new Set(hashes); + for(const hash of revoked)this.revokedSessionHashes.add(hash); + await Promise.all([...this.sessions.values()].filter(lease=>revoked.has(crypto.createHash('sha256').update(lease.sessionId).digest('hex'))).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id)))); + } async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); } async shutdown() { this.stopped=true; diff --git a/src/modules/dashboard/auth.cjs b/src/modules/dashboard/auth.cjs index 9579f24..fde56b0 100644 --- a/src/modules/dashboard/auth.cjs +++ b/src/modules/dashboard/auth.cjs @@ -1,8 +1,9 @@ const path=require('node:path'); const {SessionStore,SESSION_MS}=require('./sessions.cjs'); const {isLoopback}=require('../../app/request.cjs'); +const {validateChange}=require('./passwords.cjs'); function createAuth({store,bpmSessions}){ - const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(); + const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map(); const sessionCookieName='order_session'; const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)'); async function authenticate({request,response,route,body,reply,fail,encryptedTransport}){ @@ -11,7 +12,7 @@ const handled=(...args)=>{reply(...args);return {handled:true};}; const canSetup=isLoopback(request.socket.remoteAddress) && ['localhost','127.0.0.1'].includes(host); if(route==='/api/bootstrap/status' && request.method==='GET')return handled(200,{required:store.users().length===0,canSetup}); function signIn(user) { - const {token}=sessions.issue(user.id); + const {token}=sessions.issue(user.id,Date.now(),store.passwordVersion(user.id)); response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`); return user; } @@ -29,9 +30,34 @@ const handled=(...args)=>{reply(...args);return {handled:true};}; } const token=sessionCookiePattern.exec(request.headers.cookie || '')?.[1]; const session=sessions.lookup(token);const user=session?store.user(session.userId):null; - if(!user)fail(401,'请先登录。'); - if(session.renewed)response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`); + if(!user||session.passwordVersion!==store.passwordVersion(user.id))fail(401,'请先登录。'); + const reset=/^\/api\/users\/([\w-]+)\/password$/.exec(route); + const passwordRequest=(route==='/api/account/password'||reset)&&request.method==='POST'; + if(session.renewed&&!passwordRequest)response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`); if(route==='/api/me' && request.method==='GET')return handled(200,{user}); + if(passwordRequest){ + if(reset&&user.role!=='admin')fail(403,'仅管理员可以重置成员密码。'); + const targetId=reset?reset[1]:user.id; + if(reset&&targetId===user.id)fail(400,'请通过个人账号修改自己的密码。'); + if(!store.user(targetId))fail(404,'账号不存在。'); + validateChange(body); + const now=Date.now();for(const [id,value]of passwordFailures)if(now-value.since>900000)passwordFailures.delete(id); + if(passwordFailures.get(user.id)?.count>=10)fail(429,'当前密码验证失败次数过多,请 15 分钟后重试。'); + if(!store.authenticate(user.username,body.currentPassword)){ + const prior=passwordFailures.get(user.id);passwordFailures.set(user.id,{since:prior?.since||now,count:(prior?.count||0)+1});fail(400,'当前密码不正确。'); + } + const hashes=sessions.userSessionHashes(targetId); + store.updatePassword(targetId,body.newPassword,user); + passwordFailures.delete(user.id); + // The committed password version invalidates sessions even if pruning fails. + try{sessions.revokeUser(targetId);}catch{console.error('密码已更新,旧会话将由密码版本校验失效;会话记录清理待重试。');} + const requiresLogin=targetId===user.id; + // Do not mutate the browser cookie: another tab may have signed in while + // cleanup was pending. Password-version checks already revoke old tokens. + let cleanupPending=false; + try{if(bpmSessions?.releaseSessionHashes)await bpmSessions.releaseSessionHashes(hashes);else if(requiresLogin)await bpmSessions?.releaseSession(token);}catch{cleanupPending=true;} + return handled(200,{ok:true,requiresLogin,cleanupPending}); + } if(route==='/api/logout' && request.method==='POST'){sessions.revoke(token);response.setHeader('Set-Cookie',`${sessionCookieName}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${encryptedTransport?'; Secure':''}`);if(bpmSessions)try{await bpmSessions.releaseSession(token);}catch{fail(502,'登录窗口关闭失败,请稍后重试。');}return handled(200,{ok:true});} return {user,token}; } diff --git a/src/modules/dashboard/passwords.cjs b/src/modules/dashboard/passwords.cjs new file mode 100644 index 0000000..fdd1451 --- /dev/null +++ b/src/modules/dashboard/passwords.cjs @@ -0,0 +1,18 @@ +'use strict'; +const crypto=require('node:crypto'); +const fail=message=>{throw Object.assign(new Error(message),{status:400});}; +function validatePassword(password){if(typeof password!=='string'||password.length<12||password.length>128)fail('密码长度需为 12–128 位。');} +function hashPassword(password){validatePassword(password);const salt=crypto.randomBytes(16).toString('hex');return salt+':'+crypto.scryptSync(password,salt,32).toString('hex');} +function matchesPassword(password,encoded){ + if(typeof password!=='string'||password.length>128)return false; + const [salt,hash]=(encoded||'00000000000000000000000000000000:'+ '0'.repeat(64)).split(':'); + const actual=crypto.scryptSync(password,salt,32),expected=Buffer.from(hash||'','hex'); + return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected); +} +function validateChange(body){ + if(!body||Object.keys(body).some(key=>!['currentPassword','newPassword','confirmPassword'].includes(key)))fail('密码修改内容不正确。'); + if(typeof body.currentPassword!=='string'||!body.currentPassword||body.currentPassword.length>128)fail('请填写当前密码。'); + validatePassword(body.newPassword); + if(body.confirmPassword!==body.newPassword)fail('两次输入的新密码不一致。'); +} +module.exports={validatePassword,hashPassword,matchesPassword,validateChange}; diff --git a/src/modules/dashboard/sessions.cjs b/src/modules/dashboard/sessions.cjs index b3686ea..c466c82 100644 --- a/src/modules/dashboard/sessions.cjs +++ b/src/modules/dashboard/sessions.cjs @@ -10,27 +10,30 @@ class SessionStore { try { fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite')); this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);'); + if(!this.db.prepare('PRAGMA table_info(sessions)').all().some(column=>column.name==='passwordVersion'))this.db.exec('ALTER TABLE sessions ADD COLUMN passwordVersion INTEGER NOT NULL DEFAULT 0'); } catch(error) { try { this.db?.close(); } catch {} throw error; } } - issue(userId,now=Date.now()){ + issue(userId,now=Date.now(),passwordVersion=0){ this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(now); this.db.exec('DELETE FROM sessions WHERE hash IN (SELECT hash FROM sessions ORDER BY renewedAt DESC LIMIT -1 OFFSET 999)'); const token=crypto.randomBytes(32).toString('hex'),expires=now+SESSION_MS; - this.db.prepare('INSERT INTO sessions(hash,userId,expires,renewedAt) VALUES(?,?,?,?)').run(digest(token),userId,expires,now); + this.db.prepare('INSERT INTO sessions(hash,userId,expires,renewedAt,passwordVersion) VALUES(?,?,?,?,?)').run(digest(token),userId,expires,now,passwordVersion); return {token,expires}; } lookup(token,now=Date.now()){ if(typeof token!=='string' || !/^[a-f0-9]{64}$/.test(token))return null; - const hash=digest(token),row=this.db.prepare('SELECT userId,expires,renewedAt FROM sessions WHERE hash=?').get(hash); + const hash=digest(token),row=this.db.prepare('SELECT userId,expires,renewedAt,passwordVersion FROM sessions WHERE hash=?').get(hash); if(!row)return null; if(row.expires<=now){this.db.prepare('DELETE FROM sessions WHERE hash=?').run(hash);return null;} const renewed=now-row.renewedAt>=DAY; if(renewed){row.expires=now+SESSION_MS;this.db.prepare('UPDATE sessions SET expires=?,renewedAt=? WHERE hash=?').run(row.expires,now,hash);} - return {userId:row.userId,expires:row.expires,renewed}; + return {userId:row.userId,expires:row.expires,renewed,passwordVersion:row.passwordVersion}; } + userSessionHashes(userId){return this.db.prepare('SELECT hash FROM sessions WHERE userId=?').all(userId).map(row=>row.hash);} + revokeUser(userId){this.db.prepare('DELETE FROM sessions WHERE userId=?').run(userId);} revoke(token){if(typeof token==='string' && /^[a-f0-9]{64}$/.test(token))this.db.prepare('DELETE FROM sessions WHERE hash=?').run(digest(token));} close(){if(this.db){this.db.close();this.db=null;}} } diff --git a/src/modules/dashboard/store.cjs b/src/modules/dashboard/store.cjs index 24a943b..fbfaab1 100644 --- a/src/modules/dashboard/store.cjs +++ b/src/modules/dashboard/store.cjs @@ -2,6 +2,7 @@ const fs=require('node:fs'); const path=require('node:path'); const crypto=require('node:crypto'); const {DatabaseSync}=require('node:sqlite'); +const {validatePassword,hashPassword,matchesPassword}=require('./passwords.cjs'); const copy=value=>structuredClone(value); const safeUser=({id,username,role,createdAt})=>({id,username,role,createdAt}); const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});}; @@ -69,11 +70,10 @@ class Store { user(id){const user=this.data.users.find(user=>user.id===id);return user?safeUser(user):null;} makeUser(username,password,role) { if(typeof username!=='string' || !/^[a-zA-Z0-9_.-]{3,40}$/.test(username))fail('账号需为 3–40 位英文、数字、点、下划线或短横线。'); - if(typeof password!=='string' || password.length<12 || password.length>128)fail('密码长度需为 12–128 位。'); + validatePassword(password); if(!['admin','operator','viewer'].includes(role))fail('账号角色不正确。'); if(this.data.users.some(user=>user.username.toLowerCase()===username.toLowerCase()))fail('账号已存在。',409); - const salt=crypto.randomBytes(16).toString('hex'); - return {id:crypto.randomUUID(),username,role,createdAt:new Date().toISOString(),passwordHash:salt+':'+crypto.scryptSync(password,salt,32).toString('hex')}; + return {id:crypto.randomUUID(),username,role,createdAt:new Date().toISOString(),passwordHash:hashPassword(password)}; } bootstrap(username,password) { if(this.data.users.length)fail('管理员已经创建,请登录。',409); @@ -87,11 +87,21 @@ class Store { authenticate(username,password) { if(typeof username!=='string' || typeof password!=='string' || password.length>128)return null; const user=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase()); - const [salt,hash]=(user?.passwordHash || '00000000000000000000000000000000:'+ '0'.repeat(64)).split(':'); - const actual=crypto.scryptSync(password,salt,32); - if(!crypto.timingSafeEqual(actual,Buffer.from(hash,'hex')) || !user)return null; + if(!matchesPassword(password,user?.passwordHash) || !user)return null; return safeUser(user); } + passwordVersion(id){return this.data.users.find(user=>user.id===id)?.passwordVersion||0;} + updatePassword(id,password,actor){ + const user=this.data.users.find(user=>user.id===id);if(!user)fail('账号不存在。',404); + validatePassword(password);if(matchesPassword(password,user.passwordHash))fail('新密码不能与原密码相同。'); + const passwordHash=hashPassword(password); + return this.commit(draft=>{ + const target=draft.users.find(user=>user.id===id);target.passwordHash=passwordHash; + target.passwordVersion=(target.passwordVersion||0)+1; + this.addAudit(draft,actor.username,actor.id===id?'修改密码':'重置密码',target.username); + return safeUser(target); + }); + } recordJob(record) { return this.commit(draft=>{ const index=draft.jobs.findIndex(job=>job.jobId===record.jobId); diff --git a/tests/app/account-password.test.cjs b/tests/app/account-password.test.cjs new file mode 100644 index 0000000..16beefd --- /dev/null +++ b/tests/app/account-password.test.cjs @@ -0,0 +1,83 @@ +'use strict'; +const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'); +const {SessionStore}=require('../../src/modules/dashboard/sessions.cjs'); +const OLD='Test-password-123',NEW='Changed-password-456'; +async function fixture(t,options={}){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-password-')),store=new Store(dir);const admin=store.bootstrap('admin',OLD); + const viewer=store.addUser({username:'viewer',password:OLD,role:'viewer'},'admin'),operator=store.addUser({username:'operator',password:OLD,role:'operator'},'admin'); + let server,base;async function start(){server=createDashboard({store,outputDir:dir,...options});await new Promise(r=>server.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+server.address().port;} + async function stop(){server.closeAllConnections();await new Promise(r=>server.close(r));}await start();t.after(async()=>{await stop();fs.rmSync(dir,{recursive:true,force:true});}); + const call=(route,body,cookie,origin)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:origin||base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}); + const login=async(username='admin',password=OLD)=>{const r=await call('/api/login',{username,password});assert.equal(r.status,200);return r.headers.get('set-cookie').split(';')[0];}; + return {dir,store,admin,viewer,operator,call,login,restart:async()=>{await stop();await start();}}; +} +const input=(currentPassword=OLD,newPassword=NEW)=>({currentPassword,newPassword,confirmPassword:newPassword}); +test('every role can change own password; all old sessions expire and new credentials persist after restart',async t=>{ + const f=await fixture(t);for(const username of ['admin','viewer','operator']){ + const first=await f.login(username),second=await f.login(username);const result=await f.call('/api/account/password',input(),first);assert.equal(result.status,200);assert.equal((await result.json()).requiresLogin,true);assert.equal(result.headers.get('set-cookie'),null); + assert.equal((await f.call('/api/me',undefined,first)).status,401);assert.equal((await f.call('/api/me',undefined,second)).status,401);assert.equal((await f.call('/api/login',{username,password:OLD})).status,401); + assert.ok(new Store(f.dir).authenticate(username,NEW));await f.restart();assert.equal((await f.call('/api/me',undefined,second)).status,401);assert.equal((await f.call('/api/me',undefined,await f.login(username,NEW))).status,200); + } + const serialized=JSON.stringify(f.store.audit());assert.match(serialized,/修改密码/);assert.equal(serialized.includes(NEW),false);assert.equal(serialized.includes(OLD),false); + assert.equal(fs.readFileSync(path.join(f.dir,'state.sqlite')).includes(Buffer.from(NEW)),false); +}); +test('invalid password edits, wrong current password, and cross-origin requests preserve existing credentials and sessions',async t=>{ + const f=await fixture(t),cookie=await f.login();const original=JSON.stringify(f.store.data); + const invalid=[input('incorrect'),input(OLD,'short'),input(OLD,'x'.repeat(129)),input(OLD,OLD),{...input(),confirmPassword:'Mismatch-password-123'},{...input(),userId:f.viewer.id}]; + for(const body of invalid)assert.equal((await f.call('/api/account/password',body,cookie)).status,400); + assert.equal((await f.call('/api/account/password',input(),cookie,'https://evil.test')).status,403);assert.equal((await f.call('/api/account/password',input())).status,401); + assert.equal(JSON.stringify(f.store.data),original);assert.equal((await f.call('/api/me',undefined,cookie)).status,200); +}); +test('admin reset requires admin current password, revokes target sessions, preserves other accounts, and rejects self reset',async t=>{ + const f=await fixture(t),admin=await f.login(),target=await f.login('viewer');const route='/api/users/'+f.viewer.id+'/password'; + assert.equal((await f.call(route,input(),target)).status,403);assert.equal((await f.call(route,input('incorrect'),admin)).status,400); + assert.equal((await f.call('/api/users/'+f.admin.id+'/password',input(),admin)).status,400);assert.equal((await f.call('/api/users/missing/password',input(),admin)).status,404); + const r=await f.call(route,input(),admin);assert.equal(r.status,200);assert.equal((await r.json()).requiresLogin,false); + assert.equal((await f.call('/api/me',undefined,target)).status,401);assert.equal((await f.call('/api/me',undefined,admin)).status,200);assert.ok(f.store.authenticate('viewer',NEW));assert.ok(f.store.authenticate('admin',OLD)); + assert.match(JSON.stringify(f.store.audit()),/重置密码/); +}); +test('incorrect current passwords are rate limited without invalidating a valid session',async t=>{ + const f=await fixture(t),cookie=await f.login();for(let i=0;i<10;i++)assert.equal((await f.call('/api/account/password',input('incorrect'),cookie)).status,400); + assert.equal((await f.call('/api/account/password',input(),cookie)).status,429);assert.equal((await f.call('/api/me',undefined,cookie)).status,200); +}); +test('password version rejects old sessions even if eager session cleanup fails',async t=>{ + const f=await fixture(t),cookie=await f.login();const original=SessionStore.prototype.revokeUser;SessionStore.prototype.revokeUser=()=>{throw Error('injected cleanup failure');}; + try{assert.equal((await f.call('/api/account/password',input(),cookie)).status,200);}finally{SessionStore.prototype.revokeUser=original;} + assert.equal((await f.call('/api/me',undefined,cookie)).status,401);await f.restart();assert.equal((await f.call('/api/me',undefined,cookie)).status,401);await f.login('admin',NEW); +}); + +test('password change closes only the target account BPM login windows',async t=>{ + const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'); + const f=await fixture(t),first=await f.login('viewer'),second=await f.login('viewer'),admin=await f.login(); + const cookies=[first,second,admin],manager={revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}}; + const hashes=new SessionStore(f.dir);const targetHashes=hashes.userSessionHashes(f.viewer.id);hashes.close(); + assert.equal(targetHashes.length,2);await BpmSessionManager.prototype.releaseSessionHashes.call(manager,targetHashes);assert.deepEqual([...manager.sessions.keys()],['2']); + assert.equal(targetHashes.includes(crypto.createHash('sha256').update(admin.split('=')[1]).digest('hex')),false); +}); +test('existing database sessions survive schema migration until their account password changes',async t=>{ + const {DatabaseSync}=require('node:sqlite'),crypto=require('node:crypto'); + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-legacy-session-')),store=new Store(dir),user=store.bootstrap('admin',OLD),token=crypto.randomBytes(32).toString('hex'); + const db=new DatabaseSync(path.join(dir,'auth.sqlite'));db.exec('CREATE TABLE sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL)');db.prepare('INSERT INTO sessions VALUES(?,?,?,?)').run(crypto.createHash('sha256').update(token).digest('hex'),user.id,Date.now()+86400000,Date.now());db.close(); + const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});}); + const base='http://127.0.0.1:'+server.address().port,cookie='order_session='+token; + assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,200); + const updated=await fetch(base+'/api/account/password',{method:'POST',headers:{Origin:base,'Content-Type':'application/json',Cookie:cookie},body:JSON.stringify(input())});assert.equal(updated.status,200);assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,401); +}); + +test('a delayed password response never clears or renews over a later login cookie',async t=>{ + let arrived,release;const entered=new Promise(r=>arrived=r),gate=new Promise(r=>release=r); + const f=await fixture(t,{bpmSessions:{async releaseSessionHashes(){arrived();await gate;}}}),cookie=await f.login(); + const {DatabaseSync}=require('node:sqlite');const db=new DatabaseSync(path.join(f.dir,'auth.sqlite'));db.prepare('UPDATE sessions SET renewedAt=?').run(Date.now()-2*86400000);db.close(); + const pending=f.call('/api/account/password',input(),cookie);await entered; + try{const fresh=await f.login('viewer');release();const result=await pending;assert.equal(result.status,200);assert.equal(result.headers.get('set-cookie'),null,'late credential response must not overwrite a newer browser login');assert.equal((await f.call('/api/me',undefined,fresh)).status,200);}finally{release();} +}); +test('revoked BPM principals queued before lease creation cannot open a new login window',async()=>{ + const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'); + const manager=new BpmSessionManager({stateDir:os.tmpdir()}),principal={sessionId:'revoked-token',user:{id:'a',username:'admin',role:'admin'}},connection={id:'queued',status:'disconnected'}; + let release;const gate=new Promise(r=>release=r);const blocker=manager.run(connection.id,()=>gate); + manager.create=async(connection,principal)=>{manager.authorize(connection,principal);const lease={id:connection.id,sessionId:principal.sessionId,expiresAt:Date.now()+10000,page:{url:()=> 'https://bpmn.skyworthdigital.com/'}};manager.sessions.set(connection.id,lease);return lease;}; + const opening=assert.rejects(manager.open(connection,principal),e=>e.status===401); + try{await manager.releaseSessionHashes([crypto.createHash('sha256').update(principal.sessionId).digest('hex')]);}finally{release();} + await blocker;await opening;assert.equal(manager.sessions.size,0);assert.throws(()=>manager.authorize(connection,principal),e=>e.status===401); +}); diff --git a/tests/app/account-ui.test.cjs b/tests/app/account-ui.test.cjs new file mode 100644 index 0000000..88d095d --- /dev/null +++ b/tests/app/account-ui.test.cjs @@ -0,0 +1,28 @@ +'use strict'; +const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); +const OLD='Test-password-123',NEW='Changed-password-456'; +test('account UI lets every role change passwords, validates confirmation, and gives admins a member reset form',{timeout:90000},async t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-ui-')),store=new Store(dir);const admin=store.bootstrap('admin',OLD),viewer=store.addUser({username:'viewer',password:OLD,role:'viewer'},'admin');store.addUser({username:'operator',password:OLD,role:'operator'},'admin'); + const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;let browser; + t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const errors=[]; + const login=async(page,username,password=OLD)=>{await page.getByLabel('账号',{exact:true}).fill(username);await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('link',{name:'修改密码',exact:true}).waitFor({timeout:5000});}; + const page=await browser.newPage({viewport:{width:1440,height:1000}});page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#users');await login(page,'admin'); + assert.equal(await page.locator('[data-reset-user="'+admin.id+'"]').count(),0);await page.locator('[data-reset-user="'+viewer.id+'"]').click(); + await page.getByLabel('管理员当前密码',{exact:true}).fill(OLD);await page.getByLabel('成员新密码',{exact:true}).fill(NEW);await page.getByLabel('确认成员新密码',{exact:true}).fill(NEW);await page.getByRole('button',{name:'确认重置密码',exact:true}).click();await page.getByText('成员密码已重置,该账号需要重新登录。',{exact:true}).waitFor();assert.ok(store.authenticate('viewer',NEW));assert.equal(await page.locator('#password-reset-form').count(),0); + // The separate create-user flow remains usable after introducing reset controls. + await page.getByLabel('登录账号',{exact:true}).fill('new-member');await page.getByLabel('初始密码',{exact:true}).fill(OLD);await page.getByRole('button',{name:'创建账号',exact:true}).click();await page.getByText('new-member',{exact:true}).waitFor(); + for(const [username,password]of [['admin',OLD],['operator',OLD],['viewer',NEW]]){ + const account=username==='admin'?page:await browser.newPage();if(account!==page){account.on('pageerror',e=>errors.push(e.message));await account.goto(base+'/#account');await login(account,username,password);} + await account.getByRole('link',{name:'修改密码',exact:true}).click();await account.getByLabel('当前密码',{exact:true}).fill('incorrect');await account.getByLabel('新密码',{exact:true}).fill('Final-password-789');await account.getByLabel('确认新密码',{exact:true}).fill('different-password-789');await account.getByRole('button',{name:'保存新密码',exact:true}).click();await account.getByText('两次输入的新密码不一致。',{exact:true}).waitFor(); + await account.getByLabel('确认新密码',{exact:true}).fill('Final-password-789');await account.getByRole('button',{name:'保存新密码',exact:true}).click();await account.getByText('当前密码不正确。',{exact:true}).waitFor();assert.equal(await account.getByLabel('新密码',{exact:true}).inputValue(),'Final-password-789'); + await account.getByLabel('当前密码',{exact:true}).fill(password); + if(username==='admin'){await account.setViewportSize({width:390,height:844});assert.equal(await account.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await fs.promises.mkdir(path.resolve('output/verification'),{recursive:true});await account.screenshot({path:path.resolve('output/verification/account-password-mobile.png'),fullPage:true});await account.setViewportSize({width:1440,height:1000});} + let release,arrived;const pending=new Promise(r=>arrived=r); + if(username==='operator')await account.route('**/api/account/password',async route=>{arrived();await new Promise(r=>release=r);await route.continue();},{times:1}); + await account.getByRole('button',{name:'保存新密码',exact:true}).click(); + if(username==='operator'){await pending;await account.getByRole('link',{name:'操作记录',exact:true}).click();release();} + await account.getByRole('heading',{name:'登录工作台',exact:true}).waitFor({timeout:5000});await account.getByText('密码已修改,请使用新密码重新登录。',{exact:true}).waitFor();await login(account,username,'Final-password-789');assert.ok(store.authenticate(username,'Final-password-789')); + } + assert.deepEqual(errors,[]); +}); diff --git a/web/app.js b/web/app.js index 8bb6499..c0ad5f9 100644 --- a/web/app.js +++ b/web/app.js @@ -5,7 +5,7 @@ const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN( const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'}; const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']}; let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0; -const views={'order-rules':['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']}; +const views={account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']}; async function api(route,body,{signal}={}) { const response=await fetch('/api'+route,{signal,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined}); const result=await response.json(); @@ -19,7 +19,7 @@ function notify(message,type='success') { function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `${label}`;} function navItem(id,symbol){return ``;} function shell() { - root.innerHTML=`
`; + root.innerHTML=`
`; document.querySelector('#logout').onclick=async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();}; document.querySelector('#refresh').onclick=()=>renderView().catch(error=>notify(error.message,'danger')); document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{document.querySelector('#sidebar-menu').classList.remove('show');}); @@ -62,10 +62,6 @@ async function viewTemplates(container,isActive=()=>true) { async function viewConnections(container,isActive=()=>true) { const data=await api('/overview');if(!isActive())return;container.innerHTML=`
邮箱管理BPM 连接存储服务器业务通知
${data.connections.map(item=>`

${esc(item.name)}

${item.ready?'已就绪':'待接入'}
${esc(item.detail)}
`).join('')}
`; } -async function viewUsers(container,isActive=()=>true) { - const {users}=await api('/users');if(!isActive())return;container.innerHTML=`

团队账号

${users.map(user=>``).join('')}
账号角色创建时间
${esc(user.username)}${roles[user.role]}${formatDate(user.createdAt)}

添加同事

英文、数字、点、下划线或短横线
管理员管理配置和账号;操作员处理异常;只读成员查看和下载。
`; - document.querySelector('#user-form').onsubmit=async event=>{event.preventDefault();try{await api('/users',{username:document.querySelector('#new-username').value,password:document.querySelector('#new-password').value,role:document.querySelector('#new-role').value});notify('账号已创建。');await viewUsers(container,isActive);}catch(error){notify(error.message,'danger');}}; -} async function viewAudit(container,isActive=()=>true){const [legacy,workspace]=await Promise.all([api('/audit'),api('/workspace')]);if(!isActive())return;const audit=[...legacy.audit,...workspace.audit].sort((a,b)=>new Date(b.at)-new Date(a.at));container.innerHTML=`

最近操作记录

按时间展示最近 200 条
${audit.length?`
${audit.slice(0,200).map(item=>``).join('')}
时间(北京时间)操作人操作详情
${formatDate(item.at)}${esc(item.actor)}${esc(window.WorkspaceViews.activityText(item.action))}${esc(item.detail)}
`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}
`;} function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive);} async function renderView() { @@ -77,7 +73,7 @@ async function renderView() { document.querySelectorAll('[data-view]').forEach(link=>link.classList.toggle('active',link.dataset.view===currentView)); document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1]; const container=document.querySelector('#content');container.innerHTML='
正在加载…
'; - const fn={'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView]; + const fn={account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView]; try{await fn(container,isActive);}catch(error){if(isActive())container.innerHTML=`
${esc(error.message)}
`;} } async function authScreen() { @@ -86,7 +82,8 @@ async function authScreen() { document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}}; } -function enter(){window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} +async function passwordChanged(actorId){if(currentUser&¤tUser.id!==actorId)return false;currentUser=null;++viewGeneration;clearInterval(refreshTimer);await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;} +function enter(){window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}} window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});}); window.addEventListener('hashchange',()=>{if(currentUser)renderView();}); diff --git a/web/index.html b/web/index.html index 7cd05df..58880b1 100644 --- a/web/index.html +++ b/web/index.html @@ -1,3 +1,3 @@ 订单通知中心 -
正在连接订单通知中心…
+
正在连接订单通知中心…
diff --git a/web/modules/account/view.js b/web/modules/account/view.js new file mode 100644 index 0000000..d5a31b5 --- /dev/null +++ b/web/modules/account/view.js @@ -0,0 +1,46 @@ +'use strict'; +window.AccountViews=(()=>{ + let api,esc,formatDate,notify,user,onPasswordChanged; + const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'}; + function configure(options){({api,esc,formatDate,notify,user,onPasswordChanged}=options);} + function passwordField(id,label,existing=false){return `
`;} + function bindPasswordForm(form,{route,current,newId,confirmId,isActive,onSuccess}){ + const field=id=>form.querySelector('#'+id),error=form.querySelector('[role="alert"]'); + form.onsubmit=async event=>{ + event.preventDefault();error.textContent=''; + const body={currentPassword:field(current).value,newPassword:field(newId).value,confirmPassword:field(confirmId).value}; + if(body.newPassword!==body.confirmPassword){error.textContent='两次输入的新密码不一致。';return;} + const button=event.submitter;button.disabled=true; + try{ + const result=await api(route,body);form.reset(); + if(result.requiresLogin||isActive())await onSuccess(result); + }catch(cause){if(isActive()&&form.isConnected)error.textContent=cause.message;} + finally{if(button.isConnected)button.disabled=false;} + }; + } + async function account(container,isActive=()=>true){ + if(!isActive())return; + const actorId=user.id; + container.innerHTML=`

修改密码

当前账号:${esc(user.username)}${roles[user.role]}
${passwordField('account-current','当前密码',true)}${passwordField('account-new','新密码')}${passwordField('account-confirm','确认新密码')}
新密码需为12–128位,且不能与原密码相同。保存后,所有设备上的此账号都需重新登录。
`; + bindPasswordForm(container.querySelector('#account-password-form'),{route:'/account/password',current:'account-current',newId:'account-new',confirmId:'account-confirm',isActive,onSuccess:async result=>{if(await onPasswordChanged(actorId)===false)return;notify(result.cleanupPending?'密码已修改,请重新登录;仍有登录窗口待关闭。':'密码已修改,请使用新密码重新登录。',result.cleanupPending?'warning':'success');}}); + } + async function users(container,isActive=()=>true){ + const data=await api('/users');if(!isActive())return; + container.innerHTML=`

团队账号

${data.users.map(member=>``).join('')}
账号角色创建时间操作
${esc(member.username)}${roles[member.role]}${formatDate(member.createdAt)}${member.id===user.id?'修改我的密码':``}

添加同事

英文、数字、点、下划线或短横线
${passwordField('new-password','初始密码')}
管理员管理配置和账号;操作员处理异常;只读成员查看和下载。
`; + const create=container.querySelector('#user-form'); + create.onsubmit=async event=>{ + event.preventDefault();const button=event.submitter;button.disabled=true;const error=create.querySelector('[role="alert"]');error.textContent=''; + try{await api('/users',{username:create.querySelector('#new-username').value,password:create.querySelector('#new-password').value,role:create.querySelector('#new-role').value});create.reset();if(isActive()){await users(container,isActive);notify('账号已创建。');}} + catch(cause){if(isActive()&&create.isConnected)error.textContent=cause.message;} + finally{if(button.isConnected)button.disabled=false;} + }; + container.querySelectorAll('[data-reset-user]').forEach(button=>button.onclick=()=>{ + const member=data.users.find(item=>item.id===button.dataset.resetUser),editor=container.querySelector('#password-reset-editor'); + editor.innerHTML=`

重置 ${esc(member.username)} 的密码

${passwordField('reset-current','管理员当前密码',true)}${passwordField('reset-new','成员新密码')}${passwordField('reset-confirm','确认成员新密码')}
保存后,该成员的所有旧登录都会失效。请将新密码告知该成员。
`; + editor.querySelector('#cancel-reset').onclick=()=>editor.replaceChildren(); + bindPasswordForm(editor.querySelector('#password-reset-form'),{route:'/users/'+encodeURIComponent(member.id)+'/password',current:'reset-current',newId:'reset-new',confirmId:'reset-confirm',isActive,onSuccess:result=>{editor.replaceChildren();notify(result.cleanupPending?'成员密码已重置,仍有登录窗口待关闭。':'成员密码已重置,该账号需要重新登录。',result.cleanupPending?'warning':'success');}}); + editor.scrollIntoView({block:'nearest',behavior:'smooth'}); + }); + } + return {configure,account,users}; +})();