domain-hound 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.agents/plugins/marketplace.json +1 -0
  2. package/.claude-plugin/marketplace.json +1 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/README.md +84 -13
  5. package/assets/readme-search.png +0 -0
  6. package/clis/domain-check/broker-atom.mjs +78 -0
  7. package/clis/domain-check/com-site.mjs +64 -25
  8. package/clis/domain-check/confirm.mjs +10 -5
  9. package/clis/domain-check/dossier.mjs +603 -0
  10. package/clis/domain-check/google-play.mjs +24 -11
  11. package/clis/domain-check/index.mjs +75 -23
  12. package/clis/domain-check/marketplaces.mjs +107 -0
  13. package/clis/domain-check/meaning-words.LICENSE.txt +408 -0
  14. package/clis/domain-check/meaning-words.json +2397 -0
  15. package/clis/domain-check/meaning.mjs +77 -0
  16. package/clis/domain-check/name-search.mjs +91 -14
  17. package/clis/domain-check/naming-method.mjs +6 -4
  18. package/clis/domain-check/registry.mjs +2 -2
  19. package/clis/domain-check/safe-web.mjs +207 -0
  20. package/clis/domain-check/trademarks.mjs +372 -0
  21. package/clis/domain-check/triage-sources.mjs +39 -12
  22. package/clis/domain-check/triage.mjs +190 -63
  23. package/clis/spaceship/buy.mjs +327 -0
  24. package/clis/spaceship/client.mjs +170 -0
  25. package/clis/spaceship/dns.mjs +292 -0
  26. package/clis/spaceship/quote.mjs +123 -0
  27. package/clis/spaceship/setup.mjs +81 -0
  28. package/clis/spaceship/store.mjs +104 -0
  29. package/clis/spaceship/tools.mjs +258 -0
  30. package/display.mjs +57 -30
  31. package/dossier.mjs +185 -0
  32. package/package.json +20 -2
  33. package/plugin.json +4 -3
  34. package/results-style.mjs +10 -0
  35. package/results.mjs +258 -62
  36. package/server.json +2 -2
  37. package/server.mjs +223 -96
  38. package/share.mjs +43 -0
  39. package/site/r/share-format.mjs +125 -0
