domain-hound 0.1.7 → 0.1.9

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 (45) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +2 -2
  4. package/README.md +89 -24
  5. package/clis/domain-check/company-search.mjs +1 -0
  6. package/clis/domain-check/dossier.mjs +16 -13
  7. package/clis/domain-check/google-play.mjs +11 -48
  8. package/clis/domain-check/google-search.mjs +3 -2
  9. package/clis/domain-check/handles.mjs +235 -106
  10. package/clis/domain-check/index.mjs +49 -28
  11. package/clis/domain-check/name-score.mjs +348 -0
  12. package/clis/domain-check/name-search.mjs +70 -18
  13. package/clis/domain-check/naming-method.mjs +37 -8
  14. package/clis/domain-check/price-catalog.mjs +33 -14
  15. package/clis/domain-check/price-snapshot.json +91 -0
  16. package/clis/domain-check/prices.mjs +5 -0
  17. package/clis/domain-check/public-name-checks.mjs +275 -0
  18. package/clis/domain-check/score-log.mjs +54 -0
  19. package/clis/domain-check/triage-sources.mjs +4 -1
  20. package/clis/domain-check/triage.mjs +131 -83
  21. package/clis/domain-check/youtube-handle.mjs +18 -0
  22. package/clis/portfolio/checks.mjs +456 -0
  23. package/clis/portfolio/discover.mjs +175 -0
  24. package/clis/portfolio/move.mjs +297 -0
  25. package/clis/portfolio/page.mjs +140 -0
  26. package/clis/portfolio/portfolio.mjs +212 -0
  27. package/clis/portfolio/store.mjs +62 -0
  28. package/clis/portfolio/transfer-prices.mjs +41 -0
  29. package/clis/spaceship/client.mjs +35 -19
  30. package/clis/spaceship/tools.mjs +105 -17
  31. package/clis/spaceship/transfer.mjs +332 -0
  32. package/display.mjs +62 -61
  33. package/dossier.mjs +8 -5
  34. package/hosted-results.mjs +157 -0
  35. package/hosted.mjs +164 -0
  36. package/package.json +21 -3
  37. package/plugin.json +8 -8
  38. package/results-style.mjs +3 -0
  39. package/results.mjs +149 -94
  40. package/server.json +4 -4
  41. package/server.mjs +216 -28
  42. package/share.mjs +18 -6
  43. package/site/r/share-format.mjs +23 -8
  44. package/skills/naming/SKILL.md +76 -0
  45. package/watch.mjs +3 -3
