@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/package.json +7 -2
- package/schemas/capability-manifest.v1.schema.json +117 -0
- package/schemas/command-envelope.v1.schema.json +133 -0
- package/schemas/event-envelope.v2.schema.json +63 -0
- package/schemas/notification-envelope.v1.schema.json +106 -0
- package/schemas/policy-state.v1.schema.json +163 -0
- package/src/_auth.js +18 -0
- package/src/ai_profile.js +1 -1
- package/src/contracts.js +398 -0
- package/src/discovery.js +2 -2
- package/src/events.js +100 -39
- package/src/hub.js +322 -0
- package/src/index.js +70 -4
- package/src/peer.js +1 -1
- package/src/ulid.js +119 -0
package/src/contracts.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Phase 1 ecosystem event/command/notification/capability contracts and JSON Schema validation.
|
|
5
|
+
* Mirrors Python ecosystem_client.contracts byte-for-byte.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
const path = require("path");
|
|
9
|
+
const { signPayload, verifySignature } = require("./_auth");
|
|
10
|
+
const { generateUlid, resolveDeviceId } = require("./ulid");
|
|
11
|
+
|
|
12
|
+
const SCHEMAS_DIR = path.resolve(__dirname, "../schemas");
|
|
13
|
+
const SCHEMA_CACHE = new Map();
|
|
14
|
+
|
|
15
|
+
class SchemaValidationError extends Error {
|
|
16
|
+
constructor(message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "SchemaValidationError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const EventType = Object.freeze({
|
|
23
|
+
// Security events (OpenEye, AegisSIEM, cyber-agents)
|
|
24
|
+
SECURITY_ALERT: "security.alert",
|
|
25
|
+
SECURITY_MOTION_DETECTED: "security.motion_detected",
|
|
26
|
+
SECURITY_PERSON_DETECTED: "security.person_detected",
|
|
27
|
+
SECURITY_INTRUSION: "security.intrusion",
|
|
28
|
+
SECURITY_THREAT_BLOCKED: "security.threat_blocked",
|
|
29
|
+
SECURITY_IOC_MATCH: "security.ioc_match",
|
|
30
|
+
|
|
31
|
+
// System events (any project)
|
|
32
|
+
SYSTEM_STARTUP: "system.startup",
|
|
33
|
+
SYSTEM_SHUTDOWN: "system.shutdown",
|
|
34
|
+
SYSTEM_HEALTH_CHANGED: "system.health_changed",
|
|
35
|
+
SYSTEM_ERROR: "system.error",
|
|
36
|
+
SYSTEM_CONFIG_CHANGED: "system.config_changed",
|
|
37
|
+
|
|
38
|
+
// Network events (AegisSIEM)
|
|
39
|
+
NETWORK_DEVICE_CONNECTED: "network.device_connected",
|
|
40
|
+
NETWORK_DEVICE_DISCONNECTED: "network.device_disconnected",
|
|
41
|
+
NETWORK_ANOMALY: "network.anomaly",
|
|
42
|
+
NETWORK_BANDWIDTH_ALERT: "network.bandwidth_alert",
|
|
43
|
+
|
|
44
|
+
// Display events (MagicMirror)
|
|
45
|
+
DISPLAY_UPDATE: "display.update",
|
|
46
|
+
DISPLAY_ALERT: "display.alert",
|
|
47
|
+
DISPLAY_WIDGET_CHANGED: "display.widget_changed",
|
|
48
|
+
|
|
49
|
+
// AI events (AI_For_Survival, ecosystem-ai)
|
|
50
|
+
AI_ANALYSIS_COMPLETE: "ai.analysis_complete",
|
|
51
|
+
AI_RECOMMENDATION: "ai.recommendation",
|
|
52
|
+
AI_PLAYBOOK_TRIGGERED: "ai.playbook_triggered",
|
|
53
|
+
|
|
54
|
+
// Ecosystem service & freeze lifecycle (registry / hub)
|
|
55
|
+
ECOSYSTEM_SERVICE_REGISTERED: "ecosystem.service_registered",
|
|
56
|
+
ECOSYSTEM_SERVICE_DEREGISTERED: "ecosystem.service_deregistered",
|
|
57
|
+
ECOSYSTEM_SERVICE_UNHEALTHY: "ecosystem.service_unhealthy",
|
|
58
|
+
ECOSYSTEM_AI_PROFILE_CHANGED: "ecosystem.ai_profile_changed",
|
|
59
|
+
ECOSYSTEM_FREEZE_REQUESTED: "ecosystem.freeze_requested",
|
|
60
|
+
ECOSYSTEM_FREEZE_APPLIED: "ecosystem.freeze_applied",
|
|
61
|
+
ECOSYSTEM_RESUME_REQUESTED: "ecosystem.resume_requested",
|
|
62
|
+
|
|
63
|
+
// Scanning lifecycle (Zero-Breach-Toolkit / scan_agent)
|
|
64
|
+
SCAN_REQUESTED: "scan.requested",
|
|
65
|
+
SCAN_STARTED: "scan.started",
|
|
66
|
+
SCAN_PROGRESS: "scan.progress",
|
|
67
|
+
SCAN_COMPLETED: "scan.completed",
|
|
68
|
+
SCAN_FINDING: "scan.finding",
|
|
69
|
+
SCAN_AUTHORIZATION_CHANGED: "scan.authorization_changed",
|
|
70
|
+
|
|
71
|
+
// Policy, approvals & containment (ecosystem-policy / hub)
|
|
72
|
+
POLICY_DECISION: "policy.decision",
|
|
73
|
+
POLICY_MODE_CHANGED: "policy.mode_changed",
|
|
74
|
+
POLICY_RESTRICTIONS_CHANGED: "policy.restrictions_changed",
|
|
75
|
+
APPROVAL_REQUESTED: "approval.requested",
|
|
76
|
+
APPROVAL_DECIDED: "approval.decided",
|
|
77
|
+
CONTAINMENT_APPLIED: "containment.applied",
|
|
78
|
+
CONTAINMENT_REVERTED: "containment.reverted",
|
|
79
|
+
|
|
80
|
+
// Capabilities & automations
|
|
81
|
+
CAPABILITY_REGISTERED: "capability.registered",
|
|
82
|
+
CAPABILITY_WITHDRAWN: "capability.withdrawn",
|
|
83
|
+
AUTOMATION_REQUESTED: "automation.requested",
|
|
84
|
+
AUTOMATION_COMPLETED: "automation.completed",
|
|
85
|
+
AUTOMATION_FAILED: "automation.failed",
|
|
86
|
+
|
|
87
|
+
// Cross-device notifications (notify.*)
|
|
88
|
+
NOTIFY_SECURITY: "notify.security",
|
|
89
|
+
NOTIFY_SYSTEM: "notify.system",
|
|
90
|
+
NOTIFY_SCAN: "notify.scan",
|
|
91
|
+
NOTIFY_POLICY: "notify.policy",
|
|
92
|
+
NOTIFY_APPROVAL: "notify.approval",
|
|
93
|
+
NOTIFY_AUTOMATION: "notify.automation",
|
|
94
|
+
|
|
95
|
+
// Compute broker & Model Forge
|
|
96
|
+
COMPUTE_JOB_STARTED: "compute.job.started",
|
|
97
|
+
COMPUTE_JOB_COMPLETED: "compute.job.completed",
|
|
98
|
+
COMPUTE_JOB_FAILED: "compute.job.failed",
|
|
99
|
+
MODEL_PUBLISHED: "model.published",
|
|
100
|
+
|
|
101
|
+
// Device enrollment
|
|
102
|
+
DEVICE_ENROLLED: "device.enrolled",
|
|
103
|
+
DEVICE_UNENROLLED: "device.unenrolled",
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
function listSchemas() {
|
|
107
|
+
if (!fs.existsSync(SCHEMAS_DIR)) return [];
|
|
108
|
+
return fs
|
|
109
|
+
.readdirSync(SCHEMAS_DIR)
|
|
110
|
+
.filter((f) => f.endsWith(".schema.json"))
|
|
111
|
+
.map((f) => f.slice(0, -".schema.json".length))
|
|
112
|
+
.sort();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function loadSchema(name) {
|
|
116
|
+
const key = name.endsWith(".schema.json")
|
|
117
|
+
? name.slice(0, -".schema.json".length)
|
|
118
|
+
: name;
|
|
119
|
+
if (SCHEMA_CACHE.has(key)) return SCHEMA_CACHE.get(key);
|
|
120
|
+
const filePath = path.join(SCHEMAS_DIR, `${key}.schema.json`);
|
|
121
|
+
if (!fs.existsSync(filePath)) {
|
|
122
|
+
throw new Error(`Unknown ecosystem contract schema: ${JSON.stringify(name)}`);
|
|
123
|
+
}
|
|
124
|
+
const schema = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
125
|
+
SCHEMA_CACHE.set(key, schema);
|
|
126
|
+
return schema;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function _matchesJsonType(value, expected) {
|
|
130
|
+
if (expected === "null") return value === null;
|
|
131
|
+
if (expected === "boolean") return typeof value === "boolean";
|
|
132
|
+
if (expected === "integer") return typeof value === "number" && Number.isInteger(value);
|
|
133
|
+
if (expected === "number") return typeof value === "number" && Number.isFinite(value);
|
|
134
|
+
if (expected === "string") return typeof value === "string";
|
|
135
|
+
if (expected === "object") return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
136
|
+
if (expected === "array") return Array.isArray(value);
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function _validateNode(value, schema, nodePath, errors) {
|
|
141
|
+
if (schema.type !== undefined) {
|
|
142
|
+
const allowed = Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
143
|
+
if (!allowed.some((t) => _matchesJsonType(value, t))) {
|
|
144
|
+
errors.push(`${nodePath}: expected type [${allowed.join(", ")}], got ${value === null ? "null" : typeof value}`);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (value === null || value === undefined) return;
|
|
150
|
+
|
|
151
|
+
if ("const" in schema && value !== schema.const) {
|
|
152
|
+
errors.push(`${nodePath}: expected const ${JSON.stringify(schema.const)}, got ${JSON.stringify(value)}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
|
|
156
|
+
errors.push(`${nodePath}: value ${JSON.stringify(value)} not in ${JSON.stringify(schema.enum)}`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (typeof value === "string") {
|
|
160
|
+
if (schema.minLength !== undefined && value.length < Number(schema.minLength)) {
|
|
161
|
+
errors.push(`${nodePath}: string shorter than minLength ${schema.minLength}`);
|
|
162
|
+
}
|
|
163
|
+
if (schema.pattern !== undefined && !new RegExp(schema.pattern).test(value)) {
|
|
164
|
+
errors.push(`${nodePath}: ${JSON.stringify(value)} does not match pattern ${JSON.stringify(schema.pattern)}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (typeof value === "number") {
|
|
169
|
+
if (schema.minimum !== undefined && value < Number(schema.minimum)) {
|
|
170
|
+
errors.push(`${nodePath}: ${value} < minimum ${schema.minimum}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (Array.isArray(value)) {
|
|
175
|
+
if (schema.minItems !== undefined && value.length < Number(schema.minItems)) {
|
|
176
|
+
errors.push(`${nodePath}: array has fewer than ${schema.minItems} items`);
|
|
177
|
+
}
|
|
178
|
+
if (schema.items && typeof schema.items === "object") {
|
|
179
|
+
value.forEach((item, idx) => {
|
|
180
|
+
_validateNode(item, schema.items, `${nodePath}[${idx}]`, errors);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (typeof value === "object" && !Array.isArray(value)) {
|
|
186
|
+
for (const reqKey of schema.required || []) {
|
|
187
|
+
if (!Object.prototype.hasOwnProperty.call(value, reqKey) || value[reqKey] === undefined) {
|
|
188
|
+
errors.push(`${nodePath}: missing required property ${JSON.stringify(reqKey)}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const props = schema.properties || {};
|
|
192
|
+
if (schema.additionalProperties === false && Object.keys(props).length > 0) {
|
|
193
|
+
for (const key of Object.keys(value)) {
|
|
194
|
+
if (!Object.prototype.hasOwnProperty.call(props, key)) {
|
|
195
|
+
errors.push(`${nodePath}: unexpected property ${JSON.stringify(key)}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
for (const [key, subschema] of Object.entries(props)) {
|
|
200
|
+
if (Object.prototype.hasOwnProperty.call(value, key) && value[key] !== undefined && subschema && typeof subschema === "object") {
|
|
201
|
+
_validateNode(value[key], subschema, `${nodePath}.${key}`, errors);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function validateAgainstSchema(instance, schema) {
|
|
208
|
+
const schemaObj = typeof schema === "string" ? loadSchema(schema) : schema;
|
|
209
|
+
const errors = [];
|
|
210
|
+
_validateNode(instance, schemaObj, "$", errors);
|
|
211
|
+
return errors;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function assertValidSchema(instance, schema) {
|
|
215
|
+
const errors = validateAgainstSchema(instance, schema);
|
|
216
|
+
if (errors.length > 0) {
|
|
217
|
+
throw new SchemaValidationError(errors.join("; "));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function canonicalSignableEvent(envelope) {
|
|
222
|
+
const version = envelope && envelope.schema_version;
|
|
223
|
+
if (typeof version === "number" && Number.isInteger(version) && version >= 2) {
|
|
224
|
+
const src = envelope.source;
|
|
225
|
+
let srcObj;
|
|
226
|
+
if (typeof src === "string") {
|
|
227
|
+
srcObj = { app: src, device_id: resolveDeviceId() };
|
|
228
|
+
} else if (src && typeof src === "object") {
|
|
229
|
+
srcObj = {
|
|
230
|
+
app: String(src.app || ""),
|
|
231
|
+
device_id: String(src.device_id || ""),
|
|
232
|
+
};
|
|
233
|
+
} else {
|
|
234
|
+
srcObj = { app: "", device_id: "" };
|
|
235
|
+
}
|
|
236
|
+
const signable = {
|
|
237
|
+
schema_version: version,
|
|
238
|
+
id: envelope.id || "",
|
|
239
|
+
type: envelope.type || "",
|
|
240
|
+
source: srcObj,
|
|
241
|
+
timestamp: envelope.timestamp == null ? 0 : envelope.timestamp,
|
|
242
|
+
data: envelope.data || {},
|
|
243
|
+
};
|
|
244
|
+
if (envelope.correlation_id !== undefined && envelope.correlation_id !== null) {
|
|
245
|
+
signable.correlation_id = envelope.correlation_id;
|
|
246
|
+
}
|
|
247
|
+
return signable;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Legacy v1 envelope (5-field layout)
|
|
251
|
+
const rawSrc = envelope ? envelope.source : "";
|
|
252
|
+
const v1Source = rawSrc && typeof rawSrc === "object" ? String(rawSrc.app || "") : String(rawSrc || "");
|
|
253
|
+
return {
|
|
254
|
+
id: (envelope && envelope.id) || "",
|
|
255
|
+
type: (envelope && envelope.type) || "",
|
|
256
|
+
source: v1Source,
|
|
257
|
+
timestamp: envelope && envelope.timestamp != null ? envelope.timestamp : 0,
|
|
258
|
+
data: (envelope && envelope.data) || {},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function buildEventEnvelopeV2(eventType, sourceApp, data = {}, secret = "", opts = {}) {
|
|
263
|
+
const envelope = {
|
|
264
|
+
schema_version: 2,
|
|
265
|
+
id: opts.eventId || generateUlid(),
|
|
266
|
+
type: eventType,
|
|
267
|
+
source: {
|
|
268
|
+
app: sourceApp,
|
|
269
|
+
device_id: opts.deviceId || resolveDeviceId(),
|
|
270
|
+
},
|
|
271
|
+
timestamp: opts.timestamp == null ? Date.now() / 1000 : Number(opts.timestamp),
|
|
272
|
+
data: Object.assign({}, data || {}),
|
|
273
|
+
};
|
|
274
|
+
if (opts.correlationId !== undefined && opts.correlationId !== null) {
|
|
275
|
+
envelope.correlation_id = opts.correlationId;
|
|
276
|
+
}
|
|
277
|
+
envelope.signature = signPayload(canonicalSignableEvent(envelope), secret);
|
|
278
|
+
return envelope;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function verifyEventEnvelope(envelope, secret) {
|
|
282
|
+
if (!envelope || typeof envelope !== "object") return false;
|
|
283
|
+
const signature = envelope.signature;
|
|
284
|
+
if (!signature || typeof signature !== "string") return false;
|
|
285
|
+
return verifySignature(canonicalSignableEvent(envelope), signature, secret);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function canonicalSignableCommand(envelope) {
|
|
289
|
+
const out = {};
|
|
290
|
+
for (const [k, v] of Object.entries(envelope || {})) {
|
|
291
|
+
if (k === "signature") continue;
|
|
292
|
+
out[k] = v;
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function buildCommandEnvelope(command, actionClass, actor, target, secret, opts = {}) {
|
|
298
|
+
const authRef = opts.authorizationRef !== undefined ? opts.authorizationRef : null;
|
|
299
|
+
if (authRef && (String(authRef).startsWith("notify:") || String(authRef).startsWith("notify."))) {
|
|
300
|
+
throw new Error("A notification identifier is never a valid command authorization_ref");
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const cid = opts.commandId || generateUlid();
|
|
304
|
+
const nowTs = opts.issuedAt == null ? Date.now() / 1000 : Number(opts.issuedAt);
|
|
305
|
+
const ttlSeconds = opts.ttlSeconds == null ? 60.0 : Number(opts.ttlSeconds);
|
|
306
|
+
const envelope = {
|
|
307
|
+
schema_version: 1,
|
|
308
|
+
id: cid,
|
|
309
|
+
command,
|
|
310
|
+
action_class: actionClass,
|
|
311
|
+
actor: Object.assign({}, actor),
|
|
312
|
+
target: Object.assign({}, target),
|
|
313
|
+
parameters: Object.assign({}, opts.parameters || {}),
|
|
314
|
+
issued_at: nowTs,
|
|
315
|
+
expires_at: nowTs + ttlSeconds,
|
|
316
|
+
correlation_id: opts.correlationId || cid,
|
|
317
|
+
idempotency_key: opts.idempotencyKey || cid,
|
|
318
|
+
authorization_ref: authRef,
|
|
319
|
+
rationale: opts.rationale !== undefined ? opts.rationale : null,
|
|
320
|
+
ack_required: opts.ackRequired === undefined ? true : Boolean(opts.ackRequired),
|
|
321
|
+
};
|
|
322
|
+
envelope.signature = signPayload(canonicalSignableCommand(envelope), secret);
|
|
323
|
+
assertValidSchema(envelope, "command-envelope.v1");
|
|
324
|
+
return envelope;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function verifyCommandEnvelope(envelope, secret, opts = {}) {
|
|
328
|
+
const errors = validateAgainstSchema(envelope, "command-envelope.v1");
|
|
329
|
+
if (errors.length > 0) {
|
|
330
|
+
return { valid: false, reason: `schema invalid: ${errors[0]}` };
|
|
331
|
+
}
|
|
332
|
+
const authRef = envelope.authorization_ref;
|
|
333
|
+
if (authRef && (String(authRef).startsWith("notify:") || String(authRef).startsWith("notify."))) {
|
|
334
|
+
return { valid: false, reason: "notification reference cannot authorize a command" };
|
|
335
|
+
}
|
|
336
|
+
const current = opts.now == null ? Date.now() / 1000 : Number(opts.now);
|
|
337
|
+
const issuedAt = Number(envelope.issued_at);
|
|
338
|
+
const expiresAt = Number(envelope.expires_at);
|
|
339
|
+
if (expiresAt <= issuedAt) {
|
|
340
|
+
return { valid: false, reason: "expires_at must be greater than issued_at" };
|
|
341
|
+
}
|
|
342
|
+
if (current > expiresAt) {
|
|
343
|
+
return { valid: false, reason: "command expired" };
|
|
344
|
+
}
|
|
345
|
+
if (!verifySignature(canonicalSignableCommand(envelope), envelope.signature || "", secret)) {
|
|
346
|
+
return { valid: false, reason: "invalid command signature" };
|
|
347
|
+
}
|
|
348
|
+
return { valid: true, reason: "ok" };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function buildNotificationEnvelope(notifyType, sourceApp, severity, title, body, opts = {}) {
|
|
352
|
+
if (!opts.dedupeKey) {
|
|
353
|
+
throw new Error("dedupeKey is required for NotificationEnvelope");
|
|
354
|
+
}
|
|
355
|
+
const envelope = {
|
|
356
|
+
schema_version: 1,
|
|
357
|
+
type: notifyType,
|
|
358
|
+
id: opts.notificationId || generateUlid(),
|
|
359
|
+
dedupe_key: opts.dedupeKey,
|
|
360
|
+
source: {
|
|
361
|
+
app: sourceApp,
|
|
362
|
+
device_id: opts.deviceId || resolveDeviceId(),
|
|
363
|
+
},
|
|
364
|
+
severity,
|
|
365
|
+
title,
|
|
366
|
+
body: body || "",
|
|
367
|
+
actions: Array.isArray(opts.actions) ? opts.actions.slice() : [],
|
|
368
|
+
privacy: opts.privacy || "redacted",
|
|
369
|
+
ttl: opts.ttl || "24h",
|
|
370
|
+
deep_link: opts.deepLink !== undefined ? opts.deepLink : null,
|
|
371
|
+
created_at:
|
|
372
|
+
opts.createdAt ||
|
|
373
|
+
new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
374
|
+
};
|
|
375
|
+
if (opts.secret) {
|
|
376
|
+
const signable = Object.assign({}, envelope);
|
|
377
|
+
envelope.signature = signPayload(signable, opts.secret);
|
|
378
|
+
}
|
|
379
|
+
assertValidSchema(envelope, "notification-envelope.v1");
|
|
380
|
+
return envelope;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
module.exports = {
|
|
384
|
+
SchemaValidationError,
|
|
385
|
+
EventType,
|
|
386
|
+
listSchemas,
|
|
387
|
+
loadSchema,
|
|
388
|
+
validateAgainstSchema,
|
|
389
|
+
assertValidSchema,
|
|
390
|
+
canonicalSignableEvent,
|
|
391
|
+
buildEventEnvelopeV2,
|
|
392
|
+
verifyEventEnvelope,
|
|
393
|
+
canonicalSignableCommand,
|
|
394
|
+
buildCommandEnvelope,
|
|
395
|
+
verifyCommandEnvelope,
|
|
396
|
+
buildNotificationEnvelope,
|
|
397
|
+
};
|
|
398
|
+
|
package/src/discovery.js
CHANGED
|
@@ -66,7 +66,7 @@ class DiscoveryManager {
|
|
|
66
66
|
subscriptions: subscriptions || [],
|
|
67
67
|
};
|
|
68
68
|
const payload = JSON.stringify(dataObj);
|
|
69
|
-
const { signRequest } = require("
|
|
69
|
+
const { signRequest } = require("./_auth");
|
|
70
70
|
const registerUrl = `${this.config.registryUrl}/register`;
|
|
71
71
|
const headers = signRequest("POST", registerUrl, this.config.hmacSecret, dataObj);
|
|
72
72
|
await this._post(registerUrl, payload, headers);
|
|
@@ -80,7 +80,7 @@ class DiscoveryManager {
|
|
|
80
80
|
if (this.mode !== DiscoveryMode.REGISTRY) return false;
|
|
81
81
|
try {
|
|
82
82
|
const url = `${this.config.registryUrl}/deregister/${name}`;
|
|
83
|
-
const { signRequest } = require("
|
|
83
|
+
const { signRequest } = require("./_auth");
|
|
84
84
|
const headers = signRequest("DELETE", url, this.config.hmacSecret);
|
|
85
85
|
await this._delete(url, headers);
|
|
86
86
|
return true;
|
package/src/events.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
3
|
const http = require("http");
|
|
4
4
|
const https = require("https");
|
|
5
|
+
const { buildEventEnvelopeV2, verifyEventEnvelope } = require("./contracts");
|
|
5
6
|
|
|
6
7
|
class EventPublisher {
|
|
7
8
|
constructor(config, mode, serviceName) {
|
|
@@ -11,42 +12,71 @@ class EventPublisher {
|
|
|
11
12
|
this._peerWebhooks = {};
|
|
12
13
|
}
|
|
13
14
|
|
|
14
|
-
setPeerWebhooks(webhooks) {
|
|
15
|
+
setPeerWebhooks(webhooks) {
|
|
16
|
+
this._peerWebhooks = webhooks || {};
|
|
17
|
+
}
|
|
15
18
|
|
|
16
|
-
async publish(eventType, data) {
|
|
19
|
+
async publish(eventType, data = {}, opts = {}) {
|
|
17
20
|
if (this.mode === "standalone") {
|
|
18
21
|
return { delivered: 0, failed: 0, mode: "standalone" };
|
|
19
22
|
}
|
|
20
|
-
const envelope = this._buildEnvelope(eventType, data);
|
|
23
|
+
const envelope = this._buildEnvelope(eventType, data, opts);
|
|
24
|
+
if (this.mode === "registry") {
|
|
25
|
+
return this._publishViaRegistry(envelope);
|
|
26
|
+
}
|
|
21
27
|
const matching = this._getMatchingPeers(eventType);
|
|
22
28
|
let delivered = 0;
|
|
23
|
-
for (const
|
|
29
|
+
for (const info of Object.values(matching)) {
|
|
24
30
|
try {
|
|
25
31
|
await this._deliverToPeer(envelope, info.webhook_url);
|
|
26
32
|
delivered++;
|
|
27
|
-
} catch {
|
|
33
|
+
} catch {
|
|
34
|
+
/* failed delivery */
|
|
35
|
+
}
|
|
28
36
|
}
|
|
29
|
-
return {
|
|
37
|
+
return {
|
|
38
|
+
delivered,
|
|
39
|
+
failed: Object.keys(matching).length - delivered,
|
|
40
|
+
subscribers: Object.keys(matching),
|
|
41
|
+
};
|
|
30
42
|
}
|
|
31
43
|
|
|
32
|
-
_buildEnvelope(eventType, data) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
source: this.serviceName,
|
|
37
|
-
timestamp: Date.now() / 1000,
|
|
44
|
+
_buildEnvelope(eventType, data = {}, opts = {}) {
|
|
45
|
+
return buildEventEnvelopeV2(
|
|
46
|
+
eventType,
|
|
47
|
+
this.serviceName,
|
|
38
48
|
data,
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
49
|
+
this.config.hmacSecret || "",
|
|
50
|
+
opts
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static _sourceHeader(envelope) {
|
|
55
|
+
const src = envelope && envelope.source;
|
|
56
|
+
if (src && typeof src === "object") {
|
|
57
|
+
return String(src.app || "");
|
|
58
|
+
}
|
|
59
|
+
return String(src || "");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async _publishViaRegistry(envelope) {
|
|
63
|
+
const url = `${(this.config.registryUrl || "http://localhost:8500").replace(/\/+$/, "")}/events/publish`;
|
|
64
|
+
try {
|
|
65
|
+
return await this._postJson(url, envelope);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
return { delivered: 0, failed: 1, error: String(err && err.message ? err.message : err) };
|
|
68
|
+
}
|
|
43
69
|
}
|
|
44
70
|
|
|
45
71
|
_getMatchingPeers(eventType) {
|
|
46
72
|
const matching = {};
|
|
47
73
|
for (const [name, info] of Object.entries(this._peerWebhooks)) {
|
|
48
|
-
for (const pattern of
|
|
49
|
-
if (
|
|
74
|
+
for (const pattern of info.subscriptions || []) {
|
|
75
|
+
if (
|
|
76
|
+
pattern === "*" ||
|
|
77
|
+
(pattern.endsWith(".*") && eventType.startsWith(pattern.slice(0, -2) + ".")) ||
|
|
78
|
+
pattern === eventType
|
|
79
|
+
) {
|
|
50
80
|
matching[name] = info;
|
|
51
81
|
break;
|
|
52
82
|
}
|
|
@@ -56,26 +86,51 @@ class EventPublisher {
|
|
|
56
86
|
}
|
|
57
87
|
|
|
58
88
|
async _deliverToPeer(envelope, webhookUrl) {
|
|
89
|
+
await this._postJson(webhookUrl, envelope);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
_postJson(targetUrl, envelope) {
|
|
59
93
|
const body = JSON.stringify(envelope);
|
|
60
94
|
return new Promise((resolve, reject) => {
|
|
61
|
-
const parsed = new URL(
|
|
95
|
+
const parsed = new URL(targetUrl);
|
|
62
96
|
const lib = parsed.protocol === "https:" ? https : http;
|
|
63
|
-
const req = lib.request(
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
97
|
+
const req = lib.request(
|
|
98
|
+
{
|
|
99
|
+
hostname: parsed.hostname,
|
|
100
|
+
port: parsed.port,
|
|
101
|
+
path: parsed.pathname + parsed.search,
|
|
102
|
+
method: "POST",
|
|
103
|
+
headers: {
|
|
104
|
+
"Content-Type": "application/json",
|
|
105
|
+
"Content-Length": Buffer.byteLength(body),
|
|
106
|
+
"X-Ecosystem-Signature": envelope.signature || "",
|
|
107
|
+
"X-Ecosystem-Event": envelope.type,
|
|
108
|
+
"X-Ecosystem-Source": EventPublisher._sourceHeader(envelope),
|
|
109
|
+
},
|
|
110
|
+
timeout: this.config.requestTimeout,
|
|
72
111
|
},
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
112
|
+
(res) => {
|
|
113
|
+
let raw = "";
|
|
114
|
+
res.on("data", (chunk) => {
|
|
115
|
+
raw += chunk;
|
|
116
|
+
});
|
|
117
|
+
res.on("end", () => {
|
|
118
|
+
if (res.statusCode >= 400) {
|
|
119
|
+
return reject(new Error(`HTTP ${res.statusCode}`));
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
resolve(raw ? JSON.parse(raw) : {});
|
|
123
|
+
} catch {
|
|
124
|
+
resolve(raw);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
);
|
|
78
129
|
req.on("error", reject);
|
|
130
|
+
req.on("timeout", () => {
|
|
131
|
+
req.destroy();
|
|
132
|
+
reject(new Error("timeout"));
|
|
133
|
+
});
|
|
79
134
|
req.write(body);
|
|
80
135
|
req.end();
|
|
81
136
|
});
|
|
@@ -94,16 +149,20 @@ class EventSubscriber {
|
|
|
94
149
|
}
|
|
95
150
|
|
|
96
151
|
async dispatch(envelope) {
|
|
97
|
-
|
|
98
|
-
if (!verifySignature(signable, envelope.signature || "", this._hmacSecret)) return;
|
|
152
|
+
if (!verifyEventEnvelope(envelope, this._hmacSecret)) return false;
|
|
99
153
|
|
|
100
154
|
for (const [pattern, handlers] of Object.entries(this._handlers)) {
|
|
101
155
|
if (this._matches(envelope.type, pattern)) {
|
|
102
156
|
for (const handler of handlers) {
|
|
103
|
-
try {
|
|
157
|
+
try {
|
|
158
|
+
await handler(envelope);
|
|
159
|
+
} catch (e) {
|
|
160
|
+
console.error(`Handler error: ${e}`);
|
|
161
|
+
}
|
|
104
162
|
}
|
|
105
163
|
}
|
|
106
164
|
}
|
|
165
|
+
return true;
|
|
107
166
|
}
|
|
108
167
|
|
|
109
168
|
_matches(eventType, pattern) {
|
|
@@ -112,7 +171,9 @@ class EventSubscriber {
|
|
|
112
171
|
return eventType === pattern;
|
|
113
172
|
}
|
|
114
173
|
|
|
115
|
-
get subscriptions() {
|
|
174
|
+
get subscriptions() {
|
|
175
|
+
return Object.keys(this._handlers);
|
|
176
|
+
}
|
|
116
177
|
}
|
|
117
178
|
|
|
118
179
|
module.exports = { EventPublisher, EventSubscriber };
|