@smartindustriesllc/ecosystem-client 0.1.0 → 0.1.1

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/src/hub.js ADDED
@@ -0,0 +1,322 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Node.js HubClient for MagicMirror-Custom and JS services:
5
+ * joins an existing appEcosystem Hub (or operates standalone when offline),
6
+ * registers/resolves capability manifests, and publishes deduplicated
7
+ * `notify.*` envelopes with a local file-backed offline outbox.
8
+ */
9
+ const fs = require("fs");
10
+ const os = require("os");
11
+ const path = require("path");
12
+ const { signRequest } = require("./_auth");
13
+ const { assertValidSchema, buildNotificationEnvelope } = require("./contracts");
14
+ const { resolveDeviceId } = require("./ulid");
15
+
16
+ function defaultJsOutboxPath(appName) {
17
+ const safe = String(appName || "js-app").replace(/[^A-Za-z0-9_-]/g, "_");
18
+ const base =
19
+ process.env.ECOSYSTEM_OUTBOX_DIR ||
20
+ path.join(os.homedir(), ".local", "share", "ecosystem");
21
+ return path.join(base, `outbox-${safe}.json`);
22
+ }
23
+
24
+ class HubClient {
25
+ constructor(appName, opts = {}) {
26
+ this.appName = appName;
27
+ this.deviceId = opts.deviceId || resolveDeviceId();
28
+ this.registryUrl = (opts.registryUrl || process.env.ECOSYSTEM_REGISTRY_URL || "http://localhost:8500").replace(/\/+$/, "");
29
+ this.secret = opts.secret !== undefined ? opts.secret : (process.env.ECOSYSTEM_HMAC_SECRET || "");
30
+ this.role = String(opts.role || process.env.ECOSYSTEM_HUB_ROLE || "join").toLowerCase();
31
+ this.timeout = opts.timeout || 5000;
32
+ this.outboxPath = opts.outboxPath || defaultJsOutboxPath(appName);
33
+ this.maxOutboxItems = opts.maxOutboxItems || 250;
34
+
35
+ this._capabilities = new Map();
36
+ for (const cap of opts.capabilities || []) {
37
+ this._storeLocalCapability(cap);
38
+ }
39
+ this._joined = false;
40
+ }
41
+
42
+ get isJoined() {
43
+ return this._joined;
44
+ }
45
+
46
+ _headers(method, url, body = null) {
47
+ const base = body !== null ? { "Content-Type": "application/json" } : {};
48
+ if (!this.secret) return base;
49
+ return Object.assign(base, signRequest(method, url, this.secret, body));
50
+ }
51
+
52
+ _normalizeManifest(partial) {
53
+ const m = Object.assign({ schema_version: 1 }, partial);
54
+ if (!m.provider) {
55
+ m.provider = { app: this.appName, device_id: this.deviceId };
56
+ }
57
+ assertValidSchema(m, "capability-manifest.v1");
58
+ return m;
59
+ }
60
+
61
+ _storeLocalCapability(partial) {
62
+ const m = this._normalizeManifest(partial);
63
+ this._capabilities.set(m.capability, m);
64
+ return m;
65
+ }
66
+
67
+ async checkHealth() {
68
+ if (this.role === "off") return false;
69
+ try {
70
+ const resp = await fetch(`${this.registryUrl}/health`, {
71
+ method: "GET",
72
+ signal: AbortSignal.timeout(this.timeout),
73
+ });
74
+ return Boolean(resp && resp.ok);
75
+ } catch {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ async start() {
81
+ if (this.role === "off") {
82
+ this._joined = false;
83
+ return "standalone";
84
+ }
85
+ const ok = await this.checkHealth();
86
+ if (!ok) {
87
+ this._joined = false;
88
+ return "standalone";
89
+ }
90
+ this._joined = true;
91
+ await this.syncCapabilities();
92
+ await this.flushOutbox();
93
+ return "joined";
94
+ }
95
+
96
+ async stop() {
97
+ if (this._joined) {
98
+ const url = `${this.registryUrl}/capabilities/${encodeURIComponent(this.appName)}`;
99
+ try {
100
+ await fetch(url, {
101
+ method: "DELETE",
102
+ headers: this._headers("DELETE", url, null),
103
+ signal: AbortSignal.timeout(2500),
104
+ });
105
+ } catch {
106
+ // Best-effort withdrawal
107
+ }
108
+ }
109
+ this._joined = false;
110
+ }
111
+
112
+ async getPolicyState() {
113
+ if (!this._joined) return null;
114
+ try {
115
+ const url = `${this.registryUrl}/policy/state`;
116
+ const resp = await fetch(url, {
117
+ method: "GET",
118
+ headers: this._headers("GET", url, null),
119
+ signal: AbortSignal.timeout(this.timeout),
120
+ });
121
+ if (resp && resp.ok) {
122
+ return await resp.json();
123
+ }
124
+ } catch {
125
+ return null;
126
+ }
127
+ return null;
128
+ }
129
+
130
+ async requestFreeze(reason = "Emergency freeze", channel = "js_client") {
131
+ const payload = {
132
+ initiated_by: `${this.appName}/${this.deviceId}`,
133
+ channel: channel,
134
+ reason: reason,
135
+ };
136
+ if (!this._joined) return null;
137
+ try {
138
+ const url = `${this.registryUrl}/policy/freeze`;
139
+ const resp = await fetch(url, {
140
+ method: "POST",
141
+ headers: this._headers("POST", url, payload),
142
+ body: JSON.stringify(payload),
143
+ signal: AbortSignal.timeout(this.timeout),
144
+ });
145
+ if (resp && resp.ok) {
146
+ return await resp.json();
147
+ }
148
+ } catch {
149
+ return null;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ async registerCapability(partial) {
155
+ const manifest = this._storeLocalCapability(partial);
156
+ if (this._joined) {
157
+ await this.syncCapabilities();
158
+ }
159
+ return manifest;
160
+ }
161
+
162
+ async syncCapabilities() {
163
+ const list = [...this._capabilities.values()];
164
+ if (list.length === 0) return true;
165
+ const url = `${this.registryUrl}/capabilities/register`;
166
+ const body = { capabilities: list };
167
+ try {
168
+ const resp = await fetch(url, {
169
+ method: "POST",
170
+ headers: this._headers("POST", url, body),
171
+ body: JSON.stringify(body),
172
+ signal: AbortSignal.timeout(this.timeout),
173
+ });
174
+ return Boolean(resp && resp.ok);
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+
180
+ async resolveCapability(capabilityName) {
181
+ if (this._joined) {
182
+ const url = `${this.registryUrl}/capabilities?capability=${encodeURIComponent(capabilityName)}&resolve=true`;
183
+ try {
184
+ const resp = await fetch(url, {
185
+ method: "GET",
186
+ headers: this._headers("GET", url, null),
187
+ signal: AbortSignal.timeout(this.timeout),
188
+ });
189
+ if (resp && resp.ok) {
190
+ return await resp.json();
191
+ }
192
+ } catch {
193
+ // Fall back to local capabilities
194
+ }
195
+ }
196
+ if (this._capabilities.has(capabilityName)) {
197
+ const m = this._capabilities.get(capabilityName);
198
+ return {
199
+ capability: capabilityName,
200
+ available: true,
201
+ providers: [{ capability: capabilityName, app: this.appName, device_id: this.deviceId, manifest: m }],
202
+ unavailable_reason: null,
203
+ };
204
+ }
205
+ return {
206
+ capability: capabilityName,
207
+ available: false,
208
+ providers: [],
209
+ unavailable_reason: `Hub unreachable and capability '${capabilityName}' is not hosted locally`,
210
+ };
211
+ }
212
+
213
+ _readOutbox() {
214
+ try {
215
+ if (!fs.existsSync(this.outboxPath)) return [];
216
+ const parsed = JSON.parse(fs.readFileSync(this.outboxPath, "utf8"));
217
+ return Array.isArray(parsed) ? parsed : [];
218
+ } catch {
219
+ return [];
220
+ }
221
+ }
222
+
223
+ _writeOutbox(items) {
224
+ fs.mkdirSync(path.dirname(this.outboxPath), { recursive: true });
225
+ const bounded = items.slice(-this.maxOutboxItems);
226
+ fs.writeFileSync(this.outboxPath, JSON.stringify(bounded, null, 2), { mode: 0o600 });
227
+ }
228
+
229
+ _enqueueOffline(envelope) {
230
+ const items = this._readOutbox();
231
+ if (items.some((e) => e.dedupe_key === envelope.dedupe_key)) {
232
+ return false;
233
+ }
234
+ items.push(envelope);
235
+ this._writeOutbox(items);
236
+ return true;
237
+ }
238
+
239
+ async _sendNotification(envelope) {
240
+ const url = `${this.registryUrl}/notifications/publish`;
241
+ const resp = await fetch(url, {
242
+ method: "POST",
243
+ headers: this._headers("POST", url, envelope),
244
+ body: JSON.stringify(envelope),
245
+ signal: AbortSignal.timeout(this.timeout),
246
+ });
247
+ return Boolean(resp && resp.ok);
248
+ }
249
+
250
+ async notify(notifyType, severity, title, body, opts = {}) {
251
+ const envelope = buildNotificationEnvelope(
252
+ notifyType,
253
+ this.appName,
254
+ severity,
255
+ title,
256
+ body,
257
+ Object.assign({ deviceId: this.deviceId, secret: this.secret || undefined }, opts)
258
+ );
259
+ if (this._joined) {
260
+ try {
261
+ if (await this._sendNotification(envelope)) {
262
+ return { status: "delivered", id: envelope.id };
263
+ }
264
+ } catch {
265
+ // Fall through to offline outbox
266
+ }
267
+ }
268
+ const added = this._enqueueOffline(envelope);
269
+ return {
270
+ status: added ? "queued_offline" : "deduplicated_offline",
271
+ id: envelope.id,
272
+ };
273
+ }
274
+
275
+ async flushOutbox() {
276
+ const items = this._readOutbox();
277
+ if (items.length === 0) return { delivered: 0, remaining: 0 };
278
+ const remaining = [];
279
+ let delivered = 0;
280
+ let failed = false;
281
+ for (const env of items) {
282
+ if (failed) {
283
+ remaining.push(env);
284
+ continue;
285
+ }
286
+ try {
287
+ if (await this._sendNotification(env)) {
288
+ delivered += 1;
289
+ } else {
290
+ failed = true;
291
+ remaining.push(env);
292
+ }
293
+ } catch {
294
+ failed = true;
295
+ remaining.push(env);
296
+ }
297
+ }
298
+ this._writeOutbox(remaining);
299
+ return { delivered, remaining: remaining.length };
300
+ }
301
+
302
+ async fetchRecentNotifications(opts = {}) {
303
+ const limit = opts.limit || 25;
304
+ const minSeverity = opts.minSeverity ? `&min_severity=${encodeURIComponent(opts.minSeverity)}` : "";
305
+ const url = `${this.registryUrl}/notifications/recent?limit=${encodeURIComponent(limit)}${minSeverity}`;
306
+ try {
307
+ const resp = await fetch(url, {
308
+ method: "GET",
309
+ headers: this._headers("GET", url, null),
310
+ signal: AbortSignal.timeout(this.timeout),
311
+ });
312
+ if (!resp || !resp.ok) return [];
313
+ const data = await resp.json();
314
+ return Array.isArray(data.notifications) ? data.notifications : [];
315
+ } catch {
316
+ return [];
317
+ }
318
+ }
319
+ }
320
+
321
+ module.exports = { HubClient, defaultJsOutboxPath };
322
+
package/src/index.js CHANGED
@@ -1,7 +1,32 @@
1
+ "use strict";
2
+
1
3
  const { EcosystemConfig } = require("./config");
2
4
  const { DiscoveryManager, DiscoveryMode } = require("./discovery");
3
5
  const { EventPublisher, EventSubscriber } = require("./events");
4
6
  const { Peer } = require("./peer");
7
+ const { AIProfileClient } = require("./ai_profile");
8
+ const { HubClient, defaultJsOutboxPath } = require("./hub");
9
+ const {
10
+ generateUlid,
11
+ isUlid,
12
+ ulidTimestampMs,
13
+ resolveDeviceId,
14
+ } = require("./ulid");
15
+ const {
16
+ SchemaValidationError,
17
+ EventType,
18
+ listSchemas,
19
+ loadSchema,
20
+ validateAgainstSchema,
21
+ assertValidSchema,
22
+ canonicalSignableEvent,
23
+ buildEventEnvelopeV2,
24
+ verifyEventEnvelope,
25
+ canonicalSignableCommand,
26
+ buildCommandEnvelope,
27
+ verifyCommandEnvelope,
28
+ buildNotificationEnvelope,
29
+ } = require("./contracts");
5
30
  const os = require("os");
6
31
 
7
32
  class EcosystemClient {
@@ -68,8 +93,8 @@ class EcosystemClient {
68
93
  return null;
69
94
  }
70
95
 
71
- async publish(eventType, data) {
72
- return this._publisher.publish(eventType, data);
96
+ async publish(eventType, data, opts) {
97
+ return this._publisher.publish(eventType, data, opts);
73
98
  }
74
99
 
75
100
  on(eventPattern, handler) {
@@ -78,11 +103,24 @@ class EcosystemClient {
78
103
  }
79
104
 
80
105
  async handleWebhook(envelope) {
81
- await this._subscriber.dispatch(envelope);
106
+ return this._subscriber.dispatch(envelope);
82
107
  }
83
108
 
84
109
  async _refreshPeers() {
85
110
  this._peers = await this._discovery.getPeers();
111
+ if (this._discovery.mode === DiscoveryMode.PEER_TO_PEER) {
112
+ const webhooks = {};
113
+ for (const [name, info] of Object.entries(this._peers)) {
114
+ const baseUrl = (info && info.base_url) || "";
115
+ if (baseUrl) {
116
+ webhooks[name] = {
117
+ webhook_url: `${baseUrl.replace(/\/+$/, "")}${this.config.webhookPath}`,
118
+ subscriptions: info.subscriptions || ["*"],
119
+ };
120
+ }
121
+ }
122
+ this._publisher.setPeerWebhooks(webhooks);
123
+ }
86
124
  }
87
125
 
88
126
  _getLocalIp() {
@@ -96,4 +134,32 @@ class EcosystemClient {
96
134
  }
97
135
  }
98
136
 
99
- module.exports = { EcosystemClient, DiscoveryMode };
137
+ module.exports = {
138
+ EcosystemClient,
139
+ EcosystemConfig,
140
+ DiscoveryManager,
141
+ DiscoveryMode,
142
+ EventPublisher,
143
+ EventSubscriber,
144
+ Peer,
145
+ AIProfileClient,
146
+ HubClient,
147
+ defaultJsOutboxPath,
148
+ EventType,
149
+ SchemaValidationError,
150
+ generateUlid,
151
+ isUlid,
152
+ ulidTimestampMs,
153
+ resolveDeviceId,
154
+ listSchemas,
155
+ loadSchema,
156
+ validateAgainstSchema,
157
+ assertValidSchema,
158
+ canonicalSignableEvent,
159
+ buildEventEnvelopeV2,
160
+ verifyEventEnvelope,
161
+ canonicalSignableCommand,
162
+ buildCommandEnvelope,
163
+ verifyCommandEnvelope,
164
+ buildNotificationEnvelope,
165
+ };
package/src/peer.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const http = require("http");
2
2
  const https = require("https");
3
- const { createEcosystemToken } = require("@smartindustriesllc/ecosystem-auth");
3
+ const { createEcosystemToken } = require("./_auth");
4
4
 
5
5
  class Peer {
6
6
  constructor(name, baseUrl, hmacSecret, timeout = 5000) {
package/src/ulid.js ADDED
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Zero-dependency Crockford Base32 monotonic ULID generator and device ID helper.
5
+ * Mirrors Python ecosystem_client.ulid byte-for-byte.
6
+ */
7
+ const crypto = require("crypto");
8
+ const os = require("os");
9
+
10
+ const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
11
+ const CROCKFORD_MAP = Object.freeze(
12
+ Object.fromEntries([...CROCKFORD_ALPHABET].map((ch, idx) => [ch, idx]))
13
+ );
14
+ const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
15
+ const MAX_TIME_MS = (1n << 48n) - 1n;
16
+ const MAX_ENTROPY = (1n << 80n) - 1n;
17
+
18
+ let _lastMs = -1n;
19
+ let _lastEntropy = 0n;
20
+
21
+ function _encodeBase32(valueBigInt, length) {
22
+ const chars = new Array(length);
23
+ let v = valueBigInt;
24
+ for (let idx = length - 1; idx >= 0; idx -= 1) {
25
+ chars[idx] = CROCKFORD_ALPHABET[Number(v & 0x1fn)];
26
+ v >>= 5n;
27
+ }
28
+ return chars.join("");
29
+ }
30
+
31
+ function _randomEntropy80() {
32
+ const buf = crypto.randomBytes(10);
33
+ let val = 0n;
34
+ for (let i = 0; i < 10; i += 1) {
35
+ val = (val << 8n) | BigInt(buf[i]);
36
+ }
37
+ return val;
38
+ }
39
+
40
+ /**
41
+ * Generate a 26-character lexicographically sortable Crockford Base32 ULID.
42
+ * Monotonically increments the 80-bit random payload within the same millisecond.
43
+ * @param {number|bigint|null} [timestampMs]
44
+ * @returns {string}
45
+ */
46
+ function generateUlid(timestampMs = null) {
47
+ let nowMs = timestampMs == null ? BigInt(Date.now()) : BigInt(Math.trunc(Number(timestampMs)));
48
+ if (nowMs < 0n || nowMs > MAX_TIME_MS) {
49
+ throw new RangeError(`ULID timestampMs out of 48-bit range: ${nowMs}`);
50
+ }
51
+
52
+ let entropy;
53
+ if (timestampMs == null && nowMs === _lastMs) {
54
+ entropy = _lastEntropy + 1n;
55
+ if (entropy > MAX_ENTROPY) {
56
+ nowMs += 1n;
57
+ entropy = _randomEntropy80();
58
+ }
59
+ } else {
60
+ entropy = _randomEntropy80();
61
+ }
62
+ _lastMs = nowMs;
63
+ _lastEntropy = entropy;
64
+
65
+ return _encodeBase32(nowMs, 10) + _encodeBase32(entropy, 16);
66
+ }
67
+
68
+ /**
69
+ * Return true if value is a canonical 26-char uppercase Crockford Base32 ULID.
70
+ * @param {*} value
71
+ * @returns {boolean}
72
+ */
73
+ function isUlid(value) {
74
+ if (typeof value !== "string" || !ULID_RE.test(value)) {
75
+ return false;
76
+ }
77
+ return CROCKFORD_MAP[value[0]] <= 7;
78
+ }
79
+
80
+ /**
81
+ * Extract the 48-bit Unix millisecond timestamp from a valid ULID.
82
+ * @param {string} ulidStr
83
+ * @returns {number}
84
+ */
85
+ function ulidTimestampMs(ulidStr) {
86
+ if (!isUlid(ulidStr)) {
87
+ throw new Error(`Invalid ULID: ${JSON.stringify(ulidStr)}`);
88
+ }
89
+ let ts = 0n;
90
+ for (let i = 0; i < 10; i += 1) {
91
+ ts = (ts << 5n) | BigInt(CROCKFORD_MAP[ulidStr[i]]);
92
+ }
93
+ return Number(ts);
94
+ }
95
+
96
+ /**
97
+ * Resolve the local device identifier for event/command source metadata.
98
+ * @returns {string}
99
+ */
100
+ function resolveDeviceId() {
101
+ const envId = (process.env.ECOSYSTEM_DEVICE_ID || "").trim();
102
+ if (envId) return envId;
103
+ try {
104
+ const host = (os.hostname() || "").trim();
105
+ if (host) return host;
106
+ } catch {
107
+ // Ignore hostname lookup errors
108
+ }
109
+ return "local-device";
110
+ }
111
+
112
+ module.exports = {
113
+ CROCKFORD_ALPHABET,
114
+ generateUlid,
115
+ isUlid,
116
+ ulidTimestampMs,
117
+ resolveDeviceId,
118
+ };
119
+