@nodegx/backend 0.0.0-stage → 0.1.1
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.
- package/LICENSE +674 -0
- package/README.md +56 -2
- package/bin/nodegx-online.js +123 -0
- package/dist/cloud-bundle.cjs +154357 -0
- package/dist/cloudflare-deploy.cjs +5642 -0
- package/dist/cloudflare-domain.cjs +504 -0
- package/dist/package.json +6 -0
- package/dist/worker/LICENSE +21 -0
- package/dist/worker/worker.mjs +109100 -0
- package/package.json +38 -4
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// ../nodegx-backend/cloudflare/domainCommand.ts
|
|
31
|
+
var domainCommand_exports = {};
|
|
32
|
+
__export(domainCommand_exports, {
|
|
33
|
+
accountOf: () => accountOf,
|
|
34
|
+
cfCaller: () => cfCaller,
|
|
35
|
+
cfLoginFiles: () => cfLoginFiles,
|
|
36
|
+
cfLoginToken: () => cfLoginToken,
|
|
37
|
+
domainCredential: () => domainCredential,
|
|
38
|
+
main: () => main,
|
|
39
|
+
parseArgs: () => parseArgs,
|
|
40
|
+
readToken: () => readToken,
|
|
41
|
+
run: () => run
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(domainCommand_exports);
|
|
44
|
+
var import_node_child_process = require("node:child_process");
|
|
45
|
+
var fs2 = __toESM(require("node:fs"));
|
|
46
|
+
var os2 = __toESM(require("node:os"));
|
|
47
|
+
var path2 = __toESM(require("node:path"));
|
|
48
|
+
|
|
49
|
+
// ../nodegx-backend/cloudflare/signIn.ts
|
|
50
|
+
var crypto = __toESM(require("crypto"));
|
|
51
|
+
var fs = __toESM(require("fs"));
|
|
52
|
+
var os = __toESM(require("os"));
|
|
53
|
+
var path = __toESM(require("path"));
|
|
54
|
+
var CLOUDFLARE_TOKEN_URL = "https://dash.cloudflare.com/oauth2/token";
|
|
55
|
+
var LOCK_WAIT_MS = 15e3;
|
|
56
|
+
var LOCK_STALE_MS = 3e4;
|
|
57
|
+
var EXPIRY_MARGIN_MS = 6e4;
|
|
58
|
+
var DEFAULT_TIMEOUT_MS = 10 * 6e4;
|
|
59
|
+
var SignInError = class extends Error {
|
|
60
|
+
constructor(message, code) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.code = code;
|
|
63
|
+
this.name = "SignInError";
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
function cloudflareHome() {
|
|
67
|
+
return process.env.NODEGX_CLOUDFLARE_HOME || path.join(os.homedir(), ".nodegx", "cloudflare");
|
|
68
|
+
}
|
|
69
|
+
function signInFile() {
|
|
70
|
+
return path.join(cloudflareHome(), "sign-in.json");
|
|
71
|
+
}
|
|
72
|
+
function readSignIn(file = signInFile()) {
|
|
73
|
+
let raw;
|
|
74
|
+
try {
|
|
75
|
+
raw = fs.readFileSync(file, "utf8");
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const s = JSON.parse(raw);
|
|
81
|
+
return typeof s.accessToken === "string" && s.accessToken ? s : null;
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function writeSignIn(s, file = signInFile()) {
|
|
87
|
+
const dir = path.dirname(file);
|
|
88
|
+
fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
89
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
90
|
+
fs.writeFileSync(tmp, JSON.stringify(s, null, 2) + "\n", { mode: 384 });
|
|
91
|
+
fs.chmodSync(tmp, 384);
|
|
92
|
+
fs.renameSync(tmp, file);
|
|
93
|
+
}
|
|
94
|
+
var defaultFetch = (url, init) => fetch(url, init);
|
|
95
|
+
async function tokenRequest(form, o) {
|
|
96
|
+
const res = await (o.fetchImpl ?? defaultFetch)(o.tokenUrl ?? CLOUDFLARE_TOKEN_URL, {
|
|
97
|
+
method: "POST",
|
|
98
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
99
|
+
body: new URLSearchParams(form).toString()
|
|
100
|
+
});
|
|
101
|
+
let body = null;
|
|
102
|
+
try {
|
|
103
|
+
body = await res.json();
|
|
104
|
+
} catch {
|
|
105
|
+
}
|
|
106
|
+
if (!res.ok || !body?.access_token) {
|
|
107
|
+
const why = String(body?.error_description || body?.error || `HTTP ${res.status}`).slice(0, 300);
|
|
108
|
+
const err = new SignInError(`Cloudflare did not hand over the sign-in: ${why}`, "failed");
|
|
109
|
+
err.oauthError = body?.error;
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
return body;
|
|
113
|
+
}
|
|
114
|
+
function fromAnswer(a, clientId, asked, now, previous) {
|
|
115
|
+
return {
|
|
116
|
+
clientId,
|
|
117
|
+
accessToken: a.access_token,
|
|
118
|
+
refreshToken: a.refresh_token ?? previous?.refreshToken,
|
|
119
|
+
// No `expires_in` is read as one hour (Hydra's default) rather than as "forever".
|
|
120
|
+
expiresAt: new Date(now + (typeof a.expires_in === "number" ? a.expires_in : 3600) * 1e3).toISOString(),
|
|
121
|
+
scopes: a.scope ? a.scope.split(/\s+/).filter(Boolean) : previous?.scopes ?? [...asked],
|
|
122
|
+
signedInAt: previous?.signedInAt ?? new Date(now).toISOString(),
|
|
123
|
+
...previous ? { refreshedAt: new Date(now).toISOString() } : {}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
127
|
+
async function withLock(file, fn) {
|
|
128
|
+
const lock = `${file}.lock`;
|
|
129
|
+
const started = Date.now();
|
|
130
|
+
for (; ; ) {
|
|
131
|
+
try {
|
|
132
|
+
const fd = fs.openSync(lock, "wx", 384);
|
|
133
|
+
fs.closeSync(fd);
|
|
134
|
+
break;
|
|
135
|
+
} catch (e) {
|
|
136
|
+
if (e.code !== "EEXIST") throw e;
|
|
137
|
+
try {
|
|
138
|
+
if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.rmSync(lock, { force: true });
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
if (Date.now() - started > LOCK_WAIT_MS) {
|
|
142
|
+
throw new SignInError("Another part of NodeGX is renewing the Cloudflare sign-in and has not finished. Try again in a moment.", "failed");
|
|
143
|
+
}
|
|
144
|
+
await sleep(100);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
return await fn();
|
|
149
|
+
} finally {
|
|
150
|
+
fs.rmSync(lock, { force: true });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
var expiredSentence = () => new SignInError("Your Cloudflare sign-in has run out. Ask Claude to sign in to Cloudflare again (one page, one click).", "expired");
|
|
154
|
+
async function cloudflareAccessToken(o = {}) {
|
|
155
|
+
const file = o.file ?? signInFile();
|
|
156
|
+
const now = o.now ?? Date.now;
|
|
157
|
+
const first = readSignIn(file);
|
|
158
|
+
const began = now();
|
|
159
|
+
const fresh = (s) => o.force ? !!s.refreshedAt && Date.parse(s.refreshedAt) >= began && s !== first : Date.parse(s.expiresAt) - EXPIRY_MARGIN_MS > now();
|
|
160
|
+
if (!first) return null;
|
|
161
|
+
if (fresh(first)) return first.accessToken;
|
|
162
|
+
if (!first.refreshToken) throw expiredSentence();
|
|
163
|
+
return withLock(file, async () => {
|
|
164
|
+
const s = readSignIn(file);
|
|
165
|
+
if (!s) return null;
|
|
166
|
+
if (fresh(s)) return s.accessToken;
|
|
167
|
+
if (!s.refreshToken) throw expiredSentence();
|
|
168
|
+
let a;
|
|
169
|
+
try {
|
|
170
|
+
a = await tokenRequest({ grant_type: "refresh_token", refresh_token: s.refreshToken, client_id: s.clientId }, o);
|
|
171
|
+
} catch (e) {
|
|
172
|
+
if (e.oauthError === "invalid_grant") {
|
|
173
|
+
fs.rmSync(file, { force: true });
|
|
174
|
+
throw expiredSentence();
|
|
175
|
+
}
|
|
176
|
+
throw e;
|
|
177
|
+
}
|
|
178
|
+
const next = fromAnswer(a, s.clientId, s.scopes, now(), s);
|
|
179
|
+
writeSignIn(next, file);
|
|
180
|
+
return next.accessToken;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ../nodegx-backend/cloudflare/registrar.ts
|
|
185
|
+
var RegistrarError = class extends Error {
|
|
186
|
+
};
|
|
187
|
+
function unwrap(answer, what) {
|
|
188
|
+
if (answer.status >= 300 || answer.json?.success === false) {
|
|
189
|
+
const errs = (answer.json?.errors ?? []).map((e) => `${e.code ?? ""} ${e.message ?? ""}`.trim());
|
|
190
|
+
throw new RegistrarError(`${what} answered ${answer.status}${errs.length ? `: ${errs.join("; ")}` : ""}`);
|
|
191
|
+
}
|
|
192
|
+
return answer.json?.result;
|
|
193
|
+
}
|
|
194
|
+
var base = (account) => `/accounts/${encodeURIComponent(account)}/registrar`;
|
|
195
|
+
async function searchDomains(call, account, q, limit = 20) {
|
|
196
|
+
const r = unwrap(await call("GET", `${base(account)}/domain-search?q=${encodeURIComponent(q)}&limit=${limit}`), "The domain search");
|
|
197
|
+
return r?.domains ?? [];
|
|
198
|
+
}
|
|
199
|
+
async function checkDomains(call, account, names) {
|
|
200
|
+
if (!names.length) return [];
|
|
201
|
+
if (names.length > 20) throw new RegistrarError("Cloudflare checks at most 20 names at a time.");
|
|
202
|
+
const r = unwrap(await call("POST", `${base(account)}/domain-check`, { domains: names }), "The domain check");
|
|
203
|
+
return r?.domains ?? [];
|
|
204
|
+
}
|
|
205
|
+
function confirmationFor(offer) {
|
|
206
|
+
return `${offer.name} ${offer.pricing.registration_cost} ${offer.pricing.currency}`;
|
|
207
|
+
}
|
|
208
|
+
var REASONS = {
|
|
209
|
+
domain_unavailable: "it is already registered by someone",
|
|
210
|
+
extension_not_supported_via_api: "Cloudflare's API cannot register this ending yet (its beta covers some endings); it can be bought in the dashboard, or try another ending",
|
|
211
|
+
extension_not_supported: "Cloudflare does not sell this ending",
|
|
212
|
+
extension_disallows_registration: "this ending does not allow registration",
|
|
213
|
+
domain_premium: "it is a premium name, which Cloudflare's API does not sell (the dashboard may)"
|
|
214
|
+
};
|
|
215
|
+
function offerLine(o) {
|
|
216
|
+
if (!o.registrable) return `${o.name}: not available (${REASONS[o.reason ?? ""] ?? o.reason ?? "no reason given"})`;
|
|
217
|
+
const p = o.pricing;
|
|
218
|
+
return `${o.name}: available, ${p ? `${p.registration_cost} ${p.currency} the first year, then ${p.renewal_cost} ${p.currency} a year` : "price not given"}${o.tier && o.tier !== "standard" ? ` (${o.tier})` : ""}`;
|
|
219
|
+
}
|
|
220
|
+
function buyProblem(name, fresh, confirm) {
|
|
221
|
+
if (!fresh) return `Cloudflare did not answer for ${name}: nothing was bought.`;
|
|
222
|
+
if (!fresh.registrable) return `${offerLine(fresh)}. Nothing was bought.`;
|
|
223
|
+
if (!fresh.pricing) return `Cloudflare gave no price for ${name}: nothing was bought.`;
|
|
224
|
+
if (fresh.tier === "premium") return `${name} is a premium name, which Cloudflare's API does not sell: nothing was bought.`;
|
|
225
|
+
const expected = confirmationFor(fresh);
|
|
226
|
+
if (!confirm) {
|
|
227
|
+
return `${offerLine(fresh)}.
|
|
228
|
+
To buy it, the person must say yes to exactly this, and the command is run again with --confirm "${expected}". It is charged to the account's default card and cannot be refunded.`;
|
|
229
|
+
}
|
|
230
|
+
if (confirm.trim().replace(/\s+/g, " ") !== expected) {
|
|
231
|
+
return `The confirmation "${confirm}" is not today's offer "${expected}" (the price or the name differ). Show the person the new offer; nothing was bought.`;
|
|
232
|
+
}
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
async function registerDomain(call, account, name, options) {
|
|
236
|
+
const r = unwrap(await call("POST", `${base(account)}/registrations`, { domain_name: name, auto_renew: options.autoRenew }), "The registration");
|
|
237
|
+
return { ...r, domain_name: r?.domain_name ?? r?.context?.registration?.domain_name ?? name, state: r?.state ?? (r?.completed ? "succeeded" : "in_progress") };
|
|
238
|
+
}
|
|
239
|
+
async function getRegistration(call, account, name) {
|
|
240
|
+
return unwrap(await call("GET", `${base(account)}/registrations/${encodeURIComponent(name)}`), "The registration record");
|
|
241
|
+
}
|
|
242
|
+
async function registrationStatus(call, account, name) {
|
|
243
|
+
return unwrap(await call("GET", `${base(account)}/registrations/${encodeURIComponent(name)}/registration-status`), "The registration status");
|
|
244
|
+
}
|
|
245
|
+
async function waitForRegistration(call, account, first, options = {}) {
|
|
246
|
+
const sleep2 = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
247
|
+
let reg = first;
|
|
248
|
+
const until = Date.now() + (options.forMs ?? 12e4);
|
|
249
|
+
while (reg.state === "in_progress" && Date.now() < until) {
|
|
250
|
+
await sleep2(options.everyMs ?? 2e3);
|
|
251
|
+
reg = await registrationStatus(call, account, first.domain_name);
|
|
252
|
+
}
|
|
253
|
+
return reg;
|
|
254
|
+
}
|
|
255
|
+
function registrationSentence(reg) {
|
|
256
|
+
switch (reg.state) {
|
|
257
|
+
case "succeeded": {
|
|
258
|
+
const exp = reg.context?.registration?.expires_at?.slice(0, 10);
|
|
259
|
+
const renew = reg.context?.registration?.auto_renew;
|
|
260
|
+
return `${reg.domain_name} is yours${exp ? ` until ${exp}` : ""}${renew === true ? ", renewed automatically each year" : renew === false ? " (it does NOT renew by itself: turn on auto-renew in the dashboard, or it stops working when it expires)" : ""}.`;
|
|
261
|
+
}
|
|
262
|
+
case "in_progress":
|
|
263
|
+
return `${reg.domain_name} is still being registered: ask again in a minute (status ${reg.domain_name}).`;
|
|
264
|
+
case "action_required":
|
|
265
|
+
return `Cloudflare needs something from the person before ${reg.domain_name} is theirs: ${reg.error?.message ?? "see Domain Registration in the dashboard"}.`;
|
|
266
|
+
default:
|
|
267
|
+
return `${reg.domain_name} was not registered (${reg.state}${reg.error ? `: ${reg.error.code ?? ""} ${reg.error.message ?? ""}`.trimEnd() : ""}).`;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ../nodegx-backend/cloudflare/wranglerConfig.ts
|
|
272
|
+
function emailProblem(what, address) {
|
|
273
|
+
return /^[^\s@<>"]+@[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(address) ? null : `${what} "${address}" is not an email address (write it bare, like alerts@example.com).`;
|
|
274
|
+
}
|
|
275
|
+
function domainProblem(domain) {
|
|
276
|
+
const label = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
|
|
277
|
+
if (domain.length > 253 || !new RegExp(`^(?:${label}\\.)+[a-z]{2,63}$`).test(domain)) {
|
|
278
|
+
return `"${domain}" cannot be a domain for the app: write the bare name, lowercase, like campus.example.com (no https://, no path, no *).`;
|
|
279
|
+
}
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ../nodegx-backend/cloudflare/domainCommand.ts
|
|
284
|
+
var say = (line = "") => process.stdout.write(line + "\n");
|
|
285
|
+
var CommandError = class extends Error {
|
|
286
|
+
};
|
|
287
|
+
var USAGE = `usage: domain.mjs find <idea words\u2026>
|
|
288
|
+
domain.mjs check <name\u2026>
|
|
289
|
+
domain.mjs buy <name> [--confirm "<name> <cost> <currency>"] [--no-auto-renew]
|
|
290
|
+
domain.mjs status <name>
|
|
291
|
+
domain.mjs email <domain> [--to <address>]
|
|
292
|
+
options: --account <id>`;
|
|
293
|
+
function home() {
|
|
294
|
+
return process.env.NODEGX_CLOUDFLARE_HOME || path2.join(os2.homedir(), ".nodegx", "cloudflare");
|
|
295
|
+
}
|
|
296
|
+
function cfLoginFiles() {
|
|
297
|
+
const h = os2.homedir();
|
|
298
|
+
return [
|
|
299
|
+
process.env.NODEGX_CF_LOGIN_FILE,
|
|
300
|
+
path2.join(h, "Library", "Preferences", "cloudflare", "config", "default.json"),
|
|
301
|
+
process.env.XDG_CONFIG_HOME ? path2.join(process.env.XDG_CONFIG_HOME, "cloudflare", "config", "default.json") : void 0,
|
|
302
|
+
path2.join(h, ".config", "cloudflare", "config", "default.json"),
|
|
303
|
+
process.env.APPDATA ? path2.join(process.env.APPDATA, "cloudflare", "config", "default.json") : void 0
|
|
304
|
+
].filter((p) => !!p);
|
|
305
|
+
}
|
|
306
|
+
function readCfLogin() {
|
|
307
|
+
for (const file of cfLoginFiles()) {
|
|
308
|
+
if (!fs2.existsSync(file)) continue;
|
|
309
|
+
try {
|
|
310
|
+
return { file, login: JSON.parse(fs2.readFileSync(file, "utf8")) };
|
|
311
|
+
} catch {
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
function cfLoginToken(now = Date.now(), refresh = () => void (0, import_node_child_process.spawnSync)("cf", ["auth", "whoami", "--quiet"], { encoding: "utf8", timeout: 6e4 })) {
|
|
317
|
+
let found = readCfLogin();
|
|
318
|
+
if (!found?.login.oauth_token) return null;
|
|
319
|
+
const expired = (l) => !l.expiration_time || Date.parse(l.expiration_time) - 6e4 < now;
|
|
320
|
+
if (expired(found.login)) {
|
|
321
|
+
refresh();
|
|
322
|
+
found = readCfLogin();
|
|
323
|
+
if (!found?.login.oauth_token || expired(found.login)) {
|
|
324
|
+
throw new CommandError("Your Cloudflare sign-in has expired: run `cf auth login` (a browser sign-in), then ask again.");
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const scopes = found.login.scopes ?? [];
|
|
328
|
+
if (scopes.length && !scopes.some((s) => s === "registrar:write" || s === "registrar-domains.admin")) {
|
|
329
|
+
throw new CommandError("Your Cloudflare sign-in does not allow buying domains: run `cf auth login --force` and allow Registrar.");
|
|
330
|
+
}
|
|
331
|
+
return found.login.oauth_token;
|
|
332
|
+
}
|
|
333
|
+
function readToken() {
|
|
334
|
+
if (process.env.CLOUDFLARE_API_TOKEN) return process.env.CLOUDFLARE_API_TOKEN.trim();
|
|
335
|
+
const signedIn = cfLoginToken();
|
|
336
|
+
if (signedIn) return signedIn;
|
|
337
|
+
const file = path2.join(home(), "registrar-token");
|
|
338
|
+
if (fs2.existsSync(file)) {
|
|
339
|
+
const mode = fs2.statSync(file).mode & 63;
|
|
340
|
+
if (mode) throw new CommandError(`${file} can be read by other users of this computer: run \`chmod 600 ${file}\` first.`);
|
|
341
|
+
return fs2.readFileSync(file, "utf8").trim();
|
|
342
|
+
}
|
|
343
|
+
throw new CommandError(
|
|
344
|
+
`Finding and buying a domain needs you signed in to Cloudflare once: \`npm i -g cf\`, then \`cf auth login\` (a browser
|
|
345
|
+
sign-in; no key to make or save). The account also needs a default card (Billing) and a default registrant contact
|
|
346
|
+
(Domain Registration), once. (An API token with Registrar \xB7 Edit in ${file}, chmod 600, works too.)`
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
async function domainCredential() {
|
|
350
|
+
if (process.env.CLOUDFLARE_API_TOKEN) return process.env.CLOUDFLARE_API_TOKEN.trim();
|
|
351
|
+
const ours = readSignIn();
|
|
352
|
+
if (ours && ours.scopes.includes("registrar-domains.admin")) {
|
|
353
|
+
const token = await cloudflareAccessToken();
|
|
354
|
+
if (token) return token;
|
|
355
|
+
}
|
|
356
|
+
return readToken();
|
|
357
|
+
}
|
|
358
|
+
function cfCaller(token, apiBase = process.env.NODEGX_CF_API || "https://api.cloudflare.com/client/v4") {
|
|
359
|
+
return async (method, p, body, headers = {}) => {
|
|
360
|
+
const res = await fetch(apiBase + p, {
|
|
361
|
+
method,
|
|
362
|
+
headers: { authorization: `Bearer ${token}`, ...body === void 0 ? {} : { "content-type": "application/json" }, ...headers },
|
|
363
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
364
|
+
});
|
|
365
|
+
let json = null;
|
|
366
|
+
try {
|
|
367
|
+
json = await res.json();
|
|
368
|
+
} catch {
|
|
369
|
+
}
|
|
370
|
+
return { status: res.status, json };
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
async function accountOf(call, given) {
|
|
374
|
+
if (given) return given;
|
|
375
|
+
if (process.env.CLOUDFLARE_ACCOUNT_ID) return process.env.CLOUDFLARE_ACCOUNT_ID;
|
|
376
|
+
const r = await call("GET", "/accounts?per_page=50");
|
|
377
|
+
const accounts = r.json?.result ?? [];
|
|
378
|
+
if (r.status >= 300 || !accounts.length) throw new CommandError(`The token sees no Cloudflare account (${r.status}): give it Account \xB7 Account Settings \xB7 Read, or pass --account <id>.`);
|
|
379
|
+
if (accounts.length > 1) throw new CommandError(`The token sees ${accounts.length} accounts; choose one with --account:
|
|
380
|
+
${accounts.map((a) => ` ${a.id} ${a.name}`).join("\n")}`);
|
|
381
|
+
return accounts[0].id;
|
|
382
|
+
}
|
|
383
|
+
function wrangler(args) {
|
|
384
|
+
const pre = process.env.NODEGX_WRANGLER ? [process.execPath, process.env.NODEGX_WRANGLER] : ["npx", "--yes", "wrangler@4"];
|
|
385
|
+
const run2 = (0, import_node_child_process.spawnSync)(pre[0], [...pre.slice(1), ...args], { encoding: "utf8", env: { ...process.env, WRANGLER_SEND_METRICS: "false" } });
|
|
386
|
+
return { status: run2.status ?? 1, out: `${run2.stdout || ""}${run2.stderr || ""}`.trim() };
|
|
387
|
+
}
|
|
388
|
+
function remember(entry) {
|
|
389
|
+
const file = path2.join(home(), "domains.json");
|
|
390
|
+
fs2.mkdirSync(home(), { recursive: true });
|
|
391
|
+
const list = fs2.existsSync(file) ? JSON.parse(fs2.readFileSync(file, "utf8")) : [];
|
|
392
|
+
list.push(entry);
|
|
393
|
+
fs2.writeFileSync(file, JSON.stringify(list, null, 2) + "\n");
|
|
394
|
+
}
|
|
395
|
+
function parseArgs(argv) {
|
|
396
|
+
const [verb = "", ...tail] = argv;
|
|
397
|
+
const o = { verb, rest: [], autoRenew: true };
|
|
398
|
+
for (let i = 0; i < tail.length; i++) {
|
|
399
|
+
const a = tail[i];
|
|
400
|
+
const next = () => {
|
|
401
|
+
const v = tail[++i];
|
|
402
|
+
if (v === void 0) throw new CommandError(`${a} needs a value.
|
|
403
|
+
${USAGE}`);
|
|
404
|
+
return v;
|
|
405
|
+
};
|
|
406
|
+
if (a === "--confirm") o.confirm = next();
|
|
407
|
+
else if (a === "--no-auto-renew") o.autoRenew = false;
|
|
408
|
+
else if (a === "--account") o.account = next();
|
|
409
|
+
else if (a === "--to") o.to = next();
|
|
410
|
+
else if (a.startsWith("--")) throw new CommandError(`${a} is not an option.
|
|
411
|
+
${USAGE}`);
|
|
412
|
+
else o.rest.push(a);
|
|
413
|
+
}
|
|
414
|
+
if (!["find", "check", "buy", "status", "email"].includes(verb) || !o.rest.length) throw new CommandError(USAGE);
|
|
415
|
+
return o;
|
|
416
|
+
}
|
|
417
|
+
var bare = (n) => {
|
|
418
|
+
const name = n.trim().toLowerCase();
|
|
419
|
+
const bad = domainProblem(name);
|
|
420
|
+
if (bad) throw new CommandError(bad);
|
|
421
|
+
return name;
|
|
422
|
+
};
|
|
423
|
+
async function run(o, call) {
|
|
424
|
+
if (o.verb === "email") {
|
|
425
|
+
const domain = bare(o.rest[0]);
|
|
426
|
+
if (o.to && emailProblem("--to", o.to)) throw new CommandError(emailProblem("--to", o.to));
|
|
427
|
+
const sending = wrangler(["email", "sending", "enable", domain]);
|
|
428
|
+
say(sending.status === 0 || /already/i.test(sending.out) ? `Email sending is on for ${domain} (Cloudflare adds its records itself; 5\u201315 minutes).` : `Email sending could not be turned on for ${domain}:
|
|
429
|
+
${sending.out}`);
|
|
430
|
+
if (o.to) {
|
|
431
|
+
const addr = wrangler(["email", "routing", "addresses", "create", o.to]);
|
|
432
|
+
say(addr.status === 0 || /already/i.test(addr.out) ? `Cloudflare is emailing ${o.to} a link: the person clicks it once, and the app's alerts can reach them.` : `${o.to} could not be added:
|
|
433
|
+
${addr.out}`);
|
|
434
|
+
}
|
|
435
|
+
return sending.status === 0 ? 0 : 1;
|
|
436
|
+
}
|
|
437
|
+
const names = o.verb === "find" ? [] : o.rest.map(bare);
|
|
438
|
+
const c = call ?? cfCaller(await domainCredential());
|
|
439
|
+
const account = await accountOf(c, o.account);
|
|
440
|
+
if (o.verb === "find") {
|
|
441
|
+
const offers = await searchDomains(c, account, o.rest.join(" "));
|
|
442
|
+
if (!offers.length) say("Cloudflare suggested nothing for those words: try other words, or check names with `check`.");
|
|
443
|
+
for (const x of offers) say(offerLine(x));
|
|
444
|
+
say("\nIdeas only: `check` a name right before buying it.");
|
|
445
|
+
return 0;
|
|
446
|
+
}
|
|
447
|
+
if (o.verb === "check") {
|
|
448
|
+
for (const x of await checkDomains(c, account, names)) say(offerLine(x));
|
|
449
|
+
return 0;
|
|
450
|
+
}
|
|
451
|
+
if (o.verb === "status") {
|
|
452
|
+
say(registrationSentence(await registrationStatus(c, account, names[0])));
|
|
453
|
+
return 0;
|
|
454
|
+
}
|
|
455
|
+
const name = names[0];
|
|
456
|
+
const [fresh] = await checkDomains(c, account, [name]);
|
|
457
|
+
const problem = buyProblem(name, fresh, o.confirm);
|
|
458
|
+
if (problem) {
|
|
459
|
+
say(problem);
|
|
460
|
+
if (fresh?.registrable && fresh.pricing && !o.confirm) {
|
|
461
|
+
say(o.autoRenew ? `It renews automatically at ${fresh.pricing.renewal_cost} ${fresh.pricing.currency} a year (--no-auto-renew to turn that off).` : "It will NOT renew by itself.");
|
|
462
|
+
}
|
|
463
|
+
return o.confirm ? 1 : 0;
|
|
464
|
+
}
|
|
465
|
+
say(`Buying ${confirmationFor(fresh)} on the account's default card\u2026`);
|
|
466
|
+
const first = await registerDomain(c, account, name, { autoRenew: o.autoRenew });
|
|
467
|
+
let reg = await waitForRegistration(c, account, first);
|
|
468
|
+
if (reg.state === "succeeded") {
|
|
469
|
+
const held = await getRegistration(c, account, name).catch(() => null);
|
|
470
|
+
if (held) reg = { ...reg, context: { registration: { ...reg.context?.registration, expires_at: held.expires_at, auto_renew: held.auto_renew, status: held.status } } };
|
|
471
|
+
}
|
|
472
|
+
say(registrationSentence(reg));
|
|
473
|
+
remember({ name, at: (/* @__PURE__ */ new Date()).toISOString(), account, offer: fresh, state: reg.state, autoRenew: o.autoRenew });
|
|
474
|
+
if (reg.state === "succeeded") {
|
|
475
|
+
say(`
|
|
476
|
+
Next: \`domain.mjs email ${name} --to <your address>\`, then deploy with --domain <name or app.${name}> --alert-to \u2026 --alert-from alerts@${name}.`);
|
|
477
|
+
}
|
|
478
|
+
return reg.state === "succeeded" ? 0 : 1;
|
|
479
|
+
}
|
|
480
|
+
async function main(argv) {
|
|
481
|
+
try {
|
|
482
|
+
return await run(parseArgs(argv));
|
|
483
|
+
} catch (e) {
|
|
484
|
+
if (e instanceof CommandError || e instanceof RegistrarError) {
|
|
485
|
+
process.stderr.write(`
|
|
486
|
+
${e.message}
|
|
487
|
+
`);
|
|
488
|
+
return 1;
|
|
489
|
+
}
|
|
490
|
+
throw e;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
494
|
+
0 && (module.exports = {
|
|
495
|
+
accountOf,
|
|
496
|
+
cfCaller,
|
|
497
|
+
cfLoginFiles,
|
|
498
|
+
cfLoginToken,
|
|
499
|
+
domainCredential,
|
|
500
|
+
main,
|
|
501
|
+
parseArgs,
|
|
502
|
+
readToken,
|
|
503
|
+
run
|
|
504
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) The NodeGX contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
16
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
17
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
18
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
19
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
20
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
|
21
|
+
OR OTHER DEALINGS IN THE SOFTWARE.
|