@lensmcp/cluster 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +130 -0
  3. package/basic-ssl.d.ts +7 -0
  4. package/basic-ssl.d.ts.map +1 -0
  5. package/basic-ssl.js +158 -0
  6. package/build-scope-patterns.d.ts +12 -0
  7. package/build-scope-patterns.d.ts.map +1 -0
  8. package/build-scope-patterns.js +40 -0
  9. package/create-webpack-dev.d.ts +27 -0
  10. package/create-webpack-dev.d.ts.map +1 -0
  11. package/create-webpack-dev.js +151 -0
  12. package/create-webpack-prod.d.ts +28 -0
  13. package/create-webpack-prod.d.ts.map +1 -0
  14. package/create-webpack-prod.js +169 -0
  15. package/executors/build/build.impl.d.ts +19 -0
  16. package/executors/build/build.impl.d.ts.map +1 -0
  17. package/executors/build/build.impl.js +98 -0
  18. package/executors/build/schema.d.ts +35 -0
  19. package/executors/build/schema.json +135 -0
  20. package/executors/gateway/gateway.impl.d.ts +23 -0
  21. package/executors/gateway/gateway.impl.d.ts.map +1 -0
  22. package/executors/gateway/gateway.impl.js +39 -0
  23. package/executors/gateway/gateway.lib.d.ts +130 -0
  24. package/executors/gateway/gateway.lib.d.ts.map +1 -0
  25. package/executors/gateway/gateway.lib.js +797 -0
  26. package/executors/gateway/jwks-verify.d.ts +28 -0
  27. package/executors/gateway/jwks-verify.d.ts.map +1 -0
  28. package/executors/gateway/jwks-verify.js +121 -0
  29. package/executors/gateway/main.prod-gateway.d.ts +2 -0
  30. package/executors/gateway/main.prod-gateway.d.ts.map +1 -0
  31. package/executors/gateway/main.prod-gateway.js +290 -0
  32. package/executors/gateway/main.rollout.d.ts +2 -0
  33. package/executors/gateway/main.rollout.d.ts.map +1 -0
  34. package/executors/gateway/main.rollout.js +130 -0
  35. package/executors/gateway/manifest.d.ts +275 -0
  36. package/executors/gateway/manifest.d.ts.map +1 -0
  37. package/executors/gateway/manifest.js +344 -0
  38. package/executors/gateway/prod-gateway.lib.d.ts +58 -0
  39. package/executors/gateway/prod-gateway.lib.d.ts.map +1 -0
  40. package/executors/gateway/prod-gateway.lib.js +535 -0
  41. package/executors/gateway/providers-prod.d.ts +46 -0
  42. package/executors/gateway/providers-prod.d.ts.map +1 -0
  43. package/executors/gateway/providers-prod.js +199 -0
  44. package/executors/gateway/registry-source.d.ts +68 -0
  45. package/executors/gateway/registry-source.d.ts.map +1 -0
  46. package/executors/gateway/registry-source.js +131 -0
  47. package/executors/gateway/rollout-ops.d.ts +54 -0
  48. package/executors/gateway/rollout-ops.d.ts.map +1 -0
  49. package/executors/gateway/rollout-ops.js +167 -0
  50. package/executors/gateway/schema.d.ts +10 -0
  51. package/executors/gateway/schema.json +30 -0
  52. package/executors/serve/schema.d.ts +53 -0
  53. package/executors/serve/schema.json +196 -0
  54. package/executors/serve/serve.impl.d.ts +25 -0
  55. package/executors/serve/serve.impl.d.ts.map +1 -0
  56. package/executors/serve/serve.impl.js +243 -0
  57. package/executors/trust/schema.d.ts +6 -0
  58. package/executors/trust/schema.json +20 -0
  59. package/executors/trust/trust.impl.d.ts +42 -0
  60. package/executors/trust/trust.impl.d.ts.map +1 -0
  61. package/executors/trust/trust.impl.js +126 -0
  62. package/executors.json +24 -0
  63. package/index.d.ts +4 -0
  64. package/index.d.ts.map +1 -0
  65. package/index.js +9 -0
  66. package/main.devserver.d.ts +16 -0
  67. package/main.devserver.d.ts.map +1 -0
  68. package/main.devserver.js +812 -0
  69. package/package.json +66 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,130 @@
