diff --git a/src/lib/constants/icon-map.ts b/src/lib/constants/icon-map.ts index a24db34..7786d33 100644 --- a/src/lib/constants/icon-map.ts +++ b/src/lib/constants/icon-map.ts @@ -260,6 +260,8 @@ export const iconMap: Record = { signpost: ``, wifi: ``, // '': ``, + asterisk: ``, + certificate: ``, 'ipv6-check': ``, handshake: ``, circle: ``, diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index b08cefa..d96ec7a 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -1403,6 +1403,29 @@ export const SUB_NAV: Record = { 'negotiation', ], }, + { + href: makePath('/diagnostics/tls/ct-log-search'), + label: 'CT Log Search', + description: 'Search Certificate Transparency logs to discover all certificates issued for a domain', + icon: 'certificate', + keywords: [ + 'ct', + 'certificate', + 'transparency', + 'log', + 'search', + 'crt.sh', + 'ssl', + 'tls', + 'san', + 'subdomains', + 'discovery', + 'issuer', + 'validity', + 'wildcard', + 'monitoring', + ], + }, ], }, { diff --git a/src/lib/content/ct-log-search.ts b/src/lib/content/ct-log-search.ts new file mode 100644 index 0000000..8fa61bd --- /dev/null +++ b/src/lib/content/ct-log-search.ts @@ -0,0 +1,144 @@ +export const ctLogContent = { + title: 'Certificate Transparency Log Search', + description: 'Search Certificate Transparency logs to discover all certificates issued for a domain', + sections: { + whatIsCT: { + title: 'What is Certificate Transparency?', + content: + 'Certificate Transparency (CT) is an open framework for monitoring and auditing SSL/TLS certificates. All publicly-trusted Certificate Authorities are required to log certificates to public CT logs, creating an append-only, cryptographically-assured record of all certificates issued.', + }, + benefits: { + title: 'Benefits of CT Logs', + benefits: [ + { + benefit: 'Security Monitoring', + description: 'Detect unauthorized or mis-issued certificates for your domains in real-time', + }, + { + benefit: 'Asset Discovery', + description: + 'Discover all subdomains and hostnames that have certificates, useful for inventory and security audits', + }, + { + benefit: 'Certificate Management', + description: 'Track certificate renewals, expirations, and issuer patterns across your infrastructure', + }, + { + benefit: 'Compliance & Auditing', + description: 'Maintain compliance by ensuring only authorized CAs issue certificates for your domains', + }, + ], + }, + useCases: { + title: 'Common Use Cases', + cases: [ + { + useCase: 'Subdomain Enumeration', + description: 'Discover all subdomains for a domain by analyzing SANs in issued certificates', + example: 'Security teams use this for attack surface mapping', + }, + { + useCase: 'Mis-issuance Detection', + description: 'Identify certificates issued by unauthorized CAs or for unexpected hostnames', + example: 'Detect phishing domains or internal names leaked to public logs', + }, + { + useCase: 'Certificate Lifecycle Tracking', + description: 'Monitor certificate renewals, track expiration dates, and plan migrations', + example: 'DevOps teams use this to prevent outages from expired certificates', + }, + { + useCase: 'CA Diversity Analysis', + description: 'Understand which CAs are issuing certificates for your organization', + example: 'Compliance teams verify approved CA usage', + }, + ], + }, + certificateFields: { + title: 'Key Certificate Fields', + fields: [ + { + field: 'Common Name (CN)', + description: 'Primary domain name the certificate is issued for', + }, + { + field: 'Subject Alternative Names (SANs)', + description: 'Additional hostnames covered by the certificate, including wildcards', + }, + { + field: 'Issuer', + description: "Certificate Authority that issued the certificate (e.g., Let's Encrypt, DigiCert)", + }, + { + field: 'Validity Period', + description: 'Start (Not Before) and end (Not After) dates when the certificate is valid', + }, + { + field: 'Serial Number', + description: 'Unique identifier assigned by the CA, used for revocation lookups', + }, + { + field: 'Entry Timestamp', + description: 'When the certificate was logged to CT, which may differ from issuance date', + }, + ], + }, + security: { + title: 'Security Considerations', + points: [ + { + point: 'CT Logs are Public', + description: + 'All logged certificates are publicly visible. Avoid including sensitive hostnames in SANs if they should remain private.', + }, + { + point: 'Monitor for Unexpected Issuance', + description: + 'Regularly check CT logs for your domains to detect phishing attempts or unauthorized certificates.', + }, + { + point: 'CAA Records', + description: 'Use DNS CAA records to restrict which CAs can issue certificates for your domains.', + }, + { + point: 'Certificate Pinning', + description: 'For high-security applications, consider certificate pinning to prevent MITM attacks.', + }, + ], + }, + bestPractices: { + title: 'Best Practices', + practices: [ + { + practice: 'Regular Monitoring', + description: 'Periodically search CT logs for your domains to detect anomalies', + }, + { + practice: 'Automate Alerts', + description: 'Set up automated monitoring to alert on new certificate issuance', + }, + { + practice: 'Review SANs Carefully', + description: 'Ensure certificates only include necessary hostnames to minimize exposure', + }, + { + practice: 'Track Expiration Dates', + description: 'Monitor certificates expiring soon to prevent service disruptions', + }, + { + practice: 'Validate Issuers', + description: 'Ensure only authorized CAs are issuing certificates for your domains', + }, + ], + }, + }, + quickTips: [ + 'CT logs are append-only and cannot be modified or deleted', + 'Wildcard certificates (*.example.com) cover all subdomains', + 'Internal hostnames in SANs become publicly visible via CT logs', + 'Most browsers require CT compliance for certificates to be trusted', + 'crt.sh searches multiple CT log servers for comprehensive results', + 'Certificate issuance != activation - check validity dates carefully', + 'Use CAA records to specify which CAs can issue for your domain', + ], +}; diff --git a/src/routes/api/internal/diagnostics/ct-log-search/+server.ts b/src/routes/api/internal/diagnostics/ct-log-search/+server.ts new file mode 100644 index 0000000..e14d0e0 --- /dev/null +++ b/src/routes/api/internal/diagnostics/ct-log-search/+server.ts @@ -0,0 +1,169 @@ +import { json, error } from '@sveltejs/kit'; +import type { RequestHandler } from './$types'; + +interface CTLogRequest { + domain: string; +} + +interface CTCertificate { + id: number; + issuer_ca_id: number; + issuer_name: string; + common_name: string; + name_value: string; + entry_timestamp: string; + not_before: string; + not_after: string; + serial_number: string; +} + +interface ProcessedCertificate { + id: number; + commonName: string; + sans: string[]; + issuer: string; + issuerId: number; + entryTimestamp: string; + notBefore: string; + notAfter: string; + serialNumber: string; + isValid: boolean; + daysUntilExpiry: number; + isWildcard: boolean; + ctLogUrl: string; +} + +interface CTLogResponse { + domain: string; + certificates: ProcessedCertificate[]; + totalCertificates: number; + discoveredHostnames: string[]; + issuers: Array<{ name: string; count: number }>; + validCertificates: number; + expiringSoon: number; + wildcardCertificates: number; + timestamp: string; +} + +export const POST: RequestHandler = async ({ request }) => { + try { + const body: CTLogRequest = await request.json(); + const { domain } = body; + + if (!domain || typeof domain !== 'string' || !domain.trim()) { + throw error(400, 'Domain is required'); + } + + const trimmedDomain = domain.trim().toLowerCase(); + + // Basic domain validation + if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(trimmedDomain)) { + throw error(400, 'Invalid domain format'); + } + + const result = await searchCTLogs(trimmedDomain); + return json(result); + } catch (err) { + console.error('CT log search error:', err); + if (err && typeof err === 'object' && 'status' in err) { + throw err; + } + throw error(500, `CT log search failed: ${err instanceof Error ? err.message : 'Unknown error'}`); + } +}; + +async function searchCTLogs(domain: string): Promise { + // Query crt.sh API + const url = `https://crt.sh/?q=${encodeURIComponent(domain)}&output=json`; + + const response = await fetch(url, { + headers: { + 'User-Agent': 'CT-Log-Search/1.0', + }, + }); + + if (!response.ok) { + throw new Error(`crt.sh API returned ${response.status}`); + } + + const data: CTCertificate[] = await response.json(); + + if (!Array.isArray(data) || data.length === 0) { + return { + domain, + certificates: [], + totalCertificates: 0, + discoveredHostnames: [], + issuers: [], + validCertificates: 0, + expiringSoon: 0, + wildcardCertificates: 0, + timestamp: new Date().toISOString(), + }; + } + + const now = new Date(); + const thirtyDaysFromNow = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000); + + // Process certificates + const processedCerts: ProcessedCertificate[] = data.map((cert) => { + const sans = cert.name_value + .split('\n') + .map((n) => n.trim()) + .filter(Boolean); + + const notBefore = new Date(cert.not_before); + const notAfter = new Date(cert.not_after); + const isValid = now >= notBefore && now <= notAfter; + const daysUntilExpiry = Math.ceil((notAfter.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)); + const isWildcard = cert.common_name.startsWith('*.') || sans.some((san) => san.startsWith('*.')); + + return { + id: cert.id, + commonName: cert.common_name, + sans, + issuer: cert.issuer_name, + issuerId: cert.issuer_ca_id, + entryTimestamp: cert.entry_timestamp, + notBefore: cert.not_before, + notAfter: cert.not_after, + serialNumber: cert.serial_number, + isValid, + daysUntilExpiry, + isWildcard, + ctLogUrl: `https://crt.sh/?id=${cert.id}`, + }; + }); + + // Deduplicate and collect all hostnames + const hostnamesSet = new Set(); + processedCerts.forEach((cert) => { + cert.sans.forEach((san) => hostnamesSet.add(san)); + }); + const discoveredHostnames = Array.from(hostnamesSet).sort(); + + // Count issuers + const issuerCounts = new Map(); + processedCerts.forEach((cert) => { + issuerCounts.set(cert.issuer, (issuerCounts.get(cert.issuer) || 0) + 1); + }); + const issuers = Array.from(issuerCounts.entries()) + .map(([name, count]) => ({ name, count })) + .sort((a, b) => b.count - a.count); + + const validCertificates = processedCerts.filter((c) => c.isValid).length; + const expiringSoon = processedCerts.filter((c) => c.isValid && new Date(c.notAfter) <= thirtyDaysFromNow).length; + const wildcardCertificates = processedCerts.filter((c) => c.isWildcard).length; + + return { + domain, + certificates: processedCerts, + totalCertificates: processedCerts.length, + discoveredHostnames, + issuers, + validCertificates, + expiringSoon, + wildcardCertificates, + timestamp: new Date().toISOString(), + }; +} diff --git a/src/routes/diagnostics/tls/ct-log-search/+page.svelte b/src/routes/diagnostics/tls/ct-log-search/+page.svelte new file mode 100644 index 0000000..dbe1d93 --- /dev/null +++ b/src/routes/diagnostics/tls/ct-log-search/+page.svelte @@ -0,0 +1,845 @@ + + +
+
+

{content.title}

+

{content.description}

+
+ + +
+
+

Search CT Logs

+
+
+
+ e.key === 'Enter' && searchCTLogs()} + disabled={loading} + /> + +
+
+
+ + +
+
+ + +

