@houtini/lm 1.0.13 → 2.0.1

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 (264) hide show
  1. package/README.md +67 -237
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.js +149 -213
  4. package/dist/index.js.map +1 -1
  5. package/package.json +23 -32
  6. package/server.json +44 -0
  7. package/CHANGELOG.md +0 -282
  8. package/dist/cache/analysis-cache.d.ts +0 -33
  9. package/dist/cache/analysis-cache.d.ts.map +0 -1
  10. package/dist/cache/analysis-cache.js +0 -56
  11. package/dist/cache/analysis-cache.js.map +0 -1
  12. package/dist/cache/cache-manager.d.ts +0 -29
  13. package/dist/cache/cache-manager.d.ts.map +0 -1
  14. package/dist/cache/cache-manager.js +0 -85
  15. package/dist/cache/cache-manager.js.map +0 -1
  16. package/dist/cache/index.d.ts +0 -16
  17. package/dist/cache/index.d.ts.map +0 -1
  18. package/dist/cache/index.js +0 -17
  19. package/dist/cache/index.js.map +0 -1
  20. package/dist/cache/prompt-cache.d.ts +0 -33
  21. package/dist/cache/prompt-cache.d.ts.map +0 -1
  22. package/dist/cache/prompt-cache.js +0 -61
  23. package/dist/cache/prompt-cache.js.map +0 -1
  24. package/dist/config.d.ts +0 -41
  25. package/dist/config.d.ts.map +0 -1
  26. package/dist/config.js +0 -71
  27. package/dist/config.js.map +0 -1
  28. package/dist/core/ThreeStagePromptManager.d.ts +0 -23
  29. package/dist/core/ThreeStagePromptManager.d.ts.map +0 -1
  30. package/dist/core/ThreeStagePromptManager.js +0 -118
  31. package/dist/core/ThreeStagePromptManager.js.map +0 -1
  32. package/dist/index.d.ts.map +0 -1
  33. package/dist/plugins/base-plugin.d.ts +0 -55
  34. package/dist/plugins/base-plugin.d.ts.map +0 -1
  35. package/dist/plugins/base-plugin.js +0 -120
  36. package/dist/plugins/base-plugin.js.map +0 -1
  37. package/dist/plugins/index.d.ts +0 -58
  38. package/dist/plugins/index.d.ts.map +0 -1
  39. package/dist/plugins/index.js +0 -162
  40. package/dist/plugins/index.js.map +0 -1
  41. package/dist/plugins/types.d.ts +0 -5
  42. package/dist/plugins/types.d.ts.map +0 -1
  43. package/dist/plugins/types.js +0 -5
  44. package/dist/plugins/types.js.map +0 -1
  45. package/dist/prompts/analyze/code-quality.d.ts +0 -116
  46. package/dist/prompts/analyze/code-quality.d.ts.map +0 -1
  47. package/dist/prompts/analyze/code-quality.js +0 -437
  48. package/dist/prompts/analyze/code-quality.js.map +0 -1
  49. package/dist/prompts/analyze/compare-integration.d.ts +0 -130
  50. package/dist/prompts/analyze/compare-integration.d.ts.map +0 -1
  51. package/dist/prompts/analyze/compare-integration.js +0 -547
  52. package/dist/prompts/analyze/compare-integration.js.map +0 -1
  53. package/dist/prompts/analyze/count-files.d.ts +0 -109
  54. package/dist/prompts/analyze/count-files.d.ts.map +0 -1
  55. package/dist/prompts/analyze/count-files.js +0 -403
  56. package/dist/prompts/analyze/count-files.js.map +0 -1
  57. package/dist/prompts/analyze/database-queries.d.ts +0 -156
  58. package/dist/prompts/analyze/database-queries.d.ts.map +0 -1
  59. package/dist/prompts/analyze/database-queries.js +0 -763
  60. package/dist/prompts/analyze/database-queries.js.map +0 -1
  61. package/dist/prompts/analyze/dependencies.d.ts +0 -97
  62. package/dist/prompts/analyze/dependencies.d.ts.map +0 -1
  63. package/dist/prompts/analyze/dependencies.js +0 -337
  64. package/dist/prompts/analyze/dependencies.js.map +0 -1
  65. package/dist/prompts/analyze/diff-signatures.d.ts +0 -139
  66. package/dist/prompts/analyze/diff-signatures.d.ts.map +0 -1
  67. package/dist/prompts/analyze/diff-signatures.js +0 -708
  68. package/dist/prompts/analyze/diff-signatures.js.map +0 -1
  69. package/dist/prompts/analyze/find-patterns.d.ts +0 -128
  70. package/dist/prompts/analyze/find-patterns.d.ts.map +0 -1
  71. package/dist/prompts/analyze/find-patterns.js +0 -524
  72. package/dist/prompts/analyze/find-patterns.js.map +0 -1
  73. package/dist/prompts/analyze/find-unused-css.d.ts +0 -151
  74. package/dist/prompts/analyze/find-unused-css.d.ts.map +0 -1
  75. package/dist/prompts/analyze/find-unused-css.js +0 -760
  76. package/dist/prompts/analyze/find-unused-css.js.map +0 -1
  77. package/dist/prompts/analyze/n8n-workflow.d.ts +0 -137
  78. package/dist/prompts/analyze/n8n-workflow.d.ts.map +0 -1
  79. package/dist/prompts/analyze/n8n-workflow.js +0 -533
  80. package/dist/prompts/analyze/n8n-workflow.js.map +0 -1
  81. package/dist/prompts/analyze/project-structure.d.ts +0 -126
  82. package/dist/prompts/analyze/project-structure.d.ts.map +0 -1
  83. package/dist/prompts/analyze/project-structure.js +0 -573
  84. package/dist/prompts/analyze/project-structure.js.map +0 -1
  85. package/dist/prompts/analyze/security-audit.d.ts +0 -142
  86. package/dist/prompts/analyze/security-audit.d.ts.map +0 -1
  87. package/dist/prompts/analyze/security-audit.js +0 -641
  88. package/dist/prompts/analyze/security-audit.js.map +0 -1
  89. package/dist/prompts/analyze/single-file.d.ts +0 -162
  90. package/dist/prompts/analyze/single-file.d.ts.map +0 -1
  91. package/dist/prompts/analyze/single-file.js +0 -669
  92. package/dist/prompts/analyze/single-file.js.map +0 -1
  93. package/dist/prompts/analyze/trace-execution.d.ts +0 -126
  94. package/dist/prompts/analyze/trace-execution.d.ts.map +0 -1
  95. package/dist/prompts/analyze/trace-execution.js +0 -613
  96. package/dist/prompts/analyze/trace-execution.js.map +0 -1
  97. package/dist/prompts/analyze/wordpress-plugin-audit.d.ts +0 -116
  98. package/dist/prompts/analyze/wordpress-plugin-audit.d.ts.map +0 -1
  99. package/dist/prompts/analyze/wordpress-plugin-audit.js +0 -456
  100. package/dist/prompts/analyze/wordpress-plugin-audit.js.map +0 -1
  101. package/dist/prompts/analyze/wordpress-plugin-readiness.d.ts +0 -103
  102. package/dist/prompts/analyze/wordpress-plugin-readiness.d.ts.map +0 -1
  103. package/dist/prompts/analyze/wordpress-plugin-readiness.js +0 -506
  104. package/dist/prompts/analyze/wordpress-plugin-readiness.js.map +0 -1
  105. package/dist/prompts/analyze/wordpress-security.d.ts +0 -146
  106. package/dist/prompts/analyze/wordpress-security.d.ts.map +0 -1
  107. package/dist/prompts/analyze/wordpress-security.js +0 -702
  108. package/dist/prompts/analyze/wordpress-security.js.map +0 -1
  109. package/dist/prompts/analyze/wordpress-theme-audit.d.ts +0 -114
  110. package/dist/prompts/analyze/wordpress-theme-audit.d.ts.map +0 -1
  111. package/dist/prompts/analyze/wordpress-theme-audit.js +0 -540
  112. package/dist/prompts/analyze/wordpress-theme-audit.js.map +0 -1
  113. package/dist/prompts/custom/custom-prompt.d.ts +0 -135
  114. package/dist/prompts/custom/custom-prompt.d.ts.map +0 -1
  115. package/dist/prompts/custom/custom-prompt.js +0 -421
  116. package/dist/prompts/custom/custom-prompt.js.map +0 -1
  117. package/dist/prompts/fun/arcade-game.d.ts +0 -152
  118. package/dist/prompts/fun/arcade-game.d.ts.map +0 -1
  119. package/dist/prompts/fun/arcade-game.js +0 -657
  120. package/dist/prompts/fun/arcade-game.js.map +0 -1
  121. package/dist/prompts/fun/create_text_adventure.d.ts +0 -100
  122. package/dist/prompts/fun/create_text_adventure.d.ts.map +0 -1
  123. package/dist/prompts/fun/create_text_adventure.js +0 -401
  124. package/dist/prompts/fun/create_text_adventure.js.map +0 -1
  125. package/dist/prompts/fun/css-art-generator.d.ts +0 -168
  126. package/dist/prompts/fun/css-art-generator.d.ts.map +0 -1
  127. package/dist/prompts/fun/css-art-generator.js +0 -831
  128. package/dist/prompts/fun/css-art-generator.js.map +0 -1
  129. package/dist/prompts/generate/project-documentation.d.ts +0 -137
  130. package/dist/prompts/generate/project-documentation.d.ts.map +0 -1
  131. package/dist/prompts/generate/project-documentation.js +0 -670
  132. package/dist/prompts/generate/project-documentation.js.map +0 -1
  133. package/dist/prompts/generate/refactoring.d.ts +0 -164
  134. package/dist/prompts/generate/refactoring.d.ts.map +0 -1
  135. package/dist/prompts/generate/refactoring.js +0 -625
  136. package/dist/prompts/generate/refactoring.js.map +0 -1
  137. package/dist/prompts/generate/responsive-component.d.ts +0 -147
  138. package/dist/prompts/generate/responsive-component.d.ts.map +0 -1
  139. package/dist/prompts/generate/responsive-component.js +0 -957
  140. package/dist/prompts/generate/responsive-component.js.map +0 -1
  141. package/dist/prompts/generate/typescript-conversion.d.ts +0 -144
  142. package/dist/prompts/generate/typescript-conversion.d.ts.map +0 -1
  143. package/dist/prompts/generate/typescript-conversion.js +0 -531
  144. package/dist/prompts/generate/typescript-conversion.js.map +0 -1
  145. package/dist/prompts/generate/unit-tests.d.ts +0 -139
  146. package/dist/prompts/generate/unit-tests.d.ts.map +0 -1
  147. package/dist/prompts/generate/unit-tests.js +0 -582
  148. package/dist/prompts/generate/unit-tests.js.map +0 -1
  149. package/dist/prompts/generate/wordpress-plugin.d.ts +0 -179
  150. package/dist/prompts/generate/wordpress-plugin.d.ts.map +0 -1
  151. package/dist/prompts/generate/wordpress-plugin.js +0 -767
  152. package/dist/prompts/generate/wordpress-plugin.js.map +0 -1
  153. package/dist/prompts/generate/wordpress-theme-from-static.d.ts +0 -177
  154. package/dist/prompts/generate/wordpress-theme-from-static.d.ts.map +0 -1
  155. package/dist/prompts/generate/wordpress-theme-from-static.js +0 -699
  156. package/dist/prompts/generate/wordpress-theme-from-static.js.map +0 -1
  157. package/dist/prompts/shared/cache-manager.d.ts +0 -45
  158. package/dist/prompts/shared/cache-manager.d.ts.map +0 -1
  159. package/dist/prompts/shared/cache-manager.js +0 -129
  160. package/dist/prompts/shared/cache-manager.js.map +0 -1
  161. package/dist/prompts/shared/helpers.d.ts +0 -39
  162. package/dist/prompts/shared/helpers.d.ts.map +0 -1
  163. package/dist/prompts/shared/helpers.js +0 -151
  164. package/dist/prompts/shared/helpers.js.map +0 -1
  165. package/dist/prompts/shared/templates.d.ts +0 -35
  166. package/dist/prompts/shared/templates.d.ts.map +0 -1
  167. package/dist/prompts/shared/templates.js +0 -77
  168. package/dist/prompts/shared/templates.js.map +0 -1
  169. package/dist/prompts/shared/types.d.ts +0 -112
  170. package/dist/prompts/shared/types.d.ts.map +0 -1
  171. package/dist/prompts/shared/types.js +0 -5
  172. package/dist/prompts/shared/types.js.map +0 -1
  173. package/dist/prompts/system/find-unused-files.d.ts +0 -106
  174. package/dist/prompts/system/find-unused-files.d.ts.map +0 -1
  175. package/dist/prompts/system/find-unused-files.js +0 -357
  176. package/dist/prompts/system/find-unused-files.js.map +0 -1
  177. package/dist/security/index.d.ts +0 -39
  178. package/dist/security/index.d.ts.map +0 -1
  179. package/dist/security/index.js +0 -46
  180. package/dist/security/index.js.map +0 -1
  181. package/dist/security/integration-helpers.d.ts +0 -121
  182. package/dist/security/integration-helpers.d.ts.map +0 -1
  183. package/dist/security/integration-helpers.js +0 -190
  184. package/dist/security/integration-helpers.js.map +0 -1
  185. package/dist/security/output-encoder.d.ts +0 -94
  186. package/dist/security/output-encoder.d.ts.map +0 -1
  187. package/dist/security/output-encoder.js +0 -295
  188. package/dist/security/output-encoder.js.map +0 -1
  189. package/dist/security/prompt-injection-guard.d.ts +0 -59
  190. package/dist/security/prompt-injection-guard.d.ts.map +0 -1
  191. package/dist/security/prompt-injection-guard.js +0 -249
  192. package/dist/security/prompt-injection-guard.js.map +0 -1
  193. package/dist/security/sanitisation.d.ts +0 -67
  194. package/dist/security/sanitisation.d.ts.map +0 -1
  195. package/dist/security/sanitisation.js +0 -398
  196. package/dist/security/sanitisation.js.map +0 -1
  197. package/dist/security/security-service.d.ts +0 -103
  198. package/dist/security/security-service.d.ts.map +0 -1
  199. package/dist/security/security-service.js +0 -303
  200. package/dist/security/security-service.js.map +0 -1
  201. package/dist/security-config.d.ts +0 -45
  202. package/dist/security-config.d.ts.map +0 -1
  203. package/dist/security-config.js +0 -63
  204. package/dist/security-config.js.map +0 -1
  205. package/dist/system/function-list.d.ts +0 -61
  206. package/dist/system/function-list.d.ts.map +0 -1
  207. package/dist/system/function-list.js +0 -111
  208. package/dist/system/function-list.js.map +0 -1
  209. package/dist/system/function-registry.d.ts +0 -23
  210. package/dist/system/function-registry.d.ts.map +0 -1
  211. package/dist/system/function-registry.js +0 -136
  212. package/dist/system/function-registry.js.map +0 -1
  213. package/dist/system/health-check.d.ts +0 -33
  214. package/dist/system/health-check.d.ts.map +0 -1
  215. package/dist/system/health-check.js +0 -98
  216. package/dist/system/health-check.js.map +0 -1
  217. package/dist/system/path-resolver.d.ts +0 -55
  218. package/dist/system/path-resolver.d.ts.map +0 -1
  219. package/dist/system/path-resolver.js +0 -90
  220. package/dist/system/path-resolver.js.map +0 -1
  221. package/dist/templates/plugin-template.d.ts +0 -121
  222. package/dist/templates/plugin-template.d.ts.map +0 -1
  223. package/dist/templates/plugin-template.js +0 -454
  224. package/dist/templates/plugin-template.js.map +0 -1
  225. package/dist/types/chunking-types.d.ts +0 -88
  226. package/dist/types/chunking-types.d.ts.map +0 -1
  227. package/dist/types/chunking-types.js +0 -18
  228. package/dist/types/chunking-types.js.map +0 -1
  229. package/dist/types/prompt-stages.d.ts +0 -30
  230. package/dist/types/prompt-stages.d.ts.map +0 -1
  231. package/dist/types/prompt-stages.js +0 -6
  232. package/dist/types/prompt-stages.js.map +0 -1
  233. package/dist/types.d.ts +0 -45
  234. package/dist/types.d.ts.map +0 -1
  235. package/dist/types.js +0 -6
  236. package/dist/types.js.map +0 -1
  237. package/dist/utils/css-parser.d.ts +0 -26
  238. package/dist/utils/css-parser.d.ts.map +0 -1
  239. package/dist/utils/css-parser.js +0 -117
  240. package/dist/utils/css-parser.js.map +0 -1
  241. package/dist/utils/path-resolver.d.ts +0 -13
  242. package/dist/utils/path-resolver.d.ts.map +0 -1
  243. package/dist/utils/path-resolver.js +0 -78
  244. package/dist/utils/path-resolver.js.map +0 -1
  245. package/dist/utils/plugin-utilities.d.ts +0 -176
  246. package/dist/utils/plugin-utilities.d.ts.map +0 -1
  247. package/dist/utils/plugin-utilities.js +0 -269
  248. package/dist/utils/plugin-utilities.js.map +0 -1
  249. package/dist/utils/streamHandler.d.ts +0 -3
  250. package/dist/utils/streamHandler.d.ts.map +0 -1
  251. package/dist/utils/streamHandler.js +0 -137
  252. package/dist/utils/streamHandler.js.map +0 -1
  253. package/dist/validation/output-validator.d.ts +0 -136
  254. package/dist/validation/output-validator.d.ts.map +0 -1
  255. package/dist/validation/output-validator.js +0 -262
  256. package/dist/validation/output-validator.js.map +0 -1
  257. package/dist/validation/response-factory.d.ts +0 -44
  258. package/dist/validation/response-factory.d.ts.map +0 -1
  259. package/dist/validation/response-factory.js +0 -202
  260. package/dist/validation/response-factory.js.map +0 -1
  261. package/dist/validation/schemas.d.ts +0 -519
  262. package/dist/validation/schemas.d.ts.map +0 -1
  263. package/dist/validation/schemas.js +0 -6
  264. package/dist/validation/schemas.js.map +0 -1
