Trustworthy Link Validation and Engineering Safeguards for AI Q&A Recommendations

    This article examines how to validate links returned by large language model-powered shopping, search, and navigation assistants. It classifies link risks such as impersonation domains, similar top-level domains, re-registered expired domains, and short-link redirect chains; describes a validation pipeline covering URL extraction, protocol checks, whitelist matching, redirect expansion, certificate validation, and RDAP queries; and presents risk grading plus engineering safeguards with sample Python code. Readers will learn how to treat model-generated links as untrusted input and reduce user loss when validation fails or returns unknown results.

    1. Background

    More and more users ask intelligent dialogue systems before shopping, and then decide which website to use for placing an order. Such answers are often confident in tone and clear in structure, so users usually do not check every URL one by one. The problem is that the URLs in an answer may not point to the brand’s official site. If a user enters payment information on the wrong page, the loss can occur immediately.

    A language model can only process text, and it cannot reliably determine which company owns a domain name. It sees character similarity, while domain ownership needs to be confirmed by external data such as registration information, certificates, and whitelists. Therefore, links output by a model should be treated as untrusted input and must pass independent system-side validation before being shown to users.

    This article abstracts this scenario into a general technical problem: when a language model participates in shopping guidance, search, and navigation, how can output links be kept trustworthy, and how can user loss be reduced when something goes wrong? The article proceeds in the order of risk classification, validation flow, risk grading, and safeguards, and provides sample code. It does not cite specific test ratios. Readers who need industry data should consult the original test reports and cite the sources.

    2. Risk Classification

    Link risks can be divided into four categories by attack method. Each category has different detection signals, and the validation flow needs to cover each one separately.

    Risk type Typical form Main detection signals
    Impersonation sites The domain differs from the official domain by one character or one hyphen, or uses homoglyphs Edit distance to the whitelist, punycode encoding, similarity between the page title and the brand name
    Similar top-level domains The same entity uses a different suffix such as .cn, .net, or .shop Whether the suffix is registered in the whitelist, whether registrant information matches the brand
    Re-registered expired domains An old domain abandoned by the brand is re-registered by someone else Registration time later than known brand domains, registrar or DNS changes, recently issued certificates
    Short links and multi-hop redirects Short links hide the real destination, and the redirect chain passes through multiple unrelated hosts The hosts at each node of the redirect chain, and whether the final host is on the whitelist

    2.1 How to Identify Impersonation Sites

    Impersonation sites often copy the style and logo of a brand page. It is difficult for users to distinguish small differences on a mobile screen. Homoglyph attacks replace ordinary letters with visually similar Unicode characters. Browsers usually display such domains in punycode form starting with xn--. The validation program should first restore the domain and then compare it with the whitelist.

    2.2 How to Detect Expired Domains

    After a brand abandons a domain, the domain first goes through a grace period and is then released, and anyone can re-register it. The new registrant can inherit old backlinks, search rankings, and user bookmarks. If old URLs remain in historical pages or model training data, the model may recommend such a URL to users.

    The harm of an expired domain depends on whether it collects input. A page set up by a domain squatter can induce users to enter card numbers, passwords, or verification codes, so payment information leakage is the main consequence. A domain being expired alone does not prove malicious intent, because a brand may also register new domains. Therefore, the detection result should be a risk warning rather than a direct judgment of attack.

    Detection signals for expired domains include: the registration time is significantly later than known brand domains; the registrar or NS servers changed recently; the certificate was issued recently; the page content differs greatly from the brand’s historical pages; and the site redirects to a site unrelated to the brand. The risk level should be raised only when multiple signals appear at the same time.

    Short-link services hide the real destination. A redirect chain may also pass through multiple hosts, where the first few hops look normal and only the last hop points to a phishing page. Validation should compare the final host, not only the first URL the user clicks.

    3.1 Validation Flow

    Validation is performed in the following steps. If any step cannot be completed, the result should be marked as unknown and must not pass by default.

    1. Extract links: extract URLs from the model answer, remove trailing Chinese punctuation and parentheses, and normalize the hostname to lowercase.
    2. Protocol check: allow only http and https, and reject schemes such as javascript, data, and file.
    3. Whitelist matching: query the official domain set maintained by the platform for the brand, and compare registrable domains (eTLD+1) rather than full hostnames. The registrable domain is calculated according to the public suffix list. For example, the registrable domain of shop.example-brand.com.cn is example-brand.com.cn.
    4. Redirect chain expansion: request each hop and record the host at each hop, set timeouts and a maximum hop count, and disable automatic redirect following.
    5. Certificate validation: check whether the certificate chain is complete, whether the hostname matches, and whether the issuance time is too recent.
    6. Registration information query: obtain registration time, registrar, and NS changes through an RDAP interface. Raw WHOIS text formats are inconsistent, so RDAP is preferred.
    7. Risk grading: assign a level based on the above results, as described in Section 4.

    3.2 Sample Code

    Dependencies: Python 3.11 or later, requests==2.32.3, and tldextract==5.1.2. Key parameters are a 5-second timeout per hop, a maximum of 5 redirects, and a 30-day threshold for newly registered domains. Certificate validation results and domain age are provided by other modules and passed as parameters in the sample code.

    1. import ipaddress
    2. import socket
    3. from dataclasses import dataclass, field
    4. from urllib.parse import urlparse, urljoin
    5. import requests # requests==2.32.3
    6. import tldextract # tldextract==5.1.2
    7. REQUEST_TIMEOUT = 5 # Timeout per hop in seconds
    8. MAX_REDIRECTS = 5 # Maximum redirects
    9. NEW_DOMAIN_DAYS = 30 # Domains younger than this are high risk; sample threshold, adjust based on data
    10. # Whitelist maintained by the platform: brand -> set of registrable domains
    11. OFFICIAL_DOMAINS = {
    12. "example-brand": {"example-brand.com", "example-brand.com.cn"},
    13. }
    14. # Use the built-in public suffix list to avoid runtime network access
    15. _EXTRACTOR = tldextract.TLDExtract(suffix_list_urls=())
    16. @dataclass
    17. class LinkReport:
    18. url: str
    19. registrable: str = ""
    20. level: str = "unknown"
    21. reasons: list = field(default_factory=list)
    22. hops: list = field(default_factory=list)
    23. def registrable_domain(host: str) -> str:
    24. ext = _EXTRACTOR(host)
    25. if not ext.domain or not ext.suffix:
    26. return ""
    27. return f"{ext.domain}.{ext.suffix}"
    28. def is_private_host(host: str) -> bool:
    29. try:
    30. infos = socket.getaddrinfo(host, None)
    31. except socket.gaierror:
    32. return True # Treat unresolvable hosts as unsafe
    33. for info in infos:
    34. ip = ipaddress.ip_address(info[4][0])
    35. if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
    36. return True
    37. return False
    38. def expand_redirects(url: str) -> list:
    39. hops = []
    40. current = url
    41. with requests.Session() as session:
    42. for _ in range(MAX_REDIRECTS + 1):
    43. parsed = urlparse(current)
    44. if parsed.scheme not in ("http", "https") or not parsed.hostname:
    45. raise ValueError("Invalid redirect target")
    46. if is_private_host(parsed.hostname):
    47. raise ValueError("Target resolves to a private network or cannot be resolved")
    48. hops.append(parsed.hostname)
    49. resp = session.get(current, allow_redirects=False,
    50. stream=True, timeout=REQUEST_TIMEOUT)
    51. location = resp.headers.get("Location")
    52. resp.close()
    53. if resp.status_code in (301, 302, 303, 307, 308) and location:
    54. current = urljoin(current, location)
    55. else:
    56. return hops
    57. raise RuntimeError("Redirect count exceeds limit")
    58. def assess(url: str, brand: str, cert_valid: bool, domain_age_days=None) -> LinkReport:
    59. report = LinkReport(url=url)
    60. if urlparse(url).scheme not in ("http", "https"):
    61. report.level = "high"
    62. report.reasons.append("Protocol is not http or https")
    63. return report
    64. try:
    65. report.hops = expand_redirects(url)
    66. except (requests.RequestException, RuntimeError, ValueError) as exc:
    67. report.level = "unknown"
    68. report.reasons.append(f"Redirect chain could not be expanded: {exc.__class__.__name__}")
    69. return report
    70. final_reg = registrable_domain(report.hops[-1])
    71. report.registrable = final_reg
    72. official = OFFICIAL_DOMAINS.get(brand, set())
    73. if final_reg in official:
    74. if cert_valid:
    75. report.level = "low"
    76. report.reasons.append("Final destination is on the whitelist and certificate is valid")
    77. else:
    78. report.level = "medium"
    79. report.reasons.append("Final destination is on the whitelist, but certificate validation failed")
    80. return report
    81. reasons = ["Final destination is not on the whitelist"]
    82. new_domain = domain_age_days is not None and domain_age_days < NEW_DOMAIN_DAYS
    83. if domain_age_days is None:
    84. reasons.append("Registration time unknown; manual review required")
    85. elif new_domain:
    86. reasons.append(f"Registered only {domain_age_days} days ago")
    87. if not cert_valid:
    88. reasons.append("Certificate validation failed")
    89. report.reasons = reasons
    90. report.level = "high" if (not cert_valid or new_domain) else "medium"
    91. return report
    92. if __name__ == "__main__":
    93. r = assess("https://shop.example-brand.co/item", "example-brand",
    94. cert_valid=True, domain_age_days=12)
    95. print(r.level, r.reasons)
    96. # Example output (assuming the address is reachable and has no redirects):
    97. # high ['Final destination is not on the whitelist', 'Registered only 12 days ago']
    98. # If the domain cannot be resolved, the result is unknown.

    3.3 Common Errors and False-Positive Troubleshooting

    • Expired whitelist: the brand has launched a new domain but it has not been registered, so the result falls into high or medium. During troubleshooting, check the brand’s official announcements, update the whitelist after registration, and keep evidence.
    • Missing public suffix: if the suffix list is too old, suffixes such as .com.cn may be calculated incorrectly as registrable domains. During troubleshooting, confirm the tldextract version and the built-in list.
    • CDN or cloud service domains: when an official site is hosted on a CDN, the certificate belongs to the CDN provider, and the final host is not on the whitelist. This requires maintaining official-domain and CDN-edge entries.