fase(5): findings module complete
Some checks failed
ABE Exploratory Testing / explore (push) Has been cancelled

This commit is contained in:
debian
2026-03-05 04:06:45 -05:00
parent 96bf6e5097
commit d62bd615bf
55 changed files with 2424 additions and 48 deletions

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateFindingCommand = void 0;
const Result_1 = require("../../../../shared/domain/Result");
const Finding_1 = require("../../domain/entities/Finding");
const Severity_1 = require("../../domain/value-objects/Severity");
const FindingType_1 = require("../../domain/value-objects/FindingType");
const Evidence_1 = require("../../domain/value-objects/Evidence");
class CreateFindingCommand {
constructor(repository, eventBus) {
this.repository = repository;
this.eventBus = eventBus;
}
async execute(request) {
let severity;
let type;
try {
severity = Severity_1.Severity.fromString(request.anomaly.severity);
type = FindingType_1.FindingType.fromString(request.anomaly.type);
}
catch (e) {
return (0, Result_1.Err)(e instanceof Error ? e.message : String(e));
}
const evidence = Evidence_1.Evidence.create({
screenshotPath: request.anomaly.evidence.screenshotPath,
domSnapshotPath: request.anomaly.evidence.domSnapshotPath,
httpLog: request.anomaly.evidence.httpLog,
rawErrors: request.anomaly.evidence.rawErrors,
});
const finding = Finding_1.Finding.create({
sessionId: request.sessionId,
severity,
type,
description: request.anomaly.description,
evidence,
actionTrace: request.anomaly.actionTrace,
browser: request.anomaly.browser,
browserVersion: request.anomaly.browserVersion,
aiEnrichment: request.anomaly.aiEnrichment,
});
await this.repository.save(finding);
const events = finding.domainEvents;
for (const event of events) {
await this.eventBus.publish(event);
}
finding.clearEvents();
return (0, Result_1.Ok)({ findingId: finding.id.toString() });
}
}
exports.CreateFindingCommand = CreateFindingCommand;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnrichFindingCommand = void 0;
const Result_1 = require("../../../../shared/domain/Result");
class EnrichFindingCommand {
constructor(repository, enricher, eventBus) {
this.repository = repository;
this.enricher = enricher;
this.eventBus = eventBus;
}
async execute(request) {
const finding = await this.repository.findById(request.findingId);
if (!finding) {
return (0, Result_1.Err)(`Finding not found: ${request.findingId}`);
}
let enrichment;
try {
enrichment = await this.enricher.enrich(finding);
}
catch (e) {
return (0, Result_1.Err)(`Enrichment failed: ${e instanceof Error ? e.message : String(e)}`);
}
finding.enrich(enrichment);
await this.repository.update(finding);
const events = finding.domainEvents;
for (const event of events) {
await this.eventBus.publish(event);
}
finding.clearEvents();
return (0, Result_1.Ok)({ findingId: finding.id.toString() });
}
}
exports.EnrichFindingCommand = EnrichFindingCommand;

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResolveFindingCommand = void 0;
const Result_1 = require("../../../../shared/domain/Result");
class ResolveFindingCommand {
constructor(repository, eventBus) {
this.repository = repository;
this.eventBus = eventBus;
}
async execute(request) {
const finding = await this.repository.findById(request.findingId);
if (!finding) {
return (0, Result_1.Err)(`Finding not found: ${request.findingId}`);
}
switch (request.action) {
case 'resolve':
finding.resolve();
break;
case 'close':
finding.close();
break;
case 'investigate':
finding.investigate();
break;
}
await this.repository.update(finding);
const events = finding.domainEvents;
for (const event of events) {
await this.eventBus.publish(event);
}
finding.clearEvents();
return (0, Result_1.Ok)({ findingId: finding.id.toString(), status: finding.status.value });
}
}
exports.ResolveFindingCommand = ResolveFindingCommand;

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OnAnomalyDetected = void 0;
/**
* Listens for anomaly_detected events from crawling module
* and creates a Finding in the findings module.
*/
class OnAnomalyDetected {
constructor(createFinding) {
this.createFinding = createFinding;
}
async handle(event) {
const payload = event.payload;
if (!payload.anomaly || !payload.sessionId)
return;
await this.createFinding.execute({
anomaly: payload.anomaly,
sessionId: payload.sessionId,
});
}
}
exports.OnAnomalyDetected = OnAnomalyDetected;

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindingStatsQuery = void 0;
const Result_1 = require("../../../../shared/domain/Result");
class FindingStatsQuery {
constructor(repository) {
this.repository = repository;
}
async execute(request) {
const [total, bySeverity, openCount, resolvedCount] = await Promise.all([
this.repository.count(request.sessionId ? { sessionId: request.sessionId } : undefined),
this.repository.countBySeverity(),
this.repository.count({ status: 'open', sessionId: request.sessionId }),
this.repository.count({ status: 'resolved', sessionId: request.sessionId }),
]);
return (0, Result_1.Ok)({ total, bySeverity, openCount, resolvedCount });
}
}
exports.FindingStatsQuery = FindingStatsQuery;

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetFindingQuery = void 0;
const Result_1 = require("../../../../shared/domain/Result");
class GetFindingQuery {
constructor(repository) {
this.repository = repository;
}
async execute(request) {
const finding = await this.repository.findById(request.findingId);
if (!finding) {
return (0, Result_1.Err)(`Finding not found: ${request.findingId}`);
}
return (0, Result_1.Ok)(finding);
}
}
exports.GetFindingQuery = GetFindingQuery;

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListFindingsQuery = void 0;
const Result_1 = require("../../../../shared/domain/Result");
class ListFindingsQuery {
constructor(repository) {
this.repository = repository;
}
async execute(request) {
const filters = {
sessionId: request.sessionId,
severity: request.severity,
type: request.type,
status: request.status,
search: request.search,
};
const findings = await this.repository.findAll(filters);
const total = await this.repository.count(filters);
return (0, Result_1.Ok)({ findings, total });
}
}
exports.ListFindingsQuery = ListFindingsQuery;

