Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(domains): add a Google Cloud Domains client and a script that rebuilds the priced TLD list from the live registrar
nirholas609b189012a5
diff --git a/api/_lib/cloud-domains.js b/api/_lib/cloud-domains.jsnew file mode 100644index 000000000..86064fd76--- /dev/null+++ b/api/_lib/cloud-domains.js@@ -0,0 +1,197 @@+// Google Cloud Domains (domains.googleapis.com) client: the registrar behind the+// domain_* MCP tools and /api/domains.+//+// Authenticated as the Cloud Run runtime service account through+// getGcpAccessToken (gcp-auth.js). Every call is a real request to the API;+// nothing here is cached or faked. Callers that want caching wrap these (see+// domains-service.js).+//+// What the API can and cannot do, measured against the live service 2026-10-10:+// - searchDomains?query=<name> suggests names across TLDs, availability is+// approximate and the price is the yearly price.+// - retrieveRegisterParameters?domainName=<fqdn> exact availability, yearly+// price, supported privacy modes and the notices a registration must+// acknowledge. An unsupported TLD answers UNSUPPORTED.+// - register creates the registration (a long-running operation). With+// validateOnly:true it validates price, availability and contacts and+// registers nothing. Registration is for ONE year; the same yearly price is+// the renewal price.+// - There is no endpoint that lists supported TLDs. data/domain-tlds.json is+// probed against retrieveRegisterParameters by scripts/refresh-domain-tlds.mjs.++import { getGcpAccessToken } from './gcp-auth.js';+import { fetchUpstream } from './upstream-fetch.js';++const API = 'https://domains.googleapis.com/v1';++export const GCP_PROJECT = process.env.GOOGLE_CLOUD_PROJECT || 'aerial-vehicle-466722-p5';++// Domain work runs as its own service account, never as the identity the rest+// of the API uses. That account can register domains (which bills the project)+// and edit DNS and certificates, so it holds nothing else, and no key for it+// exists: the API's own credential impersonates it through IAM Credentials+// (roles/iam.serviceAccountTokenCreator on this account only).+export const DOMAINS_SERVICE_ACCOUNT =+ process.env.DOMAINS_SERVICE_ACCOUNT || `three-ws-domains@${GCP_PROJECT}.iam.gserviceaccount.com`;++const _token = { value: null, expiresAt: 0 };++/**+ * Access token for the domains service account. `DOMAINS_ACCESS_TOKEN` is an+ * operator override for scripts run from a workstation+ * (`DOMAINS_ACCESS_TOKEN=$(gcloud auth print-access-token)`); the server never+ * sets it.+ */+export async function getDomainsAccessToken() {+ if (process.env.DOMAINS_ACCESS_TOKEN) return process.env.DOMAINS_ACCESS_TOKEN;+ if (_token.value && Date.now() < _token.expiresAt) return _token.value;+ const base = await getGcpAccessToken();+ const res = await fetchUpstream(+ `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${DOMAINS_SERVICE_ACCOUNT}:generateAccessToken`,+ {+ method: 'POST',+ headers: { Authorization: `Bearer ${base}`, 'content-type': 'application/json' },+ body: JSON.stringify({ scope: ['https://www.googleapis.com/auth/cloud-platform'], lifetime: '3600s' }),+ },+ { name: 'gcp-iam-credentials', timeoutMs: 10_000, attempts: 2, okWhen: (r) => r.ok || r.status === 403 },+ ).catch((err) => {+ throw new CloudDomainsError(`Could not reach IAM Credentials: ${err?.message || 'network error'}`, { status: 502, code: 'domains_upstream_error' });+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok || !body.accessToken) {+ throw new CloudDomainsError(+ `The API credential may not impersonate ${DOMAINS_SERVICE_ACCOUNT}: ${body?.error?.message || res.status}`,+ { status: 503, code: 'domains_permission_denied' },+ );+ }+ _token.value = body.accessToken;+ _token.expiresAt = new Date(body.expireTime).getTime() - 5 * 60_000;+ return _token.value;+}+const LOCATION = `projects/${GCP_PROJECT}/locations/global`;++export class CloudDomainsError extends Error {+ constructor(message, { status = 502, code = 'domains_upstream_error', detail } = {}) {+ super(message);+ this.name = 'CloudDomainsError';+ this.status = status;+ this.code = code;+ if (detail !== undefined) this.detail = detail;+ }+}++/** Google's Money type ({ units: "12", nanos: 500000000 }) to a number of dollars. */+export function moneyToNumber(money) {+ if (!money) return null;+ return Number(money.units || 0) + Number(money.nanos || 0) / 1e9;+}++/** Dollars to Google's Money type. Two-decimal precision is all the registrar accepts. */+export function numberToMoney(amount, currencyCode = 'USD') {+ const cents = Math.round(Number(amount) * 100);+ const units = Math.trunc(cents / 100);+ const nanos = (cents - units * 100) * 10_000_000;+ return { currencyCode, units: String(units), ...(nanos ? { nanos } : {}) };+}++function mapUpstreamError(status, body) {+ const message = body?.error?.message || `Cloud Domains answered ${status}`;+ if (status === 400) return new CloudDomainsError(message, { status: 400, code: 'domains_invalid_request', detail: body?.error?.details });+ if (status === 403) {+ return new CloudDomainsError(+ `The platform service account lacks Cloud Domains permission: ${message}`,+ { status: 503, code: 'domains_permission_denied' },+ );+ }+ if (status === 404) return new CloudDomainsError(message, { status: 404, code: 'domains_not_found' });+ if (status === 409) return new CloudDomainsError(message, { status: 409, code: 'domains_conflict' });+ if (status === 429) return new CloudDomainsError('Cloud Domains is rate limiting requests. Retry shortly.', { status: 429, code: 'domains_rate_limited' });+ return new CloudDomainsError(message, { status: 502, code: 'domains_upstream_error' });+}++async function call(path, { method = 'GET', body, query } = {}) {+ const token = await getDomainsAccessToken();+ const url = new URL(`${API}/${path}`);+ for (const [k, v] of Object.entries(query || {})) if (v != null) url.searchParams.set(k, String(v));+ const init = {+ method,+ headers: {+ Authorization: `Bearer ${token}`,+ 'x-goog-user-project': GCP_PROJECT,+ ...(body ? { 'content-type': 'application/json' } : {}),+ },+ ...(body ? { body: JSON.stringify(body) } : {}),+ };+ // A write is never retried: a register that timed out may still have+ // succeeded, and the caller resolves that through the idempotency key.+ // A 4xx other than 429 is the API's answer about this request, so it comes+ // back as a response to map; 429 and 5xx are transient and are retried.+ const res = await fetchUpstream(url, init, {+ name: 'cloud-domains',+ timeoutMs: 20_000,+ attempts: method === 'GET' ? 3 : 1,+ okWhen: (r) => r.ok || (r.status >= 400 && r.status < 500 && r.status !== 429),+ }).catch((err) => {+ if (err?.status === 429) throw mapUpstreamError(429, null);+ throw new CloudDomainsError(`Cloud Domains is unavailable: ${err?.message || 'network error'}`, { status: 502, code: 'domains_upstream_error' });+ });+ const text = await res.text();+ let parsed = null;+ try {+ parsed = text ? JSON.parse(text) : null;+ } catch {+ parsed = null;+ }+ if (!res.ok) throw mapUpstreamError(res.status, parsed);+ return parsed;+}++/** Suggested names across TLDs for a query string. */+export async function searchDomains(query) {+ const out = await call(`${LOCATION}/registrations:searchDomains`, { query: { query } });+ return out?.registerParameters || [];+}++/** Exact availability + price + privacy + notices for one fully-qualified name. */+export async function retrieveRegisterParameters(domainName) {+ const out = await call(`${LOCATION}/registrations:retrieveRegisterParameters`, { query: { domainName } });+ return out?.registerParameters || null;+}++/**+ * Register a domain. `validateOnly: true` runs every server-side check and+ * registers nothing; the real call returns a long-running operation to poll.+ */+export async function registerDomain({ registration, yearlyPrice, domainNotices = [], contactNotices = [], validateOnly = false }) {+ return call(`${LOCATION}/registrations:register`, {+ method: 'POST',+ body: { registration, yearlyPrice, domainNotices, contactNotices, validateOnly },+ });+}++/** A long-running operation by full name (projects/.../operations/...). */+export async function getOperation(name) {+ return call(name);+}++/** The registration resource for a domain, or null when it does not exist. */+export async function getRegistration(domainName) {+ try {+ return await call(`${LOCATION}/registrations/${domainName}`);+ } catch (err) {+ if (err.code === 'domains_not_found') return null;+ throw err;+ }+}++/** Point a registration at custom nameservers (the Cloud DNS zone's). */+export async function configureCustomDns(domainName, nameServers, { validateOnly = false } = {}) {+ return call(`${LOCATION}/registrations/${domainName}:configureDnsSettings`, {+ method: 'POST',+ body: {+ dnsSettings: { customDns: { nameServers } },+ updateMask: 'customDns',+ validateOnly,+ },+ });+}diff --git a/scripts/refresh-domain-tlds.mjs b/scripts/refresh-domain-tlds.mjsnew file mode 100644index 000000000..b1901b545--- /dev/null+++ b/scripts/refresh-domain-tlds.mjs@@ -0,0 +1,93 @@+#!/usr/bin/env node+// Rebuilds data/domain-tlds.json, the list of TLDs the domain_* tools price.+//+// Cloud Domains has no "list supported TLDs" endpoint, so this probes a+// candidate list (every TLD Google documents plus common requests) against+// retrieveRegisterParameters with a throwaway label. A TLD the registrar does+// not sell answers UNSUPPORTED and is dropped; the rest are written with their+// live yearly price, supported privacy modes and required notices.+//+// node scripts/refresh-domain-tlds.mjs write data/domain-tlds.json+// node scripts/refresh-domain-tlds.mjs --dry-run print, write nothing+//+// Credentials: the same chain as the API (GCP_SERVICE_ACCOUNT_JSON, metadata+// server, or `gcloud auth application-default login`).++import { writeFileSync } from 'node:fs';+import { retrieveRegisterParameters, moneyToNumber } from '../api/_lib/cloud-domains.js';++const CANDIDATES = `com net org info biz name mobi pro tel asia xyz online site store tech cloud app dev page art shop club live+life studio media agency academy accountant actor adult africa ai airforce army attorney auction audio auto band bar bargains+beer best bet bid bike bio black blog blue boutique build builders business buzz cab cafe camera camp capital car cards care+career careers cash casino catering center ceo charity chat cheap church city claims cleaning click clinic clothing coach codes+coffee community company computer condos construction consulting contact contractors cool coupons credit creditcard cricket+cruises dance date dating deals degree delivery democrat dental dentist design diamonds digital direct directory discount+doctor dog domains earth education email energy engineer engineering enterprises equipment estate events exchange expert+exposed express fail faith family fan fans farm fashion film finance financial fish fishing fit fitness flights florist flowers+football forsale foundation fun fund furniture futbol fyi gallery game games garden gift gifts gives glass global gmbh gold+golf graphics gratis green gripe group guide guitars guru haus health healthcare help hockey holdings holiday home horse+hospital host house how icu immo immobilien inc industries ink institute insure international investments io irish jewelry+juegos kaufen kim kitchen kiwi land lawyer lease legal lgbt lighting limited limo link live loan loans lol love ltd luxury+maison management market marketing mba media memorial men menu moda moe money mortgage movie navy network new news ninja+nyc one onl organic page partners parts party pet photo photography photos pics pictures pink pizza place plumbing plus+poker porn press productions promo properties property pub quest racing recipes red rehab reise reisen rent rentals repair+report republican rest restaurant review reviews rich rip rocks rodeo run sale salon sarl school schule science security+services sex sexy shiksha shoes show singles site ski soccer social software solar solutions soy space sport store stream+studio study style sucks supplies supply support surf surgery systems tax taxi team tech technology tennis theater tips+tires today tools top tours town toys trade trading training tube university uno vacations vegas ventures vet viajes video+villas vin vip vision vodka vote voting voto voyage wang watch webcam website wedding wiki win wine work works world wtf+xyz yoga zone co us uk de fr es it nl be ch at se no dk fi pl cz pt ie eu ca au nz jp in br mx ar cl`.split(/\s+/);++const dryRun = process.argv.includes('--dry-run');+const unique = [...new Set(CANDIDATES)];+const label = 'threews-tld-probe';+const rows = [];+const skipped = [];++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// retrieveRegisterParameters is quota-limited per minute. Probe serially and,+// when the API answers 429, wait out the window instead of failing the run.+async function lookup(tld) {+ for (let attempt = 0; attempt < 6; attempt++) {+ try {+ return await retrieveRegisterParameters(`${label}.${tld}`);+ } catch (err) {+ if (err.code !== 'domains_rate_limited') throw err;+ await sleep(20_000);+ }+ }+ throw new Error(`still rate limited probing .${tld}`);+}++async function probe(tld) {+ try {+ const p = await lookup(tld);+ if (!p || p.availability === 'UNSUPPORTED') return skipped.push(tld);+ rows.push({+ tld,+ yearlyUsd: moneyToNumber(p.yearlyPrice),+ currency: p.yearlyPrice?.currencyCode || 'USD',+ privacy: p.supportedPrivacy || [],+ notices: p.domainNotices || [],+ });+ } catch (err) {+ if (err.code === 'domains_invalid_request') return skipped.push(tld);+ throw err;+ }+}++const queue = [...unique];+while (queue.length) {+ await probe(queue.shift());+ await sleep(400);+}++rows.sort((a, b) => a.tld.localeCompare(b.tld));+const out = { generatedAt: new Date().toISOString(), probed: unique.length, supported: rows.length, tlds: rows };+console.log(`probed ${unique.length}, supported ${rows.length}, unsupported ${skipped.length}`);+if (dryRun) console.log(JSON.stringify(out.tlds.slice(0, 10), null, 2));+else {+ writeFileSync(new URL('../data/domain-tlds.json', import.meta.url), JSON.stringify(out, null, '\t') + '\n');+ console.log('wrote data/domain-tlds.json');+}