Full Toolkit for Next-Level Domain Analysis
Show RFC 10023 for-sale signals in the domain summary 🏠🏷️ (#114)
Felix Wotschofskya0af9a99262d
diff --git a/app/api/domain-summary/route.test.ts b/app/api/domain-summary/route.test.tsnew file mode 100644index 0000000..d643474--- /dev/null+++ b/app/api/domain-summary/route.test.ts@@ -0,0 +1,141 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GET } from './route';++const { lookupSale, lookupWhois, logger } = vi.hoisted(() => ({+ lookupSale: vi.fn(),+ lookupWhois: vi.fn(),+ logger: { set: vi.fn(), error: vi.fn() },+}));+vi.mock('@/lib/for-sale', () => ({ lookupForSale: lookupSale }));+vi.mock('@/lib/whois', () => ({ getWhoisSummary: lookupWhois }));+vi.mock('@/lib/evlog', () => ({+ useLogger: () => logger,+ withEvlog: (handler: unknown) => handler,+}));++const whois = {+ registered: true,+ registrar: 'Example registrar',+ createdAt: '2020-01-01',+ dnssec: 'signed',+};+const sale = {+ domain: 'example.com',+ listing: { prices: ['EUR 2500'], links: [], texts: [] },+};+const request = (domain?: string) =>+ new Request(+ `https://digger.tools/api/domain-summary${domain === undefined ? '' : `?domain=${encodeURIComponent(domain)}`}`,+ );++describe('domain summary API', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ lookupWhois.mockResolvedValue(whois);+ lookupSale.mockResolvedValue(sale);+ });++ it.each([undefined, '', 'bad/domain'])(+ 'rejects invalid domains before starting either lookup: %s',+ async (domain) => {+ const response = await GET(request(domain));+ expect(response.status).toBe(400);+ expect(response.headers.get('Cache-Control')).toBe('no-store');+ expect(lookupWhois).not.toHaveBeenCalled();+ expect(lookupSale).not.toHaveBeenCalled();+ },+ );++ it('returns both summaries with the existing WHOIS cache policy', async () => {+ const response = await GET(request('www.example.com'));+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ whois, sale });+ expect(response.headers.get('Cache-Control')).toBe(+ 'public, max-age=600, s-maxage=1800',+ );+ expect(lookupWhois).toHaveBeenCalledWith('www.example.com');+ expect(lookupSale).toHaveBeenCalledWith('www.example.com');+ });++ it('also caches successful responses without a sale listing', async () => {+ const noListing = { domain: 'example.com', listing: null };+ lookupSale.mockResolvedValue(noListing);+ const response = await GET(request('example.com'));+ expect(await response.json()).toEqual({ whois, sale: noListing });+ expect(response.headers.get('Cache-Control')).toBe(+ 'public, max-age=600, s-maxage=1800',+ );+ });++ it('preserves and caches the unregistered WHOIS result', async () => {+ lookupWhois.mockResolvedValue({ registered: false });+ const response = await GET(request('example.com'));+ expect(await response.json()).toEqual({+ whois: { registered: false },+ sale,+ });+ expect(response.headers.get('Cache-Control')).toBe(+ 'public, max-age=600, s-maxage=1800',+ );+ });++ it('fails the request without caching when the WHOIS lookup rejects', async () => {+ const error = new Error('Lookup failed');+ lookupWhois.mockRejectedValue(error);+ const response = await GET(request('example.com'));+ expect(response.status).toBe(500);+ expect(response.headers.get('Cache-Control')).toBe('no-store');+ expect(await response.json()).toEqual({+ error: true,+ message: 'Error fetching domain summary',+ });+ expect(logger.error).toHaveBeenCalledOnce();+ expect(logger.error).toHaveBeenCalledWith(error);+ });++ it('keeps WHOIS with a short cache when the sale lookup rejects', async () => {+ const error = new Error('Lookup failed');+ lookupSale.mockRejectedValue(error);+ const response = await GET(request('example.com'));+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ whois, sale: null });+ expect(response.headers.get('Cache-Control')).toBe(+ 'public, max-age=60, s-maxage=60',+ );+ expect(logger.error).toHaveBeenCalledOnce();+ expect(logger.error).toHaveBeenCalledWith(error);+ });++ it('uses the short cache when WHOIS registration is unknown', async () => {+ const unknown = { ...whois, unknown: true };+ lookupWhois.mockResolvedValue(unknown);+ const response = await GET(request('example.com'));+ expect(await response.json()).toEqual({ whois: unknown, sale });+ expect(response.headers.get('Cache-Control')).toBe(+ 'public, max-age=60, s-maxage=60',+ );+ });++ it('starts both lookups before waiting for either to finish', async () => {+ let resolveWhois!: (value: typeof whois) => void;+ let resolveSale!: (value: typeof sale) => void;+ lookupWhois.mockReturnValue(+ new Promise((resolve) => {+ resolveWhois = resolve;+ }),+ );+ lookupSale.mockReturnValue(+ new Promise((resolve) => {+ resolveSale = resolve;+ }),+ );++ const responsePromise = GET(request('example.com'));+ expect(lookupWhois).toHaveBeenCalledOnce();+ expect(lookupSale).toHaveBeenCalledOnce();+ resolveWhois(whois);+ resolveSale(sale);+ expect(await (await responsePromise).json()).toEqual({ whois, sale });+ });+});diff --git a/app/api/domain-summary/route.ts b/app/api/domain-summary/route.tsnew file mode 100644index 0000000..d38cb0e--- /dev/null+++ b/app/api/domain-summary/route.ts@@ -0,0 +1,56 @@+import { NextResponse } from 'next/server';++import { useLogger, withEvlog } from '@/lib/evlog';+import { type ForSaleSummary, lookupForSale } from '@/lib/for-sale';+import { isValidDomain } from '@/lib/utils';+import { getWhoisSummary } from '@/lib/whois';++export type DomainSummaryResponse = {+ whois: Awaited<ReturnType<typeof getWhoisSummary>>;+ // null when the sale lookup failed; WHOIS is still returned.+ sale: ForSaleSummary | null;+};++export const GET = withEvlog(async (request: Request) => {+ const log = useLogger();+ const domain = new URL(request.url).searchParams.get('domain');++ if (!domain || !isValidDomain(domain)) {+ log.set({ status: 400, reason: 'invalid_domain' });+ return NextResponse.json(+ { error: true, message: 'Invalid domain' },+ { status: 400, headers: { 'Cache-Control': 'no-store' } },+ );+ }++ log.set({ domain });++ try {+ const [whois, sale] = await Promise.all([+ getWhoisSummary(domain),+ lookupForSale(domain).catch((error) => {+ log.set({ event: 'sale_lookup_failed' });+ log.error(error instanceof Error ? error : new Error(String(error)));+ return null;+ }),+ ]);++ return NextResponse.json({ whois, sale } satisfies DomainSummaryResponse, {+ headers: {+ // Retry a failed lookup soon instead of hiding a listing.+ 'Cache-Control':+ sale && !(whois.registered && whois.unknown)+ ? 'public, max-age=600, s-maxage=1800'+ : 'public, max-age=60, s-maxage=60',+ },+ });+ } catch (error) {+ log.set({ event: 'domain_summary_failed' });+ log.error(error instanceof Error ? error : new Error(String(error)));++ return NextResponse.json(+ { error: true, message: 'Error fetching domain summary' },+ { status: 500, headers: { 'Cache-Control': 'no-store' } },+ );+ }+});diff --git a/app/api/whois-summary/route.ts b/app/api/whois-summary/route.tsdeleted file mode 100644index 0bbb7a8..0000000--- a/app/api/whois-summary/route.ts+++ /dev/null@@ -1,50 +0,0 @@-import { NextResponse } from 'next/server';--import { useLogger, withEvlog } from '@/lib/evlog';-import { getWhoisSummary } from '@/lib/whois';--export type WhoisSummaryResponse = Awaited<ReturnType<typeof getWhoisSummary>>;-export type WhoisSummaryErrorResponse = { error: true; message: string };--export const GET = withEvlog(async (request: Request) => {- const log = useLogger();- const { searchParams } = new URL(request.url);- const domain = searchParams.get('domain');-- if (!domain) {- log.set({ status: 400, reason: 'missing_domain' });- return NextResponse.json(- { error: true, message: 'No domain provided' },- {- status: 400,- headers: {- 'Content-Type': 'application/json',- },- },- );- }-- log.set({ domain });-- try {- const summary = await getWhoisSummary(domain);- return NextResponse.json(summary, {- headers: {- 'Cache-Control': 'public, max-age=600, s-maxage=1800',- },- });- } catch (error) {- log.set({ event: 'whois_summary_failed' });- log.error(error instanceof Error ? error : new Error(String(error)));-- return NextResponse.json(- { error: true, message: 'Error fetching whois summary' },- {- status: 500,- headers: {- 'Content-Type': 'application/json',- },- },- );- }-});diff --git a/app/lookup/[domain]/_components/domain-summary.test.tsx b/app/lookup/[domain]/_components/domain-summary.test.tsxnew file mode 100644index 0000000..d9d909e--- /dev/null+++ b/app/lookup/[domain]/_components/domain-summary.test.tsx@@ -0,0 +1,287 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { DomainSummary } from './domain-summary';++const fixtures = vi.hoisted(() => ({+ summary: vi.fn(),+ retry: vi.fn(),+ listing: {+ prices: ['EUR 2500'],+ links: ['https://seller.example/buy'],+ texts: ['Seller details should not appear'],+ },+}));++vi.mock('swr', () => ({ default: fixtures.summary }));++describe('domain summary sale link', () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ fixtures.summary.mockReset();+ fixtures.retry.mockReset().mockResolvedValue(undefined);+ fixtures.summary.mockReturnValue({+ data: {+ whois: { registered: true, registrar: 'Example registrar' },+ sale: { domain: 'example.com', listing: fixtures.listing },+ },+ isLoading: false,+ isValidating: false,+ mutate: fixtures.retry,+ });+ fixtures.listing.prices = ['EUR 2500'];+ fixtures.listing.links = ['https://seller.example/buy'];+ container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+ });++ afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+ });++ const render = async (domain = 'example.com') => {+ await act(async () => root.render(<DomainSummary domain={domain} />));+ };++ it('requires confirmation before exposing the outgoing link and allows cancellation', async () => {+ await render();+ expect(container.textContent).toContain('€2,500');+ const button = container.querySelector('button')!;+ expect(button.hasAttribute('aria-label')).toBe(false);+ expect(button.textContent).toContain('€2,500');+ expect(button.querySelector('.sr-only')?.textContent).toContain(+ 'external website',+ );+ expect(container.textContent).not.toContain('Seller details');+ expect(container.querySelector('details')).toBeNull();+ expect(document.querySelector('a')).toBeNull();++ await act(async () => container.querySelector('button')!.click());+ const dialog = document.querySelector('[role="alertdialog"]')!;+ expect(dialog.textContent).toContain('Domain Digger does not control');+ expect(dialog.textContent).toContain('https://seller.example/buy');+ const outgoing = dialog.querySelector('a')!;+ expect(outgoing.getAttribute('href')).toBe('https://seller.example/buy');+ expect(outgoing.target).toBe('_blank');+ expect(outgoing.rel).toBe('noopener noreferrer nofollow');++ await act(async () => dialog.querySelector('button')!.click());+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();+ expect(document.querySelector('a')).toBeNull();+ });++ it('closes the confirmation when continuing', async () => {+ await render();+ await act(async () => container.querySelector('button')!.click());+ const outgoing = document.querySelector<HTMLAnchorElement>(+ '[role="alertdialog"] a',+ )!;+ // Avoid real navigation in the test while exercising the confirmation action.+ document.addEventListener('click', (event) => event.preventDefault(), {+ once: true,+ });+ await act(async () => outgoing.click());+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();+ });++ it('requests WHOIS and sale information from one endpoint', async () => {+ await render();+ expect(fixtures.summary).toHaveBeenCalledWith(+ '/api/domain-summary?domain=example.com',+ );+ expect(container.textContent).toContain('Example registrar');+ expect(container.textContent).toContain('€2,500');+ });++ it('shows placeholders while the combined summary is loading', async () => {+ fixtures.summary.mockReturnValue({ data: undefined, isLoading: true });+ await render();+ expect(container.textContent).toContain('Registrar');+ expect(container.textContent).not.toContain('For sale');+ expect(container.querySelector('button')).toBeNull();+ });++ it('shows WHOIS without a sale tile when there is no listing', async () => {+ fixtures.summary.mockReturnValue({+ data: {+ whois: { registered: true, registrar: 'Example registrar' },+ sale: { domain: 'example.com', listing: null },+ },+ isLoading: false,+ });+ await render();+ expect(container.textContent).toContain('Example registrar');+ expect(container.textContent).not.toContain('For sale');+ });++ it('shows WHOIS without a sale tile when the sale lookup failed', async () => {+ fixtures.summary.mockReturnValue({+ data: {+ whois: { registered: true, registrar: 'Example registrar' },+ sale: null,+ },+ isLoading: false,+ });+ await render();+ expect(container.textContent).toContain('Example registrar');+ expect(container.textContent).not.toContain('For sale');+ });++ it('hides sale information when WHOIS could not establish registration', async () => {+ fixtures.summary.mockReturnValue({+ data: {+ whois: { registered: true, unknown: true, registrar: null },+ sale: { domain: 'example.com', listing: fixtures.listing },+ },+ isLoading: false,+ });+ await render();+ expect(container.textContent).toContain('Unavailable');+ expect(container.textContent).not.toContain('For sale');+ });++ it('hides sale information for an unregistered domain', async () => {+ fixtures.summary.mockReturnValue({+ data: {+ whois: { registered: false },+ sale: { domain: 'example.com', listing: fixtures.listing },+ },+ isLoading: false,+ });+ await render();+ expect(container.textContent).toContain('Not registered');+ expect(container.textContent).not.toContain('For sale');+ });++ it('links an email listing to the seller’s email address', async () => {+ fixtures.listing.prices = ['USD 195000'];+ fixtures.listing.links = ['mailto:[email protected]'];+ await render();+ const link = container.querySelector('a')!;+ expect(link.querySelector('span')?.textContent).toBe('$195,000');+ expect(link.getAttribute('href')).toBe('mailto:[email protected]');+ expect(link.hasAttribute('aria-label')).toBe(false);+ expect(link.querySelector('.sr-only')?.textContent).toContain(+ 'Contact seller by email',+ );+ expect(link.hasAttribute('target')).toBe(false);+ expect(container.querySelector('button')).toBeNull();+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();+ });++ it('supports email listings without an asking price', async () => {+ fixtures.listing.prices = [];+ fixtures.listing.links = ['mailto:[email protected]'];+ await render();+ expect(container.querySelector('a span')?.textContent).toBe(+ 'Advertised for sale',+ );+ });++ it('prefers a website listing when an email address is also available', async () => {+ fixtures.listing.links = [+ 'mailto:[email protected]',+ 'https://seller.example/buy',+ ];+ await render();+ expect(container.querySelector('a')).toBeNull();+ await act(async () => container.querySelector('button')!.click());+ expect(+ document.querySelector('[role="alertdialog"] a')?.getAttribute('href'),+ ).toBe('https://seller.example/buy');+ });++ it('shows a plain value when there is no website or email URL', async () => {+ fixtures.listing.links = ['tel:+4930123456'];+ await render();+ expect(container.textContent).toContain('€2,500');+ expect(container.querySelector('button')).toBeNull();+ expect(container.querySelector('a')).toBeNull();+ });++ it.each(['EXAMPLE.COM', 'Example.com.'])(+ 'omits a redundant base-domain suffix for %s',+ async (domain) => {+ await render(domain);+ expect(container.textContent).toContain('For sale');+ expect(container.textContent).not.toContain('For sale (example.com)');+ },+ );++ it('identifies the listing domain for a subdomain search', async () => {+ await render('www.example.com');+ expect(container.textContent).toContain('For sale (example.com)');+ });++ it('shows a retryable error instead of loading forever, then recovers', async () => {+ const success = fixtures.summary();+ fixtures.summary.mockReturnValue({+ data: undefined,+ error: new Error('Request failed'),+ isLoading: false,+ isValidating: false,+ mutate: fixtures.retry,+ });+ await render();+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(+ 'Domain summary unavailable.',+ );+ expect(container.textContent).not.toContain('Registrar');+ expect(container.querySelector('button')?.textContent).toBe('Retry');+ fixtures.retry.mockImplementation(async () =>+ fixtures.summary.mockReturnValue(success),+ );+ await act(async () => container.querySelector('button')!.click());+ expect(fixtures.retry).toHaveBeenCalledOnce();+ await render();+ expect(container.querySelector('[role="alert"]')).toBeNull();+ expect(container.textContent).toContain('Example registrar');+ });++ it('keeps the error state when a manual retry also fails', async () => {+ fixtures.retry.mockRejectedValue(new Error('Request failed'));+ fixtures.summary.mockReturnValue({+ data: undefined,+ error: new Error('Request failed'),+ isLoading: false,+ isValidating: false,+ mutate: fixtures.retry,+ });+ await render();+ await act(async () => container.querySelector('button')!.click());+ expect(fixtures.retry).toHaveBeenCalledOnce();+ expect(container.querySelector('[role="alert"]')).not.toBeNull();+ });++ it('disables additional retries while a request is in progress', async () => {+ fixtures.summary.mockReturnValue({+ data: undefined,+ error: new Error('Request failed'),+ isLoading: false,+ isValidating: true,+ mutate: fixtures.retry,+ });+ await render();+ const retry = container.querySelector('button')!;+ expect(retry.disabled).toBe(true);+ expect(retry.textContent).toBe('Retrying…');+ });++ it('keeps a loaded summary visible when revalidation fails', async () => {+ fixtures.summary.mockReturnValue({+ ...fixtures.summary(),+ error: new Error('Request failed'),+ });+ await render();+ expect(container.querySelector('[role="alert"]')).toBeNull();+ expect(container.textContent).toContain('Example registrar');+ expect(container.textContent).toContain('€2,500');+ });+});diff --git a/app/lookup/[domain]/_components/domain-summary.tsx b/app/lookup/[domain]/_components/domain-summary.tsxnew file mode 100644index 0000000..96fa595--- /dev/null+++ b/app/lookup/[domain]/_components/domain-summary.tsx@@ -0,0 +1,182 @@+'use client';++import { ExternalLinkIcon, MailIcon } from 'lucide-react';+import type { FC, ReactNode } from 'react';+import useSWR from 'swr';++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from '@/components/ui/alert-dialog';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';++import type { DomainSummaryResponse } from '@/app/api/domain-summary/route';+import { formatSalePrice } from '@/lib/format-sale-price';+import { canonicalDnsName } from '@/lib/resolvers/base';++type DomainSummaryTileProps = {+ title: string;+} & (+ | { loading: true; value?: ReactNode }+ | { loading?: false; value: ReactNode }+);++const DomainSummaryTile: FC<DomainSummaryTileProps> = ({+ title,+ loading,+ value,+}) => (+ <div className="max-w-sm break-words">+ <h3 className="text-xs/6 font-medium text-zinc-500 dark:text-zinc-400">+ {title}+ </h3>+ {loading ? (+ <Skeleton className="mt-1 h-4 w-24 rounded-sm" />+ ) : (+ <p className="text-sm font-medium">{value}</p>+ )}+ </div>+);++type SaleListingLinkProps = {+ href?: string;+ children: ReactNode;+};++const SaleListingLink: FC<SaleListingLinkProps> = ({ href, children }) => {+ if (!href) return children;++ const className =+ 'inline-flex cursor-pointer items-center gap-1 text-left hover:underline focus-visible:outline-2 focus-visible:outline-offset-4';++ if (href.startsWith('mailto:')) {+ return (+ <a href={href} className={className}>+ <span>{children}</span>+ <span className="sr-only"> — Contact seller by email</span>+ <MailIcon className="size-3.5 shrink-0" aria-hidden="true" />+ </a>+ );+ }++ return (+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <button type="button" className={className}>+ <span>{children}</span>+ <span className="sr-only">+ {' '}+ — View sale listing on an external website+ </span>+ <ExternalLinkIcon className="size-3.5 shrink-0" aria-hidden="true" />+ </button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Open external website?</AlertDialogTitle>+ <AlertDialogDescription>+ This is an external website that Domain Digger does not control.+ Verify the listing and price with the seller.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <p className="text-sm break-all" dir="ltr">+ {href}+ </p>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction asChild>+ <a href={href} target="_blank" rel="noopener noreferrer nofollow">+ Continue+ <ExternalLinkIcon className="ml-2 size-4" aria-hidden="true" />+ </a>+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};++export const DomainSummary: FC<{ domain: string }> = ({ domain }) => {+ const { data, error, isLoading, isValidating, mutate } =+ useSWR<DomainSummaryResponse>(+ `/api/domain-summary?domain=${encodeURIComponent(domain)}`,+ );++ if (error && !data) {+ return (+ <div className="flex items-center gap-4">+ <p role="alert" className="text-sm text-zinc-500 dark:text-zinc-400">+ Domain summary unavailable.+ </p>+ <Button+ variant="outline"+ size="sm"+ disabled={isValidating}+ onClick={() => void mutate().catch(() => undefined)}+ >+ {isValidating ? 'Retrying…' : 'Retry'}+ </Button>+ </div>+ );+ }++ if (isLoading || !data) {+ return (+ <div className="flex flex-wrap gap-8">+ <DomainSummaryTile title="Registrar" loading />+ <DomainSummaryTile title="Creation Date" loading />+ <DomainSummaryTile title="DNSSEC" loading />+ </div>+ );+ }++ if (!data.whois.registered) {+ return (+ <div className="flex flex-wrap gap-8">+ <DomainSummaryTile title="Status" value="Not registered" />+ </div>+ );+ }++ const { whois } = data;+ // No sale tile when the WHOIS lookup failed and registration is only assumed.+ const sale = whois.unknown ? null : data.sale;+ const listing = sale?.listing;+ const saleUrl =+ listing?.links.find((link) => /^https?:\/\//i.test(link)) ??+ listing?.links.find((link) => link.startsWith('mailto:'));++ return (+ <div className="flex flex-wrap gap-8">+ <DomainSummaryTile+ title="Registrar"+ value={whois.registrar || 'Unavailable'}+ />+ <DomainSummaryTile+ title="Creation Date"+ value={whois.createdAt || 'Unavailable'}+ />+ <DomainSummaryTile title="DNSSEC" value={whois.dnssec || 'Unavailable'} />+ {sale && listing && (+ <DomainSummaryTile+ title={`For sale${sale.domain !== canonicalDnsName(domain) ? ` (${sale.domain})` : ''}`}+ value={+ <SaleListingLink href={saleUrl}>+ {listing.prices.length+ ? listing.prices.map(formatSalePrice).join(' / ')+ : 'Advertised for sale'}+ </SaleListingLink>+ }+ />+ )}+ </div>+ );+};diff --git a/app/lookup/[domain]/_components/whois-quick-info.tsx b/app/lookup/[domain]/_components/whois-quick-info.tsxdeleted file mode 100644index 03f9a31..0000000--- a/app/lookup/[domain]/_components/whois-quick-info.tsx+++ /dev/null@@ -1,82 +0,0 @@-'use client';--import type { FC } from 'react';-import useSWRImmutable from 'swr/immutable';--import { Skeleton } from '@/components/ui/skeleton';--import type { WhoisSummaryResponse } from '@/app/api/whois-summary/route';--type WhoisQuickInfoTileProps =- | {- title: string;- loading: true;- value?: string;- }- | {- title: string;- loading?: false;- value: string;- };--const WhoisQuickInfoTile: FC<WhoisQuickInfoTileProps> = ({- title,- loading,- value,-}) => (- <div>- <h3 className="text-xs/6 font-medium text-zinc-500 dark:text-zinc-400">- {title}- </h3>- {loading ? (- <Skeleton className="mt-1 h-4 w-24 rounded-sm" />- ) : (- <p className="text-sm font-medium">{value}</p>- )}- </div>-);--type WhoisQuickInfoProps = {- domain: string;-};--export const WhoisQuickInfo: FC<WhoisQuickInfoProps> = ({ domain }) => {- const { data, isLoading } = useSWRImmutable<WhoisSummaryResponse>(- `/api/whois-summary?domain=${encodeURIComponent(domain)}`,- );-- if (isLoading || !data) {- return (- <div className="flex flex-wrap gap-8">- <WhoisQuickInfoTile title="Registrar" loading />- <WhoisQuickInfoTile title="Creation Date" loading />- <WhoisQuickInfoTile title="DNSSEC" loading />- </div>- );- }-- if (!data.registered) {- return (- <div className="flex flex-wrap gap-8">- <WhoisQuickInfoTile title="Status" value="Not registered" />- </div>- );- }-- return (- <div className="flex flex-wrap gap-8">- <WhoisQuickInfoTile- title="Registrar"- value={data?.registrar || 'Unavailable'}- />- <WhoisQuickInfoTile- title="Creation Date"- value={data?.createdAt || 'Unavailable'}- />- <WhoisQuickInfoTile- title="DNSSEC"- value={data?.dnssec || 'Unavailable'}- />- </div>- );-};diff --git a/app/lookup/[domain]/layout.tsx b/app/lookup/[domain]/layout.tsxindex 04b5aa7..e9b795f 100644--- a/app/lookup/[domain]/layout.tsx+++ b/app/lookup/[domain]/layout.tsx@@ -11,10 +11,10 @@ import { isValidDomain, isWildcardDomain } from '@/lib/utils';import { Footer } from '../../_components/footer';import { Header } from '../../_components/header';+import { DomainSummary } from './_components/domain-summary';import { RelatedDomains } from './_components/related-domains';import { ResultsTabs } from './_components/results-tabs';import { ShareButton } from './_components/share-button';-import { WhoisQuickInfo } from './_components/whois-quick-info';const StarReminder = dynamic(() =>import('./_components/star-reminder').then((m) => ({@@ -83,7 +83,7 @@ const LookupLayout: FC<LookupLayoutProps> = async (props) => {</div><RelatedDomains domain={domain} />- <WhoisQuickInfo domain={domain} />+ <DomainSummary domain={domain} /></div><div className="container">diff --git a/lib/for-sale.test.ts b/lib/for-sale.test.tsnew file mode 100644index 0000000..7ae0b75--- /dev/null+++ b/lib/for-sale.test.ts@@ -0,0 +1,387 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { lookupForSale, parseForSaleRecords } from './for-sale';++describe('RFC 10023 records', () => {+ it.each(+ [+ [],+ ['I am for sale'],+ ['v=forsale1;'],+ ['v=FORSALE2;'],+ ['v=FORSALE1'],+ [' v=FORSALE1;'],+ ['unrelated v=FORSALE1;'],+ ].map((records) => ({ records })),+ )(+ 'ignores records without the exact version marker: $records',+ ({ records }) => {+ expect(parseForSaleRecords(records)).toBeNull();+ },+ );++ it.each([+ 'v=FORSALE1;',+ 'v=FORSALE1;foo=bar',+ 'v=FORSALE1;fcod=NLFS-abc',+ 'v=FORSALE1;fval=invalid',+ ])('recognizes a marker even without usable details: %s', (record) => {+ expect(parseForSaleRecords([record])).toEqual({+ prices: [],+ links: [],+ texts: [],+ });+ });++ it('combines and deduplicates details from separate records', () => {+ expect(+ parseForSaleRecords([+ 'v=FORSALE1;fval=EUR2500',+ 'v=FORSALE1;fval=BTC0.000010',+ 'v=FORSALE1;furi=https://seller.example/buy',+ 'v=FORSALE1;furi=mailto:[email protected]',+ 'v=FORSALE1;furi=tel:+4930123456',+ 'v=FORSALE1;ftxt=Call for information.',+ 'v=FORSALE1; fval=EUR2500',+ ]),+ ).toEqual({+ prices: ['EUR 2500', 'BTC 0.000010'],+ links: [+ 'https://seller.example/buy',+ 'mailto:[email protected]',+ 'tel:+4930123456',+ ],+ texts: ['Call for information.'],+ });+ });++ it('treats a semicolon in content as part of the value, not another tag', () => {+ expect(+ parseForSaleRecords(['v=FORSALE1;ftxt=Contact me;fval=EUR500']),+ ).toEqual({+ prices: [],+ links: [],+ texts: ['Contact me;fval=EUR500'],+ });+ });++ it.each([+ 'javascript:alert(1)',+ 'data:text/html,test',+ 'https://user:[email protected]/',+ '//seller.example/',+ 'https://seller.example/has space',+ 'https://seller.example/\n',+ 'https://seller.example/\u202etest',+ 'https://seller.example/\u061ctest',+ ])('does not expose unsafe links: %s', (link) => {+ expect(parseForSaleRecords([`v=FORSALE1;furi=${link}`])?.links).toEqual([]);+ });++ it.each(['eur2500', 'EUR-1', 'EUR1e6', 'USD1,000', 'EUR500;ftxt=extra'])(+ 'ignores invalid price formats: %s',+ (price) => {+ expect(parseForSaleRecords([`v=FORSALE1;fval=${price}`])?.prices).toEqual(+ [],+ );+ },+ );++ it('sanitizes control and bidi characters in human-readable text', () => {+ expect(+ parseForSaleRecords(['v=FORSALE1;ftxt=Hello\nworld\u202e!'])?.texts,+ ).toEqual(['Hello world !']);+ });++ it.each([+ '\u061c',+ '\u200e',+ '\u200f',+ '\u202a',+ '\u202b',+ '\u202c',+ '\u202d',+ '\u202e',+ '\u2066',+ '\u2067',+ '\u2068',+ '\u2069',+ ])('sanitizes each Unicode bidi control: %j', (control) => {+ expect(+ parseForSaleRecords([`v=FORSALE1;ftxt=Hello${control}world`])?.texts,+ ).toEqual(['Hello world']);+ expect(+ parseForSaleRecords([+ `v=FORSALE1;furi=https://seller.example/${control}test`,+ ])?.links,+ ).toEqual([]);+ });++ it('ignores oversized records before recognizing a sale signal', () => {+ expect(+ parseForSaleRecords([`v=FORSALE1;ftxt=${'€'.repeat(100)}`]),+ ).toBeNull();+ });++ it('enforces the 255-octet boundary using UTF-8 byte length', () => {+ const text = `${'€'.repeat(79)}xx`;+ const record = `v=FORSALE1;ftxt=${text}`;+ expect(new TextEncoder().encode(record).length).toBe(255);+ expect(parseForSaleRecords([record])?.texts).toEqual([text]);+ expect(parseForSaleRecords([record + 'x'])).toBeNull();+ });++ it('keeps valid records when another answer is oversized', () => {+ expect(+ parseForSaleRecords([+ `v=FORSALE1;ftxt=${'x'.repeat(256)}`,+ 'v=FORSALE1;fval=USD10',+ ])?.prices,+ ).toEqual(['USD 10']);+ });+});++describe('for-sale lookup', () => {+ const fetchMock = vi.fn();+ const answer = (+ data: string,+ TTL = 300,+ type = 16,+ name = '_for-sale.example.com.',+ ) => ({+ name,+ type,+ TTL,+ data,+ });+ const respond = (body: unknown, status = 200) =>+ fetchMock.mockResolvedValue(new Response(JSON.stringify(body), { status }));++ beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ });+ afterEach(() => vi.unstubAllGlobals());++ it('looks up the registrable base domain with a deadline and no upstream cache', async () => {+ respond({ Status: 0, Answer: [answer('"v=FORSALE1;fval=EUR2500"')] });+ expect(await lookupForSale('*.WWW.Example.com.')).toEqual({+ domain: 'example.com',+ listing: { prices: ['EUR 2500'], links: [], texts: [] },+ });+ const [url, options] = fetchMock.mock.calls[0];+ expect(url.toString()).toBe(+ 'https://cloudflare-dns.com/dns-query?name=_for-sale.example.com&type=TXT',+ );+ expect(options.headers.Accept).toBe('application/dns-json');+ expect(options.cache).toBe('no-store');+ expect(options.signal).toBeInstanceOf(AbortSignal);+ });++ it('decodes escaped quotes, backslashes and UTF-8 octets', async () => {+ respond({+ Status: 0,+ Answer: [+ answer(+ String.raw`"v=FORSALE1;ftxt=Gr\195\188\195\159e \"friend\" \\ end"`,+ ),+ ],+ });+ expect((await lookupForSale('example.com')).listing?.texts).toEqual([+ 'Grüße "friend" \\ end',+ ]);+ });++ it('handles plain TXT content for Atom listings', async () => {+ respond({+ Status: 0,+ Answer: [+ answer('v=FORSALE1;ftxt=This domain is for sale on atom.com'),+ answer('v=FORSALE1;fval=USD71256'),+ answer(+ 'v=FORSALE1;furi=https://www.atom.com/name/recruitable?utm_source=forsale-dns',+ ),+ ],+ });+ expect((await lookupForSale('example.com')).listing).toEqual({+ prices: ['USD 71256'],+ links: ['https://www.atom.com/name/recruitable?utm_source=forsale-dns'],+ texts: ['This domain is for sale on atom.com'],+ });+ });++ it('handles the email listing published by forsaledns.net', async () => {+ respond({+ Status: 0,+ Answer: [+ answer(+ '"v=FORSALE1;furi=mailto:[email protected]"',+ 300,+ 16,+ '_for-sale.forsaledns.net.',+ ),+ answer(+ '"v=FORSALE1;fval=USD195000"',+ 300,+ 16,+ '_for-sale.forsaledns.net.',+ ),+ ],+ });+ expect(await lookupForSale('forsaledns.net')).toEqual({+ domain: 'forsaledns.net',+ listing: {+ prices: ['USD 195000'],+ links: ['mailto:[email protected]'],+ texts: [],+ },+ });+ expect(fetchMock.mock.calls[0][0].searchParams.get('name')).toBe(+ '_for-sale.forsaledns.net',+ );+ });++ it.each([+ '"v=FORSALE1;ftxt=\\999"',+ '"v=FORSALE1;" garbage',+ '"v=FORSALE1;',+ '"v=FORSALE1;" "fval=USD10"',+ '"v=FOR" "SALE1;"',+ ])('ignores malformed presentation data: %s', async (data) => {+ respond({ Status: 0, Answer: [answer(data)] });+ expect((await lookupForSale('example.com')).listing).toBeNull();+ });++ it.each(['fcod', 'ftxt', 'furi', 'fval'])(+ 'preserves the sale marker when %s contains invalid UTF-8',+ async (tag) => {+ respond({ Status: 0, Answer: [answer(`"v=FORSALE1;${tag}=\\255"`)] });+ expect((await lookupForSale('example.com')).listing).toEqual({+ prices: [],+ links: [],+ texts: [],+ });+ },+ );++ it('does not accept invalid UTF-8 in the version marker', async () => {+ respond({ Status: 0, Answer: [answer('"v=FORSALE\\255;fcod=opaque"')] });+ expect((await lookupForSale('example.com')).listing).toBeNull();+ });++ it('does not accept a UTF-8 byte order mark before the version marker', async () => {+ respond({+ Status: 0,+ Answer: [answer(String.raw`"\239\187\191v=FORSALE1;fval=USD1"`)],+ });+ expect((await lookupForSale('example.com')).listing).toBeNull();+ });++ it.each([+ `"v=FORSALE1;ftxt=${'x'.repeat(240)}"`,+ `"v=FORSALE1;ftxt=${String.raw`\195\188`.repeat(120)}"`,+ `"v=FORSALE1;fcod=${String.raw`\255`.repeat(240)}"`,+ ])(+ 'ignores overlong quoted records, including invalid optional UTF-8',+ async (data) => {+ respond({ Status: 0, Answer: [answer(data)] });+ expect((await lookupForSale('example.com')).listing).toBeNull();+ },+ );++ it('accepts a quoted record at the 255-octet boundary', async () => {+ const text = 'x'.repeat(239);+ respond({ Status: 0, Answer: [answer(`"v=FORSALE1;ftxt=${text}"`)] });+ expect((await lookupForSale('example.com')).listing?.texts).toEqual([text]);+ });++ it.each([+ '51.198.in-addr.arpa',+ '0.1.ip6.arpa',+ '1.2.e164.arpa',+ 'WWW.IN-ADDR.ARPA.',+ ])('skips infrastructure domains before querying DNS: %s', async (domain) => {+ expect((await lookupForSale(domain)).listing).toBeNull();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('accepts answer sets at the processing limits', async () => {+ respond({+ Status: 0,+ Answer: Array.from({ length: 256 }, () =>+ answer(+ 'v=FORSALE1;ftxt=' + 'x'.repeat(4096 - 'v=FORSALE1;ftxt='.length),+ ),+ ),+ });+ expect((await lookupForSale('example.com')).listing).toBeNull();+ });++ it.each(+ [+ Array.from({ length: 257 }, () => answer('v=FORSALE1;')),+ [answer('x'.repeat(4097))],+ [answer('€'.repeat(1366))],+ ].map((answers) => ({ answers })),+ )('rejects oversized DNS responses', async ({ answers }) => {+ respond({ Status: 0, Answer: answers });+ await expect(lookupForSale('example.com')).rejects.toThrow(+ 'exceeds size limits',+ );+ });++ it('ignores non-TXT answers while preserving version-only listings', async () => {+ respond({+ Status: 0,+ Answer: [answer('alias.example.', 30, 5), answer('"v=FORSALE1;"', 7200)],+ });+ expect((await lookupForSale('example.com')).listing).toEqual({+ prices: [],+ links: [],+ texts: [],+ });+ });++ it.each([+ { Status: 0 },+ { Status: 3 },+ { Status: 3, Answer: [answer('"v=FORSALE1;"')] },+ { Status: 0, Answer: [answer('"unrelated TXT"')] },+ ])(+ 'returns no listing for successful responses without a signal: %j',+ async (body) => {+ respond(body);+ expect(await lookupForSale('example.com')).toEqual({+ domain: 'example.com',+ listing: null,+ });+ },+ );++ it.each([+ { Status: 2 },+ { Status: 5 },+ { Status: 0, TC: true },+ {},+ { Status: 0, Answer: [answer('"v=FORSALE1;"', -1)] },+ ])('rejects DNS errors, truncated or invalid responses: %j', async (body) => {+ respond(body);+ await expect(lookupForSale('example.com')).rejects.toThrow();+ });++ it('rejects HTTP and network failures', async () => {+ respond({}, 503);+ await expect(lookupForSale('example.com')).rejects.toMatchObject({+ cause: { message: expect.stringContaining('HTTP 503') },+ });+ fetchMock.mockRejectedValue(new DOMException('Timed out', 'TimeoutError'));+ await expect(lookupForSale('example.com')).rejects.toThrow('Timed out');+ });++ it('rejects invalid input before making a lookup', async () => {+ await expect(lookupForSale('example.com&name=evil.com')).rejects.toThrow(+ 'Invalid domain',+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/lib/for-sale.ts b/lib/for-sale.tsnew file mode 100644index 0000000..59b6876--- /dev/null+++ b/lib/for-sale.ts@@ -0,0 +1,147 @@+import { CloudflareDoHResolver } from './resolvers/cloudflare';+import { getBaseDomain, isValidDomain } from './utils';++const VERSION = 'v=FORSALE1;';+const MAX_ANSWERS = 256;+const MAX_ANSWER_BYTES = 4096;+const UNSAFE_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\p{Bidi_Control}]/gu;++export type ForSaleListing = {+ prices: string[];+ links: string[];+ texts: string[];+};++export type ForSaleSummary = {+ domain: string;+ listing: ForSaleListing | null;+};++const safeLink = (value: string): string | null => {+ if (/[\s\u0000-\u001f\u007f-\u009f\p{Bidi_Control}]/u.test(value))+ return null;+ try {+ const url = new URL(value);+ if (!['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol))+ return null;+ if (url.username || url.password || (!url.pathname && !url.hostname))+ return null;+ return url.href;+ } catch {+ return null;+ }+};++// Parse decoded TXT RDATA, not DNS presentation strings. A valid version alone+// is a sale signal, even when the optional content is unknown or invalid (§2.1).+export const parseForSaleRecords = (+ records: string[],+): ForSaleListing | null => {+ const saleRecords = records.filter(+ (record) =>+ record.startsWith(VERSION) &&+ new TextEncoder().encode(record).length <= 255,+ );+ if (!saleRecords.length) return null;++ const prices = new Set<string>();+ const links = new Set<string>();+ const texts = new Set<string>();++ for (const record of saleRecords) {+ const content = record.slice(VERSION.length).trimStart();+ const separator = content.indexOf('=');+ if (separator === -1) continue;++ const tag = content.slice(0, separator);+ const value = content.slice(separator + 1);++ if (tag === 'fval' && /^[A-Z]+[0-9]+(?:\.[0-9]+)?$/.test(value)) {+ prices.add(value.replace(/^([A-Z]+)/, '$1 '));+ } else if (tag === 'furi') {+ const link = safeLink(value);+ if (link) links.add(link);+ } else if (tag === 'ftxt') {+ const text = value.replace(UNSAFE_CHARACTERS, ' ').trim();+ if (text) texts.add(text);+ }+ // fcod is a cooperating party's opaque code, not a URL we can decode.+ }+ return { prices: [...prices], links: [...links], texts: [...texts] };+};++// Accept plain TXT content or quoted DNS presentation data from DoH resolvers.+// Sale records must contain a single character-string (§2.4).+// Decode decimal octet escapes before interpreting their UTF-8 content.+const decodeTxt = (data: string): string | null => {+ if (!data.startsWith('"')) return data;++ const match = /^"((?:[^"\\]|\\[\s\S])*)"$/u.exec(data);+ if (!match) return null;+ const content = match[1];+ const bytes: number[] = [];+ for (let i = 0; i < content.length; ) {+ if (content[i] === '\\') {+ const decimal = content.slice(i + 1, i + 4);+ if (/^[0-9]{3}$/.test(decimal)) {+ const octet = Number(decimal);+ if (octet > 255) return null;+ bytes.push(octet);+ i += 4;+ continue;+ }+ i++;+ }+ const character = String.fromCodePoint(content.codePointAt(i)!);+ bytes.push(...new TextEncoder().encode(character));+ i += character.length;+ }++ if (bytes.length > 255) return null;++ try {+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(+ new Uint8Array(bytes),+ );+ } catch {+ // Invalid optional bytes must not hide an otherwise valid sale signal.+ return VERSION.split('').every(+ (character, index) => bytes[index] === character.charCodeAt(0),+ )+ ? VERSION+ : null;+ }+};++export const lookupForSale = async (+ domain: string,+): Promise<ForSaleSummary> => {+ if (!isValidDomain(domain)) throw new Error('Invalid domain');++ const baseDomain = getBaseDomain(domain).toLowerCase();+ if (baseDomain === 'arpa' || baseDomain.endsWith('.arpa'))+ return { domain: baseDomain, listing: null };++ const resolver = new CloudflareDoHResolver({+ signal: AbortSignal.timeout(2500),+ });+ const { answers, rcode } = await resolver.resolveAnswers(+ `_for-sale.${baseDomain}`,+ 'TXT',+ );+ if (+ answers.length > MAX_ANSWERS ||+ answers.some(+ ({ data }) =>+ data.length > MAX_ANSWER_BYTES ||+ new TextEncoder().encode(data).length > MAX_ANSWER_BYTES,+ )+ )+ throw new Error('For-sale DNS response exceeds size limits');++ const records = (rcode === 0 ? answers : [])+ .filter((answer) => answer.type === 16)+ .map((answer) => decodeTxt(answer.data))+ .filter((record): record is string => record !== null);+ return { domain: baseDomain, listing: parseForSaleRecords(records) };+};diff --git a/lib/format-sale-price.test.ts b/lib/format-sale-price.test.tsnew file mode 100644index 0000000..8eebc56--- /dev/null+++ b/lib/format-sale-price.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { formatSalePrice } from './format-sale-price';++describe('sale price formatting', () => {+ it.each([+ ['USD 71256', '$71,256'],+ ['EUR 2500', '€2,500'],+ ['GBP 1250.50', '£1,250.50'],+ ['JPY 5000', '¥5,000'],+ ['USD 0', '$0'],+ ['USD 10.00', '$10.00'],+ ['EUR 0.00', '€0.00'],+ ['JPY 10.00', '¥10.00'],+ ['BTC 10.0000', 'BTC\u00a010.0000'],+ ['EUR 0.000001', '€0.000001'],+ ['USD 9007199254740993.01', '$9,007,199,254,740,993.01'],+ ])('formats %s as %s', (price, formatted) => {+ expect(formatSalePrice(price)).toBe(formatted);+ });++ it('keeps cryptocurrency precision when there is no standard symbol', () => {+ expect(formatSalePrice('BTC 0.000010')).toBe('BTC\u00a00.000010');+ });++ it.each(['TOKEN 100', 'not a price', 'USD -1', `USD 0.${'1'.repeat(101)}`])(+ 'falls back to the original value for %s',+ (price) => expect(formatSalePrice(price)).toBe(price),+ );+});diff --git a/lib/format-sale-price.ts b/lib/format-sale-price.tsnew file mode 100644index 0000000..f8e10fa--- /dev/null+++ b/lib/format-sale-price.ts@@ -0,0 +1,30 @@+/** Format an RFC 10023 price without converting its exact decimal to a float. */+export const formatSalePrice = (price: string): string => {+ const match = /^([A-Z]+) (\d+(?:\.\d+)?)$/.exec(price);+ if (!match) return price;++ const [, currency, amount] = match;+ const fractionDigits = amount.split('.')[1]?.length ?? 0;+ if (fractionDigits > 100) return price;++ try {+ // A fixed locale keeps server and client rendering consistent.+ const currencyDigits =+ new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency,+ }).resolvedOptions().maximumFractionDigits ?? 2;+ const digits = Math.max(currencyDigits, fractionDigits);++ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency,+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ trailingZeroDisplay: fractionDigits ? 'auto' : 'stripIfInteger',+ }).format(amount as Intl.StringNumericLiteral);+ } catch {+ // Nonstandard currency codes remain readable instead of breaking the tile.+ return price;+ }+};diff --git a/lib/whois.test.ts b/lib/whois.test.tsindex 835eef1..717c5be 100644--- a/lib/whois.test.ts+++ b/lib/whois.test.ts@@ -1,6 +1,13 @@-import { describe, expect, it } from 'vitest';+import type * as Whoiser from 'whoiser';+import { describe, expect, it, vi } from 'vitest';-import { formatDate } from './whois';+import { formatDate, getWhoisSummary } from './whois';++const { whoisDomain } = vi.hoisted(() => ({ whoisDomain: vi.fn() }));+vi.mock('whoiser', async (importOriginal) => ({+ ...(await importOriginal<typeof Whoiser>()),+ whoisDomain,+}));describe('formatDate', () => {it('formats a date as an ISO string without the time', () => {@@ -8,3 +15,37 @@ describe('formatDate', () => {expect(formatDate(date)).toBe('2021-01-01');});});++describe('getWhoisSummary', () => {+ it('marks registration as unknown when the lookup fails', async () => {+ whoisDomain.mockRejectedValue(new Error('timeout'));+ expect(await getWhoisSummary('example.com')).toEqual({+ registered: true,+ unknown: true,+ registrar: null,+ createdAt: null,+ dnssec: null,+ });+ });++ it('marks registration as unknown when the WHOIS server query errors', async () => {+ // whoiser resolves socket errors and timeouts instead of rejecting.+ whoisDomain.mockResolvedValue({ 'whois.example': { error: 'Timeout' } });+ expect(await getWhoisSummary('example.com')).toMatchObject({+ registered: true,+ unknown: true,+ });+ });++ it('does not mark a parsed result as unknown', async () => {+ whoisDomain.mockResolvedValue({+ 'whois.example': { Registrar: 'Example registrar', __raw: 'ok' },+ });+ expect(await getWhoisSummary('example.com')).toEqual({+ registered: true,+ registrar: 'Example registrar',+ createdAt: null,+ dnssec: null,+ });+ });+});diff --git a/lib/whois.ts b/lib/whois.tsindex 863e932..08ab3a9 100644--- a/lib/whois.ts+++ b/lib/whois.ts@@ -71,6 +71,8 @@ type WhoisSummary =}| {registered: true;+ // Set when the lookup failed, so registration was assumed, not confirmed.+ unknown?: true;registrar: string | null;createdAt: string | null;dnssec: string | null;@@ -99,7 +101,8 @@ export const getWhoisSummary = async (const firstResult = getFirstResult(results);- if (!firstResult) {+ // whoiser resolves socket errors and timeouts as { error } per server.+ if (!firstResult || 'error' in firstResult) {throw new Error('No valid result found for domain ' + domain);}@@ -133,6 +136,7 @@ export const getWhoisSummary = async (} catch {return {registered: true,+ unknown: true,registrar: null,createdAt: null,dnssec: null,