View File

@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Finding = void 0;
const AggregateRoot_1 = require("../../../../shared/domain/AggregateRoot");
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
const FindingStatus_1 = require("../value-objects/FindingStatus");
const FindingCreated_1 = require("../events/FindingCreated");
const FindingResolved_1 = require("../events/FindingResolved");
const FindingEnriched_1 = require("../events/FindingEnriched");
class Finding extends AggregateRoot_1.AggregateRoot {
static create(props, id) {
const findingId = id ?? UniqueId_1.UniqueId.create();
const finding = new Finding({
...props,
status: FindingStatus_1.FindingStatus.open(),
createdAt: new Date(),
}, findingId);
finding.addDomainEvent(new FindingCreated_1.FindingCreated(findingId.toString(), {
sessionId: props.sessionId,
severity: props.severity.value,
type: props.type.value,
description: props.description,
}));
return finding;
}
static reconstitute(props, id) {
return new Finding(props, id);
}
get sessionId() { return this.props.sessionId; }
get severity() { return this.props.severity; }
get type() { return this.props.type; }
get description() { return this.props.description; }
get evidence() { return this.props.evidence; }
get status() { return this.props.status; }
get actionTrace() { return this.props.actionTrace; }
get browser() { return this.props.browser; }
get browserVersion() { return this.props.browserVersion; }
get aiEnrichment() { return this.props.aiEnrichment; }
get createdAt() { return this.props.createdAt; }
get resolvedAt() { return this.props.resolvedAt; }
resolve() {
this.props.status = FindingStatus_1.FindingStatus.resolved();
this.props.resolvedAt = new Date();
this.addDomainEvent(new FindingResolved_1.FindingResolved(this.id.toString(), {
sessionId: this.props.sessionId,
resolvedAt: this.props.resolvedAt.toISOString(),
}));
}
close() {
this.props.status = FindingStatus_1.FindingStatus.closed();
}
investigate() {
this.props.status = FindingStatus_1.FindingStatus.investigating();
}
enrich(enrichment) {
this.props.aiEnrichment = enrichment;
this.addDomainEvent(new FindingEnriched_1.FindingEnriched(this.id.toString(), {
provider: enrichment.provider,
model: enrichment.model,
confidence: enrichment.confidence,
}));
}
}
exports.Finding = Finding;

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindingCreated = void 0;
const crypto_1 = require("crypto");
class FindingCreated {
constructor(aggregateId, payload) {
this.aggregateId = aggregateId;
this.payload = payload;
this.eventId = (0, crypto_1.randomUUID)();
this.eventName = 'finding.created';
this.occurredOn = new Date();
}
}
exports.FindingCreated = FindingCreated;

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindingEnriched = void 0;
const crypto_1 = require("crypto");
class FindingEnriched {
constructor(aggregateId, payload) {
this.aggregateId = aggregateId;
this.payload = payload;
this.eventId = (0, crypto_1.randomUUID)();
this.eventName = 'finding.enriched';
this.occurredOn = new Date();
}
}
exports.FindingEnriched = FindingEnriched;

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindingResolved = void 0;
const crypto_1 = require("crypto");
class FindingResolved {
constructor(aggregateId, payload) {
this.aggregateId = aggregateId;
this.payload = payload;
this.eventId = (0, crypto_1.randomUUID)();
this.eventName = 'finding.resolved';
this.occurredOn = new Date();
}
}
exports.FindingResolved = FindingResolved;

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Evidence = void 0;
const ValueObject_1 = require("../../../../shared/domain/ValueObject");
class Evidence extends ValueObject_1.ValueObject {
static create(props) {
return new Evidence(props);
}
static empty() {
return new Evidence({});
}
get screenshotPath() { return this.props.screenshotPath; }
get domSnapshotPath() { return this.props.domSnapshotPath; }
get httpLog() { return this.props.httpLog ?? []; }
get rawErrors() { return this.props.rawErrors ?? []; }
toJSON() {
return {
screenshotPath: this.props.screenshotPath,
domSnapshotPath: this.props.domSnapshotPath,
httpLog: this.props.httpLog,
rawErrors: this.props.rawErrors,
};
}
}
exports.Evidence = Evidence;

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindingStatus = void 0;
const ValueObject_1 = require("../../../../shared/domain/ValueObject");
class FindingStatus extends ValueObject_1.ValueObject {
static open() { return new FindingStatus({ value: 'open' }); }
static investigating() { return new FindingStatus({ value: 'investigating' }); }
static resolved() { return new FindingStatus({ value: 'resolved' }); }
static closed() { return new FindingStatus({ value: 'closed' }); }
static fromString(s) {
if (!FindingStatus.VALUES.includes(s)) {
throw new Error(`Invalid finding status: ${s}`);
}
return new FindingStatus({ value: s });
}
get value() { return this.props.value; }
isOpen() { return this.props.value === 'open'; }
isResolved() { return this.props.value === 'resolved'; }
}
exports.FindingStatus = FindingStatus;
FindingStatus.VALUES = ['open', 'investigating', 'resolved', 'closed'];

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindingType = void 0;
const ValueObject_1 = require("../../../../shared/domain/ValueObject");
class FindingType extends ValueObject_1.ValueObject {
static fromString(s) {
if (!FindingType.TYPES.includes(s)) {
throw new Error(`Invalid finding type: ${s}`);
}
return new FindingType({ value: s });
}
get value() { return this.props.value; }
}
exports.FindingType = FindingType;
FindingType.TYPES = [
'http_error',
'js_exception',
'console_error',
'navigation_fail',
'element_missing',
'timeout',
'validation_bypass',
'server_error_on_fuzz',
'xss_reflection',
'visual_regression',
'accessibility_violation',
'mobile_layout_issue',
'performance_degradation',
'offline_handling_missing',
'slow_network_no_feedback',
'external_service_crash',
];

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Severity = void 0;
const ValueObject_1 = require("../../../../shared/domain/ValueObject");
class Severity extends ValueObject_1.ValueObject {
static low() { return new Severity({ value: 'low' }); }
static medium() { return new Severity({ value: 'medium' }); }
static high() { return new Severity({ value: 'high' }); }
static critical() { return new Severity({ value: 'critical' }); }
static fromString(s) {
if (!Severity.LEVELS.includes(s)) {
throw new Error(`Invalid severity: ${s}`);
}
return new Severity({ value: s });
}
get value() { return this.props.value; }
}
exports.Severity = Severity;
Severity.LEVELS = ['low', 'medium', 'high', 'critical'];

