domain-hound 0.1.7 → 0.1.8

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.
@@ -0,0 +1,212 @@
1
+ // my_domains: one view of every domain the person owns, wherever they bought it. Read-only toward the world: public
2
+ // registry, DNS, site and certificate checks plus dated list prices. The confirmed list lives only in a local file.
3
+ import { attributed, md } from '../../display.mjs';
4
+ import { resultsLine } from '../../results.mjs';
5
+ import { anySignal } from '../domain-check/cache.mjs';
6
+ import { checkDomain, expiringSoonDays, loadCatalog, sortByUrgency, urgency } from './checks.mjs';
7
+ import { maxPaths, projectCandidates, spaceshipDomains } from './discover.mjs';
8
+ import { portfolioPages } from './page.mjs';
9
+ import { maxSavedDomains, portfolioDomain, portfolioFile, readList, updateList, writeList } from './store.mjs';
10
+
11
+ export const totalBudgetMs = 11_000;
12
+ const listLocation = '~/.domain-hound/portfolio.json';
13
+ const domainList = description => ({ type: 'array', minItems: 1, maxItems: maxSavedDomains, uniqueItems: true,
14
+ items: { type: 'string', minLength: 3, maxLength: 254 }, description });
15
+
16
+ export const portfolioTool = {
17
+ name: 'my_domains',
18
+ description: 'Track expiry, DNS, site, TLS, email and renewal prices for owned domains, most urgent first. '
19
+ + 'Use domains to save confirmed domains locally, remove to drop them, or no arguments to recheck. '
20
+ + 'Use find: true to preview candidates from project files and Spaceship. Show the candidates and add only the domains the person confirms. Relay say as written.',
21
+ annotations: { title: 'My domains', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
22
+ inputSchema: {
23
+ type: 'object',
24
+ properties: {
25
+ domains: domainList('Exact domains the person confirmed they own, like ["example.com"]. They join the saved list, then the whole list is checked.'),
26
+ find: { type: 'boolean', description: 'True to list candidate domains for the person to confirm. Saves and checks nothing.' },
27
+ paths: { type: 'array', minItems: 1, maxItems: maxPaths, items: { type: 'string', minLength: 1, maxLength: 1024 },
28
+ description: 'With find only: project folders to look in. Defaults to the current folder.' },
29
+ remove: domainList('Domains to drop from the saved list.'),
30
+ },
31
+ additionalProperties: false,
32
+ },
33
+ };
34
+
35
+ function domainsFrom(values, field) {
36
+ return values.map((value, index) => {
37
+ const domain = portfolioDomain(value);
38
+ if (!domain) throw Error(field + '[' + index + '] is not an exact domain. Use a domain like example.com.');
39
+ return domain;
40
+ });
41
+ }
42
+
43
+ function validate(input) {
44
+ const args = input ?? {};
45
+ if (typeof args !== 'object' || Array.isArray(args)
46
+ || Object.keys(args).some(key => !Object.hasOwn(portfolioTool.inputSchema.properties, key))) {
47
+ throw Error('Pass domains, find: true, remove, or nothing to recheck the saved list.');
48
+ }
49
+ const modes = ['domains', 'remove'].filter(key => Object.hasOwn(args, key)).concat(args.find === true ? ['find'] : []);
50
+ if (modes.length > 1) throw Error('Use one of domains, find or remove per call.');
51
+ if (Object.hasOwn(args, 'find') && typeof args.find !== 'boolean') throw Error('find must be true or false.');
52
+ if (Object.hasOwn(args, 'paths') && args.find !== true) throw Error('paths works only with find: true.');
53
+ for (const key of ['domains', 'remove']) {
54
+ if (Object.hasOwn(args, key) && (!Array.isArray(args[key]) || !args[key].length || args[key].length > maxSavedDomains)) {
55
+ throw Error(key + ' must list 1 to ' + maxSavedDomains + ' domains.');
56
+ }
57
+ }
58
+ if (Object.hasOwn(args, 'paths') && (!Array.isArray(args.paths) || !args.paths.length || args.paths.length > maxPaths
59
+ || args.paths.some(path => typeof path !== 'string' || !path.trim() || path.length > 1024 || /\p{Cc}/u.test(path)))) {
60
+ throw Error('paths must list 1 to ' + maxPaths + ' folders.');
61
+ }
62
+ return { mode: modes[0] ?? 'recheck', args };
63
+ }
64
+
65
+ const unreadable = 'Your saved list at ' + listLocation + ' could not be read. Fix or move that file, then try again.';
66
+ const money = value => '$' + value.toFixed(2).replace(/\.00$/, '');
67
+ const day = value => String(value).slice(0, 10);
68
+
69
+ // What needs doing for one domain, most urgent first. Unknown checks are left to the page.
70
+ export function issues(row) {
71
+ const r = row.registry;
72
+ const found = [...(r.problems ?? [])];
73
+ if (r.state === 'problem' && !r.problems?.length) found.push(r.reason);
74
+ if (r.daysLeft !== null && r.daysLeft >= 0 && r.daysLeft <= expiringSoonDays) {
75
+ found.push('expires in ' + r.daysLeft + (r.daysLeft === 1 ? ' day' : ' days') + ' (' + day(r.expires) + ')'
76
+ + (r.registrar ? ' at ' + r.registrar : '') + (r.autoRenewGrace ? '; registry shows auto-renew grace' : ''));
77
+ }
78
+ if (row.site.state === 'problem') found.push('site ' + row.site.reason);
79
+ if (row.tls.state === 'problem') found.push(row.tls.reason);
80
+ if (row.email.state === 'problem') found.push(row.email.reason);
81
+ if (row.money.move) found.push('save ' + money(row.money.move.saving) + ' over 3 years at ' + row.money.move.to + ' list prices');
82
+ return found;
83
+ }
84
+
85
+ // The short answer: the page link, a count, up to four urgent domains and up to two next steps. At most eight lines.
86
+ export function sayLines(rows) {
87
+ const flagged = rows.filter(row => urgency(row) <= 3);
88
+ const unknown = rows.reduce((count, row) => count + [row.registry, row.site, row.tls, row.email]
89
+ .filter(check => check.state === 'unknown').length, 0);
90
+ const lines = [rows.length + (rows.length === 1 ? ' domain' : ' domains') + ': '
91
+ + (flagged.length === 1 ? '1 needs attention' : flagged.length ? flagged.length + ' need attention' : 'nothing urgent')
92
+ + (unknown ? '. ' + unknown + (unknown === 1 ? ' check' : ' checks') + ' had no answer (see the page)' : '') + '.'];
93
+ for (const row of flagged.slice(0, 4)) lines.push(md(row.domain) + ': ' + md(issues(row).join('; ')).replace(/\.$/, '') + '.');
94
+ if (flagged.length > 4) lines.push((flagged.length - 4) + ' more on the page.');
95
+ const best = rows.filter(row => row.money.move).sort((a, b) => b.money.move.saving - a.money.move.saving)[0];
96
+ if (best) {
97
+ const move = best.money.move;
98
+ lines.push('Next: move to save ' + money(move.saving) + ' over 3 years on ' + md(best.domain) + '. [' + md(move.to) + ' transfer](' + move.url + '). '
99
+ + (move.estimate ? 'Snapshot' : 'List') + ' prices from ' + day(move.checkedAt) + '. Ask to plan the move with move_domain.');
100
+ }
101
+ const soonest = rows.filter(row => row.registry.daysLeft !== null && row.registry.daysLeft >= 0)
102
+ .sort((a, b) => a.registry.daysLeft - b.registry.daysLeft)[0];
103
+ if (soonest) {
104
+ lines.push('Next: watch expiry by email for ' + md(soonest.domain) + ' (' + day(soonest.registry.expires) + ').');
105
+ }
106
+ return lines.slice(0, 7);
107
+ }
108
+
109
+ // Check every domain side by side within one budget. A domain that runs out of time is shown with unknown checks.
110
+ export async function checkAll(domains, { checker = checkDomain, now = new Date(), budgetMs = totalBudgetMs, catalog } = {}) {
111
+ const started = performance.now();
112
+ const controller = new AbortController();
113
+ const signal = anySignal([controller.signal, AbortSignal.timeout(budgetMs)]);
114
+ const prices = catalog ?? await loadCatalog();
115
+ const late = domain => {
116
+ const unknown = { state: 'unknown', reason: 'no answer in time' };
117
+ return { domain, checkedAt: now.toISOString(),
118
+ registry: { state: 'unknown', reason: 'no answer in time', registrar: null, expires: null, daysLeft: null, status: [], nameservers: [] },
119
+ dnsHost: null, site: unknown, tls: unknown, email: unknown,
120
+ money: { currentShop: null, current: null, cheapest: null, move: null } };
121
+ };
122
+ let timer;
123
+ const cutoff = new Promise(resolve => { timer = setTimeout(resolve, budgetMs + 500); });
124
+ try {
125
+ return await Promise.all(domains.map(domain => Promise.race([
126
+ checker(domain, { signal, now, catalog: prices, deadline: started + budgetMs }).catch(() => late(domain)),
127
+ cutoff.then(() => late(domain)),
128
+ ])));
129
+ } finally {
130
+ clearTimeout(timer);
131
+ controller.abort();
132
+ }
133
+ }
134
+
135
+ const note = 'Checks use public registry records (RDAP or WHOIS), DNS, your sites over HTTPS and HTTP, and dated list prices. '
136
+ + 'An unknown result means the source did not answer. Registry auto-renew grace describes the current registration status. '
137
+ + 'Your list stays on this computer at ' + listLocation + '.';
138
+
139
+ // One page writer per server process, so the page opens in the background once, not on every call.
140
+ let sharedPages;
141
+
142
+ export async function myDomains(input, { env = process.env, file = portfolioFile(env), checker,
143
+ pages = (sharedPages ??= portfolioPages({ env })),
144
+ now = () => new Date(), budgetMs = totalBudgetMs, catalog, find = projectCandidates, spaceship = spaceshipDomains,
145
+ cwd = () => process.cwd() } = {}) {
146
+ const { mode, args } = validate(input);
147
+
148
+ if (mode === 'find') {
149
+ const paths = args.paths?.map(path => path.trim()) ?? [cwd()];
150
+ const [local, account, saved] = await Promise.all([find(paths), spaceship(), readList(file)]);
151
+ const known = new Set(saved.domains);
152
+ const merged = new Map();
153
+ for (const row of local) merged.set(row.domain, { domain: row.domain, sources: [...row.sources] });
154
+ for (const domain of account.domains ?? []) {
155
+ if (!merged.has(domain)) merged.set(domain, { domain, sources: [] });
156
+ merged.get(domain).sources.unshift('your Spaceship account');
157
+ }
158
+ const candidates = [...merged.values()].map(row => ({ ...row, saved: known.has(row.domain) }));
159
+ const fresh = candidates.filter(row => !row.saved);
160
+ const accountLine = account.state === 'ok' ? 'Spaceship account: ' + account.domains.length + ' domains listed (read-only).'
161
+ : account.state === 'not-connected' ? 'Spaceship account: not connected. Optional: a key with only domains:read lists your domains there.'
162
+ : 'Spaceship account: ' + account.reason + '.';
163
+ const lines = [fresh.length
164
+ ? 'Found ' + fresh.length + ' candidate ' + (fresh.length === 1 ? 'domain' : 'domains') + '. Nothing is saved until you confirm which are yours.'
165
+ : 'No new candidate domains found.',
166
+ ...fresh.slice(0, 25).map(row => '- ' + md(row.domain) + ' (' + md(row.sources.join(', ') || 'found') + ')'),
167
+ ...(fresh.length > 25 ? ['- and ' + (fresh.length - 25) + ' more'] : []),
168
+ ...(candidates.length > fresh.length ? [candidates.length - fresh.length + ' already saved.'] : []),
169
+ accountLine,
170
+ ...(fresh.length ? ['Confirm which domains should go on your list.'] : [])];
171
+ const say = attributed(lines.join('\n'));
172
+ return { display: say, say, candidates, spaceship: account.state };
173
+ }
174
+
175
+ if (mode === 'remove') {
176
+ const drop = new Set(domainsFrom(args.remove, 'remove'));
177
+ const { removed, kept } = await updateList(file, async saved => {
178
+ if (saved.state === 'unreadable') throw Error(unreadable);
179
+ const removed = saved.domains.filter(domain => drop.has(domain));
180
+ const kept = saved.domains.filter(domain => !drop.has(domain));
181
+ if (removed.length) await writeList(kept, file, now());
182
+ return { removed, kept };
183
+ });
184
+ const lines = [removed.length ? 'Removed ' + removed.map(md).join(', ') + ' from your saved list.' : 'None of those domains were saved.',
185
+ kept.length ? kept.length + ' saved: ' + kept.map(md).join(', ') + '.' : 'Your saved list is empty.'];
186
+ return { display: attributed(lines.join('\n')), removed, domains: kept };
187
+ }
188
+
189
+ const given = mode === 'domains' ? domainsFrom(args.domains, 'domains') : [];
190
+ const merge = async saved => {
191
+ if (saved.state === 'unreadable') throw Error(unreadable);
192
+ const domains = [...new Set([...saved.domains, ...given])];
193
+ if (domains.length > maxSavedDomains) {
194
+ throw Error('The saved list holds up to ' + maxSavedDomains + ' domains; it has ' + saved.domains.length
195
+ + '. Remove some first with remove.');
196
+ }
197
+ const added = domains.filter(domain => !saved.domains.includes(domain));
198
+ if (added.length) await writeList(domains, file, now());
199
+ return { domains, added };
200
+ };
201
+ const { domains, added } = given.length ? await updateList(file, merge) : await merge(await readList(file));
202
+ if (!domains.length) {
203
+ return { display: attributed('No saved domains yet. Name the domains you own, or ask me to find them in this project.'), domains: [] };
204
+ }
205
+
206
+ const checkedAt = now().toISOString();
207
+ const rows = sortByUrgency(await checkAll(domains, { checker, now: new Date(checkedAt), budgetMs, catalog }));
208
+ const lines = sayLines(rows);
209
+ const resultPage = await pages(rows, lines, checkedAt, note);
210
+ const say = [resultsLine(resultPage), ...lines].join('\n');
211
+ return { display: say, say, checkedAt, resultPage, added, domains: rows };
212
+ }
@@ -0,0 +1,62 @@
1
+ // The person's confirmed domain list, kept only on this machine so a repeat call needs no input.
2
+ // DOMAIN_HOUND_PORTFOLIO_FILE moves it (tests use a temporary folder). Nothing here is sent anywhere.
3
+ import { randomUUID } from 'node:crypto';
4
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { asciiDomain } from '../domain-check/name-search.mjs';
8
+ import { safeUrl } from '../domain-check/safe-web.mjs';
9
+
10
+ export const maxSavedDomains = 100;
11
+ const writes = new Map();
12
+
13
+ export function portfolioFile(env = process.env) {
14
+ return env.DOMAIN_HOUND_PORTFOLIO_FILE ? resolve(env.DOMAIN_HOUND_PORTFOLIO_FILE) : join(homedir(), '.domain-hound', 'portfolio.json');
15
+ }
16
+
17
+ export function portfolioDomain(value) {
18
+ if (typeof value !== 'string' || value.length > 254) return null;
19
+ const domain = asciiDomain(value.trim().replace(/\.$/, ''));
20
+ if (!domain || !/^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/.test(domain.split('.').at(-1))) return null;
21
+ return safeUrl('https://' + domain)?.hostname === domain ? domain : null;
22
+ }
23
+
24
+ // { domains, state }: state is "missing" (no file yet), "ok", or "unreadable" (a file we must not overwrite blindly).
25
+ export async function readList(file = portfolioFile()) {
26
+ let text;
27
+ try {
28
+ const info = await lstat(file);
29
+ if (!info.isFile() || info.size > 64 * 1024) return { domains: [], state: 'unreadable' };
30
+ text = await readFile(file, 'utf8');
31
+ } catch (error) {
32
+ return { domains: [], state: error?.code === 'ENOENT' ? 'missing' : 'unreadable' };
33
+ }
34
+ try {
35
+ const data = JSON.parse(text);
36
+ if (data && typeof data === 'object' && Array.isArray(data.domains) && data.domains.length <= maxSavedDomains
37
+ && data.domains.every(domain => typeof domain === 'string' && portfolioDomain(domain) === domain)) {
38
+ return { domains: [...new Set(data.domains)].slice(0, maxSavedDomains), state: 'ok', updatedAt: data.updatedAt ?? null };
39
+ }
40
+ } catch { /* fall through */ }
41
+ return { domains: [], state: 'unreadable' };
42
+ }
43
+
44
+ export function updateList(file, change) {
45
+ const next = (writes.get(file) ?? Promise.resolve()).catch(() => {}).then(async () => change(await readList(file)));
46
+ writes.set(file, next);
47
+ return next.finally(() => {
48
+ if (writes.get(file) === next) writes.delete(file);
49
+ });
50
+ }
51
+
52
+ export async function writeList(domains, file = portfolioFile(), now = new Date()) {
53
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
54
+ const temporary = file + '.' + randomUUID() + '.tmp';
55
+ const content = JSON.stringify({ version: 1, updatedAt: now.toISOString(), domains }, null, 2) + '\n';
56
+ try {
57
+ await writeFile(temporary, content, { flag: 'wx', mode: 0o600 });
58
+ await rename(temporary, file);
59
+ } finally {
60
+ await unlink(temporary).catch(() => {});
61
+ }
62
+ }
@@ -0,0 +1,41 @@
1
+ // Published USD renewal prices for common endings outside the portfolio's regular price feeds.
2
+ // These are dated estimates. Actual renewals can vary with discounts, taxes and premium names.
3
+ const checkedAt = '2026-11-25T00:00:00.000Z';
4
+ const godaddy = 'https://developer.godaddy.com/en/pricing/domains';
5
+ const hover = 'https://www.hover.com/domain-pricing';
6
+ const ionos = 'https://www.ionos.com/domains/domain-name-prices';
7
+ const squarespace = 'https://support.squarespace.com/hc/en-us/articles/205812208-Squarespace-domains-FAQ';
8
+ const spaceship = 'https://www.spaceship.com/domain-search/pricing/';
9
+
10
+ const renewals = new Map(Object.entries({
11
+ godaddy: { com: [22.99, godaddy], net: [24.99, godaddy], org: [23.99, godaddy] },
12
+ namecheap: {
13
+ com: [20.18, 'https://www.namecheap.com/support/knowledgebase/article.aspx/10840/2201/com-price-change-november-1-2026/'],
14
+ ai: [114.98, 'https://www.namecheap.com/domains/registration/cctld/ai/'],
15
+ io: [75.98, 'https://www.namecheap.com/domains/registration/cctld/io/'],
16
+ },
17
+ squarespace: { com: [20, squarespace], org: [20, squarespace] },
18
+ hover: { com: [19.99, hover], io: [74.99, hover], net: [19.99, hover], org: [17.99, hover] },
19
+ gandi: {
20
+ com: [38.38, 'https://www.gandi.net/en-US/domain/tld/com'],
21
+ ai: [179.76, 'https://www.gandi.net/en-US/domain/tld/ai'],
22
+ io: [74.99, 'https://www.gandi.net/en-US/domain/tld/io'],
23
+ },
24
+ ionos: { app: [25, ionos], co: [48, ionos], com: [20, ionos], me: [25, ionos], org: [20, ionos] },
25
+ }));
26
+
27
+ export function publishedRenewal(shop, ending, now) {
28
+ const prices = renewals.get(shop);
29
+ if (!prices || !Object.hasOwn(prices, ending) || now < Date.parse(checkedAt)) return null;
30
+ const [renewalPerYear, source] = prices[ending];
31
+ return { renewalPerYear, source, checkedAt, basis: 'snapshot' };
32
+ }
33
+
34
+ // The existing bundled catalog predates Spaceship's .net and .org rows. The regular prices here include the ICANN fee.
35
+ const spaceshipTransfers = new Map([['net', 11.4], ['org', 11.59]]);
36
+
37
+ export function publishedSpaceshipPrice(ending, now) {
38
+ const amount = spaceshipTransfers.get(ending);
39
+ if (amount === undefined || now < Date.parse(checkedAt)) return null;
40
+ return { id: 'spaceship', transfer: amount, renewal: amount, checkedAt, bundled: true, source: spaceship };
41
+ }
@@ -14,6 +14,11 @@ export const scopes = {
14
14
  buy: ['domains:read'],
15
15
  direct: ['domains:read', 'domains:billing', 'asyncoperations:read'],
16
16
  setup: ['domains:read', 'dnsrecords:read', 'dnsrecords:write'],
17
+ // move_domain: the live transfer quote, the direct transfer request (transferRequest needs domains:billing) and its status
18
+ // (getTransferInfo needs domains:transfer).
19
+ transfer: ['domains:read'],
20
+ transferDirect: ['domains:read', 'domains:billing', 'domains:transfer', 'asyncoperations:read'],
21
+ transferStatus: ['domains:transfer', 'asyncoperations:read'],
17
22
  };
18
23
 
19
24
  // One short instruction per tool when no key is set. It never asks for the secret in chat.
@@ -111,12 +116,36 @@ export function spaceshipClient({ key, secret, baseUrl = spaceshipBase, fetcher
111
116
  return { status: response.status, headers: response.headers, json };
112
117
  }
113
118
 
119
+ async function sendOnce(path, body, noun, privateRequest = false) {
120
+ if (!directPurchase(env)) {
121
+ throw Object.assign(new SpaceshipError('Direct purchase is off: DOMAIN_HOUND_DIRECT_PURCHASE is not 1.'), { notSent: true });
122
+ }
123
+ let headers;
124
+ try {
125
+ ({ headers } = await request('POST', path, { body, accept: [202] }));
126
+ } catch (problem) {
127
+ if (refusalStatuses.has(problem.status) && problem.detail) {
128
+ const detail = privateRequest ? null : problem.detail;
129
+ throw Object.assign(new SpaceshipError('Spaceship refused the ' + noun + ' (HTTP ' + problem.status
130
+ + (detail ? ': ' + detail : '') + ').', { status: problem.status, detail }), { notSent: true, refused: true });
131
+ }
132
+ if (privateRequest) throw new SpaceshipError('Spaceship returned no confirmed transfer result.', { ambiguous: true });
133
+ throw problem;
134
+ }
135
+ const operationId = headers.get('spaceship-async-operationid');
136
+ if (!operationId || (privateRequest && (!/^[A-Za-z0-9-]{1,36}$/.test(operationId)
137
+ || (body?.authCode && operationId.toLowerCase().includes(body.authCode.toLowerCase()))))) {
138
+ throw new SpaceshipError('Spaceship accepted the ' + noun + ' without an operation ID.', { ambiguous: true });
139
+ }
140
+ return { operationId };
141
+ }
142
+
114
143
  return {
115
144
  baseUrl: base,
116
145
  accountBinding: createHash('sha256').update(key).digest('hex'),
117
146
  // checkSingleDomainAvailability: { domain, result, premiumPricing }
118
147
  available: async domain => (await request('GET', '/v1/domains/' + domainPath(domain) + '/available')).json,
119
- // getSingleDomainPricing: { domain, priceClass, prices: { register: [...], renew: [...] } }
148
+ // getSingleDomainPricing: { domain, priceClass, prices: { register, transfer, renew } }, each a list of terms
120
149
  pricing: async domain => (await request('GET', '/v1/domains/' + domainPath(domain) + '/pricing')).json,
121
150
  // getDomainInfo: { name, lifecycleStatus, autoRenew, privacyProtection, nameservers, contacts }
122
151
  info: async domain => (await request('GET', '/v1/domains/' + domainPath(domain))).json,
@@ -146,24 +175,11 @@ export function spaceshipClient({ key, secret, baseUrl = spaceshipBase, fetcher
146
175
  // domainCreate has no price cap or idempotency field. It is sent only when the person set DOMAIN_HOUND_DIRECT_PURCHASE=1,
147
176
  // whatever the host, and exactly once: request() never retries. The gate below and Spaceship's documented refusal are
148
177
  // proven unsent (notSent); every other failure may have placed the order.
149
- async createDomain(domain, body) {
150
- if (!directPurchase(env)) {
151
- throw Object.assign(new SpaceshipError('Direct purchase is off: DOMAIN_HOUND_DIRECT_PURCHASE is not 1.'), { notSent: true });
152
- }
153
- let headers;
154
- try {
155
- ({ headers } = await request('POST', '/v1/domains/' + domainPath(domain), { body, accept: [202] }));
156
- } catch (problem) {
157
- if (refusalStatuses.has(problem.status) && problem.detail) {
158
- throw Object.assign(new SpaceshipError('Spaceship refused the order (HTTP ' + problem.status + ': ' + problem.detail + ').',
159
- { status: problem.status, detail: problem.detail }), { notSent: true, refused: true });
160
- }
161
- throw problem;
162
- }
163
- const operationId = headers.get('spaceship-async-operationid');
164
- if (!operationId) throw new SpaceshipError('Spaceship accepted the order without an operation ID.', { ambiguous: true });
165
- return { operationId };
166
- },
178
+ createDomain: (domain, body) => sendOnce('/v1/domains/' + domainPath(domain), body, 'order'),
179
+ // The transfer body contains an auth code. Never forward provider error details or unexpected operation IDs.
180
+ startTransfer: (domain, body) => sendOnce('/v1/domains/' + domainPath(domain) + '/transfer', body, 'transfer', true),
181
+ // getTransferInfo: { startedAt, finishedAt, direction, status }
182
+ transferInfo: async domain => (await request('GET', '/v1/domains/' + domainPath(domain) + '/transfer')).json,
167
183
  // getAsyncOperationDetails: { status: pending | success | failed, type, details }
168
184
  operation: async id => (await request('GET', '/v1/async-operations/' + encodeURIComponent(id))).json,
169
185
  };
@@ -5,15 +5,17 @@ import { mailProviders, websiteProviders } from './dns.mjs';
5
5
  import { exactDomain, offerLine, quoteTimes } from './quote.mjs';
6
6
  import { applySetup, previewSetup } from './setup.mjs';
7
7
  import { purchaseDir, stateStore } from './store.mjs';
8
+ import { issueTransferQuote, transferDomain, transferOfferLine, transferStatus } from './transfer.mjs';
9
+ import { loadCatalog } from '../portfolio/checks.mjs';
10
+ import { planFromFacts, planLines, transferRegistryRecord } from '../portfolio/move.mjs';
8
11
 
9
12
  // The three tools that act in the person's own Spaceship account. server.mjs only registers and dispatches them.
10
13
  const domainField = { type: 'string', minLength: 3, maxLength: 253, description: 'The exact domain, like example.com.' };
11
14
 
12
15
  export const quoteTool = {
13
16
  name: 'quote_domain',
14
- description: 'Get an exact live price for one domain from the person’s own Spaceship account: registration term (.ai is two years), '
15
- + 'upfront and renewal amounts, premium status and fresh registry availability. Returns a quote ID that expires in 10 minutes. '
16
- + 'Show the person the exact quote. Relay the display as written.',
17
+ description: 'Get a live Spaceship quote with the term, upfront and renewal prices, premium status and registry availability. '
18
+ + 'Show the exact quote, which expires in 10 minutes. Relay the display as written.',
17
19
  annotations: { title: 'Quote a domain at Spaceship', readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
18
20
  inputSchema: { type: 'object', properties: {
19
21
  domain: domainField,
@@ -23,10 +25,10 @@ export const quoteTool = {
23
25
 
24
26
  export const buyTool = {
25
27
  name: 'buy_domain',
26
- description: 'COSTS MONEY: requires an unexpired quote_id and the agreed max_usd. Stops on a changed price or above the max or server cap. '
27
- + 'Preview with Spaceship’s ' + spaceshipMcp.tool + ' by default. Check the total against the quote and both limits. Stop if the price or payment method '
28
- + 'is missing. Show the full confirmation and accept it only after approval. Direct orders require server opt-in, a standard-price minimum term, '
29
- + 'and confirm: true after approval. Spaceship sets the charge. Use checkout only with a valid quote and no submitted order. '
28
+ description: 'COSTS MONEY: needs an unexpired quote_id and agreed max_usd. Stop on price changes or above either limit. '
29
+ + 'Preview with Spaceship’s ' + spaceshipMcp.tool + ' by default. Check the quote and limits, stop if price or payment method is missing, '
30
+ + 'and accept the full confirmation only after showing it and getting approval. Direct orders need opt-in, a standard-price minimum term '
31
+ + 'and approved confirm: true. Spaceship sets the charge. Checkout requires a valid quote and no submitted order. '
30
32
  + 'Never retry an unclear order. Verify with setup_domain (verify: true) before offering DNS setup. Relay the display as written.',
31
33
  annotations: { title: 'Buy a domain (costs money)', readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
32
34
  inputSchema: { type: 'object', properties: {
@@ -40,12 +42,10 @@ export const buyTool = {
40
42
  const hostField = description => ({ type: 'string', maxLength: 253, description });
41
43
  export const setupTool = {
42
44
  name: 'setup_domain',
43
- description: 'Changes DNS: sets website and mail records for a domain in the person’s own Spaceship account. First call without plan_id '
44
- + 'to preview every exact change; nothing is written. Then, after the person says yes, call with plan_id and apply: true. '
45
- + 'Removing existing records also needs replace: true. Only provider values the person copied from their provider. '
46
- + 'With only verify: true it writes nothing: it looks the domain up at the registry and in the person’s Spaceship account to '
47
- + 'confirm a purchase. '
48
- + 'Use it after any purchase, through Spaceship’s MCP or checkout, before DNS setup. Relay the display as written.',
45
+ description: 'Changes DNS at Spaceship. Preview website and mail changes without plan_id. Apply with plan_id and apply: true after approval. '
46
+ + 'Record removal also needs replace: true. Use provider-supplied values. '
47
+ + 'With only verify: true it writes nothing: it looks the domain up at the registry and in the Spaceship account. '
48
+ + 'Verify after a purchase and before DNS setup. Relay the display as written.',
49
49
  annotations: { title: 'Set up domain DNS (changes DNS)', readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
50
50
  inputSchema: { type: 'object', properties: {
51
51
  domain: domainField,
@@ -73,7 +73,26 @@ export const setupTool = {
73
73
  }, required: ['domain'], additionalProperties: false },
74
74
  };
75
75
 
76
- export const purchaseTools = [quoteTool, buyTool, setupTool];
76
+ export const moveTool = {
77
+ name: 'move_domain',
78
+ description: 'Plan a transfer for an owned domain. Compare three-year costs, check locks and expiry, and get registrar steps. '
79
+ + 'A Spaceship key adds a 10-minute quote. COSTS MONEY with quote_id and max_usd: rechecks the quote and opens a path to checkout. '
80
+ + 'Direct transfer requires server opt-in, approval, confirm: true and the private auth_code. Keep the code private and never retry an unclear transfer. '
81
+ + 'Use status: true to follow a transfer. Relay the display as written.',
82
+ annotations: { title: 'Move a domain (plan; transfer costs money)', readOnlyHint: false, destructiveHint: true, idempotentHint: false,
83
+ openWorldHint: true },
84
+ inputSchema: { type: 'object', properties: {
85
+ domain: domainField,
86
+ quote_id: { type: 'string', maxLength: 40, description: 'The transfer quote ID from the plan.' },
87
+ max_usd: { type: 'number', exclusiveMinimum: 0, maximum: 100000, description: 'The most the person agreed to pay for the transfer, in USD.' },
88
+ confirm: { type: 'boolean', description: 'Direct transfers only: true after the person saw the dry run and said yes.' },
89
+ auth_code: { type: 'string', minLength: 1, maxLength: 50, description: 'Direct transfers only, with confirm: true. Pass the code from '
90
+ + 'the person’s private input. Keep it out of chat, logs and results.' },
91
+ status: { type: 'boolean', description: 'True, alone with domain, to follow a transfer into the person’s Spaceship account.' },
92
+ }, required: ['domain'], additionalProperties: false },
93
+ };
94
+
95
+ export const purchaseTools = [quoteTool, buyTool, setupTool, moveTool];
77
96
  export const purchaseToolNames = new Set(purchaseTools.map(tool => tool.name));
78
97
 
79
98
  // Replace stale global claims in the check tools with the handoff, whatever the rest of their wording says.
@@ -131,7 +150,7 @@ function checkInput(tool, args) {
131
150
  if (extra) throw Error(tool.name + ' does not take ' + JSON.stringify(extra.slice(0, 40)) + '.');
132
151
  const domain = exactDomain(args.domain);
133
152
  if (!domain) throw Error('Give one exact domain, such as example.com.');
134
- for (const flag of ['confirm', 'apply', 'replace', 'verify']) {
153
+ for (const flag of ['confirm', 'apply', 'replace', 'verify', 'status']) {
135
154
  if (Object.hasOwn(args, flag) && typeof args[flag] !== 'boolean') throw Error(flag + ' must be true or false.');
136
155
  }
137
156
  return domain;
@@ -142,7 +161,7 @@ function checkInput(tool, args) {
142
161
  // The purchase folder comes from the same env and is resolved here, once.
143
162
  export function purchaseHandlers({ env = process.env, credentials = () => spaceshipCredentials({ env }),
144
163
  clientFor = keys => spaceshipClient({ ...keys, env }), store = stateStore(purchaseDir(env)), registry, now = () => new Date(),
145
- sleep } = {}) {
164
+ sleep, facts, catalog = () => loadCatalog() } = {}) {
146
165
  async function client() {
147
166
  const keys = await credentials();
148
167
  return keys ? clientFor(keys) : null;
@@ -241,7 +260,76 @@ export function purchaseHandlers({ env = process.env, credentials = () => spaces
241
260
  return result(say, { domain, ...data });
242
261
  }
243
262
 
244
- const handlers = { quote_domain: quote, buy_domain: buy, setup_domain: setup };
263
+ // move_domain: a public plan by default; a live Spaceship transfer quote when a key is set; then the guarded transfer or
264
+ // its status. The auth code is only read in the direct transfer call and never appears in any answer or file.
265
+ async function move(args) {
266
+ const domain = checkInput(moveTool, args);
267
+ const has = key => Object.hasOwn(args, key);
268
+ if (has('auth_code') && typeof args.auth_code !== 'string') throw Error('auth_code must be text.');
269
+ if (has('status')) {
270
+ if (args.status !== true || Object.keys(args).some(key => key !== 'domain' && key !== 'status')) throw Error('status takes only domain and status: true.');
271
+ const api = await client();
272
+ if (!api) return result(missingKeyText('transferStatus'), { domain, transfer: null });
273
+ const { say, ...data } = await transferStatus(domain, { client: api, store });
274
+ return result(say, data);
275
+ }
276
+ if (!has('quote_id')) {
277
+ if (['max_usd', 'confirm', 'auth_code'].some(has)) throw Error('max_usd, confirm and auth_code need the quote_id from the plan.');
278
+ return plan(domain);
279
+ }
280
+ if (typeof args.quote_id !== 'string' || !args.quote_id) throw Error('Give the quote_id from the plan.');
281
+ if (typeof args.max_usd !== 'number' || !Number.isFinite(args.max_usd) || args.max_usd <= 0 || args.max_usd > 100_000) {
282
+ throw Error('Give max_usd, the most the person agreed to pay in USD.');
283
+ }
284
+ if (has('auth_code') && !directPurchaseEnabled(env)) {
285
+ throw Error('Direct transfer is off, so Domain Hound takes no auth code. The person enters it at Spaceship checkout. Nothing was sent.');
286
+ }
287
+ if (has('auth_code') && args.confirm !== true) throw Error('auth_code goes only with confirm: true, after the person approved the dry run.');
288
+ let apiPromise;
289
+ const live = async () => {
290
+ const api = await (apiPromise ??= client());
291
+ if (!api) throw new SpaceshipError(missingKeyText(directPurchaseEnabled(env) ? 'transferDirect' : 'transfer'));
292
+ return api;
293
+ };
294
+ const lazyClient = Object.fromEntries(['pricing', 'info', 'startTransfer', 'transferInfo', 'operation']
295
+ .map(method => [method, async (...rest) => (await live())[method](...rest)]));
296
+ const { say, ...data } = await transferDomain({ domain, quote_id: args.quote_id, max_usd: args.max_usd, confirm: args.confirm === true,
297
+ authCode: args.auth_code }, { client: lazyClient, accountBinding: async () => (await live()).accountBinding, store, facts, env, now,
298
+ ...(sleep && { sleep }) });
299
+ return result(say, { domain, ...data });
300
+ }
301
+
302
+ async function plan(domain) {
303
+ const at = now();
304
+ const [record, prices, api] = await Promise.all([transferRegistryRecord(domain, { facts, now: at }), catalog(), client()]);
305
+ let made = planFromFacts(domain, record, prices, at);
306
+ const extra = [];
307
+ let quoteData = null;
308
+ const canQuote = made.current.shop !== 'Spaceship' && made.verdict !== 'blocked';
309
+ if (!api) {
310
+ if (canQuote) extra.push('For a live Spaceship transfer price, set a Spaceship key with domains:read (see the README).');
311
+ } else if (canQuote) {
312
+ try {
313
+ const { offer, quote: issued } = await issueTransferQuote(domain, { client: api, store, record, now: at });
314
+ if (issued) {
315
+ made = planFromFacts(domain, record, prices, at, issued);
316
+ quoteData = { ...issued, amountUsd: issued.amount / 100, renewalUsd: issued.renewal.amount / 100 };
317
+ extra.push(transferOfferLine(issued), quoteTimes(issued) + ' Quote ID ' + issued.id + '.',
318
+ made.target?.id !== 'spaceship' ? 'This quote is for the Spaceship option. Use it only if the person chooses Spaceship.'
319
+ : directPurchaseEnabled(env) ? 'Show the person this quote and use move_domain with quote_id and max_usd for a dry run.'
320
+ : 'Show the person this quote and use move_domain with quote_id and max_usd for the Spaceship checkout handoff.');
321
+ } else {
322
+ extra.push('No live Spaceship transfer quote: ' + (offer.status === 'priced' ? offer.blockers.join('; ') + '.' : offer.reason));
323
+ }
324
+ } catch (problem) {
325
+ extra.push('No live Spaceship transfer quote: ' + (problem instanceof Error ? problem.message : 'Spaceship did not answer.'));
326
+ }
327
+ }
328
+ const say = [...planLines(made), ...extra].join('\n');
329
+ return result(say, { domain, plan: made, quote: quoteData });
330
+ }
331
+
332
+ const handlers = { quote_domain: quote, buy_domain: buy, setup_domain: setup, move_domain: move };
245
333
  return async function call(name, args) {
246
334
  try {
247
335
  return await handlers[name](args);