@silasfmartins/testhub 1.0.0

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.
Files changed (296) hide show
  1. package/.github/copilot-instructions.md +520 -0
  2. package/biome.json +37 -0
  3. package/dist/index.d.ts +45 -0
  4. package/dist/index.js +169 -0
  5. package/dist/scripts/consumer-postinstall.d.ts +15 -0
  6. package/dist/scripts/consumer-postinstall.js +785 -0
  7. package/dist/scripts/generate-docs.d.ts +16 -0
  8. package/dist/scripts/generate-docs.js +1363 -0
  9. package/dist/scripts/generate-index.d.ts +2 -0
  10. package/dist/scripts/generate-index.js +314 -0
  11. package/dist/scripts/init-api.d.ts +2 -0
  12. package/dist/scripts/init-api.js +525 -0
  13. package/dist/scripts/init-banco.d.ts +2 -0
  14. package/dist/scripts/init-banco.js +347 -0
  15. package/dist/scripts/init-frontend.d.ts +2 -0
  16. package/dist/scripts/init-frontend.js +627 -0
  17. package/dist/scripts/init-mobile.d.ts +2 -0
  18. package/dist/scripts/init-mobile.js +481 -0
  19. package/dist/scripts/init-scenarios.d.ts +2 -0
  20. package/dist/scripts/init-scenarios.js +846 -0
  21. package/dist/scripts/init-ssh.d.ts +2 -0
  22. package/dist/scripts/init-ssh.js +639 -0
  23. package/dist/scripts/package-versions.d.ts +57 -0
  24. package/dist/scripts/package-versions.js +768 -0
  25. package/dist/scripts/postinstall.d.ts +1 -0
  26. package/dist/scripts/postinstall.js +527 -0
  27. package/dist/scripts/robust-build.d.ts +7 -0
  28. package/dist/scripts/robust-build.js +88 -0
  29. package/dist/scripts/setup-local-packages.d.ts +31 -0
  30. package/dist/scripts/setup-local-packages.js +237 -0
  31. package/dist/scripts/smart-override.d.ts +2 -0
  32. package/dist/scripts/smart-override.js +1360 -0
  33. package/dist/scripts/sync-configs.d.ts +27 -0
  34. package/dist/scripts/sync-configs.js +248 -0
  35. package/dist/scripts/test-biome-parse.d.ts +5 -0
  36. package/dist/scripts/test-biome-parse.js +84 -0
  37. package/dist/scripts/ultracite-setup.d.ts +4 -0
  38. package/dist/scripts/ultracite-setup.js +310 -0
  39. package/dist/scripts/update-all-init-scripts.d.ts +2 -0
  40. package/dist/scripts/update-all-init-scripts.js +52 -0
  41. package/dist/scripts/update-biome-schema.d.ts +15 -0
  42. package/dist/scripts/update-biome-schema.js +124 -0
  43. package/dist/src/AutoCoreFacade.d.ts +145 -0
  44. package/dist/src/AutoCoreFacade.js +217 -0
  45. package/dist/src/api/ApiActions.d.ts +297 -0
  46. package/dist/src/api/ApiActions.js +1905 -0
  47. package/dist/src/api/Certificate.d.ts +60 -0
  48. package/dist/src/api/Certificate.js +79 -0
  49. package/dist/src/api/JsonResponse.d.ts +116 -0
  50. package/dist/src/api/JsonResponse.js +206 -0
  51. package/dist/src/appium/DeviceFarmViewer.d.ts +79 -0
  52. package/dist/src/appium/DeviceFarmViewer.js +1083 -0
  53. package/dist/src/appium/MobileActions.d.ts +347 -0
  54. package/dist/src/appium/MobileActions.js +1632 -0
  55. package/dist/src/appium/MobileConnection.d.ts +160 -0
  56. package/dist/src/appium/MobileConnection.js +772 -0
  57. package/dist/src/config/envLoader.d.ts +123 -0
  58. package/dist/src/config/envLoader.js +361 -0
  59. package/dist/src/config/jest-safe-setup.d.ts +19 -0
  60. package/dist/src/config/jest-safe-setup.js +369 -0
  61. package/dist/src/config/timeouts.d.ts +32 -0
  62. package/dist/src/config/timeouts.js +38 -0
  63. package/dist/src/desktop/DesktopActions.d.ts +46 -0
  64. package/dist/src/desktop/DesktopActions.js +398 -0
  65. package/dist/src/desktop/DesktopConnection.d.ts +32 -0
  66. package/dist/src/desktop/DesktopConnection.js +84 -0
  67. package/dist/src/domain/entities/TestExecution.d.ts +117 -0
  68. package/dist/src/domain/entities/TestExecution.js +150 -0
  69. package/dist/src/domain/entities/TestReport.d.ts +114 -0
  70. package/dist/src/domain/entities/TestReport.js +179 -0
  71. package/dist/src/domain/repositories/ITestRepository.d.ts +196 -0
  72. package/dist/src/domain/repositories/ITestRepository.js +14 -0
  73. package/dist/src/domain/schemas/ValidationSchemas.d.ts +159 -0
  74. package/dist/src/domain/schemas/ValidationSchemas.js +181 -0
  75. package/dist/src/functions/errors/BaseError.d.ts +78 -0
  76. package/dist/src/functions/errors/BaseError.js +245 -0
  77. package/dist/src/functions/errors/ConfigurationError.d.ts +16 -0
  78. package/dist/src/functions/errors/ConfigurationError.js +48 -0
  79. package/dist/src/functions/errors/ErrorCatalog.d.ts +148 -0
  80. package/dist/src/functions/errors/ErrorCatalog.js +157 -0
  81. package/dist/src/functions/errors/GlobalErrorHandler.d.ts +101 -0
  82. package/dist/src/functions/errors/GlobalErrorHandler.js +281 -0
  83. package/dist/src/functions/errors/IntegrationError.d.ts +17 -0
  84. package/dist/src/functions/errors/IntegrationError.js +51 -0
  85. package/dist/src/functions/errors/SecurityError.d.ts +14 -0
  86. package/dist/src/functions/errors/SecurityError.js +42 -0
  87. package/dist/src/functions/errors/SystemError.d.ts +12 -0
  88. package/dist/src/functions/errors/SystemError.js +36 -0
  89. package/dist/src/functions/errors/ValidationError.d.ts +14 -0
  90. package/dist/src/functions/errors/ValidationError.js +61 -0
  91. package/dist/src/functions/errors/index.d.ts +12 -0
  92. package/dist/src/functions/errors/index.js +13 -0
  93. package/dist/src/global-setup.d.ts +1 -0
  94. package/dist/src/global-setup.js +1037 -0
  95. package/dist/src/helpers/BancoActions.d.ts +188 -0
  96. package/dist/src/helpers/BancoActions.js +581 -0
  97. package/dist/src/helpers/EnviromentHelper.d.ts +17 -0
  98. package/dist/src/helpers/EnviromentHelper.js +66 -0
  99. package/dist/src/helpers/ParallelExecutionHelper.d.ts +183 -0
  100. package/dist/src/helpers/ParallelExecutionHelper.js +375 -0
  101. package/dist/src/helpers/SyncSignal.d.ts +15 -0
  102. package/dist/src/helpers/SyncSignal.js +44 -0
  103. package/dist/src/hubdocs/CategoryDetector.d.ts +83 -0
  104. package/dist/src/hubdocs/CategoryDetector.js +401 -0
  105. package/dist/src/hubdocs/DirectStatementInterceptor.d.ts +54 -0
  106. package/dist/src/hubdocs/DirectStatementInterceptor.js +243 -0
  107. package/dist/src/hubdocs/ExecutionTracker.d.ts +107 -0
  108. package/dist/src/hubdocs/ExecutionTracker.js +702 -0
  109. package/dist/src/hubdocs/HubDocs.d.ts +395 -0
  110. package/dist/src/hubdocs/HubDocs.js +3586 -0
  111. package/dist/src/hubdocs/StatementMethodFilter.d.ts +71 -0
  112. package/dist/src/hubdocs/StatementMethodFilter.js +618 -0
  113. package/dist/src/hubdocs/StatementTracker.d.ts +417 -0
  114. package/dist/src/hubdocs/StatementTracker.js +2419 -0
  115. package/dist/src/hubdocs/SwaggerGenerator.d.ts +59 -0
  116. package/dist/src/hubdocs/SwaggerGenerator.js +405 -0
  117. package/dist/src/hubdocs/index.d.ts +9 -0
  118. package/dist/src/hubdocs/index.js +9 -0
  119. package/dist/src/hubdocs/types.d.ts +114 -0
  120. package/dist/src/hubdocs/types.js +5 -0
  121. package/dist/src/infrastructure/DependencyContainer.d.ts +142 -0
  122. package/dist/src/infrastructure/DependencyContainer.js +250 -0
  123. package/dist/src/infrastructure/adapters/AppiumAdapter.d.ts +168 -0
  124. package/dist/src/infrastructure/adapters/AppiumAdapter.js +468 -0
  125. package/dist/src/infrastructure/adapters/OracleAdapter.d.ts +150 -0
  126. package/dist/src/infrastructure/adapters/OracleAdapter.js +388 -0
  127. package/dist/src/infrastructure/adapters/PlaywrightAdapter.d.ts +192 -0
  128. package/dist/src/infrastructure/adapters/PlaywrightAdapter.js +382 -0
  129. package/dist/src/infrastructure/adapters/SSHAdapter.d.ts +141 -0
  130. package/dist/src/infrastructure/adapters/SSHAdapter.js +428 -0
  131. package/dist/src/interfaces.d.ts +501 -0
  132. package/dist/src/interfaces.js +25 -0
  133. package/dist/src/internal/fakes/__fake-actions__.d.ts +17 -0
  134. package/dist/src/internal/fakes/__fake-actions__.js +21 -0
  135. package/dist/src/internal/fakes/__forbidden__.d.ts +10 -0
  136. package/dist/src/internal/fakes/__forbidden__.js +18 -0
  137. package/dist/src/internal/fakes/__honeypot__.d.ts +15 -0
  138. package/dist/src/internal/fakes/__honeypot__.js +24 -0
  139. package/dist/src/octane/OctaneReporter.d.ts +13 -0
  140. package/dist/src/octane/OctaneReporter.js +61 -0
  141. package/dist/src/playwright/CryptoActions.d.ts +20 -0
  142. package/dist/src/playwright/CryptoActions.js +75 -0
  143. package/dist/src/playwright/EnhancedWebActions.d.ts +7 -0
  144. package/dist/src/playwright/EnhancedWebActions.js +65 -0
  145. package/dist/src/playwright/WebActions.d.ts +1599 -0
  146. package/dist/src/playwright/WebActions.js +11788 -0
  147. package/dist/src/playwright/actions/ActionTimeline.d.ts +36 -0
  148. package/dist/src/playwright/actions/ActionTimeline.js +101 -0
  149. package/dist/src/playwright/actions/RecoveryQueue.d.ts +82 -0
  150. package/dist/src/playwright/actions/RecoveryQueue.js +130 -0
  151. package/dist/src/playwright/actions/SelectorCache.d.ts +53 -0
  152. package/dist/src/playwright/actions/SelectorCache.js +96 -0
  153. package/dist/src/playwright/actions/index.d.ts +13 -0
  154. package/dist/src/playwright/actions/index.js +14 -0
  155. package/dist/src/playwright/actions/types.d.ts +147 -0
  156. package/dist/src/playwright/actions/types.js +5 -0
  157. package/dist/src/playwright/fixtures.d.ts +112 -0
  158. package/dist/src/playwright/fixtures.js +718 -0
  159. package/dist/src/playwright/network-logs-reporter.d.ts +7 -0
  160. package/dist/src/playwright/network-logs-reporter.js +66 -0
  161. package/dist/src/playwright/registerRecoveryWrappers.d.ts +1 -0
  162. package/dist/src/playwright/registerRecoveryWrappers.js +54 -0
  163. package/dist/src/security/BuildSecurity.d.ts +12 -0
  164. package/dist/src/security/BuildSecurity.js +138 -0
  165. package/dist/src/security/EulaProtection.d.ts +70 -0
  166. package/dist/src/security/EulaProtection.js +155 -0
  167. package/dist/src/security/HoneypotManager.d.ts +46 -0
  168. package/dist/src/security/HoneypotManager.js +234 -0
  169. package/dist/src/security/KeysManager.d.ts +36 -0
  170. package/dist/src/security/KeysManager.js +158 -0
  171. package/dist/src/security/ProofOfWorkIntegration.d.ts +64 -0
  172. package/dist/src/security/ProofOfWorkIntegration.js +206 -0
  173. package/dist/src/security/SecurityValidation.d.ts +21 -0
  174. package/dist/src/security/SecurityValidation.js +163 -0
  175. package/dist/src/security/SourceMapProtection.d.ts +55 -0
  176. package/dist/src/security/SourceMapProtection.js +220 -0
  177. package/dist/src/security/protector.d.ts +1 -0
  178. package/dist/src/security/protector.js +97 -0
  179. package/dist/src/ssh/SSHActions.d.ts +262 -0
  180. package/dist/src/ssh/SSHActions.js +790 -0
  181. package/dist/src/ssh/SSHClient.d.ts +99 -0
  182. package/dist/src/ssh/SSHClient.js +409 -0
  183. package/dist/src/statements/BaseStatement.d.ts +38 -0
  184. package/dist/src/statements/BaseStatement.js +78 -0
  185. package/dist/src/testContext/AuthStateManager.d.ts +93 -0
  186. package/dist/src/testContext/AuthStateManager.js +256 -0
  187. package/dist/src/testContext/CoverageManager.d.ts +198 -0
  188. package/dist/src/testContext/CoverageManager.js +917 -0
  189. package/dist/src/testContext/TestAnnotations.d.ts +476 -0
  190. package/dist/src/testContext/TestAnnotations.js +2647 -0
  191. package/dist/src/testContext/TestContext.d.ts +138 -0
  192. package/dist/src/testContext/TestContext.js +369 -0
  193. package/dist/src/testContext/UnifiedHtmlGenerator.d.ts +7 -0
  194. package/dist/src/testContext/UnifiedHtmlGenerator.js +264 -0
  195. package/dist/src/testContext/UnifiedReportManager.d.ts +211 -0
  196. package/dist/src/testContext/UnifiedReportManager.js +1206 -0
  197. package/dist/src/testhub/DynamicConfigManager.d.ts +121 -0
  198. package/dist/src/testhub/DynamicConfigManager.js +320 -0
  199. package/dist/src/testhub/SystemsManager.d.ts +119 -0
  200. package/dist/src/testhub/SystemsManager.js +365 -0
  201. package/dist/src/testhub/TestHubClient.d.ts +335 -0
  202. package/dist/src/testhub/TestHubClient.js +1215 -0
  203. package/dist/src/testhub/TestHubReporter.d.ts +62 -0
  204. package/dist/src/testhub/TestHubReporter.js +576 -0
  205. package/dist/src/testhub/TestHubVars.d.ts +116 -0
  206. package/dist/src/testhub/TestHubVars.js +273 -0
  207. package/dist/src/utils/ActionInterceptor.d.ts +59 -0
  208. package/dist/src/utils/ActionInterceptor.js +741 -0
  209. package/dist/src/utils/ArtifactsCompressor.d.ts +43 -0
  210. package/dist/src/utils/ArtifactsCompressor.js +181 -0
  211. package/dist/src/utils/AutoLogsFinal.d.ts +47 -0
  212. package/dist/src/utils/AutoLogsFinal.js +148 -0
  213. package/dist/src/utils/CodeGenSession.d.ts +114 -0
  214. package/dist/src/utils/CodeGenSession.js +264 -0
  215. package/dist/src/utils/ConfigLogger.d.ts +133 -0
  216. package/dist/src/utils/ConfigLogger.js +611 -0
  217. package/dist/src/utils/CustomReporter.d.ts +22 -0
  218. package/dist/src/utils/CustomReporter.js +352 -0
  219. package/dist/src/utils/DataStore.d.ts +171 -0
  220. package/dist/src/utils/DataStore.js +484 -0
  221. package/dist/src/utils/DatabaseInterceptor.d.ts +19 -0
  222. package/dist/src/utils/DatabaseInterceptor.js +295 -0
  223. package/dist/src/utils/DateHelper.d.ts +16 -0
  224. package/dist/src/utils/DateHelper.js +120 -0
  225. package/dist/src/utils/DateValidator.d.ts +4 -0
  226. package/dist/src/utils/DateValidator.js +51 -0
  227. package/dist/src/utils/DocumentGenerator.d.ts +35 -0
  228. package/dist/src/utils/DocumentGenerator.js +129 -0
  229. package/dist/src/utils/EvidenceCapture.d.ts +90 -0
  230. package/dist/src/utils/EvidenceCapture.js +600 -0
  231. package/dist/src/utils/EvidenceReportGenerator.d.ts +70 -0
  232. package/dist/src/utils/EvidenceReportGenerator.js +799 -0
  233. package/dist/src/utils/FrameManagementUtil.d.ts +42 -0
  234. package/dist/src/utils/FrameManagementUtil.js +75 -0
  235. package/dist/src/utils/GlobalStatementsInterceptor.d.ts +1 -0
  236. package/dist/src/utils/GlobalStatementsInterceptor.js +1 -0
  237. package/dist/src/utils/HTMLTemplate.d.ts +1 -0
  238. package/dist/src/utils/HTMLTemplate.js +1034 -0
  239. package/dist/src/utils/InterceptacaoMagica.d.ts +23 -0
  240. package/dist/src/utils/InterceptacaoMagica.js +365 -0
  241. package/dist/src/utils/LogSanitizer.d.ts +35 -0
  242. package/dist/src/utils/LogSanitizer.js +110 -0
  243. package/dist/src/utils/Logger.d.ts +65 -0
  244. package/dist/src/utils/Logger.js +284 -0
  245. package/dist/src/utils/McpLocalClient.d.ts +141 -0
  246. package/dist/src/utils/McpLocalClient.js +871 -0
  247. package/dist/src/utils/PDFEvidenceGenerator.d.ts +20 -0
  248. package/dist/src/utils/PDFEvidenceGenerator.js +156 -0
  249. package/dist/src/utils/SpecFileAnalyzer.d.ts +35 -0
  250. package/dist/src/utils/SpecFileAnalyzer.js +209 -0
  251. package/dist/src/utils/StatementInterceptor.d.ts +18 -0
  252. package/dist/src/utils/StatementInterceptor.js +87 -0
  253. package/dist/src/utils/StatementLogger.d.ts +33 -0
  254. package/dist/src/utils/StatementLogger.js +113 -0
  255. package/dist/src/utils/StatementsInterceptor.d.ts +1 -0
  256. package/dist/src/utils/StatementsInterceptor.js +1 -0
  257. package/dist/src/utils/TeamsFlushHook.d.ts +17 -0
  258. package/dist/src/utils/TeamsFlushHook.js +168 -0
  259. package/dist/src/utils/TerminalLogCapture.d.ts +158 -0
  260. package/dist/src/utils/TerminalLogCapture.js +531 -0
  261. package/dist/src/utils/TestMethodLogger.d.ts +70 -0
  262. package/dist/src/utils/TestMethodLogger.js +95 -0
  263. package/dist/src/utils/UnifiedTeardown.d.ts +4 -0
  264. package/dist/src/utils/UnifiedTeardown.js +400 -0
  265. package/dist/src/utils/XPathCatalog.d.ts +152 -0
  266. package/dist/src/utils/XPathCatalog.js +350 -0
  267. package/dist/src/utils/generators.d.ts +90 -0
  268. package/dist/src/utils/generators.js +167 -0
  269. package/dist/src/utils/testRecovery/ResilientPlaywright.d.ts +152 -0
  270. package/dist/src/utils/testRecovery/ResilientPlaywright.js +715 -0
  271. package/dist/src/utils/testRecovery/TestRecoveryClient.d.ts +801 -0
  272. package/dist/src/utils/testRecovery/TestRecoveryClient.js +1415 -0
  273. package/dist/src/utils/testRecovery/autoFixCode.d.ts +65 -0
  274. package/dist/src/utils/testRecovery/autoFixCode.js +32 -0
  275. package/dist/vitest.config.d.ts +2 -0
  276. package/dist/vitest.config.js +59 -0
  277. package/dist/wdio.conf.d.ts +1 -0
  278. package/dist/wdio.conf.js +420 -0
  279. package/package.json +137 -0
  280. package/protect-loader.mjs +643 -0
  281. package/scripts/consumer-postinstall.ts +975 -0
  282. package/scripts/generate-index.ts +343 -0
  283. package/scripts/init-api.ts +613 -0
  284. package/scripts/init-banco.ts +437 -0
  285. package/scripts/init-frontend.ts +727 -0
  286. package/scripts/init-mobile.ts +558 -0
  287. package/scripts/init-scenarios.ts +925 -0
  288. package/scripts/init-ssh.ts +734 -0
  289. package/scripts/package-versions.ts +978 -0
  290. package/scripts/postinstall.ts +605 -0
  291. package/scripts/smart-override.ts +1675 -0
  292. package/scripts/sync-configs.ts +302 -0
  293. package/scripts/ultracite-setup.ts +370 -0
  294. package/src/types/globals.d.ts +48 -0
  295. package/tsconfig.json +29 -0
  296. package/types/autocore-sync-signal.d.ts +10 -0
