@hasna/events 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 +17 -0
- package/README.md +240 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +811 -0
- package/dist/commander.d.ts +14 -0
- package/dist/commander.js +691 -0
- package/dist/filter.d.ts +4 -0
- package/dist/filter.js +48 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +550 -0
- package/dist/signing.d.ts +9 -0
- package/dist/signing.js +39 -0
- package/dist/storage.d.ts +44 -0
- package/dist/storage.js +120 -0
- package/dist/transports.d.ts +12 -0
- package/dist/transports.js +191 -0
- package/dist/types.d.ts +118 -0
- package/dist/types.js +1 -0
- package/package.json +81 -0
package/dist/filter.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/filter.ts
|
|
3
|
+
function getPathValue(input, path) {
|
|
4
|
+
return path.split(".").reduce((value, part) => {
|
|
5
|
+
if (value && typeof value === "object" && part in value) {
|
|
6
|
+
return value[part];
|
|
7
|
+
}
|
|
8
|
+
return;
|
|
9
|
+
}, input);
|
|
10
|
+
}
|
|
11
|
+
function wildcardToRegExp(pattern) {
|
|
12
|
+
const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*");
|
|
13
|
+
return new RegExp(`^${escaped}$`);
|
|
14
|
+
}
|
|
15
|
+
function matchString(value, matcher) {
|
|
16
|
+
if (matcher === undefined)
|
|
17
|
+
return true;
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return false;
|
|
20
|
+
const matchers = Array.isArray(matcher) ? matcher : [matcher];
|
|
21
|
+
return matchers.some((item) => wildcardToRegExp(item).test(value));
|
|
22
|
+
}
|
|
23
|
+
function matchRecord(input, matcher) {
|
|
24
|
+
if (!matcher)
|
|
25
|
+
return true;
|
|
26
|
+
return Object.entries(matcher).every(([path, expected]) => {
|
|
27
|
+
const actual = getPathValue(input, path);
|
|
28
|
+
if (typeof expected === "string" || Array.isArray(expected)) {
|
|
29
|
+
return matchString(actual === undefined ? undefined : String(actual), expected);
|
|
30
|
+
}
|
|
31
|
+
return actual === expected;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function eventMatchesFilter(event, filter) {
|
|
35
|
+
return matchString(event.source, filter.source) && matchString(event.type, filter.type) && matchString(event.subject, filter.subject) && matchString(event.severity, filter.severity) && matchRecord(event.data, filter.data) && matchRecord(event.metadata, filter.metadata);
|
|
36
|
+
}
|
|
37
|
+
function channelMatchesEvent(channel, event) {
|
|
38
|
+
if (!channel.enabled)
|
|
39
|
+
return false;
|
|
40
|
+
if (!channel.filters || channel.filters.length === 0)
|
|
41
|
+
return true;
|
|
42
|
+
return channel.filters.some((filter) => eventMatchesFilter(event, filter));
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
matchString,
|
|
46
|
+
eventMatchesFilter,
|
|
47
|
+
channelMatchesEvent
|
|
48
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ChannelConfig, DeliveryResult, EmitOptions, EmitResult, EventEnvelope, EventInput, EventRedactor, ReplayOptions } from "./types.js";
|
|
2
|
+
import { type EventsStore } from "./storage.js";
|
|
3
|
+
import { type TransportDispatchOptions } from "./transports.js";
|
|
4
|
+
export * from "./types.js";
|
|
5
|
+
export * from "./storage.js";
|
|
6
|
+
export * from "./filter.js";
|
|
7
|
+
export * from "./signing.js";
|
|
8
|
+
export * from "./transports.js";
|
|
9
|
+
export interface EventsClientOptions extends TransportDispatchOptions {
|
|
10
|
+
store?: EventsStore;
|
|
11
|
+
dataDir?: string;
|
|
12
|
+
redactors?: EventRedactor[];
|
|
13
|
+
}
|
|
14
|
+
export declare function createEvent<TData extends Record<string, unknown>>(input: EventInput<TData>): EventEnvelope<TData>;
|
|
15
|
+
export declare class EventsClient {
|
|
16
|
+
private store;
|
|
17
|
+
private redactors;
|
|
18
|
+
private transportOptions;
|
|
19
|
+
constructor(options?: EventsClientOptions);
|
|
20
|
+
addChannel(input: Omit<ChannelConfig, "createdAt" | "updatedAt"> & Partial<Pick<ChannelConfig, "createdAt" | "updatedAt">>): Promise<ChannelConfig>;
|
|
21
|
+
listChannels(): Promise<ChannelConfig[]>;
|
|
22
|
+
removeChannel(id: string): Promise<boolean>;
|
|
23
|
+
emit<TData extends Record<string, unknown>>(input: EventInput<TData>, options?: EmitOptions): Promise<EmitResult<TData>>;
|
|
24
|
+
listEvents(): Promise<EventEnvelope[]>;
|
|
25
|
+
listDeliveries(): Promise<DeliveryResult[]>;
|
|
26
|
+
deliver(event: EventEnvelope): Promise<DeliveryResult[]>;
|
|
27
|
+
testChannel(id: string, input?: Partial<EventInput>): Promise<DeliveryResult>;
|
|
28
|
+
replay(options?: ReplayOptions): Promise<{
|
|
29
|
+
events: EventEnvelope[];
|
|
30
|
+
deliveries: DeliveryResult[];
|
|
31
|
+
}>;
|
|
32
|
+
private applyRedaction;
|
|
33
|
+
private deliverWithRetry;
|
|
34
|
+
}
|
|
35
|
+
export declare function redactPaths<T extends EventEnvelope>(event: T, paths: string[], replacement?: string): T;
|
|
36
|
+
export declare function sanitizeChannelForOutput(channel: ChannelConfig): ChannelConfig;
|
|
37
|
+
export declare function sanitizeChannelsForOutput(channels: ChannelConfig[]): ChannelConfig[];
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/filter.ts
|
|
3
|
+
function getPathValue(input, path) {
|
|
4
|
+
return path.split(".").reduce((value, part) => {
|
|
5
|
+
if (value && typeof value === "object" && part in value) {
|
|
6
|
+
return value[part];
|
|
7
|
+
}
|
|
8
|
+
return;
|
|
9
|
+
}, input);
|
|
10
|
+
}
|
|
11
|
+
function wildcardToRegExp(pattern) {
|
|
12
|
+
const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*");
|
|
13
|
+
return new RegExp(`^${escaped}$`);
|
|
14
|
+
}
|
|
15
|
+
function matchString(value, matcher) {
|
|
16
|
+
if (matcher === undefined)
|
|
17
|
+
return true;
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return false;
|
|
20
|
+
const matchers = Array.isArray(matcher) ? matcher : [matcher];
|
|
21
|
+
return matchers.some((item) => wildcardToRegExp(item).test(value));
|
|
22
|
+
}
|
|
23
|
+
function matchRecord(input, matcher) {
|
|
24
|
+
if (!matcher)
|
|
25
|
+
return true;
|
|
26
|
+
return Object.entries(matcher).every(([path, expected]) => {
|
|
27
|
+
const actual = getPathValue(input, path);
|
|
28
|
+
if (typeof expected === "string" || Array.isArray(expected)) {
|
|
29
|
+
return matchString(actual === undefined ? undefined : String(actual), expected);
|
|
30
|
+
}
|
|
31
|
+
return actual === expected;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function eventMatchesFilter(event, filter) {
|
|
35
|
+
return matchString(event.source, filter.source) && matchString(event.type, filter.type) && matchString(event.subject, filter.subject) && matchString(event.severity, filter.severity) && matchRecord(event.data, filter.data) && matchRecord(event.metadata, filter.metadata);
|
|
36
|
+
}
|
|
37
|
+
function channelMatchesEvent(channel, event) {
|
|
38
|
+
if (!channel.enabled)
|
|
39
|
+
return false;
|
|
40
|
+
if (!channel.filters || channel.filters.length === 0)
|
|
41
|
+
return true;
|
|
42
|
+
return channel.filters.some((filter) => eventMatchesFilter(event, filter));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/storage.ts
|
|
46
|
+
import { mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
47
|
+
import { existsSync } from "fs";
|
|
48
|
+
import { homedir } from "os";
|
|
49
|
+
import { join } from "path";
|
|
50
|
+
var HASNA_EVENTS_DIR_ENV = "HASNA_EVENTS_DIR";
|
|
51
|
+
var HASNA_EVENTS_HOME_ENV = "HASNA_EVENTS_HOME";
|
|
52
|
+
function getEventsDataDir(override) {
|
|
53
|
+
return override || process.env[HASNA_EVENTS_DIR_ENV] || process.env[HASNA_EVENTS_HOME_ENV] || join(homedir(), ".hasna", "events");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
class JsonEventsStore {
|
|
57
|
+
dataDir;
|
|
58
|
+
channelsPath;
|
|
59
|
+
eventsPath;
|
|
60
|
+
deliveriesPath;
|
|
61
|
+
constructor(dataDir = getEventsDataDir()) {
|
|
62
|
+
this.dataDir = dataDir;
|
|
63
|
+
this.channelsPath = join(dataDir, "channels.json");
|
|
64
|
+
this.eventsPath = join(dataDir, "events.json");
|
|
65
|
+
this.deliveriesPath = join(dataDir, "deliveries.json");
|
|
66
|
+
}
|
|
67
|
+
async init() {
|
|
68
|
+
await mkdir(this.dataDir, { recursive: true });
|
|
69
|
+
await this.ensureArrayFile(this.channelsPath);
|
|
70
|
+
await this.ensureArrayFile(this.eventsPath);
|
|
71
|
+
await this.ensureArrayFile(this.deliveriesPath);
|
|
72
|
+
}
|
|
73
|
+
async addChannel(channel) {
|
|
74
|
+
await this.init();
|
|
75
|
+
const channels = await this.readJson(this.channelsPath, []);
|
|
76
|
+
const index = channels.findIndex((item) => item.id === channel.id);
|
|
77
|
+
if (index >= 0) {
|
|
78
|
+
channels[index] = { ...channel, createdAt: channels[index].createdAt, updatedAt: new Date().toISOString() };
|
|
79
|
+
} else {
|
|
80
|
+
channels.push(channel);
|
|
81
|
+
}
|
|
82
|
+
await this.writeJson(this.channelsPath, channels);
|
|
83
|
+
return index >= 0 ? channels[index] : channel;
|
|
84
|
+
}
|
|
85
|
+
async listChannels() {
|
|
86
|
+
await this.init();
|
|
87
|
+
return this.readJson(this.channelsPath, []);
|
|
88
|
+
}
|
|
89
|
+
async getChannel(id) {
|
|
90
|
+
const channels = await this.listChannels();
|
|
91
|
+
return channels.find((channel) => channel.id === id);
|
|
92
|
+
}
|
|
93
|
+
async removeChannel(id) {
|
|
94
|
+
await this.init();
|
|
95
|
+
const channels = await this.readJson(this.channelsPath, []);
|
|
96
|
+
const next = channels.filter((channel) => channel.id !== id);
|
|
97
|
+
await this.writeJson(this.channelsPath, next);
|
|
98
|
+
return next.length !== channels.length;
|
|
99
|
+
}
|
|
100
|
+
async appendEvent(event) {
|
|
101
|
+
await this.init();
|
|
102
|
+
const events = await this.readJson(this.eventsPath, []);
|
|
103
|
+
events.push(event);
|
|
104
|
+
await this.writeJson(this.eventsPath, events);
|
|
105
|
+
return event;
|
|
106
|
+
}
|
|
107
|
+
async listEvents() {
|
|
108
|
+
await this.init();
|
|
109
|
+
return this.readJson(this.eventsPath, []);
|
|
110
|
+
}
|
|
111
|
+
async findEventByIdentity(identity) {
|
|
112
|
+
const events = await this.listEvents();
|
|
113
|
+
return events.find((event) => identity.id !== undefined && event.id === identity.id || identity.dedupeKey !== undefined && event.dedupeKey === identity.dedupeKey);
|
|
114
|
+
}
|
|
115
|
+
async appendDelivery(result) {
|
|
116
|
+
await this.init();
|
|
117
|
+
const deliveries = await this.readJson(this.deliveriesPath, []);
|
|
118
|
+
deliveries.push(result);
|
|
119
|
+
await this.writeJson(this.deliveriesPath, deliveries);
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
async listDeliveries() {
|
|
123
|
+
await this.init();
|
|
124
|
+
return this.readJson(this.deliveriesPath, []);
|
|
125
|
+
}
|
|
126
|
+
async exportData() {
|
|
127
|
+
return {
|
|
128
|
+
channels: await this.listChannels(),
|
|
129
|
+
events: await this.listEvents(),
|
|
130
|
+
deliveries: await this.listDeliveries()
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
async ensureArrayFile(path) {
|
|
134
|
+
if (!existsSync(path)) {
|
|
135
|
+
await writeFile(path, `[]
|
|
136
|
+
`, "utf-8");
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async readJson(path, fallback) {
|
|
140
|
+
try {
|
|
141
|
+
const raw = await readFile(path, "utf-8");
|
|
142
|
+
if (!raw.trim())
|
|
143
|
+
return fallback;
|
|
144
|
+
return JSON.parse(raw);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error.code === "ENOENT")
|
|
147
|
+
return fallback;
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async writeJson(path, value) {
|
|
152
|
+
const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
153
|
+
await writeFile(tempPath, `${JSON.stringify(value, null, 2)}
|
|
154
|
+
`, "utf-8");
|
|
155
|
+
await rename(tempPath, path);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/signing.ts
|
|
160
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
161
|
+
function buildSignatureBase(timestamp, body) {
|
|
162
|
+
return `${timestamp}.${body}`;
|
|
163
|
+
}
|
|
164
|
+
function signPayload(secret, timestamp, body) {
|
|
165
|
+
const digest = createHmac("sha256", secret).update(buildSignatureBase(timestamp, body)).digest("hex");
|
|
166
|
+
return `sha256=${digest}`;
|
|
167
|
+
}
|
|
168
|
+
function verifyPayloadSignature(secret, timestamp, body, signature) {
|
|
169
|
+
const expected = signPayload(secret, timestamp, body);
|
|
170
|
+
const actual = signature.trim();
|
|
171
|
+
const expectedBuffer = Buffer.from(expected);
|
|
172
|
+
const actualBuffer = Buffer.from(actual);
|
|
173
|
+
if (expectedBuffer.length !== actualBuffer.length)
|
|
174
|
+
return false;
|
|
175
|
+
return timingSafeEqual(expectedBuffer, actualBuffer);
|
|
176
|
+
}
|
|
177
|
+
function isTimestampWithinTolerance(timestamp, toleranceMs, now = Date.now()) {
|
|
178
|
+
const parsed = Date.parse(timestamp);
|
|
179
|
+
if (!Number.isFinite(parsed))
|
|
180
|
+
return false;
|
|
181
|
+
const reference = now instanceof Date ? now.getTime() : now;
|
|
182
|
+
return Math.abs(reference - parsed) <= toleranceMs;
|
|
183
|
+
}
|
|
184
|
+
function verifyWebhookSignature(secret, timestamp, body, signature, options = {}) {
|
|
185
|
+
if (options.toleranceMs !== undefined && !isTimestampWithinTolerance(timestamp, options.toleranceMs, options.now)) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
return verifyPayloadSignature(secret, timestamp, body, signature);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/transports.ts
|
|
192
|
+
import { randomUUID } from "crypto";
|
|
193
|
+
import { spawn } from "child_process";
|
|
194
|
+
function now() {
|
|
195
|
+
return new Date().toISOString();
|
|
196
|
+
}
|
|
197
|
+
function truncate(value, max = 4096) {
|
|
198
|
+
return value.length > max ? `${value.slice(0, max)}...` : value;
|
|
199
|
+
}
|
|
200
|
+
function buildWebhookRequest(event, channel) {
|
|
201
|
+
if (!channel.webhook)
|
|
202
|
+
throw new Error(`Channel ${channel.id} has no webhook config`);
|
|
203
|
+
const body = JSON.stringify(event);
|
|
204
|
+
const timestamp = event.time;
|
|
205
|
+
const headers = {
|
|
206
|
+
"Content-Type": "application/json",
|
|
207
|
+
"User-Agent": "@hasna/events",
|
|
208
|
+
"X-Hasna-Event-Id": event.id,
|
|
209
|
+
"X-Hasna-Event-Type": event.type,
|
|
210
|
+
"X-Hasna-Timestamp": timestamp,
|
|
211
|
+
...channel.webhook.headers
|
|
212
|
+
};
|
|
213
|
+
if (channel.webhook.secret) {
|
|
214
|
+
headers["X-Hasna-Signature"] = signPayload(channel.webhook.secret, timestamp, body);
|
|
215
|
+
}
|
|
216
|
+
return { body, headers };
|
|
217
|
+
}
|
|
218
|
+
async function dispatchWebhook(event, channel, options = {}) {
|
|
219
|
+
if (!channel.webhook)
|
|
220
|
+
throw new Error(`Channel ${channel.id} has no webhook config`);
|
|
221
|
+
const startedAt = now();
|
|
222
|
+
const { body, headers } = buildWebhookRequest(event, channel);
|
|
223
|
+
const controller = new AbortController;
|
|
224
|
+
const timeout = setTimeout(() => controller.abort(), channel.webhook.timeoutMs ?? 15000);
|
|
225
|
+
try {
|
|
226
|
+
const response = await (options.fetchImpl ?? fetch)(channel.webhook.url, {
|
|
227
|
+
method: "POST",
|
|
228
|
+
headers,
|
|
229
|
+
body,
|
|
230
|
+
signal: controller.signal
|
|
231
|
+
});
|
|
232
|
+
const responseBody = truncate(await response.text());
|
|
233
|
+
return {
|
|
234
|
+
attempt: 1,
|
|
235
|
+
status: response.ok ? "success" : "failed",
|
|
236
|
+
startedAt,
|
|
237
|
+
completedAt: now(),
|
|
238
|
+
responseStatus: response.status,
|
|
239
|
+
responseBody,
|
|
240
|
+
error: response.ok ? undefined : `Webhook returned HTTP ${response.status}`
|
|
241
|
+
};
|
|
242
|
+
} catch (error) {
|
|
243
|
+
return {
|
|
244
|
+
attempt: 1,
|
|
245
|
+
status: "failed",
|
|
246
|
+
startedAt,
|
|
247
|
+
completedAt: now(),
|
|
248
|
+
error: error instanceof Error ? error.message : String(error)
|
|
249
|
+
};
|
|
250
|
+
} finally {
|
|
251
|
+
clearTimeout(timeout);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
async function dispatchCommand(event, channel) {
|
|
255
|
+
if (!channel.command)
|
|
256
|
+
throw new Error(`Channel ${channel.id} has no command config`);
|
|
257
|
+
const startedAt = now();
|
|
258
|
+
const eventJson = JSON.stringify(event);
|
|
259
|
+
const env = {
|
|
260
|
+
...process.env,
|
|
261
|
+
...channel.command.env,
|
|
262
|
+
HASNA_CHANNEL_ID: channel.id,
|
|
263
|
+
HASNA_EVENT_ID: event.id,
|
|
264
|
+
HASNA_EVENT_TYPE: event.type,
|
|
265
|
+
HASNA_EVENT_SOURCE: event.source,
|
|
266
|
+
HASNA_EVENT_SUBJECT: event.subject ?? "",
|
|
267
|
+
HASNA_EVENT_SEVERITY: event.severity,
|
|
268
|
+
HASNA_EVENT_TIME: event.time,
|
|
269
|
+
HASNA_EVENT_DEDUPE_KEY: event.dedupeKey ?? "",
|
|
270
|
+
HASNA_EVENT_SCHEMA_VERSION: event.schemaVersion,
|
|
271
|
+
HASNA_EVENT_JSON: eventJson
|
|
272
|
+
};
|
|
273
|
+
return new Promise((resolve) => {
|
|
274
|
+
const child = spawn(channel.command.command, channel.command.args ?? [], {
|
|
275
|
+
cwd: channel.command.cwd,
|
|
276
|
+
env,
|
|
277
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
278
|
+
});
|
|
279
|
+
let stdout = "";
|
|
280
|
+
let stderr = "";
|
|
281
|
+
const timeout = setTimeout(() => child.kill("SIGTERM"), channel.command.timeoutMs ?? 15000);
|
|
282
|
+
child.stdin.end(eventJson);
|
|
283
|
+
child.stdout.on("data", (chunk) => {
|
|
284
|
+
stdout += chunk.toString();
|
|
285
|
+
});
|
|
286
|
+
child.stderr.on("data", (chunk) => {
|
|
287
|
+
stderr += chunk.toString();
|
|
288
|
+
});
|
|
289
|
+
child.on("error", (error) => {
|
|
290
|
+
clearTimeout(timeout);
|
|
291
|
+
resolve({
|
|
292
|
+
attempt: 1,
|
|
293
|
+
status: "failed",
|
|
294
|
+
startedAt,
|
|
295
|
+
completedAt: now(),
|
|
296
|
+
stdout: truncate(stdout),
|
|
297
|
+
stderr: truncate(stderr),
|
|
298
|
+
error: error.message
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
child.on("close", (code, signal) => {
|
|
302
|
+
clearTimeout(timeout);
|
|
303
|
+
const success = code === 0;
|
|
304
|
+
resolve({
|
|
305
|
+
attempt: 1,
|
|
306
|
+
status: success ? "success" : "failed",
|
|
307
|
+
startedAt,
|
|
308
|
+
completedAt: now(),
|
|
309
|
+
stdout: truncate(stdout),
|
|
310
|
+
stderr: truncate(stderr),
|
|
311
|
+
error: success ? undefined : `Command exited with ${signal ? `signal ${signal}` : `code ${code}`}`
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
async function dispatchChannel(event, channel, options = {}) {
|
|
317
|
+
if (channel.transport === "webhook")
|
|
318
|
+
return dispatchWebhook(event, channel, options);
|
|
319
|
+
if (channel.transport === "command")
|
|
320
|
+
return dispatchCommand(event, channel);
|
|
321
|
+
return {
|
|
322
|
+
attempt: 1,
|
|
323
|
+
status: "skipped",
|
|
324
|
+
startedAt: now(),
|
|
325
|
+
completedAt: now(),
|
|
326
|
+
error: `Unsupported transport: ${channel.transport}`
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
function createDeliveryResult(event, channel, attempts) {
|
|
330
|
+
const status = attempts.some((attempt) => attempt.status === "success") ? "success" : attempts.every((attempt) => attempt.status === "skipped") ? "skipped" : "failed";
|
|
331
|
+
return {
|
|
332
|
+
id: randomUUID(),
|
|
333
|
+
eventId: event.id,
|
|
334
|
+
channelId: channel.id,
|
|
335
|
+
transport: channel.transport,
|
|
336
|
+
status,
|
|
337
|
+
attempts,
|
|
338
|
+
createdAt: attempts[0]?.startedAt ?? now(),
|
|
339
|
+
completedAt: attempts.at(-1)?.completedAt ?? now()
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
// src/index.ts
|
|
343
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
344
|
+
function createEvent(input) {
|
|
345
|
+
return {
|
|
346
|
+
id: input.id ?? randomUUID2(),
|
|
347
|
+
source: input.source,
|
|
348
|
+
type: input.type,
|
|
349
|
+
time: normalizeTime(input.time),
|
|
350
|
+
subject: input.subject,
|
|
351
|
+
severity: input.severity ?? "info",
|
|
352
|
+
data: input.data ?? {},
|
|
353
|
+
message: input.message,
|
|
354
|
+
dedupeKey: input.dedupeKey,
|
|
355
|
+
schemaVersion: input.schemaVersion ?? "1.0",
|
|
356
|
+
metadata: input.metadata ?? {}
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
class EventsClient {
|
|
361
|
+
store;
|
|
362
|
+
redactors;
|
|
363
|
+
transportOptions;
|
|
364
|
+
constructor(options = {}) {
|
|
365
|
+
this.store = options.store ?? new JsonEventsStore(options.dataDir);
|
|
366
|
+
this.redactors = options.redactors ?? [];
|
|
367
|
+
this.transportOptions = { fetchImpl: options.fetchImpl };
|
|
368
|
+
}
|
|
369
|
+
async addChannel(input) {
|
|
370
|
+
const timestamp = new Date().toISOString();
|
|
371
|
+
return this.store.addChannel({
|
|
372
|
+
...input,
|
|
373
|
+
createdAt: input.createdAt ?? timestamp,
|
|
374
|
+
updatedAt: input.updatedAt ?? timestamp
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
async listChannels() {
|
|
378
|
+
return this.store.listChannels();
|
|
379
|
+
}
|
|
380
|
+
async removeChannel(id) {
|
|
381
|
+
return this.store.removeChannel(id);
|
|
382
|
+
}
|
|
383
|
+
async emit(input, options = {}) {
|
|
384
|
+
const event = createEvent(input);
|
|
385
|
+
if (options.dedupe !== false) {
|
|
386
|
+
const existing = await this.store.findEventByIdentity({ id: input.id, dedupeKey: event.dedupeKey });
|
|
387
|
+
if (existing) {
|
|
388
|
+
return { event: existing, deliveries: [], deduped: true };
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
await this.store.appendEvent(event);
|
|
392
|
+
const deliveries = options.deliver === false ? [] : await this.deliver(event);
|
|
393
|
+
return { event, deliveries, deduped: false };
|
|
394
|
+
}
|
|
395
|
+
async listEvents() {
|
|
396
|
+
return this.store.listEvents();
|
|
397
|
+
}
|
|
398
|
+
async listDeliveries() {
|
|
399
|
+
return this.store.listDeliveries();
|
|
400
|
+
}
|
|
401
|
+
async deliver(event) {
|
|
402
|
+
const channels = await this.store.listChannels();
|
|
403
|
+
const selected = channels.filter((channel) => channelMatchesEvent(channel, event));
|
|
404
|
+
const deliveries = [];
|
|
405
|
+
for (const channel of selected) {
|
|
406
|
+
const eventForChannel = await this.applyRedaction(event, channel);
|
|
407
|
+
const result = await this.deliverWithRetry(eventForChannel, channel);
|
|
408
|
+
await this.store.appendDelivery(result);
|
|
409
|
+
deliveries.push(result);
|
|
410
|
+
}
|
|
411
|
+
return deliveries;
|
|
412
|
+
}
|
|
413
|
+
async testChannel(id, input = {}) {
|
|
414
|
+
const channel = await this.store.getChannel(id);
|
|
415
|
+
if (!channel)
|
|
416
|
+
throw new Error(`Channel not found: ${id}`);
|
|
417
|
+
const event = createEvent({
|
|
418
|
+
source: input.source ?? "hasna.events",
|
|
419
|
+
type: input.type ?? "events.test",
|
|
420
|
+
subject: input.subject ?? id,
|
|
421
|
+
severity: input.severity ?? "info",
|
|
422
|
+
data: input.data ?? { test: true },
|
|
423
|
+
message: input.message ?? "Hasna events test delivery",
|
|
424
|
+
dedupeKey: input.dedupeKey,
|
|
425
|
+
schemaVersion: input.schemaVersion,
|
|
426
|
+
metadata: input.metadata,
|
|
427
|
+
time: input.time,
|
|
428
|
+
id: input.id
|
|
429
|
+
});
|
|
430
|
+
const eventForChannel = await this.applyRedaction(event, channel);
|
|
431
|
+
const result = await this.deliverWithRetry(eventForChannel, channel);
|
|
432
|
+
await this.store.appendDelivery(result);
|
|
433
|
+
return result;
|
|
434
|
+
}
|
|
435
|
+
async replay(options = {}) {
|
|
436
|
+
const events = (await this.store.listEvents()).filter((event) => {
|
|
437
|
+
if (options.eventId && event.id !== options.eventId)
|
|
438
|
+
return false;
|
|
439
|
+
if (options.source && event.source !== options.source)
|
|
440
|
+
return false;
|
|
441
|
+
if (options.type && event.type !== options.type)
|
|
442
|
+
return false;
|
|
443
|
+
return true;
|
|
444
|
+
});
|
|
445
|
+
if (options.dryRun)
|
|
446
|
+
return { events, deliveries: [] };
|
|
447
|
+
const deliveries = [];
|
|
448
|
+
for (const event of events) {
|
|
449
|
+
deliveries.push(...await this.deliver(event));
|
|
450
|
+
}
|
|
451
|
+
return { events, deliveries };
|
|
452
|
+
}
|
|
453
|
+
async applyRedaction(event, channel) {
|
|
454
|
+
let next = redactPaths(event, channel.redact?.paths ?? [], channel.redact?.replacement ?? "[REDACTED]");
|
|
455
|
+
for (const redactor of this.redactors) {
|
|
456
|
+
next = await redactor(next, channel);
|
|
457
|
+
}
|
|
458
|
+
return next;
|
|
459
|
+
}
|
|
460
|
+
async deliverWithRetry(event, channel) {
|
|
461
|
+
const policy = normalizeRetryPolicy(channel.retry);
|
|
462
|
+
const attempts = [];
|
|
463
|
+
for (let index = 0;index < policy.maxAttempts; index += 1) {
|
|
464
|
+
const attempt = await dispatchChannel(event, channel, this.transportOptions);
|
|
465
|
+
attempt.attempt = index + 1;
|
|
466
|
+
if (attempt.status === "failed" && index + 1 < policy.maxAttempts) {
|
|
467
|
+
attempt.nextBackoffMs = Math.round(policy.backoffMs * policy.multiplier ** index);
|
|
468
|
+
}
|
|
469
|
+
attempts.push(attempt);
|
|
470
|
+
if (attempt.status !== "failed")
|
|
471
|
+
break;
|
|
472
|
+
if (attempt.nextBackoffMs)
|
|
473
|
+
await Bun.sleep(attempt.nextBackoffMs);
|
|
474
|
+
}
|
|
475
|
+
return createDeliveryResult(event, channel, attempts);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function redactPaths(event, paths, replacement = "[REDACTED]") {
|
|
479
|
+
if (paths.length === 0)
|
|
480
|
+
return event;
|
|
481
|
+
const copy = structuredClone(event);
|
|
482
|
+
for (const path of paths) {
|
|
483
|
+
setPath(copy, path, replacement);
|
|
484
|
+
}
|
|
485
|
+
return copy;
|
|
486
|
+
}
|
|
487
|
+
function sanitizeChannelForOutput(channel) {
|
|
488
|
+
const copy = structuredClone(channel);
|
|
489
|
+
if (copy.webhook?.secret)
|
|
490
|
+
copy.webhook.secret = "[REDACTED]";
|
|
491
|
+
if (copy.command?.env) {
|
|
492
|
+
copy.command.env = Object.fromEntries(Object.entries(copy.command.env).map(([key, value]) => [key, shouldRedactKey(key) ? "[REDACTED]" : value]));
|
|
493
|
+
}
|
|
494
|
+
return copy;
|
|
495
|
+
}
|
|
496
|
+
function sanitizeChannelsForOutput(channels) {
|
|
497
|
+
return channels.map(sanitizeChannelForOutput);
|
|
498
|
+
}
|
|
499
|
+
function shouldRedactKey(key) {
|
|
500
|
+
return /secret|token|password|api[_-]?key|authorization/i.test(key);
|
|
501
|
+
}
|
|
502
|
+
function setPath(input, path, replacement) {
|
|
503
|
+
const parts = path.split(".");
|
|
504
|
+
let cursor = input;
|
|
505
|
+
for (const part of parts.slice(0, -1)) {
|
|
506
|
+
const next = cursor[part];
|
|
507
|
+
if (!next || typeof next !== "object")
|
|
508
|
+
return;
|
|
509
|
+
cursor = next;
|
|
510
|
+
}
|
|
511
|
+
const last = parts.at(-1);
|
|
512
|
+
if (last && last in cursor)
|
|
513
|
+
cursor[last] = replacement;
|
|
514
|
+
}
|
|
515
|
+
function normalizeTime(value) {
|
|
516
|
+
if (!value)
|
|
517
|
+
return new Date().toISOString();
|
|
518
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
519
|
+
}
|
|
520
|
+
function normalizeRetryPolicy(policy) {
|
|
521
|
+
return {
|
|
522
|
+
maxAttempts: Math.max(1, policy?.maxAttempts ?? 1),
|
|
523
|
+
backoffMs: Math.max(0, policy?.backoffMs ?? 250),
|
|
524
|
+
multiplier: Math.max(1, policy?.multiplier ?? 2)
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
export {
|
|
528
|
+
verifyWebhookSignature,
|
|
529
|
+
verifyPayloadSignature,
|
|
530
|
+
signPayload,
|
|
531
|
+
sanitizeChannelsForOutput,
|
|
532
|
+
sanitizeChannelForOutput,
|
|
533
|
+
redactPaths,
|
|
534
|
+
matchString,
|
|
535
|
+
isTimestampWithinTolerance,
|
|
536
|
+
getEventsDataDir,
|
|
537
|
+
eventMatchesFilter,
|
|
538
|
+
dispatchWebhook,
|
|
539
|
+
dispatchCommand,
|
|
540
|
+
dispatchChannel,
|
|
541
|
+
createEvent,
|
|
542
|
+
createDeliveryResult,
|
|
543
|
+
channelMatchesEvent,
|
|
544
|
+
buildWebhookRequest,
|
|
545
|
+
buildSignatureBase,
|
|
546
|
+
JsonEventsStore,
|
|
547
|
+
HASNA_EVENTS_HOME_ENV,
|
|
548
|
+
HASNA_EVENTS_DIR_ENV,
|
|
549
|
+
EventsClient
|
|
550
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface SignatureVerificationOptions {
|
|
2
|
+
toleranceMs?: number;
|
|
3
|
+
now?: number | Date;
|
|
4
|
+
}
|
|
5
|
+
export declare function buildSignatureBase(timestamp: string, body: string): string;
|
|
6
|
+
export declare function signPayload(secret: string, timestamp: string, body: string): string;
|
|
7
|
+
export declare function verifyPayloadSignature(secret: string, timestamp: string, body: string, signature: string): boolean;
|
|
8
|
+
export declare function isTimestampWithinTolerance(timestamp: string, toleranceMs: number, now?: number | Date): boolean;
|
|
9
|
+
export declare function verifyWebhookSignature(secret: string, timestamp: string, body: string, signature: string, options?: SignatureVerificationOptions): boolean;
|
package/dist/signing.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/signing.ts
|
|
3
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
4
|
+
function buildSignatureBase(timestamp, body) {
|
|
5
|
+
return `${timestamp}.${body}`;
|
|
6
|
+
}
|
|
7
|
+
function signPayload(secret, timestamp, body) {
|
|
8
|
+
const digest = createHmac("sha256", secret).update(buildSignatureBase(timestamp, body)).digest("hex");
|
|
9
|
+
return `sha256=${digest}`;
|
|
10
|
+
}
|
|
11
|
+
function verifyPayloadSignature(secret, timestamp, body, signature) {
|
|
12
|
+
const expected = signPayload(secret, timestamp, body);
|
|
13
|
+
const actual = signature.trim();
|
|
14
|
+
const expectedBuffer = Buffer.from(expected);
|
|
15
|
+
const actualBuffer = Buffer.from(actual);
|
|
16
|
+
if (expectedBuffer.length !== actualBuffer.length)
|
|
17
|
+
return false;
|
|
18
|
+
return timingSafeEqual(expectedBuffer, actualBuffer);
|
|
19
|
+
}
|
|
20
|
+
function isTimestampWithinTolerance(timestamp, toleranceMs, now = Date.now()) {
|
|
21
|
+
const parsed = Date.parse(timestamp);
|
|
22
|
+
if (!Number.isFinite(parsed))
|
|
23
|
+
return false;
|
|
24
|
+
const reference = now instanceof Date ? now.getTime() : now;
|
|
25
|
+
return Math.abs(reference - parsed) <= toleranceMs;
|
|
26
|
+
}
|
|
27
|
+
function verifyWebhookSignature(secret, timestamp, body, signature, options = {}) {
|
|
28
|
+
if (options.toleranceMs !== undefined && !isTimestampWithinTolerance(timestamp, options.toleranceMs, options.now)) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
return verifyPayloadSignature(secret, timestamp, body, signature);
|
|
32
|
+
}
|
|
33
|
+
export {
|
|
34
|
+
verifyWebhookSignature,
|
|
35
|
+
verifyPayloadSignature,
|
|
36
|
+
signPayload,
|
|
37
|
+
isTimestampWithinTolerance,
|
|
38
|
+
buildSignatureBase
|
|
39
|
+
};
|