@@ -0,0 +1,77 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { foldLatin } from './triage-sources.mjs';
3
+
4
+ // Bad-meaning screen from the open LDNOOBW lists (CC BY 4.0, see meaning-words.LICENSE.txt), built by
5
+ // scripts/build-meaning-words.mjs. A hit is a note and at most "Check first"; it never makes a name Avoid.
6
+ // Rules stay narrow to keep false alarms low:
7
+ // - is: the whole name, or one word of it ("Kick Ass"), is a listed word of three or more letters;
8
+ // - contains: a long listed word that no English dictionary word contains sits inside the glued name;
9
+ // - sounds like: the name or one word of it is spelled differently but said the same as one of those long words
10
+ // (ph/f, c/k, doubled letters).
11
+ // Words with accents match only with their accents ("göt" never matches "got"), unless five or more letters long.
12
+ const data = JSON.parse(readFileSync(new URL('./meaning-words.json', import.meta.url), 'utf8'));
13
+ const languageNames = { en: 'English', es: 'Spanish', pt: 'Portuguese', fr: 'French', de: 'German', it: 'Italian',
14
+ no: 'Norwegian', sv: 'Swedish', da: 'Danish', nl: 'Dutch', pl: 'Polish', tr: 'Turkish', 'ja-Latn': 'Japanese',
15
+ 'zh-Latn': 'Chinese' };
16
+ export const meaningSource = { name: data.source, url: data.url, license: data.license };
17
+
18
+ const plain = value => value.normalize('NFC').toLowerCase().replace(/ /g, '');
19
+ const folded = value => foldLatin(value).replace(/[^a-z]/g, '');
20
+ // Said the same: ph/f, ck/c/q/k, soft c/s, x/ks, z/s, and doubled letters.
21
+ export const soundKey = value => folded(value).replace(/ph/g, 'f').replace(/ck/g, 'k').replace(/c(?=[eiy])/g, 's')
22
+ .replace(/[cq]/g, 'k').replace(/x/g, 'ks').replace(/z/g, 's').replace(/(.)\1+/g, '$1');
23
+
24
+ const exact = new Map();
25
+ const loose = new Map();
26
+ const phrases = new Map();
27
+ const sounds = new Map();
28
+ const add = (map, key, word, language) => {
29
+ const entry = map.get(key) ?? { word, languages: [] };
30
+ if (!entry.languages.includes(language)) entry.languages.push(language);
31
+ map.set(key, entry);
32
+ };
33
+ for (const [language, words] of Object.entries(data.words)) {
34
+ for (const word of words) {
35
+ const key = folded(word);
36
+ if (word.includes(' ')) add(phrases, key, word, language);
37
+ else if (plain(word) === key || key.length >= 5) add(loose, key, word, language);
38
+ else add(exact, plain(word), word, language);
39
+ }
40
+ }
41
+ const strong = data.strong.filter(word => loose.has(word)).sort((a, b) => b.length - a.length);
42
+ for (const word of strong) if (!sounds.has(soundKey(word))) sounds.set(soundKey(word), loose.get(word));
43
+
44
+ function note(how, { word, languages }) {
45
+ const where = languages.slice(0, 2).map(language => languageNames[language] ?? language).join(' and ');
46
+ const text = { is: '“' + word + '” is a rude word in ' + where, contains: 'Contains “' + word + '”, a rude word in ' + where,
47
+ sounds: 'Sounds like “' + word + '”, a rude word in ' + where }[how];
48
+ return { how, word, languages: languages.slice(0, 2).map(language => languageNames[language] ?? language), note: text };
49
+ }
50
+
51
+ // The words of a name as typed: spaces, hyphens, digits and camel case split it.
52
+ function words(input) {
53
+ return String(input ?? '').normalize('NFC').replace(/(\p{Ll})(\p{Lu})/gu, '$1 $2').toLowerCase()
54
+ .split(/[^\p{L}]+/u).filter(Boolean);
55
+ }
56
+
57
+ export function screenMeaning(input) {
58
+ const parts = words(input);
59
+ if (!parts.length) return null;
60
+ const whole = parts.join('');
61
+ const wholeKey = folded(whole);
62
+ const find = value => exact.get(plain(value)) ?? loose.get(folded(value));
63
+ const named = find(whole) ?? phrases.get(wholeKey);
64
+ if (named && folded(whole).length >= 3) return note('is', named);
65
+ for (const part of parts.length > 1 ? parts : []) {
66
+ const hit = folded(part).length >= 3 && find(part);
67
+ if (hit) return note('contains', hit);
68
+ }
69
+ const inside = strong.find(word => word !== wholeKey && wholeKey.includes(word));
70
+ if (inside) return note('contains', loose.get(inside));
71
+ for (const part of new Set([whole, ...parts])) {
72
+ const key = folded(part);
73
+ const hit = key.length >= 3 && sounds.get(soundKey(part));
74
+ if (hit && folded(hit.word) !== key) return note('sounds', hit);
75
+ }
76
+ return null;
77
+ }
@@ -1,7 +1,8 @@
1
1
  import { domainToASCII, domainToUnicode } from 'node:url';
2
2
  import { checkDomainSite } from './com-site.mjs';
3
3
  import { cachedSignals, confirmingShops } from './confirm.mjs';
4
- import { bundledCatalog, datedListPrices, getNameCatalog, loadCachedCatalog, requestEndings, supportedEndings, targetEndings } from './price-catalog.mjs';
4
+ import { bundledCatalog, datedListPrices, getNameCatalog, isListPriceUsable, listedPrices, loadCachedCatalog, requestEndings,
5
+ supportedEndings, targetEndings } from './price-catalog.mjs';
5
6
  import { linkable, shopSearchUrl } from './prices.mjs';
6
7
  import { lookupRegistrations } from './registry.mjs';
7
8
  import { foldLatin } from './triage-sources.mjs';
@@ -45,6 +46,16 @@ export { requestEndings, supportedEndings };
45
46
  export const restrictedEndings = Object.keys(facts).filter(tld => facts[tld].eligibility);
46
47
  const firstCost = row => row.firstPayment ?? Infinity;
47
48
 
49
+ // The broker dossier orders mainstream endings first, then .xyz and .tech, then other supported endings.
50
+ export const mainstreamEndings = ['com', 'ai', 'si', 'io', 'app', 'dev', 'me', 'co', 'net', 'org'];
51
+ export const fallbackEndings = ['xyz', 'tech'];
52
+ // Requested endings, exact domains and eligibility opt-ins can compete with the mainstream tier.
53
+ export function endingTier(domain, requested = [], eligible = []) {
54
+ const tld = domainEnding(domain);
55
+ if (mainstreamEndings.includes(tld) || requested.includes(tld) || requested.includes(domain) || eligible.includes(tld)) return 0;
56
+ return fallbackEndings.includes(tld) ? 1 : 2;
57
+ }
58
+
48
59
  export function validEligibility(eligible) {
49
60
  return Array.isArray(eligible) && new Set(eligible).size === eligible.length
50
61
  && eligible.every(tld => restrictedEndings.includes(tld));
@@ -148,7 +159,8 @@ export function termCosts(tld, price, renewal) {
148
159
  };
149
160
  }
