// Minimal DNSimple client for the connected-services prototype // (docs/connected-services.md). Kept tiny and dependency-free so the only impure // part is the fetch — point it at a fake with LCHAT_DNSIMPLE_BASE in tests. // // The token this receives is a *scoped* DNSimple access token, handed to the bot // inside a time-boxed, sealed capability grant — never stored on this host. We // hold it only for the duration of one call and drop it. const BASE = (process.env.LCHAT_DNSIMPLE_BASE || "https://api.dnsimple.com").replace(/\/$/, ""); async function api(token, method, path) { const r = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${token}`, Accept: "application/json" }, }); const text = await r.text(); let data = {}; try { data = text ? JSON.parse(text) : {}; } catch {} if (!r.ok) throw new Error(data && data.message ? data.message : `DNSimple ${r.status}`); return data; } // exchangeViaBroker swaps an authorization code for an access token via the // connect broker (docs/connected-services.md). DNSimple only offers CONFIDENTIAL // OAuth apps, so the exchange needs the client_secret — which lives ONLY on the // broker (like the APNs .p8 on the push relay), never on this sidecar. We // authenticate to the broker with a per-instance bearer token and get back only // the user's access token, which the caller seals to the member and drops. export async function exchangeViaBroker({ code, state, brokerUrl, brokerToken }) { if (!brokerUrl || !brokerToken) throw new Error("connect broker not configured on this sidecar (set LCHAT_CONNECT_BROKER_URL/_TOKEN)"); const r = await fetch(`${brokerUrl.replace(/\/$/, "")}/api/exchange`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${brokerToken}` }, body: JSON.stringify({ code, state }), }); const d = await r.json().catch(() => ({})); if (!r.ok || !d.access_token) throw new Error(d && d.message ? d.message : `broker exchange ${r.status}`); return d.access_token; } // whoami resolves the single account the token acts for. An account-scoped token // returns `{ data: { account: { id } } }`; a user token that spans several // accounts returns a user instead — we refuse it, since registrar calls are // account-scoped and we won't guess which account to spend from. export async function whoami(token) { const d = await api(token, "GET", "/v2/whoami"); const id = d && d.data && d.data.account && d.data.account.id; if (!id) throw new Error("that token isn't scoped to a single account — create an account access token"); return id; } // Run an async fn over items with a bounded number in flight — the domains list // doesn't include pricing, so we fetch it per-domain and don't want N sockets at // once (nor to trip DNSimple's rate limit). async function mapLimit(items, limit, fn) { const queue = items.map((item, i) => [item, i]); const worker = async () => { for (;;) { const next = queue.shift(); if (!next) return; await fn(next[0], next[1]); } }; await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); } // listDomains returns structured rows for the DNSimple app's table. GET // /v2/{account}/domains gives name/state/expiry/auto_renew; the renewal price // isn't in that payload, so we look it up per-domain (best-effort, bounded // concurrency) — a failure just leaves that row's price undefined ("—"). export async function listDomains(token) { const account = await whoami(token); const d = await api(token, "GET", `/v2/${account}/domains?per_page=100`); const rows = ((d && d.data) || []) .filter((r) => r && r.name) .map((r) => ({ name: r.name, state: r.state || "", auto_renew: !!r.auto_renew, expires_on: r.expires_on || (r.expires_at ? String(r.expires_at).slice(0, 10) : ""), // account id → the app can deep-link to the domain's page on dnsimple.com. account_id: r.account_id || account, })); await mapLimit(rows, 8, async (row) => { try { const p = await api(token, "GET", `/v2/${account}/registrar/domains/${encodeURIComponent(row.name)}/prices`); const price = p && p.data && (p.data.renewal_price ?? p.data.registration_price); if (price != null) row.price = Number(price); } catch { /* pricing is best-effort — leave undefined */ } }); return rows; } const DOMAIN_RE = /^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/i; // checkAvailability is the read-only call `/register` makes first: is the domain // free to register, and is it premium-priced? No money moves. // GET /v2/{account}/registrar/domains/{domain}/check export async function checkAvailability(domain, token) { if (!DOMAIN_RE.test(domain || "")) throw new Error(`"${domain}" doesn't look like a domain name`); const account = await whoami(token); const d = await api(token, "GET", `/v2/${account}/registrar/domains/${encodeURIComponent(domain.toLowerCase())}/check`); const info = (d && d.data) || {}; return { domain: info.domain || domain, available: !!info.available, premium: !!info.premium }; } // registerDomain is the money-spending, irreversible step. It is deliberately // NOT called by the availability check — a real registration is confirmed by the // member tapping the "Register" chip (see docs/connected-services.md: irreversible // actions confirm in place, never as a command side effect). Wired here so the // shape is visible; the runtime does not auto-invoke it. // POST /v2/{account}/registrar/domains/{domain}/registrations { registrant_id } export async function registerDomain(domain, token, { registrantId } = {}) { if (!DOMAIN_RE.test(domain || "")) throw new Error(`"${domain}" doesn't look like a domain name`); if (!registrantId) throw new Error("registration needs a registrant contact id (registrantId)"); const account = await whoami(token); const r = await fetch( `${BASE}/v2/${account}/registrar/domains/${encodeURIComponent(domain.toLowerCase())}/registrations`, { method: "POST", headers: { Authorization: `Bearer ${token}`, Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ registrant_id: registrantId }), }, ); const d = await r.json().catch(() => ({})); if (!r.ok) throw new Error(d && d.message ? d.message : `DNSimple ${r.status}`); return { id: d && d.data && d.data.id, state: (d && d.data && d.data.state) || "requested" }; }