pepr 0.42.2 → 0.42.3

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.
package/dist/cli.js CHANGED
@@ -91,9 +91,8 @@ var import_esbuild2 = require("esbuild");
91
91
  var import_fs9 = require("fs");
92
92
  var import_path3 = require("path");
93
93
 
94
- // src/lib/assets/index.ts
95
- var import_crypto3 = __toESM(require("crypto"));
96
- var import_client_node2 = require("@kubernetes/client-node");
94
+ // src/lib/assets/assets.ts
95
+ var import_crypto2 = __toESM(require("crypto"));
97
96
 
98
97
  // src/lib/tls.ts
99
98
  var import_node_forge = __toESM(require("node-forge"));
@@ -152,1567 +151,1553 @@ function genCert(key, name2, issuer) {
152
151
  return crt;
153
152
  }
154
153
 
155
- // src/lib/assets/deploy.ts
156
- var import_crypto = __toESM(require("crypto"));
157
- var import_fs = require("fs");
158
- var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
159
-
160
- // src/lib/telemetry/logger.ts
161
- var import_pino = require("pino");
162
- var isPrettyLog = true;
163
- var pretty = {
164
- target: "pino-pretty",
165
- options: {
166
- colorize: true
167
- }
168
- };
169
- var transport = isPrettyLog ? pretty : void 0;
170
- var pinoTimeFunction = process.env.PINO_TIME_STAMP === "iso" ? () => import_pino.stdTimeFunctions.isoTime() : () => import_pino.stdTimeFunctions.epochTime();
171
- var Log = (0, import_pino.pino)({
172
- transport,
173
- timestamp: pinoTimeFunction
174
- });
175
- if (process.env.LOG_LEVEL) {
176
- Log.level = process.env.LOG_LEVEL;
177
- }
178
- var logger_default = Log;
179
-
180
- // src/lib/assets/networking.ts
181
- function apiTokenSecret(name2, apiToken) {
182
- return {
183
- apiVersion: "v1",
184
- kind: "Secret",
185
- metadata: {
186
- name: `${name2}-api-token`,
187
- namespace: "pepr-system"
188
- },
189
- type: "Opaque",
190
- data: {
191
- value: Buffer.from(apiToken).toString("base64")
192
- }
193
- };
194
- }
195
- function tlsSecret(name2, tls) {
196
- return {
197
- apiVersion: "v1",
198
- kind: "Secret",
199
- metadata: {
200
- name: `${name2}-tls`,
201
- namespace: "pepr-system"
202
- },
203
- type: "kubernetes.io/tls",
204
- data: {
205
- "tls.crt": tls.crt,
206
- "tls.key": tls.key
207
- }
208
- };
209
- }
210
- function service(name2) {
211
- return {
212
- apiVersion: "v1",
213
- kind: "Service",
214
- metadata: {
215
- name: name2,
216
- namespace: "pepr-system",
217
- labels: {
218
- "pepr.dev/controller": "admission"
219
- }
220
- },
221
- spec: {
222
- selector: {
223
- app: name2,
224
- "pepr.dev/controller": "admission"
225
- },
226
- ports: [
227
- {
228
- port: 443,
229
- targetPort: 3e3
230
- }
231
- ]
232
- }
233
- };
154
+ // src/lib/assets/helm.ts
155
+ function clusterRoleTemplate() {
156
+ return `
157
+ apiVersion: rbac.authorization.k8s.io/v1
158
+ kind: ClusterRole
159
+ metadata:
160
+ name: {{ .Values.uuid }}
161
+ namespace: pepr-system
162
+ rules:
163
+ {{- if .Values.rbac }}
164
+ {{- toYaml .Values.rbac | nindent 2 }}
165
+ {{- end }}
166
+ `;
234
167
  }
235
- function watcherService(name2) {
236
- return {
237
- apiVersion: "v1",
238
- kind: "Service",
239
- metadata: {
240
- name: `${name2}-watcher`,
241
- namespace: "pepr-system",
242
- labels: {
243
- "pepr.dev/controller": "watcher"
244
- }
245
- },
246
- spec: {
247
- selector: {
248
- app: `${name2}-watcher`,
249
- "pepr.dev/controller": "watcher"
250
- },
251
- ports: [
252
- {
253
- port: 443,
254
- targetPort: 3e3
255
- }
256
- ]
257
- }
258
- };
168
+ function namespaceTemplate() {
169
+ return `
170
+ apiVersion: v1
171
+ kind: Namespace
172
+ metadata:
173
+ name: pepr-system
174
+ {{- if .Values.namespace.annotations }}
175
+ annotations:
176
+ {{- toYaml .Values.namespace.annotations | nindent 6 }}
177
+ {{- end }}
178
+ {{- if .Values.namespace.labels }}
179
+ labels:
180
+ {{- toYaml .Values.namespace.labels | nindent 6 }}
181
+ {{- end }}
182
+ `;
259
183
  }
184
+ function chartYaml(name2, description) {
185
+ return `
186
+ apiVersion: v2
187
+ name: ${name2}
188
+ description: ${description || ""}
260
189
 
261
- // src/lib/assets/pods.ts
262
- var import_zlib = require("zlib");
190
+ # A chart can be either an 'application' or a 'library' chart.
191
+ #
192
+ # Application charts are a collection of templates that can be packaged into versioned archives
193
+ # to be deployed.
194
+ #
195
+ # Library charts provide useful utilities or functions for the chart developer. They're included as
196
+ # a dependency of application charts to inject those utilities and functions into the rendering
197
+ # pipeline. Library charts do not define any templates and therefore cannot be deployed.
198
+ type: application
263
199
 
264
- // src/sdk/sdk.ts
265
- var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
266
- function sanitizeResourceName(name2) {
267
- return name2.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 250).replace(/^[^a-z]+|[^a-z]+$/g, "");
268
- }
200
+ # This is the chart version. This version number should be incremented each time you make changes
201
+ # to the chart and its templates, including the app version.
202
+ # Versions are expected to follow Semantic Versioning (https://semver.org/)
203
+ version: 0.1.0
269
204
 
270
- // src/lib/helpers.ts
271
- function matchesRegex(pattern, testString) {
272
- return new RegExp(pattern).test(testString);
273
- }
274
- var ValidationError = class extends Error {
275
- };
276
- function validateCapabilityNames(capabilities) {
277
- if (capabilities && capabilities.length > 0) {
278
- for (let i = 0; i < capabilities.length; i++) {
279
- if (capabilities[i].name !== sanitizeResourceName(capabilities[i].name)) {
280
- throw new ValidationError(`Capability name is not a valid Kubernetes resource name: ${capabilities[i].name}`);
281
- }
282
- }
283
- }
284
- }
285
- function createRBACMap(capabilities) {
286
- return capabilities.reduce((acc, capability) => {
287
- capability.bindings.forEach((binding) => {
288
- const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;
289
- acc["pepr.dev/v1/peprstore"] = {
290
- verbs: ["create", "get", "patch", "watch"],
291
- plural: "peprstores"
292
- };
293
- acc["apiextensions.k8s.io/v1/customresourcedefinition"] = {
294
- verbs: ["patch", "create"],
295
- plural: "customresourcedefinitions"
296
- };
297
- if (!acc[key] && binding.isWatch) {
298
- acc[key] = {
299
- verbs: ["watch"],
300
- plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`
301
- };
302
- }
303
- if (binding.isFinalize) {
304
- acc[key] = {
305
- verbs: ["patch"],
306
- plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`
307
- };
308
- }
309
- });
310
- return acc;
311
- }, {});
312
- }
313
- function hasEveryOverlap(array1, array2) {
314
- if (!Array.isArray(array1) || !Array.isArray(array2)) {
315
- return false;
316
- }
317
- return array1.every((element) => array2.includes(element));
318
- }
319
- function hasAnyOverlap(array1, array2) {
320
- if (!Array.isArray(array1) || !Array.isArray(array2)) {
321
- return false;
322
- }
323
- return array1.some((element) => array2.includes(element));
324
- }
325
- function ignoredNamespaceConflict(ignoreNamespaces, bindingNamespaces) {
326
- return hasAnyOverlap(bindingNamespaces, ignoreNamespaces);
327
- }
328
- function bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces) {
329
- if (!capabilityNamespaces) {
330
- return false;
331
- }
332
- return capabilityNamespaces.length !== 0 && !hasEveryOverlap(bindingNamespaces, capabilityNamespaces);
333
- }
334
- function generateWatchNamespaceError(ignoredNamespaces, bindingNamespaces, capabilityNamespaces) {
335
- let err = "";
336
- if (ignoredNamespaceConflict(ignoredNamespaces, bindingNamespaces)) {
337
- err += `Binding uses a Pepr ignored namespace: ignoredNamespaces: [${ignoredNamespaces.join(
338
- ", "
339
- )}] bindingNamespaces: [${bindingNamespaces.join(", ")}].`;
340
- }
341
- if (bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces)) {
342
- err += `Binding uses namespace not governed by capability: bindingNamespaces: [${bindingNamespaces.join(
343
- ", "
344
- )}] capabilityNamespaces: [${capabilityNamespaces.join(", ")}].`;
345
- }
346
- return err.replace(/\.([^ ])/g, ". $1");
205
+ # This is the version number of the application being deployed. This version number should be
206
+ # incremented each time you make changes to the application. Versions are not expected to
207
+ # follow Semantic Versioning. They should reflect the version the application is using.
208
+ # It is recommended to use it with quotes.
209
+ appVersion: "1.16.0"
210
+ `;
347
211
  }
348
- function namespaceComplianceValidator(capability, ignoredNamespaces) {
349
- const { namespaces: capabilityNamespaces, bindings, name: name2 } = capability;
350
- const bindingNamespaces = bindings.flatMap((binding) => binding.filters.namespaces);
351
- const bindingRegexNamespaces = bindings.flatMap(
352
- (binding) => binding.filters.regexNamespaces || []
353
- );
354
- const namespaceError = generateWatchNamespaceError(
355
- ignoredNamespaces ? ignoredNamespaces : [],
356
- bindingNamespaces,
357
- capabilityNamespaces ? capabilityNamespaces : []
358
- );
359
- if (namespaceError !== "") {
360
- throw new Error(
361
- `Error in ${name2} capability. A binding violates namespace rules. Please check ignoredNamespaces and capability namespaces: ${namespaceError}`
362
- );
363
- }
364
- matchRegexToCapababilityNamespace(bindingRegexNamespaces, capabilityNamespaces);
365
- checkRegexNamespaces(bindingRegexNamespaces, ignoredNamespaces);
366
- }
367
- var matchRegexToCapababilityNamespace = (bindingRegexNamespaces, capabilityNamespaces) => {
368
- if (bindingRegexNamespaces.length > 0 && capabilityNamespaces && capabilityNamespaces.length > 0) {
369
- for (const regexNamespace of bindingRegexNamespaces) {
370
- let matches = false;
371
- matches = regexNamespace !== "" && capabilityNamespaces.some((capabilityNamespace) => matchesRegex(regexNamespace, capabilityNamespace));
372
- if (!matches) {
373
- throw new Error(
374
- `Ignoring Watch Callback: Object namespace does not match any capability namespace with regex ${regexNamespace}.`
375
- );
376
- }
377
- }
378
- }
379
- };
380
- var checkRegexNamespaces = (bindingRegexNamespaces, ignoredNamespaces) => {
381
- if (bindingRegexNamespaces.length > 0 && ignoredNamespaces && ignoredNamespaces.length > 0) {
382
- for (const regexNamespace of bindingRegexNamespaces) {
383
- const matchedNS = ignoredNamespaces.find((ignoredNS) => matchesRegex(regexNamespace, ignoredNS));
384
- if (matchedNS) {
385
- throw new Error(
386
- `Ignoring Watch Callback: Regex namespace: ${regexNamespace}, is an ignored namespace: ${matchedNS}.`
387
- );
388
- }
389
- }
390
- }
391
- };
392
- function secretOverLimit(str) {
393
- const encoder = new TextEncoder();
394
- const encoded = encoder.encode(str);
395
- const sizeInBytes = encoded.length;
396
- const oneMiBInBytes = 1048576;
397
- return sizeInBytes > oneMiBInBytes;
398
- }
399
- var parseTimeout = (value) => {
400
- const parsedValue = parseInt(value, 10);
401
- const floatValue = parseFloat(value);
402
- if (isNaN(parsedValue)) {
403
- throw new Error("Not a number.");
404
- } else if (parsedValue !== floatValue) {
405
- throw new Error("Value must be an integer.");
406
- } else if (parsedValue < 1 || parsedValue > 30) {
407
- throw new Error("Number must be between 1 and 30.");
408
- }
409
- return parsedValue;
410
- };
411
- function dedent(file) {
412
- const lines = file.split("\n");
413
- if (lines[0].trim() === "") {
414
- lines.shift();
415
- file = lines.join("\n");
416
- }
417
- const match = file.match(/^[ \t]*(?=\S)/gm);
418
- const indent = match && Math.min(...match.map((el) => el.length));
419
- if (indent && indent > 0) {
420
- const re = new RegExp(`^[ \\t]{${indent}}`, "gm");
421
- return file.replace(re, "");
422
- }
423
- return file;
424
- }
425
- function replaceString(str, stringA, stringB) {
426
- const escapedStringA = stringA.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
427
- const regExp = new RegExp(escapedStringA, "g");
428
- return str.replace(regExp, stringB);
429
- }
430
-
431
- // src/lib/assets/pods.ts
432
- function getNamespace(namespaceLabels) {
433
- if (namespaceLabels) {
434
- return {
435
- apiVersion: "v1",
436
- kind: "Namespace",
437
- metadata: {
438
- name: "pepr-system",
439
- labels: namespaceLabels ?? {}
440
- }
441
- };
442
- } else {
443
- return {
444
- apiVersion: "v1",
445
- kind: "Namespace",
446
- metadata: {
447
- name: "pepr-system"
448
- }
449
- };
450
- }
451
- }
452
- function getWatcher(assets, hash, buildTimestamp, imagePullSecret) {
453
- const { name: name2, image, capabilities, config } = assets;
454
- let hasSchedule = false;
455
- const app = `${name2}-watcher`;
456
- const bindings = [];
457
- for (const capability of capabilities) {
458
- if (capability.hasSchedule) {
459
- hasSchedule = true;
460
- }
461
- const watchers = capability.bindings.filter((binding) => binding.isWatch);
462
- bindings.push(...watchers);
463
- }
464
- if (bindings.length < 1 && !hasSchedule) {
465
- return null;
466
- }
467
- const deploy2 = {
468
- apiVersion: "apps/v1",
469
- kind: "Deployment",
470
- metadata: {
471
- name: app,
472
- namespace: "pepr-system",
473
- annotations: {
474
- "pepr.dev/description": config.description || ""
475
- },
476
- labels: {
477
- app,
478
- "pepr.dev/controller": "watcher",
479
- "pepr.dev/uuid": config.uuid
480
- }
481
- },
482
- spec: {
483
- replicas: 1,
484
- strategy: {
485
- type: "Recreate"
486
- },
487
- selector: {
488
- matchLabels: {
489
- app,
490
- "pepr.dev/controller": "watcher"
491
- }
492
- },
493
- template: {
494
- metadata: {
495
- annotations: {
496
- buildTimestamp: `${buildTimestamp}`
497
- },
498
- labels: {
499
- app,
500
- "pepr.dev/controller": "watcher"
501
- }
502
- },
503
- spec: {
504
- terminationGracePeriodSeconds: 5,
505
- serviceAccountName: name2,
506
- securityContext: {
507
- runAsUser: 65532,
508
- runAsGroup: 65532,
509
- runAsNonRoot: true,
510
- fsGroup: 65532
511
- },
512
- containers: [
513
- {
514
- name: "watcher",
515
- image,
516
- imagePullPolicy: "IfNotPresent",
517
- command: ["node", "/app/node_modules/pepr/dist/controller.js", hash],
518
- readinessProbe: {
519
- httpGet: {
520
- path: "/healthz",
521
- port: 3e3,
522
- scheme: "HTTPS"
523
- },
524
- initialDelaySeconds: 10
525
- },
526
- livenessProbe: {
527
- httpGet: {
528
- path: "/healthz",
529
- port: 3e3,
530
- scheme: "HTTPS"
531
- },
532
- initialDelaySeconds: 10
533
- },
534
- ports: [
535
- {
536
- containerPort: 3e3
537
- }
538
- ],
539
- resources: {
540
- requests: {
541
- memory: "256Mi",
542
- cpu: "200m"
543
- },
544
- limits: {
545
- memory: "512Mi",
546
- cpu: "500m"
547
- }
548
- },
549
- securityContext: {
550
- runAsUser: 65532,
551
- runAsGroup: 65532,
552
- runAsNonRoot: true,
553
- allowPrivilegeEscalation: false,
554
- capabilities: {
555
- drop: ["ALL"]
556
- }
557
- },
558
- volumeMounts: [
559
- {
560
- name: "tls-certs",
561
- mountPath: "/etc/certs",
562
- readOnly: true
563
- },
564
- {
565
- name: "module",
566
- mountPath: `/app/load`,
567
- readOnly: true
568
- }
569
- ],
570
- env: genEnv(config, true)
571
- }
572
- ],
573
- volumes: [
574
- {
575
- name: "tls-certs",
576
- secret: {
577
- secretName: `${name2}-tls`
578
- }
579
- },
580
- {
581
- name: "module",
582
- secret: {
583
- secretName: `${name2}-module`
584
- }
585
- }
586
- ]
587
- }
588
- }
589
- }
590
- };
591
- if (imagePullSecret) {
592
- deploy2.spec.template.spec.imagePullSecrets = [{ name: imagePullSecret }];
593
- }
594
- return deploy2;
595
- }
596
- function getDeployment(assets, hash, buildTimestamp, imagePullSecret) {
597
- const { name: name2, image, config } = assets;
598
- const app = name2;
599
- const deploy2 = {
600
- apiVersion: "apps/v1",
601
- kind: "Deployment",
602
- metadata: {
603
- name: name2,
604
- namespace: "pepr-system",
605
- annotations: {
606
- "pepr.dev/description": config.description || ""
607
- },
608
- labels: {
609
- app,
610
- "pepr.dev/controller": "admission",
611
- "pepr.dev/uuid": config.uuid
612
- }
613
- },
614
- spec: {
615
- replicas: 2,
616
- selector: {
617
- matchLabels: {
618
- app,
619
- "pepr.dev/controller": "admission"
620
- }
621
- },
622
- template: {
623
- metadata: {
624
- annotations: {
625
- buildTimestamp: `${buildTimestamp}`
626
- },
627
- labels: {
628
- app,
629
- "pepr.dev/controller": "admission"
630
- }
631
- },
632
- spec: {
633
- terminationGracePeriodSeconds: 5,
634
- priorityClassName: "system-node-critical",
635
- serviceAccountName: name2,
636
- securityContext: {
637
- runAsUser: 65532,
638
- runAsGroup: 65532,
639
- runAsNonRoot: true,
640
- fsGroup: 65532
641
- },
642
- containers: [
643
- {
644
- name: "server",
645
- image,
646
- imagePullPolicy: "IfNotPresent",
647
- command: ["node", "/app/node_modules/pepr/dist/controller.js", hash],
648
- readinessProbe: {
649
- httpGet: {
650
- path: "/healthz",
651
- port: 3e3,
652
- scheme: "HTTPS"
653
- },
654
- initialDelaySeconds: 10
655
- },
656
- livenessProbe: {
657
- httpGet: {
658
- path: "/healthz",
659
- port: 3e3,
660
- scheme: "HTTPS"
661
- },
662
- initialDelaySeconds: 10
663
- },
664
- ports: [
665
- {
666
- containerPort: 3e3
667
- }
668
- ],
669
- resources: {
670
- requests: {
671
- memory: "256Mi",
672
- cpu: "200m"
673
- },
674
- limits: {
675
- memory: "512Mi",
676
- cpu: "500m"
677
- }
678
- },
679
- env: genEnv(config),
680
- securityContext: {
681
- runAsUser: 65532,
682
- runAsGroup: 65532,
683
- runAsNonRoot: true,
684
- allowPrivilegeEscalation: false,
685
- capabilities: {
686
- drop: ["ALL"]
687
- }
688
- },
689
- volumeMounts: [
690
- {
691
- name: "tls-certs",
692
- mountPath: "/etc/certs",
693
- readOnly: true
694
- },
695
- {
696
- name: "api-token",
697
- mountPath: "/app/api-token",
698
- readOnly: true
699
- },
700
- {
701
- name: "module",
702
- mountPath: `/app/load`,
703
- readOnly: true
704
- }
705
- ]
706
- }
707
- ],
708
- volumes: [
709
- {
710
- name: "tls-certs",
711
- secret: {
712
- secretName: `${name2}-tls`
713
- }
714
- },
715
- {
716
- name: "api-token",
717
- secret: {
718
- secretName: `${name2}-api-token`
719
- }
720
- },
721
- {
722
- name: "module",
723
- secret: {
724
- secretName: `${name2}-module`
725
- }
726
- }
727
- ]
728
- }
729
- }
730
- }
731
- };
732
- if (imagePullSecret) {
733
- deploy2.spec.template.spec.imagePullSecrets = [{ name: imagePullSecret }];
734
- }
735
- return deploy2;
212
+ function watcherDeployTemplate(buildTimestamp) {
213
+ return `
214
+ apiVersion: apps/v1
215
+ kind: Deployment
216
+ metadata:
217
+ name: {{ .Values.uuid }}-watcher
218
+ namespace: pepr-system
219
+ annotations:
220
+ {{- toYaml .Values.watcher.annotations | nindent 4 }}
221
+ labels:
222
+ {{- toYaml .Values.watcher.labels | nindent 4 }}
223
+ spec:
224
+ replicas: 1
225
+ strategy:
226
+ type: Recreate
227
+ selector:
228
+ matchLabels:
229
+ app: {{ .Values.uuid }}-watcher
230
+ pepr.dev/controller: watcher
231
+ template:
232
+ metadata:
233
+ annotations:
234
+ buildTimestamp: "${buildTimestamp}"
235
+ {{- if .Values.watcher.podAnnotations }}
236
+ {{- toYaml .Values.watcher.podAnnotations | nindent 8 }}
237
+ {{- end }}
238
+ labels:
239
+ app: {{ .Values.uuid }}-watcher
240
+ pepr.dev/controller: watcher
241
+ spec:
242
+ terminationGracePeriodSeconds: {{ .Values.watcher.terminationGracePeriodSeconds }}
243
+ serviceAccountName: {{ .Values.uuid }}
244
+ securityContext:
245
+ {{- toYaml .Values.admission.securityContext | nindent 8 }}
246
+ containers:
247
+ - name: watcher
248
+ image: {{ .Values.watcher.image }}
249
+ imagePullPolicy: IfNotPresent
250
+ command:
251
+ - node
252
+ - /app/node_modules/pepr/dist/controller.js
253
+ - {{ .Values.hash }}
254
+ readinessProbe:
255
+ {{- toYaml .Values.watcher.readinessProbe | nindent 12 }}
256
+ livenessProbe:
257
+ {{- toYaml .Values.watcher.livenessProbe | nindent 12 }}
258
+ ports:
259
+ - containerPort: 3000
260
+ resources:
261
+ {{- toYaml .Values.watcher.resources | nindent 12 }}
262
+ env:
263
+ {{- toYaml .Values.watcher.env | nindent 12 }}
264
+ - name: PEPR_WATCH_MODE
265
+ value: "true"
266
+ envFrom:
267
+ {{- toYaml .Values.watcher.envFrom | nindent 12 }}
268
+ securityContext:
269
+ {{- toYaml .Values.watcher.containerSecurityContext | nindent 12 }}
270
+ volumeMounts:
271
+ - name: tls-certs
272
+ mountPath: /etc/certs
273
+ readOnly: true
274
+ - name: module
275
+ mountPath: /app/load
276
+ readOnly: true
277
+ {{- if .Values.watcher.extraVolumeMounts }}
278
+ {{- toYaml .Values.watcher.extraVolumeMounts | nindent 12 }}
279
+ {{- end }}
280
+ volumes:
281
+ - name: tls-certs
282
+ secret:
283
+ secretName: {{ .Values.uuid }}-tls
284
+ - name: module
285
+ secret:
286
+ secretName: {{ .Values.uuid }}-module
287
+ {{- if .Values.watcher.extraVolumes }}
288
+ {{- toYaml .Values.watcher.extraVolumes | nindent 8 }}
289
+ {{- end }}
290
+ `;
736
291
  }
737
- function getModuleSecret(name2, data, hash) {
738
- const compressed = (0, import_zlib.gzipSync)(data);
739
- const path = `module-${hash}.js.gz`;
740
- const compressedData = compressed.toString("base64");
741
- if (secretOverLimit(compressedData)) {
742
- const error = new Error(`Module secret for ${name2} is over the 1MB limit`);
743
- console.error("Uncaught Exception:", error);
744
- process.exit(1);
745
- } else {
746
- return {
747
- apiVersion: "v1",
748
- kind: "Secret",
749
- metadata: {
750
- name: `${name2}-module`,
751
- namespace: "pepr-system"
752
- },
753
- type: "Opaque",
754
- data: {
755
- [path]: compressed.toString("base64")
756
- }
757
- };
758
- }
292
+ function admissionDeployTemplate(buildTimestamp) {
293
+ return `
294
+ apiVersion: apps/v1
295
+ kind: Deployment
296
+ metadata:
297
+ name: {{ .Values.uuid }}
298
+ namespace: pepr-system
299
+ annotations:
300
+ {{- toYaml .Values.admission.annotations | nindent 4 }}
301
+ labels:
302
+ {{- toYaml .Values.admission.labels | nindent 4 }}
303
+ spec:
304
+ replicas: 2
305
+ selector:
306
+ matchLabels:
307
+ app: {{ .Values.uuid }}
308
+ pepr.dev/controller: admission
309
+ template:
310
+ metadata:
311
+ annotations:
312
+ buildTimestamp: "${buildTimestamp}"
313
+ {{- if .Values.admission.podAnnotations }}
314
+ {{- toYaml .Values.admission.podAnnotations | nindent 8 }}
315
+ {{- end }}
316
+ labels:
317
+ app: {{ .Values.uuid }}
318
+ pepr.dev/controller: admission
319
+ spec:
320
+ terminationGracePeriodSeconds: {{ .Values.admission.terminationGracePeriodSeconds }}
321
+ priorityClassName: system-node-critical
322
+ serviceAccountName: {{ .Values.uuid }}
323
+ securityContext:
324
+ {{- toYaml .Values.admission.securityContext | nindent 8 }}
325
+ containers:
326
+ - name: server
327
+ image: {{ .Values.admission.image }}
328
+ imagePullPolicy: IfNotPresent
329
+ command:
330
+ - node
331
+ - /app/node_modules/pepr/dist/controller.js
332
+ - {{ .Values.hash }}
333
+ readinessProbe:
334
+ {{- toYaml .Values.admission.readinessProbe | nindent 12 }}
335
+ livenessProbe:
336
+ {{- toYaml .Values.admission.livenessProbe | nindent 12 }}
337
+ ports:
338
+ - containerPort: 3000
339
+ resources:
340
+ {{- toYaml .Values.admission.resources | nindent 12 }}
341
+ env:
342
+ {{- toYaml .Values.admission.env | nindent 12 }}
343
+ - name: PEPR_WATCH_MODE
344
+ value: "false"
345
+ envFrom:
346
+ {{- toYaml .Values.admission.envFrom | nindent 12 }}
347
+ securityContext:
348
+ {{- toYaml .Values.admission.containerSecurityContext | nindent 12 }}
349
+ volumeMounts:
350
+ - name: tls-certs
351
+ mountPath: /etc/certs
352
+ readOnly: true
353
+ - name: api-token
354
+ mountPath: /app/api-token
355
+ readOnly: true
356
+ - name: module
357
+ mountPath: /app/load
358
+ readOnly: true
359
+ {{- if .Values.admission.extraVolumeMounts }}
360
+ {{- toYaml .Values.admission.extraVolumeMounts | nindent 12 }}
361
+ {{- end }}
362
+ volumes:
363
+ - name: tls-certs
364
+ secret:
365
+ secretName: {{ .Values.uuid }}-tls
366
+ - name: api-token
367
+ secret:
368
+ secretName: {{ .Values.uuid }}-api-token
369
+ - name: module
370
+ secret:
371
+ secretName: {{ .Values.uuid }}-module
372
+ {{- if .Values.admission.extraVolumes }}
373
+ {{- toYaml .Values.admission.extraVolumes | nindent 8 }}
374
+ {{- end }}
375
+ `;
759
376
  }
760
- function genEnv(config, watchMode = false, ignoreWatchMode = false) {
761
- const noWatchDef = {
762
- PEPR_PRETTY_LOG: "false",
763
- LOG_LEVEL: config.logLevel || "info"
764
- };
765
- const def = {
766
- PEPR_WATCH_MODE: watchMode ? "true" : "false",
767
- ...noWatchDef
768
- };
769
- if (config.env && config.env["PEPR_WATCH_MODE"]) {
770
- delete config.env["PEPR_WATCH_MODE"];
771
- }
772
- const cfg = config.env || {};
773
- return ignoreWatchMode ? Object.entries({ ...noWatchDef, ...cfg }).map(([name2, value]) => ({ name: name2, value })) : Object.entries({ ...def, ...cfg }).map(([name2, value]) => ({ name: name2, value }));
377
+ function serviceMonitorTemplate(name2) {
378
+ return `
379
+ {{- if .Values.${name2}.serviceMonitor.enabled }}
380
+ apiVersion: monitoring.coreos.com/v1
381
+ kind: ServiceMonitor
382
+ metadata:
383
+ name: ${name2}
384
+ annotations:
385
+ {{- toYaml .Values.${name2}.serviceMonitor.annotations | nindent 4 }}
386
+ labels:
387
+ {{- toYaml .Values.${name2}.serviceMonitor.labels | nindent 4 }}
388
+ spec:
389
+ selector:
390
+ matchLabels:
391
+ pepr.dev/controller: ${name2}
392
+ namespaceSelector:
393
+ matchNames:
394
+ - pepr-system
395
+ endpoints:
396
+ - targetPort: 3000
397
+ scheme: https
398
+ tlsConfig:
399
+ insecureSkipVerify: true
400
+ {{- end }}
401
+ `;
774
402
  }
775
403
 
776
- // src/lib/assets/rbac.ts
777
- function clusterRole(name2, capabilities, rbacMode = "admin", customRbac) {
778
- const rbacMap = createRBACMap(capabilities);
779
- const scopedRules = Object.keys(rbacMap).map((key) => {
780
- let group2;
781
- key.split("/").length < 3 ? group2 = "" : group2 = key.split("/")[0];
782
- return {
783
- apiGroups: [group2],
784
- resources: [rbacMap[key].plural],
785
- verbs: rbacMap[key].verbs
786
- };
787
- });
788
- const mergedRBAC = [...Array.isArray(customRbac) ? customRbac : [], ...scopedRules];
789
- const deduper = {};
790
- mergedRBAC.forEach((rule) => {
791
- const key = `${rule.apiGroups}/${rule.resources}`;
792
- if (deduper[key]) {
793
- deduper[key].verbs = Array.from(/* @__PURE__ */ new Set([...deduper[key].verbs, ...rule.verbs]));
404
+ // src/lib/filesystemService.ts
405
+ var import_fs = require("fs");
406
+ async function createDirectoryIfNotExists(path) {
407
+ try {
408
+ await import_fs.promises.access(path);
409
+ } catch (error) {
410
+ if (error.code === "ENOENT") {
411
+ await import_fs.promises.mkdir(path, { recursive: true });
794
412
  } else {
795
- deduper[key] = { ...rule, verbs: rule.verbs || [] };
413
+ throw error;
796
414
  }
797
- });
798
- const deduplicatedRules = Object.values(deduper);
799
- return {
800
- apiVersion: "rbac.authorization.k8s.io/v1",
801
- kind: "ClusterRole",
802
- metadata: { name: name2 },
803
- rules: rbacMode === "scoped" ? deduplicatedRules : [
804
- {
805
- apiGroups: ["*"],
806
- resources: ["*"],
807
- verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
808
- }
809
- ]
810
- };
415
+ }
811
416
  }
812
- function clusterRoleBinding(name2) {
417
+
418
+ // src/lib/assets/deploy.ts
419
+ var import_crypto = __toESM(require("crypto"));
420
+ var import_fs2 = require("fs");
421
+ var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
422
+
423
+ // src/lib/telemetry/logger.ts
424
+ var import_pino = require("pino");
425
+ var isPrettyLog = true;
426
+ var pretty = {
427
+ target: "pino-pretty",
428
+ options: {
429
+ colorize: true
430
+ }
431
+ };
432
+ var transport = isPrettyLog ? pretty : void 0;
433
+ var pinoTimeFunction = process.env.PINO_TIME_STAMP === "iso" ? () => import_pino.stdTimeFunctions.isoTime() : () => import_pino.stdTimeFunctions.epochTime();
434
+ var Log = (0, import_pino.pino)({
435
+ transport,
436
+ timestamp: pinoTimeFunction
437
+ });
438
+ if (process.env.LOG_LEVEL) {
439
+ Log.level = process.env.LOG_LEVEL;
440
+ }
441
+ var logger_default = Log;
442
+
443
+ // src/lib/assets/networking.ts
444
+ function apiTokenSecret(name2, apiToken) {
813
445
  return {
814
- apiVersion: "rbac.authorization.k8s.io/v1",
815
- kind: "ClusterRoleBinding",
816
- metadata: { name: name2 },
817
- roleRef: {
818
- apiGroup: "rbac.authorization.k8s.io",
819
- kind: "ClusterRole",
820
- name: name2
446
+ apiVersion: "v1",
447
+ kind: "Secret",
448
+ metadata: {
449
+ name: `${name2}-api-token`,
450
+ namespace: "pepr-system"
821
451
  },
822
- subjects: [
823
- {
824
- kind: "ServiceAccount",
825
- name: name2,
826
- namespace: "pepr-system"
827
- }
828
- ]
452
+ type: "Opaque",
453
+ data: {
454
+ value: Buffer.from(apiToken).toString("base64")
455
+ }
829
456
  };
830
457
  }
831
- function serviceAccount(name2) {
458
+ function tlsSecret(name2, tls) {
832
459
  return {
833
460
  apiVersion: "v1",
834
- kind: "ServiceAccount",
461
+ kind: "Secret",
835
462
  metadata: {
836
- name: name2,
463
+ name: `${name2}-tls`,
837
464
  namespace: "pepr-system"
465
+ },
466
+ type: "kubernetes.io/tls",
467
+ data: {
468
+ "tls.crt": tls.crt,
469
+ "tls.key": tls.key
838
470
  }
839
471
  };
840
472
  }
841
- function storeRole(name2) {
842
- name2 = `${name2}-store`;
473
+ function service(name2) {
843
474
  return {
844
- apiVersion: "rbac.authorization.k8s.io/v1",
845
- kind: "Role",
846
- metadata: { name: name2, namespace: "pepr-system" },
847
- rules: [
848
- {
849
- apiGroups: ["pepr.dev"],
850
- resources: ["peprstores"],
851
- resourceNames: [""],
852
- verbs: ["create", "get", "patch", "watch"]
475
+ apiVersion: "v1",
476
+ kind: "Service",
477
+ metadata: {
478
+ name: name2,
479
+ namespace: "pepr-system",
480
+ labels: {
481
+ "pepr.dev/controller": "admission"
853
482
  }
854
- ]
483
+ },
484
+ spec: {
485
+ selector: {
486
+ app: name2,
487
+ "pepr.dev/controller": "admission"
488
+ },
489
+ ports: [
490
+ {
491
+ port: 443,
492
+ targetPort: 3e3
493
+ }
494
+ ]
495
+ }
855
496
  };
856
497
  }
857
- function storeRoleBinding(name2) {
858
- name2 = `${name2}-store`;
498
+ function watcherService(name2) {
859
499
  return {
860
- apiVersion: "rbac.authorization.k8s.io/v1",
861
- kind: "RoleBinding",
862
- metadata: { name: name2, namespace: "pepr-system" },
863
- roleRef: {
864
- apiGroup: "rbac.authorization.k8s.io",
865
- kind: "Role",
866
- name: name2
867
- },
868
- subjects: [
869
- {
870
- kind: "ServiceAccount",
871
- name: name2,
872
- namespace: "pepr-system"
500
+ apiVersion: "v1",
501
+ kind: "Service",
502
+ metadata: {
503
+ name: `${name2}-watcher`,
504
+ namespace: "pepr-system",
505
+ labels: {
506
+ "pepr.dev/controller": "watcher"
873
507
  }
874
- ]
875
- };
876
- }
877
-
878
- // src/lib/k8s.ts
879
- var import_kubernetes_fluent_client2 = require("kubernetes-fluent-client");
880
- var Store = class extends import_kubernetes_fluent_client2.GenericKind {
881
- };
882
- var peprStoreGVK = {
883
- kind: "PeprStore",
884
- version: "v1",
885
- group: "pepr.dev"
886
- };
887
- (0, import_kubernetes_fluent_client2.RegisterKind)(Store, peprStoreGVK);
888
-
889
- // src/lib/assets/store.ts
890
- var { group, version, kind: kind2 } = peprStoreGVK;
891
- var singular = kind2.toLocaleLowerCase();
892
- var plural = `${singular}s`;
893
- var name = `${plural}.${group}`;
894
- var peprStoreCRD = {
895
- apiVersion: "apiextensions.k8s.io/v1",
896
- kind: "CustomResourceDefinition",
897
- metadata: {
898
- name
899
- },
900
- spec: {
901
- group,
902
- versions: [
903
- {
904
- // typescript doesn't know this is really already set, which is kind of annoying
905
- name: version || "v1",
906
- served: true,
907
- storage: true,
908
- schema: {
909
- openAPIV3Schema: {
910
- type: "object",
911
- properties: {
912
- data: {
913
- type: "object",
914
- additionalProperties: {
915
- type: "string"
916
- }
917
- }
918
- }
919
- }
508
+ },
509
+ spec: {
510
+ selector: {
511
+ app: `${name2}-watcher`,
512
+ "pepr.dev/controller": "watcher"
513
+ },
514
+ ports: [
515
+ {
516
+ port: 443,
517
+ targetPort: 3e3
920
518
  }
921
- }
922
- ],
923
- scope: "Namespaced",
924
- names: {
925
- plural,
926
- singular,
927
- kind: kind2
519
+ ]
928
520
  }
929
- }
930
- };
521
+ };
522
+ }
931
523
 
932
- // src/lib/assets/webhooks.ts
933
- var import_ramda = require("ramda");
934
- var peprIgnoreLabel = {
935
- key: "pepr.dev",
936
- operator: "NotIn",
937
- values: ["ignore"]
524
+ // src/lib/assets/pods.ts
525
+ var import_zlib = require("zlib");
526
+
527
+ // src/sdk/sdk.ts
528
+ var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
529
+ function sanitizeResourceName(name2) {
530
+ return name2.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 250).replace(/^[^a-z]+|[^a-z]+$/g, "");
531
+ }
532
+
533
+ // src/lib/helpers.ts
534
+ function matchesRegex(pattern, testString) {
535
+ return new RegExp(pattern).test(testString);
536
+ }
537
+ var ValidationError = class extends Error {
938
538
  };
939
- var peprIgnoreNamespaces = ["kube-system", "pepr-system"];
940
- var validateRule = (binding, isMutateWebhook) => {
941
- const { event, kind: kind8, isMutate, isValidate } = binding;
942
- if (isMutateWebhook && !isMutate || !isMutateWebhook && !isValidate) {
943
- return void 0;
539
+ function validateCapabilityNames(capabilities) {
540
+ if (capabilities && capabilities.length > 0) {
541
+ for (let i = 0; i < capabilities.length; i++) {
542
+ if (capabilities[i].name !== sanitizeResourceName(capabilities[i].name)) {
543
+ throw new ValidationError(`Capability name is not a valid Kubernetes resource name: ${capabilities[i].name}`);
544
+ }
545
+ }
944
546
  }
945
- const operations = event === "CREATEORUPDATE" /* CREATE_OR_UPDATE */ ? ["CREATE" /* CREATE */, "UPDATE" /* UPDATE */] : [event];
946
- const resource = kind8.plural || `${kind8.kind.toLowerCase()}s`;
947
- const ruleObject = {
948
- apiGroups: [kind8.group],
949
- apiVersions: [kind8.version || "*"],
950
- operations,
951
- resources: [resource, ...resource === "pods" ? ["pods/ephemeralcontainers"] : []]
952
- };
953
- return ruleObject;
954
- };
955
- async function generateWebhookRules(assets, isMutateWebhook) {
956
- const { config, capabilities } = assets;
957
- const rules = capabilities.flatMap((capability) => {
958
- console.info(`Module ${config.uuid} has capability: ${capability.name}`);
959
- return capability.bindings.map((binding) => validateRule(binding, isMutateWebhook)).filter((rule) => !!rule);
960
- });
961
- return (0, import_ramda.uniqWith)(import_ramda.equals, rules);
962
547
  }
963
- async function webhookConfig(assets, mutateOrValidate, timeoutSeconds = 10) {
964
- const ignore = [peprIgnoreLabel];
965
- const { name: name2, tls, config, apiToken, host } = assets;
966
- const ignoreNS = (0, import_ramda.concat)(peprIgnoreNamespaces, config?.alwaysIgnore?.namespaces || []);
967
- if (ignoreNS) {
968
- ignore.push({
969
- key: "kubernetes.io/metadata.name",
970
- operator: "NotIn",
971
- values: ignoreNS
548
+ function createRBACMap(capabilities) {
549
+ return capabilities.reduce((acc, capability) => {
550
+ capability.bindings.forEach((binding) => {
551
+ const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;
552
+ acc["pepr.dev/v1/peprstore"] = {
553
+ verbs: ["create", "get", "patch", "watch"],
554
+ plural: "peprstores"
555
+ };
556
+ acc["apiextensions.k8s.io/v1/customresourcedefinition"] = {
557
+ verbs: ["patch", "create"],
558
+ plural: "customresourcedefinitions"
559
+ };
560
+ if (!acc[key] && binding.isWatch) {
561
+ acc[key] = {
562
+ verbs: ["watch"],
563
+ plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`
564
+ };
565
+ }
566
+ if (binding.isFinalize) {
567
+ acc[key] = {
568
+ verbs: ["patch"],
569
+ plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`
570
+ };
571
+ }
972
572
  });
573
+ return acc;
574
+ }, {});
575
+ }
576
+ function hasEveryOverlap(array1, array2) {
577
+ if (!Array.isArray(array1) || !Array.isArray(array2)) {
578
+ return false;
973
579
  }
974
- const clientConfig = {
975
- caBundle: tls.ca
976
- };
977
- const apiPath = `/${mutateOrValidate}/${apiToken}`;
978
- if (host) {
979
- clientConfig.url = `https://${host}:3000${apiPath}`;
980
- } else {
981
- clientConfig.service = {
982
- name: name2,
983
- namespace: "pepr-system",
984
- path: apiPath
985
- };
580
+ return array1.every((element) => array2.includes(element));
581
+ }
582
+ function hasAnyOverlap(array1, array2) {
583
+ if (!Array.isArray(array1) || !Array.isArray(array2)) {
584
+ return false;
986
585
  }
987
- const isMutate = mutateOrValidate === "mutate";
988
- const rules = await generateWebhookRules(assets, isMutate);
989
- if (rules.length < 1) {
990
- return null;
586
+ return array1.some((element) => array2.includes(element));
587
+ }
588
+ function ignoredNamespaceConflict(ignoreNamespaces, bindingNamespaces) {
589
+ return hasAnyOverlap(bindingNamespaces, ignoreNamespaces);
590
+ }
591
+ function bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces) {
592
+ if (!capabilityNamespaces) {
593
+ return false;
991
594
  }
992
- return {
993
- apiVersion: "admissionregistration.k8s.io/v1",
994
- kind: isMutate ? "MutatingWebhookConfiguration" : "ValidatingWebhookConfiguration",
995
- metadata: { name: name2 },
996
- webhooks: [
997
- {
998
- name: `${name2}.pepr.dev`,
999
- admissionReviewVersions: ["v1", "v1beta1"],
1000
- clientConfig,
1001
- failurePolicy: config.onError === "reject" ? "Fail" : "Ignore",
1002
- matchPolicy: "Equivalent",
1003
- timeoutSeconds,
1004
- namespaceSelector: {
1005
- matchExpressions: ignore
1006
- },
1007
- objectSelector: {
1008
- matchExpressions: ignore
1009
- },
1010
- rules,
1011
- // @todo: track side effects state
1012
- sideEffects: "None"
1013
- }
1014
- ]
1015
- };
595
+ return capabilityNamespaces.length !== 0 && !hasEveryOverlap(bindingNamespaces, capabilityNamespaces);
1016
596
  }
1017
-
1018
- // src/lib/assets/deploy.ts
1019
- async function deployImagePullSecret(imagePullSecret, name2) {
1020
- try {
1021
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Get("pepr-system");
1022
- } catch {
1023
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(getNamespace());
597
+ function generateWatchNamespaceError(ignoredNamespaces, bindingNamespaces, capabilityNamespaces) {
598
+ let err = "";
599
+ if (ignoredNamespaceConflict(ignoredNamespaces, bindingNamespaces)) {
600
+ err += `Binding uses a Pepr ignored namespace: ignoredNamespaces: [${ignoredNamespaces.join(
601
+ ", "
602
+ )}] bindingNamespaces: [${bindingNamespaces.join(", ")}].`;
1024
603
  }
1025
- try {
1026
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(
1027
- {
1028
- apiVersion: "v1",
1029
- kind: "Secret",
1030
- metadata: {
1031
- name: name2,
1032
- namespace: "pepr-system"
1033
- },
1034
- type: "kubernetes.io/dockerconfigjson",
1035
- data: {
1036
- ".dockerconfigjson": Buffer.from(JSON.stringify(imagePullSecret)).toString("base64")
1037
- }
1038
- },
1039
- { force: true }
604
+ if (bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces)) {
605
+ err += `Binding uses namespace not governed by capability: bindingNamespaces: [${bindingNamespaces.join(
606
+ ", "
607
+ )}] capabilityNamespaces: [${capabilityNamespaces.join(", ")}].`;
608
+ }
609
+ return err.replace(/\.([^ ])/g, ". $1");
610
+ }
611
+ function namespaceComplianceValidator(capability, ignoredNamespaces) {
612
+ const { namespaces: capabilityNamespaces, bindings, name: name2 } = capability;
613
+ const bindingNamespaces = bindings.flatMap((binding) => binding.filters.namespaces);
614
+ const bindingRegexNamespaces = bindings.flatMap(
615
+ (binding) => binding.filters.regexNamespaces || []
616
+ );
617
+ const namespaceError = generateWatchNamespaceError(
618
+ ignoredNamespaces ? ignoredNamespaces : [],
619
+ bindingNamespaces,
620
+ capabilityNamespaces ? capabilityNamespaces : []
621
+ );
622
+ if (namespaceError !== "") {
623
+ throw new Error(
624
+ `Error in ${name2} capability. A binding violates namespace rules. Please check ignoredNamespaces and capability namespaces: ${namespaceError}`
1040
625
  );
1041
- } catch (e) {
1042
- logger_default.error(e);
1043
626
  }
627
+ matchRegexToCapababilityNamespace(bindingRegexNamespaces, capabilityNamespaces);
628
+ checkRegexNamespaces(bindingRegexNamespaces, ignoredNamespaces);
1044
629
  }
1045
- async function deploy(assets, force, webhookTimeout) {
1046
- logger_default.info("Establishing connection to Kubernetes");
1047
- const { name: name2, host, path } = assets;
1048
- logger_default.info("Applying pepr-system namespace");
1049
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(getNamespace(assets.config.customLabels?.namespace));
1050
- const mutateWebhook = await webhookConfig(assets, "mutate", webhookTimeout);
1051
- if (mutateWebhook) {
1052
- logger_default.info("Applying mutating webhook");
1053
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.MutatingWebhookConfiguration).Apply(mutateWebhook, { force });
1054
- } else {
1055
- logger_default.info("Mutating webhook not needed, removing if it exists");
1056
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.MutatingWebhookConfiguration).Delete(name2);
630
+ var matchRegexToCapababilityNamespace = (bindingRegexNamespaces, capabilityNamespaces) => {
631
+ if (bindingRegexNamespaces.length > 0 && capabilityNamespaces && capabilityNamespaces.length > 0) {
632
+ for (const regexNamespace of bindingRegexNamespaces) {
633
+ let matches = false;
634
+ matches = regexNamespace !== "" && capabilityNamespaces.some((capabilityNamespace) => matchesRegex(regexNamespace, capabilityNamespace));
635
+ if (!matches) {
636
+ throw new Error(
637
+ `Ignoring Watch Callback: Object namespace does not match any capability namespace with regex ${regexNamespace}.`
638
+ );
639
+ }
640
+ }
1057
641
  }
1058
- const validateWebhook = await webhookConfig(assets, "validate", webhookTimeout);
1059
- if (validateWebhook) {
1060
- logger_default.info("Applying validating webhook");
1061
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ValidatingWebhookConfiguration).Apply(validateWebhook, { force });
1062
- } else {
1063
- logger_default.info("Validating webhook not needed, removing if it exists");
1064
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ValidatingWebhookConfiguration).Delete(name2);
642
+ };
643
+ var checkRegexNamespaces = (bindingRegexNamespaces, ignoredNamespaces) => {
644
+ if (bindingRegexNamespaces.length > 0 && ignoredNamespaces && ignoredNamespaces.length > 0) {
645
+ for (const regexNamespace of bindingRegexNamespaces) {
646
+ const matchedNS = ignoredNamespaces.find((ignoredNS) => matchesRegex(regexNamespace, ignoredNS));
647
+ if (matchedNS) {
648
+ throw new Error(
649
+ `Ignoring Watch Callback: Regex namespace: ${regexNamespace}, is an ignored namespace: ${matchedNS}.`
650
+ );
651
+ }
652
+ }
653
+ }
654
+ };
655
+ function secretOverLimit(str) {
656
+ const encoder = new TextEncoder();
657
+ const encoded = encoder.encode(str);
658
+ const sizeInBytes = encoded.length;
659
+ const oneMiBInBytes = 1048576;
660
+ return sizeInBytes > oneMiBInBytes;
661
+ }
662
+ var parseTimeout = (value) => {
663
+ const parsedValue = parseInt(value, 10);
664
+ const floatValue = parseFloat(value);
665
+ if (isNaN(parsedValue)) {
666
+ throw new Error("Not a number.");
667
+ } else if (parsedValue !== floatValue) {
668
+ throw new Error("Value must be an integer.");
669
+ } else if (parsedValue < 1 || parsedValue > 30) {
670
+ throw new Error("Number must be between 1 and 30.");
1065
671
  }
1066
- logger_default.info("Applying the Pepr Store CRD if it doesn't exist");
1067
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.CustomResourceDefinition).Apply(peprStoreCRD, { force });
1068
- if (host) {
1069
- return;
672
+ return parsedValue;
673
+ };
674
+ function dedent(file) {
675
+ const lines = file.split("\n");
676
+ if (lines[0].trim() === "") {
677
+ lines.shift();
678
+ file = lines.join("\n");
1070
679
  }
1071
- const code = await import_fs.promises.readFile(path);
1072
- const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
1073
- if (code.length < 1) {
1074
- throw new Error("No code provided");
680
+ const match = file.match(/^[ \t]*(?=\S)/gm);
681
+ const indent = match && Math.min(...match.map((el) => el.length));
682
+ if (indent && indent > 0) {
683
+ const re = new RegExp(`^[ \\t]{${indent}}`, "gm");
684
+ return file.replace(re, "");
1075
685
  }
1076
- await setupRBAC(name2, assets.capabilities, force, assets.config);
1077
- await setupController(assets, code, hash, force);
1078
- await setupWatcher(assets, hash, force);
1079
- }
1080
- async function setupRBAC(name2, capabilities, force, config) {
1081
- const { rbacMode, rbac } = config;
1082
- logger_default.info("Applying cluster role binding");
1083
- const crb = clusterRoleBinding(name2);
1084
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ClusterRoleBinding).Apply(crb, { force });
1085
- logger_default.info("Applying cluster role");
1086
- const cr = clusterRole(name2, capabilities, rbacMode, rbac);
1087
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ClusterRole).Apply(cr, { force });
1088
- logger_default.info("Applying service account");
1089
- const sa = serviceAccount(name2);
1090
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ServiceAccount).Apply(sa, { force });
1091
- logger_default.info("Applying store role");
1092
- const role = storeRole(name2);
1093
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Role).Apply(role, { force });
1094
- logger_default.info("Applying store role binding");
1095
- const roleBinding = storeRoleBinding(name2);
1096
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.RoleBinding).Apply(roleBinding, { force });
1097
- }
1098
- async function setupController(assets, code, hash, force) {
1099
- const { name: name2 } = assets;
1100
- logger_default.info("Applying module secret");
1101
- const mod = getModuleSecret(name2, code, hash);
1102
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(mod, { force });
1103
- logger_default.info("Applying controller service");
1104
- const svc = service(name2);
1105
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Service).Apply(svc, { force });
1106
- logger_default.info("Applying TLS secret");
1107
- const tls = tlsSecret(name2, assets.tls);
1108
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(tls, { force });
1109
- logger_default.info("Applying API token secret");
1110
- const apiToken = apiTokenSecret(name2, assets.apiToken);
1111
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(apiToken, { force });
1112
- logger_default.info("Applying deployment");
1113
- const dep = getDeployment(assets, hash, assets.buildTimestamp);
1114
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Deployment).Apply(dep, { force });
686
+ return file;
1115
687
  }
1116
- async function setupWatcher(assets, hash, force) {
1117
- const watchDeployment = getWatcher(assets, hash, assets.buildTimestamp);
1118
- if (watchDeployment) {
1119
- logger_default.info("Applying watcher deployment");
1120
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Deployment).Apply(watchDeployment, { force });
1121
- logger_default.info("Applying watcher service");
1122
- const watchSvc = watcherService(assets.name);
1123
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Service).Apply(watchSvc, { force });
1124
- }
688
+ function replaceString(str, stringA, stringB) {
689
+ const escapedStringA = stringA.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
690
+ const regExp = new RegExp(escapedStringA, "g");
691
+ return str.replace(regExp, stringB);
1125
692
  }
1126
693
 
1127
- // src/lib/assets/loader.ts
1128
- var import_child_process = require("child_process");
1129
- function loadCapabilities(path) {
1130
- return new Promise((resolve6, reject) => {
1131
- const program2 = (0, import_child_process.fork)(path, {
1132
- env: {
1133
- ...process.env,
1134
- LOG_LEVEL: "warn",
1135
- PEPR_MODE: "build",
1136
- NODE_OPTIONS: "--disable-warning=DEP0040"
694
+ // src/lib/assets/pods.ts
695
+ function getNamespace(namespaceLabels) {
696
+ if (namespaceLabels) {
697
+ return {
698
+ apiVersion: "v1",
699
+ kind: "Namespace",
700
+ metadata: {
701
+ name: "pepr-system",
702
+ labels: namespaceLabels ?? {}
1137
703
  }
1138
- });
1139
- program2.on("message", (message) => {
1140
- const capabilities = message.valueOf();
1141
- for (const capability of capabilities) {
1142
- console.info(`Registered Pepr Capability "${capability.name}"`);
704
+ };
705
+ } else {
706
+ return {
707
+ apiVersion: "v1",
708
+ kind: "Namespace",
709
+ metadata: {
710
+ name: "pepr-system"
1143
711
  }
1144
- resolve6(capabilities);
1145
- });
1146
- program2.on("error", (error) => {
1147
- reject(error);
1148
- });
1149
- });
712
+ };
713
+ }
1150
714
  }
1151
-
1152
- // src/lib/assets/yaml.ts
1153
- var import_client_node = require("@kubernetes/client-node");
1154
- var import_crypto2 = __toESM(require("crypto"));
1155
- var import_fs2 = require("fs");
1156
- async function overridesFile({ hash, name: name2, image, config, apiToken, capabilities }, path) {
1157
- const rbacOverrides = clusterRole(name2, capabilities, config.rbacMode, config.rbac).rules;
1158
- const overrides = {
1159
- rbac: rbacOverrides,
1160
- secrets: {
1161
- apiToken: Buffer.from(apiToken).toString("base64")
1162
- },
1163
- hash,
1164
- namespace: {
1165
- annotations: {},
715
+ function getWatcher(assets, hash, buildTimestamp, imagePullSecret) {
716
+ const { name: name2, image, capabilities, config } = assets;
717
+ let hasSchedule = false;
718
+ const app = `${name2}-watcher`;
719
+ const bindings = [];
720
+ for (const capability of capabilities) {
721
+ if (capability.hasSchedule) {
722
+ hasSchedule = true;
723
+ }
724
+ const watchers = capability.bindings.filter((binding) => binding.isWatch);
725
+ bindings.push(...watchers);
726
+ }
727
+ if (bindings.length < 1 && !hasSchedule) {
728
+ return null;
729
+ }
730
+ const deploy2 = {
731
+ apiVersion: "apps/v1",
732
+ kind: "Deployment",
733
+ metadata: {
734
+ name: app,
735
+ namespace: "pepr-system",
736
+ annotations: {
737
+ "pepr.dev/description": config.description || ""
738
+ },
1166
739
  labels: {
1167
- "pepr.dev": ""
740
+ app,
741
+ "pepr.dev/controller": "watcher",
742
+ "pepr.dev/uuid": config.uuid
743
+ }
744
+ },
745
+ spec: {
746
+ replicas: 1,
747
+ strategy: {
748
+ type: "Recreate"
749
+ },
750
+ selector: {
751
+ matchLabels: {
752
+ app,
753
+ "pepr.dev/controller": "watcher"
754
+ }
755
+ },
756
+ template: {
757
+ metadata: {
758
+ annotations: {
759
+ buildTimestamp: `${buildTimestamp}`
760
+ },
761
+ labels: {
762
+ app,
763
+ "pepr.dev/controller": "watcher"
764
+ }
765
+ },
766
+ spec: {
767
+ terminationGracePeriodSeconds: 5,
768
+ serviceAccountName: name2,
769
+ securityContext: {
770
+ runAsUser: 65532,
771
+ runAsGroup: 65532,
772
+ runAsNonRoot: true,
773
+ fsGroup: 65532
774
+ },
775
+ containers: [
776
+ {
777
+ name: "watcher",
778
+ image,
779
+ imagePullPolicy: "IfNotPresent",
780
+ command: ["node", "/app/node_modules/pepr/dist/controller.js", hash],
781
+ readinessProbe: {
782
+ httpGet: {
783
+ path: "/healthz",
784
+ port: 3e3,
785
+ scheme: "HTTPS"
786
+ },
787
+ initialDelaySeconds: 10
788
+ },
789
+ livenessProbe: {
790
+ httpGet: {
791
+ path: "/healthz",
792
+ port: 3e3,
793
+ scheme: "HTTPS"
794
+ },
795
+ initialDelaySeconds: 10
796
+ },
797
+ ports: [
798
+ {
799
+ containerPort: 3e3
800
+ }
801
+ ],
802
+ resources: {
803
+ requests: {
804
+ memory: "256Mi",
805
+ cpu: "200m"
806
+ },
807
+ limits: {
808
+ memory: "512Mi",
809
+ cpu: "500m"
810
+ }
811
+ },
812
+ securityContext: {
813
+ runAsUser: 65532,
814
+ runAsGroup: 65532,
815
+ runAsNonRoot: true,
816
+ allowPrivilegeEscalation: false,
817
+ capabilities: {
818
+ drop: ["ALL"]
819
+ }
820
+ },
821
+ volumeMounts: [
822
+ {
823
+ name: "tls-certs",
824
+ mountPath: "/etc/certs",
825
+ readOnly: true
826
+ },
827
+ {
828
+ name: "module",
829
+ mountPath: `/app/load`,
830
+ readOnly: true
831
+ }
832
+ ],
833
+ env: genEnv(config, true)
834
+ }
835
+ ],
836
+ volumes: [
837
+ {
838
+ name: "tls-certs",
839
+ secret: {
840
+ secretName: `${name2}-tls`
841
+ }
842
+ },
843
+ {
844
+ name: "module",
845
+ secret: {
846
+ secretName: `${name2}-module`
847
+ }
848
+ }
849
+ ]
850
+ }
1168
851
  }
1169
- },
1170
- uuid: name2,
1171
- admission: {
1172
- terminationGracePeriodSeconds: 5,
1173
- failurePolicy: config.onError === "reject" ? "Fail" : "Ignore",
1174
- webhookTimeout: config.webhookTimeout,
1175
- env: genEnv(config, false, true),
1176
- envFrom: [],
1177
- image,
852
+ }
853
+ };
854
+ if (imagePullSecret) {
855
+ deploy2.spec.template.spec.imagePullSecrets = [{ name: imagePullSecret }];
856
+ }
857
+ return deploy2;
858
+ }
859
+ function getDeployment(assets, hash, buildTimestamp, imagePullSecret) {
860
+ const { name: name2, image, config } = assets;
861
+ const app = name2;
862
+ const deploy2 = {
863
+ apiVersion: "apps/v1",
864
+ kind: "Deployment",
865
+ metadata: {
866
+ name: name2,
867
+ namespace: "pepr-system",
1178
868
  annotations: {
1179
- "pepr.dev/description": `${config.description}` || ""
869
+ "pepr.dev/description": config.description || ""
1180
870
  },
1181
871
  labels: {
1182
- app: name2,
872
+ app,
1183
873
  "pepr.dev/controller": "admission",
1184
874
  "pepr.dev/uuid": config.uuid
1185
- },
1186
- securityContext: {
1187
- runAsUser: 65532,
1188
- runAsGroup: 65532,
1189
- runAsNonRoot: true,
1190
- fsGroup: 65532
1191
- },
1192
- readinessProbe: {
1193
- httpGet: {
1194
- path: "/healthz",
1195
- port: 3e3,
1196
- scheme: "HTTPS"
1197
- },
1198
- initialDelaySeconds: 10
1199
- },
1200
- livenessProbe: {
1201
- httpGet: {
1202
- path: "/healthz",
1203
- port: 3e3,
1204
- scheme: "HTTPS"
1205
- },
1206
- initialDelaySeconds: 10
1207
- },
1208
- resources: {
1209
- requests: {
1210
- memory: "256Mi",
1211
- cpu: "200m"
1212
- },
1213
- limits: {
1214
- memory: "512Mi",
1215
- cpu: "500m"
1216
- }
1217
- },
1218
- containerSecurityContext: {
1219
- runAsUser: 65532,
1220
- runAsGroup: 65532,
1221
- runAsNonRoot: true,
1222
- allowPrivilegeEscalation: false,
1223
- capabilities: {
1224
- drop: ["ALL"]
1225
- }
1226
- },
1227
- podAnnotations: {},
1228
- nodeSelector: {},
1229
- tolerations: [],
1230
- extraVolumeMounts: [],
1231
- extraVolumes: [],
1232
- affinity: {},
1233
- serviceMonitor: {
1234
- enabled: false,
1235
- labels: {},
1236
- annotations: {}
1237
875
  }
1238
876
  },
1239
- watcher: {
1240
- terminationGracePeriodSeconds: 5,
1241
- env: genEnv(config, true, true),
1242
- envFrom: [],
1243
- image,
1244
- annotations: {
1245
- "pepr.dev/description": `${config.description}` || ""
1246
- },
1247
- labels: {
1248
- app: `${name2}-watcher`,
1249
- "pepr.dev/controller": "watcher",
1250
- "pepr.dev/uuid": config.uuid
1251
- },
1252
- securityContext: {
1253
- runAsUser: 65532,
1254
- runAsGroup: 65532,
1255
- runAsNonRoot: true,
1256
- fsGroup: 65532
1257
- },
1258
- readinessProbe: {
1259
- httpGet: {
1260
- path: "/healthz",
1261
- port: 3e3,
1262
- scheme: "HTTPS"
1263
- },
1264
- initialDelaySeconds: 10
1265
- },
1266
- livenessProbe: {
1267
- httpGet: {
1268
- path: "/healthz",
1269
- port: 3e3,
1270
- scheme: "HTTPS"
1271
- },
1272
- initialDelaySeconds: 10
1273
- },
1274
- resources: {
1275
- requests: {
1276
- memory: "256Mi",
1277
- cpu: "200m"
1278
- },
1279
- limits: {
1280
- memory: "512Mi",
1281
- cpu: "500m"
877
+ spec: {
878
+ replicas: 2,
879
+ selector: {
880
+ matchLabels: {
881
+ app,
882
+ "pepr.dev/controller": "admission"
1282
883
  }
1283
884
  },
1284
- containerSecurityContext: {
1285
- runAsUser: 65532,
1286
- runAsGroup: 65532,
1287
- runAsNonRoot: true,
1288
- allowPrivilegeEscalation: false,
1289
- capabilities: {
1290
- drop: ["ALL"]
885
+ template: {
886
+ metadata: {
887
+ annotations: {
888
+ buildTimestamp: `${buildTimestamp}`
889
+ },
890
+ labels: {
891
+ app,
892
+ "pepr.dev/controller": "admission"
893
+ }
894
+ },
895
+ spec: {
896
+ terminationGracePeriodSeconds: 5,
897
+ priorityClassName: "system-node-critical",
898
+ serviceAccountName: name2,
899
+ securityContext: {
900
+ runAsUser: 65532,
901
+ runAsGroup: 65532,
902
+ runAsNonRoot: true,
903
+ fsGroup: 65532
904
+ },
905
+ containers: [
906
+ {
907
+ name: "server",
908
+ image,
909
+ imagePullPolicy: "IfNotPresent",
910
+ command: ["node", "/app/node_modules/pepr/dist/controller.js", hash],
911
+ readinessProbe: {
912
+ httpGet: {
913
+ path: "/healthz",
914
+ port: 3e3,
915
+ scheme: "HTTPS"
916
+ },
917
+ initialDelaySeconds: 10
918
+ },
919
+ livenessProbe: {
920
+ httpGet: {
921
+ path: "/healthz",
922
+ port: 3e3,
923
+ scheme: "HTTPS"
924
+ },
925
+ initialDelaySeconds: 10
926
+ },
927
+ ports: [
928
+ {
929
+ containerPort: 3e3
930
+ }
931
+ ],
932
+ resources: {
933
+ requests: {
934
+ memory: "256Mi",
935
+ cpu: "200m"
936
+ },
937
+ limits: {
938
+ memory: "512Mi",
939
+ cpu: "500m"
940
+ }
941
+ },
942
+ env: genEnv(config),
943
+ securityContext: {
944
+ runAsUser: 65532,
945
+ runAsGroup: 65532,
946
+ runAsNonRoot: true,
947
+ allowPrivilegeEscalation: false,
948
+ capabilities: {
949
+ drop: ["ALL"]
950
+ }
951
+ },
952
+ volumeMounts: [
953
+ {
954
+ name: "tls-certs",
955
+ mountPath: "/etc/certs",
956
+ readOnly: true
957
+ },
958
+ {
959
+ name: "api-token",
960
+ mountPath: "/app/api-token",
961
+ readOnly: true
962
+ },
963
+ {
964
+ name: "module",
965
+ mountPath: `/app/load`,
966
+ readOnly: true
967
+ }
968
+ ]
969
+ }
970
+ ],
971
+ volumes: [
972
+ {
973
+ name: "tls-certs",
974
+ secret: {
975
+ secretName: `${name2}-tls`
976
+ }
977
+ },
978
+ {
979
+ name: "api-token",
980
+ secret: {
981
+ secretName: `${name2}-api-token`
982
+ }
983
+ },
984
+ {
985
+ name: "module",
986
+ secret: {
987
+ secretName: `${name2}-module`
988
+ }
989
+ }
990
+ ]
1291
991
  }
992
+ }
993
+ }
994
+ };
995
+ if (imagePullSecret) {
996
+ deploy2.spec.template.spec.imagePullSecrets = [{ name: imagePullSecret }];
997
+ }
998
+ return deploy2;
999
+ }
1000
+ function getModuleSecret(name2, data, hash) {
1001
+ const compressed = (0, import_zlib.gzipSync)(data);
1002
+ const path = `module-${hash}.js.gz`;
1003
+ const compressedData = compressed.toString("base64");
1004
+ if (secretOverLimit(compressedData)) {
1005
+ const error = new Error(`Module secret for ${name2} is over the 1MB limit`);
1006
+ console.error("Uncaught Exception:", error);
1007
+ process.exit(1);
1008
+ } else {
1009
+ return {
1010
+ apiVersion: "v1",
1011
+ kind: "Secret",
1012
+ metadata: {
1013
+ name: `${name2}-module`,
1014
+ namespace: "pepr-system"
1292
1015
  },
1293
- nodeSelector: {},
1294
- tolerations: [],
1295
- extraVolumeMounts: [],
1296
- extraVolumes: [],
1297
- affinity: {},
1298
- podAnnotations: {},
1299
- serviceMonitor: {
1300
- enabled: false,
1301
- labels: {},
1302
- annotations: {}
1016
+ type: "Opaque",
1017
+ data: {
1018
+ [path]: compressed.toString("base64")
1303
1019
  }
1020
+ };
1021
+ }
1022
+ }
1023
+ function genEnv(config, watchMode = false, ignoreWatchMode = false) {
1024
+ const noWatchDef = {
1025
+ PEPR_PRETTY_LOG: "false",
1026
+ LOG_LEVEL: config.logLevel || "info"
1027
+ };
1028
+ const def = {
1029
+ PEPR_WATCH_MODE: watchMode ? "true" : "false",
1030
+ ...noWatchDef
1031
+ };
1032
+ if (config.env && config.env["PEPR_WATCH_MODE"]) {
1033
+ delete config.env["PEPR_WATCH_MODE"];
1034
+ }
1035
+ const cfg = config.env || {};
1036
+ return ignoreWatchMode ? Object.entries({ ...noWatchDef, ...cfg }).map(([name2, value]) => ({ name: name2, value })) : Object.entries({ ...def, ...cfg }).map(([name2, value]) => ({ name: name2, value }));
1037
+ }
1038
+
1039
+ // src/lib/assets/rbac.ts
1040
+ function clusterRole(name2, capabilities, rbacMode = "admin", customRbac) {
1041
+ const rbacMap = createRBACMap(capabilities);
1042
+ const scopedRules = Object.keys(rbacMap).map((key) => {
1043
+ let group2;
1044
+ key.split("/").length < 3 ? group2 = "" : group2 = key.split("/")[0];
1045
+ return {
1046
+ apiGroups: [group2],
1047
+ resources: [rbacMap[key].plural],
1048
+ verbs: rbacMap[key].verbs
1049
+ };
1050
+ });
1051
+ const mergedRBAC = [...Array.isArray(customRbac) ? customRbac : [], ...scopedRules];
1052
+ const deduper = {};
1053
+ mergedRBAC.forEach((rule) => {
1054
+ const key = `${rule.apiGroups}/${rule.resources}`;
1055
+ if (deduper[key]) {
1056
+ deduper[key].verbs = Array.from(/* @__PURE__ */ new Set([...deduper[key].verbs, ...rule.verbs]));
1057
+ } else {
1058
+ deduper[key] = { ...rule, verbs: rule.verbs || [] };
1304
1059
  }
1060
+ });
1061
+ const deduplicatedRules = Object.values(deduper);
1062
+ return {
1063
+ apiVersion: "rbac.authorization.k8s.io/v1",
1064
+ kind: "ClusterRole",
1065
+ metadata: { name: name2 },
1066
+ rules: rbacMode === "scoped" ? deduplicatedRules : [
1067
+ {
1068
+ apiGroups: ["*"],
1069
+ resources: ["*"],
1070
+ verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
1071
+ }
1072
+ ]
1305
1073
  };
1306
- await import_fs2.promises.writeFile(path, (0, import_client_node.dumpYaml)(overrides, { noRefs: true, forceQuotes: true }));
1307
1074
  }
1308
- function zarfYaml({ name: name2, image, config }, path) {
1309
- const zarfCfg = {
1310
- kind: "ZarfPackageConfig",
1075
+ function clusterRoleBinding(name2) {
1076
+ return {
1077
+ apiVersion: "rbac.authorization.k8s.io/v1",
1078
+ kind: "ClusterRoleBinding",
1079
+ metadata: { name: name2 },
1080
+ roleRef: {
1081
+ apiGroup: "rbac.authorization.k8s.io",
1082
+ kind: "ClusterRole",
1083
+ name: name2
1084
+ },
1085
+ subjects: [
1086
+ {
1087
+ kind: "ServiceAccount",
1088
+ name: name2,
1089
+ namespace: "pepr-system"
1090
+ }
1091
+ ]
1092
+ };
1093
+ }
1094
+ function serviceAccount(name2) {
1095
+ return {
1096
+ apiVersion: "v1",
1097
+ kind: "ServiceAccount",
1311
1098
  metadata: {
1312
1099
  name: name2,
1313
- description: `Pepr Module: ${config.description}`,
1314
- url: "https://github.com/defenseunicorns/pepr",
1315
- version: `${config.appVersion || "0.0.1"}`
1100
+ namespace: "pepr-system"
1101
+ }
1102
+ };
1103
+ }
1104
+ function storeRole(name2) {
1105
+ name2 = `${name2}-store`;
1106
+ return {
1107
+ apiVersion: "rbac.authorization.k8s.io/v1",
1108
+ kind: "Role",
1109
+ metadata: { name: name2, namespace: "pepr-system" },
1110
+ rules: [
1111
+ {
1112
+ apiGroups: ["pepr.dev"],
1113
+ resources: ["peprstores"],
1114
+ resourceNames: [""],
1115
+ verbs: ["create", "get", "patch", "watch"]
1116
+ }
1117
+ ]
1118
+ };
1119
+ }
1120
+ function storeRoleBinding(name2) {
1121
+ name2 = `${name2}-store`;
1122
+ return {
1123
+ apiVersion: "rbac.authorization.k8s.io/v1",
1124
+ kind: "RoleBinding",
1125
+ metadata: { name: name2, namespace: "pepr-system" },
1126
+ roleRef: {
1127
+ apiGroup: "rbac.authorization.k8s.io",
1128
+ kind: "Role",
1129
+ name: name2
1316
1130
  },
1317
- components: [
1131
+ subjects: [
1318
1132
  {
1319
- name: "module",
1320
- required: true,
1321
- manifests: [
1322
- {
1323
- name: "module",
1324
- namespace: "pepr-system",
1325
- files: [path]
1326
- }
1327
- ],
1328
- images: [image]
1133
+ kind: "ServiceAccount",
1134
+ name: name2,
1135
+ namespace: "pepr-system"
1329
1136
  }
1330
1137
  ]
1331
1138
  };
1332
- return (0, import_client_node.dumpYaml)(zarfCfg, { noRefs: true });
1333
- }
1334
- function zarfYamlChart({ name: name2, image, config }, path) {
1335
- const zarfCfg = {
1336
- kind: "ZarfPackageConfig",
1337
- metadata: {
1139
+ }
1140
+
1141
+ // src/lib/k8s.ts
1142
+ var import_kubernetes_fluent_client2 = require("kubernetes-fluent-client");
1143
+ var Store = class extends import_kubernetes_fluent_client2.GenericKind {
1144
+ };
1145
+ var peprStoreGVK = {
1146
+ kind: "PeprStore",
1147
+ version: "v1",
1148
+ group: "pepr.dev"
1149
+ };
1150
+ (0, import_kubernetes_fluent_client2.RegisterKind)(Store, peprStoreGVK);
1151
+
1152
+ // src/lib/assets/store.ts
1153
+ var { group, version, kind: kind2 } = peprStoreGVK;
1154
+ var singular = kind2.toLocaleLowerCase();
1155
+ var plural = `${singular}s`;
1156
+ var name = `${plural}.${group}`;
1157
+ var peprStoreCRD = {
1158
+ apiVersion: "apiextensions.k8s.io/v1",
1159
+ kind: "CustomResourceDefinition",
1160
+ metadata: {
1161
+ name
1162
+ },
1163
+ spec: {
1164
+ group,
1165
+ versions: [
1166
+ {
1167
+ // typescript doesn't know this is really already set, which is kind of annoying
1168
+ name: version || "v1",
1169
+ served: true,
1170
+ storage: true,
1171
+ schema: {
1172
+ openAPIV3Schema: {
1173
+ type: "object",
1174
+ properties: {
1175
+ data: {
1176
+ type: "object",
1177
+ additionalProperties: {
1178
+ type: "string"
1179
+ }
1180
+ }
1181
+ }
1182
+ }
1183
+ }
1184
+ }
1185
+ ],
1186
+ scope: "Namespaced",
1187
+ names: {
1188
+ plural,
1189
+ singular,
1190
+ kind: kind2
1191
+ }
1192
+ }
1193
+ };
1194
+
1195
+ // src/lib/assets/webhooks.ts
1196
+ var import_ramda = require("ramda");
1197
+ var peprIgnoreNamespaces = ["kube-system", "pepr-system"];
1198
+ var validateRule = (binding, isMutateWebhook) => {
1199
+ const { event, kind: kind8, isMutate, isValidate } = binding;
1200
+ if (isMutateWebhook && !isMutate || !isMutateWebhook && !isValidate) {
1201
+ return void 0;
1202
+ }
1203
+ const operations = event === "CREATEORUPDATE" /* CREATE_OR_UPDATE */ ? ["CREATE" /* CREATE */, "UPDATE" /* UPDATE */] : [event];
1204
+ const resource = kind8.plural || `${kind8.kind.toLowerCase()}s`;
1205
+ const ruleObject = {
1206
+ apiGroups: [kind8.group],
1207
+ apiVersions: [kind8.version || "*"],
1208
+ operations,
1209
+ resources: [resource, ...resource === "pods" ? ["pods/ephemeralcontainers"] : []]
1210
+ };
1211
+ return ruleObject;
1212
+ };
1213
+ async function generateWebhookRules(assets, isMutateWebhook) {
1214
+ const { config, capabilities } = assets;
1215
+ const rules = capabilities.flatMap((capability) => {
1216
+ console.info(`Module ${config.uuid} has capability: ${capability.name}`);
1217
+ return capability.bindings.map((binding) => validateRule(binding, isMutateWebhook)).filter((rule) => !!rule);
1218
+ });
1219
+ return (0, import_ramda.uniqWith)(import_ramda.equals, rules);
1220
+ }
1221
+ async function webhookConfig(assets, mutateOrValidate, timeoutSeconds = 10) {
1222
+ const ignore = [];
1223
+ const { name: name2, tls, config, apiToken, host } = assets;
1224
+ const ignoreNS = (0, import_ramda.concat)(peprIgnoreNamespaces, config?.alwaysIgnore?.namespaces || []);
1225
+ if (ignoreNS) {
1226
+ ignore.push({
1227
+ key: "kubernetes.io/metadata.name",
1228
+ operator: "NotIn",
1229
+ values: ignoreNS
1230
+ });
1231
+ }
1232
+ const clientConfig = {
1233
+ caBundle: tls.ca
1234
+ };
1235
+ const apiPath = `/${mutateOrValidate}/${apiToken}`;
1236
+ if (host) {
1237
+ clientConfig.url = `https://${host}:3000${apiPath}`;
1238
+ } else {
1239
+ clientConfig.service = {
1338
1240
  name: name2,
1339
- description: `Pepr Module: ${config.description}`,
1340
- url: "https://github.com/defenseunicorns/pepr",
1341
- version: `${config.appVersion || "0.0.1"}`
1342
- },
1343
- components: [
1241
+ namespace: "pepr-system",
1242
+ path: apiPath
1243
+ };
1244
+ }
1245
+ const isMutate = mutateOrValidate === "mutate";
1246
+ const rules = await generateWebhookRules(assets, isMutate);
1247
+ if (rules.length < 1) {
1248
+ return null;
1249
+ }
1250
+ return {
1251
+ apiVersion: "admissionregistration.k8s.io/v1",
1252
+ kind: isMutate ? "MutatingWebhookConfiguration" : "ValidatingWebhookConfiguration",
1253
+ metadata: { name: name2 },
1254
+ webhooks: [
1344
1255
  {
1345
- name: "module",
1346
- required: true,
1347
- charts: [
1348
- {
1349
- name: "module",
1350
- namespace: "pepr-system",
1351
- version: `${config.appVersion || "0.0.1"}`,
1352
- localPath: path
1353
- }
1354
- ],
1355
- images: [image]
1256
+ name: `${name2}.pepr.dev`,
1257
+ admissionReviewVersions: ["v1", "v1beta1"],
1258
+ clientConfig,
1259
+ failurePolicy: config.onError === "reject" ? "Fail" : "Ignore",
1260
+ matchPolicy: "Equivalent",
1261
+ timeoutSeconds,
1262
+ namespaceSelector: {
1263
+ matchExpressions: ignore
1264
+ },
1265
+ rules,
1266
+ // @todo: track side effects state
1267
+ sideEffects: "None"
1356
1268
  }
1357
1269
  ]
1358
1270
  };
1359
- return (0, import_client_node.dumpYaml)(zarfCfg, { noRefs: true });
1360
1271
  }
1361
- async function allYaml(assets, imagePullSecret) {
1362
- const { name: name2, tls, apiToken, path, config } = assets;
1363
- const code = await import_fs2.promises.readFile(path);
1364
- assets.hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
1365
- const mutateWebhook = await webhookConfig(assets, "mutate", assets.config.webhookTimeout);
1366
- const validateWebhook = await webhookConfig(assets, "validate", assets.config.webhookTimeout);
1367
- const watchDeployment = getWatcher(assets, assets.hash, assets.buildTimestamp, imagePullSecret);
1368
- const resources = [
1369
- getNamespace(assets.config.customLabels?.namespace),
1370
- clusterRole(name2, assets.capabilities, config.rbacMode, config.rbac),
1371
- clusterRoleBinding(name2),
1372
- serviceAccount(name2),
1373
- apiTokenSecret(name2, apiToken),
1374
- tlsSecret(name2, tls),
1375
- getDeployment(assets, assets.hash, assets.buildTimestamp, imagePullSecret),
1376
- service(name2),
1377
- watcherService(name2),
1378
- getModuleSecret(name2, code, assets.hash),
1379
- storeRole(name2),
1380
- storeRoleBinding(name2)
1381
- ];
1272
+
1273
+ // src/lib/assets/deploy.ts
1274
+ async function deployImagePullSecret(imagePullSecret, name2) {
1275
+ try {
1276
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Get("pepr-system");
1277
+ } catch {
1278
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(getNamespace());
1279
+ }
1280
+ try {
1281
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(
1282
+ {
1283
+ apiVersion: "v1",
1284
+ kind: "Secret",
1285
+ metadata: {
1286
+ name: name2,
1287
+ namespace: "pepr-system"
1288
+ },
1289
+ type: "kubernetes.io/dockerconfigjson",
1290
+ data: {
1291
+ ".dockerconfigjson": Buffer.from(JSON.stringify(imagePullSecret)).toString("base64")
1292
+ }
1293
+ },
1294
+ { force: true }
1295
+ );
1296
+ } catch (e) {
1297
+ logger_default.error(e);
1298
+ }
1299
+ }
1300
+ async function deploy(assets, force, webhookTimeout) {
1301
+ logger_default.info("Establishing connection to Kubernetes");
1302
+ const { name: name2, host, path } = assets;
1303
+ logger_default.info("Applying pepr-system namespace");
1304
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(getNamespace(assets.config.customLabels?.namespace));
1305
+ const mutateWebhook = await webhookConfig(assets, "mutate", webhookTimeout);
1382
1306
  if (mutateWebhook) {
1383
- resources.push(mutateWebhook);
1307
+ logger_default.info("Applying mutating webhook");
1308
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.MutatingWebhookConfiguration).Apply(mutateWebhook, { force });
1309
+ } else {
1310
+ logger_default.info("Mutating webhook not needed, removing if it exists");
1311
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.MutatingWebhookConfiguration).Delete(name2);
1384
1312
  }
1313
+ const validateWebhook = await webhookConfig(assets, "validate", webhookTimeout);
1385
1314
  if (validateWebhook) {
1386
- resources.push(validateWebhook);
1315
+ logger_default.info("Applying validating webhook");
1316
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ValidatingWebhookConfiguration).Apply(validateWebhook, { force });
1317
+ } else {
1318
+ logger_default.info("Validating webhook not needed, removing if it exists");
1319
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ValidatingWebhookConfiguration).Delete(name2);
1387
1320
  }
1388
- if (watchDeployment) {
1389
- resources.push(watchDeployment);
1321
+ logger_default.info("Applying the Pepr Store CRD if it doesn't exist");
1322
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.CustomResourceDefinition).Apply(peprStoreCRD, { force });
1323
+ if (host) {
1324
+ return;
1390
1325
  }
1391
- return resources.map((r) => (0, import_client_node.dumpYaml)(r, { noRefs: true })).join("---\n");
1392
- }
1393
-
1394
- // src/lib/assets/index.ts
1395
- var import_path = require("path");
1396
-
1397
- // src/lib/assets/helm.ts
1398
- function clusterRoleTemplate() {
1399
- return `
1400
- apiVersion: rbac.authorization.k8s.io/v1
1401
- kind: ClusterRole
1402
- metadata:
1403
- name: {{ .Values.uuid }}
1404
- namespace: pepr-system
1405
- rules:
1406
- {{- if .Values.rbac }}
1407
- {{- toYaml .Values.rbac | nindent 2 }}
1408
- {{- end }}
1409
- `;
1410
- }
1411
- function namespaceTemplate() {
1412
- return `
1413
- apiVersion: v1
1414
- kind: Namespace
1415
- metadata:
1416
- name: pepr-system
1417
- {{- if .Values.namespace.annotations }}
1418
- annotations:
1419
- {{- toYaml .Values.namespace.annotations | nindent 6 }}
1420
- {{- end }}
1421
- {{- if .Values.namespace.labels }}
1422
- labels:
1423
- {{- toYaml .Values.namespace.labels | nindent 6 }}
1424
- {{- end }}
1425
- `;
1426
- }
1427
- function chartYaml(name2, description) {
1428
- return `
1429
- apiVersion: v2
1430
- name: ${name2}
1431
- description: ${description || ""}
1432
-
1433
- # A chart can be either an 'application' or a 'library' chart.
1434
- #
1435
- # Application charts are a collection of templates that can be packaged into versioned archives
1436
- # to be deployed.
1437
- #
1438
- # Library charts provide useful utilities or functions for the chart developer. They're included as
1439
- # a dependency of application charts to inject those utilities and functions into the rendering
1440
- # pipeline. Library charts do not define any templates and therefore cannot be deployed.
1441
- type: application
1442
-
1443
- # This is the chart version. This version number should be incremented each time you make changes
1444
- # to the chart and its templates, including the app version.
1445
- # Versions are expected to follow Semantic Versioning (https://semver.org/)
1446
- version: 0.1.0
1447
-
1448
- # This is the version number of the application being deployed. This version number should be
1449
- # incremented each time you make changes to the application. Versions are not expected to
1450
- # follow Semantic Versioning. They should reflect the version the application is using.
1451
- # It is recommended to use it with quotes.
1452
- appVersion: "1.16.0"
1453
- `;
1454
- }
1455
- function watcherDeployTemplate(buildTimestamp) {
1456
- return `
1457
- apiVersion: apps/v1
1458
- kind: Deployment
1459
- metadata:
1460
- name: {{ .Values.uuid }}-watcher
1461
- namespace: pepr-system
1462
- annotations:
1463
- {{- toYaml .Values.watcher.annotations | nindent 4 }}
1464
- labels:
1465
- {{- toYaml .Values.watcher.labels | nindent 4 }}
1466
- spec:
1467
- replicas: 1
1468
- strategy:
1469
- type: Recreate
1470
- selector:
1471
- matchLabels:
1472
- app: {{ .Values.uuid }}-watcher
1473
- pepr.dev/controller: watcher
1474
- template:
1475
- metadata:
1476
- annotations:
1477
- buildTimestamp: "${buildTimestamp}"
1478
- {{- if .Values.watcher.podAnnotations }}
1479
- {{- toYaml .Values.watcher.podAnnotations | nindent 8 }}
1480
- {{- end }}
1481
- labels:
1482
- app: {{ .Values.uuid }}-watcher
1483
- pepr.dev/controller: watcher
1484
- spec:
1485
- terminationGracePeriodSeconds: {{ .Values.watcher.terminationGracePeriodSeconds }}
1486
- serviceAccountName: {{ .Values.uuid }}
1487
- securityContext:
1488
- {{- toYaml .Values.admission.securityContext | nindent 8 }}
1489
- containers:
1490
- - name: watcher
1491
- image: {{ .Values.watcher.image }}
1492
- imagePullPolicy: IfNotPresent
1493
- command:
1494
- - node
1495
- - /app/node_modules/pepr/dist/controller.js
1496
- - {{ .Values.hash }}
1497
- readinessProbe:
1498
- {{- toYaml .Values.watcher.readinessProbe | nindent 12 }}
1499
- livenessProbe:
1500
- {{- toYaml .Values.watcher.livenessProbe | nindent 12 }}
1501
- ports:
1502
- - containerPort: 3000
1503
- resources:
1504
- {{- toYaml .Values.watcher.resources | nindent 12 }}
1505
- env:
1506
- {{- toYaml .Values.watcher.env | nindent 12 }}
1507
- - name: PEPR_WATCH_MODE
1508
- value: "true"
1509
- envFrom:
1510
- {{- toYaml .Values.watcher.envFrom | nindent 12 }}
1511
- securityContext:
1512
- {{- toYaml .Values.watcher.containerSecurityContext | nindent 12 }}
1513
- volumeMounts:
1514
- - name: tls-certs
1515
- mountPath: /etc/certs
1516
- readOnly: true
1517
- - name: module
1518
- mountPath: /app/load
1519
- readOnly: true
1520
- {{- if .Values.watcher.extraVolumeMounts }}
1521
- {{- toYaml .Values.watcher.extraVolumeMounts | nindent 12 }}
1522
- {{- end }}
1523
- volumes:
1524
- - name: tls-certs
1525
- secret:
1526
- secretName: {{ .Values.uuid }}-tls
1527
- - name: module
1528
- secret:
1529
- secretName: {{ .Values.uuid }}-module
1530
- {{- if .Values.watcher.extraVolumes }}
1531
- {{- toYaml .Values.watcher.extraVolumes | nindent 8 }}
1532
- {{- end }}
1533
- `;
1326
+ const code = await import_fs2.promises.readFile(path);
1327
+ const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
1328
+ if (code.length < 1) {
1329
+ throw new Error("No code provided");
1330
+ }
1331
+ await setupRBAC(name2, assets.capabilities, force, assets.config);
1332
+ await setupController(assets, code, hash, force);
1333
+ await setupWatcher(assets, hash, force);
1534
1334
  }
1535
- function admissionDeployTemplate(buildTimestamp) {
1536
- return `
1537
- apiVersion: apps/v1
1538
- kind: Deployment
1539
- metadata:
1540
- name: {{ .Values.uuid }}
1541
- namespace: pepr-system
1542
- annotations:
1543
- {{- toYaml .Values.admission.annotations | nindent 4 }}
1544
- labels:
1545
- {{- toYaml .Values.admission.labels | nindent 4 }}
1546
- spec:
1547
- replicas: 2
1548
- selector:
1549
- matchLabels:
1550
- app: {{ .Values.uuid }}
1551
- pepr.dev/controller: admission
1552
- template:
1553
- metadata:
1554
- annotations:
1555
- buildTimestamp: "${buildTimestamp}"
1556
- {{- if .Values.admission.podAnnotations }}
1557
- {{- toYaml .Values.admission.podAnnotations | nindent 8 }}
1558
- {{- end }}
1559
- labels:
1560
- app: {{ .Values.uuid }}
1561
- pepr.dev/controller: admission
1562
- spec:
1563
- terminationGracePeriodSeconds: {{ .Values.admission.terminationGracePeriodSeconds }}
1564
- priorityClassName: system-node-critical
1565
- serviceAccountName: {{ .Values.uuid }}
1566
- securityContext:
1567
- {{- toYaml .Values.admission.securityContext | nindent 8 }}
1568
- containers:
1569
- - name: server
1570
- image: {{ .Values.admission.image }}
1571
- imagePullPolicy: IfNotPresent
1572
- command:
1573
- - node
1574
- - /app/node_modules/pepr/dist/controller.js
1575
- - {{ .Values.hash }}
1576
- readinessProbe:
1577
- {{- toYaml .Values.admission.readinessProbe | nindent 12 }}
1578
- livenessProbe:
1579
- {{- toYaml .Values.admission.livenessProbe | nindent 12 }}
1580
- ports:
1581
- - containerPort: 3000
1582
- resources:
1583
- {{- toYaml .Values.admission.resources | nindent 12 }}
1584
- env:
1585
- {{- toYaml .Values.admission.env | nindent 12 }}
1586
- - name: PEPR_WATCH_MODE
1587
- value: "false"
1588
- envFrom:
1589
- {{- toYaml .Values.admission.envFrom | nindent 12 }}
1590
- securityContext:
1591
- {{- toYaml .Values.admission.containerSecurityContext | nindent 12 }}
1592
- volumeMounts:
1593
- - name: tls-certs
1594
- mountPath: /etc/certs
1595
- readOnly: true
1596
- - name: api-token
1597
- mountPath: /app/api-token
1598
- readOnly: true
1599
- - name: module
1600
- mountPath: /app/load
1601
- readOnly: true
1602
- {{- if .Values.admission.extraVolumeMounts }}
1603
- {{- toYaml .Values.admission.extraVolumeMounts | nindent 12 }}
1604
- {{- end }}
1605
- volumes:
1606
- - name: tls-certs
1607
- secret:
1608
- secretName: {{ .Values.uuid }}-tls
1609
- - name: api-token
1610
- secret:
1611
- secretName: {{ .Values.uuid }}-api-token
1612
- - name: module
1613
- secret:
1614
- secretName: {{ .Values.uuid }}-module
1615
- {{- if .Values.admission.extraVolumes }}
1616
- {{- toYaml .Values.admission.extraVolumes | nindent 8 }}
1617
- {{- end }}
1618
- `;
1335
+ async function setupRBAC(name2, capabilities, force, config) {
1336
+ const { rbacMode, rbac } = config;
1337
+ logger_default.info("Applying cluster role binding");
1338
+ const crb = clusterRoleBinding(name2);
1339
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ClusterRoleBinding).Apply(crb, { force });
1340
+ logger_default.info("Applying cluster role");
1341
+ const cr = clusterRole(name2, capabilities, rbacMode, rbac);
1342
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ClusterRole).Apply(cr, { force });
1343
+ logger_default.info("Applying service account");
1344
+ const sa = serviceAccount(name2);
1345
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.ServiceAccount).Apply(sa, { force });
1346
+ logger_default.info("Applying store role");
1347
+ const role = storeRole(name2);
1348
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Role).Apply(role, { force });
1349
+ logger_default.info("Applying store role binding");
1350
+ const roleBinding = storeRoleBinding(name2);
1351
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.RoleBinding).Apply(roleBinding, { force });
1619
1352
  }
1620
- function serviceMonitorTemplate(name2) {
1621
- return `
1622
- {{- if .Values.${name2}.serviceMonitor.enabled }}
1623
- apiVersion: monitoring.coreos.com/v1
1624
- kind: ServiceMonitor
1625
- metadata:
1626
- name: ${name2}
1627
- annotations:
1628
- {{- toYaml .Values.${name2}.serviceMonitor.annotations | nindent 4 }}
1629
- labels:
1630
- {{- toYaml .Values.${name2}.serviceMonitor.labels | nindent 4 }}
1631
- spec:
1632
- selector:
1633
- matchLabels:
1634
- pepr.dev/controller: ${name2}
1635
- namespaceSelector:
1636
- matchNames:
1637
- - pepr-system
1638
- endpoints:
1639
- - targetPort: 3000
1640
- scheme: https
1641
- tlsConfig:
1642
- insecureSkipVerify: true
1643
- {{- end }}
1644
- `;
1353
+ async function setupController(assets, code, hash, force) {
1354
+ const { name: name2 } = assets;
1355
+ logger_default.info("Applying module secret");
1356
+ const mod = getModuleSecret(name2, code, hash);
1357
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(mod, { force });
1358
+ logger_default.info("Applying controller service");
1359
+ const svc = service(name2);
1360
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Service).Apply(svc, { force });
1361
+ logger_default.info("Applying TLS secret");
1362
+ const tls = tlsSecret(name2, assets.tls);
1363
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(tls, { force });
1364
+ logger_default.info("Applying API token secret");
1365
+ const apiToken = apiTokenSecret(name2, assets.apiToken);
1366
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Secret).Apply(apiToken, { force });
1367
+ logger_default.info("Applying deployment");
1368
+ const dep = getDeployment(assets, hash, assets.buildTimestamp);
1369
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Deployment).Apply(dep, { force });
1370
+ }
1371
+ async function setupWatcher(assets, hash, force) {
1372
+ const watchDeployment = getWatcher(assets, hash, assets.buildTimestamp);
1373
+ if (watchDeployment) {
1374
+ logger_default.info("Applying watcher deployment");
1375
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Deployment).Apply(watchDeployment, { force });
1376
+ logger_default.info("Applying watcher service");
1377
+ const watchSvc = watcherService(assets.name);
1378
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Service).Apply(watchSvc, { force });
1379
+ }
1645
1380
  }
1646
1381
 
1647
1382
  // src/lib/assets/index.ts
1648
- var import_fs4 = require("fs");
1383
+ var import_client_node = require("@kubernetes/client-node");
1384
+ var import_path = require("path");
1385
+ function toYaml(obj) {
1386
+ return (0, import_client_node.dumpYaml)(obj, { noRefs: true });
1387
+ }
1388
+ function createWebhookYaml(name2, config, webhookConfiguration) {
1389
+ const yaml = toYaml(webhookConfiguration);
1390
+ return replaceString(
1391
+ replaceString(
1392
+ replaceString(yaml, name2, "{{ .Values.uuid }}"),
1393
+ config.onError === "reject" ? "Fail" : "Ignore",
1394
+ "{{ .Values.admission.failurePolicy }}"
1395
+ ),
1396
+ `${config.webhookTimeout}` || "10",
1397
+ "{{ .Values.admission.webhookTimeout }}"
1398
+ );
1399
+ }
1400
+ function helmLayout(basePath, unique) {
1401
+ const helm = {
1402
+ dirs: {
1403
+ chart: (0, import_path.resolve)(`${basePath}/${unique}-chart`)
1404
+ },
1405
+ files: {}
1406
+ };
1407
+ helm.dirs = {
1408
+ ...helm.dirs,
1409
+ charts: `${helm.dirs.chart}/charts`,
1410
+ tmpls: `${helm.dirs.chart}/templates`
1411
+ };
1412
+ helm.files = {
1413
+ ...helm.files,
1414
+ valuesYaml: `${helm.dirs.chart}/values.yaml`,
1415
+ chartYaml: `${helm.dirs.chart}/Chart.yaml`,
1416
+ namespaceYaml: `${helm.dirs.tmpls}/namespace.yaml`,
1417
+ watcherServiceYaml: `${helm.dirs.tmpls}/watcher-service.yaml`,
1418
+ admissionServiceYaml: `${helm.dirs.tmpls}/admission-service.yaml`,
1419
+ mutationWebhookYaml: `${helm.dirs.tmpls}/mutation-webhook.yaml`,
1420
+ validationWebhookYaml: `${helm.dirs.tmpls}/validation-webhook.yaml`,
1421
+ admissionDeploymentYaml: `${helm.dirs.tmpls}/admission-deployment.yaml`,
1422
+ admissionServiceMonitorYaml: `${helm.dirs.tmpls}/admission-service-monitor.yaml`,
1423
+ watcherDeploymentYaml: `${helm.dirs.tmpls}/watcher-deployment.yaml`,
1424
+ watcherServiceMonitorYaml: `${helm.dirs.tmpls}/watcher-service-monitor.yaml`,
1425
+ tlsSecretYaml: `${helm.dirs.tmpls}/tls-secret.yaml`,
1426
+ apiTokenSecretYaml: `${helm.dirs.tmpls}/api-token-secret.yaml`,
1427
+ moduleSecretYaml: `${helm.dirs.tmpls}/module-secret.yaml`,
1428
+ storeRoleYaml: `${helm.dirs.tmpls}/store-role.yaml`,
1429
+ storeRoleBindingYaml: `${helm.dirs.tmpls}/store-role-binding.yaml`,
1430
+ clusterRoleYaml: `${helm.dirs.tmpls}/cluster-role.yaml`,
1431
+ clusterRoleBindingYaml: `${helm.dirs.tmpls}/cluster-role-binding.yaml`,
1432
+ serviceAccountYaml: `${helm.dirs.tmpls}/service-account.yaml`
1433
+ };
1434
+ return helm;
1435
+ }
1649
1436
 
1650
- // src/lib/filesystemService.ts
1437
+ // src/lib/assets/loader.ts
1438
+ var import_child_process = require("child_process");
1439
+ function loadCapabilities(path) {
1440
+ return new Promise((resolve6, reject) => {
1441
+ const program2 = (0, import_child_process.fork)(path, {
1442
+ env: {
1443
+ ...process.env,
1444
+ LOG_LEVEL: "warn",
1445
+ PEPR_MODE: "build",
1446
+ NODE_OPTIONS: "--disable-warning=DEP0040"
1447
+ }
1448
+ });
1449
+ program2.on("message", (message) => {
1450
+ const capabilities = message.valueOf();
1451
+ for (const capability of capabilities) {
1452
+ console.info(`Registered Pepr Capability "${capability.name}"`);
1453
+ }
1454
+ resolve6(capabilities);
1455
+ });
1456
+ program2.on("error", (error) => {
1457
+ reject(error);
1458
+ });
1459
+ });
1460
+ }
1461
+
1462
+ // src/lib/assets/yaml.ts
1463
+ var import_client_node2 = require("@kubernetes/client-node");
1651
1464
  var import_fs3 = require("fs");
1652
- async function createDirectoryIfNotExists(path) {
1653
- try {
1654
- await import_fs3.promises.access(path);
1655
- } catch (error) {
1656
- if (error.code === "ENOENT") {
1657
- await import_fs3.promises.mkdir(path, { recursive: true });
1658
- } else {
1659
- throw error;
1465
+ async function overridesFile({ hash, name: name2, image, config, apiToken, capabilities }, path) {
1466
+ const rbacOverrides = clusterRole(name2, capabilities, config.rbacMode, config.rbac).rules;
1467
+ const overrides = {
1468
+ rbac: rbacOverrides,
1469
+ secrets: {
1470
+ apiToken: Buffer.from(apiToken).toString("base64")
1471
+ },
1472
+ hash,
1473
+ namespace: {
1474
+ annotations: {},
1475
+ labels: {
1476
+ "pepr.dev": ""
1477
+ }
1478
+ },
1479
+ uuid: name2,
1480
+ admission: {
1481
+ terminationGracePeriodSeconds: 5,
1482
+ failurePolicy: config.onError === "reject" ? "Fail" : "Ignore",
1483
+ webhookTimeout: config.webhookTimeout,
1484
+ env: genEnv(config, false, true),
1485
+ envFrom: [],
1486
+ image,
1487
+ annotations: {
1488
+ "pepr.dev/description": `${config.description}` || ""
1489
+ },
1490
+ labels: {
1491
+ app: name2,
1492
+ "pepr.dev/controller": "admission",
1493
+ "pepr.dev/uuid": config.uuid
1494
+ },
1495
+ securityContext: {
1496
+ runAsUser: 65532,
1497
+ runAsGroup: 65532,
1498
+ runAsNonRoot: true,
1499
+ fsGroup: 65532
1500
+ },
1501
+ readinessProbe: {
1502
+ httpGet: {
1503
+ path: "/healthz",
1504
+ port: 3e3,
1505
+ scheme: "HTTPS"
1506
+ },
1507
+ initialDelaySeconds: 10
1508
+ },
1509
+ livenessProbe: {
1510
+ httpGet: {
1511
+ path: "/healthz",
1512
+ port: 3e3,
1513
+ scheme: "HTTPS"
1514
+ },
1515
+ initialDelaySeconds: 10
1516
+ },
1517
+ resources: {
1518
+ requests: {
1519
+ memory: "256Mi",
1520
+ cpu: "200m"
1521
+ },
1522
+ limits: {
1523
+ memory: "512Mi",
1524
+ cpu: "500m"
1525
+ }
1526
+ },
1527
+ containerSecurityContext: {
1528
+ runAsUser: 65532,
1529
+ runAsGroup: 65532,
1530
+ runAsNonRoot: true,
1531
+ allowPrivilegeEscalation: false,
1532
+ capabilities: {
1533
+ drop: ["ALL"]
1534
+ }
1535
+ },
1536
+ podAnnotations: {},
1537
+ nodeSelector: {},
1538
+ tolerations: [],
1539
+ extraVolumeMounts: [],
1540
+ extraVolumes: [],
1541
+ affinity: {},
1542
+ serviceMonitor: {
1543
+ enabled: false,
1544
+ labels: {},
1545
+ annotations: {}
1546
+ }
1547
+ },
1548
+ watcher: {
1549
+ terminationGracePeriodSeconds: 5,
1550
+ env: genEnv(config, true, true),
1551
+ envFrom: [],
1552
+ image,
1553
+ annotations: {
1554
+ "pepr.dev/description": `${config.description}` || ""
1555
+ },
1556
+ labels: {
1557
+ app: `${name2}-watcher`,
1558
+ "pepr.dev/controller": "watcher",
1559
+ "pepr.dev/uuid": config.uuid
1560
+ },
1561
+ securityContext: {
1562
+ runAsUser: 65532,
1563
+ runAsGroup: 65532,
1564
+ runAsNonRoot: true,
1565
+ fsGroup: 65532
1566
+ },
1567
+ readinessProbe: {
1568
+ httpGet: {
1569
+ path: "/healthz",
1570
+ port: 3e3,
1571
+ scheme: "HTTPS"
1572
+ },
1573
+ initialDelaySeconds: 10
1574
+ },
1575
+ livenessProbe: {
1576
+ httpGet: {
1577
+ path: "/healthz",
1578
+ port: 3e3,
1579
+ scheme: "HTTPS"
1580
+ },
1581
+ initialDelaySeconds: 10
1582
+ },
1583
+ resources: {
1584
+ requests: {
1585
+ memory: "256Mi",
1586
+ cpu: "200m"
1587
+ },
1588
+ limits: {
1589
+ memory: "512Mi",
1590
+ cpu: "500m"
1591
+ }
1592
+ },
1593
+ containerSecurityContext: {
1594
+ runAsUser: 65532,
1595
+ runAsGroup: 65532,
1596
+ runAsNonRoot: true,
1597
+ allowPrivilegeEscalation: false,
1598
+ capabilities: {
1599
+ drop: ["ALL"]
1600
+ }
1601
+ },
1602
+ nodeSelector: {},
1603
+ tolerations: [],
1604
+ extraVolumeMounts: [],
1605
+ extraVolumes: [],
1606
+ affinity: {},
1607
+ podAnnotations: {},
1608
+ serviceMonitor: {
1609
+ enabled: false,
1610
+ labels: {},
1611
+ annotations: {}
1612
+ }
1660
1613
  }
1661
- }
1662
- }
1663
-
1664
- // src/lib/assets/index.ts
1665
- function toYaml(obj) {
1666
- return (0, import_client_node2.dumpYaml)(obj, { noRefs: true });
1667
- }
1668
- function createWebhookYaml(assets, webhookConfiguration) {
1669
- const yaml = toYaml(webhookConfiguration);
1670
- return replaceString(
1671
- replaceString(
1672
- replaceString(yaml, assets.name, "{{ .Values.uuid }}"),
1673
- assets.config.onError === "reject" ? "Fail" : "Ignore",
1674
- "{{ .Values.admission.failurePolicy }}"
1675
- ),
1676
- `${assets.config.webhookTimeout}` || "10",
1677
- "{{ .Values.admission.webhookTimeout }}"
1678
- );
1614
+ };
1615
+ await import_fs3.promises.writeFile(path, (0, import_client_node2.dumpYaml)(overrides, { noRefs: true, forceQuotes: true }));
1679
1616
  }
1680
- function helmLayout(basePath, unique) {
1681
- const helm = {
1682
- dirs: {
1683
- chart: (0, import_path.resolve)(`${basePath}/${unique}-chart`)
1617
+ function generateZarfYaml(name2, image, config, path) {
1618
+ const zarfCfg = {
1619
+ kind: "ZarfPackageConfig",
1620
+ metadata: {
1621
+ name: name2,
1622
+ description: `Pepr Module: ${config.description}`,
1623
+ url: "https://github.com/defenseunicorns/pepr",
1624
+ version: `${config.appVersion || "0.0.1"}`
1684
1625
  },
1685
- files: {}
1686
- };
1687
- helm.dirs = {
1688
- ...helm.dirs,
1689
- charts: `${helm.dirs.chart}/charts`,
1690
- tmpls: `${helm.dirs.chart}/templates`
1626
+ components: [
1627
+ {
1628
+ name: "module",
1629
+ required: true,
1630
+ manifests: [
1631
+ {
1632
+ name: "module",
1633
+ namespace: "pepr-system",
1634
+ files: [path]
1635
+ }
1636
+ ],
1637
+ images: [image]
1638
+ }
1639
+ ]
1691
1640
  };
1692
- helm.files = {
1693
- ...helm.files,
1694
- valuesYaml: `${helm.dirs.chart}/values.yaml`,
1695
- chartYaml: `${helm.dirs.chart}/Chart.yaml`,
1696
- namespaceYaml: `${helm.dirs.tmpls}/namespace.yaml`,
1697
- watcherServiceYaml: `${helm.dirs.tmpls}/watcher-service.yaml`,
1698
- admissionServiceYaml: `${helm.dirs.tmpls}/admission-service.yaml`,
1699
- mutationWebhookYaml: `${helm.dirs.tmpls}/mutation-webhook.yaml`,
1700
- validationWebhookYaml: `${helm.dirs.tmpls}/validation-webhook.yaml`,
1701
- admissionDeploymentYaml: `${helm.dirs.tmpls}/admission-deployment.yaml`,
1702
- admissionServiceMonitorYaml: `${helm.dirs.tmpls}/admission-service-monitor.yaml`,
1703
- watcherDeploymentYaml: `${helm.dirs.tmpls}/watcher-deployment.yaml`,
1704
- watcherServiceMonitorYaml: `${helm.dirs.tmpls}/watcher-service-monitor.yaml`,
1705
- tlsSecretYaml: `${helm.dirs.tmpls}/tls-secret.yaml`,
1706
- apiTokenSecretYaml: `${helm.dirs.tmpls}/api-token-secret.yaml`,
1707
- moduleSecretYaml: `${helm.dirs.tmpls}/module-secret.yaml`,
1708
- storeRoleYaml: `${helm.dirs.tmpls}/store-role.yaml`,
1709
- storeRoleBindingYaml: `${helm.dirs.tmpls}/store-role-binding.yaml`,
1710
- clusterRoleYaml: `${helm.dirs.tmpls}/cluster-role.yaml`,
1711
- clusterRoleBindingYaml: `${helm.dirs.tmpls}/cluster-role-binding.yaml`,
1712
- serviceAccountYaml: `${helm.dirs.tmpls}/service-account.yaml`
1641
+ return (0, import_client_node2.dumpYaml)(zarfCfg, { noRefs: true });
1642
+ }
1643
+ function generateZarfYamlChart(name2, image, config, path) {
1644
+ const zarfCfg = {
1645
+ kind: "ZarfPackageConfig",
1646
+ metadata: {
1647
+ name: name2,
1648
+ description: `Pepr Module: ${config.description}`,
1649
+ url: "https://github.com/defenseunicorns/pepr",
1650
+ version: `${config.appVersion || "0.0.1"}`
1651
+ },
1652
+ components: [
1653
+ {
1654
+ name: "module",
1655
+ required: true,
1656
+ charts: [
1657
+ {
1658
+ name: "module",
1659
+ namespace: "pepr-system",
1660
+ version: `${config.appVersion || "0.0.1"}`,
1661
+ localPath: path
1662
+ }
1663
+ ],
1664
+ images: [image]
1665
+ }
1666
+ ]
1713
1667
  };
1714
- return helm;
1668
+ return (0, import_client_node2.dumpYaml)(zarfCfg, { noRefs: true });
1669
+ }
1670
+ async function generateAllYaml(webhooks, deployments, assets) {
1671
+ const { name: name2, tls, hash, apiToken, path, config } = assets;
1672
+ const code = await import_fs3.promises.readFile(path);
1673
+ const resources = [
1674
+ getNamespace(assets.config.customLabels?.namespace),
1675
+ clusterRole(name2, assets.capabilities, config.rbacMode, config.rbac),
1676
+ clusterRoleBinding(name2),
1677
+ serviceAccount(name2),
1678
+ apiTokenSecret(name2, apiToken),
1679
+ tlsSecret(name2, tls),
1680
+ deployments.default,
1681
+ service(name2),
1682
+ watcherService(name2),
1683
+ getModuleSecret(name2, code, hash),
1684
+ storeRole(name2),
1685
+ storeRoleBinding(name2)
1686
+ ];
1687
+ if (webhooks.mutate) {
1688
+ resources.push(webhooks.mutate);
1689
+ }
1690
+ if (webhooks.validate) {
1691
+ resources.push(webhooks.validate);
1692
+ }
1693
+ if (deployments.watch) {
1694
+ resources.push(deployments.watch);
1695
+ }
1696
+ return resources.map((r) => (0, import_client_node2.dumpYaml)(r, { noRefs: true })).join("---\n");
1715
1697
  }
1698
+
1699
+ // src/lib/assets/assets.ts
1700
+ var import_fs4 = require("fs");
1716
1701
  var Assets = class {
1717
1702
  constructor(config, path, host) {
1718
1703
  this.config = config;
@@ -1724,7 +1709,7 @@ var Assets = class {
1724
1709
  this.image = `ghcr.io/defenseunicorns/pepr/controller:v${config.peprVersion}`;
1725
1710
  this.hash = "";
1726
1711
  this.tls = genTLS(this.host || `${this.name}.pepr-system.svc`);
1727
- this.apiToken = import_crypto3.default.randomBytes(32).toString("hex");
1712
+ this.apiToken = import_crypto2.default.randomBytes(32).toString("hex");
1728
1713
  }
1729
1714
  name;
1730
1715
  tls;
@@ -1741,16 +1726,46 @@ var Assets = class {
1741
1726
  this.capabilities = await loadCapabilities(this.path);
1742
1727
  await deploy(this, force, webhookTimeout);
1743
1728
  };
1744
- zarfYaml = (path) => zarfYaml(this, path);
1745
- zarfYamlChart = (path) => zarfYamlChart(this, path);
1729
+ zarfYaml = (path) => generateZarfYaml(this.name, this.image, this.config, path);
1730
+ zarfYamlChart = (path) => generateZarfYamlChart(this.name, this.image, this.config, path);
1746
1731
  allYaml = async (imagePullSecret) => {
1747
1732
  this.capabilities = await loadCapabilities(this.path);
1748
1733
  for (const capability of this.capabilities) {
1749
1734
  namespaceComplianceValidator(capability, this.alwaysIgnore?.namespaces);
1750
1735
  }
1751
- return allYaml(this, imagePullSecret);
1736
+ const webhooks = {
1737
+ mutate: await webhookConfig(this, "mutate", this.config.webhookTimeout),
1738
+ validate: await webhookConfig(this, "validate", this.config.webhookTimeout)
1739
+ };
1740
+ const code = await import_fs4.promises.readFile(this.path);
1741
+ this.hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
1742
+ const deployments = {
1743
+ default: getDeployment(this, this.hash, this.buildTimestamp, imagePullSecret),
1744
+ watch: getWatcher(this, this.hash, this.buildTimestamp, imagePullSecret)
1745
+ };
1746
+ const assetsInputs = {
1747
+ apiToken: this.apiToken,
1748
+ capabilities: this.capabilities,
1749
+ config: this.config,
1750
+ hash: this.hash,
1751
+ name: this.name,
1752
+ path: this.path,
1753
+ tls: this.tls
1754
+ };
1755
+ return generateAllYaml(webhooks, deployments, assetsInputs);
1756
+ };
1757
+ writeWebhookFiles = async (validateWebhook, mutateWebhook, helm) => {
1758
+ if (validateWebhook || mutateWebhook) {
1759
+ await import_fs4.promises.writeFile(helm.files.admissionDeploymentYaml, dedent(admissionDeployTemplate(this.buildTimestamp)));
1760
+ await import_fs4.promises.writeFile(helm.files.admissionServiceMonitorYaml, dedent(serviceMonitorTemplate("admission")));
1761
+ }
1762
+ if (mutateWebhook) {
1763
+ await import_fs4.promises.writeFile(helm.files.mutationWebhookYaml, createWebhookYaml(this.name, this.config, mutateWebhook));
1764
+ }
1765
+ if (validateWebhook) {
1766
+ await import_fs4.promises.writeFile(helm.files.validationWebhookYaml, createWebhookYaml(this.name, this.config, validateWebhook));
1767
+ }
1752
1768
  };
1753
- /* eslint max-statements: ["warn", 21] */
1754
1769
  generateHelmChart = async (basePath) => {
1755
1770
  const helm = helmLayout(basePath, this.config.uuid);
1756
1771
  try {
@@ -1773,21 +1788,20 @@ var Assets = class {
1773
1788
  [helm.files.moduleSecretYaml, () => toYaml(getModuleSecret(this.name, code, this.hash))]
1774
1789
  ];
1775
1790
  await Promise.all(pairs.map(async ([file, content]) => await import_fs4.promises.writeFile(file, content())));
1776
- await overridesFile(this, helm.files.valuesYaml);
1791
+ const overrideData = {
1792
+ hash: this.hash,
1793
+ name: this.name,
1794
+ image: this.image,
1795
+ config: this.config,
1796
+ apiToken: this.apiToken,
1797
+ capabilities: this.capabilities
1798
+ };
1799
+ await overridesFile(overrideData, helm.files.valuesYaml);
1777
1800
  const [mutateWebhook, validateWebhook] = await Promise.all([
1778
1801
  webhookConfig(this, "mutate", this.config.webhookTimeout),
1779
1802
  webhookConfig(this, "validate", this.config.webhookTimeout)
1780
1803
  ]);
1781
- if (validateWebhook || mutateWebhook) {
1782
- await import_fs4.promises.writeFile(helm.files.admissionDeploymentYaml, dedent(admissionDeployTemplate(this.buildTimestamp)));
1783
- await import_fs4.promises.writeFile(helm.files.admissionServiceMonitorYaml, dedent(serviceMonitorTemplate("admission")));
1784
- }
1785
- if (mutateWebhook) {
1786
- await import_fs4.promises.writeFile(helm.files.mutationWebhookYaml, createWebhookYaml(this, mutateWebhook));
1787
- }
1788
- if (validateWebhook) {
1789
- await import_fs4.promises.writeFile(helm.files.validationWebhookYaml, createWebhookYaml(this, validateWebhook));
1790
- }
1804
+ await this.writeWebhookFiles(validateWebhook, mutateWebhook, helm);
1791
1805
  const watchDeployment = getWatcher(this, this.hash, this.buildTimestamp);
1792
1806
  if (watchDeployment) {
1793
1807
  await import_fs4.promises.writeFile(helm.files.watcherDeploymentYaml, dedent(watcherDeployTemplate(this.buildTimestamp)));
@@ -2007,7 +2021,7 @@ var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\nd
2007
2021
  var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a type-safe Kubernetes middleware system.\n\nThe `capabilities` directory contains all the capabilities for this module. By default,\na capability is a single typescript file in the format of `capability-name.ts` that is\nimported in the root `pepr.ts` file as `import { HelloPepr } from "./capabilities/hello-pepr";`.\nBecause this is typescript, you can organize this however you choose, e.g. creating a sub-folder\nper-capability or common logic in shared files or folders.\n\nExample Structure:\n\n```\nModule Root\n\u251C\u2500\u2500 package.json\n\u251C\u2500\u2500 pepr.ts\n\u2514\u2500\u2500 capabilities\n \u251C\u2500\u2500 example-one.ts\n \u251C\u2500\u2500 example-three.ts\n \u2514\u2500\u2500 example-two.ts\n```\n';
2008
2022
  var peprTS = 'import { PeprModule } from "pepr";\n// cfg loads your pepr configuration from package.json\nimport cfg from "./package.json";\n\n// HelloPepr is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\nimport { HelloPepr } from "./capabilities/hello-pepr";\n\n/**\n * This is the main entrypoint for this Pepr module. It is run when the module is started.\n * This is where you register your Pepr configurations and capabilities.\n */\nnew PeprModule(cfg, [\n // "HelloPepr" is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n';
2009
2023
  var helloPeprTS = 'import {\n Capability,\n K8s,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n} from "pepr";\nimport { MockAgent, setGlobalDispatcher } from "undici";\n\n/**\n * The HelloPepr Capability is an example capability to demonstrate some general concepts of Pepr.\n * To test this capability you run `pepr dev`and then run the following command:\n * `kubectl apply -f capabilities/hello-pepr.samples.yaml`\n */\nexport const HelloPepr = new Capability({\n name: "hello-pepr",\n description: "A simple example capability to show how things work.",\n namespaces: ["pepr-demo", "pepr-demo-2"],\n});\n\n// Use the \'When\' function to create a new action, use \'Store\' to persist data\nconst { When, Store } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action removes the label `remove-me` when a Namespace is created.\n * Note we don\'t need to specify the namespace here, because we\'ve already specified\n * it in the Capability definition above.\n */\nWhen(a.Namespace)\n .IsCreated()\n .Mutate(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Watch Action with K8s SSA (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action watches for the `pepr-demo-2` namespace to be created, then creates a ConfigMap with\n * the name `pepr-ssa-demo` and adds the namespace UID to the ConfigMap data. Because Pepr uses\n * server-side apply for this operation, the ConfigMap will be created or updated if it already exists.\n */\nWhen(a.Namespace)\n .IsCreated()\n .WithName("pepr-demo-2")\n .Watch(async ns => {\n Log.info("Namespace pepr-demo-2 was created.");\n\n try {\n // Apply the ConfigMap using K8s server-side apply\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: "pepr-ssa-demo",\n namespace: "pepr-demo-2",\n },\n data: {\n "ns-uid": ns.metadata.uid,\n },\n });\n } catch (error) {\n // You can use the Log object to log messages to the Pepr controller pod\n Log.error(error, "Failed to apply ConfigMap using server-side apply.");\n }\n\n // You can share data between actions using the Store, including between different types of actions\n Store.setItem("watch-data", "This data was stored by a Watch Action.");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single action. They can be in the same file or put imported from other files.\n * In this example, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivalent to manually running:\n * `kubectl label configmap example-1 pepr=was-here`\n * `kubectl annotate configmap example-1 pepr.dev=annotations-work-too`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request\n .SetLabel("pepr", "was-here")\n .SetAnnotation("pepr.dev", "annotations-work-too");\n\n // Use the Store to persist data between requests and Pepr controller pods\n Store.setItem("example-1", "was-here");\n\n // This data is written asynchronously and can be read back via `Store.getItem()` or `Store.subscribe()`\n Store.setItem("example-1-data", JSON.stringify(request.Raw.data));\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate & Validate Actions (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This combines 3 different types of actions: \'Mutate\', \'Validate\', and \'Watch\'. The order\n * of the actions is required, but each action is optional. In this example, when a ConfigMap is created\n * with the name `example-2`, then add a label and annotation, validate that the ConfigMap has the label\n * `pepr`, and log the request.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n // This Mutate Action will mutate the request before it is persisted to the cluster\n\n // Use `request.Merge()` to merge the new data with the existing data\n request.Merge({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n })\n .Validate(request => {\n // This Validate Action will validate the request before it is persisted to the cluster\n\n // Approve the request if the ConfigMap has the label \'pepr\'\n if (request.HasLabel("pepr")) {\n return request.Approve();\n }\n\n // Otherwise, deny the request with an error message (optional)\n return request.Deny("ConfigMap must have label \'pepr\'");\n })\n .Watch((cm, phase) => {\n // This Watch Action will watch the ConfigMap after it has been persisted to the cluster\n Log.info(cm, `ConfigMap was ${phase} with the name example-2`);\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 2a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action shows a simple validation that will deny any ConfigMap that has the\n * annotation `evil`. Note that the `Deny()` function takes an optional second parameter that is a\n * user-defined status code to return.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .Validate(request => {\n if (request.HasAnnotation("evil")) {\n return request.Deny("No evil CM annotations allowed.", 400);\n }\n\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action combines different styles. Unlike the previous actions, this one will look\n * for any ConfigMap in the `pepr-demo` namespace that has the label `change=by-label` during either\n * CREATE or UPDATE. Note that all conditions added such as `WithName()`, `WithLabel()`, `InNamespace()`,\n * are ANDs so all conditions must be true for the request to be processed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("change", "by-label")\n .Mutate(request => {\n // The K8s object e are going to mutate\n const cm = request.Raw;\n\n // Get the username and uid of the K8s request\n const { username, uid } = request.Request.userInfo;\n\n // Store some data about the request in the configmap\n cm.data["username"] = username;\n cm.data["uid"] = uid;\n\n // You can still mix other ways of making changes too\n request.SetAnnotation("pepr.dev", "making-waves");\n });\n\n// This action validates the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Validate(request => {\n // Log and then always approve the request\n Log.info("CM with label \'change=by-label\' was deleted.");\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action show how you can use the `Mutate()` function without an inline function.\n * This is useful if you want to keep your actions small and focused on a single task,\n * or if you want to reuse the same function in multiple actions.\n */\nWhen(a.ConfigMap).IsCreated().WithName("example-4").Mutate(example4Cb);\n\n// This function uses the complete type definition, but is not required.\nfunction example4Cb(cm: PeprMutateRequest<a.ConfigMap>) {\n cm.SetLabel("pepr.dev/first", "true");\n cm.SetLabel("pepr.dev/second", "true");\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is the same as Example 4, except this only operates on a CM in the `pepr-demo-2` namespace.\n * Note because the Capability defines namespaces, the namespace specified here must be one of those.\n * Alternatively, you can remove the namespace from the Capability definition and specify it here.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .InNamespace("pepr-demo-2")\n .WithName("example-4a")\n .Mutate(example4Cb);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action is a bit more complex. It will look for any ConfigMap in the `pepr-demo`\n * namespace that has the label `chuck-norris` during CREATE. When it finds one, it will fetch a\n * random Chuck Norris joke from the API and add it to the ConfigMap. This is a great example of how\n * you can use Pepr to make changes to your K8s objects based on external data.\n *\n * Note the use of the `async` keyword. This is required for any action that uses `await` or `fetch()`.\n *\n * Also note we are passing a type to the `fetch()` function. This is optional, but it will help you\n * avoid mistakes when working with the data returned from the API. You can also use the `as` keyword to\n * cast the data returned from the API.\n *\n * These are equivalent:\n * ```ts\n * const joke = await fetch<TheChuckNorrisJoke>("https://icanhazdadjoke.com/");\n * const joke = await fetch("https://icanhazdadjoke.com/") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://icanhazdadjoke.com")\n * ```\n */\ninterface TheChuckNorrisJoke {\n id: string;\n joke: string;\n status: number;\n}\n\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("chuck-norris")\n .Mutate(cm => cm.SetLabel("got-jokes", "true"))\n .Watch(async cm => {\n const jokeURL = "https://icanhazdadjoke.com";\n\n const mockAgent: MockAgent = new MockAgent();\n setGlobalDispatcher(mockAgent);\n const mockClient = mockAgent.get(jokeURL);\n mockClient.intercept({ path: "/", method: "GET" }).reply(\n 200,\n {\n id: "R7UfaahVfFd",\n joke: "Funny joke goes here.",\n status: 200,\n },\n {\n headers: {\n "Content-Type": "application/json; charset=utf-8",\n },\n },\n );\n\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(jokeURL, {\n headers: {\n Accept: "application/json",\n },\n });\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n const { joke } = response.data;\n // Add Joke to the Store\n await Store.setItemAndWait(jokeURL, joke);\n // Add the Chuck Norris joke to the configmap\n try {\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: cm.metadata.name,\n namespace: cm.metadata.namespace,\n },\n data: {\n "chuck-says": Store.getItem(jokeURL),\n },\n });\n } catch (error) {\n Log.error(error, "Failed to apply ConfigMap using server-side apply.", {\n cm,\n });\n }\n }\n\n // You can also assert on different HTTP response codes\n if (response.status === fetchStatus.NOT_FOUND) {\n // Do something else\n return;\n }\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Mutate(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Untyped Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * Out of the box, Pepr supports all the standard Kubernetes objects. However, you can also create\n * your own types. This is useful if you are working with an Operator that creates custom resources.\n * There are two ways to do this, the first is to use the `When()` function with a `GenericKind`,\n * the second is to create a new class that extends `GenericKind` and use the `RegisterKind()` function.\n *\n * This example shows how to use the `When()` function with a `GenericKind`. Note that you\n * must specify the `group`, `version`, and `kind` of the object (if applicable). This is how Pepr knows\n * if the action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intellisense for the object, so you will need to refer to the\n * Kubernetes API documentation for the object you are working with.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-1\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```\n */\nWhen(a.GenericKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n})\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Typed Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This example shows how to use the `RegisterKind()` function to create a new type. This is useful\n * if you are working with an Operator that creates custom resources and you want to have intellisense\n * for the object. Note that you must specify the `group`, `version`, and `kind` of the object (if applicable)\n * as this is how Pepr knows if the action should be triggered or not.\n *\n * Once you register a new Kind with Pepr, you can use the `When()` function with the new Kind. Ideally,\n * you should register custom Kinds at the top of your Capability file or Pepr Module so they are available\n * to all actions, but we are putting it here for demonstration purposes.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-2\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```*\n */\nclass UnicornKind extends a.GenericKind {\n spec: {\n /**\n * JSDoc comments can be added to explain more details about the field.\n *\n * @example\n * ```ts\n * request.Raw.spec.message = "Hello Pepr!";\n * ```\n * */\n message: string;\n counter: number;\n };\n}\n\nRegisterKind(UnicornKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n});\n\nWhen(UnicornKind)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr with type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * A callback function that is called once the Pepr Store is fully loaded.\n */\nStore.onReady(data => {\n Log.info(data, "Pepr Store Ready");\n});\n';
2010
- var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, files: ["/dist", "/src", "!src/**/*.test.ts", "!dist/**/*.test.d.ts*"], version: "0.42.2", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { ci: "npm ci", "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", version: "node scripts/set-version.js", build: "tsc && node build.mjs && npm pack", "build:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev .", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage --testPathIgnorePatterns='cosign.e2e.test.ts'", "test:journey": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run", "test:journey:prep": "if [ ! -d ./pepr-upgrade-test ]; then git clone https://github.com/defenseunicorns/pepr-upgrade-test.git ; fi", "test:journey-wasm": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:image": "docker buildx build --output type=docker --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest --detectOpenHandles journey/entrypoint.test.ts && npm run test:journey:prep && npm run test:journey:upgrade", "test:journey:run-wasm": "jest --detectOpenHandles journey/entrypoint-wasm.test.ts", "test:journey:upgrade": "npm run test:journey:k3d && npm run test:journey:image && jest --detectOpenHandles journey/pepr-upgrade.test.ts", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write", prepare: `if [ "$NODE_ENV" != 'production' ]; then husky; fi` }, dependencies: { "@types/ramda": "0.30.2", express: "4.21.2", "fast-json-patch": "3.1.1", "follow-redirects": "1.15.9", "http-status-codes": "^2.3.0", "json-pointer": "^0.6.2", "kubernetes-fluent-client": "3.3.7", pino: "9.6.0", "pino-pretty": "13.0.0", "prom-client": "15.1.3", ramda: "0.30.1", sigstore: "3.0.0" }, devDependencies: { "@commitlint/cli": "19.6.1", "@commitlint/config-conventional": "19.6.0", "@fast-check/jest": "^2.0.1", "@jest/globals": "29.7.0", "@types/eslint": "9.6.1", "@types/express": "5.0.0", "@types/follow-redirects": "1.14.4", "@types/json-pointer": "^1.0.34", "@types/node": "22.x.x", "@types/node-forge": "1.3.11", "@types/uuid": "10.0.0", "fast-check": "^3.19.0", husky: "^9.1.6", jest: "29.7.0", "js-yaml": "^4.1.0", "ts-jest": "29.2.5", undici: "^7.0.1" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "7.18.0", "@typescript-eslint/parser": "7.18.0", "@types/prompts": "2.4.9", eslint: "8.57.0", commander: "12.1.0", esbuild: "0.24.0", "node-forge": "1.3.1", prettier: "3.4.2", prompts: "2.4.2", typescript: "^5.3.3", uuid: "11.0.3" } };
2024
+ var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, files: ["/dist", "/src", "!src/**/*.test.ts", "!dist/**/*.test.d.ts*"], version: "0.42.3", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { ci: "npm ci", "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", version: "node scripts/set-version.js", build: "tsc && node build.mjs && npm pack", "build:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev .", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage --testPathIgnorePatterns='cosign.e2e.test.ts'", "test:journey": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run", "test:journey:prep": "if [ ! -d ./pepr-upgrade-test ]; then git clone https://github.com/defenseunicorns/pepr-upgrade-test.git ; fi", "test:journey-wasm": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:image": "docker buildx build --output type=docker --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest --detectOpenHandles journey/entrypoint.test.ts && npm run test:journey:prep && npm run test:journey:upgrade", "test:journey:run-wasm": "jest --detectOpenHandles journey/entrypoint-wasm.test.ts", "test:journey:upgrade": "npm run test:journey:k3d && npm run test:journey:image && jest --detectOpenHandles journey/pepr-upgrade.test.ts", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write", prepare: `if [ "$NODE_ENV" != 'production' ]; then husky; fi` }, dependencies: { "@types/ramda": "0.30.2", express: "4.21.2", "fast-json-patch": "3.1.1", "follow-redirects": "1.15.9", "http-status-codes": "^2.3.0", "json-pointer": "^0.6.2", "kubernetes-fluent-client": "3.3.7", pino: "9.6.0", "pino-pretty": "13.0.0", "prom-client": "15.1.3", ramda: "0.30.1", sigstore: "3.0.0" }, devDependencies: { "@commitlint/cli": "19.6.1", "@commitlint/config-conventional": "19.6.0", "@fast-check/jest": "^2.0.1", "@jest/globals": "29.7.0", "@types/eslint": "9.6.1", "@types/express": "5.0.0", "@types/follow-redirects": "1.14.4", "@types/json-pointer": "^1.0.34", "@types/node": "22.x.x", "@types/node-forge": "1.3.11", "@types/uuid": "10.0.0", "fast-check": "^3.19.0", husky: "^9.1.6", jest: "29.7.0", "js-yaml": "^4.1.0", "ts-jest": "29.2.5", undici: "^7.0.1" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "7.18.0", "@typescript-eslint/parser": "7.18.0", "@types/prompts": "2.4.9", eslint: "8.57.0", commander: "12.1.0", esbuild: "0.24.0", "node-forge": "1.3.1", prettier: "3.4.2", prompts: "2.4.2", typescript: "^5.3.3", uuid: "11.0.3" } };
2011
2025
 
2012
2026
  // src/templates/pepr.code-snippets.json
2013
2027
  var pepr_code_snippets_default = {