freertc 0.1.32 → 0.5.0
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/README.md +204 -12
- package/bin/freertc.mjs +38 -633
- package/migrations/0001_initial.sql +43 -0
- package/migrations/0002_kademlia_overlay.sql +32 -0
- package/migrations/0003_announcement_role.sql +4 -0
- package/package.json +44 -17
- package/public/app.js +746 -169
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/index.html +200 -799
- package/public/pigeonlogo.svg +51 -0
- package/scripts/d1-schema.sql +36 -0
- package/scripts/deploy-cloudflare.mjs +190 -0
- package/scripts/dev-server.mjs +54 -7
- package/scripts/generate-relay-identity.mjs +14 -0
- package/scripts/name-setup.mjs +332 -0
- package/scripts/node-relay.mjs +1128 -0
- package/scripts/project-bootstrap.mjs +13 -6
- package/scripts/wrangler-install-wizard.mjs +21 -11
- package/src/client.js +3468 -0
- package/src/direct/cert.js +95 -0
- package/src/direct/common.js +187 -0
- package/src/direct/dial.js +47 -0
- package/src/direct/directory.js +230 -0
- package/src/direct/listener.js +201 -0
- package/src/direct/lookup.js +75 -0
- package/src/direct/names.js +150 -0
- package/src/direct/node-relay-direct.js +170 -0
- package/src/direct/portmap.js +214 -0
- package/src/direct/reachable.js +40 -0
- package/src/direct/record.js +188 -0
- package/src/index.js +1401 -199
- package/src/kademlia.js +133 -0
- package/src/node/account-sync.js +98 -0
- package/src/node/cost-meter.js +92 -0
- package/src/node/d1-sqlite.js +108 -0
- package/src/node/data-dir.js +66 -0
- package/src/node/durable-object.js +58 -0
- package/src/node/lan-beacon.js +55 -0
- package/src/node/link-crypto.js +99 -0
- package/src/node/relay-links.js +385 -0
- package/src/node/relay-name.js +193 -0
- package/src/node/relay-pq.js +68 -0
- package/src/node/relay-stats.js +276 -0
- package/src/node/stats-page.js +281 -0
- package/src/node/websocket-pair.js +117 -0
- package/src/punch/offer.js +143 -0
- package/src/punch/rendezvous.js +124 -0
- package/src/punch/transport.js +257 -0
- package/src/relay-fetch.js +131 -0
- package/src/relay-id.js +74 -0
- package/src/relay-identity.js +298 -0
- package/src/relay-overlay.js +857 -0
- package/src/tunnel/client.js +276 -0
- package/src/tunnel/frames.js +64 -0
- package/src/tunnel/home.js +271 -0
- package/wrangler.template.jsonc +34 -9
- package/wrangler.workers-dev.jsonc +20 -3
- package/scripts/non-cloudflare-server.mjs +0 -433
- package/scripts/postinstall-message.mjs +0 -133
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// npx freertc name [--domain example.com] [--worker <script name>]
|
|
3
|
+
//
|
|
4
|
+
// Gives the local relay on this machine a name and a certificate on your own
|
|
5
|
+
// domain, kept by your own FreeRTC Worker (src/direct/names.js,
|
|
6
|
+
// src/node/relay-name.js). Run it once on each machine that runs a relay:
|
|
7
|
+
//
|
|
8
|
+
// 1. Log in to Cloudflare with wrangler (a browser window, if not already).
|
|
9
|
+
// 2. Find your FreeRTC Worker (by its /health) and the domain (a zone in
|
|
10
|
+
// your account).
|
|
11
|
+
// 3. The first time for a domain: the Worker needs an API token that can
|
|
12
|
+
// only edit DNS on that domain. Wrangler's login cannot make tokens, so
|
|
13
|
+
// this opens Cloudflare's token page already filled in (DNS edit, that
|
|
14
|
+
// domain only): click Create Token, then Copy, and press Enter here (it is read from
|
|
15
|
+
// the clipboard, never shown or pasted in the terminal), once. It is
|
|
16
|
+
// checked, stored in the Worker (NAMES_DNS_TOKEN, NAMES_ZONE_ID,
|
|
17
|
+
// NAMES_DOMAIN) and never written on this machine.
|
|
18
|
+
// 4. Register this relay with the Worker: its node id goes in the Worker's
|
|
19
|
+
// database (table freertc_name_owners), so the Worker gives names only
|
|
20
|
+
// to your relays.
|
|
21
|
+
// 5. Write <data dir>/names.json; the relay picks it up when it next starts.
|
|
22
|
+
//
|
|
23
|
+
// Everything goes through Cloudflare's API with your login, so it works
|
|
24
|
+
// whether the Worker came from the Deploy button or from `npm run deploy`.
|
|
25
|
+
|
|
26
|
+
import { spawnSync } from 'node:child_process';
|
|
27
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
28
|
+
import path from 'node:path';
|
|
29
|
+
import readline from 'node:readline/promises';
|
|
30
|
+
import { pathToFileURL } from 'node:url';
|
|
31
|
+
import { generateRandomPair } from 'unsea';
|
|
32
|
+
import { createRelayIdentity, decodeRelayIdentitySecret, encodeRelayIdentitySecret } from '../src/relay-identity.js';
|
|
33
|
+
import { OWNERS_TABLE, relayHostname } from '../src/direct/names.js';
|
|
34
|
+
import { resolveProjectRoot } from './project-bootstrap.mjs';
|
|
35
|
+
|
|
36
|
+
const API = 'https://api.cloudflare.com/client/v4';
|
|
37
|
+
|
|
38
|
+
const ROOT = resolveProjectRoot(process.cwd());
|
|
39
|
+
const say = (line) => console.log(`[freertc name] ${line}`);
|
|
40
|
+
|
|
41
|
+
export function parseArgs(args) {
|
|
42
|
+
const out = { domain: null, worker: null };
|
|
43
|
+
for (let i = 0; i < args.length; i++) {
|
|
44
|
+
if (args[i] === '--domain') out.domain = args[++i];
|
|
45
|
+
else if (args[i].startsWith('--domain=')) out.domain = args[i].slice(9);
|
|
46
|
+
else if (args[i] === '--worker') out.worker = args[++i];
|
|
47
|
+
else if (args[i].startsWith('--worker=')) out.worker = args[i].slice(9);
|
|
48
|
+
}
|
|
49
|
+
if (out.domain) out.domain = out.domain.toLowerCase().replace(/\.$/, '');
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** This relay's identity: the same file the relay keeps (generated now if it has not run yet). */
|
|
54
|
+
export async function relayIdentity(dataDir) {
|
|
55
|
+
mkdirSync(dataDir, { recursive: true });
|
|
56
|
+
const file = path.join(dataDir, 'relay-identity.json');
|
|
57
|
+
let secret = process.env.RELAY_IDENTITY_SECRET || (existsSync(file) ? readFileSync(file, 'utf8').trim() : null);
|
|
58
|
+
if (!secret) {
|
|
59
|
+
const pair = await generateRandomPair();
|
|
60
|
+
secret = encodeRelayIdentitySecret(pair.pub, pair.priv);
|
|
61
|
+
writeFileSync(file, secret, { mode: 0o600 });
|
|
62
|
+
}
|
|
63
|
+
const { publicKey, privateKey } = decodeRelayIdentitySecret(secret);
|
|
64
|
+
return createRelayIdentity(publicKey, privateKey);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** `wrangler auth token` (reading the login's token) needs a recent wrangler: npx fetches it once. */
|
|
68
|
+
const LOGIN_WRANGLER = 'wrangler@4.156.0';
|
|
69
|
+
|
|
70
|
+
function wrangler(args, options = {}) {
|
|
71
|
+
const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
|
72
|
+
return spawnSync(npx, ['--yes', LOGIN_WRANGLER, ...args], { cwd: ROOT, encoding: 'utf8', env: process.env, shell: process.platform === 'win32', ...options });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The login's token, from `wrangler auth token --json` (printed over several lines). */
|
|
76
|
+
export function tokenFromOutput(stdout) {
|
|
77
|
+
const text = String(stdout || '');
|
|
78
|
+
const start = text.indexOf('{'), end = text.lastIndexOf('}');
|
|
79
|
+
if (start >= 0 && end > start) {
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(text.slice(start, end + 1));
|
|
82
|
+
if (typeof parsed?.token === 'string' && parsed.token) return parsed.token;
|
|
83
|
+
} catch { /* not JSON */ }
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function oauthToken() {
|
|
89
|
+
const json = wrangler(['auth', 'token', '--json'], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
90
|
+
const token = tokenFromOutput(json.stdout);
|
|
91
|
+
if (token) return token;
|
|
92
|
+
// Without --json it prints just the token, on its own line.
|
|
93
|
+
const plain = wrangler(['auth', 'token'], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
94
|
+
const line = String(plain.stdout || '').trim().split('\n').map((l) => l.trim()).filter(Boolean).pop() || '';
|
|
95
|
+
return /^[A-Za-z0-9._-]{20,}$/.test(line) ? line : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function login() {
|
|
99
|
+
say('logging in to Cloudflare (a browser window)');
|
|
100
|
+
const result = wrangler(['login'], { stdio: 'inherit' });
|
|
101
|
+
if (result.status !== 0) throw new Error('wrangler login did not finish');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function openInBrowser(url) {
|
|
105
|
+
const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
106
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
107
|
+
spawnSync(opener, args, { stdio: 'ignore' });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Does this look like a Cloudflare API token (and nothing else)? */
|
|
111
|
+
export function looksLikeToken(text) {
|
|
112
|
+
return /^[A-Za-z0-9_-]{30,200}$/.test(String(text || '').trim());
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const CLIPBOARD_READERS = {
|
|
116
|
+
darwin: [['pbpaste', []]],
|
|
117
|
+
win32: [['powershell', ['-NoProfile', '-Command', 'Get-Clipboard']]],
|
|
118
|
+
linux: [['wl-paste', ['-n']], ['xclip', ['-selection', 'clipboard', '-o']], ['xsel', ['-b', '-o']]],
|
|
119
|
+
};
|
|
120
|
+
const CLIPBOARD_CLEARERS = {
|
|
121
|
+
darwin: [['pbcopy', []]],
|
|
122
|
+
win32: [['powershell', ['-NoProfile', '-Command', 'Set-Clipboard -Value $null']]],
|
|
123
|
+
linux: [['wl-copy', ['--clear']], ['xclip', ['-selection', 'clipboard', '-i']], ['xsel', ['-b', '-c']]],
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** The clipboard's text, read here (nothing is pasted into the terminal), or null without a way to read it. */
|
|
127
|
+
function readClipboard() {
|
|
128
|
+
for (const [command, args] of CLIPBOARD_READERS[process.platform] || []) {
|
|
129
|
+
const result = spawnSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
130
|
+
if (result.status === 0) return String(result.stdout || '').trim();
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Empty the clipboard, so the token does not stay there. */
|
|
136
|
+
function clearClipboard() {
|
|
137
|
+
for (const [command, args] of CLIPBOARD_CLEARERS[process.platform] || []) {
|
|
138
|
+
if (spawnSync(command, args, { input: '', stdio: ['pipe', 'ignore', 'ignore'] }).status === 0) return true;
|
|
139
|
+
}
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Read keys with nothing echoed: until Enter, returning what was typed (with
|
|
145
|
+
* any bracketed-paste markers removed). Ctrl-C quits.
|
|
146
|
+
*/
|
|
147
|
+
function readKeysSilently(prompt) {
|
|
148
|
+
if (!process.stdin.isTTY) throw new Error('needs a terminal');
|
|
149
|
+
process.stdout.write(prompt);
|
|
150
|
+
return new Promise((resolve) => {
|
|
151
|
+
let typed = '';
|
|
152
|
+
const done = (value) => {
|
|
153
|
+
process.stdin.off('data', onData);
|
|
154
|
+
process.stdin.setRawMode(false);
|
|
155
|
+
process.stdin.pause();
|
|
156
|
+
process.stdout.write('\n');
|
|
157
|
+
resolve(value);
|
|
158
|
+
};
|
|
159
|
+
const onData = (chunk) => {
|
|
160
|
+
const text = chunk.toString('utf8');
|
|
161
|
+
if (text.includes('\u0003')) { process.stdout.write('\n'); process.exit(130); }
|
|
162
|
+
typed += text;
|
|
163
|
+
const enter = typed.search(/[\r\n]/);
|
|
164
|
+
if (enter >= 0) done(typed.slice(0, enter).replace(/\x1b\[20[01]~/g, '').trim());
|
|
165
|
+
};
|
|
166
|
+
process.stdin.setRawMode(true);
|
|
167
|
+
process.stdin.resume();
|
|
168
|
+
process.stdin.on('data', onData);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Get the token without it ever showing on screen: copied in the browser, read
|
|
174
|
+
* here from the clipboard when Enter is pressed (no paste into the terminal,
|
|
175
|
+
* so no terminal shows it or warns about a paste), then the clipboard is
|
|
176
|
+
* emptied. Without a clipboard tool, it is typed or pasted with nothing echoed.
|
|
177
|
+
*/
|
|
178
|
+
async function tokenFromOwner() {
|
|
179
|
+
if (readClipboard() !== null) {
|
|
180
|
+
await readKeysSilently('[freertc name] click Copy next to the new token in the browser, then press Enter here (do not paste it): ');
|
|
181
|
+
const text = readClipboard();
|
|
182
|
+
if (!looksLikeToken(text)) return null;
|
|
183
|
+
say(clearClipboard() ? 'read the token from the clipboard and emptied the clipboard' : 'read the token from the clipboard (empty the clipboard yourself)');
|
|
184
|
+
return text.trim();
|
|
185
|
+
}
|
|
186
|
+
const typed = await readKeysSilently('[freertc name] paste the token here (nothing is shown): ');
|
|
187
|
+
return looksLikeToken(typed) ? typed : null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Cloudflare's token page, filled in: DNS edit on this one zone. */
|
|
191
|
+
export function tokenTemplateUrl(account, zone) {
|
|
192
|
+
const keys = encodeURIComponent(JSON.stringify([{ key: 'dns', type: 'edit' }]));
|
|
193
|
+
return `https://dash.cloudflare.com/profile/api-tokens?permissionGroupKeys=${keys}&accountId=${account}&zoneId=${zone.id}&name=${encodeURIComponent(`freertc names ${zone.name}`)}`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Get the DNS token from the owner, once, and check it can edit this zone's DNS. */
|
|
197
|
+
async function dnsTokenFromOwner(account, zone) {
|
|
198
|
+
const url = tokenTemplateUrl(account, zone);
|
|
199
|
+
say(`the Worker needs a token that can edit DNS on ${zone.name} only. Opening Cloudflare's token page, filled in:`);
|
|
200
|
+
console.log(` ${url}`);
|
|
201
|
+
say('check that it says Zone / DNS / Edit and Include / Specific zone / ' + zone.name + ', then click Continue to summary and Create Token');
|
|
202
|
+
openInBrowser(url);
|
|
203
|
+
for (let tries = 0; tries < 3; tries++) {
|
|
204
|
+
const pasted = await tokenFromOwner();
|
|
205
|
+
if (!pasted) { say('that is not a Cloudflare token (nothing was shown or kept); copy the token itself and try again'); continue; }
|
|
206
|
+
try {
|
|
207
|
+
await api(pasted, 'GET', `/zones/${zone.id}/dns_records?per_page=1`);
|
|
208
|
+
return pasted;
|
|
209
|
+
} catch (error) {
|
|
210
|
+
say(`that token cannot read ${zone.name}'s DNS (${error.message}); try again`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
throw new Error('no working token');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function api(token, method, pathname, body) {
|
|
217
|
+
const response = await fetch(`${API}${pathname}`, {
|
|
218
|
+
method,
|
|
219
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
220
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
221
|
+
});
|
|
222
|
+
const data = await response.json().catch(() => null);
|
|
223
|
+
if (!response.ok || data?.success === false) {
|
|
224
|
+
const why = data?.errors?.map((e) => `${e.code}: ${e.message}`).join('; ') || `status ${response.status}`;
|
|
225
|
+
const error = new Error(`${method} ${pathname}: ${why}`);
|
|
226
|
+
error.status = response.status;
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
return data?.result;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function choose(question, options) {
|
|
233
|
+
if (options.length === 1) return options[0];
|
|
234
|
+
if (!process.stdin.isTTY) throw new Error(`${question} (several: ${options.join(', ')}); pass it on the command line`);
|
|
235
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
236
|
+
try {
|
|
237
|
+
options.forEach((o, i) => console.log(` ${i + 1}. ${o}`));
|
|
238
|
+
const answer = await rl.question(`${question} [1-${options.length}]: `);
|
|
239
|
+
const pick = options[Number(answer) - 1];
|
|
240
|
+
if (!pick) throw new Error('no choice made');
|
|
241
|
+
return pick;
|
|
242
|
+
} finally {
|
|
243
|
+
rl.close();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The account's FreeRTC Workers: scripts whose workers.dev /health answers as a relay. */
|
|
248
|
+
async function findWorkers(token, account, subdomain, wanted) {
|
|
249
|
+
const scripts = (await api(token, 'GET', `/accounts/${account}/workers/scripts`)) || [];
|
|
250
|
+
const names = scripts.map((s) => s.id).filter((n) => !wanted || n === wanted);
|
|
251
|
+
const found = [];
|
|
252
|
+
await Promise.all(names.map(async (name) => {
|
|
253
|
+
const url = `https://${name}.${subdomain}.workers.dev`;
|
|
254
|
+
try {
|
|
255
|
+
const health = await (await fetch(`${url}/health`, { signal: AbortSignal.timeout(8000) })).json();
|
|
256
|
+
if (health?.relay_url && health?.node_id) found.push({ name, url });
|
|
257
|
+
} catch { /* not a relay, or not on workers.dev */ }
|
|
258
|
+
}));
|
|
259
|
+
return found.sort((a, b) => a.name.localeCompare(b.name));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
263
|
+
const args = parseArgs(argv);
|
|
264
|
+
const dataDir = path.resolve(process.env.FREERTC_DATA_DIR || path.join(process.cwd(), '.freertc-relay'));
|
|
265
|
+
const identity = await relayIdentity(dataDir);
|
|
266
|
+
say(`this relay: ${identity.nodeId.slice(0, 16)}… (data in ${dataDir})`);
|
|
267
|
+
|
|
268
|
+
let token = oauthToken();
|
|
269
|
+
if (!token) { login(); token = oauthToken(); }
|
|
270
|
+
if (!token) throw new Error('no Cloudflare login (wrangler auth token gave nothing)');
|
|
271
|
+
|
|
272
|
+
// Account, Worker, domain.
|
|
273
|
+
const accounts = (await api(token, 'GET', '/accounts')) || [];
|
|
274
|
+
const accountName = await choose('Which Cloudflare account?', accounts.map((a) => `${a.name} (${a.id})`));
|
|
275
|
+
const account = accountName.match(/\(([0-9a-f]+)\)$/)[1];
|
|
276
|
+
const { subdomain } = await api(token, 'GET', `/accounts/${account}/workers/subdomain`);
|
|
277
|
+
const workers = await findWorkers(token, account, subdomain, args.worker);
|
|
278
|
+
if (!workers.length) throw new Error(args.worker ? `no FreeRTC Worker named ${args.worker} answers on workers.dev` : 'no FreeRTC Worker in this account answers on workers.dev; deploy one first (the Deploy button or npx freertc deploy)');
|
|
279
|
+
const workerLabel = await choose('Which FreeRTC Worker?', workers.map((w) => w.name));
|
|
280
|
+
const worker = workers.find((w) => w.name === workerLabel);
|
|
281
|
+
const zones = (await api(token, 'GET', `/zones?per_page=50&account.id=${account}${args.domain ? `&name=${encodeURIComponent(args.domain)}` : ''}`)) || [];
|
|
282
|
+
if (!zones.length) throw new Error(args.domain ? `${args.domain} is not a domain on this Cloudflare account` : 'this Cloudflare account has no domains');
|
|
283
|
+
const domain = await choose('Which domain do relay names go on?', zones.map((z) => z.name));
|
|
284
|
+
const zone = zones.find((z) => z.name === domain);
|
|
285
|
+
say(`Worker ${worker.url}, domain ${domain}`);
|
|
286
|
+
|
|
287
|
+
// The Worker's DNS token, the first time (or for a new domain).
|
|
288
|
+
const settings = await api(token, 'GET', `/accounts/${account}/workers/scripts/${worker.name}/settings`);
|
|
289
|
+
// Does the Worker already name relays on this domain (set up from this or another machine)?
|
|
290
|
+
const naming = await fetch(new URL('/api/v1/name', worker.url)).then((r) => r.json()).catch(() => null);
|
|
291
|
+
// Workers with names answer here: with `names` (now), or (the first version) 404 'gives no names' / 405 to a GET.
|
|
292
|
+
const hasNames = naming && ('names' in naming || /gives no names|method not allowed/.test(String(naming.error || '')));
|
|
293
|
+
if (!hasNames) {
|
|
294
|
+
throw new Error(`${worker.name} runs an older FreeRTC without relay names; redeploy it first (the Deploy button, or npx freertc deploy), then run this again`);
|
|
295
|
+
}
|
|
296
|
+
const nameFile = path.join(dataDir, 'names.json');
|
|
297
|
+
const sameDomain = naming?.ok === true && naming.domain === domain;
|
|
298
|
+
// (The first version cannot say its domain: then the token is asked for again, which replaces it; harmless.)
|
|
299
|
+
if (!sameDomain) {
|
|
300
|
+
const created = await dnsTokenFromOwner(account, zone);
|
|
301
|
+
for (const [name, text] of [['NAMES_DNS_TOKEN', created], ['NAMES_ZONE_ID', zone.id], ['NAMES_DOMAIN', domain]]) {
|
|
302
|
+
await api(token, 'PUT', `/accounts/${account}/workers/scripts/${worker.name}/secrets`, { name, text, type: 'secret_text' });
|
|
303
|
+
}
|
|
304
|
+
say(`stored a DNS token for ${domain} in ${worker.name} (it can edit DNS on ${domain} only)`);
|
|
305
|
+
} else say(`${worker.name} already has a DNS token for ${domain}`);
|
|
306
|
+
|
|
307
|
+
// Register this relay in the Worker's database.
|
|
308
|
+
const d1 = (settings?.bindings || []).find((b) => b.type === 'd1' && b.name === 'DB');
|
|
309
|
+
if (!d1?.id && !d1?.database_id) throw new Error(`${worker.name} has no DB database binding`);
|
|
310
|
+
const databaseId = d1.id || d1.database_id;
|
|
311
|
+
await api(token, 'POST', `/accounts/${account}/d1/database/${databaseId}/query`, {
|
|
312
|
+
sql: `CREATE TABLE IF NOT EXISTS ${OWNERS_TABLE} (node_id TEXT PRIMARY KEY, added_at_ms INTEGER NOT NULL)`,
|
|
313
|
+
});
|
|
314
|
+
await api(token, 'POST', `/accounts/${account}/d1/database/${databaseId}/query`, {
|
|
315
|
+
sql: `INSERT OR IGNORE INTO ${OWNERS_TABLE} (node_id, added_at_ms) VALUES (?, ?)`,
|
|
316
|
+
params: [identity.nodeId, Date.now()],
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
const name = relayHostname(identity.nodeId, domain);
|
|
320
|
+
writeFileSync(nameFile, JSON.stringify({ worker: worker.url, domain, name }, null, 2) + '\n');
|
|
321
|
+
say(`registered. This relay will be ${name}`);
|
|
322
|
+
say('restart the relay (npm run dev): it claims the name, gets its Let\'s Encrypt certificate, and serves');
|
|
323
|
+
say(` wss://${name}:8443/ws`);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const entry = process.argv[1] ? pathToFileURL(process.argv[1]).href : null;
|
|
327
|
+
if (import.meta.url === entry) {
|
|
328
|
+
main().catch((error) => {
|
|
329
|
+
console.error(`[freertc name] ${error?.message || error}`);
|
|
330
|
+
process.exitCode = 1;
|
|
331
|
+
});
|
|
332
|
+
}
|