@trentapps/manager-protocol 1.1.3 → 1.2.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 (142) hide show
  1. package/README.md +164 -17
  2. package/dist/analyzers/CSSAnalyzer.d.ts +180 -8
  3. package/dist/analyzers/CSSAnalyzer.d.ts.map +1 -1
  4. package/dist/analyzers/CSSAnalyzer.js +561 -105
  5. package/dist/analyzers/CSSAnalyzer.js.map +1 -1
  6. package/dist/config/dashboard.d.ts +55 -0
  7. package/dist/config/dashboard.d.ts.map +1 -0
  8. package/dist/config/dashboard.js +103 -0
  9. package/dist/config/dashboard.js.map +1 -0
  10. package/dist/config/index.d.ts +7 -0
  11. package/dist/config/index.d.ts.map +1 -0
  12. package/dist/config/index.js +7 -0
  13. package/dist/config/index.js.map +1 -0
  14. package/dist/dashboard/httpDashboard.d.ts +100 -0
  15. package/dist/dashboard/httpDashboard.d.ts.map +1 -0
  16. package/dist/dashboard/httpDashboard.js +1276 -0
  17. package/dist/dashboard/httpDashboard.js.map +1 -0
  18. package/dist/dashboard/index.d.ts +6 -0
  19. package/dist/dashboard/index.d.ts.map +1 -0
  20. package/dist/dashboard/index.js +7 -0
  21. package/dist/dashboard/index.js.map +1 -0
  22. package/dist/engine/AuditLogger.d.ts +370 -2
  23. package/dist/engine/AuditLogger.d.ts.map +1 -1
  24. package/dist/engine/AuditLogger.js +1064 -24
  25. package/dist/engine/AuditLogger.js.map +1 -1
  26. package/dist/engine/GitHubClient.d.ts +183 -0
  27. package/dist/engine/GitHubClient.d.ts.map +1 -0
  28. package/dist/engine/GitHubClient.js +411 -0
  29. package/dist/engine/GitHubClient.js.map +1 -0
  30. package/dist/engine/RateLimiter.d.ts +5 -3
  31. package/dist/engine/RateLimiter.d.ts.map +1 -1
  32. package/dist/engine/RateLimiter.js +49 -72
  33. package/dist/engine/RateLimiter.js.map +1 -1
  34. package/dist/engine/RuleDependencyAnalyzer.d.ts +73 -0
  35. package/dist/engine/RuleDependencyAnalyzer.d.ts.map +1 -0
  36. package/dist/engine/RuleDependencyAnalyzer.js +475 -0
  37. package/dist/engine/RuleDependencyAnalyzer.js.map +1 -0
  38. package/dist/engine/RulesEngine.d.ts +102 -3
  39. package/dist/engine/RulesEngine.d.ts.map +1 -1
  40. package/dist/engine/RulesEngine.js +326 -21
  41. package/dist/engine/RulesEngine.js.map +1 -1
  42. package/dist/engine/TaskManager.d.ts +10 -14
  43. package/dist/engine/TaskManager.d.ts.map +1 -1
  44. package/dist/engine/TaskManager.js +169 -197
  45. package/dist/engine/TaskManager.js.map +1 -1
  46. package/dist/engine/index.d.ts +3 -0
  47. package/dist/engine/index.d.ts.map +1 -1
  48. package/dist/engine/index.js +5 -0
  49. package/dist/engine/index.js.map +1 -1
  50. package/dist/rules/azure.d.ts.map +1 -1
  51. package/dist/rules/azure.js +12 -14
  52. package/dist/rules/azure.js.map +1 -1
  53. package/dist/rules/compliance.d.ts.map +1 -1
  54. package/dist/rules/compliance.js +23 -41
  55. package/dist/rules/compliance.js.map +1 -1
  56. package/dist/rules/condition-optimizer.d.ts +151 -0
  57. package/dist/rules/condition-optimizer.d.ts.map +1 -0
  58. package/dist/rules/condition-optimizer.js +479 -0
  59. package/dist/rules/condition-optimizer.js.map +1 -0
  60. package/dist/rules/css.d.ts.map +1 -1
  61. package/dist/rules/css.js +538 -0
  62. package/dist/rules/css.js.map +1 -1
  63. package/dist/rules/field-standards.d.ts +1172 -0
  64. package/dist/rules/field-standards.d.ts.map +1 -0
  65. package/dist/rules/field-standards.js +908 -0
  66. package/dist/rules/field-standards.js.map +1 -0
  67. package/dist/rules/flask.d.ts.map +1 -1
  68. package/dist/rules/flask.js +18 -31
  69. package/dist/rules/flask.js.map +1 -1
  70. package/dist/rules/index.d.ts +220 -0
  71. package/dist/rules/index.d.ts.map +1 -1
  72. package/dist/rules/index.js +155 -0
  73. package/dist/rules/index.js.map +1 -1
  74. package/dist/rules/ml-ai.d.ts.map +1 -1
  75. package/dist/rules/ml-ai.js +11 -13
  76. package/dist/rules/ml-ai.js.map +1 -1
  77. package/dist/rules/patterns.d.ts +568 -0
  78. package/dist/rules/patterns.d.ts.map +1 -0
  79. package/dist/rules/patterns.js +1359 -0
  80. package/dist/rules/patterns.js.map +1 -0
  81. package/dist/rules/security.d.ts.map +1 -1
  82. package/dist/rules/security.js +580 -19
  83. package/dist/rules/security.js.map +1 -1
  84. package/dist/rules/shared-patterns.d.ts +268 -0
  85. package/dist/rules/shared-patterns.d.ts.map +1 -0
  86. package/dist/rules/shared-patterns.js +556 -0
  87. package/dist/rules/shared-patterns.js.map +1 -0
  88. package/dist/rules/storage.d.ts +8 -2
  89. package/dist/rules/storage.d.ts.map +1 -1
  90. package/dist/rules/storage.js +541 -3
  91. package/dist/rules/storage.js.map +1 -1
  92. package/dist/rules/stripe.d.ts.map +1 -1
  93. package/dist/rules/stripe.js +19 -26
  94. package/dist/rules/stripe.js.map +1 -1
  95. package/dist/rules/websocket.d.ts.map +1 -1
  96. package/dist/rules/websocket.js +32 -40
  97. package/dist/rules/websocket.js.map +1 -1
  98. package/dist/supervisor/AgentSupervisor.d.ts +52 -0
  99. package/dist/supervisor/AgentSupervisor.d.ts.map +1 -1
  100. package/dist/supervisor/AgentSupervisor.js +120 -1
  101. package/dist/supervisor/AgentSupervisor.js.map +1 -1
  102. package/dist/supervisor/ManagedServerRegistry.d.ts +139 -2
  103. package/dist/supervisor/ManagedServerRegistry.d.ts.map +1 -1
  104. package/dist/supervisor/ManagedServerRegistry.js +590 -6
  105. package/dist/supervisor/ManagedServerRegistry.js.map +1 -1
  106. package/dist/supervisor/ProjectTracker.d.ts +2 -1
  107. package/dist/supervisor/ProjectTracker.d.ts.map +1 -1
  108. package/dist/supervisor/ProjectTracker.js +5 -9
  109. package/dist/supervisor/ProjectTracker.js.map +1 -1
  110. package/dist/testing/index.d.ts +11 -0
  111. package/dist/testing/index.d.ts.map +1 -0
  112. package/dist/testing/index.js +12 -0
  113. package/dist/testing/index.js.map +1 -0
  114. package/dist/testing/rule-tester.d.ts +217 -0
  115. package/dist/testing/rule-tester.d.ts.map +1 -0
  116. package/dist/testing/rule-tester.examples.d.ts +57 -0
  117. package/dist/testing/rule-tester.examples.d.ts.map +1 -0
  118. package/dist/testing/rule-tester.examples.js +375 -0
  119. package/dist/testing/rule-tester.examples.js.map +1 -0
  120. package/dist/testing/rule-tester.js +381 -0
  121. package/dist/testing/rule-tester.js.map +1 -0
  122. package/dist/testing/rule-validator.d.ts +141 -0
  123. package/dist/testing/rule-validator.d.ts.map +1 -0
  124. package/dist/testing/rule-validator.js +640 -0
  125. package/dist/testing/rule-validator.js.map +1 -0
  126. package/dist/types/index.d.ts +265 -4
  127. package/dist/types/index.d.ts.map +1 -1
  128. package/dist/types/index.js +57 -2
  129. package/dist/types/index.js.map +1 -1
  130. package/dist/utils/index.d.ts +2 -0
  131. package/dist/utils/index.d.ts.map +1 -1
  132. package/dist/utils/index.js +2 -0
  133. package/dist/utils/index.js.map +1 -1
  134. package/dist/utils/rate-limiting.d.ts +268 -0
  135. package/dist/utils/rate-limiting.d.ts.map +1 -0
  136. package/dist/utils/rate-limiting.js +403 -0
  137. package/dist/utils/rate-limiting.js.map +1 -0
  138. package/dist/utils/shared.d.ts +306 -0
  139. package/dist/utils/shared.d.ts.map +1 -0
  140. package/dist/utils/shared.js +464 -0
  141. package/dist/utils/shared.js.map +1 -0
  142. package/package.json +3 -2