@@ -1,702 +0,0 @@
1
- /**
2
- * Plugin Template - Modern v4.2 (Single Source of Truth)
3
- *
4
- * Universal template that intelligently handles both single-file and multi-file analysis
5
- * Automatically detects analysis type based on provided parameters
6
- *
7
- * Copy this template for creating any new plugin - it adapts to your needs
8
- */
9
- import { BasePlugin } from '../../plugins/base-plugin.js';
10
- import { ThreeStagePromptManager } from '../../core/ThreeStagePromptManager.js';
11
- import { withSecurity } from '../../security/integration-helpers.js';
12
- import { readFileContent } from '../shared/helpers.js';
13
- import { ModelSetup, ResponseProcessor, ParameterValidator, ErrorHandler, MultiFileAnalysis, TokenCalculator } from '../../utils/plugin-utilities.js';
14
- import { getAnalysisCache } from '../../cache/index.js';
15
- // Common Node.js modules - Use these instead of require()
16
- import { basename, extname, relative } from 'path';
17
- import { readFile, stat } from 'fs/promises';
18
- export class WordPressSecurityAnalyzer extends BasePlugin {
19
- constructor() {
20
- super();
21
- this.name = 'analyze_wordpress_security';
22
- this.category = 'analyze';
23
- this.description = 'Comprehensive WordPress security analysis for plugins, themes, and core implementations with OWASP and WordPress-specific vulnerability detection';
24
- // Universal parameter set - supports both single and multi-file scenarios
25
- this.parameters = {
26
- // Single-file parameters
27
- code: {
28
- type: 'string',
29
- description: 'The WordPress code to analyze (for single-file analysis)',
30
- required: false
31
- },
32
- filePath: {
33
- type: 'string',
34
- description: 'Path to single WordPress file to analyze',
35
- required: false
36
- },
37
- // Multi-file parameters
38
- projectPath: {
39
- type: 'string',
40
- description: 'Path to WordPress plugin/theme root (for multi-file analysis)',
41
- required: false
42
- },
43
- files: {
44
- type: 'array',
45
- description: 'Array of specific file paths (for multi-file analysis)',
46
- required: false,
47
- items: { type: 'string' }
48
- },
49
- maxDepth: {
50
- type: 'number',
51
- description: 'Maximum directory depth for multi-file discovery (1-5)',
52
- required: false,
53
- default: 3
54
- },
55
- // WordPress-specific parameters
56
- wpType: {
57
- type: 'string',
58
- description: 'WordPress component type',
59
- enum: ['plugin', 'theme', 'core', 'mu-plugin', 'dropin'],
60
- default: 'plugin',
61
- required: false
62
- },
63
- wpVersion: {
64
- type: 'string',
65
- description: 'Target WordPress version for compatibility checks',
66
- required: false,
67
- default: '6.4'
68
- },
69
- analysisDepth: {
70
- type: 'string',
71
- description: 'Level of security analysis detail',
72
- enum: ['basic', 'detailed', 'comprehensive'],
73
- default: 'detailed',
74
- required: false
75
- },
76
- analysisType: {
77
- type: 'string',
78
- description: 'Type of security analysis to perform',
79
- enum: ['owasp', 'wordpress', 'comprehensive'],
80
- default: 'comprehensive',
81
- required: false
82
- },
83
- // Security-specific parameters
84
- includeOwaspTop10: {
85
- type: 'boolean',
86
- description: 'Include OWASP Top 10 vulnerability checks',
87
- default: true,
88
- required: false
89
- },
90
- checkCapabilities: {
91
- type: 'boolean',
92
- description: 'Analyze WordPress capability and role management',
93
- default: true,
94
- required: false
95
- },
96
- auditDatabaseQueries: {
97
- type: 'boolean',
98
- description: 'Audit database queries for SQL injection vulnerabilities',
99
- default: true,
100
- required: false
101
- }
102
- };
103
- this.analysisCache = getAnalysisCache();
104
- this.multiFileAnalysis = new MultiFileAnalysis();
105
- // Cache and analysis utilities are initialized above
106
- }
107
- async execute(params, llmClient) {
108
- return await withSecurity(this, params, llmClient, async (secureParams) => {
109
- try {
110
- // 1. Auto-detect analysis mode based on parameters
111
- const analysisMode = this.detectAnalysisMode(secureParams);
112
- // 2. Validate parameters based on detected mode
113
- this.validateParameters(secureParams, analysisMode);
114
- // 3. Setup model
115
- const { model, contextLength } = await ModelSetup.getReadyModel(llmClient);
116
- // 4. Route to appropriate analysis method
117
- if (analysisMode === 'single-file') {
118
- return await this.executeSingleFileAnalysis(secureParams, model, contextLength);
119
- }
120
- else {
121
- return await this.executeMultiFileAnalysis(secureParams, model, contextLength);
122
- }
123
- }
124
- catch (error) {
125
- return ErrorHandler.createExecutionError('analyze_wordpress_security', error);
126
- }
127
- });
128
- }
129
- /**
130
- * Auto-detect whether this is single-file or multi-file analysis
131
- */
132
- detectAnalysisMode(params) {
133
- // Single-file indicators take priority
134
- if (params.code || params.filePath) {
135
- return 'single-file';
136
- }
137
- // Multi-file indicators
138
- if (params.projectPath || params.files) {
139
- return 'multi-file';
140
- }
141
- // Default to multi-file for WordPress plugin/theme analysis
142
- return 'multi-file';
143
- }
144
- /**
145
- * Validate parameters based on detected analysis mode
146
- */
147
- validateParameters(params, mode) {
148
- if (mode === 'single-file') {
149
- ParameterValidator.validateCodeOrFile(params);
150
- }
151
- else {
152
- ParameterValidator.validateProjectPath(params);
153
- ParameterValidator.validateDepth(params);
154
- }
155
- // Universal validations
156
- ParameterValidator.validateEnum(params, 'analysisType', ['owasp', 'wordpress', 'comprehensive']);
157
- ParameterValidator.validateEnum(params, 'analysisDepth', ['basic', 'detailed', 'comprehensive']);
158
- ParameterValidator.validateEnum(params, 'wpType', ['plugin', 'theme', 'core', 'mu-plugin', 'dropin']);
159
- }
160
- /**
161
- * Execute single-file analysis
162
- */
163
- async executeSingleFileAnalysis(params, model, contextLength) {
164
- // Process single file input
165
- let codeToAnalyze = params.code;
166
- if (params.filePath) {
167
- codeToAnalyze = await readFileContent(params.filePath);
168
- }
169
- // Generate prompt stages for single file
170
- const promptStages = this.getSingleFilePromptStages({
171
- ...params,
172
- code: codeToAnalyze
173
- });
174
- // Execute with appropriate method
175
- const promptManager = new ThreeStagePromptManager();
176
- const needsChunking = TokenCalculator.needsChunking(promptStages, contextLength);
177
- if (needsChunking) {
178
- const chunkSize = TokenCalculator.calculateOptimalChunkSize(promptStages, contextLength);
179
- const dataChunks = promptManager.chunkDataPayload(promptStages.dataPayload, chunkSize);
180
- const conversation = promptManager.createChunkedConversation(promptStages, dataChunks);
181
- const messages = [
182
- conversation.systemMessage,
183
- ...conversation.dataMessages,
184
- conversation.analysisMessage
185
- ];
186
- return await ResponseProcessor.executeChunked(messages, model, contextLength, 'analyze_wordpress_security', 'single');
187
- }
188
- else {
189
- return await ResponseProcessor.executeDirect(promptStages, model, contextLength, 'analyze_wordpress_security');
190
- }
191
- }
192
- /**
193
- * Execute multi-file analysis
194
- */
195
- async executeMultiFileAnalysis(params, model, contextLength) {
196
- // Discover files
197
- let filesToAnalyze = params.files ||
198
- await this.discoverRelevantFiles(params.projectPath, params.maxDepth, params.analysisType);
199
- // Perform multi-file analysis with caching
200
- const analysisResult = await this.performMultiFileAnalysis(filesToAnalyze, params, model, contextLength);
201
- // Generate prompt stages for multi-file
202
- const promptStages = this.getMultiFilePromptStages({
203
- ...params,
204
- analysisResult,
205
- fileCount: filesToAnalyze.length
206
- });
207
- // Always use chunking for multi-file
208
- const promptManager = new ThreeStagePromptManager();
209
- const chunkSize = TokenCalculator.calculateOptimalChunkSize(promptStages, contextLength);
210
- const dataChunks = promptManager.chunkDataPayload(promptStages.dataPayload, chunkSize);
211
- const conversation = promptManager.createChunkedConversation(promptStages, dataChunks);
212
- const messages = [
213
- conversation.systemMessage,
214
- ...conversation.dataMessages,
215
- conversation.analysisMessage
216
- ];
217
- return await ResponseProcessor.executeChunked(messages, model, contextLength, 'analyze_wordpress_security', 'multifile');
218
- }
219
- /**
220
- * WordPress Security Analysis - Single File Expert Prompt
221
- */
222
- getSingleFilePromptStages(params) {
223
- const { code, wpType, wpVersion, analysisDepth, analysisType, filePath } = params;
224
- const fileName = filePath ? basename(filePath) : 'WordPress file';
225
- const systemAndContext = `You are a world-class WordPress security expert with 15+ years of experience in WordPress core development, plugin security auditing, and vulnerability research. You've discovered and patched hundreds of WordPress security vulnerabilities and are intimately familiar with the WordPress Security Team's standards.
226
-
227
- **YOUR EXPERTISE:**
228
- - WordPress Core Security Architecture (hooks, capabilities, data validation)
229
- - OWASP Top 10 vulnerabilities in WordPress context
230
- - WordPress-specific attack vectors (privilege escalation, data exposure, injection attacks)
231
- - WordPress Coding Standards security requirements
232
- - Plugin Review Team security guidelines
233
- - WordFence, Sucuri, and security scanner detection patterns
234
-
235
- **ANALYSIS CONTEXT:**
236
- - WordPress Component: ${wpType}
237
- - WordPress Version: ${wpVersion}
238
- - Analysis Depth: ${analysisDepth}
239
- - Analysis Type: ${analysisType}
240
- - File: ${fileName}
241
- - OWASP Top 10: ${params.includeOwaspTop10 ? 'Enabled' : 'Disabled'}
242
- - Capability Checks: ${params.checkCapabilities ? 'Enabled' : 'Disabled'}
243
- - Database Auditing: ${params.auditDatabaseQueries ? 'Enabled' : 'Disabled'}
244
-
245
- **WORDPRESS SECURITY FOCUS AREAS:**
246
-
247
- 🔒 **Authentication & Authorization:**
248
- - wp_verify_nonce() usage and nonce validation
249
- - current_user_can() capability checks
250
- - is_user_logged_in() authentication verification
251
- - Role and capability management
252
- - Session handling and user meta security
253
-
254
- 🛡️ **Data Validation & Sanitization:**
255
- - sanitize_text_field(), sanitize_email(), sanitize_url() usage
256
- - wp_kses() and wp_kses_post() for HTML filtering
257
- - esc_html(), esc_attr(), esc_url() output escaping
258
- - wp_unslash() and stripslashes_deep() handling
259
- - Custom validation function security
260
-
261
- 💉 **SQL Injection Prevention:**
262
- - $wpdb->prepare() statement usage
263
- - Direct query vulnerabilities
264
- - Custom table operations security
265
- - Meta query and WP_Query parameter validation
266
- - Database prefix usage and table access
267
-
268
- 🌐 **Cross-Site Scripting (XSS) Prevention:**
269
- - Output escaping in templates and admin areas
270
- - AJAX handler security and validation
271
- - JavaScript variable escaping
272
- - Admin notice and error message security
273
- - Custom field and user input handling
274
-
275
- 🔐 **WordPress-Specific Vulnerabilities:**
276
- - File upload restrictions and validation
277
- - Shortcode parameter validation and escaping
278
- - Widget and customizer security
279
- - REST API endpoint authorization
280
- - Admin AJAX action security
281
- - Cron job security and scheduling
282
-
283
- **SECURITY AUDIT METHODOLOGY:**
284
- 1. **Privilege Escalation Detection**: Identify unauthorized capability bypasses
285
- 2. **Data Exposure Analysis**: Find information leakage vulnerabilities
286
- 3. **Injection Vector Mapping**: Locate all user input processing points
287
- 4. **Authentication Bypass Detection**: Check for login and nonce circumvention
288
- 5. **File Security Assessment**: Analyze upload, inclusion, and access controls`;
289
- const dataPayload = `**WORDPRESS CODE TO ANALYZE:**
290
-
291
- \`\`\`php
292
- ${code}
293
- \`\`\`
294
-
295
- ${filePath ? `\n**File Context:** ${filePath}` : ''}
296
-
297
- **SECURITY ANALYSIS INSTRUCTIONS:**
298
- Focus on WordPress-specific security patterns and vulnerabilities. Pay special attention to user input handling, capability checks, nonce validation, database queries, and output escaping.`;
299
- const outputInstructions = `**PROVIDE COMPREHENSIVE WORDPRESS SECURITY ANALYSIS:**
300
-
301
- {
302
- "securitySummary": "2-3 sentence overview of the file's security posture and most critical vulnerabilities",
303
-
304
- "criticalFindings": [
305
- {
306
- "vulnerability": "SQL Injection in Custom Query",
307
- "severity": "critical|high|medium|low",
308
- "cweId": "CWE-89",
309
- "owaspCategory": "A03:2021 – Injection",
310
- "line": 42,
311
- "codeSnippet": "SELECT * FROM wp_posts WHERE ID = $_GET['id']",
312
- "description": "Direct user input used in SQL query without sanitization",
313
- "exploit": "Attacker can inject malicious SQL: ?id=1 UNION SELECT user_pass FROM wp_users",
314
- "impact": "Complete database compromise, data theft, privilege escalation",
315
- "fix": "Use $wpdb->prepare(): $wpdb->prepare('SELECT * FROM wp_posts WHERE ID = %d', intval($_GET['id']))",
316
- "wpFunction": "$wpdb->prepare()"
317
- }
318
- ],
319
-
320
- "authenticationIssues": [
321
- {
322
- "issue": "Missing capability check",
323
- "severity": "high",
324
- "line": 67,
325
- "description": "Administrative function accessible without proper capability verification",
326
- "fix": "Add: if (!current_user_can('manage_options')) wp_die('Insufficient permissions');",
327
- "wpFunction": "current_user_can()"
328
- }
329
- ],
330
-
331
- "dataValidationIssues": [
332
- {
333
- "issue": "Unsanitized user input",
334
- "severity": "medium",
335
- "line": 23,
336
- "description": "User input stored without proper sanitization",
337
- "fix": "Use: sanitize_text_field($_POST['user_input'])",
338
- "wpFunction": "sanitize_text_field()"
339
- }
340
- ],
341
-
342
- "outputEscapingIssues": [
343
- {
344
- "issue": "Unescaped output in HTML context",
345
- "severity": "high",
346
- "line": 89,
347
- "description": "User data output without proper escaping - XSS vulnerability",
348
- "fix": "Use: echo esc_html($user_data) instead of echo $user_data",
349
- "wpFunction": "esc_html()"
350
- }
351
- ],
352
-
353
- "nonceValidationIssues": [
354
- {
355
- "issue": "Missing nonce verification",
356
- "severity": "medium",
357
- "line": 34,
358
- "description": "Form processing without CSRF protection",
359
- "fix": "Add: wp_verify_nonce($_POST['_wpnonce'], 'action_name')",
360
- "wpFunction": "wp_verify_nonce()"
361
- }
362
- ],
363
-
364
- "fileSecurityIssues": [
365
- {
366
- "issue": "Unrestricted file upload",
367
- "severity": "critical",
368
- "line": 156,
369
- "description": "File upload without type or size validation",
370
- "fix": "Validate file type with wp_check_filetype() and restrict extensions",
371
- "wpFunction": "wp_check_filetype()"
372
- }
373
- ],
374
-
375
- "wordpressSpecificIssues": [
376
- {
377
- "issue": "Direct file access not prevented",
378
- "severity": "low",
379
- "description": "PHP file missing ABSPATH check",
380
- "fix": "Add: if (!defined('ABSPATH')) exit; at the top of the file",
381
- "wpFunction": "defined('ABSPATH')"
382
- }
383
- ],
384
-
385
- "securityBestPractices": {
386
- "implemented": [
387
- "Proper hook usage",
388
- "Sanitized database queries"
389
- ],
390
- "missing": [
391
- "Input validation on all user data",
392
- "Output escaping in templates",
393
- "Capability checks on administrative functions"
394
- ]
395
- },
396
-
397
- "owaspTop10Assessment": [
398
- {
399
- "category": "A01:2021 – Broken Access Control",
400
- "status": "vulnerable|secure|needs_review",
401
- "findings": ["Missing capability checks", "Direct file access allowed"]
402
- },
403
- {
404
- "category": "A03:2021 – Injection",
405
- "status": "vulnerable|secure|needs_review",
406
- "findings": ["SQL injection in line 42", "Unsanitized input processing"]
407
- }
408
- ],
409
-
410
- "recommendedActions": {
411
- "immediate": [
412
- "Fix critical SQL injection vulnerability on line 42",
413
- "Add capability checks to administrative functions"
414
- ],
415
- "shortTerm": [
416
- "Implement comprehensive input validation",
417
- "Add output escaping throughout templates"
418
- ],
419
- "longTerm": [
420
- "Implement security code review process",
421
- "Add automated security testing"
422
- ]
423
- },
424
-
425
- "securityScore": 4,
426
- "maxSecurityScore": 10,
427
- "confidence": 0.95
428
- }
429
-
430
- **CRITICAL REQUIREMENTS:**
431
- - Focus on WordPress-specific security patterns and functions
432
- - Provide specific WordPress function recommendations (wp_verify_nonce, current_user_can, etc.)
433
- - Include CWE IDs and OWASP mappings where applicable
434
- - Give concrete, copy-paste fixes for each vulnerability
435
- - Prioritize findings by potential impact and exploitability`;
436
- return { systemAndContext, dataPayload, outputInstructions };
437
- }
438
- /**
439
- * WordPress Security Analysis - Multi-File Project Audit
440
- */
441
- getMultiFilePromptStages(params) {
442
- const { analysisResult, analysisType, analysisDepth, fileCount, wpType } = params;
443
- const systemAndContext = `You are a senior WordPress security consultant specializing in ${analysisDepth} multi-file security audits for WordPress ${wpType}s.
444
-
445
- **PROJECT SECURITY CONTEXT:**
446
- - WordPress Component: ${wpType}
447
- - Analysis Type: ${analysisType}
448
- - Analysis Depth: ${analysisDepth}
449
- - Files Analyzed: ${fileCount}
450
- - Audit Scope: Cross-file security vulnerabilities and architectural security issues
451
-
452
- **MULTI-FILE SECURITY EXPERTISE:**
453
- You excel at identifying security issues that span multiple files:
454
- - Cross-file data flow vulnerabilities
455
- - Inconsistent security implementations
456
- - Privilege escalation chains across components
457
- - Authentication bypass patterns
458
- - Data exposure through file interactions
459
- - Plugin/theme architecture security flaws`;
460
- const dataPayload = `**WORDPRESS PROJECT SECURITY ANALYSIS RESULTS:**
461
-
462
- ${JSON.stringify(analysisResult, null, 2)}`;
463
- const outputInstructions = `**PROVIDE COMPREHENSIVE PROJECT SECURITY AUDIT:**
464
-
465
- {
466
- "projectSecuritySummary": "Overall security assessment of the WordPress ${wpType} and critical cross-file vulnerabilities",
467
-
468
- "crossFileVulnerabilities": [
469
- {
470
- "type": "privilege_escalation|data_exposure|authentication_bypass|injection_chain",
471
- "severity": "critical|high|medium|low",
472
- "title": "Cross-file security issue title",
473
- "description": "How the vulnerability spans multiple files",
474
- "affectedFiles": ["file1.php", "file2.php", "file3.php"],
475
- "attackVector": "Step-by-step explanation of how an attacker would exploit this",
476
- "impact": "What an attacker could achieve",
477
- "fix": "Comprehensive fix spanning all affected files"
478
- }
479
- ],
480
-
481
- "architecturalSecurityIssues": [
482
- {
483
- "issue": "Inconsistent nonce validation",
484
- "severity": "medium",
485
- "description": "Some AJAX handlers validate nonces while others don't",
486
- "affectedFiles": ["admin.php", "ajax-handler.php"],
487
- "recommendation": "Implement consistent nonce validation across all AJAX endpoints"
488
- }
489
- ],
490
-
491
- "securityPatternAnalysis": {
492
- "authenticationPatterns": "consistent|inconsistent|missing",
493
- "authorizationPatterns": "consistent|inconsistent|missing",
494
- "dataValidationPatterns": "consistent|inconsistent|missing",
495
- "outputEscapingPatterns": "consistent|inconsistent|missing"
496
- },
497
-
498
- "overallSecurityRecommendations": {
499
- "architecture": ["Implement centralized security validation", "Add security middleware layer"],
500
- "implementation": ["Standardize nonce validation", "Implement consistent capability checks"],
501
- "monitoring": ["Add security logging", "Implement intrusion detection"]
502
- }
503
- }`;
504
- return { systemAndContext, dataPayload, outputInstructions };
505
- }
506
- /**
507
- * Backwards compatibility method
508
- */
509
- getPromptStages(params) {
510
- const mode = this.detectAnalysisMode(params);
511
- if (mode === 'single-file') {
512
- return this.getSingleFilePromptStages(params);
513
- }
514
- else {
515
- return this.getMultiFilePromptStages(params);
516
- }
517
- }
518
- // Multi-file helper methods
519
- async discoverRelevantFiles(projectPath, maxDepth, analysisType) {
520
- const extensions = this.getFileExtensions(analysisType);
521
- return await this.multiFileAnalysis.discoverFiles(projectPath, extensions, maxDepth);
522
- }
523
- async performMultiFileAnalysis(files, params, model, contextLength) {
524
- const cacheKey = this.analysisCache.generateKey('analyze_wordpress_security', params, files);
525
- const cached = await this.analysisCache.get(cacheKey);
526
- if (cached)
527
- return cached;
528
- const fileAnalysisResults = await this.multiFileAnalysis.analyzeBatch(files, (file) => this.analyzeIndividualFile(file, params, model), contextLength);
529
- // WordPress-specific aggregated analysis
530
- const aggregatedResult = {
531
- summary: `WordPress security analysis of ${files.length} files`,
532
- findings: fileAnalysisResults,
533
- securityPatterns: this.identifyWordPressSecurityPatterns(fileAnalysisResults),
534
- vulnerabilityChains: this.identifyVulnerabilityChains(fileAnalysisResults),
535
- complianceStatus: this.assessWordPressCompliance(fileAnalysisResults),
536
- data: {
537
- fileCount: files.length,
538
- phpFileCount: fileAnalysisResults.filter(f => f.extension === '.php').length,
539
- jsFileCount: fileAnalysisResults.filter(f => f.extension === '.js').length,
540
- hasMainPluginFile: fileAnalysisResults.some(f => f.fileName.endsWith('.php') && f.hasPluginHeader),
541
- hasSecurityFeatures: this.hasSecurityFeatures(fileAnalysisResults)
542
- }
543
- };
544
- await this.analysisCache.cacheAnalysis(cacheKey, aggregatedResult, {
545
- modelUsed: model.identifier || 'unknown',
546
- executionTime: Date.now() - Date.now(),
547
- timestamp: new Date().toISOString()
548
- });
549
- return aggregatedResult;
550
- }
551
- async analyzeIndividualFile(file, params, model) {
552
- const content = await readFile(file, 'utf-8');
553
- const stats = await stat(file);
554
- const fileName = basename(file);
555
- const extension = extname(file);
556
- return {
557
- filePath: file,
558
- fileName,
559
- extension,
560
- size: content.length,
561
- lines: content.split('\n').length,
562
- relativePath: relative(params.projectPath || '', file),
563
- // WordPress-specific analysis
564
- hasPluginHeader: this.hasWordPressPluginHeader(content),
565
- hasDirectAccess: content.includes('ABSPATH'),
566
- usesNonces: this.checkNonceUsage(content),
567
- usesCapabilityChecks: this.checkCapabilityUsage(content),
568
- usesSanitization: this.checkSanitizationUsage(content),
569
- usesEscaping: this.checkEscapingUsage(content),
570
- hasDatabaseQueries: this.checkDatabaseQueries(content),
571
- securityScore: this.calculateSecurityScore(content),
572
- modified: stats.mtime
573
- };
574
- }
575
- // WordPress security pattern detection methods
576
- identifyWordPressSecurityPatterns(results) {
577
- return {
578
- nonceUsage: results.filter(r => r.usesNonces).length,
579
- capabilityChecks: results.filter(r => r.usesCapabilityChecks).length,
580
- sanitizationUsage: results.filter(r => r.usesSanitization).length,
581
- escapingUsage: results.filter(r => r.usesEscaping).length,
582
- consistencyScore: this.calculateConsistencyScore(results)
583
- };
584
- }
585
- identifyVulnerabilityChains(results) {
586
- const vulnerabilities = [];
587
- // Check for common vulnerability chains
588
- const hasUnsanitizedInput = results.some(r => !r.usesSanitization);
589
- const hasUnescapedOutput = results.some(r => !r.usesEscaping);
590
- const hasMissingCapChecks = results.some(r => !r.usesCapabilityChecks);
591
- if (hasUnsanitizedInput && hasUnescapedOutput) {
592
- vulnerabilities.push('XSS vulnerability chain: unsanitized input + unescaped output');
593
- }
594
- if (hasMissingCapChecks && hasUnsanitizedInput) {
595
- vulnerabilities.push('Privilege escalation chain: missing capability checks + unsanitized input');
596
- }
597
- return vulnerabilities;
598
- }
599
- assessWordPressCompliance(results) {
600
- return {
601
- codingStandardsCompliance: this.checkCodingStandards(results),
602
- securityGuidelinesCompliance: this.checkSecurityGuidelines(results),
603
- pluginReviewRequirements: this.checkPluginReviewRequirements(results)
604
- };
605
- }
606
- hasSecurityFeatures(results) {
607
- return results.some(r => r.usesNonces || r.usesCapabilityChecks || r.usesSanitization);
608
- }
609
- // WordPress security detection helper methods
610
- hasWordPressPluginHeader(content) {
611
- return /Plugin Name:|Description:|Version:|Author:/.test(content);
612
- }
613
- checkNonceUsage(content) {
614
- return /wp_verify_nonce|wp_create_nonce|check_admin_referer/.test(content);
615
- }
616
- checkCapabilityUsage(content) {
617
- return /current_user_can|user_can|is_super_admin/.test(content);
618
- }
619
- checkSanitizationUsage(content) {
620
- return /sanitize_text_field|sanitize_email|sanitize_url|sanitize_file_name/.test(content);
621
- }
622
- checkEscapingUsage(content) {
623
- return /esc_html|esc_attr|esc_url|wp_kses/.test(content);
624
- }
625
- checkDatabaseQueries(content) {
626
- return /\$wpdb|get_posts|WP_Query|get_option/.test(content);
627
- }
628
- calculateSecurityScore(content) {
629
- let score = 0;
630
- if (this.checkNonceUsage(content))
631
- score += 2;
632
- if (this.checkCapabilityUsage(content))
633
- score += 2;
634
- if (this.checkSanitizationUsage(content))
635
- score += 2;
636
- if (this.checkEscapingUsage(content))
637
- score += 2;
638
- if (content.includes('ABSPATH'))
639
- score += 1;
640
- if (!content.includes('$_GET') && !content.includes('$_POST'))
641
- score += 1;
642
- return Math.min(score, 10);
643
- }
644
- calculateConsistencyScore(results) {
645
- if (results.length === 0)
646
- return 0;
647
- const avgSecurityScore = results.reduce((sum, r) => sum + (r.securityScore || 0), 0) / results.length;
648
- return Math.round(avgSecurityScore);
649
- }
650
- checkCodingStandards(results) {
651
- // Simplified compliance check
652
- const goodPractices = results.filter(r => r.securityScore >= 7).length;
653
- const percentage = (goodPractices / results.length) * 100;
654
- if (percentage >= 80)
655
- return 'compliant';
656
- if (percentage >= 60)
657
- return 'mostly_compliant';
658
- return 'non_compliant';
659
- }
660
- checkSecurityGuidelines(results) {
661
- const secureFiles = results.filter(r => r.usesNonces && r.usesCapabilityChecks).length;
662
- const percentage = (secureFiles / results.length) * 100;
663
- if (percentage >= 90)
664
- return 'excellent';
665
- if (percentage >= 70)
666
- return 'good';
667
- if (percentage >= 50)
668
- return 'fair';
669
- return 'poor';
670
- }
671
- checkPluginReviewRequirements(results) {
672
- const requirements = [];
673
- if (results.every(r => r.hasDirectAccess)) {
674
- requirements.push('✅ All files have direct access protection');
675
- }
676
- else {
677
- requirements.push('❌ Some files missing ABSPATH check');
678
- }
679
- if (results.some(r => r.usesNonces)) {
680
- requirements.push('✅ CSRF protection implemented');
681
- }
682
- else {
683
- requirements.push('❌ Missing CSRF protection (nonces)');
684
- }
685
- return requirements;
686
- }
687
- getFileExtensions(analysisType) {
688
- const extensionMap = {
689
- 'owasp': ['.php', '.js', '.html', '.css'], // Core web files for OWASP analysis
690
- 'wordpress': ['.php', '.js'], // WordPress-specific files
691
- 'comprehensive': ['.php', '.js', '.html', '.css', '.json', '.xml', '.htaccess'] // Complete analysis
692
- };
693
- return extensionMap[analysisType] || extensionMap.comprehensive;
694
- }
695
- generateCacheKey(files, params) {
696
- const fileHash = files.join('|');
697
- const paramHash = JSON.stringify(params);
698
- return `${fileHash}_${paramHash}`.substring(0, 64);
699
- }
700
- }
701
- export default WordPressSecurityAnalyzer;
702
- //# sourceMappingURL=wordpress-security.js.map