@@ -0,0 +1,456 @@
1
+ // Public facts about one domain the person owns: registry record, DNS host, website, TLS certificate, email setup and
2
+ // list-price money. Every check is read-only and shares one deadline. Each check answers ok, problem, none or unknown:
3
+ // "unknown" means the check did not get an answer (a timeout, a resolver failure, an address we refuse to visit), and
4
+ // is never reported as a failure.
5
+ import { Resolver } from 'node:dns/promises';
6
+ import { get as httpGet } from 'node:http';
7
+ import { get as httpsGet } from 'node:https';
8
+ import { connect as tlsConnect } from 'node:tls';
9
+ import { anySignal, cacheDir } from '../domain-check/cache.mjs';
10
+ import { lookupPublic } from '../domain-check/com-site.mjs';
11
+ import { registryFacts } from '../domain-check/dossier.mjs';
12
+ import { domainEnding } from '../domain-check/name-search.mjs';
13
+ import { datedListPrices, isListPriceUsable, loadCachedCatalog } from '../domain-check/price-catalog.mjs';
14
+ import { linkable, shops } from '../domain-check/prices.mjs';
15
+ import { documentedWhois, systemQueryWhois, systemResolveNs } from '../domain-check/registry.mjs';
16
+ import { evidenceUrl, followSite } from '../domain-check/safe-web.mjs';
17
+
18
+ const day = 86_400_000;
19
+ export const expiringSoonDays = 30;
20
+ export const certificateSoonDays = 14;
21
+ // A move is offered only when it saves more than this per year at list prices.
22
+ export const minimumYearlySaving = 5;
23
+ const timeoutCodes = new Set(['ETIMEOUT', 'ETIMEDOUT', 'ECANCELLED', 'ABORT_ERR', 'ESERVFAIL', 'EAI_AGAIN']);
24
+ const userAgent = 'DomainHound (+https://domainhound.dev; read-only domain check)';
25
+
26
+ const daysUntil = (iso, now) => {
27
+ const at = Date.parse(iso);
28
+ return Number.isFinite(at) ? Math.floor((at - now.getTime()) / day) : null;
29
+ };
30
+ const isTimeout = (error, signal) => Boolean(signal?.aborted) || error?.name === 'AbortError' || timeoutCodes.has(error?.code)
31
+ || /timed out/i.test(String(error?.message ?? ''));
32
+
33
+ // ---- Registry ----------------------------------------------------------------------------------------------------
34
+
35
+ // Registry status words (RDAP/EPP, normalized to lower case with spaces) that need the owner's attention.
36
+ const statusProblems = [
37
+ ['redemption period', 'in redemption: the registration lapsed and must be restored'],
38
+ ['pending restore', 'restore pending at the registry'],
39
+ ['pending delete', 'pending delete: the registry will release it'],
40
+ ['server hold', 'on registry hold: it does not resolve'],
41
+ ['client hold', 'on registrar hold: it does not resolve'],
42
+ ];
43
+
44
+ export function readWhois(reply, domain) {
45
+ const values = /^Domain(?: Name)?:[ \t]*(\S+)/im.exec(reply);
46
+ if (values?.[1].toLowerCase().replace(/\.$/, '') !== domain || /^Status:\s*(?:free|available)\s*$/im.test(reply)) return null;
47
+ const field = keys => new RegExp('^(?:' + keys + '):[ \\t]*([^\\r\\n]+)', 'im').exec(reply)?.[1]?.trim();
48
+ const date = keys => {
49
+ const at = Date.parse(field(keys));
50
+ return Number.isFinite(at) ? new Date(at).toISOString() : null;
51
+ };
52
+ const registrar = field('Registrar|Sponsoring Registrar')?.replace(/[^\p{L}\p{N} .,&()'/-]/gu, ' ').slice(0, 80) ?? null;
53
+ const status = [...reply.matchAll(/^Domain Status:[ \t]*([a-z][a-zA-Z ]{1,38})(?=\s*(?:https?:|$))/gim)]
54
+ .map(([, value]) => value.trim().replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase()).slice(0, 24);
55
+ const nameservers = [...reply.matchAll(/^Name Server:[ \t]*([a-z0-9.-]{3,253})/gim)]
56
+ .map(([, value]) => value.toLowerCase().replace(/\.$/, '')).slice(0, 8);
57
+ return { registered: 'taken', registrar, created: date('Creation Date|Created on|Registered on'),
58
+ expires: date('Registry Expiry Date|Registrar Registration Expiration Date|Expiry Date|Expiration Date'),
59
+ status, nameservers };
60
+ }
61
+
62
+ export async function portfolioRegistry(domain, { deadline = performance.now() + 6000, signal, query = systemQueryWhois,
63
+ rdap = registryFacts } = {}) {
64
+ const facts = await rdap(domain, { signal, deadline });
65
+ const tld = domain.split('.').at(-1);
66
+ const left = () => Math.floor(deadline - performance.now());
67
+ if (facts.source?.method === 'rdap' || ['app', 'dev'].includes(tld) || left() < 500 || signal?.aborted) return facts;
68
+ let host = documentedWhois.get(tld);
69
+ if (!host) {
70
+ const iana = await query('whois.iana.org', tld, Math.min(950, left()));
71
+ host = /^(?:refer|whois):[ \t]*([a-z\d.-]+)[ \t\r]*$/im.exec(iana)?.[1];
72
+ }
73
+ if (!host || left() < 300 || signal?.aborted) return facts;
74
+ const whois = readWhois(await query(host, domain, Math.min(1500, left())), domain);
75
+ return whois ? { ...facts, ...whois, expires: whois.expires ?? facts.expires,
76
+ nameservers: whois.nameservers.length ? whois.nameservers : facts.nameservers,
77
+ checkedAt: new Date().toISOString(), source: { method: 'whois', url: 'whois://' + host } } : facts;
78
+ }
79
+
80
+ export function readRegistry(facts, now) {
81
+ if (!facts || facts.registered !== 'taken') {
82
+ return { state: facts?.registered === 'free' ? 'problem' : 'unknown',
83
+ reason: facts?.registered === 'free' ? 'the registry has no record: not registered' : facts?.reason ?? 'no registry answer',
84
+ registrar: null, created: null, expires: null, daysLeft: null, status: [], nameservers: facts?.nameservers ?? [],
85
+ source: facts?.source ?? null };
86
+ }
87
+ const status = Array.isArray(facts.status) ? facts.status : [];
88
+ const daysLeft = facts.expires ? daysUntil(facts.expires, now) : null;
89
+ const problems = statusProblems.filter(([word]) => status.includes(word)).map(([, text]) => text);
90
+ if (daysLeft !== null && daysLeft < 0) problems.unshift('expired ' + -daysLeft + (daysLeft === -1 ? ' day ago' : ' days ago'));
91
+ return {
92
+ state: problems.length ? 'problem' : 'ok',
93
+ problems,
94
+ registrar: facts.registrar ?? null,
95
+ created: facts.created ?? null,
96
+ // The registry's own transfer event, when it publishes one. Never inferred from "last changed".
97
+ transferred: facts.transferred ?? null,
98
+ expires: facts.expires ?? null,
99
+ daysLeft,
100
+ status,
101
+ // Only the registry's own status word counts as evidence of auto-renew; nothing else is claimed.
102
+ autoRenewGrace: status.includes('auto renew period'),
103
+ transferLock: status.length ? status.includes('client transfer prohibited') : null,
104
+ nameservers: facts.nameservers ?? [],
105
+ source: facts.source ?? null,
106
+ checkedAt: facts.checkedAt ?? null,
107
+ };
108
+ }
109
+
110
+ // ---- DNS host ----------------------------------------------------------------------------------------------------
111
+
112
+ const dnsHosts = [
113
+ ['Cloudflare', ['ns.cloudflare.com', 'cloudflare.com']],
114
+ ['AWS Route 53', ['awsdns-', 'awsdns']],
115
+ ['Google Cloud DNS', ['googledomains.com']],
116
+ ['Azure DNS', ['azure-dns.com', 'azure-dns.net', 'azure-dns.org', 'azure-dns.info']],
117
+ ['Vercel', ['vercel-dns.com']],
118
+ ['NS1 (often Netlify)', ['nsone.net']],
119
+ ['Spaceship', ['spaceship.net']],
120
+ ['GoDaddy', ['domaincontrol.com']],
121
+ ['Namecheap', ['registrar-servers.com']],
122
+ ['Porkbun', ['porkbun.com']],
123
+ ['Dynadot', ['dynadot.com']],
124
+ ['Gandi', ['gandi.net']],
125
+ ['Squarespace', ['squarespacedns.com']],
126
+ ['DigitalOcean', ['digitalocean.com']],
127
+ ['Hetzner', ['hetzner.com', 'hetzner.de', 'first-ns.de', 'second-ns.de', 'second-ns.com']],
128
+ ['DNSimple', ['dnsimple.com', 'dnsimple-edge.net']],
129
+ ['Akamai', ['akam.net']],
130
+ ['UltraDNS', ['ultradns.com', 'ultradns.net', 'ultradns.org', 'ultradns.biz', 'ultradns.info']],
131
+ ['IONOS', ['ui-dns.com', 'ui-dns.de', 'ui-dns.org', 'ui-dns.biz']],
132
+ ['Wix', ['wixdns.net']],
133
+ ];
134
+
135
+ export function dnsHost(nameservers = []) {
136
+ const hosts = nameservers.map(value => String(value).toLowerCase().replace(/\.$/, '')).filter(Boolean);
137
+ if (!hosts.length) return null;
138
+ for (const [name, suffixes] of dnsHosts) {
139
+ if (hosts.some(host => suffixes.some(suffix => suffix.endsWith('-') || suffix === 'awsdns'
140
+ ? host.includes(suffix) : host === suffix || host.endsWith('.' + suffix)))) return name;
141
+ }
142
+ // Unknown provider: show the name servers' own domain (three labels under a country's second level, like co.uk).
143
+ const labels = hosts[0].split('.');
144
+ return labels.slice(/^(?:co|com|net|org|ac|gov|ne|or)\.[a-z]{2}$/.test(labels.slice(-2).join('.')) ? -3 : -2).join('.');
145
+ }
146
+
147
+ // ---- Website -----------------------------------------------------------------------------------------------------
148
+
149
+ // One request, no body: the status and any redirect. Every hop goes through safe-web's followSite, which refuses
150
+ // IP literals, credentials, ports and local names, and lookupPublic, which refuses addresses outside the public internet.
151
+ export function statusOnly(url, signal) {
152
+ return new Promise((resolve, reject) => {
153
+ if (signal?.aborted) return reject(Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' }));
154
+ const get = url.protocol === 'https:' ? httpsGet : httpGet;
155
+ const request = get(url, { lookup: lookupPublic(signal), signal, agent: false,
156
+ headers: { accept: 'text/html, */*;q=0.5', 'user-agent': userAgent, 'accept-encoding': 'identity' } }, response => {
157
+ const status = response.statusCode;
158
+ const location = [301, 302, 303, 307, 308].includes(status) && typeof response.headers.location === 'string'
159
+ ? response.headers.location : null;
160
+ response.destroy();
161
+ resolve({ status, location, contentType: String(response.headers['content-type'] ?? '') });
162
+ });
163
+ request.on('error', reject);
164
+ });
165
+ }
166
+
167
+ function failureText(error) {
168
+ const code = String(error?.code ?? '');
169
+ if (/^(?:CERT_|ERR_TLS_|UNABLE_TO_|DEPTH_ZERO|SELF_SIGNED)/.test(code)) return 'certificate rejected (' + code + ')';
170
+ if (/No public address/i.test(String(error?.message))) return 'no public address';
171
+ if (code === 'ENOTFOUND') return 'no address in DNS';
172
+ if (code === 'ECONNREFUSED') return 'connection refused';
173
+ if (code === 'ECONNRESET') return 'connection reset';
174
+ return 'no response';
175
+ }
176
+
177
+ // The site's answer at https and http, following redirects. https wins when it answered at all.
178
+ export async function siteCheck(domain, { signal, load = statusOnly, hopMs = 3500 } = {}) {
179
+ const outer = signal ?? new AbortController().signal;
180
+ const run = async scheme => {
181
+ let lastError = null;
182
+ const hop = async (url, hopSignal) => {
183
+ const own = anySignal([hopSignal ?? outer, AbortSignal.timeout(hopMs)]);
184
+ try {
185
+ return await load(url, own);
186
+ } catch (error) {
187
+ lastError = { error, timedOut: isTimeout(error, own) };
188
+ throw error;
189
+ }
190
+ };
191
+ const visit = await followSite(scheme + '://' + domain + '/', { signal: outer, load: hop });
192
+ return readVisit(visit, lastError);
193
+ };
194
+ const [secure, plain] = await Promise.all([run('https'), run('http')]);
195
+ // An https answer settles it, even an error status. Without one, a working http site still counts as up, except on
196
+ // endings browsers open over HTTPS only: there the answering http server proves the host is up and https is not.
197
+ if (secure.state === 'ok' || (secure.state === 'problem' && secure.httpStatus)) return secure;
198
+ if (plain.state === 'ok') {
199
+ const ending = domain.split('.').at(-1);
200
+ if (httpsOnlyEndings.has(ending)) {
201
+ return { ...plain, state: secure.state, reason: 'HTTPS ' + (secure.reason ?? 'failed') + '. Browsers require HTTPS on .' + ending,
202
+ note: 'HTTP answered. HTTPS ' + (secure.reason ?? 'failed') + '.', httpOnly: true };
203
+ }
204
+ return { ...plain, note: 'http only' + (secure.reason ? '; https: ' + secure.reason : '') };
205
+ }
206
+ return secure;
207
+ }
208
+
209
+ // Endings on the browsers' HSTS preload list as a whole (Google Registry): a plain-http site there cannot be opened.
210
+ export const httpsOnlyEndings = new Set(['app', 'dev', 'page', 'new', 'day', 'foo', 'boo', 'esq', 'ing', 'meme', 'mov', 'nexus',
211
+ 'phd', 'prof', 'rsvp', 'soy', 'zip']);
212
+
213
+ export function readVisit(visit, lastError) {
214
+ if (visit.stopped) {
215
+ // followSite stops on an unsafe redirect (private, local or IP target) without requesting it.
216
+ return { state: 'unknown', reason: visit.stopped.reason === 'unsafe redirect'
217
+ ? 'redirects to a private or unsafe address; not followed' : visit.stopped.reason };
218
+ }
219
+ if (visit.failed || !visit.final) {
220
+ if (lastError?.timedOut) return { state: 'unknown', reason: 'no answer in time' };
221
+ return { state: 'problem', reason: failureText(lastError?.error) };
222
+ }
223
+ const { url, status } = visit.final;
224
+ const redirect = (visit.hops?.length ?? 0) > 1 ? evidenceUrl(url) : null;
225
+ const base = { httpStatus: status, finalUrl: evidenceUrl(url), ...(redirect && { redirect }) };
226
+ if (status >= 200 && status < 400) return { state: 'ok', ...base };
227
+ // Bot walls and sign-in pages still prove a server answers for the domain.
228
+ if ([401, 403, 429].includes(status)) return { state: 'ok', ...base, note: 'answers HTTP ' + status + ' to automated checks' };
229
+ return { state: 'problem', ...base, reason: 'HTTP ' + status };
230
+ }
231
+
232
+ // ---- TLS certificate ---------------------------------------------------------------------------------------------
233
+
234
+ // The certificate the apex serves on port 443, read even when it is invalid so the reason can be named.
235
+ export function readCertificate(domain, { signal, timeoutMs = 4000 } = {}) {
236
+ return new Promise((resolve, reject) => {
237
+ const own = anySignal([signal ?? new AbortController().signal, AbortSignal.timeout(timeoutMs)]);
238
+ if (own.aborted) return reject(Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' }));
239
+ const socket = tlsConnect({ host: domain, port: 443, servername: domain, rejectUnauthorized: false,
240
+ lookup: lookupPublic(own), ALPNProtocols: ['http/1.1'] });
241
+ const stop = () => {
242
+ socket.destroy();
243
+ reject(Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' }));
244
+ };
245
+ own.addEventListener('abort', stop, { once: true });
246
+ socket.once('secureConnect', () => {
247
+ own.removeEventListener('abort', stop);
248
+ const certificate = socket.getPeerCertificate();
249
+ const answer = { authorized: socket.authorized, error: socket.authorizationError ? String(socket.authorizationError) : null,
250
+ validTo: certificate?.valid_to ?? null, issuer: certificate?.issuer?.O ?? null };
251
+ socket.destroy();
252
+ resolve(answer);
253
+ });
254
+ socket.once('error', error => {
255
+ own.removeEventListener('abort', stop);
256
+ socket.destroy();
257
+ reject(error);
258
+ });
259
+ });
260
+ }
261
+
262
+ export async function tlsCheck(domain, { signal, read = readCertificate, now = new Date() } = {}) {
263
+ let answer;
264
+ try {
265
+ answer = await read(domain, { signal });
266
+ } catch (error) {
267
+ if (isTimeout(error, signal)) return { state: 'unknown', reason: 'no answer in time' };
268
+ const text = failureText(error);
269
+ // Nothing listening for HTTPS is a missing certificate, not an invalid one.
270
+ return { state: ['connection refused', 'no address in DNS', 'no public address'].includes(text) ? 'none' : 'problem',
271
+ reason: text };
272
+ }
273
+ const expires = Number.isFinite(Date.parse(answer?.validTo)) ? new Date(answer.validTo).toISOString() : null;
274
+ const daysLeft = expires ? daysUntil(expires, now) : null;
275
+ const issuer = typeof answer?.issuer === 'string' ? answer.issuer.replace(/[^\p{L}\p{N} .,&()'-]/gu, '').slice(0, 60) : null;
276
+ const base = { expires, daysLeft, ...(issuer && { issuer }) };
277
+ if (!answer?.authorized) {
278
+ const code = String(answer?.error ?? 'unknown error').replace(/[^A-Z0-9_]/gi, '').slice(0, 60);
279
+ return { state: 'problem', ...base, reason: code === 'CERT_HAS_EXPIRED' ? 'certificate expired' : 'certificate invalid (' + code + ')' };
280
+ }
281
+ if (daysLeft !== null && daysLeft <= certificateSoonDays) {
282
+ return { state: 'problem', ...base, reason: 'certificate expires in ' + Math.max(0, daysLeft) + ' days' };
283
+ }
284
+ return { state: 'ok', ...base };
285
+ }
286
+
287
+ // ---- Email -------------------------------------------------------------------------------------------------------
288
+
289
+ export function systemResolver() {
290
+ const resolver = new Resolver({ timeout: 2000, tries: 2 });
291
+ return {
292
+ resolveMx: name => resolver.resolveMx(name),
293
+ resolveTxt: name => resolver.resolveTxt(name),
294
+ cancel: () => resolver.cancel(),
295
+ };
296
+ }
297
+
298
+ // One DNS question: the answer, null for a definite "nothing there", or "unknown" when the resolver did not answer.
299
+ async function ask(question) {
300
+ try {
301
+ return await question();
302
+ } catch (error) {
303
+ if (['ENODATA', 'ENOTFOUND'].includes(error?.code)) return null;
304
+ return 'unknown';
305
+ }
306
+ }
307
+
308
+ export async function mailCheck(domain, { resolver = systemResolver(), signal } = {}) {
309
+ const cancel = () => resolver.cancel?.();
310
+ signal?.addEventListener('abort', cancel, { once: true });
311
+ try {
312
+ const [mx, txt, dmarcTxt] = await Promise.all([
313
+ ask(() => resolver.resolveMx(domain)),
314
+ ask(() => resolver.resolveTxt(domain)),
315
+ ask(() => resolver.resolveTxt('_dmarc.' + domain)),
316
+ ]);
317
+ const joined = rows => Array.isArray(rows) ? rows.map(parts => Array.isArray(parts) ? parts.join('') : String(parts)) : [];
318
+ const mxRows = Array.isArray(mx) ? mx : [];
319
+ // RFC 7505: a single MX of "." declares that the domain accepts no incoming mail.
320
+ const nullMx = mxRows.length === 1 && ['', '.'].includes(String(mxRows[0]?.exchange ?? '').trim());
321
+ const spf = txt === 'unknown' ? 'unknown' : joined(txt).some(value => /^v=spf1(?:\s|$)/i.test(value.trim()));
322
+ const dmarc = dmarcTxt === 'unknown' ? 'unknown' : joined(dmarcTxt).some(value => /^v=DMARC1\s*(?:;|$)/i.test(value.trim()));
323
+ const facts = { mx: mx === 'unknown' ? 'unknown' : nullMx ? 'null' : mxRows.length > 0, spf, dmarc,
324
+ mxHosts: nullMx ? [] : mxRows.map(row => String(row?.exchange ?? '').toLowerCase()).filter(Boolean).slice(0, 4) };
325
+ if (mx === 'unknown') return { state: 'unknown', ...facts, reason: 'MX lookup did not answer' };
326
+ if (nullMx || !mxRows.length) {
327
+ return { state: 'none', ...facts, reason: nullMx ? 'declares no incoming mail (null MX)' : 'no MX record found' };
328
+ }
329
+ const missing = [spf === false && 'SPF', dmarc === false && 'DMARC'].filter(Boolean);
330
+ if (missing.length) return { state: 'problem', ...facts, reason: 'mail without ' + missing.join(' and ') };
331
+ if (spf === 'unknown' || dmarc === 'unknown') return { state: 'unknown', ...facts, reason: 'SPF or DMARC lookup did not answer' };
332
+ return { state: 'ok', ...facts };
333
+ } finally {
334
+ signal?.removeEventListener('abort', cancel);
335
+ }
336
+ }
337
+
338
+ // ---- Money -------------------------------------------------------------------------------------------------------
339
+
340
+ // Registrar names in RDAP mapped to the shops whose dated list prices we read.
341
+ const registrarShops = [
342
+ [/\bspaceship\b/i, 'spaceship'], [/\bporkbun\b/i, 'porkbun'], [/\bdynadot\b/i, 'dynadot'], [/\bgandi\b/i, 'gandi'],
343
+ [/\bcloudflare\b/i, 'cloudflare'], [/\bnamecheap\b/i, 'namecheap'], [/\bnamesilo\b/i, 'namesilo'],
344
+ ];
345
+ export const registrarShop = registrar => registrarShops.find(([pattern]) => pattern.test(String(registrar ?? '')))?.[1] ?? null;
346
+
347
+ const priceSources = {
348
+ spaceship: () => 'https://www.spaceship.com/domain-search/pricing/',
349
+ dynadot: () => 'https://www.dynadot.com/domain/prices?currency=USD',
350
+ porkbun: () => 'https://porkbun.com/products/domains',
351
+ gandi: tld => 'https://www.gandi.net/en/domain/tld/' + encodeURIComponent(tld) + '?currency=USD',
352
+ cloudflare: () => 'https://www.cloudflare.com/products/registrar/',
353
+ };
354
+ // Each shop's own transfer-in page. Only linkable shops (not data-only ones) can be a move target.
355
+ export const transferPages = {
356
+ spaceship: 'https://www.spaceship.com/domains/transfer/',
357
+ dynadot: 'https://www.dynadot.com/domain/transfer',
358
+ gandi: 'https://shop.gandi.net/en/domain/transfer',
359
+ };
360
+
361
+ const cents = value => Math.round((value + Number.EPSILON) * 100) / 100;
362
+ // These catalog endings normally add one year on transfer. Other terms (for example .ai and .uk)
363
+ // need different calculations to compare the same coverage.
364
+ const oneYearTransfers = new Set(['com', 'net', 'org', 'app', 'dev', 'io', 'me', 'co', 'xyz', 'tech', 'sh', 'gg', 'inc', 'studio']);
365
+
366
+ export async function loadCatalog(directory = cacheDir) {
367
+ return loadCachedCatalog(directory).catch(() => null);
368
+ }
369
+
370
+ // Dated list prices only. A saving is offered when it is real (both prices known, a transfer price listed) and more
371
+ // than minimumYearlySaving per year over three years. Premium names renew higher than these list prices.
372
+ export function moneyFacts(domain, registrar, catalog, now = new Date()) {
373
+ const tld = domainEnding(domain);
374
+ const byShop = new Map();
375
+ for (const row of [...datedListPrices(catalog, tld, now), ...datedListPrices(null, tld, now)]) {
376
+ if (!Number.isFinite(row.renewal) || Date.parse(row.checkedAt) > now.getTime()) continue;
377
+ if (!byShop.has(row.id) || row.checkedAt > byShop.get(row.id).checkedAt) byShop.set(row.id, row);
378
+ }
379
+ const rows = [...byShop.values()];
380
+ const shop = registrarShop(registrar);
381
+ const dated = row => ({ shop: row.shop, renewal: row.renewal, checkedAt: row.checkedAt, estimate: Boolean(row.bundled),
382
+ source: priceSources[row.id]?.(tld) ?? null });
383
+ const current = shop ? rows.find(row => row.id === shop) : null;
384
+ const cheapest = rows.reduce((best, row) => (
385
+ !best || row.renewal < best.renewal || (row.renewal === best.renewal && row.id === shop)
386
+ ) ? row : best, null);
387
+ let move = null;
388
+ if (current && oneYearTransfers.has(tld) && isListPriceUsable(current.checkedAt, now)) {
389
+ for (const row of rows) {
390
+ if (row.renewal >= current.renewal || !linkable(row.id) || !transferPages[row.id]
391
+ || !Number.isFinite(row.transfer) || !isListPriceUsable(row.checkedAt, now)) continue;
392
+ // Staying: three renewals. Moving: the transfer (which adds a year) and two renewals at the new shop.
393
+ const saving = cents(3 * current.renewal - (row.transfer + 2 * row.renewal));
394
+ if (saving / 3 > minimumYearlySaving && (!move || saving > move.saving)) {
395
+ move = { to: row.shop, saving, transfer: row.transfer, renewal: row.renewal, checkedAt: row.checkedAt,
396
+ estimate: Boolean(row.bundled), url: transferPages[row.id], source: priceSources[row.id]?.(tld) ?? null };
397
+ }
398
+ }
399
+ }
400
+ return {
401
+ currentShop: shop ? shops[shop]?.name ?? null : null,
402
+ current: current ? dated(current) : null,
403
+ cheapest: cheapest ? dated(cheapest) : null,
404
+ move,
405
+ };
406
+ }
407
+
408
+ // ---- One domain --------------------------------------------------------------------------------------------------
409
+
410
+ export async function checkDomain(domain, { signal, now = new Date(), catalog = null, deadline,
411
+ registry = portfolioRegistry, site = siteCheck, tls = tlsCheck, mail = mailCheck, resolveNs = systemResolveNs } = {}) {
412
+ const end = deadline ?? performance.now() + 9000;
413
+ const guard = async (work, fallback) => {
414
+ try { return await work(); } catch { return fallback; }
415
+ };
416
+ const [facts, web, certificate, email, nameservers] = await Promise.all([
417
+ guard(() => registry(domain, { signal, deadline: Math.min(end, performance.now() + 6000) }), null),
418
+ guard(() => site(domain, { signal }), { state: 'unknown', reason: 'site check failed to run' }),
419
+ guard(() => tls(domain, { signal, now }), { state: 'unknown', reason: 'certificate check failed to run' }),
420
+ guard(() => mail(domain, { signal }), { state: 'unknown', reason: 'mail check failed to run' }),
421
+ guard(() => resolveNs(domain), []),
422
+ ]);
423
+ const record = readRegistry(facts, now);
424
+ const activeNameservers = Array.isArray(nameservers) && nameservers.length ? nameservers : record.nameservers;
425
+ const money = moneyFacts(domain, record.registrar, catalog, now);
426
+ if (record.state !== 'ok' || record.autoRenewGrace || record.status.includes('pending transfer')
427
+ || now.getTime() - Date.parse(record.created) < 60 * day || now.getTime() - Date.parse(record.transferred) < 60 * day) money.move = null;
428
+ return {
429
+ domain,
430
+ checkedAt: now.toISOString(),
431
+ registry: record,
432
+ nameservers: activeNameservers,
433
+ dnsHost: dnsHost(activeNameservers),
434
+ site: web,
435
+ tls: certificate,
436
+ email,
437
+ money,
438
+ };
439
+ }
440
+
441
+ // The urgency order the say and the page share: lower is more urgent.
442
+ export function urgency(row) {
443
+ const days = row.registry.daysLeft;
444
+ if (row.registry.state === 'problem') return 0;
445
+ if (days !== null && days <= expiringSoonDays) return 1;
446
+ if (row.site.state === 'problem' || row.tls.state === 'problem' || row.email.state === 'problem') return 2;
447
+ if (row.money.move) return 3;
448
+ if ([row.registry, row.site, row.tls, row.email].some(check => check.state === 'unknown')) return 4;
449
+ return 5;
450
+ }
451
+
452
+ export function sortByUrgency(rows) {
453
+ return rows.map((row, index) => ({ row, index, rank: urgency(row) }))
454
+ .sort((a, b) => a.rank - b.rank || (a.row.registry.daysLeft ?? Infinity) - (b.row.registry.daysLeft ?? Infinity) || a.index - b.index)
455
+ .map(({ row }) => row);
456
+ }
@@ -0,0 +1,175 @@
1
+ // Candidate domains for the person to confirm: from project files the agent points at, and from the person's own
2
+ // Spaceship account when a key is configured. Only a fixed list of public project files is opened (never .env or any
3
+ // other secret file), nothing is stored, and the Spaceship call is the read-only domain list.
4
+ import { lstat, open, readdir } from 'node:fs/promises';
5
+ import { basename, join, relative, resolve } from 'node:path';
6
+ import { safeUrl } from '../domain-check/safe-web.mjs';
7
+ import { isLoopback, spaceshipBase, spaceshipCredentials } from '../spaceship/client.mjs';
8
+ import { portfolioDomain } from './store.mjs';
9
+
10
+ // The only files discovery reads. Matching is on the exact name, so .env, .env.local, keys and configs with secrets
11
+ // are never opened.
12
+ export const projectFiles = ['CNAME', 'package.json', 'wrangler.toml', 'wrangler.json', 'wrangler.jsonc', 'vercel.json',
13
+ 'netlify.toml', 'README.md', 'readme.md', 'Readme.md', 'README'];
14
+ const strongFiles = new Set(['CNAME', 'package.json', 'wrangler.toml', 'wrangler.json', 'wrangler.jsonc', 'vercel.json', 'netlify.toml']);
15
+ const skipDirs = new Set(['node_modules', 'dist', 'build', 'out', 'vendor', 'coverage', 'target', 'tmp', 'cache']);
16
+ const maxFileBytes = 256 * 1024;
17
+ const maxDirsPerPath = 60;
18
+ export const maxPaths = 10;
19
+ export const maxCandidates = 40;
20
+
21
+ // Hosted subdomains and well-known third-party sites are not the person's own domains.
22
+ const hostedSuffixes = ['github.io', 'pages.dev', 'workers.dev', 'vercel.app', 'netlify.app', 'herokuapp.com', 'web.app',
23
+ 'firebaseapp.com', 'fly.dev', 'onrender.com', 'azurewebsites.net', 'cloudfront.net', 'amazonaws.com', 'appspot.com',
24
+ 'glitch.me', 'replit.app', 'surge.sh', 'gitlab.io', 'readthedocs.io', 'blogspot.com', 'wordpress.com', 'substack.com'];
25
+ const thirdParty = new Set(['github.com', 'githubusercontent.com', 'npmjs.com', 'npmjs.org', 'shields.io', 'badgen.net',
26
+ 'twitter.com', 'x.com', 'linkedin.com', 'youtube.com', 'youtu.be', 'google.com', 'apple.com', 'microsoft.com',
27
+ 'mozilla.org', 'wikipedia.org', 'stackoverflow.com', 'anthropic.com', 'claude.ai', 'claude.com', 'openai.com',
28
+ 'vercel.com', 'netlify.com', 'cloudflare.com', 'nodejs.org', 'modelcontextprotocol.io', 'example.com', 'example.org',
29
+ 'example.net', 'w3.org', 'json-schema.org', 'schema.org', 'opensource.org', 'creativecommons.org', 'gitlab.com',
30
+ 'bitbucket.org', 'discord.gg', 'discord.com', 'medium.com', 'docker.com', 'python.org', 'pypi.org', 'unpkg.com',
31
+ 'jsdelivr.net', 'reddit.com', 'facebook.com', 'instagram.com', 'tiktok.com', 'spaceship.com', 'spaceship.dev',
32
+ 'godaddy.com', 'namecheap.com', 'porkbun.com', 'dynadot.com', 'gandi.net', 'iana.org', 'icann.org', 'ietf.org',
33
+ 'rfc-editor.org', 'mit-license.org', 'chromewebstore.google.com', 'gstatic.com', 'googleapis.com', 'readme.com']);
34
+ const twoLevel = new Set(['co.uk', 'org.uk', 'ac.uk', 'com.au', 'net.au', 'co.nz', 'co.jp', 'com.br', 'co.za', 'com.mx']);
35
+
36
+ // The registrable domain of a host, if it can be the person's own.
37
+ export function ownDomain(host) {
38
+ const value = portfolioDomain(host);
39
+ if (!value) return null;
40
+ const labels = value.split('.');
41
+ const keep = twoLevel.has(labels.slice(-2).join('.')) ? 3 : 2;
42
+ const domain = labels.slice(-keep).join('.');
43
+ if (hostedSuffixes.some(suffix => value === suffix || value.endsWith('.' + suffix)) || thirdParty.has(domain)) return null;
44
+ return portfolioDomain(domain);
45
+ }
46
+
47
+ const urlHosts = text => [...String(text).matchAll(/\bhttps?:\/\/[^\s<>"'`\])},]+/gi)]
48
+ .map(([url]) => safeUrl(url)?.hostname).filter(Boolean);
49
+
50
+ // Domains named in one project file, by its kind.
51
+ export function domainsInFile(name, text) {
52
+ if (name === 'CNAME') return String(text).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(0, 1);
53
+ if (name === 'package.json') {
54
+ try {
55
+ const data = JSON.parse(text);
56
+ return typeof data?.homepage === 'string' ? urlHosts(data.homepage) : [];
57
+ } catch {
58
+ return [];
59
+ }
60
+ }
61
+ if (name.startsWith('wrangler.')) {
62
+ // Routes and custom domains only: other strings in the file (main = "src/index.ts") look like hosts too.
63
+ return String(text).split(/\r?\n/).filter(line => /\b(?:pattern|zone_name|routes?|custom_domain|domains?)\b/i.test(line))
64
+ .flatMap(line => [...line.matchAll(/["']([a-z0-9*.-]+\.[a-z]{2,63})(?:\/[^"']*)?["']/gi)].map(match => match[1].replace(/^\*\.?/, '')));
65
+ }
66
+ if (name === 'vercel.json') {
67
+ let aliases = [];
68
+ try {
69
+ const data = JSON.parse(text);
70
+ aliases = (Array.isArray(data?.alias) ? data.alias : [data?.alias]).filter(value => typeof value === 'string');
71
+ } catch { /* URLs below still count */ }
72
+ return [...aliases, ...urlHosts(text)];
73
+ }
74
+ return urlHosts(text);
75
+ }
76
+
77
+ async function readSmallFile(path) {
78
+ const info = await lstat(path).catch(() => null);
79
+ // Regular files only: a symlink could point anywhere on the machine.
80
+ if (!info?.isFile() || info.size > maxFileBytes) return null;
81
+ const handle = await open(path, 'r');
82
+ try {
83
+ return await handle.readFile('utf8');
84
+ } finally {
85
+ await handle.close();
86
+ }
87
+ }
88
+
89
+ async function projectDirs(root) {
90
+ const dirs = [root];
91
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
92
+ for (const entry of entries) {
93
+ if (dirs.length >= maxDirsPerPath) break;
94
+ if (entry.isDirectory() && !entry.name.startsWith('.') && !skipDirs.has(entry.name)) dirs.push(join(root, entry.name));
95
+ }
96
+ return dirs;
97
+ }
98
+
99
+ // Candidates from the project folders the agent points at (the server's working folder when none are given).
100
+ export async function projectCandidates(paths = [process.cwd()]) {
101
+ const found = new Map();
102
+ for (const path of paths.slice(0, maxPaths)) {
103
+ const root = resolve(path);
104
+ const info = await lstat(root).catch(() => null);
105
+ if (!info?.isDirectory()) continue;
106
+ for (const dir of await projectDirs(root)) {
107
+ // Names as the folder lists them, so a case-insensitive disk never reads one file twice.
108
+ const names = (await readdir(dir).catch(() => [])).filter(name => projectFiles.includes(name));
109
+ for (const name of names) {
110
+ const text = await readSmallFile(join(dir, name)).catch(() => null);
111
+ if (text == null) continue;
112
+ // Shown as the project folder's name and the file inside it, never as an absolute path.
113
+ const where = [basename(root), relative(root, join(dir, name))].join('/').replaceAll('\\', '/');
114
+ for (const host of domainsInFile(name, text)) {
115
+ const domain = ownDomain(host);
116
+ if (!domain) continue;
117
+ if (!found.has(domain)) found.set(domain, { domain, sources: [], strong: false });
118
+ const row = found.get(domain);
119
+ if (row.sources.length < 3 && !row.sources.includes(where)) row.sources.push(where);
120
+ row.strong ||= strongFiles.has(name);
121
+ }
122
+ }
123
+ }
124
+ }
125
+ // Deployment files first, then README links.
126
+ return [...found.values()].sort((a, b) => Number(b.strong) - Number(a.strong) || a.domain.localeCompare(b.domain))
127
+ .slice(0, maxCandidates);
128
+ }
129
+
130
+ // The person's domains at Spaceship (listDomains, read-only, needs only domains:read). The key never leaves this
131
+ // function except in the request headers to Spaceship.
132
+ export async function spaceshipDomains({ credentials = () => spaceshipCredentials(), fetcher = globalThis.fetch,
133
+ baseUrl = spaceshipBase, timeout = 6000 } = {}) {
134
+ const base = baseUrl.replace(/\/+$/, '');
135
+ if (base !== spaceshipBase && !isLoopback(base)) return { state: 'unknown', reason: 'Spaceship API base must be ' + spaceshipBase };
136
+ let keys;
137
+ try {
138
+ keys = await credentials();
139
+ } catch {
140
+ keys = null;
141
+ }
142
+ if (!keys?.key || !keys?.secret) return { state: 'not-connected' };
143
+ const domains = [];
144
+ let read = 0;
145
+ for (let page = 0; page < 10; page++) {
146
+ let response;
147
+ try {
148
+ response = await fetcher(base + '/v1/domains?' + new URLSearchParams({ take: '100', skip: String(read) }), {
149
+ method: 'GET', redirect: 'error', signal: AbortSignal.timeout(timeout),
150
+ headers: { 'X-API-Key': keys.key, 'X-API-Secret': keys.secret, Accept: 'application/json' },
151
+ });
152
+ } catch {
153
+ return { state: 'unknown', reason: 'Spaceship did not answer in time', domains };
154
+ }
155
+ if (response.status === 401 || response.status === 403) {
156
+ await response.body?.cancel?.().catch(() => {});
157
+ return { state: 'unknown', reason: 'Spaceship refused the API key or its scope (the list needs domains:read)', domains };
158
+ }
159
+ if (response.status !== 200) {
160
+ await response.body?.cancel?.().catch(() => {});
161
+ return { state: 'unknown', reason: 'Spaceship answered HTTP ' + response.status, domains };
162
+ }
163
+ const json = await response.json().catch(() => null);
164
+ const items = Array.isArray(json?.items) ? json.items : null;
165
+ if (!items || !Number.isInteger(json.total) || items.length > 100 || json.total < read + items.length
166
+ || (!items.length && read < json.total)) return { state: 'unknown', reason: 'Spaceship returned an incomplete list', domains };
167
+ read += items.length;
168
+ for (const item of items) {
169
+ const domain = portfolioDomain(item?.name);
170
+ if (domain && !domains.includes(domain)) domains.push(domain);
171
+ }
172
+ if (read === json.total) return { state: 'ok', domains };
173
+ }
174
+ return { state: 'unknown', reason: 'Only the first 1,000 Spaceship entries were checked', domains };
175
+ }