husteno-o feat: code review system, type safety, error handling, AI provider fallback · 9/9/2026
5ccaeae
169 lines · 5.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import { cache, getOrSet } from "@devpulse/cache";
import { NotFoundError, ValidationError } from "@devpulse/core";
import { logger } from "@devpulse/logger";

export interface VulnerabilityRecord {
  id: string;
  summary: string;
  details: string;
  severity?: string;
  published: string;
  modified: string;
  affectedPackage?: {
    name: string;
    ecosystem: string;
  };
  fixedVersions: string[];
  references: string[];
}

export class SecurityService {
  async lookupCve(cveId: string): Promise<VulnerabilityRecord> {
    const cleanId = cveId.trim().toUpperCase();
    if (!cleanId.startsWith("CVE-") && !cleanId.startsWith("GHSA-")) {
      throw new ValidationError("Vulnerability ID must start with 'CVE-' or 'GHSA-'.");
    }

    const cacheKey = `cve:${cleanId}`;

    return getOrSet(
      cacheKey,
      async () => {
        logger.debug({ cveId: cleanId }, "Fetching vulnerability from OSV API");
        const response = await fetch(`https://api.osv.dev/v1/vulns/${encodeURIComponent(cleanId)}`);

        if (response.status === 404) {
          throw new NotFoundError("Vulnerability", cleanId);
        }
        if (!response.ok) {
          throw new Error(
            `Failed to fetch CVE data from OSV API: returned status ${response.status}`,
          );
        }

        interface OsvRange {
          events?: { fixed?: string }[];
        }
        interface OsvAffected {
          ranges?: OsvRange[];
          package?: { name: string; ecosystem: string };
        }
        interface OsvVulnerability {
          affected?: OsvAffected[];
          references?: { url: string }[];
          id: string;
          summary: string;
          details?: string;
          severity?: { score?: string }[];
          published?: string;
          modified?: string;
          database_specific?: { severity?: string };
        }
        const data = (await response.json()) as OsvVulnerability;
        const affected = data.affected?.[0];
        const fixedVersions: string[] = [];

        if (affected?.ranges) {
          for (const r of affected.ranges) {
            for (const event of r.events || []) {
              if (event.fixed) fixedVersions.push(event.fixed);
            }
          }
        }

        const references = ((data as { references?: { url: string }[] }).references || [])
          .map((r: unknown) => (r as { url: string }).url)
          .slice(0, 5);

        return {
          id: data.id,
          summary: data.summary || "No summary provided in advisory database.",
          details: data.details || data.summary || "No details provided.",
          severity: data.database_specific?.severity || data.severity?.[0]?.score || "Unknown",
          published: data.published || new Date().toISOString(),
          modified: data.modified || new Date().toISOString(),
          affectedPackage: affected?.package
            ? {
                name: affected.package.name,
                ecosystem: affected.package.ecosystem,
              }
            : undefined,
          fixedVersions,
          references,
        };
      },
      86400, // Cache for 24 hours
      cache,
    );
  }

  async lookupPackageVulnerabilities(
    ecosystem: string,
    packageName: string,
    version?: string,
  ): Promise<VulnerabilityRecord[]> {
    const cacheKey = `vuln:pkg:${ecosystem.toLowerCase()}:${packageName.toLowerCase()}:${version || "latest"}`;

    return getOrSet(
      cacheKey,
      async () => {
        interface OsvQueryBody {
          package: { name: string; ecosystem: string };
          version?: string;
        }
        const body: OsvQueryBody = {
          package: {
            name: packageName.trim(),
            ecosystem: ecosystem.trim(),
          },
        };
        if (version) {
          body.version = version.trim();
        }

        const response = await fetch("https://api.osv.dev/v1/query", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        });

        if (!response.ok) {
          throw new Error(`Failed to query OSV API for vulnerabilities: ${response.statusText}`);
        }

        interface OsvVulnSummary {
          id: string;
          summary?: string;
          details?: string;
          published?: string;
          modified?: string;
          references?: { url: string }[];
        }
        interface OsvQueryResponse {
          vulns?: OsvVulnSummary[];
        }
        const data = (await response.json()) as OsvQueryResponse;
        const vulns = data.vulns || [];

        return vulns.slice(0, 10).map((v) => ({
          id: v.id,
          summary: v.summary || "Advisory reported",
          details: v.details || "",
          published: v.published || new Date().toISOString(),
          modified: v.modified || new Date().toISOString(),
          affectedPackage: {
            name: packageName,
            ecosystem,
          },
          fixedVersions: [],
          references: (v.references || []).map((r) => r.url).slice(0, 3),
        }));
      },
      3600, // 1 hour cache
      cache,
    );
  }
}

export const securityService = new SecurityService();