@zintrust/workers 0.1.27

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 (178) hide show
  1. package/README.md +861 -0
  2. package/dist/AnomalyDetection.d.ts +102 -0
  3. package/dist/AnomalyDetection.js +321 -0
  4. package/dist/AutoScaler.d.ts +127 -0
  5. package/dist/AutoScaler.js +425 -0
  6. package/dist/BroadcastWorker.d.ts +21 -0
  7. package/dist/BroadcastWorker.js +24 -0
  8. package/dist/CanaryController.d.ts +103 -0
  9. package/dist/CanaryController.js +380 -0
  10. package/dist/ChaosEngineering.d.ts +79 -0
  11. package/dist/ChaosEngineering.js +216 -0
  12. package/dist/CircuitBreaker.d.ts +106 -0
  13. package/dist/CircuitBreaker.js +374 -0
  14. package/dist/ClusterLock.d.ts +90 -0
  15. package/dist/ClusterLock.js +385 -0
  16. package/dist/ComplianceManager.d.ts +177 -0
  17. package/dist/ComplianceManager.js +556 -0
  18. package/dist/DatacenterOrchestrator.d.ts +133 -0
  19. package/dist/DatacenterOrchestrator.js +404 -0
  20. package/dist/DeadLetterQueue.d.ts +122 -0
  21. package/dist/DeadLetterQueue.js +539 -0
  22. package/dist/HealthMonitor.d.ts +42 -0
  23. package/dist/HealthMonitor.js +301 -0
  24. package/dist/MultiQueueWorker.d.ts +89 -0
  25. package/dist/MultiQueueWorker.js +277 -0
  26. package/dist/NotificationWorker.d.ts +21 -0
  27. package/dist/NotificationWorker.js +23 -0
  28. package/dist/Observability.d.ts +153 -0
  29. package/dist/Observability.js +530 -0
  30. package/dist/PluginManager.d.ts +123 -0
  31. package/dist/PluginManager.js +392 -0
  32. package/dist/PriorityQueue.d.ts +117 -0
  33. package/dist/PriorityQueue.js +244 -0
  34. package/dist/ResourceMonitor.d.ts +164 -0
  35. package/dist/ResourceMonitor.js +605 -0
  36. package/dist/SLAMonitor.d.ts +110 -0
  37. package/dist/SLAMonitor.js +274 -0
  38. package/dist/WorkerFactory.d.ts +193 -0
  39. package/dist/WorkerFactory.js +1507 -0
  40. package/dist/WorkerInit.d.ts +85 -0
  41. package/dist/WorkerInit.js +223 -0
  42. package/dist/WorkerMetrics.d.ts +114 -0
  43. package/dist/WorkerMetrics.js +509 -0
  44. package/dist/WorkerRegistry.d.ts +145 -0
  45. package/dist/WorkerRegistry.js +319 -0
  46. package/dist/WorkerShutdown.d.ts +61 -0
  47. package/dist/WorkerShutdown.js +159 -0
  48. package/dist/WorkerVersioning.d.ts +107 -0
  49. package/dist/WorkerVersioning.js +300 -0
  50. package/dist/build-manifest.json +462 -0
  51. package/dist/config/workerConfig.d.ts +3 -0
  52. package/dist/config/workerConfig.js +19 -0
  53. package/dist/createQueueWorker.d.ts +23 -0
  54. package/dist/createQueueWorker.js +113 -0
  55. package/dist/dashboard/index.d.ts +1 -0
  56. package/dist/dashboard/index.js +1 -0
  57. package/dist/dashboard/types.d.ts +117 -0
  58. package/dist/dashboard/types.js +1 -0
  59. package/dist/dashboard/workers-api.d.ts +4 -0
  60. package/dist/dashboard/workers-api.js +638 -0
  61. package/dist/dashboard/workers-dashboard-ui.d.ts +3 -0
  62. package/dist/dashboard/workers-dashboard-ui.js +1026 -0
  63. package/dist/dashboard/workers-dashboard.d.ts +4 -0
  64. package/dist/dashboard/workers-dashboard.js +904 -0
  65. package/dist/helper/index.d.ts +5 -0
  66. package/dist/helper/index.js +10 -0
  67. package/dist/http/WorkerApiController.d.ts +38 -0
  68. package/dist/http/WorkerApiController.js +312 -0
  69. package/dist/http/WorkerController.d.ts +374 -0
  70. package/dist/http/WorkerController.js +1351 -0
  71. package/dist/http/middleware/CustomValidation.d.ts +92 -0
  72. package/dist/http/middleware/CustomValidation.js +270 -0
  73. package/dist/http/middleware/DatacenterValidator.d.ts +3 -0
  74. package/dist/http/middleware/DatacenterValidator.js +94 -0
  75. package/dist/http/middleware/EditWorkerValidation.d.ts +7 -0
  76. package/dist/http/middleware/EditWorkerValidation.js +55 -0
  77. package/dist/http/middleware/FeaturesValidator.d.ts +3 -0
  78. package/dist/http/middleware/FeaturesValidator.js +60 -0
  79. package/dist/http/middleware/InfrastructureValidator.d.ts +31 -0
  80. package/dist/http/middleware/InfrastructureValidator.js +226 -0
  81. package/dist/http/middleware/OptionsValidator.d.ts +3 -0
  82. package/dist/http/middleware/OptionsValidator.js +112 -0
  83. package/dist/http/middleware/PayloadSanitizer.d.ts +7 -0
  84. package/dist/http/middleware/PayloadSanitizer.js +42 -0
  85. package/dist/http/middleware/ProcessorPathSanitizer.d.ts +3 -0
  86. package/dist/http/middleware/ProcessorPathSanitizer.js +74 -0
  87. package/dist/http/middleware/QueueNameSanitizer.d.ts +3 -0
  88. package/dist/http/middleware/QueueNameSanitizer.js +45 -0
  89. package/dist/http/middleware/ValidateDriver.d.ts +7 -0
  90. package/dist/http/middleware/ValidateDriver.js +20 -0
  91. package/dist/http/middleware/VersionSanitizer.d.ts +3 -0
  92. package/dist/http/middleware/VersionSanitizer.js +25 -0
  93. package/dist/http/middleware/WorkerNameSanitizer.d.ts +3 -0
  94. package/dist/http/middleware/WorkerNameSanitizer.js +46 -0
  95. package/dist/http/middleware/WorkerValidationChain.d.ts +27 -0
  96. package/dist/http/middleware/WorkerValidationChain.js +185 -0
  97. package/dist/index.d.ts +46 -0
  98. package/dist/index.js +48 -0
  99. package/dist/routes/workers.d.ts +12 -0
  100. package/dist/routes/workers.js +81 -0
  101. package/dist/storage/WorkerStore.d.ts +45 -0
  102. package/dist/storage/WorkerStore.js +195 -0
  103. package/dist/type.d.ts +76 -0
  104. package/dist/type.js +1 -0
  105. package/dist/ui/router/ui.d.ts +3 -0
  106. package/dist/ui/router/ui.js +83 -0
  107. package/dist/ui/types/worker-ui.d.ts +229 -0
  108. package/dist/ui/types/worker-ui.js +5 -0
  109. package/package.json +53 -0
  110. package/src/AnomalyDetection.ts +434 -0
  111. package/src/AutoScaler.ts +654 -0
  112. package/src/BroadcastWorker.ts +34 -0
  113. package/src/CanaryController.ts +531 -0
  114. package/src/ChaosEngineering.ts +301 -0
  115. package/src/CircuitBreaker.ts +495 -0
  116. package/src/ClusterLock.ts +499 -0
  117. package/src/ComplianceManager.ts +815 -0
  118. package/src/DatacenterOrchestrator.ts +561 -0
  119. package/src/DeadLetterQueue.ts +733 -0
  120. package/src/HealthMonitor.ts +390 -0
  121. package/src/MultiQueueWorker.ts +431 -0
  122. package/src/NotificationWorker.ts +33 -0
  123. package/src/Observability.ts +696 -0
  124. package/src/PluginManager.ts +551 -0
  125. package/src/PriorityQueue.ts +351 -0
  126. package/src/ResourceMonitor.ts +769 -0
  127. package/src/SLAMonitor.ts +408 -0
  128. package/src/WorkerFactory.ts +2108 -0
  129. package/src/WorkerInit.ts +313 -0
  130. package/src/WorkerMetrics.ts +709 -0
  131. package/src/WorkerRegistry.ts +443 -0
  132. package/src/WorkerShutdown.ts +210 -0
  133. package/src/WorkerVersioning.ts +422 -0
  134. package/src/config/workerConfig.ts +25 -0
  135. package/src/createQueueWorker.ts +174 -0
  136. package/src/dashboard/index.ts +6 -0
  137. package/src/dashboard/types.ts +141 -0
  138. package/src/dashboard/workers-api.ts +785 -0
  139. package/src/dashboard/zintrust.svg +30 -0
  140. package/src/helper/index.ts +11 -0
  141. package/src/http/WorkerApiController.ts +369 -0
  142. package/src/http/WorkerController.ts +1512 -0
  143. package/src/http/middleware/CustomValidation.ts +360 -0
  144. package/src/http/middleware/DatacenterValidator.ts +124 -0
  145. package/src/http/middleware/EditWorkerValidation.ts +74 -0
  146. package/src/http/middleware/FeaturesValidator.ts +82 -0
  147. package/src/http/middleware/InfrastructureValidator.ts +295 -0
  148. package/src/http/middleware/OptionsValidator.ts +144 -0
  149. package/src/http/middleware/PayloadSanitizer.ts +52 -0
  150. package/src/http/middleware/ProcessorPathSanitizer.ts +86 -0
  151. package/src/http/middleware/QueueNameSanitizer.ts +55 -0
  152. package/src/http/middleware/ValidateDriver.ts +29 -0
  153. package/src/http/middleware/VersionSanitizer.ts +30 -0
  154. package/src/http/middleware/WorkerNameSanitizer.ts +56 -0
  155. package/src/http/middleware/WorkerValidationChain.ts +230 -0
  156. package/src/index.ts +98 -0
  157. package/src/routes/workers.ts +154 -0
  158. package/src/storage/WorkerStore.ts +240 -0
  159. package/src/type.ts +89 -0
  160. package/src/types/queue-monitor.d.ts +38 -0
  161. package/src/types/queue-redis.d.ts +38 -0
  162. package/src/ui/README.md +13 -0
  163. package/src/ui/components/JsonEditor.js +670 -0
  164. package/src/ui/components/JsonViewer.js +387 -0
  165. package/src/ui/components/WorkerCard.js +178 -0
  166. package/src/ui/components/WorkerExpandPanel.js +257 -0
  167. package/src/ui/components/fetcher.js +42 -0
  168. package/src/ui/components/sla-scorecard.js +32 -0
  169. package/src/ui/components/styles.css +30 -0
  170. package/src/ui/components/table-expander.js +34 -0
  171. package/src/ui/integration/worker-ui-integration.js +565 -0
  172. package/src/ui/router/ui.ts +99 -0
  173. package/src/ui/services/workerApi.js +240 -0
  174. package/src/ui/types/worker-ui.ts +283 -0
  175. package/src/ui/utils/jsonValidator.js +444 -0
  176. package/src/ui/workers/index.html +202 -0
  177. package/src/ui/workers/main.js +1781 -0
  178. package/src/ui/workers/styles.css +1350 -0
