domain-hound 0.1.4 → 0.1.6

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 (43) 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 +106 -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/handles.mjs +337 -0
  12. package/clis/domain-check/index.mjs +69 -20
  13. package/clis/domain-check/marketplaces.mjs +107 -0
  14. package/clis/domain-check/meaning-words.LICENSE.txt +408 -0
  15. package/clis/domain-check/meaning-words.json +2397 -0
  16. package/clis/domain-check/meaning.mjs +77 -0
  17. package/clis/domain-check/name-search.mjs +83 -13
  18. package/clis/domain-check/naming-method.mjs +6 -4
  19. package/clis/domain-check/price-catalog.mjs +20 -12
  20. package/clis/domain-check/price-snapshot.json +142 -10
  21. package/clis/domain-check/registry.mjs +112 -19
  22. package/clis/domain-check/safe-web.mjs +207 -0
  23. package/clis/domain-check/traction.mjs +2 -2
  24. package/clis/domain-check/trademarks.mjs +372 -0
  25. package/clis/domain-check/triage-sources.mjs +52 -64
  26. package/clis/domain-check/triage.mjs +262 -72
  27. package/clis/spaceship/buy.mjs +327 -0
  28. package/clis/spaceship/client.mjs +170 -0
  29. package/clis/spaceship/dns.mjs +292 -0
  30. package/clis/spaceship/quote.mjs +123 -0
  31. package/clis/spaceship/setup.mjs +81 -0
  32. package/clis/spaceship/store.mjs +104 -0
  33. package/clis/spaceship/tools.mjs +258 -0
  34. package/display.mjs +16 -9
  35. package/dossier.mjs +185 -0
  36. package/package.json +36 -5
  37. package/plugin.json +4 -3
  38. package/results-style.mjs +10 -0
  39. package/results.mjs +291 -61
  40. package/server.json +3 -3
  41. package/server.mjs +275 -59
  42. package/share.mjs +43 -0
  43. package/site/r/share-format.mjs +125 -0
