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