@things-factory/integration-base 10.1.117 → 10.1.118
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-server/engine/connector/headless-connector.d.ts +1 -0
- package/dist-server/engine/connector/headless-connector.js +5 -1
- package/dist-server/engine/connector/headless-connector.js.map +1 -1
- package/dist-server/engine/index.d.ts +2 -0
- package/dist-server/engine/index.js +5 -0
- package/dist-server/engine/index.js.map +1 -1
- package/dist-server/engine/integration-runtime.d.ts +47 -0
- package/dist-server/engine/integration-runtime.js +78 -0
- package/dist-server/engine/integration-runtime.js.map +1 -0
- package/dist-server/engine/resource-pool/headless-pool.js +6 -1
- package/dist-server/engine/resource-pool/headless-pool.js.map +1 -1
- package/dist-server/engine/scenario-engine.js +4 -0
- package/dist-server/engine/scenario-engine.js.map +1 -1
- package/dist-server/index.d.ts +1 -0
- package/dist-server/index.js +8 -0
- package/dist-server/index.js.map +1 -1
- package/dist-server/routers/scenario-schedule-run.d.ts +2 -1
- package/dist-server/routers/scenario-schedule-run.js +9 -0
- package/dist-server/routers/scenario-schedule-run.js.map +1 -1
- package/dist-server/service/connection/connection.js +3 -0
- package/dist-server/service/connection/connection.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
|
@@ -14,6 +14,7 @@ export declare class HeadlessConnector implements Connector {
|
|
|
14
14
|
inheritanceMode: "isolate";
|
|
15
15
|
ready(connectionConfigs: any): Promise<void>;
|
|
16
16
|
connect(connection: any): Promise<void>;
|
|
17
|
+
protected isCookieValid(cookies: any[]): boolean;
|
|
17
18
|
setupPage(page: any, uri: any, timeout: any): Promise<void>;
|
|
18
19
|
applyCookiesAndVerifySession(page: any, cookies: any, loginInfo: any): Promise<void>;
|
|
19
20
|
performLogin(page: any, uri: any, loginInfo: any): Promise<void>;
|
|
@@ -174,8 +174,9 @@ class HeadlessConnector {
|
|
|
174
174
|
connection_manager_1.ConnectionManager.logger.info('User is already logged in, skipping login process.');
|
|
175
175
|
return page;
|
|
176
176
|
}
|
|
177
|
-
if (cookies && isCookieValid(cookies)) {
|
|
177
|
+
if (cookies && this.isCookieValid(cookies)) {
|
|
178
178
|
await this.applyCookiesAndVerifySession(page, cookies, loginInfo);
|
|
179
|
+
connection.cookies = await page.cookies();
|
|
179
180
|
return page;
|
|
180
181
|
}
|
|
181
182
|
await this.performLogin(page, uri, loginInfo);
|
|
@@ -385,6 +386,9 @@ class HeadlessConnector {
|
|
|
385
386
|
});
|
|
386
387
|
connection_manager_1.ConnectionManager.logger.info(`headless-connector connection(${connection.name}:${connection.endpoint}) is connected`);
|
|
387
388
|
}
|
|
389
|
+
isCookieValid(cookies) {
|
|
390
|
+
return isCookieValid(cookies);
|
|
391
|
+
}
|
|
388
392
|
async setupPage(page, uri, timeout) {
|
|
389
393
|
await page.setRequestInterception(true);
|
|
390
394
|
await page.setBypassCSP(true);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headless-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/headless-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAEzD,kEAA8E;AAG9E;;;;;;;;;;EAUE;AAEF,MAAa,iBAAiB;IAA9B;QACE;;;;WAIG;QACH,qBAAgB,GAAG,IAAI,CAAA;QAEvB;;;;WAIG;QACH,oBAAe,GAAG,SAAkB,CAAA;IAytBtC,CAAC;IAvtBC,KAAK,CAAC,KAAK,CAAC,iBAAiB;QAC3B,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QACjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAA;IAC3E,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAAU;QACtB,MAAM,EACJ,QAAQ,EAAE,GAAG,GAAG,GAAG,EACnB,MAAM,EAAE,EACN,QAAQ,GA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IAAI,WAAW;QACb,OAAO,iDAAiD,CAAA;IAC1D,CAAC;IAED,IAAI,IAAI;QACN,OAAO,0CAA0C,CAAA;IACnD,CAAC;CACF;AAtuBD,8CAsuBC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,oBAAoB,EAAE,IAAI,iBAAiB,EAAE,CAAC,CAAA;AAElF,SAAS,aAAa,CAAC,OAAc;IACnC,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,0BAA0B;IACxD,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAW,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,CAAA;AAC9E,CAAC","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { getHeadlessPool, getPoolStats } from '../resource-pool/headless-pool'\nimport { Browser, Page } from 'puppeteer'\n\n/*\n Functionality of the headless-connector:\n - Provides a mechanism to acquire an active session page.\n - Performs login when necessary to obtain valid cookies.\n - Applies these cookies to the page for session management.\n - Pages are acquired from the `headlessPool`, which manages browser instances.\n - During the login process, pages from the pool are used for actions like form filling and navigation.\n - Valid cookies are saved after login and reused for subsequent page acquisitions.\n - Users must explicitly release the page after use through the `releasePage` method.\n - Released pages are returned to the `headlessPool` for reuse.\n*/\n\nexport class HeadlessConnector implements Connector {\n /**\n * 외부 사이트 로그인 세션 보유 — 같은 connection name 의 동시 acquireSessionPage\n * 호출이 같은 외부 계정 세션을 서로 invalidate 하지 않도록 ConnectionManager 가\n * mutex 직렬화. 상속 connector (allbaro, kiscon 등) 자동 적용.\n */\n sessionExclusive = true\n\n /**\n * 자식 도메인이 부모의 Connection 정의를 inherit 할 때 자식별 새 인스턴스 생성.\n * cookies/세션·자격증명 격리. 헤드리스 사이트 connector 는 외부 자격증명이\n * 자식 (테넌트) 마다 다를 수 있으므로 ISOLATE 가 자연 default.\n */\n inheritanceMode = 'isolate' as const\n\n async ready(connectionConfigs) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n ConnectionManager.logger.info('headless-connector connections are ready')\n }\n\n async connect(connection) {\n const {\n endpoint: uri = '1',\n params: {\n username = '',\n password = '',\n loginPagePath = '/login',\n loginApiUrl = null,\n usernameSelector = '#username',\n passwordSelector = '#password',\n submitSelector = '#submit',\n successSelector = null,\n shadowDomSelectors = '', // Comma separated shadow DOM selectors\n timeout = 15000, // Default timeout for operations\n retries = 3, // Default number of retries for login or page actions\n // 쿠키 캐시 재사용 건너뛰고 매 acquireSessionPage 마다 로그인하도록 강제.\n // 서버 세션 만료가 잦거나 검증이 비싼 사이트(예: 올바로) 에서 사용.\n forceLogin = false\n } = {}\n } = connection\n\n const loginInfo = {\n loginRequired: Boolean(username), // Determine if login is required\n forceLogin: Boolean(forceLogin),\n username,\n password,\n loginPagePath,\n loginApiUrl,\n timeout,\n retries,\n loginSelectors: {\n usernameSelector,\n passwordSelector,\n submitSelector,\n successSelector,\n shadowDomSelectors: shadowDomSelectors\n .split(',')\n .map(selector => selector.trim())\n .filter(Boolean)\n }\n }\n\n async function acquireBrowser() {\n try {\n const pool = getHeadlessPool()\n \n // Pool 상태 모니터링 (디버깅용)\n try {\n const stats = getPoolStats()\n ConnectionManager.logger.debug(`Pool stats before acquire - borrowed: ${stats.borrowed}, available: ${stats.available}, pending: ${stats.pending}`)\n } catch (statsError) {\n ConnectionManager.logger.warn('Failed to get pool stats:', statsError)\n }\n \n const browser = await pool.acquire()\n ConnectionManager.logger.info('Browser acquired successfully from pool')\n return browser\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire browser from pool:', error)\n \n // 풀 상태 로깅으로 디버깅 도움\n try {\n const stats = getPoolStats()\n ConnectionManager.logger.error(`Pool stats during acquire error - borrowed: ${stats.borrowed}, available: ${stats.available}, pending: ${stats.pending}, max: ${stats.max}`)\n } catch (statsError) {\n ConnectionManager.logger.error('Failed to get pool stats during error:', statsError)\n }\n \n throw error\n }\n }\n\n async function releaseBrowser(browser: Browser) {\n if (!browser) {\n ConnectionManager.logger.warn('Attempted to release null/undefined browser')\n return\n }\n\n try {\n // 브라우저가 아직 연결되어 있는지 확인\n if (!browser.isConnected()) {\n ConnectionManager.logger.warn('Attempted to release disconnected browser')\n return\n }\n\n // Pool 상태 모니터링 (릴리즈 전)\n try {\n const statsBefore = getPoolStats()\n ConnectionManager.logger.debug(`Pool stats before release - borrowed: ${statsBefore.borrowed}, available: ${statsBefore.available}`)\n } catch (statsError) {\n ConnectionManager.logger.warn('Failed to get pool stats before release:', statsError)\n }\n\n const pool = getHeadlessPool()\n await pool.release(browser)\n ConnectionManager.logger.info('Browser successfully released to pool')\n \n // Pool 상태 모니터링 (릴리즈 후)\n try {\n const statsAfter = getPoolStats()\n ConnectionManager.logger.debug(`Pool stats after release - borrowed: ${statsAfter.borrowed}, available: ${statsAfter.available}`)\n } catch (statsError) {\n ConnectionManager.logger.warn('Failed to get pool stats after release:', statsError)\n }\n } catch (error) {\n ConnectionManager.logger.error('Failed to release browser to pool:', error)\n \n // 에러 발생시 풀 상태 로깅\n try {\n const stats = getPoolStats()\n ConnectionManager.logger.error(`Pool stats during release error - borrowed: ${stats.borrowed}, available: ${stats.available}, pending: ${stats.pending}`)\n } catch (statsError) {\n ConnectionManager.logger.error('Failed to get pool stats during release error:', statsError)\n }\n \n // 풀 릴리즈가 실패한 경우 브라우저 강제 종료 시도\n try {\n if (browser && browser.isConnected()) {\n await browser.close()\n ConnectionManager.logger.warn('Forcibly closed browser due to pool release failure')\n }\n } catch (forceCloseError) {\n ConnectionManager.logger.error('Failed to force close browser after pool release failure:', forceCloseError)\n }\n }\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n endpoint: connection.endpoint,\n params: connection.params,\n acquireSessionPage: async () => {\n const browser = await acquireBrowser()\n let page\n let cookies = connection.cookies\n\n try {\n page = await browser.newPage()\n await this.setupPage(page, uri, timeout)\n\n if (loginInfo.loginRequired) {\n if (loginInfo.forceLogin) {\n // 매번 새로 로그인 — 쿠키·세션 재사용 검증 모두 건너뜀.\n // 세션이 서버측에서 자주 만료되는 사이트 용도.\n ConnectionManager.logger.info('forceLogin=true — skipping cookie reuse, performing fresh login')\n connection.cookies = undefined\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n } else {\n // 먼저 기본 페이지로 이동\n await page.goto(uri, { waitUntil: 'networkidle2', timeout })\n\n // 현재 세션의 Authorization 헤더 확인\n const headers = await page.evaluate(() => {\n return fetch(window.location.href, { method: 'GET' })\n .then(response => response.headers.get('Authorization'))\n .catch(() => null)\n })\n\n if (headers) {\n ConnectionManager.logger.info('User is already logged in, skipping login process.')\n return page\n }\n\n if (cookies && isCookieValid(cookies)) {\n await this.applyCookiesAndVerifySession(page, cookies, loginInfo)\n return page\n }\n\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n }\n } else {\n // 로그인이 필요하지 않은 경우에도 기본 페이지로 이동\n await page.goto(uri, { waitUntil: 'networkidle2', timeout })\n }\n\n return page\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire session page:', error)\n \n // CRITICAL: 에러 발생 시 확실한 리소스 정리\n if (page) {\n try {\n await page.close()\n ConnectionManager.logger.info('Page closed during acquireSessionPage error handling')\n } catch (closeError) {\n ConnectionManager.logger.error('Failed to close page during acquireSessionPage error:', closeError)\n }\n }\n \n try {\n await releaseBrowser(browser)\n ConnectionManager.logger.info('Browser released during acquireSessionPage error handling')\n } catch (releaseError) {\n ConnectionManager.logger.error('Failed to release browser during acquireSessionPage error:', releaseError)\n }\n \n throw error\n }\n },\n releasePage: async (page: Page) => {\n try {\n if (page && !page.isClosed()) {\n const browser = page.browser()\n \n // 페이지를 먼저 닫기\n try {\n await page.close()\n ConnectionManager.logger.info('Page closed successfully')\n } catch (closeError) {\n ConnectionManager.logger.error('Failed to close page:', closeError)\n }\n \n // 브라우저를 풀에 반환\n try {\n await releaseBrowser(browser)\n ConnectionManager.logger.info('Browser released successfully')\n } catch (releaseError) {\n ConnectionManager.logger.error('Failed to release browser:', releaseError)\n // 풀 릴리즈가 실패한 경우 브라우저 강제 종료 시도\n try {\n if (browser && browser.isConnected()) {\n await browser.close()\n ConnectionManager.logger.warn('Forcibly closed browser due to pool release failure')\n }\n } catch (forceCloseError) {\n ConnectionManager.logger.error('Failed to force close browser:', forceCloseError)\n }\n }\n }\n } catch (error) {\n ConnectionManager.logger.error('Critical error in releasePage:', error)\n }\n },\n // 세션 회복을 위한 재로그인 메서드\n reAuthenticateSession: async () => {\n ConnectionManager.logger.info(`Re-authenticating session for connection: ${connection.name}`)\n \n let browser = null\n let page = null\n\n try {\n browser = await acquireBrowser()\n page = await browser.newPage()\n await this.setupPage(page, uri, loginInfo.timeout)\n \n if (loginInfo.loginRequired) {\n await this.performLogin(page, uri, loginInfo)\n const newCookies = await page.cookies()\n connection.cookies = newCookies\n ConnectionManager.logger.info(`Session re-authenticated successfully for connection: ${connection.name}`)\n }\n \n // CRITICAL: 페이지와 함께 브라우저 정보도 반환하여 정확한 릴리즈 추적\n return {\n page,\n browser,\n requiresManualRelease: true // 수동 릴리즈 필요 표시\n }\n } catch (error) {\n ConnectionManager.logger.error(`Failed to re-authenticate session for connection: ${connection.name}`, error)\n \n // 에러 시 확실한 리소스 정리\n if (page) {\n try {\n if (!page.isClosed()) {\n await page.close()\n ConnectionManager.logger.info('Page closed during reauth error handling')\n }\n } catch (closeError) {\n ConnectionManager.logger.error('Failed to close page during reauth error:', closeError)\n }\n }\n \n if (browser) {\n try {\n await releaseBrowser(browser)\n ConnectionManager.logger.info('Browser released during reauth error handling')\n } catch (releaseError) {\n ConnectionManager.logger.error('Failed to release browser during reauth error:', releaseError)\n // 풀 릴리즈가 실패한 경우 브라우저 강제 종료 시도\n try {\n if (browser.isConnected()) {\n await browser.close()\n ConnectionManager.logger.warn('Forcibly closed browser during reauth error due to pool release failure')\n }\n } catch (forceCloseError) {\n ConnectionManager.logger.error('Failed to force close browser during reauth error:', forceCloseError)\n }\n }\n }\n \n throw error\n }\n },\n // 세션 유효성 검사\n validateSession: async (page: Page) => {\n try {\n if (!loginInfo.loginRequired) {\n return true\n }\n\n // 페이지가 닫혔거나 연결이 끊어진 경우\n if (!page || page.isClosed()) {\n ConnectionManager.logger.warn(`Page is closed or null for connection: ${connection.name}`)\n return false\n }\n\n // URL 기반 로그인 리디렉션 체크\n let currentUrl: string\n try {\n currentUrl = page.url()\n } catch (urlError) {\n ConnectionManager.logger.warn(`Cannot get page URL for connection: ${connection.name}`, urlError)\n return false\n }\n \n if (currentUrl.includes(loginInfo.loginPagePath) || \n currentUrl.includes('/login') || \n currentUrl.includes('/signin') || \n currentUrl.includes('/auth')) {\n ConnectionManager.logger.info(`Redirected to login page: ${currentUrl}`)\n return false\n }\n\n // 로그인 폼 요소 기반 체크\n const needsLogin = await page.evaluate(() => {\n try {\n // 로그인 페이지 특정 요소들이 있는지 확인\n const loginIndicators = ['#username', '#password', '.login-form', '[type=\"password\"]']\n return loginIndicators.some(selector => {\n const element = document.querySelector(selector) as HTMLElement\n return element && element.offsetParent !== null // 보이는 요소만 체크\n })\n } catch (evalError) {\n return true // 에러 시 안전하게 재로그인 필요로 간주\n }\n })\n\n // 추가 세션 검증: 간단한 API 호출로 인증 상태 확인\n try {\n const testResponse = await page.evaluate(async () => {\n try {\n const response = await fetch(window.location.origin, { \n method: 'HEAD',\n credentials: 'include'\n })\n return {\n status: response.status,\n ok: response.ok\n }\n } catch (fetchError) {\n return { status: 0, ok: false }\n }\n })\n \n // 인증이 필요한 엔드포인트에서 401/403 반환시 세션 무효\n if (testResponse.status === 401 || testResponse.status === 403) {\n ConnectionManager.logger.info(`Authentication failed with status ${testResponse.status} for connection: ${connection.name}`)\n return false\n }\n } catch (apiTestError) {\n ConnectionManager.logger.warn(`Session API test failed for connection: ${connection.name}`, apiTestError)\n // API 테스트 실패는 세션 무효로 간주하지 않음 (네트워크 문제일 수 있음)\n }\n\n return !needsLogin\n } catch (error) {\n ConnectionManager.logger.warn(`Session validation failed for connection: ${connection.name}`, error)\n return false\n }\n },\n acquireBrowser,\n releaseBrowser\n })\n\n ConnectionManager.logger.info(\n `headless-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async setupPage(page, uri, timeout) {\n await page.setRequestInterception(true)\n\n await page.setBypassCSP(true)\n\n await page.setUserAgent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Safari/537.36'\n )\n\n await page.evaluateOnNewDocument(() => {\n Object.defineProperty(navigator, 'webdriver', { get: () => false })\n })\n\n await page.setExtraHTTPHeaders({\n 'Upgrade-Insecure-Requests': '0',\n 'accept-language': 'en-US,en;q=0.9',\n referer: uri\n })\n\n await page.setDefaultNavigationTimeout(timeout)\n\n page.on('console', async msg => {\n const args = await Promise.all(msg.args().map(arg => arg.jsonValue().catch(() => undefined)))\n\n if (args.some(a => a !== undefined)) {\n ConnectionManager.logger.info(`[browser ${msg.type()}]`, ...args.filter(a => a !== undefined))\n } else {\n const text = msg.text()\n if (text) ConnectionManager.logger.info(`[browser ${msg.type()}]`, text)\n }\n })\n\n page.on('request', request => {\n if (request.isInterceptResolutionHandled()) {\n return\n }\n\n const resourceType = request.resourceType()\n\n // fetch(), XMLHttpRequest 등의 API 호출은 항상 허용\n if (resourceType === 'fetch' || resourceType === 'xhr') {\n request.continue()\n return\n }\n\n const headers = request.headers()\n if (headers['access-control-request-headers']) {\n const filteredHeaders = headers['access-control-request-headers']\n .split(',')\n .map(header => header.trim())\n .filter(header => header.toLowerCase() !== 'upgrade-insecure-requests')\n\n if (filteredHeaders.length > 0) {\n headers['access-control-request-headers'] = filteredHeaders.join(', ')\n } else {\n delete headers['access-control-request-headers']\n }\n }\n\n if (headers['upgrade-insecure-requests']) {\n delete headers['upgrade-insecure-requests']\n }\n\n // 이미지, 스타일시트, 폰트는 차단하되 API 요청은 허용\n if (['image', 'stylesheet', 'font'].includes(resourceType)) {\n request.abort()\n } else {\n request.continue()\n }\n })\n\n page.on('requestfailed', request => {\n try {\n // 정적 리소스(이미지·폰트·CSS 등) 의 실패는 로그인 흐름과 무관한 소음이므로 무시.\n // document / xhr / fetch 같은 의미있는 요청 실패만 출력.\n const type = request.resourceType()\n const NOISY_TYPES = new Set(['image', 'font', 'stylesheet', 'media', 'manifest', 'other'])\n if (NOISY_TYPES.has(type)) return\n\n // 일부 사이트의 정적 자원이 다른 type 으로 잡힐 수 있어 확장자 기반 보강 필터.\n const url = request.url()\n if (/\\.(png|jpe?g|gif|webp|svg|ico|woff2?|ttf|otf|eot|css|map)(\\?|$)/i.test(url)) return\n\n console.warn(\n `[headless] request failed (type=${type}): ${request.method()} ${url} — ${request.failure()?.errorText}`\n )\n } catch (error) {\n console.error('Error in requestfailed handler:', error)\n }\n })\n }\n\n async applyCookiesAndVerifySession(page, cookies, loginInfo) {\n await page.setCookie(...cookies)\n await page.reload({ waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n if (loginInfo.loginRequired && loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Session invalid, login required')\n }\n }\n }\n\n async performLogin(page, uri, loginInfo) {\n let lastError: Error | null = null\n for (let attempt = 1; attempt <= loginInfo.retries; attempt++) {\n try {\n await page.goto(`${uri}${loginInfo.loginPagePath}`, { waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n const usernameInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.usernameSelector\n )\n const passwordInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.passwordSelector\n )\n const submitButton = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.submitSelector\n )\n\n if (!usernameInput || !passwordInput || !submitButton) {\n throw new Error(\n `Failed to locate login form elements ` +\n `(username=${!!usernameInput}, password=${!!passwordInput}, submit=${!!submitButton}). ` +\n `Selectors: username='${loginInfo.loginSelectors.usernameSelector}', ` +\n `password='${loginInfo.loginSelectors.passwordSelector}', ` +\n `submit='${loginInfo.loginSelectors.submitSelector}'. ` +\n `사이트 폼 변경 가능성 — Connection params 의 *Selector 값을 실제 폼에 맞춰 덮어쓰세요.`\n )\n }\n\n await usernameInput.type(loginInfo.username)\n await passwordInput.type(loginInfo.password)\n\n var loginApiUrl =\n loginInfo.loginApiUrl ||\n (await page.evaluate(button => {\n const form = button.closest('form')\n return form ? form.action : null\n }, submitButton))\n\n if (loginApiUrl && !loginApiUrl.startsWith('http')) {\n loginApiUrl = `${uri}${loginApiUrl}`\n }\n\n if (!loginApiUrl) {\n throw new Error('❌ Unable to detect login API URL!')\n }\n\n console.log('✅ Detected login API URL:', loginApiUrl)\n\n const [response] = await Promise.all([\n page.waitForResponse(response => {\n const url = response.url()\n const method = response.request().method()\n\n return url === loginApiUrl && method === 'POST' && [200, 201, 204, 302, 304].includes(response.status())\n }),\n page.evaluate(button => button.click(), submitButton),\n page.waitForNavigation({ waitUntil: 'networkidle2', timeout: loginInfo.timeout }) // 로그인 후 리디렉션 감지\n ])\n\n if (response) {\n const status = response.status()\n if (status >= 200 && status < 400) {\n ConnectionManager.logger.info(`Login successful with status code: ${status}`)\n return\n } else if (status >= 400) {\n throw new Error(`Login failed with status code: ${status}`)\n }\n } else {\n throw new Error('No response received during login')\n }\n\n if (loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Login failed: Success selector not found')\n }\n }\n } catch (error: any) {\n lastError = error\n ConnectionManager.logger.warn(`Login attempt ${attempt} failed:`, error)\n\n try {\n await page.screenshot({ path: `logs/login-failure-attempt-${attempt}.png` })\n } catch (error) {\n ConnectionManager.logger.error('Failed to capture screenshot:', error)\n }\n\n if (attempt === loginInfo.retries) {\n throw new Error(\n `Login failed after ${loginInfo.retries} attempts — last cause: ${lastError?.message || lastError}`\n )\n }\n }\n }\n }\n\n async resolveShadowDom(page, shadowSelectors, targetSelector) {\n let context\n\n if (!shadowSelectors || shadowSelectors.length === 0) {\n // No Shadow DOM path; use document root as the context.\n // XPath 지원 — puppeteer 22+ 의 통합 선택자: `xpath/<expression>` prefix.\n // 셀렉터가 `//`, `(//`, `.//` 로 시작하면 xpath/ 로 감싸 page.$ 에 전달.\n if (typeof targetSelector === 'string' && /^\\s*(\\(|\\/\\/|\\.\\/\\/)/.test(targetSelector)) {\n return await page.$('xpath/' + targetSelector.trim())\n }\n context = page.mainFrame() // Puppeteer uses frames to represent document\n return context.$(targetSelector) // CSS selector — Search directly in the document root\n }\n\n context = page // Start with the page as the context\n for (const selector of shadowSelectors) {\n const shadowHost = await context.$(selector)\n if (!shadowHost) {\n throw new Error(`Shadow host not found: ${selector}`)\n }\n context = await page.evaluateHandle(host => host.shadowRoot, shadowHost)\n }\n return context.evaluateHandle((shadowRoot, selector) => shadowRoot.querySelector(selector), targetSelector)\n }\n\n async disconnect(connection) {\n try {\n // 연결 해제 전 리소스 정리 로그\n ConnectionManager.logger.info(`Starting disconnect process for connection: ${connection.name}`)\n \n // 풀 상태 확인 (정보성 로깅)\n try {\n const pool = getHeadlessPool()\n ConnectionManager.logger.info(`Pool status before disconnect - available resources exist: ${!!pool}`)\n } catch (poolError) {\n ConnectionManager.logger.warn(`Could not access pool during disconnect: ${poolError.message}`)\n }\n\n ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`headless-connector connection(${connection.name}) is disconnected`)\n } catch (error) {\n ConnectionManager.logger.error(`Error disconnecting headless-connector connection(${connection.name}):`, error)\n // Still try to remove the connection instance even if cleanup failed\n try {\n ConnectionManager.removeConnectionInstance(connection)\n } catch (removeError) {\n ConnectionManager.logger.error(`Failed to remove connection instance ${connection.name}:`, removeError)\n }\n }\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'username',\n label: 'username',\n useDomainAttribute: true\n },\n {\n type: 'secret',\n name: 'password',\n label: 'password',\n useDomainAttribute: true\n },\n {\n type: 'string',\n name: 'loginPagePath',\n label: 'login-page-path'\n },\n {\n type: 'string',\n name: 'loginApiUrl',\n label: 'login-api-url'\n },\n {\n type: 'string',\n name: 'usernameSelector',\n label: 'username-selector'\n },\n {\n type: 'string',\n name: 'passwordSelector',\n label: 'password-selector'\n },\n {\n type: 'string',\n name: 'submitSelector',\n label: 'submit-selector'\n },\n {\n type: 'string',\n name: 'successSelector',\n label: 'success-selector'\n },\n {\n type: 'string',\n name: 'shadowDomSelectors',\n label: 'shadow-dom-selectors'\n },\n {\n type: 'number',\n name: 'timeout',\n label: 'timeout',\n value: 15000\n },\n {\n type: 'number',\n name: 'retries',\n label: 'maximum-retries',\n value: 3\n }\n ]\n }\n\n get taskPrefixes() {\n return ['headless']\n }\n\n get description() {\n return 'Headless Pool Connector with login capabilities'\n }\n\n get help() {\n return 'integration/connector/headless-connector'\n }\n}\n\nConnectionManager.registerConnector('headless-connector', new HeadlessConnector())\n\nfunction isCookieValid(cookies: any[]): boolean {\n if (!cookies || cookies.length === 0) return false\n const now = Date.now() / 1000 // Current time in seconds\n return cookies.some((cookie: any) => cookie.expires && cookie.expires > now)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"headless-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/headless-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAEzD,kEAA8E;AAG9E;;;;;;;;;;EAUE;AAEF,MAAa,iBAAiB;IAA9B;QACE;;;;WAIG;QACH,qBAAgB,GAAG,IAAI,CAAA;QAEvB;;;;WAIG;QACH,oBAAe,GAAG,SAAkB,CAAA;IA8tBtC,CAAC;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ACtB,KAAK,EAAE,iBAAiB;aACzB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,iBAAiB;gBACvB,KAAK,EAAE,kBAAkB;aAC1B;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,oBAAoB;gBAC1B,KAAK,EAAE,sBAAsB;aAC9B;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,SAAS;gBAChB,KAAK,EAAE,KAAK;aACb;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,iBAAiB;gBACxB,KAAK,EAAE,CAAC;aACT;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,UAAU,CAAC,CAAA;IACrB,CAAC;IAED,IAAI,WAAW;QACb,OAAO,iDAAiD,CAAA;IAC1D,CAAC;IAED,IAAI,IAAI;QACN,OAAO,0CAA0C,CAAA;IACnD,CAAC;CACF;AA3uBD,8CA2uBC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,oBAAoB,EAAE,IAAI,iBAAiB,EAAE,CAAC,CAAA;AAElF,SAAS,aAAa,CAAC,OAAc;IACnC,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,0BAA0B;IACxD,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAW,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,CAAA;AAC9E,CAAC","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { getHeadlessPool, getPoolStats } from '../resource-pool/headless-pool'\nimport { Browser, Page } from 'puppeteer'\n\n/*\n Functionality of the headless-connector:\n - Provides a mechanism to acquire an active session page.\n - Performs login when necessary to obtain valid cookies.\n - Applies these cookies to the page for session management.\n - Pages are acquired from the `headlessPool`, which manages browser instances.\n - During the login process, pages from the pool are used for actions like form filling and navigation.\n - Valid cookies are saved after login and reused for subsequent page acquisitions.\n - Users must explicitly release the page after use through the `releasePage` method.\n - Released pages are returned to the `headlessPool` for reuse.\n*/\n\nexport class HeadlessConnector implements Connector {\n /**\n * 외부 사이트 로그인 세션 보유 — 같은 connection name 의 동시 acquireSessionPage\n * 호출이 같은 외부 계정 세션을 서로 invalidate 하지 않도록 ConnectionManager 가\n * mutex 직렬화. 상속 connector (allbaro, kiscon 등) 자동 적용.\n */\n sessionExclusive = true\n\n /**\n * 자식 도메인이 부모의 Connection 정의를 inherit 할 때 자식별 새 인스턴스 생성.\n * cookies/세션·자격증명 격리. 헤드리스 사이트 connector 는 외부 자격증명이\n * 자식 (테넌트) 마다 다를 수 있으므로 ISOLATE 가 자연 default.\n */\n inheritanceMode = 'isolate' as const\n\n async ready(connectionConfigs) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n ConnectionManager.logger.info('headless-connector connections are ready')\n }\n\n async connect(connection) {\n const {\n endpoint: uri = '1',\n params: {\n username = '',\n password = '',\n loginPagePath = '/login',\n loginApiUrl = null,\n usernameSelector = '#username',\n passwordSelector = '#password',\n submitSelector = '#submit',\n successSelector = null,\n shadowDomSelectors = '', // Comma separated shadow DOM selectors\n timeout = 15000, // Default timeout for operations\n retries = 3, // Default number of retries for login or page actions\n // 쿠키 캐시 재사용 건너뛰고 매 acquireSessionPage 마다 로그인하도록 강제.\n // 서버 세션 만료가 잦거나 검증이 비싼 사이트(예: 올바로) 에서 사용.\n forceLogin = false\n } = {}\n } = connection\n\n const loginInfo = {\n loginRequired: Boolean(username), // Determine if login is required\n forceLogin: Boolean(forceLogin),\n username,\n password,\n loginPagePath,\n loginApiUrl,\n timeout,\n retries,\n loginSelectors: {\n usernameSelector,\n passwordSelector,\n submitSelector,\n successSelector,\n shadowDomSelectors: shadowDomSelectors\n .split(',')\n .map(selector => selector.trim())\n .filter(Boolean)\n }\n }\n\n async function acquireBrowser() {\n try {\n const pool = getHeadlessPool()\n \n // Pool 상태 모니터링 (디버깅용)\n try {\n const stats = getPoolStats()\n ConnectionManager.logger.debug(`Pool stats before acquire - borrowed: ${stats.borrowed}, available: ${stats.available}, pending: ${stats.pending}`)\n } catch (statsError) {\n ConnectionManager.logger.warn('Failed to get pool stats:', statsError)\n }\n \n const browser = await pool.acquire()\n ConnectionManager.logger.info('Browser acquired successfully from pool')\n return browser\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire browser from pool:', error)\n \n // 풀 상태 로깅으로 디버깅 도움\n try {\n const stats = getPoolStats()\n ConnectionManager.logger.error(`Pool stats during acquire error - borrowed: ${stats.borrowed}, available: ${stats.available}, pending: ${stats.pending}, max: ${stats.max}`)\n } catch (statsError) {\n ConnectionManager.logger.error('Failed to get pool stats during error:', statsError)\n }\n \n throw error\n }\n }\n\n async function releaseBrowser(browser: Browser) {\n if (!browser) {\n ConnectionManager.logger.warn('Attempted to release null/undefined browser')\n return\n }\n\n try {\n // 브라우저가 아직 연결되어 있는지 확인\n if (!browser.isConnected()) {\n ConnectionManager.logger.warn('Attempted to release disconnected browser')\n return\n }\n\n // Pool 상태 모니터링 (릴리즈 전)\n try {\n const statsBefore = getPoolStats()\n ConnectionManager.logger.debug(`Pool stats before release - borrowed: ${statsBefore.borrowed}, available: ${statsBefore.available}`)\n } catch (statsError) {\n ConnectionManager.logger.warn('Failed to get pool stats before release:', statsError)\n }\n\n const pool = getHeadlessPool()\n await pool.release(browser)\n ConnectionManager.logger.info('Browser successfully released to pool')\n \n // Pool 상태 모니터링 (릴리즈 후)\n try {\n const statsAfter = getPoolStats()\n ConnectionManager.logger.debug(`Pool stats after release - borrowed: ${statsAfter.borrowed}, available: ${statsAfter.available}`)\n } catch (statsError) {\n ConnectionManager.logger.warn('Failed to get pool stats after release:', statsError)\n }\n } catch (error) {\n ConnectionManager.logger.error('Failed to release browser to pool:', error)\n \n // 에러 발생시 풀 상태 로깅\n try {\n const stats = getPoolStats()\n ConnectionManager.logger.error(`Pool stats during release error - borrowed: ${stats.borrowed}, available: ${stats.available}, pending: ${stats.pending}`)\n } catch (statsError) {\n ConnectionManager.logger.error('Failed to get pool stats during release error:', statsError)\n }\n \n // 풀 릴리즈가 실패한 경우 브라우저 강제 종료 시도\n try {\n if (browser && browser.isConnected()) {\n await browser.close()\n ConnectionManager.logger.warn('Forcibly closed browser due to pool release failure')\n }\n } catch (forceCloseError) {\n ConnectionManager.logger.error('Failed to force close browser after pool release failure:', forceCloseError)\n }\n }\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n endpoint: connection.endpoint,\n params: connection.params,\n acquireSessionPage: async () => {\n const browser = await acquireBrowser()\n let page\n let cookies = connection.cookies\n\n try {\n page = await browser.newPage()\n await this.setupPage(page, uri, timeout)\n\n if (loginInfo.loginRequired) {\n if (loginInfo.forceLogin) {\n // 매번 새로 로그인 — 쿠키·세션 재사용 검증 모두 건너뜀.\n // 세션이 서버측에서 자주 만료되는 사이트 용도.\n ConnectionManager.logger.info('forceLogin=true — skipping cookie reuse, performing fresh login')\n connection.cookies = undefined\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n } else {\n // 먼저 기본 페이지로 이동\n await page.goto(uri, { waitUntil: 'networkidle2', timeout })\n\n // 현재 세션의 Authorization 헤더 확인\n const headers = await page.evaluate(() => {\n return fetch(window.location.href, { method: 'GET' })\n .then(response => response.headers.get('Authorization'))\n .catch(() => null)\n })\n\n if (headers) {\n ConnectionManager.logger.info('User is already logged in, skipping login process.')\n return page\n }\n\n if (cookies && this.isCookieValid(cookies)) {\n await this.applyCookiesAndVerifySession(page, cookies, loginInfo)\n connection.cookies = await page.cookies()\n return page\n }\n\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n }\n } else {\n // 로그인이 필요하지 않은 경우에도 기본 페이지로 이동\n await page.goto(uri, { waitUntil: 'networkidle2', timeout })\n }\n\n return page\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire session page:', error)\n \n // CRITICAL: 에러 발생 시 확실한 리소스 정리\n if (page) {\n try {\n await page.close()\n ConnectionManager.logger.info('Page closed during acquireSessionPage error handling')\n } catch (closeError) {\n ConnectionManager.logger.error('Failed to close page during acquireSessionPage error:', closeError)\n }\n }\n \n try {\n await releaseBrowser(browser)\n ConnectionManager.logger.info('Browser released during acquireSessionPage error handling')\n } catch (releaseError) {\n ConnectionManager.logger.error('Failed to release browser during acquireSessionPage error:', releaseError)\n }\n \n throw error\n }\n },\n releasePage: async (page: Page) => {\n try {\n if (page && !page.isClosed()) {\n const browser = page.browser()\n \n // 페이지를 먼저 닫기\n try {\n await page.close()\n ConnectionManager.logger.info('Page closed successfully')\n } catch (closeError) {\n ConnectionManager.logger.error('Failed to close page:', closeError)\n }\n \n // 브라우저를 풀에 반환\n try {\n await releaseBrowser(browser)\n ConnectionManager.logger.info('Browser released successfully')\n } catch (releaseError) {\n ConnectionManager.logger.error('Failed to release browser:', releaseError)\n // 풀 릴리즈가 실패한 경우 브라우저 강제 종료 시도\n try {\n if (browser && browser.isConnected()) {\n await browser.close()\n ConnectionManager.logger.warn('Forcibly closed browser due to pool release failure')\n }\n } catch (forceCloseError) {\n ConnectionManager.logger.error('Failed to force close browser:', forceCloseError)\n }\n }\n }\n } catch (error) {\n ConnectionManager.logger.error('Critical error in releasePage:', error)\n }\n },\n // 세션 회복을 위한 재로그인 메서드\n reAuthenticateSession: async () => {\n ConnectionManager.logger.info(`Re-authenticating session for connection: ${connection.name}`)\n \n let browser = null\n let page = null\n\n try {\n browser = await acquireBrowser()\n page = await browser.newPage()\n await this.setupPage(page, uri, loginInfo.timeout)\n \n if (loginInfo.loginRequired) {\n await this.performLogin(page, uri, loginInfo)\n const newCookies = await page.cookies()\n connection.cookies = newCookies\n ConnectionManager.logger.info(`Session re-authenticated successfully for connection: ${connection.name}`)\n }\n \n // CRITICAL: 페이지와 함께 브라우저 정보도 반환하여 정확한 릴리즈 추적\n return {\n page,\n browser,\n requiresManualRelease: true // 수동 릴리즈 필요 표시\n }\n } catch (error) {\n ConnectionManager.logger.error(`Failed to re-authenticate session for connection: ${connection.name}`, error)\n \n // 에러 시 확실한 리소스 정리\n if (page) {\n try {\n if (!page.isClosed()) {\n await page.close()\n ConnectionManager.logger.info('Page closed during reauth error handling')\n }\n } catch (closeError) {\n ConnectionManager.logger.error('Failed to close page during reauth error:', closeError)\n }\n }\n \n if (browser) {\n try {\n await releaseBrowser(browser)\n ConnectionManager.logger.info('Browser released during reauth error handling')\n } catch (releaseError) {\n ConnectionManager.logger.error('Failed to release browser during reauth error:', releaseError)\n // 풀 릴리즈가 실패한 경우 브라우저 강제 종료 시도\n try {\n if (browser.isConnected()) {\n await browser.close()\n ConnectionManager.logger.warn('Forcibly closed browser during reauth error due to pool release failure')\n }\n } catch (forceCloseError) {\n ConnectionManager.logger.error('Failed to force close browser during reauth error:', forceCloseError)\n }\n }\n }\n \n throw error\n }\n },\n // 세션 유효성 검사\n validateSession: async (page: Page) => {\n try {\n if (!loginInfo.loginRequired) {\n return true\n }\n\n // 페이지가 닫혔거나 연결이 끊어진 경우\n if (!page || page.isClosed()) {\n ConnectionManager.logger.warn(`Page is closed or null for connection: ${connection.name}`)\n return false\n }\n\n // URL 기반 로그인 리디렉션 체크\n let currentUrl: string\n try {\n currentUrl = page.url()\n } catch (urlError) {\n ConnectionManager.logger.warn(`Cannot get page URL for connection: ${connection.name}`, urlError)\n return false\n }\n \n if (currentUrl.includes(loginInfo.loginPagePath) || \n currentUrl.includes('/login') || \n currentUrl.includes('/signin') || \n currentUrl.includes('/auth')) {\n ConnectionManager.logger.info(`Redirected to login page: ${currentUrl}`)\n return false\n }\n\n // 로그인 폼 요소 기반 체크\n const needsLogin = await page.evaluate(() => {\n try {\n // 로그인 페이지 특정 요소들이 있는지 확인\n const loginIndicators = ['#username', '#password', '.login-form', '[type=\"password\"]']\n return loginIndicators.some(selector => {\n const element = document.querySelector(selector) as HTMLElement\n return element && element.offsetParent !== null // 보이는 요소만 체크\n })\n } catch (evalError) {\n return true // 에러 시 안전하게 재로그인 필요로 간주\n }\n })\n\n // 추가 세션 검증: 간단한 API 호출로 인증 상태 확인\n try {\n const testResponse = await page.evaluate(async () => {\n try {\n const response = await fetch(window.location.origin, { \n method: 'HEAD',\n credentials: 'include'\n })\n return {\n status: response.status,\n ok: response.ok\n }\n } catch (fetchError) {\n return { status: 0, ok: false }\n }\n })\n \n // 인증이 필요한 엔드포인트에서 401/403 반환시 세션 무효\n if (testResponse.status === 401 || testResponse.status === 403) {\n ConnectionManager.logger.info(`Authentication failed with status ${testResponse.status} for connection: ${connection.name}`)\n return false\n }\n } catch (apiTestError) {\n ConnectionManager.logger.warn(`Session API test failed for connection: ${connection.name}`, apiTestError)\n // API 테스트 실패는 세션 무효로 간주하지 않음 (네트워크 문제일 수 있음)\n }\n\n return !needsLogin\n } catch (error) {\n ConnectionManager.logger.warn(`Session validation failed for connection: ${connection.name}`, error)\n return false\n }\n },\n acquireBrowser,\n releaseBrowser\n })\n\n ConnectionManager.logger.info(\n `headless-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n protected isCookieValid(cookies: any[]): boolean {\n return isCookieValid(cookies)\n }\n\n async setupPage(page, uri, timeout) {\n await page.setRequestInterception(true)\n\n await page.setBypassCSP(true)\n\n await page.setUserAgent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Safari/537.36'\n )\n\n await page.evaluateOnNewDocument(() => {\n Object.defineProperty(navigator, 'webdriver', { get: () => false })\n })\n\n await page.setExtraHTTPHeaders({\n 'Upgrade-Insecure-Requests': '0',\n 'accept-language': 'en-US,en;q=0.9',\n referer: uri\n })\n\n await page.setDefaultNavigationTimeout(timeout)\n\n page.on('console', async msg => {\n const args = await Promise.all(msg.args().map(arg => arg.jsonValue().catch(() => undefined)))\n\n if (args.some(a => a !== undefined)) {\n ConnectionManager.logger.info(`[browser ${msg.type()}]`, ...args.filter(a => a !== undefined))\n } else {\n const text = msg.text()\n if (text) ConnectionManager.logger.info(`[browser ${msg.type()}]`, text)\n }\n })\n\n page.on('request', request => {\n if (request.isInterceptResolutionHandled()) {\n return\n }\n\n const resourceType = request.resourceType()\n\n // fetch(), XMLHttpRequest 등의 API 호출은 항상 허용\n if (resourceType === 'fetch' || resourceType === 'xhr') {\n request.continue()\n return\n }\n\n const headers = request.headers()\n if (headers['access-control-request-headers']) {\n const filteredHeaders = headers['access-control-request-headers']\n .split(',')\n .map(header => header.trim())\n .filter(header => header.toLowerCase() !== 'upgrade-insecure-requests')\n\n if (filteredHeaders.length > 0) {\n headers['access-control-request-headers'] = filteredHeaders.join(', ')\n } else {\n delete headers['access-control-request-headers']\n }\n }\n\n if (headers['upgrade-insecure-requests']) {\n delete headers['upgrade-insecure-requests']\n }\n\n // 이미지, 스타일시트, 폰트는 차단하되 API 요청은 허용\n if (['image', 'stylesheet', 'font'].includes(resourceType)) {\n request.abort()\n } else {\n request.continue()\n }\n })\n\n page.on('requestfailed', request => {\n try {\n // 정적 리소스(이미지·폰트·CSS 등) 의 실패는 로그인 흐름과 무관한 소음이므로 무시.\n // document / xhr / fetch 같은 의미있는 요청 실패만 출력.\n const type = request.resourceType()\n const NOISY_TYPES = new Set(['image', 'font', 'stylesheet', 'media', 'manifest', 'other'])\n if (NOISY_TYPES.has(type)) return\n\n // 일부 사이트의 정적 자원이 다른 type 으로 잡힐 수 있어 확장자 기반 보강 필터.\n const url = request.url()\n if (/\\.(png|jpe?g|gif|webp|svg|ico|woff2?|ttf|otf|eot|css|map)(\\?|$)/i.test(url)) return\n\n console.warn(\n `[headless] request failed (type=${type}): ${request.method()} ${url} — ${request.failure()?.errorText}`\n )\n } catch (error) {\n console.error('Error in requestfailed handler:', error)\n }\n })\n }\n\n async applyCookiesAndVerifySession(page, cookies, loginInfo) {\n await page.setCookie(...cookies)\n await page.reload({ waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n if (loginInfo.loginRequired && loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Session invalid, login required')\n }\n }\n }\n\n async performLogin(page, uri, loginInfo) {\n let lastError: Error | null = null\n for (let attempt = 1; attempt <= loginInfo.retries; attempt++) {\n try {\n await page.goto(`${uri}${loginInfo.loginPagePath}`, { waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n const usernameInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.usernameSelector\n )\n const passwordInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.passwordSelector\n )\n const submitButton = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.submitSelector\n )\n\n if (!usernameInput || !passwordInput || !submitButton) {\n throw new Error(\n `Failed to locate login form elements ` +\n `(username=${!!usernameInput}, password=${!!passwordInput}, submit=${!!submitButton}). ` +\n `Selectors: username='${loginInfo.loginSelectors.usernameSelector}', ` +\n `password='${loginInfo.loginSelectors.passwordSelector}', ` +\n `submit='${loginInfo.loginSelectors.submitSelector}'. ` +\n `사이트 폼 변경 가능성 — Connection params 의 *Selector 값을 실제 폼에 맞춰 덮어쓰세요.`\n )\n }\n\n await usernameInput.type(loginInfo.username)\n await passwordInput.type(loginInfo.password)\n\n var loginApiUrl =\n loginInfo.loginApiUrl ||\n (await page.evaluate(button => {\n const form = button.closest('form')\n return form ? form.action : null\n }, submitButton))\n\n if (loginApiUrl && !loginApiUrl.startsWith('http')) {\n loginApiUrl = `${uri}${loginApiUrl}`\n }\n\n if (!loginApiUrl) {\n throw new Error('❌ Unable to detect login API URL!')\n }\n\n console.log('✅ Detected login API URL:', loginApiUrl)\n\n const [response] = await Promise.all([\n page.waitForResponse(response => {\n const url = response.url()\n const method = response.request().method()\n\n return url === loginApiUrl && method === 'POST' && [200, 201, 204, 302, 304].includes(response.status())\n }),\n page.evaluate(button => button.click(), submitButton),\n page.waitForNavigation({ waitUntil: 'networkidle2', timeout: loginInfo.timeout }) // 로그인 후 리디렉션 감지\n ])\n\n if (response) {\n const status = response.status()\n if (status >= 200 && status < 400) {\n ConnectionManager.logger.info(`Login successful with status code: ${status}`)\n return\n } else if (status >= 400) {\n throw new Error(`Login failed with status code: ${status}`)\n }\n } else {\n throw new Error('No response received during login')\n }\n\n if (loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Login failed: Success selector not found')\n }\n }\n } catch (error: any) {\n lastError = error\n ConnectionManager.logger.warn(`Login attempt ${attempt} failed:`, error)\n\n try {\n await page.screenshot({ path: `logs/login-failure-attempt-${attempt}.png` })\n } catch (error) {\n ConnectionManager.logger.error('Failed to capture screenshot:', error)\n }\n\n if (attempt === loginInfo.retries) {\n throw new Error(\n `Login failed after ${loginInfo.retries} attempts — last cause: ${lastError?.message || lastError}`\n )\n }\n }\n }\n }\n\n async resolveShadowDom(page, shadowSelectors, targetSelector) {\n let context\n\n if (!shadowSelectors || shadowSelectors.length === 0) {\n // No Shadow DOM path; use document root as the context.\n // XPath 지원 — puppeteer 22+ 의 통합 선택자: `xpath/<expression>` prefix.\n // 셀렉터가 `//`, `(//`, `.//` 로 시작하면 xpath/ 로 감싸 page.$ 에 전달.\n if (typeof targetSelector === 'string' && /^\\s*(\\(|\\/\\/|\\.\\/\\/)/.test(targetSelector)) {\n return await page.$('xpath/' + targetSelector.trim())\n }\n context = page.mainFrame() // Puppeteer uses frames to represent document\n return context.$(targetSelector) // CSS selector — Search directly in the document root\n }\n\n context = page // Start with the page as the context\n for (const selector of shadowSelectors) {\n const shadowHost = await context.$(selector)\n if (!shadowHost) {\n throw new Error(`Shadow host not found: ${selector}`)\n }\n context = await page.evaluateHandle(host => host.shadowRoot, shadowHost)\n }\n return context.evaluateHandle((shadowRoot, selector) => shadowRoot.querySelector(selector), targetSelector)\n }\n\n async disconnect(connection) {\n try {\n // 연결 해제 전 리소스 정리 로그\n ConnectionManager.logger.info(`Starting disconnect process for connection: ${connection.name}`)\n \n // 풀 상태 확인 (정보성 로깅)\n try {\n const pool = getHeadlessPool()\n ConnectionManager.logger.info(`Pool status before disconnect - available resources exist: ${!!pool}`)\n } catch (poolError) {\n ConnectionManager.logger.warn(`Could not access pool during disconnect: ${poolError.message}`)\n }\n\n ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`headless-connector connection(${connection.name}) is disconnected`)\n } catch (error) {\n ConnectionManager.logger.error(`Error disconnecting headless-connector connection(${connection.name}):`, error)\n // Still try to remove the connection instance even if cleanup failed\n try {\n ConnectionManager.removeConnectionInstance(connection)\n } catch (removeError) {\n ConnectionManager.logger.error(`Failed to remove connection instance ${connection.name}:`, removeError)\n }\n }\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'username',\n label: 'username',\n useDomainAttribute: true\n },\n {\n type: 'secret',\n name: 'password',\n label: 'password',\n useDomainAttribute: true\n },\n {\n type: 'string',\n name: 'loginPagePath',\n label: 'login-page-path'\n },\n {\n type: 'string',\n name: 'loginApiUrl',\n label: 'login-api-url'\n },\n {\n type: 'string',\n name: 'usernameSelector',\n label: 'username-selector'\n },\n {\n type: 'string',\n name: 'passwordSelector',\n label: 'password-selector'\n },\n {\n type: 'string',\n name: 'submitSelector',\n label: 'submit-selector'\n },\n {\n type: 'string',\n name: 'successSelector',\n label: 'success-selector'\n },\n {\n type: 'string',\n name: 'shadowDomSelectors',\n label: 'shadow-dom-selectors'\n },\n {\n type: 'number',\n name: 'timeout',\n label: 'timeout',\n value: 15000\n },\n {\n type: 'number',\n name: 'retries',\n label: 'maximum-retries',\n value: 3\n }\n ]\n }\n\n get taskPrefixes() {\n return ['headless']\n }\n\n get description() {\n return 'Headless Pool Connector with login capabilities'\n }\n\n get help() {\n return 'integration/connector/headless-connector'\n }\n}\n\nConnectionManager.registerConnector('headless-connector', new HeadlessConnector())\n\nfunction isCookieValid(cookies: any[]): boolean {\n if (!cookies || cookies.length === 0) return false\n const now = Date.now() / 1000 // Current time in seconds\n return cookies.some((cookie: any) => cookie.expires && cookie.expires > now)\n}\n"]}
|
|
@@ -7,4 +7,6 @@ export * from './task-registry';
|
|
|
7
7
|
export * from './analyzer/analyze-integration';
|
|
8
8
|
export * from './edge-client';
|
|
9
9
|
export * from './resource-pool';
|
|
10
|
+
export { HeadlessConnector } from './connector/headless-connector';
|
|
11
|
+
export { lookupDomainEnvVar } from '../utils/domain-inheritance';
|
|
10
12
|
export { Connector, Context, TaskHandler } from './types';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.lookupDomainEnvVar = exports.HeadlessConnector = void 0;
|
|
3
4
|
const tslib_1 = require("tslib");
|
|
4
5
|
require("./connector/index.js");
|
|
5
6
|
require("./task/index.js");
|
|
@@ -10,4 +11,8 @@ tslib_1.__exportStar(require("./task-registry"), exports);
|
|
|
10
11
|
tslib_1.__exportStar(require("./analyzer/analyze-integration"), exports);
|
|
11
12
|
tslib_1.__exportStar(require("./edge-client"), exports);
|
|
12
13
|
tslib_1.__exportStar(require("./resource-pool"), exports);
|
|
14
|
+
var headless_connector_1 = require("./connector/headless-connector");
|
|
15
|
+
Object.defineProperty(exports, "HeadlessConnector", { enumerable: true, get: function () { return headless_connector_1.HeadlessConnector; } });
|
|
16
|
+
var domain_inheritance_1 = require("../utils/domain-inheritance");
|
|
17
|
+
Object.defineProperty(exports, "lookupDomainEnvVar", { enumerable: true, get: function () { return domain_inheritance_1.lookupDomainEnvVar; } });
|
|
13
18
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../server/engine/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../server/engine/index.ts"],"names":[],"mappings":";;;;AAAA,gCAA6B;AAC7B,2BAAwB;AAExB,+DAAoC;AACpC,8DAAmC;AACnC,4DAAiC;AACjC,0DAA+B;AAC/B,yEAA8C;AAC9C,wDAA6B;AAC7B,0DAA+B;AAC/B,qEAAkE;AAAzD,uHAAA,iBAAiB,OAAA;AAC1B,kEAAgE;AAAvD,wHAAA,kBAAkB,OAAA","sourcesContent":["import './connector/index.js'\nimport './task/index.js'\n\nexport * from './connection-manager'\nexport * from './evaluate-template'\nexport * from './scenario-engine'\nexport * from './task-registry'\nexport * from './analyzer/analyze-integration'\nexport * from './edge-client'\nexport * from './resource-pool'\nexport { HeadlessConnector } from './connector/headless-connector'\nexport { lookupDomainEnvVar } from '../utils/domain-inheritance'\n\nexport { Connector, Context, TaskHandler } from './types'\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **Whether integration runs in this process** — on by default, turned off once by an application that runs
|
|
3
|
+
* it elsewhere (ADR-0110 addition 2, ruling 2026-10-05).
|
|
4
|
+
*
|
|
5
|
+
* ── Why ────────────────────────────────────────────────────────────────────
|
|
6
|
+
* An application that depends on this module gets, at boot, every connection connected (a headless connection
|
|
7
|
+
* launches a browser) and every active scenario started. operato-plant serves its screens from one process and
|
|
8
|
+
* runs integration — headless browsers and scheduled scenarios — in another (`MES_PROCESS_ROLE=worker`). The
|
|
9
|
+
* serving process must not launch a browser or run a scenario because a setting was forgotten.
|
|
10
|
+
*
|
|
11
|
+
* ── What off means ────────────────────────────────────────────────────────
|
|
12
|
+
* Only running stops: the boot does not connect or load anything, the headless pool is not made, and the four
|
|
13
|
+
* ways in — connecting a connection, loading a scenario, starting an iteration, a scheduled run — are refused by
|
|
14
|
+
* name (`integration-runtime-off`) with the reason the application gave, which says where integration runs.
|
|
15
|
+
* Reading and saving connection and scenario definitions works as before.
|
|
16
|
+
*
|
|
17
|
+
* ── Once, and early ───────────────────────────────────────────────────────
|
|
18
|
+
* `disable` must come before `bootstrap-module-start` (an application calls it while its module loads; the
|
|
19
|
+
* shell loads every module before it emits the hook). Called after the boot it does not try to stop what is
|
|
20
|
+
* already running — it throws `integration-runtime-disabled-too-late`. There is no `enable`: a process that
|
|
21
|
+
* was told integration runs elsewhere does not change its mind.
|
|
22
|
+
*
|
|
23
|
+
* The state is on `globalThis`, so a second copy of this module in one process (hand copies, duplicate
|
|
24
|
+
* installs) reads the same answer.
|
|
25
|
+
*/
|
|
26
|
+
export declare const INTEGRATION_RUNTIME_OFF = "integration-runtime-off";
|
|
27
|
+
export declare const INTEGRATION_RUNTIME_DISABLED_TOO_LATE = "integration-runtime-disabled-too-late";
|
|
28
|
+
/** A refusal because integration does not run in this process. */
|
|
29
|
+
export declare class IntegrationRuntimeOff extends Error {
|
|
30
|
+
readonly code = "integration-runtime-off";
|
|
31
|
+
constructor(what: string, reason: string);
|
|
32
|
+
}
|
|
33
|
+
export declare const IntegrationRuntime: {
|
|
34
|
+
/** True unless an application turned integration off in this process. */
|
|
35
|
+
readonly enabled: boolean;
|
|
36
|
+
/** Why it is off, as the application said it; undefined while on. */
|
|
37
|
+
readonly reason: string | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Turn integration off in this process, for good. `reason` should say where it runs instead — it is shown to
|
|
40
|
+
* whoever presses a connect button here.
|
|
41
|
+
*/
|
|
42
|
+
disable(reason: string): void;
|
|
43
|
+
/** Throw the named refusal when off. `what` names what was asked for. */
|
|
44
|
+
assertEnabled(what: string): void;
|
|
45
|
+
/** The boot has happened; from here `disable` is too late. Called by this module's boot hook. */
|
|
46
|
+
markBooted(): void;
|
|
47
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* **Whether integration runs in this process** — on by default, turned off once by an application that runs
|
|
4
|
+
* it elsewhere (ADR-0110 addition 2, ruling 2026-10-05).
|
|
5
|
+
*
|
|
6
|
+
* ── Why ────────────────────────────────────────────────────────────────────
|
|
7
|
+
* An application that depends on this module gets, at boot, every connection connected (a headless connection
|
|
8
|
+
* launches a browser) and every active scenario started. operato-plant serves its screens from one process and
|
|
9
|
+
* runs integration — headless browsers and scheduled scenarios — in another (`MES_PROCESS_ROLE=worker`). The
|
|
10
|
+
* serving process must not launch a browser or run a scenario because a setting was forgotten.
|
|
11
|
+
*
|
|
12
|
+
* ── What off means ────────────────────────────────────────────────────────
|
|
13
|
+
* Only running stops: the boot does not connect or load anything, the headless pool is not made, and the four
|
|
14
|
+
* ways in — connecting a connection, loading a scenario, starting an iteration, a scheduled run — are refused by
|
|
15
|
+
* name (`integration-runtime-off`) with the reason the application gave, which says where integration runs.
|
|
16
|
+
* Reading and saving connection and scenario definitions works as before.
|
|
17
|
+
*
|
|
18
|
+
* ── Once, and early ───────────────────────────────────────────────────────
|
|
19
|
+
* `disable` must come before `bootstrap-module-start` (an application calls it while its module loads; the
|
|
20
|
+
* shell loads every module before it emits the hook). Called after the boot it does not try to stop what is
|
|
21
|
+
* already running — it throws `integration-runtime-disabled-too-late`. There is no `enable`: a process that
|
|
22
|
+
* was told integration runs elsewhere does not change its mind.
|
|
23
|
+
*
|
|
24
|
+
* The state is on `globalThis`, so a second copy of this module in one process (hand copies, duplicate
|
|
25
|
+
* installs) reads the same answer.
|
|
26
|
+
*/
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.IntegrationRuntime = exports.IntegrationRuntimeOff = exports.INTEGRATION_RUNTIME_DISABLED_TOO_LATE = exports.INTEGRATION_RUNTIME_OFF = void 0;
|
|
29
|
+
exports.INTEGRATION_RUNTIME_OFF = 'integration-runtime-off';
|
|
30
|
+
exports.INTEGRATION_RUNTIME_DISABLED_TOO_LATE = 'integration-runtime-disabled-too-late';
|
|
31
|
+
const STATE = Symbol.for('things-factory.integration-base.runtime');
|
|
32
|
+
function state() {
|
|
33
|
+
const holder = globalThis;
|
|
34
|
+
return (holder[STATE] ??= { booted: false });
|
|
35
|
+
}
|
|
36
|
+
/** A refusal because integration does not run in this process. */
|
|
37
|
+
class IntegrationRuntimeOff extends Error {
|
|
38
|
+
constructor(what, reason) {
|
|
39
|
+
super(`${exports.INTEGRATION_RUNTIME_OFF}: ${what} does not run in this process — ${reason}`);
|
|
40
|
+
this.code = exports.INTEGRATION_RUNTIME_OFF;
|
|
41
|
+
this.name = 'IntegrationRuntimeOff';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
exports.IntegrationRuntimeOff = IntegrationRuntimeOff;
|
|
45
|
+
exports.IntegrationRuntime = {
|
|
46
|
+
/** True unless an application turned integration off in this process. */
|
|
47
|
+
get enabled() {
|
|
48
|
+
return !state().off;
|
|
49
|
+
},
|
|
50
|
+
/** Why it is off, as the application said it; undefined while on. */
|
|
51
|
+
get reason() {
|
|
52
|
+
return state().off?.reason;
|
|
53
|
+
},
|
|
54
|
+
/**
|
|
55
|
+
* Turn integration off in this process, for good. `reason` should say where it runs instead — it is shown to
|
|
56
|
+
* whoever presses a connect button here.
|
|
57
|
+
*/
|
|
58
|
+
disable(reason) {
|
|
59
|
+
const s = state();
|
|
60
|
+
if (s.off)
|
|
61
|
+
return;
|
|
62
|
+
if (s.booted) {
|
|
63
|
+
throw new Error(`${exports.INTEGRATION_RUNTIME_DISABLED_TOO_LATE}: integration was turned off after the application booted; connections and scenarios may already be running — turn it off while the module loads`);
|
|
64
|
+
}
|
|
65
|
+
s.off = { reason: String(reason ?? '').trim() || 'integration is turned off in this process' };
|
|
66
|
+
},
|
|
67
|
+
/** Throw the named refusal when off. `what` names what was asked for. */
|
|
68
|
+
assertEnabled(what) {
|
|
69
|
+
const off = state().off;
|
|
70
|
+
if (off)
|
|
71
|
+
throw new IntegrationRuntimeOff(what, off.reason);
|
|
72
|
+
},
|
|
73
|
+
/** The boot has happened; from here `disable` is too late. Called by this module's boot hook. */
|
|
74
|
+
markBooted() {
|
|
75
|
+
state().booted = true;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
//# sourceMappingURL=integration-runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"integration-runtime.js","sourceRoot":"","sources":["../../server/engine/integration-runtime.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;;;AAEU,QAAA,uBAAuB,GAAG,yBAAyB,CAAA;AACnD,QAAA,qCAAqC,GAAG,uCAAuC,CAAA;AAO5F,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAA;AAEnE,SAAS,KAAK;IACZ,MAAM,MAAM,GAAG,UAAiE,CAAA;IAChF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAA;AAC9C,CAAC;AAED,kEAAkE;AAClE,MAAa,qBAAsB,SAAQ,KAAK;IAE9C,YAAY,IAAY,EAAE,MAAc;QACtC,KAAK,CAAC,GAAG,+BAAuB,KAAK,IAAI,mCAAmC,MAAM,EAAE,CAAC,CAAA;QAF9E,SAAI,GAAG,+BAAuB,CAAA;QAGrC,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAA;IACrC,CAAC;CACF;AAND,sDAMC;AAEY,QAAA,kBAAkB,GAAG;IAChC,yEAAyE;IACzE,IAAI,OAAO;QACT,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,CAAA;IACrB,CAAC;IAED,qEAAqE;IACrE,IAAI,MAAM;QACR,OAAO,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,CAAA;IAC5B,CAAC;IAED;;;OAGG;IACH,OAAO,CAAC,MAAc;QACpB,MAAM,CAAC,GAAG,KAAK,EAAE,CAAA;QACjB,IAAI,CAAC,CAAC,GAAG;YAAE,OAAM;QACjB,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CACb,GAAG,6CAAqC,kJAAkJ,CAC3L,CAAA;QACH,CAAC;QACD,CAAC,CAAC,GAAG,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,2CAA2C,EAAE,CAAA;IAChG,CAAC;IAED,yEAAyE;IACzE,aAAa,CAAC,IAAY;QACxB,MAAM,GAAG,GAAG,KAAK,EAAE,CAAC,GAAG,CAAA;QACvB,IAAI,GAAG;YAAE,MAAM,IAAI,qBAAqB,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC5D,CAAC;IAED,iGAAiG;IACjG,UAAU;QACR,KAAK,EAAE,CAAC,MAAM,GAAG,IAAI,CAAA;IACvB,CAAC;CACF,CAAA","sourcesContent":["/**\n * **Whether integration runs in this process** — on by default, turned off once by an application that runs\n * it elsewhere (ADR-0110 addition 2, ruling 2026-10-05).\n *\n * ── Why ────────────────────────────────────────────────────────────────────\n * An application that depends on this module gets, at boot, every connection connected (a headless connection\n * launches a browser) and every active scenario started. operato-plant serves its screens from one process and\n * runs integration — headless browsers and scheduled scenarios — in another (`MES_PROCESS_ROLE=worker`). The\n * serving process must not launch a browser or run a scenario because a setting was forgotten.\n *\n * ── What off means ────────────────────────────────────────────────────────\n * Only running stops: the boot does not connect or load anything, the headless pool is not made, and the four\n * ways in — connecting a connection, loading a scenario, starting an iteration, a scheduled run — are refused by\n * name (`integration-runtime-off`) with the reason the application gave, which says where integration runs.\n * Reading and saving connection and scenario definitions works as before.\n *\n * ── Once, and early ───────────────────────────────────────────────────────\n * `disable` must come before `bootstrap-module-start` (an application calls it while its module loads; the\n * shell loads every module before it emits the hook). Called after the boot it does not try to stop what is\n * already running — it throws `integration-runtime-disabled-too-late`. There is no `enable`: a process that\n * was told integration runs elsewhere does not change its mind.\n *\n * The state is on `globalThis`, so a second copy of this module in one process (hand copies, duplicate\n * installs) reads the same answer.\n */\n\nexport const INTEGRATION_RUNTIME_OFF = 'integration-runtime-off'\nexport const INTEGRATION_RUNTIME_DISABLED_TOO_LATE = 'integration-runtime-disabled-too-late'\n\ninterface RuntimeState {\n off?: { reason: string }\n booted: boolean\n}\n\nconst STATE = Symbol.for('things-factory.integration-base.runtime')\n\nfunction state(): RuntimeState {\n const holder = globalThis as unknown as Record<symbol, RuntimeState | undefined>\n return (holder[STATE] ??= { booted: false })\n}\n\n/** A refusal because integration does not run in this process. */\nexport class IntegrationRuntimeOff extends Error {\n readonly code = INTEGRATION_RUNTIME_OFF\n constructor(what: string, reason: string) {\n super(`${INTEGRATION_RUNTIME_OFF}: ${what} does not run in this process — ${reason}`)\n this.name = 'IntegrationRuntimeOff'\n }\n}\n\nexport const IntegrationRuntime = {\n /** True unless an application turned integration off in this process. */\n get enabled(): boolean {\n return !state().off\n },\n\n /** Why it is off, as the application said it; undefined while on. */\n get reason(): string | undefined {\n return state().off?.reason\n },\n\n /**\n * Turn integration off in this process, for good. `reason` should say where it runs instead — it is shown to\n * whoever presses a connect button here.\n */\n disable(reason: string): void {\n const s = state()\n if (s.off) return\n if (s.booted) {\n throw new Error(\n `${INTEGRATION_RUNTIME_DISABLED_TOO_LATE}: integration was turned off after the application booted; connections and scenarios may already be running — turn it off while the module loads`\n )\n }\n s.off = { reason: String(reason ?? '').trim() || 'integration is turned off in this process' }\n },\n\n /** Throw the named refusal when off. `what` names what was asked for. */\n assertEnabled(what: string): void {\n const off = state().off\n if (off) throw new IntegrationRuntimeOff(what, off.reason)\n },\n\n /** The boot has happened; from here `disable` is too late. Called by this module's boot hook. */\n markBooted(): void {\n state().booted = true\n }\n}\n"]}
|
|
@@ -9,6 +9,7 @@ exports.default = getHeadlessPool;
|
|
|
9
9
|
exports.getPoolStats = getPoolStats;
|
|
10
10
|
exports.forceCleanupPool = forceCleanupPool;
|
|
11
11
|
const shell_1 = require("@things-factory/shell");
|
|
12
|
+
const integration_runtime_1 = require("../integration-runtime");
|
|
12
13
|
/*
|
|
13
14
|
* ── The pool is made when the application boots, not when this module is loaded (2026-10-04) ──
|
|
14
15
|
* It used to be made at import, with `min: 2`, so loading this module launched two headless Chromes. The shell's
|
|
@@ -24,6 +25,8 @@ const shell_1 = require("@things-factory/shell");
|
|
|
24
25
|
*/
|
|
25
26
|
let integrationPool;
|
|
26
27
|
function pool() {
|
|
28
|
+
/* Off in this process: no browser is launched here, at boot or on use (ADR-0110 addition 2). */
|
|
29
|
+
integration_runtime_1.IntegrationRuntime.assertEnabled('the headless browser pool');
|
|
27
30
|
integrationPool ??= (0, shell_1.getOrCreateHeadlessPool)('integration', {
|
|
28
31
|
min: 2,
|
|
29
32
|
max: 20,
|
|
@@ -37,7 +40,9 @@ function pool() {
|
|
|
37
40
|
return integrationPool;
|
|
38
41
|
}
|
|
39
42
|
(0, shell_1.onHook)('bootstrap-module-start', () => {
|
|
40
|
-
|
|
43
|
+
integration_runtime_1.IntegrationRuntime.markBooted();
|
|
44
|
+
if (integration_runtime_1.IntegrationRuntime.enabled)
|
|
45
|
+
pool();
|
|
41
46
|
});
|
|
42
47
|
/**
|
|
43
48
|
* Get the integration headless pool
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headless-pool.js","sourceRoot":"","sources":["../../../server/engine/resource-pool/headless-pool.ts"],"names":[],"mappings":";AAAA;;;GAGG;;
|
|
1
|
+
{"version":3,"file":"headless-pool.js","sourceRoot":"","sources":["../../../server/engine/resource-pool/headless-pool.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AA8CH,0CAWC;AAgD2B,kCAAO;AA1CnC,oCA8BC;AAMD,4CAGC;AApGD,iDAAqH;AAErH,gEAA2D;AAE3D;;;;;;;;;;;;GAYG;AACH,IAAI,eAAuE,CAAA;AAE3E,SAAS,IAAI;IACX,gGAAgG;IAChG,wCAAkB,CAAC,aAAa,CAAC,2BAA2B,CAAC,CAAA;IAC7D,eAAe,KAA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AAY,EAAE,CAAC;YACf,cAAc,EAAE,CAAC;YACjB,aAAa,EAAE,CAAC;YAChB,aAAa,EAAE,CAAC;YAChB,iBAAiB,EAAE,CAAC;YACpB,sBAAsB,EAAE,CAAC;YACzB,eAAe,EAAE,GAAG;YACpB,YAAY,EAAE,IAAI;SACnB,CAAA;IACH,CAAC;IAED,8CAA8C;IAC9C,OAAO;QACL,GAAG,gBAAgB,CAAC,UAAU;QAC9B,GAAG,gBAAgB,CAAC,UAAU;QAC9B,sBAAsB,EAAE,QAAQ,CAAC,gBAAgB,CAAC,UAAU,CAAC,sBAAsB,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC;QAC3G,eAAe,EAAE,gBAAgB,CAAC,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;KAC9E,CAAA;AACH,CAAC;AAED;;;GAGG;AACH,SAAgB,gBAAgB;IAC9B,2CAA2C;IAC3C,OAAO,eAAe,CAAC,CAAC,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CAAA;AACtE,CAAC","sourcesContent":["/**\n * Integration Base Headless Pool\n * Using the unified headless pool system from @things-factory/shell\n */\n\nimport { getAllPoolStats, getOrCreateHeadlessPool, HEADLESS_POOL_ARGUMENT_SETS, onHook } from '@things-factory/shell'\n\nimport { IntegrationRuntime } from '../integration-runtime'\n\n/*\n * ── The pool is made when the application boots, not when this module is loaded (2026-10-04) ──\n * It used to be made at import, with `min: 2`, so loading this module launched two headless Chromes. The shell's\n * module loader loads every things-factory module in an application's dependency tree, so **any** process that\n * loaded the shell — every DB test of operato-warehouse among them — launched two browsers it never used. Their\n * sockets keep the event loop alive, and the shell's cleanup waits for `beforeExit`, which never comes while\n * they are open: the test file passed in half a second and its process did not end (measured: warehouse\n * `master-change-approval.db.test.cjs`, two chrome-headless-shell children and two TCP sockets to 127.0.0.1).\n *\n * Now it is made on `bootstrap-module-start`, as board-service's label pool is — an application still has two\n * warm browsers from boot — or on first use, whichever comes first. A process that never boots an application\n * and never acquires launches nothing.\n */\nlet integrationPool: ReturnType<typeof getOrCreateHeadlessPool> | undefined\n\nfunction pool() {\n /* Off in this process: no browser is launched here, at boot or on use (ADR-0110 addition 2). */\n IntegrationRuntime.assertEnabled('the headless browser pool')\n integrationPool ??= getOrCreateHeadlessPool('integration', {\n min: 2,\n max: 20,\n args: [...HEADLESS_POOL_ARGUMENT_SETS.basic, ...HEADLESS_POOL_ARGUMENT_SETS.keychain_safe],\n acquireTimeoutMillis: 15000,\n testOnBorrow: true,\n enableStats: true,\n enableRecovery: true,\n enableCleanup: true\n })\n return integrationPool\n}\n\nonHook('bootstrap-module-start', () => {\n IntegrationRuntime.markBooted()\n if (IntegrationRuntime.enabled) pool()\n})\n\n/**\n * Get the integration headless pool\n * @returns Pool instance with acquire/release methods\n */\nexport function getHeadlessPool() {\n return {\n acquire: () => pool().acquire(),\n release: (resource: any) => pool().release(resource),\n size: 0, // These will be dynamically calculated if needed\n available: 0,\n borrowed: 0,\n pending: 0,\n max: 20,\n min: 2\n }\n}\n\n/**\n * Get pool statistics\n * @returns Detailed pool statistics\n */\nexport function getPoolStats() {\n const allStats = getAllPoolStats()\n const integrationStats = allStats.integration\n\n if (!integrationStats) {\n return {\n size: 0,\n available: 0,\n borrowed: 0,\n pending: 0,\n max: 20,\n min: 2,\n totalCreated: 0,\n totalDestroyed: 0,\n totalAcquired: 0,\n totalReleased: 0,\n currentlyAcquired: 0,\n averageAcquisitionTime: 0,\n utilizationRate: '0',\n lastActivity: null\n }\n }\n\n // Convert to format expected by existing code\n return {\n ...integrationStats.poolStatus,\n ...integrationStats.statistics,\n averageAcquisitionTime: parseInt(integrationStats.statistics.averageAcquisitionTime.replace('ms', '')) || 0,\n utilizationRate: integrationStats.poolStatus.utilizationRate.replace('%', '')\n }\n}\n\n/**\n * Force cleanup pool - delegates to unified system\n * @returns Promise<void>\n */\nexport function forceCleanupPool(): Promise<void> {\n /* Nothing made yet is nothing to clean. */\n return integrationPool ? integrationPool.reset() : Promise.resolve()\n}\n\n// Legacy compatibility - re-export the main function\nexport { getHeadlessPool as default }\n"]}
|
|
@@ -5,6 +5,7 @@ const shell_1 = require("@things-factory/shell");
|
|
|
5
5
|
const scenario_1 = require("../service/scenario/scenario");
|
|
6
6
|
const scenario_instance_type_1 = require("../service/scenario-instance/scenario-instance-type");
|
|
7
7
|
const pending_queue_1 = require("./pending-queue");
|
|
8
|
+
const integration_runtime_1 = require("./integration-runtime");
|
|
8
9
|
const auth_base_1 = require("@things-factory/auth-base");
|
|
9
10
|
const resolve_steps_1 = require("../service/scenario/resolve-steps");
|
|
10
11
|
const debug = require('debug')('things-factory:integration-base:scenario-engine');
|
|
@@ -32,6 +33,7 @@ class ScenarioEngine {
|
|
|
32
33
|
return instances.filter(instance => !scenarioName || instance.scenarioName == scenarioName);
|
|
33
34
|
}
|
|
34
35
|
static async load(instanceName, scenarioConfig, context) {
|
|
36
|
+
integration_runtime_1.IntegrationRuntime.assertEnabled(`scenario "${instanceName}"`);
|
|
35
37
|
const { domain: scenarioDomain } = scenarioConfig;
|
|
36
38
|
const domain = context?.domain || scenarioDomain;
|
|
37
39
|
debug('load', domain.subdomain, instanceName);
|
|
@@ -86,6 +88,7 @@ class ScenarioEngine {
|
|
|
86
88
|
* `alreadyRunning` — `run` would hand back the running instance and report nothing.
|
|
87
89
|
*/
|
|
88
90
|
static async runIteration(instanceName, scenarioConfig, context) {
|
|
91
|
+
integration_runtime_1.IntegrationRuntime.assertEnabled(`scenario "${instanceName}"`);
|
|
89
92
|
const { domain: scenarioDomain, iteration = 'SELF' } = scenarioConfig;
|
|
90
93
|
const domain = context?.domain || scenarioDomain;
|
|
91
94
|
const targetDomains = await ScenarioEngine.getTargetDomains(domain, iteration);
|
|
@@ -143,6 +146,7 @@ class ScenarioEngine {
|
|
|
143
146
|
* @returns Promise that resolves immediately, but scenarios execute sequentially
|
|
144
147
|
*/
|
|
145
148
|
static async loadIteration(instanceName, scenarioConfig, context) {
|
|
149
|
+
integration_runtime_1.IntegrationRuntime.assertEnabled(`scenario "${instanceName}"`);
|
|
146
150
|
const { domain: scenarioDomain, iteration = 'SELF' } = scenarioConfig;
|
|
147
151
|
const domain = context?.domain || scenarioDomain;
|
|
148
152
|
debug('load-iteration', domain.subdomain, instanceName, iteration);
|