@@ -0,0 +1,295 @@
1
+ import { Logger, type IRequest, type IResponse } from '@zintrust/core';
2
+
3
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
4
+
5
+ const VALID_DRIVERS = new Set(['database', 'redis', 'memory']);
6
+ const VALID_DEAD_LETTER_POLICIES = new Set(['expire', 'retry', 'dead-letter']);
7
+
8
+ export interface InfrastructureConfig {
9
+ persistence: {
10
+ driver: string;
11
+ };
12
+ redis: {
13
+ env: boolean;
14
+ host: string;
15
+ port: string;
16
+ db: string;
17
+ password: string;
18
+ };
19
+ deadLetterQueue: {
20
+ policy: string;
21
+ };
22
+ compliance: {
23
+ config: {
24
+ retentionDays: number;
25
+ };
26
+ };
27
+ observability: {
28
+ enabled: boolean;
29
+ };
30
+ autoScaler: {
31
+ enabled: boolean;
32
+ minWorkers: number;
33
+ maxWorkers: number;
34
+ };
35
+ }
36
+
37
+ const validatePersistence = (persistence: InfrastructureConfig['persistence']): string | null => {
38
+ if (!persistence) return 'Persistence configuration is required';
39
+
40
+ // Validate persistence driver
41
+ if (!persistence.driver) {
42
+ return 'Persistence driver is required';
43
+ }
44
+
45
+ if (!VALID_DRIVERS.has(persistence.driver)) {
46
+ return 'Persistence driver must be one of: database, redis, memory';
47
+ }
48
+
49
+ return null;
50
+ };
51
+
52
+ const validateRedis = (redis: InfrastructureConfig['redis']): string | null => {
53
+ if (!redis) return 'Redis configuration is required';
54
+
55
+ // Validate env flag
56
+ if (typeof redis.env !== 'boolean') {
57
+ return 'Redis env flag must be a boolean';
58
+ }
59
+
60
+ // Validate required fields when not using env
61
+ if (!redis.env) {
62
+ const requiredFieldsError = validateRequiredRedisFields(redis);
63
+ if (requiredFieldsError) return requiredFieldsError;
64
+ }
65
+
66
+ // Validate string fields
67
+ return validateRedisStringFields(redis);
68
+ };
69
+
70
+ const validateRequiredRedisFields = (redis: InfrastructureConfig['redis']): string | null => {
71
+ if (!redis.host || typeof redis.host !== 'string') {
72
+ return 'Redis host is required when env is false';
73
+ }
74
+ if (redis.port === undefined || redis.port === null) {
75
+ return 'Redis port is required when env is false';
76
+ }
77
+ if (typeof redis.port !== 'string' && typeof redis.port !== 'number') {
78
+ return 'Redis port must be a string or number';
79
+ }
80
+ if (!redis.db || typeof redis.db !== 'string') {
81
+ return 'Redis db is required when env is false';
82
+ }
83
+ return null;
84
+ };
85
+
86
+ const validateRedisStringFields = (redis: InfrastructureConfig['redis']): string | null => {
87
+ if (redis.host && typeof redis.host !== 'string') {
88
+ return 'Redis host must be a string';
89
+ }
90
+ if (redis.port && typeof redis.port !== 'string' && typeof redis.port !== 'number') {
91
+ return 'Redis port must be a string or number';
92
+ }
93
+ if (redis.db && typeof redis.db !== 'string') {
94
+ return 'Redis db must be a string';
95
+ }
96
+ if (redis.password && typeof redis.password !== 'string') {
97
+ return 'Redis password must be a string';
98
+ }
99
+ return null;
100
+ };
101
+
102
+ const validateDeadLetterQueue = (
103
+ deadLetterQueue: InfrastructureConfig['deadLetterQueue']
104
+ ): string | null => {
105
+ if (!deadLetterQueue) return 'DeadLetterQueue configuration is required';
106
+
107
+ // Validate policy
108
+ if (!deadLetterQueue.policy) {
109
+ return 'DeadLetterQueue policy is required';
110
+ }
111
+
112
+ if (!VALID_DEAD_LETTER_POLICIES.has(deadLetterQueue.policy)) {
113
+ return 'Policy must be one of: expire, retry, dead-letter';
114
+ }
115
+
116
+ return null;
117
+ };
118
+
119
+ const validateCompliance = (compliance: InfrastructureConfig['compliance']): string | null => {
120
+ if (!compliance) return 'Compliance configuration is required';
121
+
122
+ if (!compliance.config) {
123
+ return 'Compliance config is required';
124
+ }
125
+
126
+ if (typeof compliance.config.retentionDays !== 'number' || compliance.config.retentionDays < 0) {
127
+ return 'Retention days must be a non-negative number';
128
+ }
129
+ const MAX_RETENTION_DAYS = 3650; // ~10 years
130
+ if (compliance.config.retentionDays > MAX_RETENTION_DAYS) {
131
+ return `Retention days cannot exceed ${MAX_RETENTION_DAYS}`;
132
+ }
133
+
134
+ return null;
135
+ };
136
+
137
+ const validateObservability = (
138
+ observability: InfrastructureConfig['observability']
139
+ ): string | null => {
140
+ if (!observability) return 'Observability configuration is required';
141
+
142
+ if (typeof observability.enabled !== 'boolean') {
143
+ return 'Observability enabled flag must be a boolean';
144
+ }
145
+
146
+ return null;
147
+ };
148
+
149
+ const validateAutoScaler = (autoScaler: InfrastructureConfig['autoScaler']): string | null => {
150
+ if (!autoScaler) return 'AutoScaler configuration is required';
151
+
152
+ if (typeof autoScaler.enabled !== 'boolean') {
153
+ return 'AutoScaler enabled flag must be a boolean';
154
+ }
155
+
156
+ if (autoScaler.enabled) {
157
+ const minWorkersError = validateWorkerCount(autoScaler.minWorkers, 'minWorkers');
158
+ if (minWorkersError) return minWorkersError;
159
+
160
+ const maxWorkersError = validateWorkerCount(autoScaler.maxWorkers, 'maxWorkers');
161
+ if (maxWorkersError) return maxWorkersError;
162
+
163
+ if (autoScaler.minWorkers > autoScaler.maxWorkers) {
164
+ return 'AutoScaler minWorkers cannot be greater than maxWorkers';
165
+ }
166
+ const MAX_AUTOSCALER_WORKERS = 1000;
167
+ if (autoScaler.maxWorkers > MAX_AUTOSCALER_WORKERS) {
168
+ return `AutoScaler maxWorkers cannot exceed ${MAX_AUTOSCALER_WORKERS}`;
169
+ }
170
+ }
171
+
172
+ return null;
173
+ };
174
+
175
+ const validateWorkerCount = (value: number, fieldName: string): string | null => {
176
+ if (typeof value !== 'number') {
177
+ return `AutoScaler ${fieldName} must be a number`;
178
+ }
179
+
180
+ if (!Number.isInteger(value)) {
181
+ return `AutoScaler ${fieldName} must be a whole number (integer)`;
182
+ }
183
+
184
+ if (value < 0) {
185
+ return `AutoScaler ${fieldName} must be a non-negative number`;
186
+ }
187
+
188
+ return null;
189
+ };
190
+
191
+ const sanitizeInfrastructure = (infrastructure: InfrastructureConfig): InfrastructureConfig => {
192
+ return {
193
+ ...infrastructure,
194
+ autoScaler: {
195
+ ...infrastructure.autoScaler,
196
+ minWorkers: Math.floor(infrastructure.autoScaler.minWorkers),
197
+ maxWorkers: Math.floor(infrastructure.autoScaler.maxWorkers),
198
+ },
199
+ };
200
+ };
201
+
202
+ export const withInfrastructureValidation = (handler: RouteHandler): RouteHandler => {
203
+ return async (req: IRequest, res: IResponse): Promise<void> => {
204
+ try {
205
+ const data = req.data();
206
+ const infrastructure = data['infrastructure'] as InfrastructureConfig;
207
+
208
+ if (!infrastructure) {
209
+ return res.setStatus(400).json({
210
+ error: 'Infrastructure configuration is required',
211
+ code: 'MISSING_INFRASTRUCTURE',
212
+ });
213
+ }
214
+
215
+ // Validate persistence
216
+ const persistenceError = validatePersistence(infrastructure.persistence);
217
+ if (persistenceError) {
218
+ return res.setStatus(400).json({
219
+ error: 'Invalid persistence configuration',
220
+ message: persistenceError,
221
+ code: 'INVALID_PERSISTENCE_CONFIG',
222
+ });
223
+ }
224
+
225
+ // Validate redis
226
+ const redisError = validateRedis(infrastructure.redis);
227
+ if (redisError) {
228
+ return res.setStatus(400).json({
229
+ error: 'Invalid redis configuration',
230
+ message: redisError,
231
+ code: 'INVALID_REDIS_CONFIG',
232
+ });
233
+ }
234
+
235
+ // Validate deadLetterQueue
236
+ const deadLetterQueueError = validateDeadLetterQueue(infrastructure.deadLetterQueue);
237
+ if (deadLetterQueueError) {
238
+ return res.setStatus(400).json({
239
+ error: 'Invalid deadLetterQueue configuration',
240
+ message: deadLetterQueueError,
241
+ code: 'INVALID_DEAD_LETTER_QUEUE_CONFIG',
242
+ });
243
+ }
244
+
245
+ // Validate compliance
246
+ const complianceError = validateCompliance(infrastructure.compliance);
247
+ if (complianceError) {
248
+ return res.setStatus(400).json({
249
+ error: 'Invalid compliance configuration',
250
+ message: complianceError,
251
+ code: 'INVALID_COMPLIANCE_CONFIG',
252
+ });
253
+ }
254
+
255
+ // Validate observability
256
+ const observabilityError = validateObservability(infrastructure.observability);
257
+ if (observabilityError) {
258
+ return res.setStatus(400).json({
259
+ error: 'Invalid observability configuration',
260
+ message: observabilityError,
261
+ code: 'INVALID_OBSERVABILITY_CONFIG',
262
+ });
263
+ }
264
+
265
+ // Validate autoScaler
266
+ const autoScalerError = validateAutoScaler(infrastructure.autoScaler);
267
+ if (autoScalerError) {
268
+ return res.setStatus(400).json({
269
+ error: 'Invalid autoScaler configuration',
270
+ message: autoScalerError,
271
+ code: 'INVALID_AUTO_SCALER_CONFIG',
272
+ });
273
+ }
274
+
275
+ // Sanitize infrastructure values
276
+ const currentBody = req.getBody() as Record<string, unknown>;
277
+ const sanitizedInfrastructure = sanitizeInfrastructure(infrastructure);
278
+
279
+ // Update the infrastructure in the request body
280
+ const updatedBody = {
281
+ ...currentBody,
282
+ infrastructure: sanitizedInfrastructure,
283
+ };
284
+ req.setBody(updatedBody);
285
+
286
+ return handler(req, res);
287
+ } catch (error) {
288
+ Logger.error('Infrastructure validation failed', error);
289
+ return res.setStatus(500).json({
290
+ error: 'Internal validation error',
291
+ code: 'VALIDATION_ERROR',
292
+ });
293
+ }
294
+ };
295
+ };
@@ -0,0 +1,144 @@
1
+ import { Logger, type IRequest, type IResponse } from '@zintrust/core';
2
+
3
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
4
+
5
+ interface OptionsConfig {
6
+ concurrency: number;
7
+ limiter: {
8
+ max: number;
9
+ duration: number;
10
+ };
11
+ }
12
+
13
+ const validateConcurrency = (concurrency: unknown): string | null => {
14
+ if (concurrency === undefined || concurrency === null) {
15
+ return 'Concurrency is required';
16
+ }
17
+
18
+ if (typeof concurrency !== 'number') {
19
+ return 'Concurrency must be a number';
20
+ }
21
+
22
+ if (!Number.isInteger(concurrency)) {
23
+ return 'Concurrency must be a whole number (integer)';
24
+ }
25
+
26
+ if (concurrency < 1) {
27
+ return 'Concurrency must be at least 1';
28
+ }
29
+
30
+ const MAX_CONCURRENCY = 200;
31
+ if (concurrency > MAX_CONCURRENCY) {
32
+ return `Concurrency cannot exceed ${MAX_CONCURRENCY}`;
33
+ }
34
+
35
+ return null;
36
+ };
37
+
38
+ const validateLimiter = (limiter: OptionsConfig['limiter']): string | null => {
39
+ if (!limiter) {
40
+ return 'Limiter configuration is required';
41
+ }
42
+
43
+ // Validate max
44
+ if (limiter.max === undefined || limiter.max === null) {
45
+ return 'Limiter max is required';
46
+ }
47
+
48
+ if (typeof limiter.max !== 'number') {
49
+ return 'Limiter max must be a number';
50
+ }
51
+
52
+ if (!Number.isInteger(limiter.max)) {
53
+ return 'Limiter max must be a whole number (integer)';
54
+ }
55
+
56
+ if (limiter.max < 1) {
57
+ return 'Limiter max must be at least 1';
58
+ }
59
+ const MAX_LIMITER_MAX = 100000;
60
+ if (limiter.max > MAX_LIMITER_MAX) {
61
+ return `Limiter max cannot exceed ${MAX_LIMITER_MAX}`;
62
+ }
63
+
64
+ // Validate duration
65
+ if (limiter.duration === undefined || limiter.duration === null) {
66
+ return 'Limiter duration is required';
67
+ }
68
+
69
+ if (typeof limiter.duration !== 'number') {
70
+ return 'Limiter duration must be a number';
71
+ }
72
+
73
+ if (!Number.isInteger(limiter.duration)) {
74
+ return 'Limiter duration must be a whole number (integer)';
75
+ }
76
+
77
+ if (limiter.duration < 1000) {
78
+ return 'Limiter duration must be at least 1000ms';
79
+ }
80
+ const MAX_LIMITER_DURATION = 24 * 60 * 60 * 1000; // 1 day
81
+ if (limiter.duration > MAX_LIMITER_DURATION) {
82
+ return `Limiter duration cannot exceed ${MAX_LIMITER_DURATION} ms`;
83
+ }
84
+
85
+ return null;
86
+ };
87
+
88
+ export const withOptionsValidation = (handler: RouteHandler): RouteHandler => {
89
+ return async (req: IRequest, res: IResponse): Promise<void> => {
90
+ try {
91
+ const data = req.data();
92
+ const options = data['options'] as OptionsConfig;
93
+
94
+ if (!options) {
95
+ return res.setStatus(400).json({
96
+ error: 'Options configuration is required',
97
+ code: 'MISSING_OPTIONS',
98
+ });
99
+ }
100
+
101
+ // Validate concurrency
102
+ const concurrencyError = validateConcurrency(options.concurrency);
103
+ if (concurrencyError) {
104
+ return res.setStatus(400).json({
105
+ error: 'Invalid concurrency',
106
+ message: concurrencyError,
107
+ code: 'INVALID_CONCURRENCY',
108
+ });
109
+ }
110
+
111
+ // Validate limiter
112
+ const limiterError = validateLimiter(options.limiter);
113
+ if (limiterError) {
114
+ return res.setStatus(400).json({
115
+ error: 'Invalid limiter configuration',
116
+ message: limiterError,
117
+ code: 'INVALID_LIMITER_CONFIG',
118
+ });
119
+ }
120
+
121
+ // Sanitize concurrency to ensure it's an integer
122
+ const currentBody = req.getBody() as Record<string, unknown>;
123
+ const sanitizedOptions = {
124
+ ...options,
125
+ concurrency: Math.floor(options.concurrency),
126
+ limiter: {
127
+ ...options.limiter,
128
+ max: Math.floor(options.limiter.max),
129
+ duration: Math.floor(options.limiter.duration),
130
+ },
131
+ };
132
+
133
+ req.setBody({ ...currentBody, options: sanitizedOptions });
134
+
135
+ return handler(req, res);
136
+ } catch (error) {
137
+ Logger.error('Options validation failed', error);
138
+ return res.setStatus(500).json({
139
+ error: 'Internal validation error',
140
+ code: 'VALIDATION_ERROR',
141
+ });
142
+ }
143
+ };
144
+ };
@@ -0,0 +1,52 @@
1
+ import { Logger, type IRequest, type IResponse } from '@zintrust/core';
2
+
3
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
4
+
5
+ /**
6
+ * Middleware to strip unknown properties from the request body.
7
+ * Only properties included in the allowedKeys list are preserved.
8
+ */
9
+ export const withStrictPayloadKeys = (
10
+ allowedKeys: string[],
11
+ handler: RouteHandler
12
+ ): RouteHandler => {
13
+ const allowedSet = new Set(allowedKeys);
14
+
15
+ return async (req: IRequest, res: IResponse): Promise<void> => {
16
+ try {
17
+ const data = req.data();
18
+
19
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
20
+ // If body is not an object, skip stripping or strictly enforce object?
21
+ // For worker creation, it must be an object.
22
+ // Let's rely on downstream validators to complain if data is missing/wrong type.
23
+ return handler(req, res);
24
+ }
25
+
26
+ const body = data as Record<string, unknown>;
27
+ const strippedBody: Record<string, unknown> = {};
28
+ let hasUnknowns = false;
29
+
30
+ for (const key of Object.keys(body)) {
31
+ if (allowedSet.has(key)) {
32
+ strippedBody[key] = body[key];
33
+ } else {
34
+ hasUnknowns = true;
35
+ }
36
+ }
37
+
38
+ if (hasUnknowns) {
39
+ // Update the body with sanitized version
40
+ req.setBody(strippedBody);
41
+ }
42
+
43
+ return handler(req, res);
44
+ } catch (error) {
45
+ Logger.error('Strict payload validation failed', error);
46
+ return res.setStatus(500).json({
47
+ error: 'Internal validation error',
48
+ code: 'VALIDATION_ERROR',
49
+ });
50
+ }
51
+ };
52
+ };
@@ -0,0 +1,86 @@
1
+ import { Logger, NodeSingletons, type IRequest, type IResponse } from '@zintrust/core';
2
+
3
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
4
+
5
+ const PROCESSOR_PATH_PATTERN = /^[a-zA-Z0-9/_.-]+\.(ts|js)$/;
6
+
7
+ const decodeProcessorPath = (processor: string): string => {
8
+ return processor
9
+ .replaceAll('&#x2F;', '/') // HTML hex entity for /
10
+ .replaceAll('%2F', '/') // URL encoding for /
11
+ .replaceAll('&#x2E;', '.') // HTML hex entity for .
12
+ .replaceAll('%2E', '.') // URL encoding for .
13
+ .replaceAll('&#x5F;', '_') // HTML hex entity for _
14
+ .replaceAll('%5F', '_') // URL encoding for _
15
+ .replaceAll('&#x2D;', '-') // HTML hex entity for -
16
+ .replaceAll('%2D', '-'); // URL encoding for -
17
+ };
18
+
19
+ export const withProcessorPathValidation = (handler: RouteHandler): RouteHandler => {
20
+ return async (req: IRequest, res: IResponse): Promise<void> => {
21
+ try {
22
+ const data = req.data();
23
+ let processor = data['processor'] as string;
24
+
25
+ if (!processor) {
26
+ return res.setStatus(400).json({
27
+ error: 'Processor path is required',
28
+ code: 'MISSING_PROCESSOR_PATH',
29
+ });
30
+ }
31
+
32
+ // Decode URL-encoded characters
33
+ processor = decodeProcessorPath(processor);
34
+
35
+ // Trim whitespace
36
+ processor = processor.trim();
37
+
38
+ // Prevent path traversal
39
+ if (processor.includes('..') || processor.startsWith('/')) {
40
+ return res.setStatus(400).json({
41
+ error: 'Invalid processor path',
42
+ message: 'Processor path must be relative and cannot contain path traversal',
43
+ code: 'INVALID_PROCESSOR_PATH',
44
+ });
45
+ }
46
+
47
+ if (!PROCESSOR_PATH_PATTERN.test(processor)) {
48
+ Logger.error('Processor path validation failed', {
49
+ processor,
50
+ pattern: PROCESSOR_PATH_PATTERN.toString(),
51
+ testResult: PROCESSOR_PATH_PATTERN.test(processor),
52
+ });
53
+ return res.setStatus(400).json({
54
+ error: 'Invalid processor path',
55
+ message: `Processor must be a TypeScript or JavaScript file. Got: "${processor}"`,
56
+ code: 'INVALID_PROCESSOR_EXTENSION',
57
+ });
58
+ }
59
+
60
+ // Sanitize the processor path (remove any invalid characters just in case)
61
+ const sanitizedProcessor = processor.replaceAll(/[^a-zA-Z0-9/_.-]/g, '');
62
+ const path = NodeSingletons.path;
63
+ // Ensure resolved path stays within repository/app scope
64
+ const BASE_PROCESSOR_DIR = path.resolve(process.cwd());
65
+ const resolved = path.resolve(BASE_PROCESSOR_DIR, sanitizedProcessor);
66
+ if (!resolved.startsWith(BASE_PROCESSOR_DIR)) {
67
+ return res.setStatus(400).json({
68
+ error: 'Invalid processor path',
69
+ message: 'Processor path resolves outside of allowed base directory',
70
+ code: 'INVALID_PROCESSOR_PATH_TRAVERSAL',
71
+ });
72
+ }
73
+
74
+ const currentBody = req.getBody() as Record<string, unknown>;
75
+ req.setBody({ ...currentBody, processor: sanitizedProcessor });
76
+
77
+ return handler(req, res);
78
+ } catch (error) {
79
+ Logger.error('Processor path validation failed', error);
80
+ return res.setStatus(500).json({
81
+ error: 'Internal validation error',
82
+ code: 'VALIDATION_ERROR',
83
+ });
84
+ }
85
+ };
86
+ };
@@ -0,0 +1,55 @@
1
+ import { Logger, type IRequest, type IResponse } from '@zintrust/core';
2
+
3
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
4
+
5
+ const QUEUE_NAME_PATTERN = /^[a-zA-Z0-9_-]{3,50}$/;
6
+
7
+ export const withQueueNameValidation = (handler: RouteHandler): RouteHandler => {
8
+ return async (req: IRequest, res: IResponse): Promise<void> => {
9
+ try {
10
+ const data = req.data();
11
+ const queueName = data['queueName'] as string;
12
+
13
+ if (!queueName) {
14
+ return res.setStatus(400).json({
15
+ error: 'Queue name is required',
16
+ code: 'MISSING_QUEUE_NAME',
17
+ });
18
+ }
19
+
20
+ if (!QUEUE_NAME_PATTERN.test(queueName)) {
21
+ return res.setStatus(400).json({
22
+ error: 'Invalid queue name',
23
+ message:
24
+ 'Queue name must be 3-50 characters long and contain only letters, numbers, hyphens, and underscores',
25
+ code: 'INVALID_QUEUE_NAME',
26
+ });
27
+ }
28
+
29
+ // Sanitize the queue name
30
+ const sanitizedQueueName = queueName
31
+ .trim()
32
+ .replaceAll(/[^a-zA-Z0-9_-]/g, '')
33
+ .substring(0, 50);
34
+
35
+ if (sanitizedQueueName.length < 3) {
36
+ return res.setStatus(400).json({
37
+ error: 'Queue name too short after sanitization',
38
+ message: 'Queue name must be at least 3 characters long',
39
+ code: 'QUEUE_NAME_TOO_SHORT',
40
+ });
41
+ }
42
+
43
+ const currentBody = req.getBody() as Record<string, unknown>;
44
+ req.setBody({ ...currentBody, queueName: sanitizedQueueName });
45
+
46
+ return handler(req, res);
47
+ } catch (error) {
48
+ Logger.error('Queue name validation failed', error);
49
+ return res.setStatus(500).json({
50
+ error: 'Internal validation error',
51
+ code: 'VALIDATION_ERROR',
52
+ });
53
+ }
54
+ };
55
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Validate Driver Middleware
3
+ * Ensures the 'driver' query parameter is valid if present.
4
+ */
5
+
6
+ import type { IRequest, IResponse } from '@zintrust/core';
7
+
8
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
9
+
10
+ const VALID_DRIVERS = new Set(['database', 'redis', 'memory']);
11
+
12
+ export const withDriverValidation = (handler: RouteHandler): RouteHandler => {
13
+ return async (req: IRequest, res: IResponse): Promise<void> => {
14
+ const driver = req.getQueryParam('driver');
15
+
16
+ // Normalize to string if it's an array (take first)
17
+ const driverValue = Array.isArray(driver) ? driver[0] : driver;
18
+
19
+ if (driverValue && !VALID_DRIVERS.has(driverValue)) {
20
+ res.setStatus(400).json({
21
+ error: 'Invalid driver parameter',
22
+ message: 'Driver must be one of: database, redis, memory',
23
+ });
24
+ return;
25
+ }
26
+
27
+ return handler(req, res);
28
+ };
29
+ };
@@ -0,0 +1,30 @@
1
+ import { Logger, type IRequest, type IResponse } from '@zintrust/core';
2
+
3
+ export type RouteHandler = (req: IRequest, res: IResponse) => Promise<void> | void;
4
+
5
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+$/;
6
+
7
+ export const withVersionValidation = (handler: RouteHandler): RouteHandler => {
8
+ return async (req: IRequest, res: IResponse): Promise<void> => {
9
+ try {
10
+ const data = req.data();
11
+ const version = data['version'] as string;
12
+
13
+ if (version && !VERSION_PATTERN.test(version)) {
14
+ return res.setStatus(400).json({
15
+ error: 'Invalid version format',
16
+ message: 'Version must follow semantic versioning (e.g., 1.0.0)',
17
+ code: 'INVALID_VERSION_FORMAT',
18
+ });
19
+ }
20
+
21
+ return handler(req, res);
22
+ } catch (error) {
23
+ Logger.error('Version validation failed', error);
24
+ return res.setStatus(500).json({
25
+ error: 'Internal validation error',
26
+ code: 'VALIDATION_ERROR',
27
+ });
28
+ }
29
+ };
30
+ };