@@ -0,0 +1,327 @@
1
+ import { shopSearchUrl } from '../domain-check/prices.mjs';
2
+ import { boundFields, cents, changes, freshRegistry, liveOffer, minimumYears, offerLine, quoteLifetimeMs, usd } from './quote.mjs';
3
+ import { digest } from './store.mjs';
4
+
5
+ export const defaultCapUsd = 30;
6
+ export const checkoutUrl = domain => shopSearchUrl('spaceship', domain);
7
+
8
+ // Spaceship's own MCP server. Its purchase confirmation shows the term, the prices and the payment source, and a person
9
+ // approves it. Endpoint and client setup: https://www.spaceship.com/knowledgebase/ai-apps-supported-by-spaceship-and-spacemail-mcp/
10
+ export const spaceshipMcp = Object.freeze({
11
+ url: 'https://mcp.spaceship.com/mcp',
12
+ docs: 'https://www.spaceship.com/knowledgebase/ai-apps-supported-by-spaceship-and-spacemail-mcp/',
13
+ tool: 'domain_register',
14
+ poll: 'async_operation_get',
15
+ claude: 'claude mcp add --transport http spaceship https://mcp.spaceship.com/mcp',
16
+ codex: 'codex mcp add spaceship --url https://mcp.spaceship.com/mcp',
17
+ });
18
+
19
+ // Direct purchase through the REST API is the person's explicit opt-in, set only in the MCP server's environment.
20
+ // Exactly "1" turns it on; anything else, including "true", leaves it off. No tool argument reaches this.
21
+ export const directPurchaseEnabled = (env = process.env) => env?.DOMAIN_HOUND_DIRECT_PURCHASE === '1';
22
+
23
+ // The REST API cannot discover the account owner's contact, so the person sets its ID in the MCP server's environment.
24
+ // Spaceship documents contact IDs as 27 to 32 letters and digits (docs.spaceship.dev: updateDomainContacts and getContact,
25
+ // which domainCreate's contact IDs share).
26
+ export const contactIdPattern = /^[A-Za-z0-9]{27,32}$/;
27
+ export function ownerContact(env = process.env) {
28
+ const raw = env?.DOMAIN_HOUND_SPACESHIP_CONTACT_ID;
29
+ if (raw === undefined || raw.trim() === '') {
30
+ return { id: null, problem: 'Direct purchase needs DOMAIN_HOUND_SPACESHIP_CONTACT_ID, the contact ID of the Spaceship account owner. '
31
+ + 'Only the person can set it, in the MCP server settings' };
32
+ }
33
+ if (!contactIdPattern.test(raw.trim())) {
34
+ return { id: null, problem: 'DOMAIN_HOUND_SPACESHIP_CONTACT_ID is not a valid Spaceship contact ID (27 to 32 letters and digits). '
35
+ + 'Only the person can fix it, in the MCP server settings' };
36
+ }
37
+ return { id: raw.trim(), problem: null };
38
+ }
39
+
40
+ // The person's hard limit, set in the MCP server configuration. The agent has no input that raises it.
41
+ export function capCents(env = process.env) {
42
+ const raw = env.DOMAIN_HOUND_MAX_USD;
43
+ if (raw === undefined || raw.trim() === '') return defaultCapUsd * 100;
44
+ const value = Number(raw.trim());
45
+ if (!/^\d+(?:\.\d{1,2})?$/.test(raw.trim()) || !(value > 0) || value > 100_000) {
46
+ throw Error('DOMAIN_HOUND_MAX_USD must be a dollar amount, such as 30. Fix it in the MCP server settings.');
47
+ }
48
+ return Math.round(value * 100);
49
+ }
50
+
51
+ // domainCreate body: auto renew, high privacy, and the account owner for every contact role.
52
+ export function orderBody({ years }, owner) {
53
+ return { autoRenew: true, years, privacyProtection: { level: 'high', userConsent: true },
54
+ contacts: { registrant: owner, admin: owner, tech: owner, billing: owner } };
55
+ }
56
+
57
+ // One durable claim per domain, so neither a repeated call nor a second quote can send another order. Its status:
58
+ // "checking" while the last price check runs (nothing sent yet), "sending" from just before the POST, "sent" once Spaceship
59
+ // accepted the order (also when the order later failed), "uncertain" when the outcome is unknown. Every claim blocks; only
60
+ // "checking" may be cleared by hand. Older and unknown statuses, and unreadable files, count as sent.
61
+ export const claimKey = domain => 'dom-' + digest(domain).slice(0, 20);
62
+
63
+ // A quote whose expiry cannot be read counts as expired.
64
+ const readableExpiry = quote => typeof quote.expiresAt === 'string' && Number.isFinite(Date.parse(quote.expiresAt));
65
+ const expired = (quote, at) => !readableExpiry(quote) || at.getTime() >= Date.parse(quote.expiresAt);
66
+
67
+ // Issue a quote: one live check, bound to domain, term, amounts and currency, valid for ten minutes.
68
+ export async function issueQuote(domain, { client, store, registry, years, now = new Date() }) {
69
+ const offer = await liveOffer(domain, { client, registry, years, now });
70
+ if (offer.status !== 'available') return { offer, quote: null };
71
+ const expiresAt = new Date(now.getTime() + quoteLifetimeMs).toISOString();
72
+ const { accountBinding, ...quote } = await store.saveBound('quotes', 'dhq-', { ...boundFields(offer),
73
+ registry: offer.registry, offeredYears: offer.offeredYears, checkedAt: offer.checkedAt, expiresAt,
74
+ accountBinding: client.accountBinding });
75
+ return { offer, quote };
76
+ }
77
+
78
+ const term = years => years + (years === 1 ? ' year' : ' years');
79
+ const per = years => years === 1 ? 'year' : years + ' years';
80
+
81
+ // Last resort only, after a valid quote, when Spaceship's MCP cannot be used and nothing was submitted: the Spaceship search
82
+ // page, where the person pays at checkout and checks the same limits themselves.
83
+ export const checkoutHandoff = (quote, { max, cap }) => 'Buy it yourself at Spaceship: [' + quote.domain + ' at Spaceship]('
84
+ + checkoutUrl(quote.domain) + '). Before paying, check the same limits: ' + term(quote.years) + ', at most ' + usd(quote.amount)
85
+ + ' upfront (this quote; your max ' + usd(max) + ', cap ' + usd(cap) + '), renewal at most ' + usd(quote.renewal.amount) + ' per '
86
+ + per(quote.renewal.years) + ', WHOIS privacy on, auto-renew on. Stop if either price is higher or the term or settings differ. '
87
+ + 'Then ask Domain Hound to verify the domain '
88
+ + 'before DNS setup.';
89
+
90
+ // The default purchase path: Spaceship's own MCP previews the order, a person approves that exact confirmation, and only then
91
+ // does the agent accept it with the confirmation token bound to that preview.
92
+ export function mcpHandoff(quote, { max, cap }) {
93
+ const { domain } = quote;
94
+ const args = 'domain ' + domain + ', ' + term(quote.years) + ', WHOIS privacy on, auto-renew on';
95
+ return [
96
+ 'Hand off to Spaceship’s own MCP. Domain Hound ordered nothing.',
97
+ '1. Preview: call ' + spaceshipMcp.tool + ' with ' + args + ', and no confirmationToken. This registers nothing.',
98
+ '2. Check the preview: exactly ' + domain + ', ' + term(quote.years) + ', the USD total upfront and the renewal. Stop if the upfront '
99
+ + 'total is above this quote ' + usd(quote.amount) + ', the person’s max ' + usd(max) + ' or Domain Hound’s cap ' + usd(cap)
100
+ + ', if the renewal is above ' + usd(quote.renewal.amount) + ' per ' + per(quote.renewal.years)
101
+ + ', or if the price or the payment method is missing. Require USD, WHOIS privacy and auto-renew in the preview.',
102
+ '3. Show the person the full confirmation and wait for their yes. Only then call ' + spaceshipMcp.tool + ' again with the exact '
103
+ + 'same arguments, the confirmationToken from that preview and confirmationResponse: "accept". A fresh preview needs a fresh yes.',
104
+ '4. Poll ' + spaceshipMcp.poll + ' until the operation finishes. If the outcome is unclear, stop: no retry and no other route, '
105
+ + 'not here, not through Domain Hound, not at checkout. Tell the person to check orders in their Spaceship account.',
106
+ '5. After the operation succeeds, call setup_domain with domain ' + domain + ' and verify: true. Offer DNS setup only after it verifies.',
107
+ 'No Spaceship MCP? Connect it, then sign in when asked (' + spaceshipMcp.docs + '):',
108
+ 'Claude Code: `' + spaceshipMcp.claude + '`',
109
+ 'Codex: `' + spaceshipMcp.codex + '`',
110
+ 'Last resort, only if Spaceship’s MCP cannot be used and nothing was submitted there: ' + checkoutHandoff(quote, { max, cap }),
111
+ ].join('\n');
112
+ }
113
+
114
+ // Direct mode charges what Spaceship sets at registration. The quote is the best estimate, not the charge.
115
+ const estimateLine = quote => 'Quoted estimate, not the actual charge: ' + usd(quote.amount) + ' upfront for ' + term(quote.years)
116
+ + ', renewal ' + usd(quote.renewal.amount) + ' per ' + per(quote.renewal.years) + '. Spaceship sets the actual charge; your '
117
+ + 'Spaceship account shows it.';
118
+
119
+ const refusal = (text, fields = {}) => ({ ok: false, ordered: false, say: text, ...fields });
120
+ const checkAccount = 'Do not retry here, through Spaceship’s MCP or at checkout. Check orders in your Spaceship account first.';
121
+ const alreadySent = (domain, prior) => refusal('An order for ' + domain + ' was already sent'
122
+ + (prior?.status ? ' (' + prior.status + (prior.operationId ? ', operation ' + prior.operationId : '') + ')' : '')
123
+ + '. Domain Hound never sends a second order. ' + checkAccount,
124
+ { alreadySent: true, ...(prior?.operationId && { operationId: prior.operationId }) });
125
+
126
+ // A claim in "checking" is a live guard: another call holds it and has sent nothing yet. It never clears by itself, since
127
+ // that call may still be running, so the person gets the safe manual recovery.
128
+ const inProgress = (domain, store, path) => refusal('Not ordered: another purchase of this domain is in progress (' + domain + '). '
129
+ + 'Its claim ' + path + ' says "checking": that purchase is running its last price check and has sent no order. Domain Hound '
130
+ + 'sends no second order. Wait a minute and ask again. If no purchase is running (say, Domain Hound stopped mid-check): '
131
+ + 'stop every Domain Hound instance that uses ' + store.directory + ', check that the claim’s status is exactly "checking", '
132
+ + 'move the file out of that folder, then get a fresh quote. If the status is anything else, leave the file and check orders '
133
+ + 'in your Spaceship account.', { inProgress: true, claimPath: path });
134
+
135
+ // The answer for any existing claim: in progress while it is checking, already sent otherwise.
136
+ async function blockedBy(domain, store) {
137
+ const key = claimKey(domain);
138
+ const prior = await store.readClaim(key);
139
+ if (!prior) return null;
140
+ return prior.status === 'checking' ? inProgress(domain, store, store.claimPath(key)) : alreadySent(domain, prior);
141
+ }
142
+
143
+ // Guardrails in order: no earlier order, valid unexpired quote, explicit max, cap, strict re-quote. Then, without direct
144
+ // mode, the Spaceship MCP handoff. With direct mode: owner contact, non-premium, registry minimum term, registry free, dry run
145
+ // or order. The earlier order comes first: it needs no key and no quote, so a lost key or an expired quote still ends in
146
+ // the account check and never in another route.
147
+ export async function buyDomain(input, { client, accountBinding, store, registry, env = process.env,
148
+ now = () => new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), polls = 5, pollMs = 3000 }) {
149
+ const { domain, quote_id: quoteId, max_usd: maxUsd, confirm = false } = input;
150
+ const blocked = await blockedBy(domain, store);
151
+ if (blocked) return blocked;
152
+ const cap = capCents(env);
153
+ const stored = await store.readBound('quotes', 'dhq-', quoteId);
154
+ if (!stored) return refusal('No valid quote with that ID. Call quote_domain, show the person the exact quote, then use its ID.');
155
+ const { accountBinding: quotedAccount, ...quote } = stored;
156
+ if (quote.domain !== domain) return refusal('That quote is for ' + quote.domain + ', not ' + domain + '. Nothing ordered.');
157
+ if (expired(quote, now())) {
158
+ return refusal('Quote ' + quoteId + (readableExpiry(quote) ? ' expired at ' + quote.expiresAt.slice(11, 16) + ' UTC.' : ' has no readable expiry, so it counts as expired.')
159
+ + ' Quote again. Nothing ordered.', { expired: true });
160
+ }
161
+ const max = cents(String(maxUsd));
162
+ if (max === null || max <= 0) return refusal('Give max_usd as a positive USD amount in whole cents.');
163
+ if (quote.amount > max) {
164
+ return refusal('The quote is ' + usd(quote.amount) + ', over the max of ' + usd(max) + '. Nothing ordered.', { overMax: true });
165
+ }
166
+ if (quote.amount > cap) {
167
+ return refusal('The quote is ' + usd(quote.amount) + ', over the cap of ' + usd(cap) + ' set by DOMAIN_HOUND_MAX_USD. '
168
+ + 'Only the person can raise it in the MCP server settings. Nothing ordered.', { overCap: true });
169
+ }
170
+ if (quotedAccount !== await accountBinding()) return refusal('The Spaceship key changed since the quote. Quote again.');
171
+ const fresh = await liveOffer(domain, { client, registry, years: quote.years, now: now() });
172
+ if (expired(quote, now())) {
173
+ return refusal('The quote expired during the price check. Quote again.');
174
+ }
175
+ const changed = changes(quote, fresh);
176
+ if (changed.length) {
177
+ return refusal('Not ordered: ' + changed.join('; ') + '. Quote again and show the person the new quote.', { changed });
178
+ }
179
+ // An order claimed by another call while this one re-checked: no handoff, dry run or order may go around it.
180
+ const claimed = await blockedBy(domain, store);
181
+ if (claimed) return claimed;
182
+ const summary = offerLine(quote) + ' Re-checked ' + fresh.checkedAt.slice(11, 16) + ' UTC, unchanged. The quote is within the max '
183
+ + 'of ' + usd(max) + ' and the cap of ' + usd(cap) + '.';
184
+ if (!directPurchaseEnabled(env)) {
185
+ return { ok: true, ordered: false, handoff: 'spaceship-mcp', quote, ceilings: { quote: quote.amount, max, cap },
186
+ say: [summary, mcpHandoff(quote, { max, cap })].join('\n') };
187
+ }
188
+ const direct = directRefusal(quote, fresh, env);
189
+ if (direct) {
190
+ return refusal('Not ordered: ' + direct + '. Nothing was sent.\n' + summary + '\n' + mcpHandoff(quote, { max, cap }),
191
+ { direct: false, handoff: 'spaceship-mcp' });
192
+ }
193
+ if (confirm !== true) {
194
+ return { ok: true, ordered: false, dryRun: true, quote, say: ['Dry run. Nothing ordered.', summary, estimateLine(quote),
195
+ 'Direct purchase is on. Show the person this exact quote. Only after their yes, call buy_domain again with confirm true.'].join('\n') };
196
+ }
197
+ return placeOrder(quote, { client, store, registry, owner: ownerContact(env).id, now, sleep, polls, pollMs });
198
+ }
199
+
200
+ // Direct mode orders only what the brief allows: the owner contact is set, a standard price, the registry minimum term
201
+ // (one year; two for .ai), and a registry that answers free. The minimum is known per ending, never inferred from the terms
202
+ // Spaceship happens to price: a .com priced only for two years is still refused.
203
+ function directRefusal(quote, fresh, env) {
204
+ const { problem } = ownerContact(env);
205
+ if (problem) return problem;
206
+ if (quote.premium || quote.priceClass !== 'standard') return 'direct purchase never buys a premium domain';
207
+ const minimum = minimumYears(quote.domain);
208
+ if (quote.years !== minimum || fresh.years !== minimum) {
209
+ return 'direct purchase buys only the registry minimum term, ' + term(minimum) + ', not ' + term(quote.years);
210
+ }
211
+ if (fresh.registry !== 'free') return 'the registry did not confirm availability';
212
+ return null;
213
+ }
214
+
215
+ async function placeOrder(quote, { client, store, registry, owner, now, sleep, polls, pollMs }) {
216
+ const { domain } = quote;
217
+ const key = claimKey(domain);
218
+ let record = await store.claim(key, { domain, quoteId: quote.id, quotedAmount: quote.amount, years: quote.years,
219
+ status: 'checking', at: now().toISOString() });
220
+ if (!record) {
221
+ return await blockedBy(domain, store) ?? refusal('Not ordered: another purchase of this domain was in progress and has just '
222
+ + 'ended. This call sent nothing. Get a fresh quote.');
223
+ }
224
+ // Last check while holding the claim in "checking", seconds before the order: the same price, term, availability and a
225
+ // free registry. These refusals are proven before anything is sent, so they release the claim.
226
+ let last;
227
+ try {
228
+ last = await liveOffer(domain, { client, registry, years: quote.years, now: now() });
229
+ } catch (problem) {
230
+ await store.release(key);
231
+ return refusal('Not ordered: the last price check failed (' + problem.message + '). Nothing was sent. Quote again.');
232
+ }
233
+ const changed = changes(quote, last);
234
+ if (!changed.length && last.registry !== 'free') changed.push('the registry did not confirm availability');
235
+ if (expired(quote, now())) changed.push('the quote expired');
236
+ if (changed.length) {
237
+ await store.release(key);
238
+ return refusal('Not ordered: ' + changed.join('; ') + '. Nothing was sent. Quote again and show the person the new quote.', { changed });
239
+ }
240
+ // Recorded atomically just before the POST. If it cannot be written, nothing is sent.
241
+ record = { ...record, status: 'sending' };
242
+ try {
243
+ await store.updateClaim(key, record);
244
+ } catch (problem) {
245
+ await store.release(key);
246
+ return refusal('Not ordered: Domain Hound could not record the order on disk (' + problem.message + '). Nothing was sent.');
247
+ }
248
+ // From here the order may exist. Local bookkeeping is best effort: a disk error never hides the outcome, and a failed
249
+ // write leaves the existing claim file in place (writes replace it atomically), so no second order can follow.
250
+ const mark = async fields => {
251
+ record = { ...record, ...fields };
252
+ try { await store.updateClaim(key, record); } catch { /* the claim on disk still blocks a second order */ }
253
+ };
254
+ let operationId;
255
+ try {
256
+ ({ operationId } = await client.createDomain(domain, orderBody(quote, owner)));
257
+ } catch (problem) {
258
+ // Only the client's own gate and Spaceship's documented refusal are proven unsent. Anything else keeps the claim:
259
+ // no retry, no other path, the person checks the account.
260
+ if (problem.notSent === true) {
261
+ await store.release(key);
262
+ if (problem.refused === true) {
263
+ return refusal('Not ordered: ' + problem.message + ' Spaceship placed no order for ' + domain + '. Fix the cause, then '
264
+ + 'get a fresh quote.', { refused: true });
265
+ }
266
+ return refusal('Not ordered: ' + problem.message + ' Nothing was sent.');
267
+ }
268
+ await mark({ status: 'uncertain', reason: String(problem.message).slice(0, 200) });
269
+ return refusal('The order result for ' + domain + ' is unclear (' + problem.message + '). Domain Hound will not send it again. '
270
+ + checkAccount, { ambiguous: true });
271
+ }
272
+ await mark({ status: 'sent', operationId });
273
+ let operation = null;
274
+ for (let attempt = 0; attempt < polls; attempt++) {
275
+ operation = await client.operation(operationId).catch(() => null);
276
+ if (operation?.status === 'success' || operation?.status === 'failed') break;
277
+ if (attempt < polls - 1) await sleep(pollMs);
278
+ }
279
+ if (operation?.status === 'failed') {
280
+ await mark({ status: 'sent', outcome: 'failed' });
281
+ return refusal('Spaceship reports the order for ' + domain + ' failed (operation ' + operationId + '). Domain Hound will not '
282
+ + 'send it again. ' + checkAccount, { failed: true, operationId });
283
+ }
284
+ if (operation?.status !== 'success') {
285
+ await mark({ status: 'uncertain' });
286
+ return refusal('Spaceship has not finished the order for ' + domain + ' (operation ' + operationId + '). Domain Hound will not '
287
+ + 'send it again. ' + checkAccount, { ambiguous: true, operationId });
288
+ }
289
+ const verified = await verifyRegistration(domain, { client, registry });
290
+ const checks = { ...verified.checks, ownerIsRegistrant: verified.info?.contacts?.registrant === owner };
291
+ const at = now().toISOString();
292
+ const receipt = { domain, at, quoteId: quote.id, operationId, years: quote.years, quotedAmount: quote.amount,
293
+ quotedRenewal: quote.renewal, currency: quote.currency,
294
+ note: 'Quoted estimates, not the actual charge. Spaceship sets the actual charge; see the order in your Spaceship account.',
295
+ checks };
296
+ let path = null;
297
+ let receiptProblem = null;
298
+ try {
299
+ path = await store.saveReceipt(receipt);
300
+ } catch (problem) {
301
+ receiptProblem = problem instanceof Error ? problem.message : String(problem);
302
+ }
303
+ await mark({ status: 'sent', outcome: verified.registered ? 'success' : 'success-unverified', ...(path && { receipt: path }) });
304
+ const missing = Object.entries(checks).filter(([, ok]) => !ok).map(([name]) => name);
305
+ return { ok: true, ordered: true, verified: verified.registered, operationId, receipt, receiptPath: path, say: [
306
+ 'Ordered ' + domain + ': Spaceship reports the registration succeeded (operation ' + operationId + ').',
307
+ estimateLine(quote),
308
+ missing.length ? 'Readback needs a look: ' + missing.join(', ') + '. Check your Spaceship account.'
309
+ : 'Verified: registered at the registry and in your Spaceship account, high privacy, auto renew on, owner contact set.',
310
+ path ? 'Receipt: ' + path : 'No local receipt: Domain Hound could not save it (' + receiptProblem + '). The order itself went '
311
+ + 'through; your Spaceship account has the record.',
312
+ verified.registered ? setupOffer(domain) : 'Check again with setup_domain and verify: true. Offer DNS setup only after it verifies.'].join('\n') };
313
+ }
314
+
315
+ export const setupOffer = domain => 'Next: set up ' + domain + ' for your website and mail. Call setup_domain with website or mail to '
316
+ + 'preview the exact DNS records.';
317
+
318
+ // Independent proof a domain belongs to this account: the registry lists it as registered, and the authenticated Spaceship
319
+ // account holds it. Either alone could be someone else's registration or a pending order.
320
+ export async function verifyRegistration(domain, { client, registry }) {
321
+ const [info, registryStatus] = await Promise.all([
322
+ client.info(domain).catch(problem => problem?.status === 404 ? null : undefined), freshRegistry(domain, registry)]);
323
+ const inAccount = info?.name === domain && info.lifecycleStatus === 'registered';
324
+ const checks = { registry: registryStatus === 'taken', account: inAccount, privacyHigh: info?.privacyProtection?.level === 'high',
325
+ autoRenew: info?.autoRenew === true };
326
+ return { registered: checks.registry && checks.account, checks, info, registryStatus, accountKnown: info !== undefined };
327
+ }
@@ -0,0 +1,170 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+
4
+ // First-party Spaceship REST API: https://docs.spaceship.dev
5
+ // Every request sends X-API-Key and X-API-Secret, JSON bodies, and refuses redirects.
6
+ export const spaceshipBase = 'https://spaceship.dev/api';
7
+ export const keychainService = 'domain-hound';
8
+ export const keychainAccounts = { key: 'spaceship-key', secret: 'spaceship-secret' };
9
+
10
+ // The smallest Spaceship API scopes each tool needs.
11
+ // Direct purchase (DOMAIN_HOUND_DIRECT_PURCHASE=1) also needs domains:billing for domainCreate and asyncoperations:read.
12
+ export const scopes = {
13
+ quote: ['domains:read'],
14
+ buy: ['domains:read'],
15
+ direct: ['domains:read', 'domains:billing', 'asyncoperations:read'],
16
+ setup: ['domains:read', 'dnsrecords:read', 'dnsrecords:write'],
17
+ };
18
+
19
+ // One short instruction per tool when no key is set. It never asks for the secret in chat.
20
+ export function missingKeyText(tool) {
21
+ return 'No Spaceship API key found. In Spaceship, create a key with only ' + scopes[tool].join(', ')
22
+ + '. Then set DOMAIN_HOUND_SPACESHIP_KEY and DOMAIN_HOUND_SPACESHIP_SECRET for the MCP server, or store both in the '
23
+ + 'macOS Keychain as shown under "Buy and set up" in the README. Never paste the secret into chat.';
24
+ }
25
+
26
+ export class SpaceshipError extends Error {
27
+ constructor(message, { status = null, ambiguous = false, detail = null } = {}) {
28
+ super(message);
29
+ this.status = status;
30
+ this.ambiguous = ambiguous;
31
+ this.detail = detail;
32
+ }
33
+ }
34
+
35
+ // domainCreate documents 400, 401, 403, 404, 422 and 429 as application/problem+json with a detail string; 402 with the same
36
+ // body is the same definite refusal. Only such an answer proves Spaceship placed no order. A timeout (also HTTP 408), a 5xx,
37
+ // a body that cannot be read or a body without a detail string stays unclear.
38
+ const refusalStatuses = new Set([400, 401, 402, 403, 404, 422, 429]);
39
+ function problemDetail(response, text) {
40
+ if (!/^application\/problem\+json\s*(?:;|$)/i.test(response.headers.get('content-type') ?? '')) return null;
41
+ try {
42
+ const body = JSON.parse(text);
43
+ const detail = body && typeof body === 'object' && !Array.isArray(body) && typeof body.detail === 'string'
44
+ ? body.detail.replace(/\p{Cc}+/gu, ' ').trim().slice(0, 200) : '';
45
+ return detail || null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ function readKeychain(account) {
52
+ if (process.platform !== 'darwin') return Promise.resolve(null);
53
+ return new Promise(resolve => {
54
+ execFile('/usr/bin/security', ['find-generic-password', '-s', keychainService, '-a', account, '-w'],
55
+ { timeout: 4000, windowsHide: true }, (error, stdout) => resolve(error ? null : stdout.replace(/\r?\n$/, '') || null));
56
+ });
57
+ }
58
+
59
+ // Environment first, then the macOS Keychain. Returns null when either half is missing.
60
+ export async function spaceshipCredentials({ env = process.env, keychain = readKeychain } = {}) {
61
+ const key = env.DOMAIN_HOUND_SPACESHIP_KEY?.trim();
62
+ const secret = env.DOMAIN_HOUND_SPACESHIP_SECRET?.trim();
63
+ if (key && secret) return { key, secret, source: 'environment' };
64
+ const [storedKey, storedSecret] = await Promise.all([keychain(keychainAccounts.key), keychain(keychainAccounts.secret)]);
65
+ if (storedKey?.trim() && storedSecret?.trim()) return { key: storedKey.trim(), secret: storedSecret.trim(), source: 'keychain' };
66
+ return null;
67
+ }
68
+
69
+ const loopback = new Set(['127.0.0.1', 'localhost', '[::1]']);
70
+ export const isLoopback = url => loopback.has(new URL(url).hostname);
71
+
72
+ const domainPath = domain => encodeURIComponent(domain);
73
+
74
+ // The person's explicit opt-in for live registration orders, read from the MCP server's environment only. Exactly "1".
75
+ const directPurchase = env => env?.DOMAIN_HOUND_DIRECT_PURCHASE === '1';
76
+
77
+ // A thin client for the documented endpoints. baseUrl and fetcher are injectable for the local test mock only. env is the
78
+ // server environment; no tool argument reaches it.
79
+ export function spaceshipClient({ key, secret, baseUrl = spaceshipBase, fetcher = globalThis.fetch, timeout = 8000, env = process.env }) {
80
+ if (!key || !secret) throw new SpaceshipError('Spaceship API key and secret are required.');
81
+ const base = baseUrl.replace(/\/+$/, '');
82
+ if (base !== spaceshipBase && !isLoopback(base)) throw new SpaceshipError('Spaceship API base must be ' + spaceshipBase + '.');
83
+
84
+ async function request(method, path, { query, body, accept = [200] } = {}) {
85
+ const url = base + path + (query ? '?' + new URLSearchParams(query) : '');
86
+ let response;
87
+ try {
88
+ response = await fetcher(url, {
89
+ method, redirect: 'error', signal: AbortSignal.timeout(timeout),
90
+ headers: { 'X-API-Key': key, 'X-API-Secret': secret, Accept: 'application/json',
91
+ ...(body !== undefined && { 'Content-Type': 'application/json' }) },
92
+ ...(body !== undefined && { body: JSON.stringify(body) }),
93
+ });
94
+ } catch {
95
+ // A write may have reached Spaceship before the connection failed.
96
+ throw new SpaceshipError('Spaceship did not answer in time.', { ambiguous: method !== 'GET' });
97
+ }
98
+ let readable = true;
99
+ const text = await response.text().catch(() => { readable = false; return ''; });
100
+ if (!accept.includes(response.status)) {
101
+ const reason = response.status === 401 || response.status === 403 ? 'Spaceship refused the API key or its scope'
102
+ : response.status === 404 ? 'Spaceship has no such item' : response.status === 429 ? 'Spaceship rate limit reached'
103
+ : 'Spaceship answered HTTP ' + response.status;
104
+ throw new SpaceshipError(reason + '.', { status: response.status, ambiguous: method !== 'GET' && response.status >= 500,
105
+ detail: readable ? problemDetail(response, text) : null });
106
+ }
107
+ let json = null;
108
+ if (text) {
109
+ try { json = JSON.parse(text); } catch { throw new SpaceshipError('Spaceship returned invalid JSON.', { status: response.status }); }
110
+ }
111
+ return { status: response.status, headers: response.headers, json };
112
+ }
113
+
114
+ return {
115
+ baseUrl: base,
116
+ accountBinding: createHash('sha256').update(key).digest('hex'),
117
+ // checkSingleDomainAvailability: { domain, result, premiumPricing }
118
+ available: async domain => (await request('GET', '/v1/domains/' + domainPath(domain) + '/available')).json,
119
+ // getSingleDomainPricing: { domain, priceClass, prices: { register: [...], renew: [...] } }
120
+ pricing: async domain => (await request('GET', '/v1/domains/' + domainPath(domain) + '/pricing')).json,
121
+ // getDomainInfo: { name, lifecycleStatus, autoRenew, privacyProtection, nameservers, contacts }
122
+ info: async domain => (await request('GET', '/v1/domains/' + domainPath(domain))).json,
123
+ // getResourceRecordsList, read every page.
124
+ async dnsRecords(domain) {
125
+ const items = [];
126
+ let total;
127
+ for (let page = 0; page < 20; page++) {
128
+ const { json } = await request('GET', '/v1/dns/records/' + domainPath(domain), {
129
+ query: { take: 500, skip: items.length },
130
+ });
131
+ const rows = json?.items;
132
+ total ??= json?.total;
133
+ if (!Array.isArray(rows) || !Number.isInteger(total) || total < 0 || json.total !== total
134
+ || items.length + rows.length > total || (!rows.length && items.length < total)) {
135
+ throw new SpaceshipError('Spaceship returned an incomplete DNS list. Preview again.');
136
+ }
137
+ items.push(...rows);
138
+ if (items.length === total) return items;
139
+ }
140
+ throw new SpaceshipError('Spaceship listed too many DNS records to plan safely.');
141
+ },
142
+ // saveRecords with force false: adds items, or updates the TTL of an exact match.
143
+ saveRecords: (domain, items) => request('PUT', '/v1/dns/records/' + domainPath(domain), { body: { force: false, items }, accept: [204] }),
144
+ // deleteRecords: removes exact custom records only.
145
+ deleteRecords: (domain, items) => request('DELETE', '/v1/dns/records/' + domainPath(domain), { body: items, accept: [204] }),
146
+ // domainCreate has no price cap or idempotency field. It is sent only when the person set DOMAIN_HOUND_DIRECT_PURCHASE=1,
147
+ // whatever the host, and exactly once: request() never retries. The gate below and Spaceship's documented refusal are
148
+ // 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
+ },
167
+ // getAsyncOperationDetails: { status: pending | success | failed, type, details }
168
+ operation: async id => (await request('GET', '/v1/async-operations/' + encodeURIComponent(id))).json,
169
+ };
170
+ }