'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { BpmVault } = require('./bpm-vault.cjs'); const { loadPlaywright, browserOptions } = require('./runtime.cjs'); const { BpmListClient } = require('./bpm-list-client.cjs'); const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' }; const LOGIN_FORMS = { 'https://sso.skyworthdigital.com': { username:'#username', password:'#password', submit:'#kc-form-login button[type="submit"]', form:'#kc-form-login', actionPath:'/realms/skyworthdigital/login-actions/authenticate' } }; const TTL = 10 * 60 * 1000; const KEYS = new Set(['Tab','Enter','Backspace','Delete','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Home','End','Escape','Control+A']); const error = (message, status = 400) => Object.assign(new Error(message), { status }); const safe = cause => cause?.status ? cause : error('BPM 浏览器暂不可用,请重试。', 503); const object = (value, fields) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => fields.includes(key)); class BpmSessionManager { constructor({ stateDir, browserFactory, urls, allowedOrigins, probe, loginForms } = {}) { this.stateDir = path.resolve(stateDir); fs.mkdirSync(this.stateDir, { recursive: true }); if (urls!==undefined && !object(urls,['main'])) throw error('BPM 地址配置无效。'); this.urls = { ...DEFAULT_URLS, ...urls }; this.allowedOrigins = new Set(Object.values(DEFAULT_URLS).map(url => new URL(url).origin)); this.allowedOrigins.add('https://sso.skyworthdigital.com'); if (allowedOrigins) { // Injection exists only for local integration fixtures; it cannot widen production's external allowlist. for (const origin of allowedOrigins) { const parsed = new URL(origin); if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !['http:','https:'].includes(parsed.protocol) || parsed.origin !== origin) throw error('测试域名必须为本机地址。'); this.allowedOrigins.add(origin); } } for (const target of Object.values(this.urls)) if (!this.allowed(target)) throw error('BPM 地址不在允许范围内。',403); this.loginForms = { ...LOGIN_FORMS }; // Only local fixtures may register additional forms; callers cannot replace company forms. for (const [origin,form] of Object.entries(loginForms || {})) { const parsed = new URL(origin); if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !this.allowedOrigins.has(origin) || parsed.origin!==origin || !object(form,['username','password','submit']) || !['username','password'].every(key=>typeof form[key]==='string' && /^#[a-zA-Z_][\w-]*$/.test(form[key])) || (form.submit!==undefined && !/^#[a-zA-Z_][\w-]*$/.test(form.submit))) throw error('测试登录表单无效。'); this.loginForms[origin] = { ...form }; } 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; } 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 }); } accountMetadata(stored) { return stored ? {configured:true,username:stored.username,updatedAt:stored.updatedAt} : {configured:false,username:'',updatedAt:null}; } async migrateAccounts(connections) { await this.vault().migrateAccounts(connections.map(connection=>connection.id)); } async checkAccount(connection,principal,input) { return this.run(connection?.id,async()=>{this.authorize(connection,principal);if(!object(input,['username'])||typeof input.username!=='string'||!input.username.trim()||input.username.length>150)throw error('请输入有效的 BPM 账号。');return this.vault().accountAvailability(connection.id,input.username);}); } async account(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); return this.accountMetadata(await this.vault().read('account:'+connection.id)); }); } async saveAccount(connection,principal,credentials) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); if (!object(credentials,['username','password']) || typeof credentials.username!=='string' || !credentials.username.trim() || credentials.username.length>150 || typeof credentials.password!=='string' || !credentials.password || credentials.password.length>256) throw error('请输入有效的 BPM 账号和密码。'); const lease=this.sessions.get(connection.id); if (lease && lease.sessionId!==principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409); const stored={username:credentials.username.trim(),password:credentials.password,updatedAt:new Date().toISOString()}; const previous=await this.vault().read('account:'+connection.id); // A password rotation retains valid cookies. Only an actual account change revokes // authentication; first custody can reuse a user's already saved manual login. await this.vault().write('account:'+connection.id,stored); if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) { try{await this.vault().remove(connection.id);await this.closeLease(connection.id);} catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;} } return this.accountMetadata(stored); }); } async clearAccount(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id); return this.accountMetadata(null); }); } async fillSavedAccount(lease) { const stored=await this.vault().read('account:'+lease.id); if (!stored) return {filled:false,message:'请先保存托管账号。'}; const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin]; if (!form || lease.blocked) return {filled:false,message:'请打开支持的 BPM 登录页面。'}; try { await Promise.all([lease.page.locator(form.username).waitFor({state:'visible',timeout:1500}),lease.page.locator(form.password).waitFor({state:'visible',timeout:1500})]); // Validate and set both values in one browser task: a navigation or DOM replacement // between separate locator.fill calls must never redirect a secret to another field. const filled=await lease.page.evaluate(({origin,form,username,password})=>{ if (location.origin!==origin || window!==window.top) return false; const user=document.querySelector(form.username), secret=document.querySelector(form.password); const usable=(node,type)=>node instanceof HTMLInputElement && node.type===type && !node.disabled && !node.readOnly && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none'; if (!usable(user,'text') || !usable(secret,'password') || user===secret) return false; const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; set.call(user,username);set.call(secret,password); for (const node of [user,secret]) { node.dispatchEvent(new Event('input',{bubbles:true})); node.dispatchEvent(new Event('change',{bubbles:true})); } return true; },{origin,form,username:stored.username,password:stored.password}); return {filled,message:filled?'已填入托管账号,请完成登录。':'请打开支持的 BPM 登录表单。'}; } catch { return {filled:false,message:'请等待登录表单显示后重试。'}; } } async fillAccount(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); }); } async automaticSubmit(lease,stored,submit=false) { const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin]; if (!form?.submit || lease.blocked) return false; return lease.page.evaluate(({origin,form,stored,submit})=>{ if (location.origin!==origin || window!==window.top) return false; const visible=node=>!!node && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none'; const user=document.querySelector(form.username),secret=document.querySelector(form.password),button=document.querySelector(form.submit); if (!(user instanceof HTMLInputElement) || user.type!=='text' || !visible(user) || user.disabled || user.readOnly || !(secret instanceof HTMLInputElement) || secret.type!=='password' || !visible(secret) || secret.disabled || secret.readOnly || !visible(button) || button.disabled || button.type!=='submit') return false; const login=user.form; if (!login || secret.form!==login || button.form!==login || login.method.toLowerCase()!=='post' || (form.form && !login.matches(form.form))) return false; if ((button.getAttribute('formmethod') || login.method).toLowerCase()!=='post' || !['','_self'].includes(button.getAttribute('formtarget') || login.target)) return false; const action=new URL(button.getAttribute('formaction') || login.action,location.href); if (action.origin!==origin || (form.actionPath && action.pathname!==form.actionPath)) return false; // Any additional visible field or challenge requires the user's intervention. const challenge=/captcha|recaptcha|hcaptcha|turnstile|otp|one.?time|totp|verification|verify.?code/i; if (Array.from(document.querySelectorAll('input,iframe,img,[id],[class]')).some(node=>visible(node) && challenge.test([node.id,node.className,node.getAttribute('name'),node.getAttribute('autocomplete'),node.getAttribute('src'),node.getAttribute('title')].join(' ')))) return false; if (Array.from(login.elements).some(node=>visible(node) && node!==user && node!==secret && !['submit','button','hidden','reset'].includes(node.type))) return false; if (submit) { const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; set.call(user,stored.username);set.call(secret,stored.password); button.click(); } return true; },{origin,form,stored:{username:stored.username,password:stored.password},submit}).catch(()=>false); } async persistLease(lease) { await this.captureSessions(lease); const storageState=await lease.context.storageState({indexedDB:true}); await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage}); } canPersistVerified(result) { return result.status==='connected' && result.checks.portal.ok; } async ensure(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409); const lease=await this.create(connection,principal); try { let result=await this.verify(lease); this.authorize(connection,principal); if (this.canPersistVerified(result)) await this.persistLease(lease); if (result.status==='connected') return result; // Network failures and a healthy portal never justify submitting credentials again. if (result.status!=='login_required' || result.checks.portal.message!=='请在此入口完成登录。' || lease.blocked) return result; const stored=await this.vault().read('account:'+connection.id); if (!stored) return result; const manual=message=>{ if (!result.checks.portal.ok) result.checks.portal.message=message; return result; }; if (Date.parse(stored.nextAttemptAt)>Date.now()) return manual('自动登录暂缓,请稍后重试或更新托管账号。'); await this.readOnlyGoto(lease,this.urls.main); if (lease.blocked || !this.allowed(lease.page.url())) return manual('请人工检查 BPM 登录页面。'); if (!await this.automaticSubmit(lease,stored)) return manual('需要人工完成验证码或登录验证。'); // Persist before a request to avoid repeated retries after a crash or failed password. await this.vault().write('account:'+connection.id,{...stored,nextAttemptAt:new Date(Date.now()+15*60*1000).toISOString()}); if (!await this.automaticSubmit(lease,stored,true)) return manual('需要人工完成登录验证。'); await this.settleNavigation(lease); result=await this.verify(lease);this.authorize(connection,principal); if (this.canPersistVerified(result)) { await this.persistLease(lease);delete stored.nextAttemptAt;await this.vault().write('account:'+connection.id,stored); } else if (!result.checks.portal.ok) result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。'; return result; } finally { await this.closeLease(connection.id); } }); } async scanArrivals(connection,principal) { const query=()=>this.run(connection?.id,async()=>{ this.authorize(connection,principal); if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后扫描。',409); const saved=await this.vault().read(connection.id); const rows=await (this.listClient ||= new BpmListClient()).scan(saved?.storageState); this.authorize(connection,principal);return rows; }); try{return await query();}catch(cause){if(cause.status!==401)throw cause;} // Renewal takes the same per-connection lock, so it must run after query releases it. const renewed=await this.ensure(connection,principal); if(renewed.status!=='connected')throw error(renewed.checks?.portal?.message||'请在 BPM 连接中完成登录。',401); return query(); } 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.stopped) throw error('BPM 服务正在关闭。',503); if (connection.status === 'disabled' || this.disabled.has(connection.id)) throw error('此 BPM 连接已停用。',409); } run(id, work) { const before = this.operations.get(id) || Promise.resolve(); const operation = before.catch(()=>{}).then(work).catch(cause=>{ throw safe(cause); }); this.operations.set(id, operation); operation.finally(()=>{ if (this.operations.get(id) === operation) this.operations.delete(id); }).catch(()=>{}); return operation; } touch(lease) { lease.expiresAt = Date.now() + TTL; clearTimeout(lease.timer); lease.timer = setTimeout(()=>this.run(lease.id, async()=>{ if (lease.expiresAt <= Date.now()) await this.closeLease(lease.id); }).catch(()=>{}), TTL + 10); lease.timer.unref?.(); } async getLease(id, principal, touch = false, closing = false) { const lease = this.sessions.get(id); if (!lease) throw error('登录窗口已关闭,请重新打开。',410); this.authorize(lease.connection,principal); if (lease.sessionId !== principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409); if (lease.expiresAt <= Date.now()) { await this.closeLease(id); throw error('登录窗口已过期,请重新打开。',410); } if (!closing && (lease.blocked || !this.allowed(lease.page.url()))) throw error('已阻止离开允许的 BPM 域名,请重新打开登录窗口。',403); if (touch) this.touch(lease); return lease; } async browser() { if (this.stopped) throw error('BPM 服务正在关闭。',503); if (!this.browserPromise) this.browserPromise = Promise.resolve().then(()=>this.browserFactory()).catch(cause=>{ this.browserPromise=null; throw cause; }); return this.browserPromise; } async create(connection, principal) { this.authorize(connection,principal); if (this.sessions.size >= 3) throw error('同时登录窗口已达上限,请先关闭其他窗口。',429); const lease = { id:connection.id, connection:{...connection}, sessionId:principal.sessionId, context:null, page:null, blocked:false, sessionStorage:{} }; this.sessions.set(connection.id,lease); this.touch(lease); try { const stored = await this.vault().read(connection.id); lease.sessionStorage = stored?.sessionStorage || {}; const browser = await this.browser(); this.authorize(connection,principal); lease.context = await browser.newContext({ viewport:{width:1280,height:800}, acceptDownloads:false, serviceWorkers:'block', permissions:[], storageState:stored?.storageState }); await lease.context.route('**/*', async route => { try { // A popup is never a remote-control surface. Block its first navigation, // before even an allowed host can redirect it elsewhere. if (route.request().isNavigationRequest() && route.request().frame().page()!==lease.page) return await route.abort('blockedbyclient'); if (this.allowed(route.request().url())) { // route.continue follows redirects without re-entering the route handler. // Inspect each redirect before Chromium receives it, including resource redirects. const response=await route.fetch({maxRedirects:0,timeout:25000}); const location=response.headers().location; if (location && response.status()>=300 && response.status()<400 && !this.allowed(new URL(location,route.request().url()).href)) { if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked=true; return await route.abort('blockedbyclient'); } if (/attachment/i.test(response.headers()['content-disposition']||'')) return await route.abort('blockedbyclient'); // Await inside this try: closing a context can dispose the fetched response // before fulfill finishes. Returning its promise bypasses this catch. return await route.fulfill({response}); } if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked = true; await route.abort('blockedbyclient'); } catch { await route.abort('failed').catch(()=>{}); } }); if (lease.context.routeWebSocket) await lease.context.routeWebSocket(/.*/, socket => { const url=socket.url().replace(/^ws:/,'http:').replace(/^wss:/,'https:'); if (this.allowed(url)) socket.connectToServer(); else socket.close(); }); await lease.context.addInitScript(({ sessions }) => { try { if (sessionStorage.length===0) for (const [key,value] of Object.entries(sessions[location.origin] || {})) sessionStorage.setItem(key,value); } catch {} // Native file pickers are not part of remote login and must never reach the service desktop. const disable = () => document.querySelectorAll('input[type=file]').forEach(input=>{ input.disabled=true; }); new MutationObserver(disable).observe(document,{childList:true,subtree:true}); document.addEventListener('click', event => { if (event.target.closest?.('input[type=file],a[download]')) { event.preventDefault(); event.stopImmediatePropagation(); } },true); }, { sessions:lease.sessionStorage }); lease.page = await lease.context.newPage(); // Playwright routes omit redirected requests. A private Chromium request-stage // guard sees every hop before any network access, including redirect chains. lease.network = await lease.context.newCDPSession(lease.page); lease.mainFrameId=(await lease.network.send('Page.getFrameTree')).frameTree.frame.id; // Raw mouse/keyboard input returns before a form-triggered navigation commits. // Track main-frame navigation independently so verification never races it. const started=event=>{ if (event.frameId!==lease.mainFrameId || lease.pendingNavigation) return; lease.pendingNavigation=new Promise(resolve=>{lease.finishNavigation=resolve;}); }; lease.network.on('Page.frameRequestedNavigation',started); lease.network.on('Page.frameStartedLoading',started); const finished=event=>{ if (event.frameId!==lease.mainFrameId) return; lease.finishNavigation?.(); lease.pendingNavigation=null; lease.finishNavigation=null; }; lease.network.on('Page.frameStoppedLoading',finished); // Portal images/widgets can stall after its document is ready. Login // verification needs the committed document, not every subresource. lease.network.on('Page.lifecycleEvent',event=>{if(event.name==='DOMContentLoaded')finished(event);}); await lease.network.send('Page.enable'); await lease.network.send('Page.setLifecycleEventsEnabled',{enabled:true}); lease.network.on('Fetch.requestPaused', async event => { try { if (this.allowed(event.request.url)) await lease.network.send('Fetch.continueRequest',{requestId:event.requestId}); else { if (event.resourceType==='Document' && event.frameId===lease.mainFrameId) lease.blocked=true; await lease.network.send('Fetch.failRequest',{requestId:event.requestId,errorReason:'BlockedByClient'}); } } catch {} }); await lease.network.send('Fetch.enable',{patterns:[{urlPattern:'*',requestStage:'Request'}]}); lease.context.on('page', page=>{ if (page !== lease.page) page.close().catch(()=>{}); }); lease.page.on('download', download=>download.cancel().catch(()=>{})); lease.page.on('dialog', dialog=>dialog.dismiss().catch(()=>{})); await lease.page.goto(this.urls.main,{waitUntil:'domcontentloaded',timeout:30000}); this.authorize(connection,principal); if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403); await this.fillSavedAccount(lease); return lease; } catch (cause) { await this.closeLease(connection.id); throw safe(cause); } } async open(connection, principal) { 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); return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host }; }); } async frame(id,principal) { return this.run(id,async()=>{ const lease=await this.getLease(id,principal); return lease.page.screenshot({type:'jpeg',quality:75,caret:'initial',timeout:10000}); }); } async input(id,principal,action) { return this.run(id,async()=>{ if (!object(action,['type','x','y','text','key','deltaX','deltaY'])) throw error('输入操作无效。'); const type=action.type; if (type==='click') { if (!Number.isFinite(action.x)||!Number.isFinite(action.y)||action.x<0||action.x>=1280||action.y<0||action.y>=800) throw error('点击位置无效。'); } else if (type==='text') { if (typeof action.text!=='string'||action.text.length>2000) throw error('输入文字过长或无效。'); } else if (type==='key') { if (!KEYS.has(action.key)) throw error('不支持此按键。'); } else if (type==='scroll') { if (![action.deltaX,action.deltaY].every(value=>Number.isFinite(value)&&Math.abs(value)<=10000)) throw error('滚动距离无效。'); } else throw error('输入操作无效。'); const lease=await this.getLease(id,principal,true); if (type==='click') await lease.page.mouse.click(action.x,action.y); if (type==='text') await lease.page.keyboard.insertText(action.text); if (type==='key') await lease.page.keyboard.press(action.key); if (type==='scroll') await lease.page.mouse.wheel(action.deltaX,action.deltaY); return {ok:true}; }); } async navigate(id,principal,action) { return this.run(id,async()=>{ if (!object(action,['target']) || !['main','reload','back'].includes(action.target)) throw error('导航目标无效。'); const lease=await this.getLease(id,principal,true), options={waitUntil:'domcontentloaded',timeout:30000}; if (action.target==='reload') await lease.page.reload(options); else if (action.target==='back') await lease.page.goBack(options); else await lease.page.goto(this.urls[action.target],options); if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403); await this.fillSavedAccount(lease); return {ok:true,host:new URL(lease.page.url()).host}; }); } async defaultProbe(page) { // A visible company SSO form is an explicit login state. The authenticated // portal renders its user menu asynchronously after DOMContentLoaded. if(new URL(page.url()).origin==='https://sso.skyworthdigital.com' && await page.locator('#kc-form-login').isVisible().catch(()=>false))return {ok:false}; const marker=page.locator('a.yz-btn-signinuser .x-btn-inner').first(); await marker.waitFor({state:'visible',timeout:15000}).catch(()=>{}); if (!await marker.isVisible().catch(()=>false)) return {ok:false}; const identity=(await marker.innerText()).trim(); return {ok:!!identity && !/^(登录|请登录|未登录|sign\s*in|login)$/i.test(identity),identity}; } async captureSessions(lease) { for (const frame of lease.page.frames()) { if (!this.allowed(frame.url())) continue; const item=await frame.evaluate(()=>({origin:location.origin,values:Object.fromEntries(Object.entries(sessionStorage))})).catch(()=>null); if (item) lease.sessionStorage[item.origin]=item.values; } } async settleNavigation(lease) { // A protocol round trip lets an input-triggered navigation notification arrive; // the wait itself follows lifecycle events, with a deadline rather than a sleep. await lease.network.send('Page.getFrameTree'); const pending=lease.pendingNavigation; if (pending) { let timeout; try { await Promise.race([pending,new Promise((_,reject)=>{timeout=setTimeout(()=>reject(error('BPM 页面仍在加载,请稍后重试。',503)),15000);})]); } finally { clearTimeout(timeout); } } await lease.page.waitForLoadState('domcontentloaded',{timeout:15000}); } async readOnlyGoto(lease,url) { await this.settleNavigation(lease); for (let attempt=0;attempt<2;attempt++) { try { return await lease.page.goto(url,{waitUntil:'domcontentloaded',timeout:25000}); } catch (cause) { // Retry only our read-only verification GET, never the user's login action. if (attempt || lease.blocked || !/interrupted by another navigation|ERR_ABORTED/i.test(cause.message||'')) throw cause; await this.settleNavigation(lease); } } } async verify(lease) { const checkedAt=new Date().toISOString(); try { await this.settleNavigation(lease);await this.captureSessions(lease); lease.blocked=false; const response=await this.readOnlyGoto(lease,this.urls.main); if (lease.blocked || !this.allowed(lease.page.url())) throw error('域名被阻止。',403); if (response && response.status()>=400) throw error('BPM 暂时无法连接。',503); const result=await this.probe(lease.page,'portal'); const ok=result?.ok===true && typeof result.identity==='string' && !!result.identity.trim(); await this.captureSessions(lease); return {status:ok?'connected':'login_required',identity:ok?result.identity.trim().slice(0,150):'',checkedAt,checks:{portal:{ok,message:ok?'已验证登录账号。':'请在此入口完成登录。'}}}; } catch { return {status:'error',identity:'',checkedAt,checks:{portal:{ok:false,message:lease.blocked?'已阻止离开允许的 BPM 域名。':'暂时无法验证此入口。'}}}; } } async save(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); const result=await this.verify(lease); this.authorize(connection,principal); // Failed verification never replaces a previously working credential snapshot. if (this.canPersistVerified(result)) await this.persistLease(lease); return result; }); } async check(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const transient=!this.sessions.has(connection.id); const lease=transient ? await this.create(connection,principal) : await this.getLease(connection.id,principal,true); try { const result=await this.verify(lease); this.authorize(connection,principal); if(this.canPersistVerified(result))await this.persistLease(lease); return result; } finally { if (transient) await this.closeLease(connection.id); } }); } async closeLease(id) { const lease=this.sessions.get(id); if (!lease) return; clearTimeout(lease.timer); this.sessions.delete(id); await lease.context?.close().catch(()=>{}); } 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 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; await Promise.allSettled([...this.operations.values()]); await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id))); if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{}); this._vault?.destroy(); } } module.exports={BpmSessionManager};