Add account password changes and administrator resets
This commit is contained in:
1 parent
23e28a7dcb
commit
060b36682d
14 files changed
+263
-26
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
@@ -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;}}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user