Quick Examples

+
+
+ {#each examples as example (example.domain)} + + {/each} +
+
+
+ + + {#if loading} +
+
+
+ +
+

Searching Certificate Transparency Logs

+

Querying CT logs for {domain}...

+
+
+
+
+ {/if} + + + {#if error} +
+
+
+ + {error} +
+
+
+ {/if} + + + {#if results} +
+
+

CT Log Results for {results.domain}

+ +
+
+ +
+
+ +
+

{results.totalCertificates} Total Certificates

+

Found in Certificate Transparency logs

+
+
+
+ + +
+ {#each statsConfig as stat (stat.key)} +
+

+ + {stat.label} +

+
+ {stat.isArray + ? (results[stat.key as keyof CTLogResponse] as any[]).length + : results[stat.key as keyof CTLogResponse]} +
+

{stat.desc}

+
+ {/each} +
+ + + {#if results.discoveredHostnames.length > 0} +
+

+ + Discovered Hostnames ({results.discoveredHostnames.length}) +

+
+ {#each results.discoveredHostnames.slice(0, 50) as hostname (hostname)} + + {#if hostname.startsWith('*')} + + {/if} + {hostname} + + {/each} + {#if results.discoveredHostnames.length > 50} + + +{results.discoveredHostnames.length - 50} more + + {/if} +
+
+ {/if} + + + {#if results.issuers.length > 0} +
+

+ + Certificate Issuers ({results.issuers.length}) +

+
+ {#each results.issuers.slice(0, 10) as issuer (issuer.name)} +
+ {issuer.name} + {issuer.count} +
+ {/each} +
+
+ {/if} + + +
+

+ + Certificates ({results.certificates.length}) +

+
+ {#each results.certificates.slice(0, 20) as cert (cert.id)} +
+
toggleCert(cert.id)} + onkeydown={(e) => e.key === 'Enter' && toggleCert(cert.id)} + > +
+ {#if cert.isWildcard} + + {/if} + {cert.commonName} + {#each getCertBadges(cert) as badge (badge.text)} + {badge.text} + {/each} +
+ +
+ + {#if expandedCert === cert.id} +
+
+ {#each certDetailFields as field (field.key)} +
+ +
+ {field.label}{field.isSans ? ` (${cert.sans.length})` : ''} + {#if field.isSans} +
+ {#each cert.sans.slice(0, 10) as san (san)} + {san} + {/each} + {#if cert.sans.length > 10} + +{cert.sans.length - 10} more + {/if} +
+ {:else if field.isLink} + + crt.sh #{cert.id} + + {:else if field.formatter} + {field.formatter(cert)} + {:else} + {cert[field.key as keyof ProcessedCertificate]} + {/if} +
+
+ {/each} +
+
+ {/if} +
+ {/each} + {#if results.certificates.length > 20} +
+ Showing first 20 of {results.certificates.length} certificates +
+ {/if} +
+
+
+
+ {/if} + + +
+
+

About Certificate Transparency

+
+
+ +
+ + +

{content.sections.whatIsCT.title}

+
+
+

{content.sections.whatIsCT.content}

+
+
+ + {#each [{ title: content.sections.benefits.title, items: content.sections.benefits.benefits, keys: ['benefit', 'description'] }, { title: content.sections.useCases.title, items: content.sections.useCases.cases, keys: ['useCase', 'description', 'example'] }, { title: content.sections.certificateFields.title, items: content.sections.certificateFields.fields, keys: ['field', 'description'] }, { title: content.sections.security.title, items: content.sections.security.points, keys: ['point', 'description'] }, { title: content.sections.bestPractices.title, items: content.sections.bestPractices.practices, keys: ['practice', 'description'] }] as section (section.title)} +
+ + +

{section.title}

+
+
+
    + {#each section.items as item ((item as any)[section.keys[0]])} +
  • + {(item as any)[section.keys[0]]}: + {(item as any)[section.keys[1]]} + {#if section.keys[2] && (item as any)[section.keys[2]]} + ({(item as any)[section.keys[2]]}) + {/if} +
  • + {/each} +
+
+
+ {/each} + + +
+ + +

Quick Tips

+
+
+
    + {#each content.quickTips as tip (tip)} +
  • {tip}
  • + {/each} +
+
+
+
+
+
+ + diff --git a/tests/api/internal-endpoints/ct-log-search.test.ts b/tests/api/internal-endpoints/ct-log-search.test.ts new file mode 100644 index 0000000..a036046 --- /dev/null +++ b/tests/api/internal-endpoints/ct-log-search.test.ts @@ -0,0 +1,113 @@ +import { describe, it, expect } from 'vitest'; +import { API_BASE_URL } from '../utils/api-test-helpers'; + +describe('CT Log Search API', () => { + async function makeRequest(domain: string) { + const response = await fetch(`${API_BASE_URL}/api/internal/diagnostics/ct-log-search`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ domain }) + }); + const data = await response.json(); + return { status: response.status, data }; + } + + describe('Valid Domain Searches', () => { + it('should search example.com', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + expect(data.domain).toBe('example.com'); + expect(data.certificates).toBeInstanceOf(Array); + expect(data.totalCertificates).toBeGreaterThan(0); + expect(data.discoveredHostnames).toBeInstanceOf(Array); + expect(data.issuers).toBeInstanceOf(Array); + expect(data.validCertificates).toBeGreaterThanOrEqual(0); + expect(data.expiringSoon).toBeGreaterThanOrEqual(0); + expect(data.wildcardCertificates).toBeGreaterThanOrEqual(0); + expect(data.timestamp).toBeDefined(); + }); + + it('should include required certificate fields', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + expect(data.certificates.length).toBeGreaterThan(0); + + const cert = data.certificates[0]; + expect(cert).toHaveProperty('id'); + expect(cert).toHaveProperty('commonName'); + expect(cert).toHaveProperty('sans'); + expect(cert).toHaveProperty('issuer'); + expect(cert).toHaveProperty('issuerId'); + expect(cert).toHaveProperty('entryTimestamp'); + expect(cert).toHaveProperty('notBefore'); + expect(cert).toHaveProperty('notAfter'); + expect(cert).toHaveProperty('serialNumber'); + expect(cert).toHaveProperty('isValid'); + expect(cert).toHaveProperty('daysUntilExpiry'); + expect(cert).toHaveProperty('isWildcard'); + expect(cert).toHaveProperty('ctLogUrl'); + }); + + it('should discover hostnames from SANs', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + expect(data.discoveredHostnames).toBeInstanceOf(Array); + expect(data.discoveredHostnames.length).toBeGreaterThan(0); + }); + + it('should aggregate issuer statistics', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + expect(data.issuers).toBeInstanceOf(Array); + + if (data.issuers.length > 0) { + const issuer = data.issuers[0]; + expect(issuer).toHaveProperty('name'); + expect(issuer).toHaveProperty('count'); + expect(typeof issuer.name).toBe('string'); + expect(typeof issuer.count).toBe('number'); + } + }); + }); + + describe('Error Handling', () => { + it('should reject empty domain', async () => { + const { status, data } = await makeRequest(''); + + expect(status).toBe(400); + expect(data.message).toMatch(/domain.*required/i); + }); + + it('should reject missing domain', async () => { + const response = await fetch(`${API_BASE_URL}/api/internal/diagnostics/ct-log-search`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}) + }); + + expect(response.status).toBe(400); + const data = await response.json(); + expect(data.message).toMatch(/domain.*required/i); + }); + + it('should reject invalid domain format', async () => { + const { status, data } = await makeRequest('invalid..domain'); + + expect(status).toBe(400); + expect(data.message).toMatch(/invalid|format/i); + }); + + it('should handle domain with no certificates', async () => { + const { status, data } = await makeRequest('this-domain-has-no-certificates-123456789.example'); + + expect(status).toBe(200); + expect(data.totalCertificates).toBe(0); + expect(data.certificates).toHaveLength(0); + expect(data.discoveredHostnames).toHaveLength(0); + }); + }); +}); diff --git a/tests/unit/content/ct-log-search.test.ts b/tests/unit/content/ct-log-search.test.ts new file mode 100644 index 0000000..9ca28df --- /dev/null +++ b/tests/unit/content/ct-log-search.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect } from 'vitest'; +import { ctLogContent } from '$lib/content/ct-log-search'; + +describe('CT Log Search Content', () => { + it('should have title and description', () => { + expect(ctLogContent.title).toBe('Certificate Transparency Log Search'); + expect(ctLogContent.description).toBeTruthy(); + expect(typeof ctLogContent.description).toBe('string'); + }); + + it('should have whatIsCT section', () => { + expect(ctLogContent.sections.whatIsCT).toBeDefined(); + expect(ctLogContent.sections.whatIsCT.title).toBeTruthy(); + expect(ctLogContent.sections.whatIsCT.content).toBeTruthy(); + }); + + it('should have benefits section with array', () => { + expect(ctLogContent.sections.benefits).toBeDefined(); + expect(ctLogContent.sections.benefits.title).toBeTruthy(); + expect(Array.isArray(ctLogContent.sections.benefits.benefits)).toBe(true); + expect(ctLogContent.sections.benefits.benefits.length).toBeGreaterThan(0); + ctLogContent.sections.benefits.benefits.forEach((item) => { + expect(item.benefit).toBeTruthy(); + expect(item.description).toBeTruthy(); + }); + }); + + it('should have useCases section with array', () => { + expect(ctLogContent.sections.useCases).toBeDefined(); + expect(ctLogContent.sections.useCases.title).toBeTruthy(); + expect(Array.isArray(ctLogContent.sections.useCases.cases)).toBe(true); + expect(ctLogContent.sections.useCases.cases.length).toBeGreaterThan(0); + ctLogContent.sections.useCases.cases.forEach((item) => { + expect(item.useCase).toBeTruthy(); + expect(item.description).toBeTruthy(); + expect(item.example).toBeTruthy(); + }); + }); + + it('should have certificateFields section with array', () => { + expect(ctLogContent.sections.certificateFields).toBeDefined(); + expect(ctLogContent.sections.certificateFields.title).toBeTruthy(); + expect(Array.isArray(ctLogContent.sections.certificateFields.fields)).toBe(true); + expect(ctLogContent.sections.certificateFields.fields.length).toBeGreaterThan(0); + ctLogContent.sections.certificateFields.fields.forEach((item) => { + expect(item.field).toBeTruthy(); + expect(item.description).toBeTruthy(); + }); + }); + + it('should have security section with array', () => { + expect(ctLogContent.sections.security).toBeDefined(); + expect(ctLogContent.sections.security.title).toBeTruthy(); + expect(Array.isArray(ctLogContent.sections.security.points)).toBe(true); + expect(ctLogContent.sections.security.points.length).toBeGreaterThan(0); + ctLogContent.sections.security.points.forEach((item) => { + expect(item.point).toBeTruthy(); + expect(item.description).toBeTruthy(); + }); + }); + + it('should have bestPractices section with array', () => { + expect(ctLogContent.sections.bestPractices).toBeDefined(); + expect(ctLogContent.sections.bestPractices.title).toBeTruthy(); + expect(Array.isArray(ctLogContent.sections.bestPractices.practices)).toBe(true); + expect(ctLogContent.sections.bestPractices.practices.length).toBeGreaterThan(0); + ctLogContent.sections.bestPractices.practices.forEach((item) => { + expect(item.practice).toBeTruthy(); + expect(item.description).toBeTruthy(); + }); + }); + + it('should have quickTips array', () => { + expect(Array.isArray(ctLogContent.quickTips)).toBe(true); + expect(ctLogContent.quickTips.length).toBeGreaterThan(0); + ctLogContent.quickTips.forEach((tip) => { + expect(typeof tip).toBe('string'); + expect(tip.length).toBeGreaterThan(0); + }); + }); +}); diff --git a/tests/unit/routes/api/internal/diagnostics/ct-log-search/server.test.ts b/tests/unit/routes/api/internal/diagnostics/ct-log-search/server.test.ts new file mode 100644 index 0000000..9f077d9 --- /dev/null +++ b/tests/unit/routes/api/internal/diagnostics/ct-log-search/server.test.ts @@ -0,0 +1,89 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { POST } from '../../../../../../../src/routes/api/internal/diagnostics/ct-log-search/+server'; + +describe('CT Log Search API', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should return error for missing domain', async () => { + const request = new Request('http://localhost', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + + await expect(POST({ request } as any)).rejects.toThrow(); + }); + + it('should return error for invalid domain format', async () => { + const request = new Request('http://localhost', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ domain: 'invalid..domain' }), + }); + + await expect(POST({ request } as any)).rejects.toThrow(); + }); + + it('should accept valid domain', async () => { + const mockResponse = { + ok: true, + json: vi.fn().mockResolvedValue([ + { + id: 123456, + issuer_ca_id: 1, + issuer_name: "Let's Encrypt", + common_name: 'example.com', + name_value: 'example.com\nwww.example.com', + entry_timestamp: '2024-01-01T00:00:00Z', + not_before: '2024-01-01T00:00:00Z', + not_after: '2024-04-01T00:00:00Z', + serial_number: 'abc123', + }, + ]), + }; + + globalThis.fetch = vi.fn().mockResolvedValue(mockResponse); + + const request = new Request('http://localhost', { + method: 'POST', + body: JSON.stringify({ domain: 'example.com' }), + }); + + const response = await POST({ request } as any); + const data = await response.json(); + + expect(data.domain).toBe('example.com'); + expect(data.totalCertificates).toBe(1); + expect(data.certificates).toHaveLength(1); + expect(data.discoveredHostnames).toContain('example.com'); + expect(data.discoveredHostnames).toContain('www.example.com'); + }); + + it('should handle empty results from crt.sh', async () => { + const mockResponse = { + ok: true, + json: vi.fn().mockResolvedValue([]), + }; + + globalThis.fetch = vi.fn().mockResolvedValue(mockResponse); + + const request = new Request('http://localhost', { + method: 'POST', + body: JSON.stringify({ domain: 'nonexistent.example' }), + }); + + const response = await POST({ request } as any); + const data = await response.json(); + + expect(data.domain).toBe('nonexistent.example'); + expect(data.totalCertificates).toBe(0); + expect(data.certificates).toHaveLength(0); + expect(data.discoveredHostnames).toHaveLength(0); + }); +});