47
dist/modules/findings/index.js vendored Normal file
View File

@@ -0,0 +1,47 @@
"use strict";
// Findings Module — Public API
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFindingsRouter = exports.PlaywrightScriptExporter = exports.JSONExporter = exports.MarkdownExporter = exports.KyselyFindingRepository = exports.OnAnomalyDetected = exports.FindingStatsQuery = exports.ListFindingsQuery = exports.GetFindingQuery = exports.ResolveFindingCommand = exports.EnrichFindingCommand = exports.CreateFindingCommand = exports.FindingEnriched = exports.FindingResolved = exports.FindingCreated = exports.Evidence = exports.FindingStatus = exports.FindingType = exports.Severity = exports.Finding = void 0;
// Domain
var Finding_1 = require("./domain/entities/Finding");
Object.defineProperty(exports, "Finding", { enumerable: true, get: function () { return Finding_1.Finding; } });
var Severity_1 = require("./domain/value-objects/Severity");
Object.defineProperty(exports, "Severity", { enumerable: true, get: function () { return Severity_1.Severity; } });
var FindingType_1 = require("./domain/value-objects/FindingType");
Object.defineProperty(exports, "FindingType", { enumerable: true, get: function () { return FindingType_1.FindingType; } });
var FindingStatus_1 = require("./domain/value-objects/FindingStatus");
Object.defineProperty(exports, "FindingStatus", { enumerable: true, get: function () { return FindingStatus_1.FindingStatus; } });
var Evidence_1 = require("./domain/value-objects/Evidence");
Object.defineProperty(exports, "Evidence", { enumerable: true, get: function () { return Evidence_1.Evidence; } });
var FindingCreated_1 = require("./domain/events/FindingCreated");
Object.defineProperty(exports, "FindingCreated", { enumerable: true, get: function () { return FindingCreated_1.FindingCreated; } });
var FindingResolved_1 = require("./domain/events/FindingResolved");
Object.defineProperty(exports, "FindingResolved", { enumerable: true, get: function () { return FindingResolved_1.FindingResolved; } });
var FindingEnriched_1 = require("./domain/events/FindingEnriched");
Object.defineProperty(exports, "FindingEnriched", { enumerable: true, get: function () { return FindingEnriched_1.FindingEnriched; } });
// Application
var CreateFindingCommand_1 = require("./application/commands/CreateFindingCommand");
Object.defineProperty(exports, "CreateFindingCommand", { enumerable: true, get: function () { return CreateFindingCommand_1.CreateFindingCommand; } });
var EnrichFindingCommand_1 = require("./application/commands/EnrichFindingCommand");
Object.defineProperty(exports, "EnrichFindingCommand", { enumerable: true, get: function () { return EnrichFindingCommand_1.EnrichFindingCommand; } });
var ResolveFindingCommand_1 = require("./application/commands/ResolveFindingCommand");
Object.defineProperty(exports, "ResolveFindingCommand", { enumerable: true, get: function () { return ResolveFindingCommand_1.ResolveFindingCommand; } });
var GetFindingQuery_1 = require("./application/queries/GetFindingQuery");
Object.defineProperty(exports, "GetFindingQuery", { enumerable: true, get: function () { return GetFindingQuery_1.GetFindingQuery; } });
var ListFindingsQuery_1 = require("./application/queries/ListFindingsQuery");
Object.defineProperty(exports, "ListFindingsQuery", { enumerable: true, get: function () { return ListFindingsQuery_1.ListFindingsQuery; } });
var FindingStatsQuery_1 = require("./application/queries/FindingStatsQuery");
Object.defineProperty(exports, "FindingStatsQuery", { enumerable: true, get: function () { return FindingStatsQuery_1.FindingStatsQuery; } });
var OnAnomalyDetected_1 = require("./application/event-handlers/OnAnomalyDetected");
Object.defineProperty(exports, "OnAnomalyDetected", { enumerable: true, get: function () { return OnAnomalyDetected_1.OnAnomalyDetected; } });
// Infrastructure
var KyselyFindingRepository_1 = require("./infrastructure/repositories/KyselyFindingRepository");
Object.defineProperty(exports, "KyselyFindingRepository", { enumerable: true, get: function () { return KyselyFindingRepository_1.KyselyFindingRepository; } });
var MarkdownExporter_1 = require("./infrastructure/exporters/MarkdownExporter");
Object.defineProperty(exports, "MarkdownExporter", { enumerable: true, get: function () { return MarkdownExporter_1.MarkdownExporter; } });
var JSONExporter_1 = require("./infrastructure/exporters/JSONExporter");
Object.defineProperty(exports, "JSONExporter", { enumerable: true, get: function () { return JSONExporter_1.JSONExporter; } });
var PlaywrightScriptExporter_1 = require("./infrastructure/exporters/PlaywrightScriptExporter");
Object.defineProperty(exports, "PlaywrightScriptExporter", { enumerable: true, get: function () { return PlaywrightScriptExporter_1.PlaywrightScriptExporter; } });
var FindingsController_1 = require("./infrastructure/http/FindingsController");
Object.defineProperty(exports, "createFindingsRouter", { enumerable: true, get: function () { return FindingsController_1.createFindingsRouter; } });

