Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .husky/post-checkout
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-checkout "$@"
3 changes: 3 additions & 0 deletions .husky/post-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-commit' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-commit "$@"
3 changes: 3 additions & 0 deletions .husky/post-merge
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-merge' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-merge "$@"
3 changes: 3 additions & 0 deletions .husky/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs pre-push "$@"
60 changes: 60 additions & 0 deletions apps/api/src/analytics/ml/detector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { FeatureVector, AnomalyResult } from "./types";

type Stats = {
mean: FeatureVector;
std: FeatureVector;
};

function zScore(value: number, mean: number, std: number) {
if (std === 0) return 0;
return (value - mean) / std;
}

export class MLDetector {
private stats: Stats;

constructor(trainingData: FeatureVector[]) {
this.stats = this.computeStats(trainingData);
}

private computeStats(data: FeatureVector[]): Stats {
const keys: (keyof FeatureVector)[] = [
"frequency",
"timeGapAvg",
"errorRate",
];

const mean: any = {};
const std: any = {};

for (const key of keys) {
const values = data.map((d) => d[key]);
const avg = values.reduce((a, b) => a + b, 0) / values.length;

mean[key] = avg;

const variance =
values.reduce((a, b) => a + Math.pow(b - avg, 2), 0) /
values.length;

std[key] = Math.sqrt(variance);
}

return { mean, std };
}

public predict(userId: string, input: FeatureVector): AnomalyResult {
const score =
Math.abs(zScore(input.frequency, this.stats.mean.frequency, this.stats.std.frequency)) +
Math.abs(zScore(input.timeGapAvg, this.stats.mean.timeGapAvg, this.stats.std.timeGapAvg)) +
Math.abs(zScore(input.errorRate, this.stats.mean.errorRate, this.stats.std.errorRate));

const isAnomaly = score > 3; // threshold (tunable)

return {
userId,
score,
isAnomaly,
};
}
}
26 changes: 26 additions & 0 deletions apps/api/src/analytics/ml/feature-extractor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { EventRecord, FeatureVector } from "./types";

export function extractFeatures(events: EventRecord[]): FeatureVector {
if (!events.length) {
return { frequency: 0, timeGapAvg: 0, errorRate: 0 };
}

const sorted = [...events].sort((a, b) => a.timestamp - b.timestamp);

let gaps: number[] = [];
let errors = 0;

for (let i = 1; i < sorted.length; i++) {
gaps.push(sorted[i].timestamp - sorted[i - 1].timestamp);
}

for (const e of events) {
if (e.metadata?.error === true) errors++;
}

return {
frequency: events.length,
timeGapAvg: gaps.length ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0,
errorRate: errors / events.length,
};
}
23 changes: 23 additions & 0 deletions apps/api/src/analytics/ml/pipeline-hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { MLDetector } from "./detector";
import { extractFeatures } from "./feature-extractor";
import { EventRecord } from "./types";

export class AnalysisMLPipeline {
private detector: MLDetector;

constructor(trainingData: any[]) {
this.detector = new MLDetector(trainingData);
}

run(userId: string, events: EventRecord[]) {
const features = extractFeatures(events);

const result = this.detector.predict(userId, features);

return {
userId,
features,
anomaly: result,
};
}
}
18 changes: 18 additions & 0 deletions apps/api/src/analytics/ml/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export type EventRecord = {
userId: string;
action: string;
timestamp: number;
metadata?: Record<string, any>;
};

export type FeatureVector = {
frequency: number;
timeGapAvg: number;
errorRate: number;
};

export type AnomalyResult = {
userId: string;
score: number;
isAnomaly: boolean;
};
36 changes: 36 additions & 0 deletions apps/api/src/integrations/discord.provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NotificationPayload } from "./types";

export class DiscordProvider {
constructor(private webhookUrl: string) {}

async send(payload: NotificationPayload) {
const { scan } = payload;

const color =
scan.severity === "critical"
? 16711680
: scan.severity === "warning"
? 16753920
: 3447003;

const message = {
embeds: [
{
title: `📡 Scan Alert: ${scan.title}`,
description: scan.message,
color,
timestamp: new Date(scan.timestamp).toISOString(),
footer: {
text: "GasGuard Scanner",
},
},
],
};

await fetch(this.webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(message),
});
}
}
35 changes: 35 additions & 0 deletions apps/api/src/integrations/notifier.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { SlackProvider } from "./slack.provider";
import { DiscordProvider } from "./discord.provider";
import { NotificationPayload, ScanResult } from "./types";

export class NotifierService {
private slack?: SlackProvider;
private discord?: DiscordProvider;

constructor() {
const slackUrl = process.env.SLACK_WEBHOOK_URL;
const discordUrl = process.env.DISCORD_WEBHOOK_URL;

if (slackUrl) this.slack = new SlackProvider(slackUrl);
if (discordUrl) this.discord = new DiscordProvider(discordUrl);
}

async notify(scan: ScanResult, source?: string) {
const payload: NotificationPayload = {
scan,
source,
};

const tasks: Promise<any>[] = [];

if (this.slack) {
tasks.push(this.slack.send(payload));
}

if (this.discord) {
tasks.push(this.discord.send(payload));
}

await Promise.allSettled(tasks);
}
}
34 changes: 34 additions & 0 deletions apps/api/src/integrations/slack.provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { NotificationPayload } from "./types";

export class SlackProvider {
constructor(private webhookUrl: string) {}

async send(payload: NotificationPayload) {
const { scan } = payload;

const color =
scan.severity === "critical"
? "#ff0000"
: scan.severity === "warning"
? "#ffa500"
: "#36a64f";

const message = {
attachments: [
{
color,
title: `📡 Scan Alert: ${scan.title}`,
text: scan.message,
footer: "GasGuard Scanner",
ts: Math.floor(scan.timestamp / 1000),
},
],
};

await fetch(this.webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(message),
});
}
}
14 changes: 14 additions & 0 deletions apps/api/src/integrations/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export type ScanSeverity = "info" | "warning" | "critical";

export type ScanResult = {
id: string;
title: string;
message: string;
severity: ScanSeverity;
timestamp: number;
};

export type NotificationPayload = {
scan: ScanResult;
source?: string;
};
Loading
Loading