1
+ # @lensmcp/cluster
2
+
3
+ > Run your Nx workspace as a local, production-shaped cluster — backend pods on unix sockets with true HMR, behind ONE HTTPS gateway with per-project domains, scale-from-zero, autoscale, idle-kill, and local-CA TLS.
4
+
5
+ `@lensmcp/cluster` is the Nx plugin behind [LensMCP](https://github.com/kiwiapps-ltd/lensmcp), an observability lens for coding agents. It turns a monorepo of NestJS services and frontend apps into a cluster that behaves like production *on your laptop*: each backend service runs N hot-swappable child processes ("pods") on unix sockets with real NestJS HMR (20–100ms edit loop, in-memory state preserved), and a single HTTPS gateway routes traffic to them by hostname — `app.tetros.ai.local`, `api.tetros.ai.local`, and so on — over a locally-trusted CA so HTTPS *just works*.
6
+
7
+ The point is parity. The same gateway routing core (`matchRoute` / `buildRouteTable`) runs in dev and in production, so what you exercise locally — per-domain routing, path-mounted microservices, scale-from-zero, edge JWT verification + ABAC, and weighted / attribute-based rollout — is the same shape that ships. In dev the gateway runs on `node:http` + `http-proxy` (it owns the unix-socket pods and their lifecycle); in production the same routing brain is composed over a **Fastify + [@fastify/reply-from](https://github.com/fastify/fastify-reply-from) (undici)** transport, shipped as a **Node 26 distroless** image for the high-RPS edge. Throughout, the cluster publishes to the LensMCP event bus (service up/down, cold starts, autoscale, idle kills, request-derived traffic edges) so the dashboard can draw your live topology.
8
+
9
+ ## Install
10
+
11
+ It's a dev-time Nx plugin:
12
+
13
+ ```bash
14
+ yarn add -D @lensmcp/cluster
15
+ ```
16
+
17
+ Peer dependencies `@nx/devkit`, `@nx/webpack`, and `webpack` are required. `fastify`, `@fastify/reply-from`, and `ioredis` are **optional** peers — install them only if you run the production gateway (Fastify/undici) and/or its Redis-backed registry.
18
+
19
+ ## The `cluster` field
20
+
21
+ A project opts into the cluster by adding a top-level `cluster` block to its `project.json`. The gateway scans every project in the workspace, reads these declarations, and synthesizes the route table from them. (The legacy field name `davnx` is still read for back-compat.)
22
+
23
+ A backend NestJS service in **pod / socket-pool mode**:
24
+
25
+ ```jsonc
26
+ {
27
+ "name": "api",
28
+ "cluster": {
29
+ "host": "api.tetros.ai.local", // public dev hostname (TLS SAN added automatically)
30
+ "service": "api", // socket-pool mode: round-robin the devserver's pods
31
+ "minPods": 1, // spawn this many; autoscale up to maxPods
32
+ "maxPods": 4, // ceiling while requests overlap
33
+ "idleKillSec": 120, // kill a scaled-from-zero service after N idle seconds
34
+ "eager": false // false (default) = start on first request (scale from zero)
35
+ },
36
+ "targets": { "serve-hmr": { "executor": "@lensmcp/cluster:serve", "options": { "childCount": 1 } } }
37
+ }
38
+ ```
39
+
40
+ A frontend app (Vite, etc.) in **TCP / upstream mode**, claiming the root domain as the catch-all:
41
+
42
+ ```jsonc
43
+ {
44
+ "name": "dashboard",
45
+ "cluster": {
46
+ "host": "app.tetros.ai.local",
47
+ "port": 5173, // shorthand for upstream: http://localhost:5173
48
+ "default": true // also serves any unmatched hostname
49
+ }
50
+ }
51
+ ```
52
+
53
+ A second backend **path-mounted** under a shared API domain:
54
+
55
+ ```jsonc
56
+ {
57
+ "name": "crm",
58
+ "cluster": {
59
+ "host": "api.tetros.ai.local", // same host as `api`...
60
+ "path": "/crm", // ...but mounted under a path prefix
61
+ "service": "crm",
62
+ "prependPrefix": "/crm" // forward to the service at /crm/... (prod parity)
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### Fields
68
+
69
+ | field | meaning |
70
+ | --- | --- |
71
+ | `host` | Public dev hostname (e.g. `api.tetros.ai.local`). A TLS SAN is added for it automatically. |
72
+ | `path` | Mount path under `host` — lets multiple backends share one domain (host+path routes outrank host-only). |
73
+ | `service` | **Socket-pool (pods) mode**: the cluster devserver's service name. The gateway round-robins directly over its children's unix sockets — one load balancer in front of N pods, like prod. Pod services also auto-expose `internal.<host>` for east-west calls that **skip** the gateway middleware (the JWT seam). |
74
+ | `upstream` | **TCP mode**: full URL where the dev server listens (e.g. a Vite app). |
75
+ | `port` | Shorthand for `upstream: http://localhost:<port>`. |
76
+ | `prependPrefix` | Prepend to forwarded URLs — serve a prefix-mounted service at the root of its own dev domain (prod parity). |
77
+ | `default` | This project is the catch-all for unmatched hostnames. |
78
+ | `internalHost` | Override the auto `internal.<host>` name, or `false` to disable the internal route. |
79
+ | `auth` | Edge auth policy: `{ default, overrides }` (JWT verify + identity injection + per-path ABAC enforcement). Absent ⇒ unguarded at the edge. Typically generated from controller decorators rather than hand-written. |
80
+ | `eager` | `true` = start at gateway boot; `false` (default) = start on first request (scale from zero). |
81
+ | `minPods` / `maxPods` | Pod range: spawn `minPods`, autoscale up to `maxPods` while requests overlap. |
82
+ | `idleKillSec` | Kill a gateway-spawned (non-eager) service after this many idle seconds. |
83
+ | `serveTarget` | Nx target that runs the service. Default `serve-hmr`. |
84
+ | `adminUrl` | Devserver admin endpoint for scaling (defaults from `port`). |
85
+
86
+ A declaration must route *somewhere*: either a pod `service` or a TCP `upstream`/`port`.
87
+
88
+ ## Executors
89
+
90
+ | executor | purpose | key command |
91
+ | --- | --- | --- |
92
+ | `@lensmcp/cluster:serve` | Webpack watch + integrated devserver running a pod pool of NestJS children (true HMR). | `nx run api:serve-hmr` |
93
+ | `@lensmcp/cluster:gateway` | The workspace HTTPS front door — reads every project's `cluster` field, routes by hostname, serves the local-CA cert with all SANs. | `nx run gateway:serve` |
94
+ | `@lensmcp/cluster:trust` | One-time local HTTPS setup: trust the local CA in the OS keychain + write `/etc/hosts` entries (127.0.0.1 + ::1) for every gateway hostname. Idempotent. | `nx run gateway:trust` |
95
+ | `@lensmcp/cluster:build` | Production webpack build for a NestJS app. | `nx run api:build` |
96
+
97
+ (Target names like `serve-hmr` / `gateway` are conventions; the executor is what matters.)
98
+
99
+ ### Key options
100
+
101
+ **`serve`** — `entryFile`, `tsConfigFile` (required); `childCount` (pods in the pool); `internalPort` (plain-HTTP listener straight to children, no gateway middleware — for service-to-service calls); `workers` (extra entry bundles compiled in watch mode); `servePrefix`, `serviceName`, `configEnv`; `orgScopes` / `bundlePackages` / `nodeExternalsConfig` (control what's bundled vs externalized); an embedded `gateway` block (`middleware`, `routes`, `https`, `extraPorts`) for single-service setups.
102
+
103
+ > Pass `minPods` via the `--childCount` option — the Nx daemon drops spawner env, so don't pin `childCount` in `serve-hmr` options expecting `minPods` to flow through.
104
+
105
+ **`gateway`** — `ports` (default `[443]` so dev domains need no `:port`); `https` (default `true`, terminate TLS with the local CA); `middleware` (workspace-relative JS module `(req) => void` run on every request — the JWT/auth seam; throwing rejects with 401); `trafficFlushMs` (traffic-edge aggregation window before flushing to the LensMCP bus; default 5000).
106
+
107
+ **`trust`** — `serveTarget` (whose `gateway.routes` hostnames to set up, default `serve-hmr`); `hosts` (extra hostnames to add to `/etc/hosts`).
108
+
109
+ **`build`** — `entryFile`, `tsConfigFile` (required); `outputPath`, `assets`, `workers`; `generatePackageJson`; `runtimeDependencies`; `migrationsDir` / `ormConfigPath`; the same bundling controls as `serve`.
110
+
111
+ ## Gateway
112
+
113
+ One front door, two transports sharing one routing brain:
114
+
115
+ - **Routing** — every `cluster` declaration becomes a route; requests match by hostname (exact beats `*.suffix` wildcard) then by most-specific path prefix. A *claimed* host's unmatched root is served by the gateway itself (`/health` aggregate, `/.well-known/...`, CORS + preflights); an *unclaimed* host can only reach the `default` route or 404.
116
+ - **Dev transport** — `node:http` + `http-proxy`. It owns the unix-socket pods: **scale-from-zero** on first request, autoscale while requests overlap, idle-kill, supervised reforks, and ghost-socket sweeping.
117
+ - **Prod transport** — the same `matchRoute` composed over **Fastify + @fastify/reply-from (undici)** (connection-reusing, HTTP/1.1 pipelined; benchmarks materially lower CPU/req than http-proxy), shipped as a **Node 26 distroless** image. No process management — prod pods are always-on (k8s keeps them up).
118
+ - **Edge auth + identity** — for `jwt` routes the gateway verifies the end-user token (dev: HS256 shared secret; prod: RS256 via JWKS) and stamps trusted identity headers (`x-user-id`, `x-tenant-id`, roles, perms) onto the forwarded request; `internal.<host>` routes require `x-api-key`. Per-path **ABAC** rules (a `permission` or full predicate over verified claims + IP/headers, scoped by HTTP method) are enforced at the edge → 403.
119
+ - **Rollout** — per-request upstream selection supports **weighted** cohorts (smooth nginx-style split for canary / blue-green) and **attribute-based targeting** (route by user / tenant / IP / header / sticky device key, consistent-hashed so a ramp moves a key across the boundary at most once). The serving version rides on `x-lensmcp-version` and the trace.
120
+
121
+ ## How it fits
122
+
123
+ `@lensmcp/cluster` is one library in the LensMCP workspace:
124
+
125
+ - **[lensmcp](https://github.com/kiwiapps-ltd/lensmcp)** — the lens / observability dashboard that renders the live cluster topology the gateway publishes.
126
+ - **[@lensmcp/node-instrumentation](https://github.com/kiwiapps-ltd/lensmcp/tree/main/libs/node-instrumentation)** — zero-touch Node instrumentation injected into each pod (the host source stays lens-free); it feeds the events (egress, db/redis/queue ops, NestJS class traces and request flows) the dashboard correlates with the gateway's traffic edges.
127
+
128
+ ---
129
+
130
+ Part of [LensMCP](https://github.com/kiwiapps-ltd/lensmcp). Apache-2.0.
package/basic-ssl.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare const CA_CERT_FILE = "davnx-local-ca.crt";
2
+ export declare function getCertificateSync(cacheDir: string, name?: string, domains?: string[]): string;
3
+ /** Absolute path of the trust-once CA certificate inside `cacheDir`. */
4
+ export declare function caCertPath(cacheDir: string): string;
5
+ /** Mint the local CA if it doesn't exist yet; returns the CA cert path. */
6
+ export declare function ensureCaSync(cacheDir: string): string;
7
+ //# sourceMappingURL=basic-ssl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"basic-ssl.d.ts","sourceRoot":"","sources":["../../../libs/cluster/src/basic-ssl.ts"],"names":[],"mappings":"AA6BA,eAAO,MAAM,YAAY,uBAAuB,CAAC;AAGjD,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,SAAc,EAAE,OAAO,GAAE,MAAM,EAAO,GAAG,MAAM,CAoCvG;AAED,wEAAwE;AACxE,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED,2EAA2E;AAC3E,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMrD"}
package/basic-ssl.js ADDED
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CA_CERT_FILE = void 0;
4
+ exports.getCertificateSync = getCertificateSync;
5
+ exports.caCertPath = caCertPath;
6
+ exports.ensureCaSync = ensureCaSync;
7
+ const tslib_1 = require("tslib");
8
+ /**
9
+ * Dev HTTPS certificates, mkcert-style: a long-lived LOCAL CA (10 years,
10
+ * minted once per project, trusted once in the OS keychain) signs short-lived
11
+ * leaf certs (30 days, re-minted per SAN set). Because the browser chains the
12
+ * leaf to the trusted CA, cert rotation and new gateway hostnames never show
13
+ * an interstitial again — unlike a bare self-signed cert, which would need
14
+ * re-trusting on every change.
15
+ *
16
+ * `getCertificateSync` returns ONE concatenated PEM (leaf key + leaf cert +
17
+ * CA cert). Node's `https.createServer({ key: pem, cert: pem })` accepts it:
18
+ * `key` takes the first private-key block, `cert` takes every certificate
19
+ * block (leaf first, then the CA as the served chain).
20
+ *
21
+ * Trust once (macOS):
22
+ * sudo security add-trusted-cert -d -r trustRoot \
23
+ * -k /Library/Keychains/System.keychain <cacheDir>/davnx-local-ca.crt
24
+ */
25
+ const crypto = tslib_1.__importStar(require("node:crypto"));
26
+ const fs = tslib_1.__importStar(require("node:fs"));
27
+ const path = tslib_1.__importStar(require("node:path"));
28
+ /** Re-mint the leaf when the cached one is older than this (TTL is 30 days). */
29
+ const LEAF_MAX_AGE_MS = 25 * 24 * 60 * 60 * 1000;
30
+ /** CA lifetime (~10 years) and the remaining-validity floor for reuse. */
31
+ const CA_TTL_DAYS = 3650;
32
+ const CA_MIN_REMAINING_MS = 30 * 24 * 60 * 60 * 1000;
33
+ exports.CA_CERT_FILE = 'davnx-local-ca.crt';
34
+ const CA_KEY_FILE = '_ca-key.pem';
35
+ function getCertificateSync(cacheDir, name = 'davnx.dev', domains = []) {
36
+ // The SAN set is part of the cache key: adding a gateway hostname must
37
+ // mint a fresh leaf, not serve a cached one that lacks the new SAN.
38
+ const sanKey = crypto
39
+ .createHash('sha256')
40
+ .update([name, ...[...domains].sort()].join('|'))
41
+ .digest('hex')
42
+ .slice(0, 12);
43
+ const leafPath = path.join(cacheDir, `_leaf-${sanKey}.pem`);
44
+ try {
45
+ const stat = fs.statSync(leafPath);
46
+ if (Date.now() - stat.ctimeMs < LEAF_MAX_AGE_MS) {
47
+ return fs.readFileSync(leafPath, 'utf8');
48
+ }
49
+ }
50
+ catch {
51
+ /* no cache yet */
52
+ }
53
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
54
+ const forge = require('node-forge');
55
+ fs.mkdirSync(cacheDir, { recursive: true });
56
+ const ca = loadOrCreateCa(cacheDir, forge);
57
+ const pem = createLeafCertificate(forge, ca, name, domains);
58
+ fs.writeFileSync(leafPath, pem);
59
+ // Stale leaves and the pre-1.3.4 self-signed cache just rot here — sweep
60
+ // them so the dir holds only the active leaf + the CA pair.
61
+ for (const f of fs.readdirSync(cacheDir)) {
62
+ const stale = (/^_leaf-.*\.pem$/.test(f) && f !== `_leaf-${sanKey}.pem`) ||
63
+ /^_cert.*\.pem$/.test(f) ||
64
+ /-dev\.crt$/.test(f);
65
+ if (stale) {
66
+ try {
67
+ fs.unlinkSync(path.join(cacheDir, f));
68
+ }
69
+ catch { /* best effort */ }
70
+ }
71
+ }
72
+ return pem;
73
+ }
74
+ /** Absolute path of the trust-once CA certificate inside `cacheDir`. */
75
+ function caCertPath(cacheDir) {
76
+ return path.join(cacheDir, exports.CA_CERT_FILE);
77
+ }
78
+ /** Mint the local CA if it doesn't exist yet; returns the CA cert path. */
79
+ function ensureCaSync(cacheDir) {
80
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
81
+ const forge = require('node-forge');
82
+ fs.mkdirSync(cacheDir, { recursive: true });
83
+ loadOrCreateCa(cacheDir, forge);
84
+ return caCertPath(cacheDir);
85
+ }
86
+ function loadOrCreateCa(cacheDir, forge) {
87
+ const certPath = path.join(cacheDir, exports.CA_CERT_FILE);
88
+ const keyPath = path.join(cacheDir, CA_KEY_FILE);
89
+ try {
90
+ const cert = forge.pki.certificateFromPem(fs.readFileSync(certPath, 'utf8'));
91
+ const key = forge.pki.privateKeyFromPem(fs.readFileSync(keyPath, 'utf8'));
92
+ if (cert.validity.notAfter.getTime() - Date.now() > CA_MIN_REMAINING_MS) {
93
+ return { cert, key };
94
+ }
95
+ }
96
+ catch {
97
+ /* no CA yet (or unreadable) — mint one */
98
+ }
99
+ const keys = forge.pki.rsa.generateKeyPair(2048);
100
+ const cert = forge.pki.createCertificate();
101
+ cert.publicKey = keys.publicKey;
102
+ cert.serialNumber = `00${Date.now().toString(16)}`;
103
+ cert.validity.notBefore = new Date(Date.now() - 24 * 60 * 60 * 1000); // clock-skew slack
104
+ cert.validity.notAfter = new Date();
105
+ cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + CA_TTL_DAYS);
106
+ const attrs = [
107
+ { name: 'commonName', value: 'davnx local dev CA' },
108
+ { name: 'organizationName', value: 'davnx' },
109
+ { shortName: 'OU', value: 'dev' },
110
+ ];
111
+ cert.setSubject(attrs);
112
+ cert.setIssuer(attrs);
113
+ cert.setExtensions([
114
+ { name: 'basicConstraints', cA: true, critical: true },
115
+ { name: 'keyUsage', keyCertSign: true, cRLSign: true, critical: true },
116
+ { name: 'subjectKeyIdentifier' },
117
+ ]);
118
+ cert.sign(keys.privateKey, forge.md.sha256.create());
119
+ fs.writeFileSync(certPath, forge.pki.certificateToPem(cert));
120
+ fs.writeFileSync(keyPath, forge.pki.privateKeyToPem(keys.privateKey), { mode: 0o600 });
121
+ return { cert, key: keys.privateKey };
122
+ }
123
+ function createLeafCertificate(forge, ca, name, domains, ttlDays = 30) {
124
+ const keys = forge.pki.rsa.generateKeyPair(2048);
125
+ const cert = forge.pki.createCertificate();
126
+ cert.publicKey = keys.publicKey;
127
+ cert.serialNumber = `00${Date.now().toString(16)}`;
128
+ cert.validity.notBefore = new Date(Date.now() - 24 * 60 * 60 * 1000); // clock-skew slack
129
+ cert.validity.notAfter = new Date();
130
+ cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + ttlDays);
131
+ cert.setSubject([
132
+ { name: 'commonName', value: name },
133
+ { name: 'organizationName', value: 'davnx' },
134
+ { shortName: 'OU', value: 'dev' },
135
+ ]);
136
+ cert.setIssuer(ca.cert.subject.attributes);
137
+ // SANs: localhost + loopbacks always; the gateway hostnames (incl. wildcards) on top.
138
+ const altNames = [
139
+ { type: 2, value: 'localhost' },
140
+ { type: 2, value: '*.localhost' },
141
+ { type: 7, ip: '127.0.0.1' },
142
+ { type: 7, ip: '::1' },
143
+ ...[...new Set(domains)].filter((d) => d && d !== 'localhost').map((d) => ({ type: 2, value: d })),
144
+ ];
145
+ // Apple/Chrome policy for leaf certs: SAN required, EKU serverAuth required,
146
+ // and a leaf must NOT be a CA — keyUsage stays signature/encipherment only.
147
+ cert.setExtensions([
148
+ { name: 'basicConstraints', cA: false },
149
+ { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true },
150
+ { name: 'extKeyUsage', serverAuth: true, clientAuth: true },
151
+ { name: 'subjectAltName', altNames },
152
+ { name: 'subjectKeyIdentifier' },
153
+ ]);
154
+ cert.sign(ca.key, forge.md.sha256.create());
155
+ return (forge.pki.privateKeyToPem(keys.privateKey) +
156
+ forge.pki.certificateToPem(cert) +
157
+ forge.pki.certificateToPem(ca.cert));
158
+ }
@@ -0,0 +1,12 @@
1
+ export interface NodeExternalsConfig {
2
+ allowlist?: (string | RegExp)[];
3
+ additionalModuleDirs?: string[];
4
+ importType?: string;
5
+ }
6
+ export interface ScopePatterns {
7
+ allowlistPatterns: RegExp[];
8
+ scopePrefixes: string[];
9
+ scopePatterns: RegExp[];
10
+ }
11
+ export declare function buildScopePatterns(orgScopes: string[]): ScopePatterns;
12
+ //# sourceMappingURL=build-scope-patterns.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-scope-patterns.d.ts","sourceRoot":"","sources":["../../../libs/cluster/src/build-scope-patterns.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,mBAAmB;IAClC,SAAS,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAChC,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,aAAa;IAC5B,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB;AAED,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,aAAa,CAoCrE"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildScopePatterns = buildScopePatterns;
4
+ function buildScopePatterns(orgScopes) {
5
+ const allowlistPatterns = [];
6
+ const scopePrefixes = [];
7
+ const scopePatterns = [];
8
+ for (const scope of orgScopes) {
9
+ if (!scope)
10
+ continue;
11
+ const regexMatch = scope.match(/^\/(.+)\/([gimsuy]*)$/);
12
+ if (regexMatch) {
13
+ // Regex: /pattern/flags — strip 'g' flag to avoid stateful lastIndex in .test()
14
+ const flags = regexMatch[2].replace('g', '');
15
+ const regex = new RegExp(regexMatch[1], flags);
16
+ allowlistPatterns.push(regex);
17
+ scopePatterns.push(regex);
18
+ }
19
+ else if (scope.includes('/')) {
20
+ // Prefix: @frontegg/agenshield → matches @frontegg/agenshield*
21
+ const escaped = scope.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
22
+ allowlistPatterns.push(new RegExp(`^${escaped}`));
23
+ scopePrefixes.push(scope);
24
+ }
25
+ else if (scope.startsWith('@')) {
26
+ // Org scope: @myorg → matches @myorg/*
27
+ const escaped = scope.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
28
+ allowlistPatterns.push(new RegExp(`^${escaped}/`));
29
+ scopePrefixes.push(scope.endsWith('/') ? scope : `${scope}/`);
30
+ }
31
+ else {
32
+ // Exact package name: lodash → matches lodash and lodash/subpath
33
+ const escaped = scope.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
34
+ const regex = new RegExp(`^${escaped}(/|$)`);
35
+ allowlistPatterns.push(regex);
36
+ scopePatterns.push(regex);
37
+ }
38
+ }
39
+ return { allowlistPatterns, scopePrefixes, scopePatterns };
40
+ }
@@ -0,0 +1,27 @@
1
+ import { type NodeExternalsConfig } from './build-scope-patterns';
2
+ export type { NodeExternalsConfig };
3
+ export interface DevWebpackOptions {
4
+ appName: string;
5
+ appRoot: string;
6
+ outputDir: string;
7
+ main: string;
8
+ tsConfig: string;
9
+ workspaceRoot: string;
10
+ assets?: string[];
11
+ port: number;
12
+ serviceName: string;
13
+ memoryLimit?: number;
14
+ buildLibsFromSource?: boolean;
15
+ orgScopes?: string[];
16
+ bundlePackages?: string[];
17
+ nodeExternalsConfig?: NodeExternalsConfig;
18
+ additionalEntryPoints?: Array<{
19
+ entryName: string;
20
+ entryPath: string;
21
+ }>;
22
+ webpackConfigPath?: string;
23
+ /** Parent terminates TLS (gateway.https) — reload notifications go over https. */
24
+ httpsReload?: boolean;
25
+ }
26
+ export declare function createDevWebpackConfig(options: DevWebpackOptions): Record<string, any>;
27
+ //# sourceMappingURL=create-webpack-dev.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-webpack-dev.d.ts","sourceRoot":"","sources":["../../../libs/cluster/src/create-webpack-dev.ts"],"names":[],"mappings":"AAIA,OAAO,EAAsB,KAAK,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAOtF,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;IAC1C,qBAAqB,CAAC,EAAE,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxE,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kFAAkF;IAClF,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AA2CD,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAoItF"}