View File

@@ -0,0 +1,94 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSONExporter = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
class JSONExporter {
constructor(targetUrl = '', abeVersion = '0.1.0') {
this.targetUrl = targetUrl;
this.abeVersion = abeVersion;
}
async export(finding, outputDir) {
fs.mkdirSync(outputDir, { recursive: true });
const report = {
version: '1.0',
generated_at: finding.createdAt.toISOString(),
environment: {
target_url: this.targetUrl,
abe_version: this.abeVersion,
os: os.platform(),
node_version: process.version,
},
finding: {
id: finding.id.toString(),
type: finding.type.value,
severity: finding.severity.value,
status: finding.status.value,
description: finding.description,
browser: finding.browser,
browser_version: finding.browserVersion,
},
reproduction: {
seed: finding.actionTrace[0]?.seed ?? null,
steps: finding.actionTrace.map((action, index) => ({
step: index + 1,
action_type: action.type,
selector: action.selector,
value: action.value,
url: action.url,
timestamp: action.timestamp,
})),
},
evidence: {
screenshot: finding.evidence.screenshotPath ?? null,
dom_snapshot: finding.evidence.domSnapshotPath ?? null,
http_log: finding.evidence.httpLog.map((r) => ({
url: r.url,
method: r.method,
status: r.status,
duration_ms: r.durationMs,
})),
raw_errors: finding.evidence.rawErrors,
},
ai_enrichment: finding.aiEnrichment ?? null,
};
const filePath = path.join(outputDir, 'report.json');
fs.writeFileSync(filePath, JSON.stringify(report, null, 2), 'utf8');
return filePath;
}
}
exports.JSONExporter = JSONExporter;

