@smartindustriesllc/ecosystem-client 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Mikel Smart
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # @smartindustriesllc/ecosystem-client
2
+
3
+ Client library for joining the
4
+ [appEcosystem](https://github.com/M1K31/appEcosystem) service mesh from Node.js:
5
+ register a service, discover peers, and publish or subscribe to events.
6
+
7
+ The Node counterpart of the Python `appecosystem-client` package. Services find
8
+ each other through a local registry, so an application can react to what other
9
+ applications on the network are doing without any of them being hard-wired to
10
+ each other.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @smartindustriesllc/ecosystem-client
16
+ ```
17
+
18
+ Node 18+. Pulls in `@smartindustriesllc/ecosystem-auth` for request signing.
19
+
20
+ `bonjour-service` is an *optional* dependency used for mDNS discovery; the
21
+ client falls back to the registry when it is absent.
22
+
23
+ ## Join the ecosystem
24
+
25
+ ```js
26
+ const { EcosystemClient } = require("@smartindustriesllc/ecosystem-client");
27
+
28
+ const eco = new EcosystemClient({
29
+ serviceName: "my-app",
30
+ servicePort: 9000,
31
+ });
32
+
33
+ await eco.start(); // register, then discover peers
34
+ await eco.publish("myapp.ready", { version: "1.0" });
35
+ await eco.stop(); // deregister cleanly
36
+ ```
37
+
38
+ ## Receive events
39
+
40
+ ```js
41
+ eco.on("camera.*", (event) => {
42
+ console.log(event.type, event.data);
43
+ });
44
+ ```
45
+
46
+ `*` matches one namespace segment: `camera.*` matches `camera.motion` and
47
+ `camera.offline`. An event with an empty type matches nothing, so a malformed
48
+ publish from one service cannot fan out to every subscriber.
49
+
50
+ ## Configuration
51
+
52
+ The registry URL and shared secret resolve the same way as every other
53
+ ecosystem service — from the environment, falling back to the file-backed store
54
+ at `~/.config/ecosystem/secret.env`.
55
+
56
+ ## License
57
+
58
+ MIT — see [LICENSE](./LICENSE).
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@smartindustriesllc/ecosystem-client",
3
+ "version": "0.1.0",
4
+ "description": "Service registration, peer discovery and event bus client for the appEcosystem service mesh",
5
+ "main": "src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "scripts": {
15
+ "test": "node --test"
16
+ },
17
+ "keywords": [
18
+ "service-discovery",
19
+ "events",
20
+ "microservices",
21
+ "mdns",
22
+ "appecosystem"
23
+ ],
24
+ "author": "Mikel Smart",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/M1K31/appEcosystem.git",
29
+ "directory": "ecosystem_client_js"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/M1K31/appEcosystem/issues"
33
+ },
34
+ "homepage": "https://github.com/M1K31/appEcosystem#readme",
35
+ "engines": {
36
+ "node": ">=18"
37
+ },
38
+ "dependencies": {
39
+ "@smartindustriesllc/ecosystem-auth": "^0.1.0"
40
+ },
41
+ "optionalDependencies": {
42
+ "bonjour-service": "^1.4.4"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Client for the shared ecosystem AI profile (JS mirror of Python's
3
+ * AIProfileClient). Reads the ecosystem-wide LLM selection from the registry
4
+ * and can write changes back, so a selection made in any app appears here too.
5
+ * Requests are signed with the replay-resistant v0.3.0 scheme. Best-effort:
6
+ * returns null when the registry is unreachable so the UI degrades gracefully.
7
+ */
8
+
9
+ const { signRequest } = require("@smartindustriesllc/ecosystem-auth");
10
+
11
+ class AIProfileClient {
12
+ /**
13
+ * @param {string} registryUrl
14
+ * @param {{serviceName?: string, secret?: string, timeout?: number}} [opts]
15
+ */
16
+ constructor(registryUrl, opts = {}) {
17
+ this.registryUrl = (registryUrl || "http://localhost:8500").replace(/\/+$/, "");
18
+ this.serviceName = opts.serviceName || "";
19
+ this.secret = opts.secret || process.env.ECOSYSTEM_HMAC_SECRET || "";
20
+ this.timeout = opts.timeout || 5000;
21
+ }
22
+
23
+ _headers(method, url, body) {
24
+ if (!this.secret) return {};
25
+ return signRequest(method, url, this.secret, body);
26
+ }
27
+
28
+ /** Fetch the shared profile, or null if unreachable. */
29
+ async fetch() {
30
+ const url = `${this.registryUrl}/ai-profile`;
31
+ try {
32
+ const resp = await fetch(url, {
33
+ method: "GET",
34
+ headers: this._headers("GET", url, null),
35
+ signal: AbortSignal.timeout(this.timeout),
36
+ });
37
+ if (!resp.ok) return null;
38
+ return await resp.json();
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /** Return just the ecosystem-wide selected model (or null). */
45
+ async selectedModel() {
46
+ const profile = await this.fetch();
47
+ return profile ? profile.selected_model : null;
48
+ }
49
+
50
+ /** Write changes to the shared profile (propagates to all apps). */
51
+ async update(changes) {
52
+ const url = `${this.registryUrl}/ai-profile`;
53
+ try {
54
+ const resp = await fetch(url, {
55
+ method: "PUT",
56
+ headers: Object.assign(
57
+ { "Content-Type": "application/json" },
58
+ this._headers("PUT", url, changes)
59
+ ),
60
+ body: JSON.stringify(changes),
61
+ signal: AbortSignal.timeout(this.timeout),
62
+ });
63
+ if (!resp.ok) return null;
64
+ return await resp.json();
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+ }
70
+
71
+ module.exports = { AIProfileClient };
package/src/config.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Configuration for the ecosystem client.
3
+ * Mirrors Python ecosystem_client.config.
4
+ */
5
+
6
+ const { resolveSecret } = require("./secret");
7
+
8
+ class EcosystemConfig {
9
+ constructor(opts = {}) {
10
+ this.registryUrl = opts.registryUrl || process.env.ECOSYSTEM_REGISTRY_URL || "http://localhost:8500";
11
+ // Fail-closed, file-backed: explicit override -> ECOSYSTEM_HMAC_SECRET env
12
+ // -> ~/.config/ecosystem/secret.env. Never the committed dev default (the
13
+ // registry rejects it), so an unprovisioned client gets "" and is refused
14
+ // rather than silently signing with a forgeable key.
15
+ this.hmacSecret = resolveSecret(opts.hmacSecret);
16
+ this.serviceName = opts.serviceName || process.env.ECOSYSTEM_SERVICE_NAME || null;
17
+ this.servicePort = opts.servicePort || parseInt(process.env.ECOSYSTEM_SERVICE_PORT || "0") || null;
18
+ this.healthEndpoint = opts.healthEndpoint || process.env.ECOSYSTEM_HEALTH_ENDPOINT || "/health";
19
+ this.webhookPath = opts.webhookPath || "/ecosystem/events";
20
+ this.enabled = opts.enabled !== undefined ? opts.enabled : (process.env.ECOSYSTEM_ENABLED || "true").toLowerCase() !== "false";
21
+ this.discoveryInterval = opts.discoveryInterval || parseInt(process.env.ECOSYSTEM_DISCOVERY_INTERVAL || "60");
22
+ this.requestTimeout = opts.requestTimeout || 5000;
23
+ this.eventRetryAttempts = opts.eventRetryAttempts || 3;
24
+ this.eventRetryDelay = opts.eventRetryDelay || 5000;
25
+ this.peers = opts.peers || this._parsePeersEnv();
26
+ }
27
+
28
+ _parsePeersEnv() {
29
+ const peersStr = process.env.ECOSYSTEM_PEERS || "";
30
+ if (!peersStr) return {};
31
+ const peers = {};
32
+ for (const pair of peersStr.split(",")) {
33
+ const [name, url] = pair.trim().split("=");
34
+ if (name && url) peers[name.trim()] = url.trim();
35
+ }
36
+ return peers;
37
+ }
38
+ }
39
+
40
+ module.exports = { EcosystemConfig };
@@ -0,0 +1,184 @@
1
+ const http = require("http");
2
+ const https = require("https");
3
+
4
+ const DiscoveryMode = {
5
+ REGISTRY: "registry",
6
+ PEER_TO_PEER: "peer_to_peer",
7
+ STANDALONE: "standalone",
8
+ };
9
+
10
+ class DiscoveryManager {
11
+ constructor(config) {
12
+ this.config = config;
13
+ this.mode = DiscoveryMode.STANDALONE;
14
+ this._peers = {};
15
+ this._mdnsPeers = [];
16
+ }
17
+
18
+ async detectMode() {
19
+ if (!this.config.enabled) {
20
+ this.mode = DiscoveryMode.STANDALONE;
21
+ return this.mode;
22
+ }
23
+
24
+ if (await this._checkRegistry()) {
25
+ this.mode = DiscoveryMode.REGISTRY;
26
+ return this.mode;
27
+ }
28
+
29
+ const mdnsPeers = this._checkMdns();
30
+ if (mdnsPeers.length > 0) {
31
+ this._mdnsPeers = mdnsPeers;
32
+ this.mode = DiscoveryMode.PEER_TO_PEER;
33
+ return this.mode;
34
+ }
35
+
36
+ if (Object.keys(this.config.peers).length > 0) {
37
+ this.mode = DiscoveryMode.PEER_TO_PEER;
38
+ return this.mode;
39
+ }
40
+
41
+ this.mode = DiscoveryMode.STANDALONE;
42
+ return this.mode;
43
+ }
44
+
45
+ async getPeers() {
46
+ if (this.mode === DiscoveryMode.REGISTRY) {
47
+ return await this._fetchRegistryServices();
48
+ }
49
+ if (this.mode === DiscoveryMode.PEER_TO_PEER) {
50
+ const peers = {};
51
+ for (const [name, url] of Object.entries(this.config.peers)) {
52
+ peers[name] = { name, base_url: url };
53
+ }
54
+ return peers;
55
+ }
56
+ return {};
57
+ }
58
+
59
+ async registerSelf(name, host, port, healthEndpoint, webhookUrl, subscriptions) {
60
+ if (this.mode !== DiscoveryMode.REGISTRY) return false;
61
+ try {
62
+ const dataObj = {
63
+ name, host, port,
64
+ health_endpoint: healthEndpoint,
65
+ webhook_url: webhookUrl,
66
+ subscriptions: subscriptions || [],
67
+ };
68
+ const payload = JSON.stringify(dataObj);
69
+ const { signRequest } = require("@smartindustriesllc/ecosystem-auth");
70
+ const registerUrl = `${this.config.registryUrl}/register`;
71
+ const headers = signRequest("POST", registerUrl, this.config.hmacSecret, dataObj);
72
+ await this._post(registerUrl, payload, headers);
73
+ return true;
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+
79
+ async deregisterSelf(name) {
80
+ if (this.mode !== DiscoveryMode.REGISTRY) return false;
81
+ try {
82
+ const url = `${this.config.registryUrl}/deregister/${name}`;
83
+ const { signRequest } = require("@smartindustriesllc/ecosystem-auth");
84
+ const headers = signRequest("DELETE", url, this.config.hmacSecret);
85
+ await this._delete(url, headers);
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ async _checkRegistry() {
93
+ try {
94
+ await this._get(`${this.config.registryUrl}/health`);
95
+ return true;
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+
101
+ _checkMdns() {
102
+ try {
103
+ const { Bonjour } = require("bonjour-service");
104
+ // Synchronous browse not practical; return empty for now
105
+ } catch { /* not installed */ }
106
+ return [];
107
+ }
108
+
109
+ async _fetchRegistryServices() {
110
+ try {
111
+ const data = await this._get(`${this.config.registryUrl}/services`);
112
+ const peers = {};
113
+ for (const svc of data) {
114
+ peers[svc.name] = svc;
115
+ }
116
+ return peers;
117
+ } catch {
118
+ return {};
119
+ }
120
+ }
121
+
122
+ _get(url) {
123
+ return new Promise((resolve, reject) => {
124
+ const lib = url.startsWith("https") ? https : http;
125
+ const req = lib.get(url, { timeout: this.config.requestTimeout }, (res) => {
126
+ let body = "";
127
+ res.on("data", (chunk) => body += chunk);
128
+ res.on("end", () => {
129
+ if (res.statusCode >= 400) return reject(new Error(`HTTP ${res.statusCode}`));
130
+ try { resolve(JSON.parse(body)); } catch { resolve(body); }
131
+ });
132
+ });
133
+ req.on("error", reject);
134
+ req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
135
+ });
136
+ }
137
+
138
+ _post(url, body, customHeaders = {}) {
139
+ return new Promise((resolve, reject) => {
140
+ const parsed = new URL(url);
141
+ const lib = parsed.protocol === "https:" ? https : http;
142
+ const headers = Object.assign({
143
+ "Content-Type": "application/json",
144
+ "Content-Length": Buffer.byteLength(body)
145
+ }, customHeaders);
146
+ const req = lib.request({
147
+ hostname: parsed.hostname, port: parsed.port, path: parsed.pathname,
148
+ method: "POST", headers,
149
+ timeout: this.config.requestTimeout,
150
+ }, (res) => {
151
+ let data = "";
152
+ res.on("data", (chunk) => data += chunk);
153
+ res.on("end", () => {
154
+ if (res.statusCode >= 400) return reject(new Error(`HTTP ${res.statusCode}`));
155
+ try { resolve(JSON.parse(data)); } catch { resolve(data); }
156
+ });
157
+ });
158
+ req.on("error", reject);
159
+ req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
160
+ req.write(body);
161
+ req.end();
162
+ });
163
+ }
164
+
165
+ _delete(url, customHeaders = {}) {
166
+ return new Promise((resolve, reject) => {
167
+ const parsed = new URL(url);
168
+ const lib = parsed.protocol === "https:" ? https : http;
169
+ const req = lib.request({
170
+ hostname: parsed.hostname, port: parsed.port, path: parsed.pathname,
171
+ method: "DELETE", headers: customHeaders, timeout: this.config.requestTimeout,
172
+ }, (res) => {
173
+ let data = "";
174
+ res.on("data", (chunk) => data += chunk);
175
+ res.on("end", () => resolve(data));
176
+ });
177
+ req.on("error", reject);
178
+ req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
179
+ req.end();
180
+ });
181
+ }
182
+ }
183
+
184
+ module.exports = { DiscoveryManager, DiscoveryMode };
package/src/events.js ADDED
@@ -0,0 +1,118 @@
1
+ const { signPayload, verifySignature } = require("@smartindustriesllc/ecosystem-auth");
2
+ const crypto = require("crypto");
3
+ const http = require("http");
4
+ const https = require("https");
5
+
6
+ class EventPublisher {
7
+ constructor(config, mode, serviceName) {
8
+ this.config = config;
9
+ this.mode = mode;
10
+ this.serviceName = serviceName;
11
+ this._peerWebhooks = {};
12
+ }
13
+
14
+ setPeerWebhooks(webhooks) { this._peerWebhooks = webhooks; }
15
+
16
+ async publish(eventType, data) {
17
+ if (this.mode === "standalone") {
18
+ return { delivered: 0, failed: 0, mode: "standalone" };
19
+ }
20
+ const envelope = this._buildEnvelope(eventType, data);
21
+ const matching = this._getMatchingPeers(eventType);
22
+ let delivered = 0;
23
+ for (const [name, info] of Object.entries(matching)) {
24
+ try {
25
+ await this._deliverToPeer(envelope, info.webhook_url);
26
+ delivered++;
27
+ } catch { /* failed delivery */ }
28
+ }
29
+ return { delivered, failed: Object.keys(matching).length - delivered, subscribers: Object.keys(matching) };
30
+ }
31
+
32
+ _buildEnvelope(eventType, data) {
33
+ const envelope = {
34
+ id: crypto.randomUUID(),
35
+ type: eventType,
36
+ source: this.serviceName,
37
+ timestamp: Date.now() / 1000,
38
+ data,
39
+ };
40
+ const signable = { id: envelope.id, type: envelope.type, source: envelope.source, timestamp: envelope.timestamp, data: envelope.data };
41
+ envelope.signature = signPayload(signable, this.config.hmacSecret);
42
+ return envelope;
43
+ }
44
+
45
+ _getMatchingPeers(eventType) {
46
+ const matching = {};
47
+ for (const [name, info] of Object.entries(this._peerWebhooks)) {
48
+ for (const pattern of (info.subscriptions || [])) {
49
+ if (pattern === "*" || (pattern.endsWith(".*") && eventType.startsWith(pattern.slice(0, -2) + ".")) || pattern === eventType) {
50
+ matching[name] = info;
51
+ break;
52
+ }
53
+ }
54
+ }
55
+ return matching;
56
+ }
57
+
58
+ async _deliverToPeer(envelope, webhookUrl) {
59
+ const body = JSON.stringify(envelope);
60
+ return new Promise((resolve, reject) => {
61
+ const parsed = new URL(webhookUrl);
62
+ const lib = parsed.protocol === "https:" ? https : http;
63
+ const req = lib.request({
64
+ hostname: parsed.hostname, port: parsed.port, path: parsed.pathname,
65
+ method: "POST",
66
+ headers: {
67
+ "Content-Type": "application/json",
68
+ "Content-Length": Buffer.byteLength(body),
69
+ "X-Ecosystem-Signature": envelope.signature,
70
+ "X-Ecosystem-Event": envelope.type,
71
+ "X-Ecosystem-Source": envelope.source,
72
+ },
73
+ timeout: this.config.requestTimeout,
74
+ }, (res) => {
75
+ res.resume();
76
+ res.on("end", () => res.statusCode < 400 ? resolve() : reject(new Error(`HTTP ${res.statusCode}`)));
77
+ });
78
+ req.on("error", reject);
79
+ req.write(body);
80
+ req.end();
81
+ });
82
+ }
83
+ }
84
+
85
+ class EventSubscriber {
86
+ constructor(hmacSecret) {
87
+ this._hmacSecret = hmacSecret;
88
+ this._handlers = {};
89
+ }
90
+
91
+ on(eventPattern, handler) {
92
+ if (!this._handlers[eventPattern]) this._handlers[eventPattern] = [];
93
+ this._handlers[eventPattern].push(handler);
94
+ }
95
+
96
+ async dispatch(envelope) {
97
+ const signable = { id: envelope.id, type: envelope.type, source: envelope.source, timestamp: envelope.timestamp, data: envelope.data };
98
+ if (!verifySignature(signable, envelope.signature || "", this._hmacSecret)) return;
99
+
100
+ for (const [pattern, handlers] of Object.entries(this._handlers)) {
101
+ if (this._matches(envelope.type, pattern)) {
102
+ for (const handler of handlers) {
103
+ try { await handler(envelope); } catch (e) { console.error(`Handler error: ${e}`); }
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ _matches(eventType, pattern) {
110
+ if (pattern === "*") return true;
111
+ if (pattern.endsWith(".*")) return eventType.startsWith(pattern.slice(0, -2) + ".");
112
+ return eventType === pattern;
113
+ }
114
+
115
+ get subscriptions() { return Object.keys(this._handlers); }
116
+ }
117
+
118
+ module.exports = { EventPublisher, EventSubscriber };
package/src/index.js ADDED
@@ -0,0 +1,99 @@
1
+ const { EcosystemConfig } = require("./config");
2
+ const { DiscoveryManager, DiscoveryMode } = require("./discovery");
3
+ const { EventPublisher, EventSubscriber } = require("./events");
4
+ const { Peer } = require("./peer");
5
+ const os = require("os");
6
+
7
+ class EcosystemClient {
8
+ constructor(opts = {}) {
9
+ this.config = new EcosystemConfig(opts);
10
+ this.config.serviceName = opts.serviceName || this.config.serviceName;
11
+ this.config.servicePort = opts.servicePort || this.config.servicePort;
12
+ this.config.healthEndpoint = opts.healthEndpoint || this.config.healthEndpoint;
13
+
14
+ this._serviceName = this.config.serviceName;
15
+ this._servicePort = this.config.servicePort;
16
+ this._healthEndpoint = this.config.healthEndpoint;
17
+ this._subscriptions = opts.subscriptions || [];
18
+
19
+ this._discovery = new DiscoveryManager(this.config);
20
+ this._publisher = new EventPublisher(this.config, DiscoveryMode.STANDALONE, this._serviceName);
21
+ this._subscriber = new EventSubscriber(this.config.hmacSecret);
22
+ this._peers = {};
23
+ this._peerObjects = {};
24
+ this._started = false;
25
+ this._refreshInterval = null;
26
+ }
27
+
28
+ get mode() { return this._discovery.mode; }
29
+
30
+ async start() {
31
+ if (this._started) return;
32
+ const mode = await this._discovery.detectMode();
33
+ this._publisher.mode = mode;
34
+
35
+ if (mode === DiscoveryMode.REGISTRY) {
36
+ const host = this._getLocalIp();
37
+ const webhookUrl = `http://${host}:${this._servicePort}${this.config.webhookPath}`;
38
+ await this._discovery.registerSelf(
39
+ this._serviceName, host, this._servicePort,
40
+ this._healthEndpoint, webhookUrl, this._subscriptions
41
+ );
42
+ }
43
+
44
+ await this._refreshPeers();
45
+ this._started = true;
46
+
47
+ this._refreshInterval = setInterval(() => this._refreshPeers().catch(() => {}), this.config.discoveryInterval * 1000);
48
+ }
49
+
50
+ async stop() {
51
+ if (this._refreshInterval) clearInterval(this._refreshInterval);
52
+ if (this._discovery.mode === DiscoveryMode.REGISTRY) {
53
+ await this._discovery.deregisterSelf(this._serviceName);
54
+ }
55
+ this._started = false;
56
+ }
57
+
58
+ async discover(serviceName) {
59
+ if (this._peerObjects[serviceName] && !this._peerObjects[serviceName].isDegraded) {
60
+ return this._peerObjects[serviceName];
61
+ }
62
+ const info = this._peers[serviceName];
63
+ if (info && info.base_url) {
64
+ const peer = new Peer(serviceName, info.base_url, this.config.hmacSecret, this.config.requestTimeout);
65
+ this._peerObjects[serviceName] = peer;
66
+ return peer;
67
+ }
68
+ return null;
69
+ }
70
+
71
+ async publish(eventType, data) {
72
+ return this._publisher.publish(eventType, data);
73
+ }
74
+
75
+ on(eventPattern, handler) {
76
+ this._subscriber.on(eventPattern, handler);
77
+ if (!this._subscriptions.includes(eventPattern)) this._subscriptions.push(eventPattern);
78
+ }
79
+
80
+ async handleWebhook(envelope) {
81
+ await this._subscriber.dispatch(envelope);
82
+ }
83
+
84
+ async _refreshPeers() {
85
+ this._peers = await this._discovery.getPeers();
86
+ }
87
+
88
+ _getLocalIp() {
89
+ const nets = os.networkInterfaces();
90
+ for (const name of Object.keys(nets)) {
91
+ for (const net of nets[name]) {
92
+ if (net.family === "IPv4" && !net.internal) return net.address;
93
+ }
94
+ }
95
+ return "127.0.0.1";
96
+ }
97
+ }
98
+
99
+ module.exports = { EcosystemClient, DiscoveryMode };
package/src/peer.js ADDED
@@ -0,0 +1,67 @@
1
+ const http = require("http");
2
+ const https = require("https");
3
+ const { createEcosystemToken } = require("@smartindustriesllc/ecosystem-auth");
4
+
5
+ class Peer {
6
+ constructor(name, baseUrl, hmacSecret, timeout = 5000) {
7
+ this.name = name;
8
+ this.baseUrl = baseUrl.replace(/\/$/, "");
9
+ this._hmacSecret = hmacSecret;
10
+ this._timeout = timeout;
11
+ this._degraded = false;
12
+ }
13
+
14
+ get isDegraded() { return this._degraded; }
15
+ markDegraded() { this._degraded = true; }
16
+ markHealthy() { this._degraded = false; }
17
+
18
+ async get(path) { return this._request("GET", path); }
19
+ async post(path, body) { return this._request("POST", path, body); }
20
+
21
+ async _request(method, path, body = null) {
22
+ const url = `${this.baseUrl}${path}`;
23
+ const token = createEcosystemToken(this._hmacSecret, this.name);
24
+ const headers = {
25
+ "Authorization": `Bearer ${JSON.stringify(token)}`,
26
+ "X-Ecosystem-Source": this.name,
27
+ };
28
+ if (body) headers["Content-Type"] = "application/json";
29
+
30
+ try {
31
+ const result = await this._httpRequest(method, url, headers, body);
32
+ this.markHealthy();
33
+ return result;
34
+ } catch (e) {
35
+ this.markDegraded();
36
+ return null;
37
+ }
38
+ }
39
+
40
+ _httpRequest(method, url, headers, body) {
41
+ return new Promise((resolve, reject) => {
42
+ const parsed = new URL(url);
43
+ const lib = parsed.protocol === "https:" ? https : http;
44
+ const bodyStr = body ? JSON.stringify(body) : null;
45
+ if (bodyStr) headers["Content-Length"] = Buffer.byteLength(bodyStr);
46
+
47
+ const req = lib.request({
48
+ hostname: parsed.hostname, port: parsed.port,
49
+ path: parsed.pathname + parsed.search,
50
+ method, headers, timeout: this._timeout,
51
+ }, (res) => {
52
+ let data = "";
53
+ res.on("data", (chunk) => data += chunk);
54
+ res.on("end", () => {
55
+ if (res.statusCode >= 400) return reject(new Error(`HTTP ${res.statusCode}`));
56
+ try { resolve(JSON.parse(data)); } catch { resolve(data); }
57
+ });
58
+ });
59
+ req.on("error", reject);
60
+ req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
61
+ if (bodyStr) req.write(bodyStr);
62
+ req.end();
63
+ });
64
+ }
65
+ }
66
+
67
+ module.exports = { Peer };
package/src/secret.js ADDED
@@ -0,0 +1,55 @@
1
+ /* Shared-secret resolution — JS mirror of Python ecosystem_auth.tokens.
2
+ *
3
+ * All ecosystem apps read one file-backed secret (~/.config/ecosystem/secret.env)
4
+ * so a single `ecosystem secret import` (or the in-app setup panel) provisions
5
+ * every service on the host — MagicMirror included. Resolution order:
6
+ * explicit override -> ECOSYSTEM_HMAC_SECRET env -> secret file
7
+ * Fail-closed: there is NO default. If none is found, the empty string is
8
+ * returned (peers requiring a real secret reject unsigned requests), rather than
9
+ * trusting the known development default.
10
+ */
11
+ const fs = require("fs");
12
+ const os = require("os");
13
+ const path = require("path");
14
+
15
+ const DEFAULT_DEV_SECRET = "dev-ecosystem-secret-change-in-production";
16
+
17
+ function secretFilePath() {
18
+ return (
19
+ process.env.ECOSYSTEM_SECRET_FILE ||
20
+ path.join(os.homedir(), ".config", "ecosystem", "secret.env")
21
+ );
22
+ }
23
+
24
+ function readSecretFile() {
25
+ try {
26
+ const p = secretFilePath();
27
+ if (!fs.existsSync(p)) return null;
28
+ for (let line of fs.readFileSync(p, "utf8").split(/\r?\n/)) {
29
+ line = line.trim();
30
+ if (!line || line.startsWith("#")) continue;
31
+ if (line.startsWith("export ")) line = line.slice("export ".length);
32
+ if (line.startsWith("ECOSYSTEM_HMAC_SECRET=")) {
33
+ const val = line.slice("ECOSYSTEM_HMAC_SECRET=".length).trim()
34
+ .replace(/^["']|["']$/g, "");
35
+ return val || null;
36
+ }
37
+ }
38
+ } catch (e) {
39
+ return null;
40
+ }
41
+ return null;
42
+ }
43
+
44
+ /**
45
+ * Resolve the shared secret fail-closed. Never returns the dev default; returns
46
+ * "" when nothing is configured so callers/peers fail safely.
47
+ */
48
+ function resolveSecret(override) {
49
+ const secret =
50
+ override || process.env.ECOSYSTEM_HMAC_SECRET || readSecretFile() || "";
51
+ if (secret === DEFAULT_DEV_SECRET) return "";
52
+ return secret;
53
+ }
54
+
55
+ module.exports = { DEFAULT_DEV_SECRET, secretFilePath, readSecretFile, resolveSecret };