150
161
 
151
- export function rankName(rows) {
162
+ // Exact names first, then by attractiveness tier, then by upfront payment (including any minimum term).
163
+ export function rankName(rows, requested = [], eligible = []) {
152
164
  return rows.map(row => {
153
165
  const { tld, exact, status, price = null, renewal = null } = row;
154
166
  const reason = status === 'premium' ? row.premium === 'risk' ? 'May be premium' : 'Premium price' : status === 'reserved' ? 'Not offered for registration'
@@ -157,13 +169,17 @@ export function rankName(rows) {
157
169
  : exact ? 'Exact name' : 'Name variation';
158
170
  return { ...row, ...termCosts(tld, price, renewal), reason, terms: facts[tld] ?? null,
159
171
  renewalJump: price != null && renewal > 2 * price };
160
- }).sort((a, b) => Number(b.exact) - Number(a.exact) || firstCost(a) - firstCost(b)
172
+ }).sort((a, b) => Number(b.exact) - Number(a.exact)
173
+ || endingTier(a.domain, requested, eligible) - endingTier(b.domain, requested, eligible) || firstCost(a) - firstCost(b)
161
174
  || supportedEndings.indexOf(a.tld) - supportedEndings.indexOf(b.tld) || a.domain.localeCompare(b.domain));
162
175
  }
163
176
 
164
- export function pickName(rows, eligible) {
177
+ // The cheapest upfront payment within the most attractive tier that has a recommendable free row.
178
+ export function pickName(rows, eligible, requested = []) {
179
+ const tier = row => endingTier(row.domain, requested, eligible);
165
180
  return rows.reduce((best, row) => {
166
181
  if (!canRecommend(row.tld, eligible) || premiumRisk(row.domain) || !['probably-free', 'confirmed'].includes(row.status)) return best;
182
+ if (best && tier(row) !== tier(best)) return tier(row) < tier(best) ? row : best;
167
183
  return !best || firstCost(row) < firstCost(best) ||
168
184
  (firstCost(row) === firstCost(best) && row.exact && !best.exact) ? row : best;
169
185
  }, undefined);
@@ -194,9 +210,36 @@ export function listQuote(catalog, { domain, tld }, now, bundled = bundledCatalo
194
210
  };
195
211
  }
196
212
 
213
+ // Savings are proof, never a pitch: the pick's three-year list cost against the median of at least three distinct shops'
214
+ // dated list prices for the same ending, all over a common three-year term. The lower median is used, so the comparison
215
+ // is never the highest price. Only a strictly positive difference counts; anything else returns null.
216
+ export function listSavings(catalog, { tld, price, renewal, shop, priceCheckedAt }, now, bundled = bundledCatalog) {
217
+ if (!(price > 0) || !(renewal > 0) || !shop || !priceCheckedAt) return null;
218
+ const own = termCosts(tld, price, renewal);
219
+ if (own.minimumYears !== 1 || own.renewalYears !== 1 || own.threeYear == null) return null;
220
+ const byShop = new Map();
221
+ for (const row of [...datedListPrices(catalog, tld, now, bundled), ...listedPrices(bundled, tld)]) {
222
+ if (!byShop.has(row.shop) && row.firstYear > 0 && row.renewal > 0 && isListPriceUsable(row.checkedAt, now)) {
223
+ byShop.set(row.shop, row);
224
+ }
225
+ }
226
+ const listed = byShop.get(shop);
227
+ // The pick must be one of the compared list prices, unchanged.
228
+ if (listed?.firstYear !== price || listed.renewal !== renewal || listed.checkedAt !== priceCheckedAt) return null;
229
+ const totals = [...byShop.values()].map(row => ({ shop: row.shop, checkedAt: row.checkedAt,
230
+ total: termCosts(tld, row.firstYear, row.renewal).threeYear })).sort((a, b) => a.total - b.total || a.shop.localeCompare(b.shop));
231
+ if (totals.length < 3) return null;
232
+ const median = totals[Math.floor((totals.length - 1) / 2)];
233
+ const saved = Math.round((median.total - own.threeYear) * 100) / 100;
234
+ if (!(saved > 0) || median.shop === shop) return null;
235
+ const dates = totals.map(row => new Date(row.checkedAt).toISOString().slice(0, 10)).sort();
236
+ return { years: 3, here: own.threeYear, shop, median: median.total, medianShop: median.shop, saved, shops: totals.length,
237
+ checkedFrom: dates[0], checkedTo: dates.at(-1) };
238
+ }
239
+
197
240
  // A premium, reserved or possible-premium signal never leaves a list price on the row.
198
241
  export function withoutListPrice(row, status, reason) {
199
- return { ...row, status, price: null, renewal: null, priceSource: null, priceCheckedAt: null,
242
+ return { ...row, status, price: null, renewal: null, priceSource: null, priceCheckedAt: null, savings: null,
200
243
  ...(reason && { registryReason: reason }) };
201
244
  }
202
245
 
@@ -225,7 +268,8 @@ export function mergeQuote(row, quote) {
225
268
  : quote.status === 'premium' ? quote.premium ?? true : possiblePremium(row, quote) ? 'possible'
226
269
  : (row.premium === 'risk' || row.premiumRisk) && quote.standard !== true ? 'possible' : false;
227
270
  const price = money(quote.price) > 0 ? quote.price : null;
228
- return { ...row, status: premium ? 'premium' : quote.status, price, renewal: price == null ? null : quote.renewal ?? null,
271
+ // A shop quote replaces the list price, so a list-price comparison no longer applies.
272
+ return { ...row, savings: null, status: premium ? 'premium' : quote.status, price, renewal: price == null ? null : quote.renewal ?? null,
229
273
  ...(premium && { premium }), shop: quote.shopName, buyUrl: quote.buyUrl, priceCheckedAt: null, priceSource: null,
230
274
  quotedAt: quote.checkedAt ?? null, checkedAt: quote.checkedAt ?? row.checkedAt, source: 'shop' };
231
275
  }
@@ -242,10 +286,11 @@ export async function searchCandidates(groups, options = {}) {
242
286
  const siteEndings = options.siteEndings ?? (options.skipComSite ? [] : ['com']);
243
287
  const lookedUp = new Map();
244
288
  const checks = [];
289
+ const lateChecks = [];
245
290
  let catalog = null;
246
291
  let timer;
247
292
  let complete = false;
248
- const onResult = ({ domain, tld, exact }, registry) => {
293
+ const onResult = ({ domain, tld, exact }, registry, dnsCode) => {
249
294
  if (timeLeft() <= 0) return;
250
295
  const publish = (result) => {
251
296
  lookedUp.set(domain, result);
@@ -258,16 +303,32 @@ export async function searchCandidates(groups, options = {}) {
258
303
  const checkTaken = registry.status === 'taken' && exact && siteEndings.includes(tld) && (options.siteFilter?.(domain) ?? true);
259
304
  if (!checkNegative) publish(registry);
260
305
  if (!checkNegative && !checkTaken) return;
261
- const timeout = Math.min(options.siteTimeout ?? 1200, timeLeft());
306
+ if (dnsCode === 'ENOTFOUND' && !options.verifyFreeSite && !options.comSite) {
307
+ // NXDOMAIN for the hostname also rules out its web address. Reuse the DNS answer.
308
+ sites.set(domain, { result: { state: 'no-site', why: 'DNS NXDOMAIN' } });
309
+ if (checkNegative) publish(registry);
310
+ return;
311
+ }
312
+ // A taken site may get a longer, final check that outlives the first answer (settleSites collects it).
313
+ const late = checkTaken && options.lateSiteMs > 0;
314
+ const timeout = late ? options.lateSiteMs : Math.min(options.siteTimeout ?? 1200, timeLeft());
262
315
  const visit = checkNegative ? options.verifyFreeSite ?? options.comSite ?? checkDomainSite
263
316
  : options.comSite ?? checkDomainSite;
264
- const pending = Promise.resolve().then(() => visit(domain, timeout, options.siteDetails || checkNegative)).then(site => {
317
+ const pending = Promise.resolve().then(() => visit(domain, timeout, options.siteDetails || checkNegative))
318
+ .then(site => {
265
319
  sites.get(domain).result = site;
266
320
  options.onSite?.(domain, site);
267
321
  if (checkNegative) publish(applyLiveSite(registry, site));
268
322
  }, () => { if (checkNegative) publish(registry); });
269
323
  sites.set(domain, { pending });
270
- checks.push(pending);
324
+ if (!late) checks.push(pending);
325
+ else {
326
+ // The first answer still waits as long as for any site check; the late check keeps running after that.
327
+ lateChecks.push(pending);
328
+ checks.push(Promise.race([pending, new Promise(resolve => {
329
+ setTimeout(resolve, Math.min(options.siteTimeout ?? 1200, timeLeft())).unref?.();
330
+ })]));
331
+ }
271
332
  };
272
333
  const loadCatalog = options.cachedOnly ? loadCachedCatalog(options.directory)
273
334
  : getNameCatalog({ ...options, now, coldWaitMs: bundled ? 0 : Math.min(1900, budgetMs) });
@@ -301,15 +362,16 @@ export async function searchCandidates(groups, options = {}) {
301
362
  ? { shop: quote.shop, checkedAt: quote.priceCheckedAt, ...termCosts(row.tld, quote.price, quote.renewal),
302
363
  renewalJump: quote.renewal > 2 * quote.price }
303
364
  : null;
365
+ const savings = status === 'probably-free' ? listSavings(catalog, { ...row, ...quote }, now, bundled) : null;
304
366
  const settled = withPremiumRisk({ ...row, status, checkedAt: lookup.checkedAt ?? checkedAt, source: lookup.source,
305
367
  registryReason: lookup.reason, forSale: Boolean(lookup.forSale), ...(lookup.marketplace && { marketplace: lookup.marketplace }),
306
368
  ...(status === 'check-at-shop' && lookup.likely && { likely: lookup.likely }),
307
- ...(status !== 'taken' ? quote : listPrice && { listPrice }) });
369
+ ...(status !== 'taken' ? quote : listPrice && { listPrice }), ...(savings && { savings }) });
308
370
  if (status === 'premium') return { ...withoutListPrice(settled, 'premium'), premium: true };
309
371
  if (status === 'reserved') return withoutListPrice(settled, 'reserved', lookup.reason);
310
372
  const signal = status === 'taken' ? null : signals.get(row.domain);
311
373
  return signal ? mergeQuote(settled, signal) : settled;
312
- }));
374
+ }), options.preferredEndings, options.eligible);
313
375
  const checkedSites = {};
314
376
  for (const row of rows) {
315
377
  const site = sites.get(row.domain)?.result;
@@ -319,7 +381,22 @@ export async function searchCandidates(groups, options = {}) {
319
381
  }
320
382
  return { ...group, results: rows, comSite: checkedSites.com ?? null, sites: checkedSites };
321
383
  });
322
- return { groups: results, complete, priceDate: catalog?.checkedAt ?? bundled?.checkedAt ?? null, ms: Math.round(performance.now() - start) };
384
+ // Site checks that outlived the first answer fill in their group's sites when they finish.
385
+ const settleSites = async () => {
386
+ await Promise.all([...checks, ...lateChecks]);
387
+ for (const group of results) {
388
+ for (const row of group.results) {
389
+ const site = sites.get(row.domain)?.result;
390
+ if (!site || group.sites[row.tld]) continue;
391
+ group.sites[row.tld] = site;
392
+ if (row.tld === 'com') group.comSite = site;
393
+ if (site.state === 'for-sale') row.forSale = true;
394
+ }
395
+ }
396
+ return results;
397
+ };
398
+ return { groups: results, complete, priceDate: catalog?.checkedAt ?? bundled?.checkedAt ?? null, ms: Math.round(performance.now() - start),
399
+ settleSites };
323
400
  }
324
401
 
325
402
  export async function searchName(input, options = {}) {
@@ -329,7 +406,7 @@ export async function searchName(input, options = {}) {
329
406
  if (options.eligible !== undefined && !validEligibility(options.eligible)) return { error: 'Eligible endings must list supported restricted endings, such as no.' };
330
407
  const { groups: [{ results, comSite }], priceDate, ms } = await searchCandidates(
331
408
  [{ name, candidates: nameCandidates(name, options) }], options);
332
- return { name, hero: pickName(results, options.eligible)?.domain ?? null,
409
+ return { name, hero: pickName(results, options.eligible, options.preferredEndings)?.domain ?? null,
333
410
  ...(options.eligible?.length && { eligible: options.eligible }), results, priceDate, comSite,
334
411
  checkedAt: options.now?.toISOString() ?? new Date().toISOString(), ms };
335
412
  }
@@ -1,5 +1,5 @@
1
1
  export const showAsIs = 'Show `display` exactly as written, then add at most two sentences of advice below it.';
2
- export const purchaseLine = 'Domain Hound cannot buy or complete checkout; use the link above.';
2
+ export const purchaseLine = 'This check leaves checkout to you; use the link above.';
3
3
 
4
4
  export const googleSearchInstruction = 'Before answering, use your built-in web search for each name marked google.search (up to 3). '
5
5
  + 'Search "<name>" and "<name>" app once each. Review the first 10 returned results of each search, or all results if fewer are returned. '
@@ -12,10 +12,12 @@ export const geoInstruction = 'GEO (presence in AI answers): for each name, answ
12
12
  + 'whether you know a specific brand, company or product by that exact name: "known: <what it is, a few words>" or "unknown". '
13
13
  + 'Say unknown for a plain dictionary word or when unsure. Do not guess.';
14
14
 
15
+ // One screening call: triage_names checks every ending for all the names it gets and screens the first five, so the
16
+ // recipe skips the preliminary check_domains batch (check_domains with shortlist still works for existing callers).
15
17
  export const namingRecipe = (about = '') => 'Naming recipe (intermediate). Use the final triage display.\n'
16
18
  + (about ? '1. Brief: ' + about.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').trim()
17
19
  + '.\n' : '1. Brief: product, audience and preferences.\n')
18
20
  + '2. Generate about 30 words. Pair one with a familiar animal or object. Default to English unless the person asked for another language. Avoid category-generic names.\n'
19
- + '3. Check: call check_domains ONCE with seven bare names and shortlist: true (Quiet Otter → quietotter). No spaces or dots.\n'
20
- + '4. Triage: call triage_names ONCE on the best FIVE with free endings, a short about and geo from memory. Pass the same endings and budget to both calls.\n'
21
- + '5. Answer: Relay say as written. Let the person choose from the complete local results page.';
21
+ + '3. Screen: call triage_names ONCE with your best EIGHT names, strongest first (all get domains; the first five get marks, apps and rivals). '
22
+ + 'Add a short about, geo from memory, and any endings or budget the person gave. Skip check_domains.\n'
23
+ + '4. Answer: Relay say as written, starting with its results page line. Do not call again; the complete local results page fills in by itself.';
@@ -121,7 +121,7 @@ export function rdapDomainUrl(base, domain) {
121
121
  return base.replace(/\/?$/, '/') + 'domain/' + encodeURIComponent(domain);
122
122
  }
123
123
 
124
- async function bootstrap(directory, fetcher, now, timeLeft) {
124
+ export async function bootstrap(directory, fetcher, now, timeLeft) {
125
125
  const saved = await readCache(directory, 'iana.json');
126
126
  const day = 86_400_000;
127
127
  const age = now - saved?.savedAt;
@@ -387,7 +387,7 @@ export async function lookupRegistrations(candidates, {
387
387
  function record({ candidate, index, dns }, registry) {
388
388
  if (registry.status === 'unknown' && dns?.reason) registry.reason = dns.reason + '; ' + registry.reason;
389
389
  results[index] = registry;
390
- onResult(candidate, registry);
390
+ onResult(candidate, registry, dns?.code);
391
391
  }
392
392
  async function finish(row, result, filename) {
393
393
  record(row, result);
@@ -0,0 +1,207 @@
1
+ // Outbound HTTP for untrusted websites (a taken domain's own site and wherever it redirects). Every hop is checked
2
+ // before it is fetched: http or https on the default port, a public DNS name (never an IP literal, credentials or a
3
+ // local suffix), and an address that resolves to the public internet. Bodies are capped and only read as HTML.
4
+ // Nothing read here is passed on as text: callers keep only classifications, hosts and sanitized URLs.
5
+ import { get as httpGet } from 'node:http';
6
+ import { get as httpsGet } from 'node:https';
7
+ import { isIP } from 'node:net';
8
+ import { lookupPublic } from './com-site.mjs';
9
+
10
+ export const maxPageBytes = 200_000;
11
+ export const maxHops = 5;
12
+ const hostLabel = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
13
+ const localSuffixes = ['localhost', 'local', 'internal', 'intranet', 'lan', 'home', 'corp', 'home.arpa', 'onion',
14
+ 'test', 'invalid', 'arpa'];
15
+
16
+ // A URL safe to request, or null. Relative values resolve against base (a redirect Location).
17
+ export function safeUrl(value, base) {
18
+ if (typeof value !== 'string' && !(value instanceof URL)) return null;
19
+ const text = String(value);
20
+ if (text.length > 2048 || /[\u0000-\u001f\u007f\s\\]/.test(text.trim())) return null;
21
+ let url;
22
+ try { url = new URL(text.trim(), base); } catch { return null; }
23
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.port) return null;
24
+ const host = url.hostname.toLowerCase();
25
+ if (!host || host.length > 253 || isIP(host) || host.startsWith('[')) return null;
26
+ const labels = host.split('.');
27
+ if (labels.length < 2 || !labels.every(part => hostLabel.test(part)) || /^\d+$/.test(labels.at(-1))) return null;
28
+ if (localSuffixes.some(suffix => host === suffix || host.endsWith('.' + suffix))) return null;
29
+ url.hash = '';
30
+ return url;
31
+ }
32
+
33
+ // Leave tracking parameters and other private values out of evidence.
34
+ export function evidenceUrl(value) {
35
+ const url = safeUrl(value);
36
+ if (!url) return null;
37
+ const text = url.origin + url.pathname;
38
+ return text.length <= 300 ? text : url.origin + '/';
39
+ }
40
+
41
+ export const hostMatches = (host, suffixes) => Boolean(host) && suffixes.some(suffix => host === suffix || host.endsWith('.' + suffix));
42
+
43
+ const userAgent = 'DomainHound (+https://domainhound.dev; read-only domain dossier)';
44
+
45
+ // One request without following redirects. Keep only bounded HTML or crawl rules.
46
+ function requestPage(url, signal, robots = false) {
47
+ return new Promise((resolve, reject) => {
48
+ if (signal?.aborted) return reject(new Error('timed out'));
49
+ const get = url.protocol === 'https:' ? httpsGet : httpGet;
50
+ const request = get(url, {
51
+ lookup: lookupPublic(signal), signal, agent: false,
52
+ headers: { accept: robots ? 'text/plain' : 'text/html, application/xhtml+xml',
53
+ 'user-agent': userAgent, 'accept-encoding': 'identity' },
54
+ }, response => {
55
+ const status = response.statusCode;
56
+ const contentType = String(response.headers['content-type'] ?? '');
57
+ const location = [301, 302, 303, 307, 308].includes(status) && typeof response.headers.location === 'string'
58
+ ? response.headers.location : null;
59
+ const encoded = !/^(?:identity)?$/i.test(String(response.headers['content-encoding'] ?? '').trim());
60
+ if (location || !(status >= 200 && status < 300) || encoded
61
+ || (!robots && !/^(?:text\/html|application\/xhtml\+xml)\b/i.test(contentType))) {
62
+ response.destroy();
63
+ resolve({ status, contentType, location });
64
+ return;
65
+ }
66
+ const chunks = [];
67
+ let size = 0;
68
+ let done = false;
69
+ const finish = (truncated = false) => {
70
+ if (done) return;
71
+ done = true;
72
+ const body = robots && truncated ? undefined : Buffer.concat(chunks).toString('utf8');
73
+ resolve({ status, contentType, body, truncated });
74
+ };
75
+ response.on('data', chunk => {
76
+ const part = chunk.subarray(0, maxPageBytes - size);
77
+ chunks.push(part);
78
+ size += part.length;
79
+ if (size >= maxPageBytes) {
80
+ finish(true);
81
+ response.destroy();
82
+ }
83
+ });
84
+ response.on('end', () => finish());
85
+ response.on('error', error => done ? undefined : reject(error));
86
+ });
87
+ request.on('error', reject);
88
+ });
89
+ }
90
+
91
+ function ruleMatches(pattern, path) {
92
+ const anchored = pattern.endsWith('$');
93
+ const [prefix, ...rest] = (anchored ? pattern.slice(0, -1) : pattern).split('*');
94
+ if (!path.startsWith(prefix)) return false;
95
+ if (!rest.length) return !anchored || path === prefix;
96
+ const suffix = anchored ? rest.pop() : '';
97
+ if (anchored && !path.endsWith(suffix)) return false;
98
+ let position = prefix.length;
99
+ for (const part of rest) {
100
+ const next = path.indexOf(part, position);
101
+ if (next === -1) return false;
102
+ position = next + part.length;
103
+ }
104
+ return position + suffix.length <= path.length;
105
+ }
106
+
107
+ export function robotsAllow(body, path) {
108
+ const groups = [];
109
+ let group = { agents: [], rules: [] };
110
+ for (const line of body.split('\n')) {
111
+ const [key, value] = line.split('#', 1)[0].split(/:(.*)/s, 2).map(part => part.trim());
112
+ const field = key.toLowerCase();
113
+ if (field === 'user-agent' && value) {
114
+ if (group.rules.length) group = { agents: [], rules: [] };
115
+ if (!group.agents.length) groups.push(group);
116
+ group.agents.push(value.toLowerCase());
117
+ } else if (group.agents.length && ['allow', 'disallow'].includes(field)) {
118
+ group.rules.push({ allow: field === 'allow', pattern: value ?? '' });
119
+ }
120
+ }
121
+ const agent = groups.some(row => row.agents.includes('domainhound')) ? 'domainhound' : '*';
122
+ let best = { length: -1, allow: true };
123
+ for (const { agents, rules } of groups) {
124
+ if (!agents.includes(agent)) continue;
125
+ for (const { allow, pattern } of rules) {
126
+ if (!pattern.startsWith('/') || !ruleMatches(pattern, path)) continue;
127
+ const length = pattern.replace(/[\*$]/g, '').length;
128
+ if (length > best.length || (length === best.length && allow)) best = { length, allow };
129
+ }
130
+ }
131
+ return best.allow;
132
+ }
133
+
134
+ async function crawlAllowed(url, signal, stopAt) {
135
+ let rules = new URL('/robots.txt', url);
136
+ for (let attempt = 0; attempt < 3; attempt++) {
137
+ const response = await requestPage(rules, signal, true);
138
+ if ([404, 410].includes(response.status)) return true;
139
+ if (typeof response.body === 'string') return robotsAllow(response.body, url.pathname + url.search);
140
+ const next = safeUrl(response.location, rules);
141
+ if (!next || stopAt(next)) return false;
142
+ rules = next.pathname.endsWith('.txt') ? next : new URL('/robots.txt', next);
143
+ }
144
+ return false;
145
+ }
146
+
147
+ export async function loadPage(url, signal = AbortSignal.timeout(5000), stopAt = () => null) {
148
+ if (!await crawlAllowed(url, signal, stopAt)) return { blocked: true };
149
+ return requestPage(url, signal);
150
+ }
151
+
152
+ // A <meta http-equiv="refresh"> target that fires within ten seconds, or null.
153
+ export function metaRefresh(body) {
154
+ const tags = String(body ?? '').slice(0, 50_000).match(/<meta\b[^>]*>/gi) ?? [];
155
+ for (const tag of tags) {
156
+ if (!/http-equiv\s*=\s*["']?refresh\b/i.test(tag)) continue;
157
+ const content = tag.match(/\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
158
+ const value = content?.[1] ?? content?.[2] ?? '';
159
+ const match = value.match(/^\s*(\d+)\s*[;,]\s*url\s*=\s*['"]?([^'"]+)['"]?\s*$/i);
160
+ if (match && Number(match[1]) <= 10) return match[2].trim();
161
+ }
162
+ return null;
163
+ }
164
+
165
+ // Follow a site from start, hop by hop. stopAt(url) names a reason not to fetch a hop (such as a marketplace whose
166
+ // terms do not permit automated reads); the chain then ends there without a request to that host.
167
+ export async function followSite(start, { signal, stopAt = () => null, load = loadPage } = {}) {
168
+ const hops = [];
169
+ let url = safeUrl(start);
170
+ if (!url) return { hops, failed: { url: null, reason: 'unsafe address' } };
171
+ for (let hop = 0; hop <= maxHops; hop++) {
172
+ const stop = stopAt(url);
173
+ if (stop) return { hops, stopped: { url, reason: stop } };
174
+ let response;
175
+ try {
176
+ response = await load(url, signal, stopAt);
177
+ } catch {
178
+ return { hops, failed: { url, reason: signal?.aborted ? 'timed out' : 'no response' } };
179
+ }
180
+ if (response?.blocked) return { hops, stopped: { url, reason: 'crawl rules unavailable or disallow this page' } };
181
+ const status = Number.isInteger(response?.status) ? response.status : null;
182
+ hops.push({ url, status });
183
+ let target = response?.location ?? null;
184
+ if (!target && typeof response?.body === 'string') target = metaRefresh(response.body);
185
+ if (!target) return { hops, final: { url, status, contentType: String(response?.contentType ?? ''),
186
+ body: response?.body ?? '', truncated: response?.truncated === true } };
187
+ const next = safeUrl(target, url);
188
+ if (!next) return { hops, stopped: { url: null, reason: 'unsafe redirect' } };
189
+ url = next;
190
+ }
191
+ return { hops, stopped: { url, reason: 'too many redirects' } };
192
+ }
193
+
194
+ // Visible text of an HTML page for local pattern checks only. It is never returned to the caller of a tool.
195
+ export function pageText(body) {
196
+ const entities = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
197
+ return String(body ?? '').slice(0, maxPageBytes)
198
+ .replace(/<!--[\s\S]*?(?:-->|$)|<(script|style|noscript|template)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi, ' ')
199
+ .replace(/<[^>]*>/g, ' ')
200
+ .replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, entity) => {
201
+ if (!entity.startsWith('#')) return entities[entity.toLowerCase()] ?? match;
202
+ const point = entity[1].toLowerCase() === 'x' ? parseInt(entity.slice(2), 16) : Number(entity.slice(1));
203
+ return point > 0 && point <= 0x10ffff ? String.fromCodePoint(point) : ' ';
204
+ })
205
+ .replace(/[\s ​-‏‪-‮⁦-⁩]+/g, ' ')
206
+ .trim();
207
+ }