View File

@@ -0,0 +1,109 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownExporter = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class MarkdownExporter {
async export(finding, outputDir) {
fs.mkdirSync(outputDir, { recursive: true });
const date = finding.createdAt.toISOString().split('T')[0];
const seed = finding.actionTrace[0]?.seed ?? 'N/A';
const replayCmd = `npm run replay -- --report ${outputDir}/report.json`;
const steps = finding.actionTrace
.map((action, i) => {
switch (action.type) {
case 'navigate':
return `${i + 1}. Navigate to \`${action.url}\``;
case 'click':
return `${i + 1}. Click element \`${action.selector}\``;
case 'fill':
return `${i + 1}. Fill \`${action.selector}\` with \`${JSON.stringify(action.value ?? '')}\``;
case 'select':
return `${i + 1}. Select \`${action.value}\` in \`${action.selector}\``;
case 'submit':
return `${i + 1}. Submit form \`${action.selector}\``;
default:
return `${i + 1}. ${action.type}`;
}
})
.join('\n');
const httpTable = finding.evidence.httpLog.length > 0
? [
'| Method | URL | Status | Duration |',
'|--------|-----|--------|----------|',
...finding.evidence.httpLog.map((r) => `| ${r.method} | ${r.url} | ${r.status} | ${r.durationMs}ms |`),
].join('\n')
: '_No HTTP log available._';
const rawErrors = finding.evidence.rawErrors.length > 0
? '```\n' + finding.evidence.rawErrors.join('\n') + '\n```'
: '_No raw errors recorded._';
const md = `# Bug Report — ${finding.type.value}${date}
## Summary
${finding.description}
## Severity
**${finding.severity.value}** — detected by ABE heuristic rule \`${finding.type.value}\`
## Status
**${finding.status.value}**
## Reproduction Steps
${steps.length > 0 ? steps : '_No steps recorded._'}
**Seed used**: \`${seed}\`
**Replay command**: \`${replayCmd}\`
## Observed Behavior
${finding.description}
## Evidence
- Screenshot: \`${finding.evidence.screenshotPath ?? 'N/A'}\`
- DOM Snapshot: \`${finding.evidence.domSnapshotPath ?? 'N/A'}\`
- HTTP Log:
${httpTable}
## Raw Errors
${rawErrors}
`;
const filePath = path.join(outputDir, 'report.md');
fs.writeFileSync(filePath, md, 'utf8');
return filePath;
}
}
exports.MarkdownExporter = MarkdownExporter;