@@ -0,0 +1,1359 @@
1
+ /**
2
+ * Enterprise Agent Supervisor - Rule Pattern Builders
3
+ *
4
+ * Reusable pattern builders for creating common governance rules.
5
+ * These builders provide sensible defaults while allowing full customization.
6
+ *
7
+ * Task #31: Create Shared Library for Common Rule Patterns
8
+ */
9
+ // ============================================================================
10
+ // HELPER FUNCTIONS
11
+ // ============================================================================
12
+ /**
13
+ * Generate a unique rule ID with prefix
14
+ */
15
+ export function generateRuleId(prefix, suffix) {
16
+ const timestamp = Date.now().toString(36);
17
+ return suffix ? `${prefix}-${suffix}` : `${prefix}-${timestamp}`;
18
+ }
19
+ /**
20
+ * Merge actions, with override taking precedence
21
+ */
22
+ function mergeActions(defaultActions, overrideActions, additionalActions) {
23
+ if (overrideActions && overrideActions.length > 0) {
24
+ return [...overrideActions, ...(additionalActions || [])];
25
+ }
26
+ return [...defaultActions, ...(additionalActions || [])];
27
+ }
28
+ /**
29
+ * Merge conditions
30
+ */
31
+ function mergeConditions(defaultConditions, additionalConditions) {
32
+ return [...defaultConditions, ...(additionalConditions || [])];
33
+ }
34
+ // ============================================================================
35
+ // AUTHENTICATION RULE BUILDER
36
+ // ============================================================================
37
+ /**
38
+ * Create an authentication rule
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * const apiAuthRule = createAuthenticationRule({
43
+ * id: 'auth-api-001',
44
+ * name: 'Require API Authentication',
45
+ * categories: ['external_api', 'data_access'],
46
+ * requiredAuthTypes: ['bearer', 'api_key'],
47
+ * failureAction: 'deny'
48
+ * });
49
+ * ```
50
+ */
51
+ export function createAuthenticationRule(options) {
52
+ const { id, name, description = 'Enforces authentication requirements', enabled = true, priority = 950, riskWeight = 45, tags = ['authentication', 'security'], categories = ['external_api'], authTokenField = 'authToken', requiredAuthTypes, allowUnauthenticatedIn, failureAction = 'deny', failureMessage = 'Authentication required for this operation', additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
53
+ // Build conditions
54
+ const conditions = [];
55
+ // Category condition
56
+ if (categories.length === 1) {
57
+ conditions.push({
58
+ field: 'actionCategory',
59
+ operator: 'equals',
60
+ value: categories[0]
61
+ });
62
+ }
63
+ else if (categories.length > 1) {
64
+ conditions.push({
65
+ field: 'actionCategory',
66
+ operator: 'in',
67
+ value: categories
68
+ });
69
+ }
70
+ // Auth token existence check
71
+ conditions.push({
72
+ field: authTokenField,
73
+ operator: 'not_exists',
74
+ value: null
75
+ });
76
+ // Environment allowance
77
+ if (allowUnauthenticatedIn && allowUnauthenticatedIn.length > 0) {
78
+ conditions.push({
79
+ field: 'environment',
80
+ operator: 'not_in',
81
+ value: allowUnauthenticatedIn
82
+ });
83
+ }
84
+ // Build actions
85
+ const defaultActions = [
86
+ { type: failureAction, message: failureMessage }
87
+ ];
88
+ if (failureAction === 'deny') {
89
+ defaultActions.push({ type: 'log' });
90
+ }
91
+ return {
92
+ id,
93
+ name,
94
+ description,
95
+ type: 'security',
96
+ enabled,
97
+ priority,
98
+ conditions: mergeConditions(conditions, additionalConditions),
99
+ conditionLogic,
100
+ actions: mergeActions(defaultActions, overrideActions, additionalActions),
101
+ riskWeight,
102
+ tags: [...new Set([...tags, 'authentication'])],
103
+ metadata: {
104
+ ...metadata,
105
+ patternBuilder: 'createAuthenticationRule',
106
+ requiredAuthTypes
107
+ }
108
+ };
109
+ }
110
+ // ============================================================================
111
+ // DATA ACCESS RULE BUILDER
112
+ // ============================================================================
113
+ /**
114
+ * Create a data access rule
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const piiAccessRule = createDataAccessRule({
119
+ * id: 'data-pii-001',
120
+ * name: 'Restrict PII Access',
121
+ * dataTypes: ['pii', 'ssn', 'email'],
122
+ * allowedRoles: ['admin', 'data_officer'],
123
+ * requireJustification: true,
124
+ * bulkThreshold: 100
125
+ * });
126
+ * ```
127
+ */
128
+ export function createDataAccessRule(options) {
129
+ const { id, name, description = 'Enforces data access controls', enabled = true, priority = 920, riskWeight = 40, tags = ['data-access', 'security'], dataClassifications, dataTypes, allowedRoles, requireJustification = false, bulkThreshold: _bulkThreshold, requireEncryption = false, unauthorizedAction = 'deny', unauthorizedMessage = 'Unauthorized data access attempt', additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
130
+ const conditions = [];
131
+ // Category condition
132
+ conditions.push({
133
+ field: 'actionCategory',
134
+ operator: 'in',
135
+ value: ['data_access', 'pii_access']
136
+ });
137
+ // Data classification condition
138
+ if (dataClassifications && dataClassifications.length > 0) {
139
+ conditions.push({
140
+ field: 'dataClassification',
141
+ operator: 'in',
142
+ value: dataClassifications
143
+ });
144
+ }
145
+ // Data type condition
146
+ if (dataTypes && dataTypes.length > 0) {
147
+ if (dataTypes.length === 1) {
148
+ conditions.push({
149
+ field: 'dataType',
150
+ operator: 'equals',
151
+ value: dataTypes[0]
152
+ });
153
+ }
154
+ else {
155
+ conditions.push({
156
+ field: 'dataType',
157
+ operator: 'in',
158
+ value: dataTypes
159
+ });
160
+ }
161
+ }
162
+ // Role restriction
163
+ if (allowedRoles && allowedRoles.length > 0) {
164
+ conditions.push({
165
+ field: 'userRole',
166
+ operator: 'not_in',
167
+ value: allowedRoles
168
+ });
169
+ }
170
+ // Justification requirement
171
+ if (requireJustification) {
172
+ conditions.push({
173
+ field: 'businessJustification',
174
+ operator: 'not_exists',
175
+ value: null
176
+ });
177
+ }
178
+ // Encryption requirement
179
+ if (requireEncryption) {
180
+ conditions.push({
181
+ field: 'encryptionEnabled',
182
+ operator: 'not_equals',
183
+ value: true
184
+ });
185
+ }
186
+ // Build actions
187
+ const defaultActions = [
188
+ { type: unauthorizedAction, message: unauthorizedMessage },
189
+ { type: 'log' }
190
+ ];
191
+ const baseRule = {
192
+ id,
193
+ name,
194
+ description,
195
+ type: 'security',
196
+ enabled,
197
+ priority,
198
+ conditions: mergeConditions(conditions, additionalConditions),
199
+ conditionLogic,
200
+ actions: mergeActions(defaultActions, overrideActions, additionalActions),
201
+ riskWeight,
202
+ tags: [...new Set([...tags, 'data-access'])],
203
+ metadata: {
204
+ ...metadata,
205
+ patternBuilder: 'createDataAccessRule',
206
+ dataClassifications,
207
+ dataTypes,
208
+ allowedRoles
209
+ }
210
+ };
211
+ return baseRule;
212
+ }
213
+ /**
214
+ * Create a bulk data access rule (separate from basic data access)
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * const bulkExportRule = createBulkDataAccessRule({
219
+ * id: 'data-bulk-001',
220
+ * name: 'Bulk Export Approval',
221
+ * bulkThreshold: 1000,
222
+ * requireApproval: true
223
+ * });
224
+ * ```
225
+ */
226
+ export function createBulkDataAccessRule(options) {
227
+ const { id, name, description = 'Requires approval for bulk data operations', enabled = true, priority = 880, riskWeight = 35, tags = ['bulk-operations', 'data-export'], bulkThreshold, additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
228
+ const conditions = [
229
+ {
230
+ field: 'actionName',
231
+ operator: 'matches_regex',
232
+ value: '(export|download|extract|dump)'
233
+ },
234
+ {
235
+ field: 'recordCount',
236
+ operator: 'greater_than',
237
+ value: bulkThreshold
238
+ }
239
+ ];
240
+ const defaultActions = [
241
+ { type: 'require_approval', message: `Bulk data operation (>${bulkThreshold} records) requires approval` },
242
+ { type: 'log' }
243
+ ];
244
+ return {
245
+ id,
246
+ name,
247
+ description,
248
+ type: 'security',
249
+ enabled,
250
+ priority,
251
+ conditions: mergeConditions(conditions, additionalConditions),
252
+ conditionLogic,
253
+ actions: mergeActions(defaultActions, overrideActions, additionalActions),
254
+ riskWeight,
255
+ tags: [...new Set([...tags, 'bulk-operations'])],
256
+ metadata: {
257
+ ...metadata,
258
+ patternBuilder: 'createBulkDataAccessRule',
259
+ bulkThreshold
260
+ }
261
+ };
262
+ }
263
+ // ============================================================================
264
+ // RATE LIMIT RULE BUILDER
265
+ // ============================================================================
266
+ /**
267
+ * Create a rate limit rule
268
+ *
269
+ * @example
270
+ * ```typescript
271
+ * const apiRateLimitRule = createRateLimitRule({
272
+ * id: 'rate-api-001',
273
+ * name: 'API Rate Limit',
274
+ * categories: ['external_api'],
275
+ * maxRequests: 100,
276
+ * windowMs: 60000,
277
+ * scope: 'agent'
278
+ * });
279
+ * ```
280
+ */
281
+ export function createRateLimitRule(options) {
282
+ const { id, name, description = 'Enforces rate limiting', enabled = true, priority = 850, riskWeight = 20, tags = ['rate-limit', 'operational'], categories, actionNames, maxRequests, windowMs, burstLimit, scope = 'agent', rateLimitMessage = `Rate limit exceeded (${maxRequests} requests per ${windowMs / 1000}s)`, additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
283
+ const conditions = [];
284
+ // Category condition
285
+ if (categories && categories.length > 0) {
286
+ if (categories.length === 1) {
287
+ conditions.push({
288
+ field: 'actionCategory',
289
+ operator: 'equals',
290
+ value: categories[0]
291
+ });
292
+ }
293
+ else {
294
+ conditions.push({
295
+ field: 'actionCategory',
296
+ operator: 'in',
297
+ value: categories
298
+ });
299
+ }
300
+ }
301
+ // Action name condition
302
+ if (actionNames && actionNames.length > 0) {
303
+ const pattern = actionNames.join('|');
304
+ conditions.push({
305
+ field: 'actionName',
306
+ operator: 'matches_regex',
307
+ value: `(${pattern})`
308
+ });
309
+ }
310
+ // Rate limit exceeded condition (checked by rate limiter)
311
+ conditions.push({
312
+ field: 'rateLimitExceeded',
313
+ operator: 'equals',
314
+ value: true
315
+ });
316
+ const defaultActions = [
317
+ { type: 'rate_limit', message: rateLimitMessage }
318
+ ];
319
+ return {
320
+ id,
321
+ name,
322
+ description,
323
+ type: 'rate_limit',
324
+ enabled,
325
+ priority,
326
+ conditions: mergeConditions(conditions, additionalConditions),
327
+ conditionLogic,
328
+ actions: mergeActions(defaultActions, overrideActions, additionalActions),
329
+ riskWeight,
330
+ tags: [...new Set([...tags, 'rate-limit'])],
331
+ metadata: {
332
+ ...metadata,
333
+ patternBuilder: 'createRateLimitRule',
334
+ maxRequests,
335
+ windowMs,
336
+ burstLimit,
337
+ scope
338
+ }
339
+ };
340
+ }
341
+ // ============================================================================
342
+ // COMPLIANCE RULE BUILDER
343
+ // ============================================================================
344
+ /**
345
+ * Compliance framework definitions
346
+ */
347
+ export const COMPLIANCE_FRAMEWORKS = {
348
+ gdpr: {
349
+ name: 'GDPR',
350
+ fullName: 'General Data Protection Regulation',
351
+ tags: ['gdpr', 'privacy', 'eu'],
352
+ defaultPriority: 920,
353
+ defaultRiskWeight: 45
354
+ },
355
+ hipaa: {
356
+ name: 'HIPAA',
357
+ fullName: 'Health Insurance Portability and Accountability Act',
358
+ tags: ['hipaa', 'phi', 'healthcare'],
359
+ defaultPriority: 950,
360
+ defaultRiskWeight: 55
361
+ },
362
+ 'pci-dss': {
363
+ name: 'PCI-DSS',
364
+ fullName: 'Payment Card Industry Data Security Standard',
365
+ tags: ['pci-dss', 'cardholder-data', 'financial'],
366
+ defaultPriority: 970,
367
+ defaultRiskWeight: 60
368
+ },
369
+ sox: {
370
+ name: 'SOX',
371
+ fullName: 'Sarbanes-Oxley Act',
372
+ tags: ['sox', 'financial', 'audit'],
373
+ defaultPriority: 940,
374
+ defaultRiskWeight: 50
375
+ },
376
+ soc2: {
377
+ name: 'SOC2',
378
+ fullName: 'Service Organization Control 2',
379
+ tags: ['soc2', 'security', 'trust'],
380
+ defaultPriority: 900,
381
+ defaultRiskWeight: 40
382
+ },
383
+ ccpa: {
384
+ name: 'CCPA',
385
+ fullName: 'California Consumer Privacy Act',
386
+ tags: ['ccpa', 'privacy', 'california'],
387
+ defaultPriority: 910,
388
+ defaultRiskWeight: 40
389
+ }
390
+ };
391
+ /**
392
+ * Create a compliance rule for a specific framework
393
+ *
394
+ * @example
395
+ * ```typescript
396
+ * const gdprConsentRule = createComplianceRule('gdpr', {
397
+ * id: 'gdpr-consent-001',
398
+ * name: 'GDPR Consent Verification',
399
+ * checkConsent: true,
400
+ * dataTypes: ['pii', 'email', 'name']
401
+ * });
402
+ *
403
+ * const hipaaPhiRule = createComplianceRule('hipaa', {
404
+ * id: 'hipaa-phi-001',
405
+ * name: 'HIPAA PHI Protection',
406
+ * dataTypes: ['phi'],
407
+ * requireEncryption: true,
408
+ * requirements: { minimumNecessary: 10 }
409
+ * });
410
+ * ```
411
+ */
412
+ export function createComplianceRule(framework, options) {
413
+ const frameworkConfig = COMPLIANCE_FRAMEWORKS[framework];
414
+ const { id, name, description = `${frameworkConfig.fullName} compliance rule`, enabled = true, priority = frameworkConfig.defaultPriority, riskWeight = frameworkConfig.defaultRiskWeight, tags = [], checkRetention = false, checkConsent = false, allowedRegions, requireAuditLog = true, requireEncryption = false, dataTypes, requirements, additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
415
+ const conditions = [];
416
+ const actions = [];
417
+ // Base data access condition
418
+ conditions.push({
419
+ field: 'actionCategory',
420
+ operator: 'in',
421
+ value: ['data_access', 'data_modification', 'pii_access']
422
+ });
423
+ // Data type conditions
424
+ if (dataTypes && dataTypes.length > 0) {
425
+ conditions.push({
426
+ field: 'dataType',
427
+ operator: 'in',
428
+ value: dataTypes
429
+ });
430
+ }
431
+ // Framework-specific conditions
432
+ switch (framework) {
433
+ case 'gdpr':
434
+ if (checkConsent) {
435
+ conditions.push({
436
+ field: 'processingBasis',
437
+ operator: 'equals',
438
+ value: 'consent'
439
+ });
440
+ conditions.push({
441
+ field: 'consentValid',
442
+ operator: 'not_equals',
443
+ value: true
444
+ });
445
+ actions.push({
446
+ type: 'deny',
447
+ message: 'GDPR: Valid consent required for this data processing'
448
+ });
449
+ }
450
+ if (checkRetention) {
451
+ conditions.push({
452
+ field: 'dataRetentionExceeded',
453
+ operator: 'equals',
454
+ value: true
455
+ });
456
+ actions.push({
457
+ type: 'deny',
458
+ message: 'GDPR: Data has exceeded retention period'
459
+ });
460
+ }
461
+ if (allowedRegions && allowedRegions.length > 0) {
462
+ conditions.push({
463
+ field: 'destinationRegion',
464
+ operator: 'not_in',
465
+ value: allowedRegions
466
+ });
467
+ actions.push({
468
+ type: 'require_approval',
469
+ message: 'GDPR: Cross-border data transfer requires DPO approval'
470
+ });
471
+ }
472
+ break;
473
+ case 'hipaa':
474
+ if (requireEncryption) {
475
+ conditions.push({
476
+ field: 'encryptionEnabled',
477
+ operator: 'not_equals',
478
+ value: true
479
+ });
480
+ actions.push({
481
+ type: 'deny',
482
+ message: 'HIPAA: PHI must be encrypted in transit and at rest'
483
+ });
484
+ }
485
+ if (requirements?.minimumNecessary) {
486
+ conditions.push({
487
+ field: 'fieldsRequested',
488
+ operator: 'greater_than',
489
+ value: requirements.minimumNecessary
490
+ });
491
+ actions.push({
492
+ type: 'require_approval',
493
+ message: 'HIPAA: Broad PHI access requires business justification'
494
+ });
495
+ }
496
+ if (requirements?.identityVerification) {
497
+ conditions.push({
498
+ field: 'verificationCompleted',
499
+ operator: 'not_equals',
500
+ value: true
501
+ });
502
+ actions.push({
503
+ type: 'deny',
504
+ message: 'HIPAA: Identity verification required'
505
+ });
506
+ }
507
+ break;
508
+ case 'pci-dss':
509
+ if (requireEncryption) {
510
+ conditions.push({
511
+ field: 'encryptionEnabled',
512
+ operator: 'not_equals',
513
+ value: true
514
+ });
515
+ actions.push({
516
+ type: 'deny',
517
+ message: 'PCI-DSS: Cardholder data must be encrypted'
518
+ });
519
+ }
520
+ break;
521
+ case 'sox':
522
+ if (requirements?.dualApproval) {
523
+ actions.push({
524
+ type: 'require_approval',
525
+ message: 'SOX: Financial data modification requires dual approval'
526
+ });
527
+ }
528
+ // Segregation of duties
529
+ conditions.push({
530
+ field: 'actionCategory',
531
+ operator: 'equals',
532
+ value: 'financial'
533
+ });
534
+ break;
535
+ }
536
+ // Add audit logging if required
537
+ if (requireAuditLog) {
538
+ actions.push({ type: 'log' });
539
+ }
540
+ // If no specific actions defined, add a default warning
541
+ if (actions.length === 0 || (actions.length === 1 && actions[0].type === 'log')) {
542
+ actions.unshift({
543
+ type: 'warn',
544
+ message: `${frameworkConfig.name}: Compliance check triggered - review required`
545
+ });
546
+ }
547
+ return {
548
+ id,
549
+ name,
550
+ description,
551
+ type: 'compliance',
552
+ enabled,
553
+ priority,
554
+ conditions: mergeConditions(conditions, additionalConditions),
555
+ conditionLogic,
556
+ actions: mergeActions(actions, overrideActions, additionalActions),
557
+ riskWeight,
558
+ tags: [...new Set([...frameworkConfig.tags, ...tags])],
559
+ metadata: {
560
+ ...metadata,
561
+ patternBuilder: 'createComplianceRule',
562
+ framework,
563
+ frameworkFullName: frameworkConfig.fullName,
564
+ requirements
565
+ }
566
+ };
567
+ }
568
+ // ============================================================================
569
+ // ENVIRONMENT RULE BUILDER
570
+ // ============================================================================
571
+ /**
572
+ * Create an environment-specific rule
573
+ *
574
+ * @example
575
+ * ```typescript
576
+ * const prodDeployRule = createEnvironmentRule('production', {
577
+ * id: 'env-prod-001',
578
+ * name: 'Production Deployment Control',
579
+ * environments: ['production'],
580
+ * actionNames: ['deploy', 'release'],
581
+ * requireApproval: true,
582
+ * requireRollbackPlan: true
583
+ * });
584
+ *
585
+ * const devRelaxedRule = createEnvironmentRule('development', {
586
+ * id: 'env-dev-001',
587
+ * name: 'Development Mode - Relaxed',
588
+ * environments: ['development'],
589
+ * categories: ['code_execution'],
590
+ * blockInEnvironments: false,
591
+ * message: 'Development mode - operation allowed'
592
+ * });
593
+ * ```
594
+ */
595
+ export function createEnvironmentRule(targetEnv, options) {
596
+ const { id, name, description = `Environment-specific rule for ${targetEnv}`, enabled = true, priority = targetEnv === 'production' ? 920 : 800, riskWeight = targetEnv === 'production' ? 40 : 20, tags = ['environment', targetEnv], environments, categories, actionNames, requireApproval = false, blockInEnvironments = false, requireFeatureFlag = false, requireRollbackPlan = false, message, additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
597
+ const conditions = [];
598
+ const actions = [];
599
+ // Environment condition
600
+ if (environments.length === 1) {
601
+ conditions.push({
602
+ field: 'environment',
603
+ operator: 'equals',
604
+ value: environments[0]
605
+ });
606
+ }
607
+ else if (environments.length > 1) {
608
+ conditions.push({
609
+ field: 'environment',
610
+ operator: 'in',
611
+ value: environments
612
+ });
613
+ }
614
+ // Category condition
615
+ if (categories && categories.length > 0) {
616
+ if (categories.length === 1) {
617
+ conditions.push({
618
+ field: 'actionCategory',
619
+ operator: 'equals',
620
+ value: categories[0]
621
+ });
622
+ }
623
+ else {
624
+ conditions.push({
625
+ field: 'actionCategory',
626
+ operator: 'in',
627
+ value: categories
628
+ });
629
+ }
630
+ }
631
+ // Action name condition
632
+ if (actionNames && actionNames.length > 0) {
633
+ const pattern = actionNames.join('|');
634
+ conditions.push({
635
+ field: 'actionName',
636
+ operator: 'matches_regex',
637
+ value: `(${pattern})`
638
+ });
639
+ }
640
+ // Rollback plan requirement
641
+ if (requireRollbackPlan) {
642
+ conditions.push({
643
+ field: 'rollbackPlanDefined',
644
+ operator: 'not_equals',
645
+ value: true
646
+ });
647
+ actions.push({
648
+ type: 'warn',
649
+ message: message || `${environments.join('/')} changes should have a rollback plan`
650
+ });
651
+ }
652
+ // Feature flag requirement
653
+ if (requireFeatureFlag) {
654
+ conditions.push({
655
+ field: 'isNewFeature',
656
+ operator: 'equals',
657
+ value: true
658
+ });
659
+ conditions.push({
660
+ field: 'featureFlagEnabled',
661
+ operator: 'not_equals',
662
+ value: true
663
+ });
664
+ actions.push({
665
+ type: 'warn',
666
+ message: message || 'New features should use feature flags'
667
+ });
668
+ }
669
+ // Block or require approval
670
+ if (blockInEnvironments) {
671
+ actions.push({
672
+ type: 'deny',
673
+ message: message || `Operation blocked in ${environments.join('/')} environment`
674
+ });
675
+ }
676
+ else if (requireApproval) {
677
+ actions.push({
678
+ type: 'require_approval',
679
+ message: message || `Operation requires approval in ${environments.join('/')} environment`
680
+ });
681
+ }
682
+ // Add logging for production
683
+ if (environments.includes('production')) {
684
+ actions.push({ type: 'log' });
685
+ }
686
+ // Default action if none specified
687
+ if (actions.length === 0) {
688
+ actions.push({
689
+ type: 'warn',
690
+ message: message || `Environment rule triggered for ${environments.join('/')}`
691
+ });
692
+ }
693
+ return {
694
+ id,
695
+ name,
696
+ description,
697
+ type: 'operational',
698
+ enabled,
699
+ priority,
700
+ conditions: mergeConditions(conditions, additionalConditions),
701
+ conditionLogic,
702
+ actions: mergeActions(actions, overrideActions, additionalActions),
703
+ riskWeight,
704
+ tags: [...new Set([...tags, ...environments])],
705
+ metadata: {
706
+ ...metadata,
707
+ patternBuilder: 'createEnvironmentRule',
708
+ targetEnvironments: environments,
709
+ requireApproval,
710
+ blockInEnvironments,
711
+ requireFeatureFlag,
712
+ requireRollbackPlan
713
+ }
714
+ };
715
+ }
716
+ // ============================================================================
717
+ // SECURITY RULE BUILDER
718
+ // ============================================================================
719
+ /**
720
+ * Injection pattern definitions
721
+ */
722
+ export const INJECTION_PATTERNS = {
723
+ sql_injection: {
724
+ pattern: '(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|OR|AND)\\b.*[\'";])|(--)|(\\*/)|(/\\*)',
725
+ description: 'SQL injection detection',
726
+ tags: ['sql-injection', 'owasp']
727
+ },
728
+ command_injection: {
729
+ pattern: '([;&|`$]|\\$\\(|\\{\\{)',
730
+ description: 'Command injection detection',
731
+ tags: ['command-injection', 'owasp']
732
+ },
733
+ xss: {
734
+ pattern: '(<script|javascript:|on\\w+\\s*=|<img.*onerror)',
735
+ description: 'Cross-site scripting detection',
736
+ tags: ['xss', 'owasp']
737
+ },
738
+ path_traversal: {
739
+ pattern: '(\\.\\./|\\.\\.\\\\|%2e%2e%2f|%252e%252e%252f)',
740
+ description: 'Path traversal detection',
741
+ tags: ['path-traversal', 'owasp']
742
+ }
743
+ };
744
+ /**
745
+ * Create a security rule
746
+ *
747
+ * @example
748
+ * ```typescript
749
+ * const sqlInjectionRule = createSecurityRule({
750
+ * id: 'sec-sql-001',
751
+ * name: 'SQL Injection Prevention',
752
+ * patternType: 'sql_injection',
753
+ * patternField: 'query',
754
+ * detectionAction: 'deny',
755
+ * sendNotification: true
756
+ * });
757
+ *
758
+ * const sandboxRule = createSecurityRule({
759
+ * id: 'sec-sandbox-001',
760
+ * name: 'Require Sandbox for Code',
761
+ * requireSandbox: true,
762
+ * detectionAction: 'deny'
763
+ * });
764
+ * ```
765
+ */
766
+ export function createSecurityRule(options) {
767
+ const { id, name, description, enabled = true, priority = 980, riskWeight = 60, tags = ['security'], patternType, customPattern, patternField, requireSandbox = false, requireCodeValidation = false, blockSystemFiles = false, systemFilesPattern = '^(/etc|/sys|/proc|/boot|C:\\\\Windows|C:\\\\System)', detectionAction = 'deny', sendNotification = false, additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
768
+ const conditions = [];
769
+ const actions = [];
770
+ let derivedTags = [...tags];
771
+ let ruleDescription = description;
772
+ // Pattern-based detection
773
+ if (patternType && patternType !== 'custom') {
774
+ const patternConfig = INJECTION_PATTERNS[patternType];
775
+ const field = patternField || (patternType === 'sql_injection' ? 'query' : 'command');
776
+ conditions.push({
777
+ field: 'actionCategory',
778
+ operator: 'equals',
779
+ value: patternType === 'sql_injection' ? 'data_access' : 'code_execution'
780
+ });
781
+ conditions.push({
782
+ field,
783
+ operator: 'matches_regex',
784
+ value: patternConfig.pattern
785
+ });
786
+ ruleDescription = ruleDescription || patternConfig.description;
787
+ derivedTags = [...derivedTags, ...patternConfig.tags];
788
+ actions.push({
789
+ type: detectionAction,
790
+ message: `${patternConfig.description} - action blocked`
791
+ });
792
+ }
793
+ else if (customPattern && patternField) {
794
+ // Custom pattern detection
795
+ conditions.push({
796
+ field: patternField,
797
+ operator: 'matches_regex',
798
+ value: customPattern
799
+ });
800
+ actions.push({
801
+ type: detectionAction,
802
+ message: 'Security pattern detected - action blocked'
803
+ });
804
+ }
805
+ // Sandbox requirement
806
+ if (requireSandbox) {
807
+ conditions.push({
808
+ field: 'actionCategory',
809
+ operator: 'equals',
810
+ value: 'code_execution'
811
+ });
812
+ conditions.push({
813
+ field: 'sandboxed',
814
+ operator: 'not_equals',
815
+ value: true
816
+ });
817
+ conditions.push({
818
+ field: 'environment',
819
+ operator: 'equals',
820
+ value: 'production'
821
+ });
822
+ actions.push({
823
+ type: detectionAction,
824
+ message: 'Code execution in production requires sandboxing'
825
+ });
826
+ derivedTags.push('sandbox');
827
+ ruleDescription = ruleDescription || 'Requires sandbox for code execution';
828
+ }
829
+ // Code validation requirement
830
+ if (requireCodeValidation) {
831
+ conditions.push({
832
+ field: 'actionCategory',
833
+ operator: 'equals',
834
+ value: 'code_execution'
835
+ });
836
+ conditions.push({
837
+ field: 'codeValidated',
838
+ operator: 'not_equals',
839
+ value: true
840
+ });
841
+ actions.push({
842
+ type: detectionAction,
843
+ message: 'Code execution requires validation'
844
+ });
845
+ derivedTags.push('code-validation');
846
+ ruleDescription = ruleDescription || 'Requires code validation before execution';
847
+ }
848
+ // System file protection
849
+ if (blockSystemFiles) {
850
+ conditions.push({
851
+ field: 'actionCategory',
852
+ operator: 'equals',
853
+ value: 'file_system'
854
+ });
855
+ conditions.push({
856
+ field: 'filePath',
857
+ operator: 'matches_regex',
858
+ value: systemFilesPattern
859
+ });
860
+ actions.push({
861
+ type: 'deny',
862
+ message: 'Access to system files is prohibited'
863
+ });
864
+ derivedTags.push('file-system');
865
+ ruleDescription = ruleDescription || 'Blocks access to system files';
866
+ }
867
+ // Notification
868
+ if (sendNotification) {
869
+ actions.push({
870
+ type: 'notify',
871
+ message: `Security alert: ${name}`
872
+ });
873
+ }
874
+ // Always log security events
875
+ actions.push({ type: 'log' });
876
+ return {
877
+ id,
878
+ name,
879
+ description: ruleDescription || 'Security enforcement rule',
880
+ type: 'security',
881
+ enabled,
882
+ priority,
883
+ conditions: mergeConditions(conditions, additionalConditions),
884
+ conditionLogic,
885
+ actions: mergeActions(actions, overrideActions, additionalActions),
886
+ riskWeight,
887
+ tags: [...new Set(derivedTags)],
888
+ metadata: {
889
+ ...metadata,
890
+ patternBuilder: 'createSecurityRule',
891
+ patternType,
892
+ requireSandbox,
893
+ requireCodeValidation,
894
+ blockSystemFiles
895
+ }
896
+ };
897
+ }
898
+ // ============================================================================
899
+ // OPERATIONAL RULE BUILDER
900
+ // ============================================================================
901
+ /**
902
+ * Create an operational rule
903
+ *
904
+ * @example
905
+ * ```typescript
906
+ * const costControlRule = createOperationalRule({
907
+ * id: 'ops-cost-001',
908
+ * name: 'API Cost Control',
909
+ * costThreshold: 50,
910
+ * categories: ['external_api']
911
+ * });
912
+ *
913
+ * const resourceLimitRule = createOperationalRule({
914
+ * id: 'ops-resource-001',
915
+ * name: 'Memory Usage Warning',
916
+ * memoryThreshold: 1024,
917
+ * tokenThreshold: 100000
918
+ * });
919
+ * ```
920
+ */
921
+ export function createOperationalRule(options) {
922
+ const { id, name, description = 'Operational governance rule', enabled = true, priority = 850, riskWeight = 25, tags = ['operational'], costThreshold, memoryThreshold, tokenThreshold, dailyBudget, maxRetries, sessionActionLimit, requireBackupVerification = false, enforceDeploymentWindow = false, additionalConditions, overrideActions, additionalActions, conditionLogic = 'all', metadata } = options;
923
+ const conditions = [];
924
+ const actions = [];
925
+ const derivedTags = [...tags];
926
+ // Cost threshold
927
+ if (costThreshold !== undefined) {
928
+ conditions.push({
929
+ field: 'estimatedCost',
930
+ operator: 'greater_than',
931
+ value: costThreshold
932
+ });
933
+ actions.push({
934
+ type: 'require_approval',
935
+ message: `Operation cost exceeds $${costThreshold} - requires approval`
936
+ });
937
+ derivedTags.push('cost');
938
+ }
939
+ // Memory threshold
940
+ if (memoryThreshold !== undefined) {
941
+ conditions.push({
942
+ field: 'estimatedMemoryMb',
943
+ operator: 'greater_than',
944
+ value: memoryThreshold
945
+ });
946
+ actions.push({
947
+ type: 'warn',
948
+ message: `Operation may consume >${memoryThreshold}MB memory`
949
+ });
950
+ derivedTags.push('memory');
951
+ }
952
+ // Token threshold for LLM
953
+ if (tokenThreshold !== undefined) {
954
+ conditions.push({
955
+ field: 'actionName',
956
+ operator: 'contains',
957
+ value: 'llm'
958
+ });
959
+ conditions.push({
960
+ field: 'tokenCount',
961
+ operator: 'greater_than',
962
+ value: tokenThreshold
963
+ });
964
+ actions.push({
965
+ type: 'require_approval',
966
+ message: `LLM call exceeds ${tokenThreshold} tokens - requires approval`
967
+ });
968
+ derivedTags.push('llm', 'tokens');
969
+ }
970
+ // Daily budget
971
+ if (dailyBudget !== undefined) {
972
+ conditions.push({
973
+ field: 'dailySpend',
974
+ operator: 'greater_than',
975
+ value: dailyBudget
976
+ });
977
+ conditions.push({
978
+ field: 'budgetOverrideApproved',
979
+ operator: 'not_equals',
980
+ value: true
981
+ });
982
+ actions.push({
983
+ type: 'deny',
984
+ message: `Daily budget limit ($${dailyBudget}) exceeded`
985
+ });
986
+ derivedTags.push('budget');
987
+ }
988
+ // Retry limit
989
+ if (maxRetries !== undefined) {
990
+ conditions.push({
991
+ field: 'retryCount',
992
+ operator: 'greater_than',
993
+ value: maxRetries
994
+ });
995
+ actions.push({
996
+ type: 'deny',
997
+ message: `Maximum retry attempts (${maxRetries}) exceeded`
998
+ });
999
+ actions.push({
1000
+ type: 'escalate',
1001
+ message: 'Operation repeatedly failing - escalation required'
1002
+ });
1003
+ derivedTags.push('retry');
1004
+ }
1005
+ // Session action limit
1006
+ if (sessionActionLimit !== undefined) {
1007
+ conditions.push({
1008
+ field: 'sessionActionCount',
1009
+ operator: 'greater_than',
1010
+ value: sessionActionLimit
1011
+ });
1012
+ actions.push({
1013
+ type: 'warn',
1014
+ message: `Session action count exceeds ${sessionActionLimit} - consider session rotation`
1015
+ });
1016
+ derivedTags.push('session');
1017
+ }
1018
+ // Backup verification
1019
+ if (requireBackupVerification) {
1020
+ conditions.push({
1021
+ field: 'operation',
1022
+ operator: 'in',
1023
+ value: ['delete', 'truncate', 'drop', 'purge']
1024
+ });
1025
+ conditions.push({
1026
+ field: 'environment',
1027
+ operator: 'equals',
1028
+ value: 'production'
1029
+ });
1030
+ conditions.push({
1031
+ field: 'backupVerified',
1032
+ operator: 'not_equals',
1033
+ value: true
1034
+ });
1035
+ actions.push({
1036
+ type: 'require_approval',
1037
+ message: 'Destructive operation requires backup verification'
1038
+ });
1039
+ derivedTags.push('backup', 'destructive');
1040
+ }
1041
+ // Deployment window
1042
+ if (enforceDeploymentWindow) {
1043
+ conditions.push({
1044
+ field: 'actionName',
1045
+ operator: 'equals',
1046
+ value: 'deploy'
1047
+ });
1048
+ conditions.push({
1049
+ field: 'environment',
1050
+ operator: 'equals',
1051
+ value: 'production'
1052
+ });
1053
+ conditions.push({
1054
+ field: 'deploymentWindowOpen',
1055
+ operator: 'not_equals',
1056
+ value: true
1057
+ });
1058
+ actions.push({
1059
+ type: 'require_approval',
1060
+ message: 'Production deployment outside approved window requires approval'
1061
+ });
1062
+ derivedTags.push('deployment');
1063
+ }
1064
+ // Always log operational events
1065
+ actions.push({ type: 'log' });
1066
+ return {
1067
+ id,
1068
+ name,
1069
+ description,
1070
+ type: 'operational',
1071
+ enabled,
1072
+ priority,
1073
+ conditions: mergeConditions(conditions, additionalConditions),
1074
+ conditionLogic,
1075
+ actions: mergeActions(actions, overrideActions, additionalActions),
1076
+ riskWeight,
1077
+ tags: [...new Set(derivedTags)],
1078
+ metadata: {
1079
+ ...metadata,
1080
+ patternBuilder: 'createOperationalRule',
1081
+ costThreshold,
1082
+ memoryThreshold,
1083
+ tokenThreshold,
1084
+ dailyBudget,
1085
+ maxRetries,
1086
+ sessionActionLimit
1087
+ }
1088
+ };
1089
+ }
1090
+ // ============================================================================
1091
+ // CONVENIENCE BUILDERS
1092
+ // ============================================================================
1093
+ /**
1094
+ * Create a simple deny rule
1095
+ */
1096
+ export function createDenyRule(options) {
1097
+ const { id, name, conditions, message, priority = 900, riskWeight = 50, tags = [], type = 'security' } = options;
1098
+ return {
1099
+ id,
1100
+ name,
1101
+ type,
1102
+ enabled: true,
1103
+ priority,
1104
+ conditions,
1105
+ conditionLogic: 'all',
1106
+ actions: [
1107
+ { type: 'deny', message },
1108
+ { type: 'log' }
1109
+ ],
1110
+ riskWeight,
1111
+ tags
1112
+ };
1113
+ }
1114
+ /**
1115
+ * Create a simple approval rule
1116
+ */
1117
+ export function createApprovalRule(options) {
1118
+ const { id, name, conditions, message, priority = 850, riskWeight = 35, tags = [], type = 'operational' } = options;
1119
+ return {
1120
+ id,
1121
+ name,
1122
+ type,
1123
+ enabled: true,
1124
+ priority,
1125
+ conditions,
1126
+ conditionLogic: 'all',
1127
+ actions: [
1128
+ { type: 'require_approval', message },
1129
+ { type: 'log' }
1130
+ ],
1131
+ riskWeight,
1132
+ tags
1133
+ };
1134
+ }
1135
+ /**
1136
+ * Create a simple warning rule
1137
+ */
1138
+ export function createWarningRule(options) {
1139
+ const { id, name, conditions, message, priority = 700, riskWeight = 15, tags = [], type = 'operational' } = options;
1140
+ return {
1141
+ id,
1142
+ name,
1143
+ type,
1144
+ enabled: true,
1145
+ priority,
1146
+ conditions,
1147
+ conditionLogic: 'all',
1148
+ actions: [
1149
+ { type: 'warn', message }
1150
+ ],
1151
+ riskWeight,
1152
+ tags
1153
+ };
1154
+ }
1155
+ /**
1156
+ * Create an audit-only rule (logs without blocking)
1157
+ */
1158
+ export function createAuditRule(options) {
1159
+ const { id, name, conditions, priority = 500, tags = ['audit'] } = options;
1160
+ return {
1161
+ id,
1162
+ name,
1163
+ type: 'compliance',
1164
+ enabled: true,
1165
+ priority,
1166
+ conditions,
1167
+ conditionLogic: 'all',
1168
+ actions: [
1169
+ { type: 'log' },
1170
+ { type: 'allow' }
1171
+ ],
1172
+ riskWeight: 5,
1173
+ tags
1174
+ };
1175
+ }
1176
+ // ============================================================================
1177
+ // RULE SET BUILDERS
1178
+ // ============================================================================
1179
+ /**
1180
+ * Create a complete rule set for a compliance framework
1181
+ */
1182
+ export function createComplianceRuleSet(framework, baseId, options) {
1183
+ const { enabled = true, priorityOffset = 0 } = options || {};
1184
+ const rules = [];
1185
+ switch (framework) {
1186
+ case 'gdpr':
1187
+ rules.push(createComplianceRule('gdpr', {
1188
+ id: `${baseId}-consent`,
1189
+ name: 'GDPR - Consent Verification',
1190
+ checkConsent: true,
1191
+ enabled,
1192
+ priority: 910 + priorityOffset
1193
+ }), createComplianceRule('gdpr', {
1194
+ id: `${baseId}-retention`,
1195
+ name: 'GDPR - Data Retention',
1196
+ checkRetention: true,
1197
+ enabled,
1198
+ priority: 850 + priorityOffset
1199
+ }), createComplianceRule('gdpr', {
1200
+ id: `${baseId}-transfer`,
1201
+ name: 'GDPR - Cross-Border Transfer',
1202
+ allowedRegions: ['EU', 'EEA', 'adequacy_decision'],
1203
+ enabled,
1204
+ priority: 920 + priorityOffset
1205
+ }));
1206
+ break;
1207
+ case 'hipaa':
1208
+ rules.push(createComplianceRule('hipaa', {
1209
+ id: `${baseId}-encryption`,
1210
+ name: 'HIPAA - PHI Encryption',
1211
+ dataTypes: ['phi'],
1212
+ requireEncryption: true,
1213
+ enabled,
1214
+ priority: 960 + priorityOffset
1215
+ }), createComplianceRule('hipaa', {
1216
+ id: `${baseId}-minimum`,
1217
+ name: 'HIPAA - Minimum Necessary',
1218
+ dataTypes: ['phi'],
1219
+ requirements: { minimumNecessary: 10 },
1220
+ enabled,
1221
+ priority: 920 + priorityOffset
1222
+ }), createAuditRule({
1223
+ id: `${baseId}-audit`,
1224
+ name: 'HIPAA - PHI Access Audit',
1225
+ conditions: [{ field: 'dataType', operator: 'equals', value: 'phi' }],
1226
+ priority: 950 + priorityOffset,
1227
+ tags: ['hipaa', 'phi', 'audit']
1228
+ }));
1229
+ break;
1230
+ case 'pci-dss':
1231
+ rules.push(createDataAccessRule({
1232
+ id: `${baseId}-cardholder`,
1233
+ name: 'PCI-DSS - Cardholder Data Access',
1234
+ dataTypes: ['cardholder', 'pan'],
1235
+ allowedRoles: ['payment_processor', 'fraud_analyst', 'security_admin'],
1236
+ enabled,
1237
+ priority: 980 + priorityOffset,
1238
+ tags: ['pci-dss', 'cardholder-data']
1239
+ }), createDenyRule({
1240
+ id: `${baseId}-cvv`,
1241
+ name: 'PCI-DSS - CVV Storage Prohibition',
1242
+ conditions: [
1243
+ { field: 'actionCategory', operator: 'equals', value: 'data_modification' },
1244
+ { field: 'operation', operator: 'in', value: ['write', 'store', 'save'] },
1245
+ { field: 'dataType', operator: 'equals', value: 'cvv' }
1246
+ ],
1247
+ message: 'PCI-DSS: CVV/CVC storage is strictly prohibited',
1248
+ priority: 990 + priorityOffset,
1249
+ riskWeight: 70,
1250
+ tags: ['pci-dss', 'cvv'],
1251
+ type: 'compliance'
1252
+ }));
1253
+ break;
1254
+ case 'sox':
1255
+ rules.push(createApprovalRule({
1256
+ id: `${baseId}-financial`,
1257
+ name: 'SOX - Financial Data Audit',
1258
+ conditions: [
1259
+ { field: 'actionCategory', operator: 'equals', value: 'financial' },
1260
+ { field: 'operation', operator: 'in', value: ['write', 'update', 'delete'] }
1261
+ ],
1262
+ message: 'SOX: Financial data modification requires dual approval',
1263
+ priority: 940 + priorityOffset,
1264
+ tags: ['sox', 'financial', 'audit'],
1265
+ type: 'compliance'
1266
+ }), createDenyRule({
1267
+ id: `${baseId}-sod`,
1268
+ name: 'SOX - Segregation of Duties',
1269
+ conditions: [
1270
+ { field: 'actionCategory', operator: 'equals', value: 'financial' },
1271
+ { field: 'operation', operator: 'equals', value: 'approve' },
1272
+ { field: 'initiatorId', operator: 'equals', value: '$userId' }
1273
+ ],
1274
+ message: 'SOX: Cannot approve own financial transactions',
1275
+ priority: 930 + priorityOffset,
1276
+ riskWeight: 50,
1277
+ tags: ['sox', 'segregation-of-duties'],
1278
+ type: 'compliance'
1279
+ }));
1280
+ break;
1281
+ }
1282
+ return rules;
1283
+ }
1284
+ /**
1285
+ * Create a complete security rule set
1286
+ */
1287
+ export function createSecurityRuleSet(baseId, options) {
1288
+ const { enabled = true, includeInjectionPrevention = true, includeSandboxing = true, includeSystemFileProtection = true } = options || {};
1289
+ const rules = [];
1290
+ if (includeInjectionPrevention) {
1291
+ rules.push(createSecurityRule({
1292
+ id: `${baseId}-sql`,
1293
+ name: 'SQL Injection Prevention',
1294
+ patternType: 'sql_injection',
1295
+ patternField: 'query',
1296
+ sendNotification: true,
1297
+ enabled
1298
+ }), createSecurityRule({
1299
+ id: `${baseId}-cmd`,
1300
+ name: 'Command Injection Prevention',
1301
+ patternType: 'command_injection',
1302
+ patternField: 'command',
1303
+ sendNotification: true,
1304
+ enabled
1305
+ }), createSecurityRule({
1306
+ id: `${baseId}-xss`,
1307
+ name: 'XSS Prevention',
1308
+ patternType: 'xss',
1309
+ patternField: 'input',
1310
+ sendNotification: true,
1311
+ enabled
1312
+ }));
1313
+ }
1314
+ if (includeSandboxing) {
1315
+ rules.push(createSecurityRule({
1316
+ id: `${baseId}-sandbox`,
1317
+ name: 'Production Sandboxing Required',
1318
+ requireSandbox: true,
1319
+ enabled
1320
+ }), createSecurityRule({
1321
+ id: `${baseId}-validation`,
1322
+ name: 'Code Validation Required',
1323
+ requireCodeValidation: true,
1324
+ enabled
1325
+ }));
1326
+ }
1327
+ if (includeSystemFileProtection) {
1328
+ rules.push(createSecurityRule({
1329
+ id: `${baseId}-sysfiles`,
1330
+ name: 'System File Protection',
1331
+ blockSystemFiles: true,
1332
+ enabled
1333
+ }));
1334
+ }
1335
+ return rules;
1336
+ }
1337
+ export default {
1338
+ // Main builders
1339
+ createAuthenticationRule,
1340
+ createDataAccessRule,
1341
+ createBulkDataAccessRule,
1342
+ createRateLimitRule,
1343
+ createComplianceRule,
1344
+ createEnvironmentRule,
1345
+ createSecurityRule,
1346
+ createOperationalRule,
1347
+ // Convenience builders
1348
+ createDenyRule,
1349
+ createApprovalRule,
1350
+ createWarningRule,
1351
+ createAuditRule,
1352
+ // Rule set builders
1353
+ createComplianceRuleSet,
1354
+ createSecurityRuleSet,
1355
+ // Constants
1356
+ COMPLIANCE_FRAMEWORKS,
1357
+ INJECTION_PATTERNS
1358
+ };
1359
+ //# sourceMappingURL=patterns.js.map