@@ -0,0 +1,234 @@
1
+ /**
2
+ * HoneypotManager: Sistema de honeypots dinâmicos para detecção de automação
3
+ * Cria armadilhas invisíveis em tempo de execução que detectam uso por IA
4
+ */
5
+ import { createHash, randomBytes } from 'node:crypto';
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { Logger } from '../utils/Logger.js';
9
+ export class HoneypotManager {
10
+ static tripped = false;
11
+ static zeroWidthChars = '\u200B\u200C\u200D\uFEFF'; // Zero-width chars
12
+ /**
13
+ * Verifica se algum honeypot foi ativado
14
+ */
15
+ static isTripped() {
16
+ return (HoneypotManager.tripped ||
17
+ process.env.AUTOCORE_HONEYPOT_TRIPPED === 'true');
18
+ }
19
+ /**
20
+ * Marca um honeypot como ativado
21
+ */
22
+ static tripHoneypot(source) {
23
+ HoneypotManager.tripped = true;
24
+ process.env.AUTOCORE_HONEYPOT_TRIPPED = 'true';
25
+ process.env.AUTOCORE_HONEYPOT_SOURCE = source;
26
+ // Só mostrar log em modo debug para reduzir spam
27
+ if (process.env.AUTOCORE_DEBUG_LOGS ||
28
+ process.env.NODE_ENV === 'development') {
29
+ Logger.warning(`⚠️ Honeypot ativado: ${source}`);
30
+ }
31
+ }
32
+ /**
33
+ * Injeta caracteres invisíveis em strings/comentários TypeScript
34
+ * Marcam arquivos sem afetar funcionalidade
35
+ */
36
+ static injectInvisibleMarkers(content, marker = 'autocore') {
37
+ const hasher = createHash('sha256');
38
+ hasher.update(marker + content.length);
39
+ const hash = hasher.digest('hex').substring(0, 8);
40
+ // Inserir caracteres zero-width no começo e fim
41
+ const invisiblePrefix = HoneypotManager.zeroWidthChars.repeat(2) +
42
+ hash
43
+ .split('')
44
+ .map((c) => c === '0'
45
+ ? '\u200B'
46
+ : c === '1'
47
+ ? '\u200C'
48
+ : c === '2'
49
+ ? '\u200D'
50
+ : '\uFEFF')
51
+ .join('');
52
+ const invisibleSuffix = HoneypotManager.zeroWidthChars;
53
+ return invisiblePrefix + content + invisibleSuffix;
54
+ }
55
+ /**
56
+ * Cria source maps com metadados de proteção
57
+ */
58
+ static injectSourceMapProtection(sourceMapContent) {
59
+ try {
60
+ const sourceMap = JSON.parse(sourceMapContent);
61
+ sourceMap['x-rbqa-token'] = randomBytes(16).toString('hex');
62
+ sourceMap['x-rbqa-checksum'] = createHash('sha256')
63
+ .update(sourceMapContent)
64
+ .digest('hex')
65
+ .substring(0, 16);
66
+ sourceMap['x-rbqa-timestamp'] = Date.now();
67
+ return JSON.stringify(sourceMap);
68
+ }
69
+ catch {
70
+ return sourceMapContent;
71
+ }
72
+ }
73
+ /**
74
+ * Cria arquivos honeypot dinâmicos em diretórios temporários
75
+ */
76
+ static createDynamicHoneypots(baseDir) {
77
+ const tempDirs = ['.tmp', '.cache', '.build', '.generated'];
78
+ for (const dir of tempDirs) {
79
+ const fullPath = join(baseDir, dir);
80
+ try {
81
+ mkdirSync(fullPath, { recursive: true });
82
+ // Criar arquivo TypeScript honeypot
83
+ const tsHoneypot = HoneypotManager.generateTsHoneypot(`${dir}Helper`);
84
+ writeFileSync(join(fullPath, 'helper.ts'), tsHoneypot);
85
+ // Criar arquivo JSON honeypot (config falso)
86
+ const jsonHoneypot = HoneypotManager.generateJsonHoneypot();
87
+ writeFileSync(join(fullPath, 'config.json'), jsonHoneypot);
88
+ }
89
+ catch {
90
+ // falha silenciosa
91
+ }
92
+ }
93
+ }
94
+ /**
95
+ * Gera honeypot TypeScript com aparência legítima
96
+ */
97
+ static generateTsHoneypot(className) {
98
+ const invisibleMarker = HoneypotManager.zeroWidthChars;
99
+ return `${invisibleMarker}/**
100
+ * ${className}: Utilitário para operações auxiliares
101
+ * Parte do sistema de build automatizado
102
+ */
103
+
104
+ export interface ${className}Config {
105
+ timeout: number
106
+ retries: number
107
+ debug: boolean
108
+ }
109
+
110
+ export class ${className} {
111
+ private config: ${className}Config
112
+
113
+ constructor(config: Partial<${className}Config> = {}) {
114
+ // Detectar uso - marca degradação
115
+ HoneypotManager.tripHoneypot('${className}')
116
+
117
+ this.config = {
118
+ timeout: 5000,
119
+ retries: 3,
120
+ debug: false,
121
+ ...config
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Executa operação auxiliar
127
+ * @param operation Operação a executar
128
+ */
129
+ async execute(operation: string): Promise<any> {
130
+ HoneypotManager.tripHoneypot('${className}.execute')
131
+ return null
132
+ }
133
+
134
+ /**
135
+ * Valida configuração
136
+ */
137
+ validate(): boolean {
138
+ HoneypotManager.tripHoneypot('${className}.validate')
139
+ return false
140
+ }
141
+ }
142
+
143
+ // Detectar qualquer importação deste módulo
144
+ if (typeof process !== 'undefined') {
145
+ process.env.AUTOCORE_HONEYPOT_TRIPPED = 'true'
146
+ process.env.AUTOCORE_HONEYPOT_SOURCE = '${className}'
147
+ }
148
+
149
+ export default ${className}
150
+ ${invisibleMarker}`;
151
+ }
152
+ /**
153
+ * Gera honeypot JSON com configurações falsas mas realistas
154
+ */
155
+ static generateJsonHoneypot() {
156
+ const config = {
157
+ name: 'autocore-config',
158
+ version: '1.0.0',
159
+ automation: {
160
+ enabled: true,
161
+ timeout: 30_000,
162
+ retries: 5,
163
+ endpoints: [
164
+ 'http://localhost:3000/api/test',
165
+ 'http://localhost:4000/mock',
166
+ ],
167
+ },
168
+ testing: {
169
+ framework: 'playwright',
170
+ browser: 'chromium',
171
+ headless: true,
172
+ viewport: { width: 1920, height: 1080 },
173
+ },
174
+ reporting: {
175
+ format: 'json',
176
+ output: './reports/',
177
+ includeLogs: true,
178
+ },
179
+ // Metadados de proteção invisíveis
180
+ _rbqa_marker: randomBytes(8).toString('hex'),
181
+ _protection_enabled: true,
182
+ _honeypot_id: randomBytes(4).toString('hex'),
183
+ };
184
+ return JSON.stringify(config, null, 2);
185
+ }
186
+ /**
187
+ * Verifica integridade de arquivos protegidos
188
+ */
189
+ static verifyFileIntegrity(filePath) {
190
+ try {
191
+ if (!existsSync(filePath))
192
+ return false;
193
+ // Skip verificação para arquivos de configuração comuns em desenvolvimento
194
+ const fileName = filePath.toLowerCase();
195
+ if (fileName.includes('package.json') ||
196
+ fileName.includes('tsconfig.json') ||
197
+ fileName.includes('.gitignore') ||
198
+ fileName.includes('node_modules')) {
199
+ return true; // Permitir modificações em arquivos de config
200
+ }
201
+ const content = readFileSync(filePath, 'utf8');
202
+ // Verificar marcadores invisíveis
203
+ const hasMarkers = HoneypotManager.zeroWidthChars
204
+ .split('')
205
+ .some((char) => content.includes(char));
206
+ if (!hasMarkers) {
207
+ HoneypotManager.tripHoneypot(`file_integrity_${filePath}`);
208
+ return false;
209
+ }
210
+ return true;
211
+ }
212
+ catch {
213
+ return false;
214
+ }
215
+ }
216
+ /**
217
+ * Cria método isento que força degradação quando chamado
218
+ */
219
+ static createPoisonMethod(methodName) {
220
+ return (...args) => {
221
+ HoneypotManager.tripHoneypot(`poison_method_${methodName}`);
222
+ // Retornar valor que parece normal mas marca degradação
223
+ if (methodName.includes('test') || methodName.includes('expect')) {
224
+ return { pass: false, message: () => 'Teste falhou' };
225
+ }
226
+ return null;
227
+ };
228
+ }
229
+ }
230
+ // Auto-registro para detecção de importação
231
+ if (typeof process !== 'undefined') {
232
+ process.env.AUTOCORE_HONEYPOT_MANAGER_LOADED = 'true';
233
+ }
234
+ export default HoneypotManager;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * AutoCore Keys Manager: Geração e validação de chaves locais
3
+ * Sistema de chaves únicas por instalação para autenticação offline
4
+ */
5
+ type InstallationKeys = {
6
+ installId: string;
7
+ publicKey: string;
8
+ privateKey: string;
9
+ timestamp: string;
10
+ hostname: string;
11
+ };
12
+ /**
13
+ * Cria chaves de instalação se não existirem
14
+ */
15
+ export declare function ensureInstallationKeys(): InstallationKeys;
16
+ /**
17
+ * Valida se as chaves estão presentes e válidas
18
+ */
19
+ export declare function validateInstallationKeys(): boolean;
20
+ /**
21
+ * Obtém ID de instalação atual
22
+ */
23
+ export declare function getInstallationId(): string | null;
24
+ /**
25
+ * Remove chaves (para limpeza)
26
+ */
27
+ export declare function removeInstallationKeys(): void;
28
+ /**
29
+ * Assina dados com chave privada da instalação
30
+ */
31
+ export declare function signWithInstallationKey(data: string): string | null;
32
+ /**
33
+ * Verifica assinatura com chave pública
34
+ */
35
+ export declare function verifyInstallationSignature(data: string, signature: string, publicKey?: string): boolean;
36
+ export {};
@@ -0,0 +1,158 @@
1
+ /**
2
+ * AutoCore Keys Manager: Geração e validação de chaves locais
3
+ * Sistema de chaves únicas por instalação para autenticação offline
4
+ */
5
+ import { createHash, generateKeyPairSync, randomBytes, sign, verify, } from 'node:crypto';
6
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync, } from 'node:fs';
7
+ import { homedir, hostname } from 'node:os';
8
+ import { join } from 'node:path';
9
+ const KEYS_DIR_NAME = '.rbqa';
10
+ const KEYS_SUBDIR = 'keys';
11
+ const KEYPAIR_FILE = 'autocore.key';
12
+ const INSTALL_ID_FILE = 'install.id';
13
+ /**
14
+ * Obtém diretório de chaves do usuário
15
+ */
16
+ function getKeysDirectory() {
17
+ const home = homedir();
18
+ return join(home, KEYS_DIR_NAME, KEYS_SUBDIR);
19
+ }
20
+ /**
21
+ * Gera ID único de instalação
22
+ */
23
+ function generateInstallId() {
24
+ const timestamp = Date.now().toString(36);
25
+ const random = randomBytes(16).toString('hex');
26
+ const machine = hostname() || 'unknown';
27
+ return createHash('sha256')
28
+ .update(`${timestamp}:${random}:${machine}`)
29
+ .digest('hex')
30
+ .substring(0, 32);
31
+ }
32
+ /**
33
+ * Gera par de chaves ECDSA
34
+ */
35
+ function generateKeyPair() {
36
+ const { publicKey, privateKey } = generateKeyPairSync('ec', {
37
+ namedCurve: 'secp256k1',
38
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
39
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
40
+ });
41
+ return { publicKey, privateKey };
42
+ }
43
+ /**
44
+ * Cria chaves de instalação se não existirem
45
+ */
46
+ export function ensureInstallationKeys() {
47
+ const keysDir = getKeysDirectory();
48
+ const keyFile = join(keysDir, KEYPAIR_FILE);
49
+ const idFile = join(keysDir, INSTALL_ID_FILE);
50
+ // Verificar se já existem
51
+ if (existsSync(keyFile) && existsSync(idFile)) {
52
+ try {
53
+ const keys = JSON.parse(readFileSync(keyFile, 'utf8'));
54
+ const storedId = readFileSync(idFile, 'utf8').trim();
55
+ if (keys.installId === storedId) {
56
+ return keys;
57
+ }
58
+ }
59
+ catch {
60
+ // Falha na leitura, regeramos
61
+ }
62
+ }
63
+ // Criar diretório se não existir
64
+ if (!existsSync(keysDir)) {
65
+ mkdirSync(keysDir, { recursive: true });
66
+ }
67
+ // Gerar novas chaves
68
+ const installId = generateInstallId();
69
+ const { publicKey, privateKey } = generateKeyPair();
70
+ const hostName = hostname() || 'unknown';
71
+ const keys = {
72
+ installId,
73
+ publicKey,
74
+ privateKey,
75
+ timestamp: new Date().toISOString(),
76
+ hostname: hostName,
77
+ };
78
+ // Salvar chaves
79
+ writeFileSync(keyFile, JSON.stringify(keys, null, 2), { mode: 0o600 });
80
+ writeFileSync(idFile, installId, { mode: 0o600 });
81
+ return keys;
82
+ }
83
+ /**
84
+ * Valida se as chaves estão presentes e válidas
85
+ */
86
+ export function validateInstallationKeys() {
87
+ try {
88
+ const keys = ensureInstallationKeys();
89
+ return Boolean(keys.installId &&
90
+ keys.publicKey &&
91
+ keys.privateKey &&
92
+ keys.installId.length === 32);
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ }
98
+ /**
99
+ * Obtém ID de instalação atual
100
+ */
101
+ export function getInstallationId() {
102
+ try {
103
+ const keys = ensureInstallationKeys();
104
+ return keys.installId;
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ /**
111
+ * Remove chaves (para limpeza)
112
+ */
113
+ export function removeInstallationKeys() {
114
+ const keysDir = getKeysDirectory();
115
+ const keyFile = join(keysDir, KEYPAIR_FILE);
116
+ const idFile = join(keysDir, INSTALL_ID_FILE);
117
+ try {
118
+ unlinkSync(keyFile);
119
+ }
120
+ catch {
121
+ // ignorar se não existir
122
+ }
123
+ try {
124
+ unlinkSync(idFile);
125
+ }
126
+ catch {
127
+ // ignorar se não existir
128
+ }
129
+ }
130
+ /**
131
+ * Assina dados com chave privada da instalação
132
+ */
133
+ export function signWithInstallationKey(data) {
134
+ try {
135
+ const keys = ensureInstallationKeys();
136
+ const signature = sign('sha256', Buffer.from(data), {
137
+ key: keys.privateKey,
138
+ format: 'pem',
139
+ });
140
+ return signature.toString('base64');
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
146
+ /**
147
+ * Verifica assinatura com chave pública
148
+ */
149
+ export function verifyInstallationSignature(data, signature, publicKey) {
150
+ try {
151
+ const keys = ensureInstallationKeys();
152
+ const pubKey = publicKey || keys.publicKey;
153
+ return verify('sha256', Buffer.from(data), { key: pubKey, format: 'pem' }, Buffer.from(signature, 'base64'));
154
+ }
155
+ catch {
156
+ return false;
157
+ }
158
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * ProofOfWorkIntegration: Integração de proof-of-work em métodos críticos
3
+ * Adiciona custos computacionais para desencorajar automação massiva
4
+ */
5
+ export interface ProofOfWorkChallenge {
6
+ difficulty: number;
7
+ nonce: string;
8
+ timestamp: number;
9
+ solution?: string;
10
+ }
11
+ export declare class ProofOfWorkIntegration {
12
+ private static readonly DEFAULT_DIFFICULTY;
13
+ private static readonly MAX_SOLVE_TIME;
14
+ private static challenges;
15
+ /**
16
+ * Gera desafio proof-of-work
17
+ */
18
+ static generateChallenge(identifier: string, difficulty?: number): ProofOfWorkChallenge;
19
+ /**
20
+ * Resolve desafio proof-of-work
21
+ */
22
+ static solveChallenge(identifier: string, maxTime?: number): Promise<string | null>;
23
+ /**
24
+ * Verifica se uma solução é válida
25
+ */
26
+ static verifySolution(identifier: string, solution: string): boolean;
27
+ /**
28
+ * Wrapper para métodos críticos que requer proof-of-work
29
+ */
30
+ static protectMethod<T extends (...args: any[]) => any>(originalMethod: T, methodName: string, difficulty?: number): T;
31
+ /**
32
+ * Decorator para proteção automática de métodos
33
+ */
34
+ static ProofOfWork(difficulty?: number): (target: any, propertyName: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
35
+ /**
36
+ * Proteção para APIs críticas do Playwright
37
+ */
38
+ static protectPlaywrightAPIs(): void;
39
+ /**
40
+ * Proteção para APIs críticas do WebDriver
41
+ */
42
+ static protectWebDriverAPIs(): void;
43
+ /**
44
+ * Aplicar proteção automática em APIs críticas
45
+ */
46
+ static autoProtectCriticalAPIs(): void;
47
+ /**
48
+ * Proteger métodos críticos do framework
49
+ */
50
+ private static protectFrameworkMethods;
51
+ /**
52
+ * Gera nonce aleatório
53
+ */
54
+ private static generateNonce;
55
+ /**
56
+ * Verifica se hash satisfaz dificuldade
57
+ */
58
+ private static isValidSolution;
59
+ /**
60
+ * Limpa desafios antigos
61
+ */
62
+ static cleanupOldChallenges(): void;
63
+ }
64
+ export default ProofOfWorkIntegration;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * ProofOfWorkIntegration: Integração de proof-of-work em métodos críticos
3
+ * Adiciona custos computacionais para desencorajar automação massiva
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import { HoneypotManager } from './HoneypotManager.js';
7
+ import { Logger } from '../utils/Logger.js';
8
+ export class ProofOfWorkIntegration {
9
+ static DEFAULT_DIFFICULTY = 4; // Ajustável baseado na performance
10
+ static MAX_SOLVE_TIME = 5000; // 5 segundos máximo
11
+ static challenges = new Map();
12
+ /**
13
+ * Gera desafio proof-of-work
14
+ */
15
+ static generateChallenge(identifier, difficulty) {
16
+ const challenge = {
17
+ difficulty: difficulty || ProofOfWorkIntegration.DEFAULT_DIFFICULTY,
18
+ nonce: ProofOfWorkIntegration.generateNonce(),
19
+ timestamp: Date.now(),
20
+ };
21
+ ProofOfWorkIntegration.challenges.set(identifier, challenge);
22
+ return challenge;
23
+ }
24
+ /**
25
+ * Resolve desafio proof-of-work
26
+ */
27
+ static async solveChallenge(identifier, maxTime) {
28
+ const challenge = ProofOfWorkIntegration.challenges.get(identifier);
29
+ if (!challenge)
30
+ return null;
31
+ const startTime = Date.now();
32
+ const timeLimit = maxTime || ProofOfWorkIntegration.MAX_SOLVE_TIME;
33
+ let counter = 0;
34
+ while (Date.now() - startTime < timeLimit) {
35
+ const attempt = `${challenge.nonce}:${counter}`;
36
+ const hash = createHash('sha256').update(attempt).digest('hex');
37
+ if (ProofOfWorkIntegration.isValidSolution(hash, challenge.difficulty)) {
38
+ challenge.solution = attempt;
39
+ return attempt;
40
+ }
41
+ counter++;
42
+ // Yield periodicamente para não bloquear
43
+ if (counter % 1000 === 0) {
44
+ await new Promise((resolve) => setImmediate(resolve));
45
+ }
46
+ }
47
+ // Timeout - marcar como possível automação
48
+ HoneypotManager.tripHoneypot(`pow_timeout_${identifier}`);
49
+ return null;
50
+ }
51
+ /**
52
+ * Verifica se uma solução é válida
53
+ */
54
+ static verifySolution(identifier, solution) {
55
+ const challenge = ProofOfWorkIntegration.challenges.get(identifier);
56
+ if (!challenge)
57
+ return false;
58
+ const hash = createHash('sha256').update(solution).digest('hex');
59
+ const isValid = ProofOfWorkIntegration.isValidSolution(hash, challenge.difficulty);
60
+ if (!isValid) {
61
+ HoneypotManager.tripHoneypot(`pow_invalid_${identifier}`);
62
+ }
63
+ return isValid;
64
+ }
65
+ /**
66
+ * Wrapper para métodos críticos que requer proof-of-work
67
+ */
68
+ static protectMethod(originalMethod, methodName, difficulty) {
69
+ return (async (...args) => {
70
+ // Verificar se honeypot já foi ativado
71
+ if (HoneypotManager.isTripped()) {
72
+ Logger.warning(`⚠️ AutoCore: Método ${methodName} bloqueado - honeypot ativo`);
73
+ return null;
74
+ }
75
+ // Gerar e resolver desafio
76
+ const challenge = ProofOfWorkIntegration.generateChallenge(methodName, difficulty);
77
+ const solution = await ProofOfWorkIntegration.solveChallenge(methodName);
78
+ if (!solution) {
79
+ Logger.warning(`⚠️ AutoCore: Proof-of-work falhou para ${methodName}`);
80
+ HoneypotManager.tripHoneypot(`pow_failed_${methodName}`);
81
+ return null;
82
+ }
83
+ // Verificar solução
84
+ if (!ProofOfWorkIntegration.verifySolution(methodName, solution)) {
85
+ Logger.warning(`⚠️ AutoCore: Solução inválida para ${methodName}`);
86
+ return null;
87
+ }
88
+ // Executar método original
89
+ return originalMethod.apply(ProofOfWorkIntegration, args);
90
+ });
91
+ }
92
+ /**
93
+ * Decorator para proteção automática de métodos
94
+ */
95
+ static ProofOfWork(difficulty) {
96
+ return (target, propertyName, descriptor) => {
97
+ const originalMethod = descriptor.value;
98
+ descriptor.value = ProofOfWorkIntegration.protectMethod(originalMethod, `${target.constructor.name}.${propertyName}`, difficulty);
99
+ return descriptor;
100
+ };
101
+ }
102
+ /**
103
+ * Proteção para APIs críticas do Playwright
104
+ */
105
+ static protectPlaywrightAPIs() {
106
+ try {
107
+ // Proteger métodos críticos se Playwright estiver disponível
108
+ const playwright = require('playwright');
109
+ if (playwright?.chromium?.launch) {
110
+ const originalLaunch = playwright.chromium.launch;
111
+ playwright.chromium.launch = ProofOfWorkIntegration.protectMethod(originalLaunch.bind(playwright.chromium), 'playwright.chromium.launch', 3);
112
+ }
113
+ if (playwright?.firefox?.launch) {
114
+ const originalLaunch = playwright.firefox.launch;
115
+ playwright.firefox.launch = ProofOfWorkIntegration.protectMethod(originalLaunch.bind(playwright.firefox), 'playwright.firefox.launch', 3);
116
+ }
117
+ Logger.info('AutoCore: APIs Playwright protegidas com proof-of-work');
118
+ }
119
+ catch {
120
+ // Playwright não disponível - ok
121
+ }
122
+ }
123
+ /**
124
+ * Proteção para APIs críticas do WebDriver
125
+ */
126
+ static protectWebDriverAPIs() {
127
+ try {
128
+ // Proteger selenium-webdriver se disponível
129
+ const webdriver = require('selenium-webdriver');
130
+ if (webdriver?.Builder) {
131
+ const originalBuild = webdriver.Builder.prototype.build;
132
+ webdriver.Builder.prototype.build =
133
+ ProofOfWorkIntegration.protectMethod(originalBuild, 'webdriver.Builder.build', 3);
134
+ }
135
+ Logger.info('AutoCore: APIs WebDriver protegidas com proof-of-work');
136
+ }
137
+ catch {
138
+ // WebDriver não disponível - ok
139
+ }
140
+ }
141
+ /**
142
+ * Aplicar proteção automática em APIs críticas
143
+ */
144
+ static autoProtectCriticalAPIs() {
145
+ if (process.env.AUTOCORE_POW_DISABLED === 'true')
146
+ return;
147
+ ProofOfWorkIntegration.protectPlaywrightAPIs();
148
+ ProofOfWorkIntegration.protectWebDriverAPIs();
149
+ // Proteger métodos do próprio framework
150
+ ProofOfWorkIntegration.protectFrameworkMethods();
151
+ }
152
+ /**
153
+ * Proteger métodos críticos do framework
154
+ */
155
+ static protectFrameworkMethods() {
156
+ try {
157
+ // Proteger métodos de Actions se disponível
158
+ const actions = require('../playwright/Actions.js');
159
+ if (actions?.Actions) {
160
+ const criticalMethods = ['click', 'fill', 'goto', 'waitForSelector'];
161
+ for (const methodName of criticalMethods) {
162
+ if (typeof actions.Actions.prototype[methodName] === 'function') {
163
+ const originalMethod = actions.Actions.prototype[methodName];
164
+ actions.Actions.prototype[methodName] =
165
+ ProofOfWorkIntegration.protectMethod(originalMethod, `Actions.${methodName}`, 2);
166
+ }
167
+ }
168
+ }
169
+ }
170
+ catch {
171
+ // Métodos não disponíveis - ok
172
+ }
173
+ }
174
+ /**
175
+ * Gera nonce aleatório
176
+ */
177
+ static generateNonce() {
178
+ return (Math.random().toString(36).substring(2, 15) +
179
+ Math.random().toString(36).substring(2, 15));
180
+ }
181
+ /**
182
+ * Verifica se hash satisfaz dificuldade
183
+ */
184
+ static isValidSolution(hash, difficulty) {
185
+ return hash.substring(0, difficulty) === '0'.repeat(difficulty);
186
+ }
187
+ /**
188
+ * Limpa desafios antigos
189
+ */
190
+ static cleanupOldChallenges() {
191
+ const now = Date.now();
192
+ const maxAge = 60_000; // 1 minuto
193
+ for (const [key, challenge,] of ProofOfWorkIntegration.challenges.entries()) {
194
+ if (now - challenge.timestamp > maxAge) {
195
+ ProofOfWorkIntegration.challenges.delete(key);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ // Auto-proteção na importação
201
+ ProofOfWorkIntegration.autoProtectCriticalAPIs();
202
+ // Cleanup periódico
203
+ setInterval(() => {
204
+ ProofOfWorkIntegration.cleanupOldChallenges();
205
+ }, 30_000); // A cada 30 segundos
206
+ export default ProofOfWorkIntegration;