View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlaywrightScriptExporter = void 0;
class PlaywrightScriptExporter {
generate(finding) {
const trace = finding.actionTrace;
const lines = [
'// Auto-generated replay script by ABE (Autonomous Bug Explorer)',
`// Generated at: ${new Date().toISOString()}`,
`// Finding ID: ${finding.id.toString()}`,
`// Type: ${finding.type.value} | Severity: ${finding.severity.value}`,
`// Steps: ${trace.length}`,
'',
"const { chromium } = require('playwright');",
'',
'(async () => {',
' const browser = await chromium.launch({ headless: true });',
' const context = await browser.newContext();',
' const page = await context.newPage();',
'',
];
for (let i = 0; i < trace.length; i++) {
const action = trace[i];
lines.push(` // Step ${i + 1}: ${action.type} (seed=${action.seed})`);
switch (action.type) {
case 'navigate':
lines.push(` await page.goto(${JSON.stringify(action.url)});`);
break;
case 'click':
lines.push(` await page.locator(${JSON.stringify(action.selector)}).first().click();`);
break;
case 'fill':
lines.push(` await page.locator(${JSON.stringify(action.selector)}).first().fill(${JSON.stringify(action.value ?? '')});`);
break;
case 'select':
lines.push(` await page.locator(${JSON.stringify(action.selector)}).first().selectOption(${JSON.stringify(action.value ?? '')});`);
break;
case 'submit':
lines.push(` await page.locator(${JSON.stringify(action.selector)}).first().dispatchEvent('submit');`);
break;
}
lines.push('');
}
lines.push(" console.log('Replay complete');", ' await browser.close();', '})();');
return lines.join('\n');
}
}
exports.PlaywrightScriptExporter = PlaywrightScriptExporter;

View File

