@mrsimpson/homelab-core-components 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,723 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ExposedWebApp = exports.AuthType = void 0;
37
+ const cloudflare = __importStar(require("@pulumi/cloudflare"));
38
+ const k8s = __importStar(require("@pulumi/kubernetes"));
39
+ const pulumi = __importStar(require("@pulumi/pulumi"));
40
+ /**
41
+ * ExposedWebApp — reusable Pulumi component for deploying web apps with secure internet exposure.
42
+ *
43
+ * Handles the full stack: Deployment → Service → HTTPRoute/IngressRoute → TLS → DNS.
44
+ *
45
+ * ## Authentication modes
46
+ * - `AuthType.NONE` — no auth, public access
47
+ * - `AuthType.FORWARD` — Authelia forward-auth via Traefik ForwardAuth middleware
48
+ * - `AuthType.OAUTH2_PROXY` — GitHub OAuth via the shared oauth2-proxy IngressRoute
49
+ *
50
+ * ## What gets created automatically
51
+ * - `Namespace` (with Pod Security Standards labels, unless you pass your own)
52
+ * - `Deployment` + `Service` (ClusterIP)
53
+ * - `HTTPRoute` or `IngressRoute[]` depending on auth mode
54
+ * - Optional `PersistentVolumeClaim` (when `storage` is set)
55
+ * - Optional Cloudflare DNS `Record` (when `cloudflare` is set)
56
+ * - Optional `ExternalSecret` for GHCR pull credentials (when `imagePullSecrets` references `ghcr-pull-secret`)
57
+ *
58
+ * ## Key options
59
+ *
60
+ * ### Container overrides
61
+ * - `command` / `args` — override entrypoint / arguments (e.g. `args: ["web", "--port", "4096"]`)
62
+ *
63
+ * ### Extra volumes
64
+ * - `extraVolumes` / `extraVolumeMounts` — inject additional volumes (ConfigMaps, hostPath, etc.)
65
+ * alongside the built-in storage PVC mount.
66
+ *
67
+ * ### Node pinning
68
+ * - `nodeSelector` — pin the pod to specific node(s) by label.
69
+ * **Required when using hostPath volumes**, which are node-local by definition.
70
+ * Example: `{ "kubernetes.io/hostname": "flinker" }`
71
+ *
72
+ * ### Security context
73
+ * - `securityContext.runAsUser/Group/fsGroup` — UID/GID for the container and volume ownership.
74
+ * - `securityContext.allowRoot` — set to `true` only when the image genuinely requires UID 0.
75
+ * Automatically relaxes the namespace Pod Security Standard from `restricted` to `baseline`.
76
+ * Also disables `runAsNonRoot` on the pod and container security contexts.
77
+ * Prefer fixing the image to run as non-root instead of using this flag.
78
+ * - `extraVolumes` with `hostPath` — automatically relaxes the namespace PSS to `privileged`
79
+ * (the only level that permits hostPath volumes per the Kubernetes PSS spec).
80
+ * The pod itself still runs as non-root with all capabilities dropped.
81
+ *
82
+ * ### Service account
83
+ * - `serviceAccountName` — set the pod's ServiceAccount (must already exist in the namespace).
84
+ * Useful when the app needs RBAC permissions (e.g. managing pods via the K8s API).
85
+ *
86
+ * ### Health probes
87
+ * - `probes.readinessProbe` / `probes.livenessProbe` — standard Kubernetes probe objects
88
+ * applied to the main app container. Omit to use no probes (Kubernetes default).
89
+ *
90
+ * ## OAuth2-Proxy middleware naming
91
+ *
92
+ * When `auth` is `AuthType.OAUTH2_PROXY`, three Traefik middlewares are created in the
93
+ * app's namespace with deterministic names:
94
+ * - `<name>-oauth2-forwardauth` — ForwardAuth check against oauth2-proxy
95
+ * - `<name>-oauth2-errors` — 401 → redirect to sign-in
96
+ * - `<name>-oauth2-chain` — chains errors + forwardauth
97
+ *
98
+ * Apps that need **additional IngressRoutes** (e.g. wildcard subdomain routes) can
99
+ * reference the chain middleware by name to share the same auth flow:
100
+ * ```yaml
101
+ * middlewares:
102
+ * - name: <name>-oauth2-chain
103
+ * namespace: <app-namespace>
104
+ * ```
105
+ *
106
+ * ## Example
107
+ * ```typescript
108
+ * homelab.createExposedWebApp("blog", {
109
+ * image: "ghost:5",
110
+ * domain: pulumi.interpolate`blog.${homelabConfig.domain}`,
111
+ * port: 2368,
112
+ * auth: AuthType.OAUTH2_PROXY,
113
+ * storage: { size: "10Gi", mountPath: "/var/lib/ghost/content" },
114
+ * nodeSelector: { "kubernetes.io/hostname": "flinker" },
115
+ * extraVolumes: [{ name: "cfg", configMap: { name: "blog-config" } }],
116
+ * extraVolumeMounts: [{ name: "cfg", mountPath: "/etc/blog" }],
117
+ * });
118
+ * ```
119
+ */
120
+ /**
121
+ * Authentication type for ExposedWebApp
122
+ */
123
+ var AuthType;
124
+ (function (AuthType) {
125
+ /** No authentication required */
126
+ AuthType["NONE"] = "none";
127
+ /** Authelia forward authentication via Traefik ForwardAuth middleware */
128
+ AuthType["FORWARD"] = "forward";
129
+ /** OAuth2-Proxy authentication via GitHub OAuth (uses IngressRoute instead of HTTPRoute) */
130
+ AuthType["OAUTH2_PROXY"] = "oauth2";
131
+ })(AuthType || (exports.AuthType = AuthType = {}));
132
+ class ExposedWebApp extends pulumi.ComponentResource {
133
+ namespace;
134
+ deployment;
135
+ service;
136
+ /** Route resource(s): single HTTPRoute (Authelia/NONE) or IngressRoute[] (OAuth2-Proxy) */
137
+ route;
138
+ forwardAuthMiddleware;
139
+ dnsRecord;
140
+ pvc;
141
+ constructor(name, args, opts) {
142
+ super("homelab:ExposedWebApp", name, {}, opts);
143
+ const childOpts = { parent: this };
144
+ // Use provided namespace or create a new one
145
+ const isCreatingNamespace = !args.namespace;
146
+ // Pod Security Standard level for the namespace:
147
+ // - "restricted": default, enforces non-root, no hostPath, etc.
148
+ // - "baseline": required when allowRoot is set (permits running as UID 0)
149
+ // - "privileged": required when hostPath volumes are present (hostPath is
150
+ // forbidden even in baseline per the K8s PSS spec)
151
+ const hasHostPath = args.extraVolumes?.some((v) => typeof v === "object" && v !== null && "hostPath" in v);
152
+ const podSecurityLevel = hasHostPath
153
+ ? "privileged"
154
+ : args.securityContext?.allowRoot
155
+ ? "baseline"
156
+ : "restricted";
157
+ const namespace = args.namespace ||
158
+ new k8s.core.v1.Namespace(`${name}-ns`, {
159
+ metadata: {
160
+ name: name,
161
+ labels: {
162
+ app: name,
163
+ environment: pulumi.getStack(),
164
+ // Pod Security Standards — relaxed to "baseline" when the image requires root
165
+ "pod-security.kubernetes.io/enforce": podSecurityLevel,
166
+ "pod-security.kubernetes.io/audit": podSecurityLevel,
167
+ "pod-security.kubernetes.io/warn": podSecurityLevel,
168
+ },
169
+ },
170
+ }, childOpts);
171
+ this.namespace = namespace;
172
+ // If creating a new namespace AND imagePullSecrets are specified,
173
+ // automatically create ExternalSecrets for common pull secret names
174
+ const pullSecretResources = [];
175
+ if (isCreatingNamespace && args.imagePullSecrets && args.externalSecrets) {
176
+ const storeName = args.externalSecrets.storeName || "pulumi-esc";
177
+ // Create dependencies for ExternalSecret
178
+ const externalSecretDeps = [namespace];
179
+ if (args.externalSecrets.operator) {
180
+ externalSecretDeps.push(args.externalSecrets.operator);
181
+ }
182
+ args.imagePullSecrets.forEach((pullSecret) => {
183
+ // Only auto-create for known secret names to avoid creating unnecessary resources
184
+ if (pullSecret.name === "ghcr-pull-secret") {
185
+ pullSecretResources.push(new k8s.apiextensions.CustomResource(`${name}-ghcr-pull-secret`, {
186
+ apiVersion: "external-secrets.io/v1beta1",
187
+ kind: "ExternalSecret",
188
+ metadata: {
189
+ name: "ghcr-pull-secret",
190
+ namespace: namespace.metadata.name,
191
+ },
192
+ spec: {
193
+ refreshInterval: "1h",
194
+ secretStoreRef: {
195
+ name: storeName,
196
+ kind: "ClusterSecretStore",
197
+ },
198
+ target: {
199
+ name: "ghcr-pull-secret",
200
+ creationPolicy: "Owner",
201
+ template: {
202
+ type: "kubernetes.io/dockerconfigjson",
203
+ data: {
204
+ ".dockerconfigjson": `{"auths":{"ghcr.io":{"username":"{{ .github_username }}","password":"{{ .github_token }}","auth":"{{ printf "%s:%s" .github_username .github_token | b64enc }}"}}}`,
205
+ },
206
+ },
207
+ },
208
+ data: [
209
+ {
210
+ secretKey: "github_username",
211
+ remoteRef: {
212
+ key: "github-username",
213
+ },
214
+ },
215
+ {
216
+ secretKey: "github_token",
217
+ remoteRef: {
218
+ key: "github-token",
219
+ },
220
+ },
221
+ ],
222
+ },
223
+ }, { ...childOpts, dependsOn: externalSecretDeps }));
224
+ }
225
+ else if (pullSecret.name === "dockerhub-pull-secret") {
226
+ pullSecretResources.push(new k8s.apiextensions.CustomResource(`${name}-dockerhub-pull-secret`, {
227
+ apiVersion: "external-secrets.io/v1beta1",
228
+ kind: "ExternalSecret",
229
+ metadata: {
230
+ name: "dockerhub-pull-secret",
231
+ namespace: namespace.metadata.name,
232
+ },
233
+ spec: {
234
+ refreshInterval: "1h",
235
+ secretStoreRef: {
236
+ name: storeName,
237
+ kind: "ClusterSecretStore",
238
+ },
239
+ target: {
240
+ name: "dockerhub-pull-secret",
241
+ creationPolicy: "Owner",
242
+ template: {
243
+ type: "kubernetes.io/dockerconfigjson",
244
+ data: {
245
+ ".dockerconfigjson": `{
246
+ "auths": {
247
+ "https://index.docker.io/v1/": {
248
+ "username": "{{ .dockerhub_username }}",
249
+ "password": "{{ .dockerhub_token }}",
250
+ "auth": "{{ printf "%s:%s" .dockerhub_username .dockerhub_token | b64enc }}"
251
+ }
252
+ }
253
+ }`,
254
+ },
255
+ },
256
+ },
257
+ data: [
258
+ {
259
+ secretKey: "dockerhub_username",
260
+ remoteRef: {
261
+ key: "dockerhub-credentials/username",
262
+ },
263
+ },
264
+ {
265
+ secretKey: "dockerhub_token",
266
+ remoteRef: {
267
+ key: "dockerhub-credentials/token",
268
+ },
269
+ },
270
+ ],
271
+ },
272
+ }, { ...childOpts, dependsOn: externalSecretDeps }));
273
+ }
274
+ });
275
+ }
276
+ // Optional: Create PVC for persistent storage
277
+ if (args.storage) {
278
+ this.pvc = new k8s.core.v1.PersistentVolumeClaim(`${name}-pvc`, {
279
+ metadata: {
280
+ name: `${name}-storage`,
281
+ namespace: namespace.metadata.name,
282
+ },
283
+ spec: {
284
+ accessModes: ["ReadWriteOnce"],
285
+ storageClassName: args.storage.storageClass || "local-path",
286
+ resources: {
287
+ requests: {
288
+ storage: args.storage.size,
289
+ },
290
+ },
291
+ },
292
+ }, childOpts);
293
+ }
294
+ // Main application container
295
+ const appContainer = {
296
+ name: "app",
297
+ image: args.image,
298
+ ports: [
299
+ {
300
+ containerPort: args.port,
301
+ name: "http",
302
+ },
303
+ ],
304
+ env: args.env || [],
305
+ resources: args.resources || {
306
+ requests: { cpu: "100m", memory: "128Mi" },
307
+ limits: { cpu: "500m", memory: "512Mi" },
308
+ },
309
+ securityContext: {
310
+ allowPrivilegeEscalation: false,
311
+ // Only enforce runAsNonRoot when the image supports it (opt-out via allowRoot)
312
+ ...(args.securityContext?.allowRoot ? {} : { runAsNonRoot: true }),
313
+ capabilities: {
314
+ drop: ["ALL"],
315
+ },
316
+ seccompProfile: {
317
+ type: "RuntimeDefault",
318
+ },
319
+ },
320
+ };
321
+ // Add optional command / args overrides
322
+ if (args.command) {
323
+ appContainer.command = args.command;
324
+ }
325
+ if (args.args) {
326
+ appContainer.args = args.args;
327
+ }
328
+ // Add optional probes
329
+ if (args.probes?.readinessProbe) {
330
+ appContainer.readinessProbe = args.probes.readinessProbe;
331
+ }
332
+ if (args.probes?.livenessProbe) {
333
+ appContainer.livenessProbe = args.probes.livenessProbe;
334
+ }
335
+ // Build volume mounts: storage PVC mount + any extra mounts
336
+ const volumeMounts = [];
337
+ if (args.storage && this.pvc) {
338
+ volumeMounts.push({
339
+ name: "storage",
340
+ mountPath: args.storage.mountPath,
341
+ });
342
+ }
343
+ if (args.extraVolumeMounts) {
344
+ volumeMounts.push(...args.extraVolumeMounts);
345
+ }
346
+ if (volumeMounts.length > 0) {
347
+ appContainer.volumeMounts = volumeMounts;
348
+ }
349
+ // Build volumes list: storage PVC + any extra volumes
350
+ const volumes = [];
351
+ if (args.storage && this.pvc) {
352
+ volumes.push({
353
+ name: "storage",
354
+ persistentVolumeClaim: {
355
+ claimName: this.pvc.metadata.name,
356
+ },
357
+ });
358
+ }
359
+ if (args.extraVolumes) {
360
+ volumes.push(...args.extraVolumes);
361
+ }
362
+ // Create Deployment
363
+ // Build deployment dependencies - include pull secrets if we created them
364
+ const deploymentDeps = [namespace, ...pullSecretResources];
365
+ this.deployment = new k8s.apps.v1.Deployment(`${name}-deployment`, {
366
+ metadata: {
367
+ name: name,
368
+ namespace: namespace.metadata.name,
369
+ labels: {
370
+ app: name,
371
+ environment: pulumi.getStack(),
372
+ },
373
+ },
374
+ spec: {
375
+ replicas: args.replicas || 1,
376
+ selector: {
377
+ matchLabels: {
378
+ app: name,
379
+ },
380
+ },
381
+ template: {
382
+ metadata: {
383
+ labels: {
384
+ app: name,
385
+ },
386
+ },
387
+ spec: {
388
+ serviceAccountName: args.serviceAccountName,
389
+ imagePullSecrets: args.imagePullSecrets,
390
+ nodeSelector: args.nodeSelector,
391
+ securityContext: {
392
+ // Only enforce runAsNonRoot when the image supports it (opt-out via allowRoot)
393
+ ...(args.securityContext?.allowRoot ? {} : { runAsNonRoot: true }),
394
+ // When allowRoot is true, omit runAsUser/runAsGroup to let the image use its own UID
395
+ ...(args.securityContext?.allowRoot
396
+ ? {}
397
+ : {
398
+ runAsUser: args.securityContext?.runAsUser || 1000,
399
+ runAsGroup: args.securityContext?.runAsGroup || 1000,
400
+ }),
401
+ fsGroup: args.securityContext?.allowRoot
402
+ ? undefined
403
+ : args.securityContext?.fsGroup || 1000,
404
+ },
405
+ containers: [
406
+ appContainer,
407
+ ...(args.extraContainers ?? []),
408
+ ],
409
+ initContainers: args.initContainers,
410
+ volumes: volumes.length > 0 ? volumes : undefined,
411
+ },
412
+ },
413
+ },
414
+ }, { ...childOpts, dependsOn: deploymentDeps });
415
+ // Create Service
416
+ this.service = new k8s.core.v1.Service(`${name}-service`, {
417
+ metadata: {
418
+ name: name,
419
+ namespace: namespace.metadata.name,
420
+ },
421
+ spec: {
422
+ type: "ClusterIP",
423
+ selector: {
424
+ app: name,
425
+ },
426
+ ports: [
427
+ {
428
+ port: 80,
429
+ targetPort: args.port,
430
+ protocol: "TCP",
431
+ name: "http",
432
+ },
433
+ ],
434
+ },
435
+ }, { ...childOpts, dependsOn: [this.deployment] });
436
+ // --- Routing & Authentication ---
437
+ // OAuth2-Proxy uses IngressRoute (Traefik CRD) for reliable cross-namespace support
438
+ // Authelia and NONE use Gateway API HTTPRoute
439
+ if (args.auth === AuthType.OAUTH2_PROXY) {
440
+ // --- OAuth2-Proxy: IngressRoute-based routing ---
441
+ const oauth2Group = args.oauth2Proxy?.group || "users";
442
+ const oauth2Namespace = args.oauth2Proxy?.namespace || "oauth2-proxy";
443
+ const oauth2ProxyServiceAddress = `http://oauth2-proxy-${oauth2Group}.${oauth2Namespace}.svc.cluster.local/oauth2/auth`;
444
+ // ForwardAuth middleware - checks session via /oauth2/auth
445
+ this.forwardAuthMiddleware = new k8s.apiextensions.CustomResource(`${name}-oauth2-forwardauth`, {
446
+ apiVersion: "traefik.io/v1alpha1",
447
+ kind: "Middleware",
448
+ metadata: {
449
+ name: `${name}-oauth2-forwardauth`,
450
+ namespace: namespace.metadata.name,
451
+ },
452
+ spec: {
453
+ forwardAuth: {
454
+ address: oauth2ProxyServiceAddress,
455
+ trustForwardHeader: true,
456
+ // CRITICAL: Forward Cookie header so oauth2-proxy can see the session
457
+ authRequestHeaders: ["Cookie", "Authorization"],
458
+ authResponseHeaders: [
459
+ "X-Auth-Request-User",
460
+ "X-Auth-Request-Email",
461
+ "X-Auth-Request-Groups",
462
+ "Set-Cookie",
463
+ ],
464
+ },
465
+ },
466
+ }, { ...childOpts, dependsOn: [this.service] });
467
+ // Use shared redirect service from oauth2-proxy namespace
468
+ // This eliminates per-app ConfigMap + Deployment + Service (3 resources saved!)
469
+ // Errors middleware - catches 401 and serves redirect page from shared service
470
+ const errorsMiddleware = new k8s.apiextensions.CustomResource(`${name}-oauth2-errors`, {
471
+ apiVersion: "traefik.io/v1alpha1",
472
+ kind: "Middleware",
473
+ metadata: {
474
+ name: `${name}-oauth2-errors`,
475
+ namespace: namespace.metadata.name,
476
+ },
477
+ spec: {
478
+ errors: {
479
+ status: ["401"],
480
+ service: {
481
+ // Use ExternalName service to reference shared redirect service in oauth2-proxy namespace
482
+ name: "oauth2-shared-redirect",
483
+ namespace: "oauth2-proxy",
484
+ port: 80,
485
+ },
486
+ query: pulumi.interpolate `/?rd=https://${args.domain}{url}`,
487
+ },
488
+ },
489
+ }, { ...childOpts, dependsOn: [this.service] });
490
+ // Chain middleware - errors wraps forwardauth
491
+ const chainMiddleware = new k8s.apiextensions.CustomResource(`${name}-oauth2-chain`, {
492
+ apiVersion: "traefik.io/v1alpha1",
493
+ kind: "Middleware",
494
+ metadata: {
495
+ name: `${name}-oauth2-chain`,
496
+ namespace: namespace.metadata.name,
497
+ },
498
+ spec: {
499
+ chain: {
500
+ middlewares: [
501
+ { name: `${name}-oauth2-errors` },
502
+ { name: `${name}-oauth2-forwardauth` },
503
+ ],
504
+ },
505
+ },
506
+ }, { ...childOpts, dependsOn: [errorsMiddleware, this.forwardAuthMiddleware] });
507
+ // IngressRoute 1: /oauth2/* → oauth2-proxy (unprotected, handles sign-in flow)
508
+ const signinRoute = new k8s.apiextensions.CustomResource(`${name}-oauth2-signin-route`, {
509
+ apiVersion: "traefik.io/v1alpha1",
510
+ kind: "IngressRoute",
511
+ metadata: {
512
+ name: `${name}-oauth2-signin`,
513
+ namespace: namespace.metadata.name,
514
+ },
515
+ spec: {
516
+ // Use "web" entryPoint: Cloudflare terminates TLS, traffic arrives as HTTP
517
+ entryPoints: ["web"],
518
+ routes: [
519
+ {
520
+ match: pulumi.interpolate `Host(\`${args.domain}\`) && PathPrefix(\`/oauth2/\`)`,
521
+ kind: "Rule",
522
+ services: [
523
+ {
524
+ name: `oauth2-proxy-${oauth2Group}`,
525
+ namespace: oauth2Namespace,
526
+ port: 80,
527
+ },
528
+ ],
529
+ },
530
+ ],
531
+ },
532
+ }, { ...childOpts, dependsOn: [namespace] });
533
+ // IngressRoute 2: /* → app backend (protected by middleware chain)
534
+ const appRoute = new k8s.apiextensions.CustomResource(`${name}-oauth2-app-route`, {
535
+ apiVersion: "traefik.io/v1alpha1",
536
+ kind: "IngressRoute",
537
+ metadata: {
538
+ name: `${name}-oauth2-app`,
539
+ namespace: namespace.metadata.name,
540
+ },
541
+ spec: {
542
+ entryPoints: ["web"],
543
+ routes: [
544
+ {
545
+ match: pulumi.interpolate `Host(\`${args.domain}\`)`,
546
+ kind: "Rule",
547
+ middlewares: [
548
+ {
549
+ name: `${name}-oauth2-chain`,
550
+ namespace: namespace.metadata.name,
551
+ },
552
+ ],
553
+ services: [
554
+ {
555
+ name: this.service.metadata.name,
556
+ port: 80,
557
+ },
558
+ ],
559
+ priority: 1, // Lower priority than /oauth2/* route
560
+ },
561
+ ],
562
+ },
563
+ }, { ...childOpts, dependsOn: [this.service, chainMiddleware, signinRoute] });
564
+ this.route = [signinRoute, appRoute];
565
+ }
566
+ else {
567
+ // --- Authelia / NONE: Gateway API HTTPRoute ---
568
+ const gatewayName = args.gatewayApi?.gatewayName || "homelab-gateway";
569
+ const gatewayNamespace = args.gatewayApi?.gatewayNamespace || "traefik-system";
570
+ // Build Gateway API dependencies
571
+ const httpRouteDeps = [this.service];
572
+ if (args.gatewayApi?.controller) {
573
+ httpRouteDeps.push(args.gatewayApi.controller);
574
+ }
575
+ if (args.tls?.clusterIssuer) {
576
+ httpRouteDeps.push(args.tls.clusterIssuer);
577
+ }
578
+ // Create ForwardAuth middleware for Authelia
579
+ if (args.auth === AuthType.FORWARD) {
580
+ this.forwardAuthMiddleware = new k8s.apiextensions.CustomResource(`${name}-forwardauth`, {
581
+ apiVersion: "traefik.io/v1alpha1",
582
+ kind: "Middleware",
583
+ metadata: {
584
+ name: `forwardauth`,
585
+ namespace: namespace.metadata.name,
586
+ },
587
+ spec: {
588
+ forwardAuth: {
589
+ address: "http://authelia.authelia.svc.cluster.local:9091/api/authz/auth-request",
590
+ trustForwardHeader: true,
591
+ authRequestHeaders: [
592
+ "X-Original-URL",
593
+ "X-Original-Method",
594
+ "X-Forwarded-Host",
595
+ "X-Forwarded-Proto",
596
+ "X-Forwarded-Uri",
597
+ "Accept",
598
+ "Authorization",
599
+ "Cookie",
600
+ ],
601
+ authResponseHeaders: [
602
+ "Remote-User",
603
+ "Remote-Groups",
604
+ "Remote-Name",
605
+ "Remote-Email",
606
+ ],
607
+ },
608
+ },
609
+ }, {
610
+ ...childOpts,
611
+ dependsOn: httpRouteDeps,
612
+ });
613
+ httpRouteDeps.push(this.forwardAuthMiddleware);
614
+ }
615
+ // Determine TLS configuration
616
+ const tlsIssuerName = args.tls?.clusterIssuerName || "letsencrypt-prod";
617
+ const hasTLS = args.tls?.clusterIssuer || args.tls?.clusterIssuerName;
618
+ // Build HTTPRoute spec
619
+ const httpRouteSpec = {
620
+ parentRefs: [
621
+ {
622
+ name: gatewayName,
623
+ namespace: gatewayNamespace,
624
+ },
625
+ ],
626
+ hostnames: [args.domain],
627
+ rules: [
628
+ {
629
+ matches: [
630
+ {
631
+ path: {
632
+ type: "PathPrefix",
633
+ value: "/",
634
+ },
635
+ },
636
+ ],
637
+ backendRefs: [
638
+ {
639
+ name: this.service.metadata.name,
640
+ port: 80,
641
+ },
642
+ ],
643
+ },
644
+ ],
645
+ };
646
+ // Add ForwardAuth middleware for Authelia authentication
647
+ if (args.auth === AuthType.FORWARD && this.forwardAuthMiddleware) {
648
+ httpRouteSpec.rules[0].filters = [
649
+ {
650
+ type: "RequestHeaderModifier",
651
+ requestHeaderModifier: {
652
+ set: [
653
+ {
654
+ name: "X-Original-URL",
655
+ value: `https://${args.domain}`,
656
+ },
657
+ {
658
+ name: "X-Original-Method",
659
+ value: "GET",
660
+ },
661
+ ],
662
+ },
663
+ },
664
+ {
665
+ type: "ExtensionRef",
666
+ extensionRef: {
667
+ group: "traefik.io",
668
+ kind: "Middleware",
669
+ name: this.forwardAuthMiddleware.metadata.name,
670
+ },
671
+ },
672
+ ];
673
+ }
674
+ // Create Gateway API HTTPRoute
675
+ this.route = new k8s.apiextensions.CustomResource(`${name}-httproute`, {
676
+ apiVersion: "gateway.networking.k8s.io/v1",
677
+ kind: "HTTPRoute",
678
+ metadata: {
679
+ name: name,
680
+ namespace: namespace.metadata.name,
681
+ annotations: hasTLS
682
+ ? {
683
+ "cert-manager.io/cluster-issuer": tlsIssuerName,
684
+ }
685
+ : {},
686
+ },
687
+ spec: httpRouteSpec,
688
+ }, {
689
+ ...childOpts,
690
+ dependsOn: httpRouteDeps,
691
+ });
692
+ }
693
+ // Optional: Create Cloudflare DNS record
694
+ if (args.cloudflare) {
695
+ this.dnsRecord = new cloudflare.Record(`${name}-dns`, {
696
+ zoneId: args.cloudflare.zoneId,
697
+ name: args.domain,
698
+ type: "CNAME",
699
+ content: args.cloudflare.tunnelCname,
700
+ // Proxy through Cloudflare to enable both IPv4 and IPv6
701
+ proxied: true,
702
+ comment: `Managed by Pulumi - ${name}`,
703
+ // Allow Pulumi to take ownership of a pre-existing record with the
704
+ // same name/type (e.g. when migrating from manually-created records
705
+ // or when the Pulumi URN changes due to refactoring).
706
+ allowOverwrite: true,
707
+ }, childOpts);
708
+ }
709
+ this.registerOutputs({
710
+ namespaceName: this.namespace.metadata.name,
711
+ deploymentName: this.deployment.metadata.name,
712
+ serviceName: this.service.metadata.name,
713
+ routeName: Array.isArray(this.route)
714
+ ? this.route.map((r) => r.metadata.name)
715
+ : this.route.metadata.name,
716
+ forwardAuthMiddlewareName: this.forwardAuthMiddleware?.metadata.name,
717
+ domain: args.domain,
718
+ dnsRecordId: this.dnsRecord?.id,
719
+ });
720
+ }
721
+ }
722
+ exports.ExposedWebApp = ExposedWebApp;
723
+ //# sourceMappingURL=ExposedWebApp.js.map