@@ -0,0 +1,131 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFindingsRouter = createFindingsRouter;
const express_1 = require("express");
const MarkdownExporter_1 = require("../exporters/MarkdownExporter");
const JSONExporter_1 = require("../exporters/JSONExporter");
const PlaywrightScriptExporter_1 = require("../exporters/PlaywrightScriptExporter");
const path_1 = __importDefault(require("path"));
function createFindingsRouter(deps) {
const router = (0, express_1.Router)();
const markdownExporter = new MarkdownExporter_1.MarkdownExporter();
const jsonExporter = new JSONExporter_1.JSONExporter();
const playwrightExporter = new PlaywrightScriptExporter_1.PlaywrightScriptExporter();
// GET /api/findings — list findings with filters
router.get('/', async (req, res) => {
const { sessionId, severity, type, status, search } = req.query;
const result = await deps.listFindings.execute({ sessionId, severity, type, status, search });
if (!result.ok) {
res.status(500).json({ error: result.error });
return;
}
const { findings, total } = result.value;
res.json({
findings: findings.map(f => toDTO(f)),
total,
});
});
// GET /api/findings/stats — aggregate stats
router.get('/stats', async (req, res) => {
const { sessionId } = req.query;
const result = await deps.findingStats.execute({ sessionId });
if (!result.ok) {
res.status(500).json({ error: result.error });
return;
}
res.json(result.value);
});
// GET /api/findings/:id — finding detail
router.get('/:id', async (req, res) => {
const findingId = req.params['id'];
const result = await deps.getFinding.execute({ findingId });
if (!result.ok) {
res.status(404).json({ error: result.error });
return;
}
res.json(toDTO(result.value));
});
// PATCH /api/findings/:id/status — update status
router.patch('/:id/status', async (req, res) => {
const findingId = req.params['id'];
const { action } = req.body;
if (!action || !['resolve', 'close', 'investigate'].includes(action)) {
res.status(400).json({ error: 'action must be one of: resolve, close, investigate' });
return;
}
const result = await deps.resolveFinding.execute({ findingId, action });
if (!result.ok) {
res.status(404).json({ error: result.error });
return;
}
res.json(result.value);
});
// POST /api/findings/:id/enrich — trigger AI enrichment
router.post('/:id/enrich', async (req, res) => {
const findingId = req.params['id'];
const result = await deps.enrichFinding.execute({ findingId });
if (!result.ok) {
res.status(422).json({ error: result.error });
return;
}
res.json(result.value);
});
// GET /api/findings/:id/export/markdown — download as Markdown
router.get('/:id/export/markdown', async (req, res) => {
const findingId = req.params['id'];
const result = await deps.getFinding.execute({ findingId });
if (!result.ok) {
res.status(404).json({ error: result.error });
return;
}
const outputDir = path_1.default.join(process.cwd(), 'reports', findingId);
const filePath = await markdownExporter.export(result.value, outputDir);
res.download(filePath, `finding-${findingId}.md`);
});
// GET /api/findings/:id/export/json — download as JSON
router.get('/:id/export/json', async (req, res) => {
const findingId = req.params['id'];
const result = await deps.getFinding.execute({ findingId });
if (!result.ok) {
res.status(404).json({ error: result.error });
return;
}
const outputDir = path_1.default.join(process.cwd(), 'reports', findingId);
const filePath = await jsonExporter.export(result.value, outputDir);
res.download(filePath, `finding-${findingId}.json`);
});
// GET /api/findings/:id/export/playwright — download Playwright script
router.get('/:id/export/playwright', async (req, res) => {
const findingId = req.params['id'];
const result = await deps.getFinding.execute({ findingId });
if (!result.ok) {
res.status(404).json({ error: result.error });
return;
}
const script = playwrightExporter.generate(result.value);
res.setHeader('Content-Type', 'text/javascript');
res.setHeader('Content-Disposition', `attachment; filename="finding-${findingId}.spec.js"`);
res.send(script);
});
return router;
}
function toDTO(f) {
return {
id: f.id.toString(),
sessionId: f.sessionId,
type: f.type.value,
severity: f.severity.value,
description: f.description,
status: f.status.value,
browser: f.browser,
browserVersion: f.browserVersion,
actionTraceLength: f.actionTrace.length,
evidence: f.evidence.toJSON(),
aiEnrichment: f.aiEnrichment ?? null,
createdAt: f.createdAt.toISOString(),
resolvedAt: f.resolvedAt?.toISOString() ?? null,
};
}

View File

@@ -0,0 +1,138 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KyselyFindingRepository = void 0;
const Finding_1 = require("../../domain/entities/Finding");
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
const Severity_1 = require("../../domain/value-objects/Severity");
const FindingType_1 = require("../../domain/value-objects/FindingType");
const FindingStatus_1 = require("../../domain/value-objects/FindingStatus");
const Evidence_1 = require("../../domain/value-objects/Evidence");
class KyselyFindingRepository {
constructor(db) {
this.db = db;
}
async save(finding) {
const row = {
id: finding.id.toString(),
session_id: finding.sessionId,
type: finding.type.value,
severity: finding.severity.value,
description: finding.description,
status: finding.status.value,
action_trace_json: JSON.stringify(finding.actionTrace),
evidence_json: JSON.stringify(finding.evidence.toJSON()),
screenshot_path: finding.evidence.screenshotPath ?? null,
dom_snapshot_path: finding.evidence.domSnapshotPath ?? null,
browser: finding.browser ?? null,
browser_version: finding.browserVersion ?? null,
ai_enrichment_json: finding.aiEnrichment ? JSON.stringify(finding.aiEnrichment) : null,
created_at: finding.createdAt.getTime(),
resolved_at: finding.resolvedAt ? finding.resolvedAt.getTime() : null,
};
await this.db.insertInto('findings').values(row).execute();
}
async findById(id) {
const row = await this.db
.selectFrom('findings')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
return row ? this.toDomain(row) : undefined;
}
async findAll(filters) {
let query = this.db.selectFrom('findings').selectAll();
if (filters?.sessionId) {
query = query.where('session_id', '=', filters.sessionId);
}
if (filters?.severity) {
query = query.where('severity', '=', filters.severity);
}
if (filters?.type) {
query = query.where('type', '=', filters.type);
}
if (filters?.status) {
query = query.where('status', '=', filters.status);
}
if (filters?.search) {
query = query.where('description', 'like', `%${filters.search}%`);
}
const rows = await query.orderBy('created_at', 'desc').execute();
return rows.map((row) => this.toDomain(row));
}
async update(finding) {
await this.db
.updateTable('findings')
.set({
status: finding.status.value,
ai_enrichment_json: finding.aiEnrichment ? JSON.stringify(finding.aiEnrichment) : null,
resolved_at: finding.resolvedAt ? finding.resolvedAt.getTime() : null,
})
.where('id', '=', finding.id.toString())
.execute();
}
async count(filters) {
let query = this.db.selectFrom('findings').select(eb => eb.fn.countAll().as('cnt'));
if (filters?.sessionId) {
query = query.where('session_id', '=', filters.sessionId);
}
if (filters?.severity) {
query = query.where('severity', '=', filters.severity);
}
if (filters?.type) {
query = query.where('type', '=', filters.type);
}
if (filters?.status) {
query = query.where('status', '=', filters.status);
}
const result = await query.executeTakeFirst();
return Number(result?.cnt ?? 0);
}
async countBySeverity() {
const rows = await this.db
.selectFrom('findings')
.select(['severity', eb => eb.fn.countAll().as('cnt')])
.groupBy('severity')
.execute();
const result = {};
for (const row of rows) {
result[row.severity] = Number(row.cnt);
}
return result;
}
toDomain(row) {
const actionTrace = this.parseJson(row.action_trace_json, []);
const evidenceData = this.parseJson(row.evidence_json, {});
const aiEnrichment = row.ai_enrichment_json
? this.parseJson(row.ai_enrichment_json, undefined)
: undefined;
const props = {
sessionId: row.session_id,
severity: Severity_1.Severity.fromString(row.severity),
type: FindingType_1.FindingType.fromString(row.type),
description: row.description,
evidence: Evidence_1.Evidence.create({
screenshotPath: row.screenshot_path ?? undefined,
domSnapshotPath: row.dom_snapshot_path ?? undefined,
httpLog: evidenceData.httpLog ?? [],
rawErrors: evidenceData.rawErrors ?? [],
}),
status: FindingStatus_1.FindingStatus.fromString(row.status),
actionTrace,
browser: row.browser ?? undefined,
browserVersion: row.browser_version ?? undefined,
aiEnrichment,
createdAt: new Date(row.created_at),
resolvedAt: row.resolved_at ? new Date(row.resolved_at) : undefined,
};
return Finding_1.Finding.reconstitute(props, UniqueId_1.UniqueId.from(row.id));
}
parseJson(json, fallback) {
try {
return JSON.parse(json);
}
catch {
return fallback;
}
}
}
exports.KyselyFindingRepository = KyselyFindingRepository;