@infernetprotocol/cli 0.1.22
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 +15 -0
- package/commands/chat.js +268 -0
- package/commands/console.js +229 -0
- package/commands/debug.js +222 -0
- package/commands/deploy.js +524 -0
- package/commands/doctor.js +501 -0
- package/commands/firewall.js +39 -0
- package/commands/gpu.js +130 -0
- package/commands/help.js +54 -0
- package/commands/init.js +304 -0
- package/commands/login.js +305 -0
- package/commands/logs.js +93 -0
- package/commands/model.js +359 -0
- package/commands/payments.js +92 -0
- package/commands/payout.js +128 -0
- package/commands/pubkey.js +116 -0
- package/commands/register.js +304 -0
- package/commands/remove.js +230 -0
- package/commands/service.js +255 -0
- package/commands/setup.js +869 -0
- package/commands/start.js +903 -0
- package/commands/stats.js +85 -0
- package/commands/status.js +116 -0
- package/commands/stop.js +81 -0
- package/commands/train.js +563 -0
- package/commands/tui.js +285 -0
- package/commands/uncensored.js +222 -0
- package/commands/update.js +80 -0
- package/commands/upgrade.js +2 -0
- package/examples/app.js +153 -0
- package/index.js +207 -0
- package/lib/chat-executor.js +232 -0
- package/lib/config.js +148 -0
- package/lib/daemonize.js +46 -0
- package/lib/firewall.js +190 -0
- package/lib/hf-model.js +166 -0
- package/lib/identity.js +18 -0
- package/lib/ipc.js +114 -0
- package/lib/model-fit.js +67 -0
- package/lib/model-key.js +52 -0
- package/lib/network.js +240 -0
- package/lib/nip44.js +130 -0
- package/lib/node-client.js +152 -0
- package/lib/peers.js +133 -0
- package/lib/prompt.js +49 -0
- package/lib/remote-chat.js +115 -0
- package/lib/route.js +44 -0
- package/lib/runtime-config.js +130 -0
- package/lib/version.js +32 -0
- package/package.json +57 -0
package/lib/model-fit.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared model-fit utilities — used by setup, model pull, and the
|
|
3
|
+
* daemon's model_install node command so the capacity check is
|
|
4
|
+
* enforced consistently regardless of how a pull is triggered.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Rough on-disk sizes (GB) for commonly used models. Unknown names
|
|
9
|
+
* pass through unchecked — ollama will surface the error at pull time.
|
|
10
|
+
*/
|
|
11
|
+
export const KNOWN_MODEL_SIZES = {
|
|
12
|
+
"qwen2.5:0.5b": 0.4,
|
|
13
|
+
"qwen2.5:1.5b": 1.0,
|
|
14
|
+
"qwen2.5:3b": 2.0,
|
|
15
|
+
"qwen2.5:7b": 4.4,
|
|
16
|
+
"qwen2.5:14b": 9.0,
|
|
17
|
+
"qwen2.5:32b": 20.0,
|
|
18
|
+
"qwen2.5:72b": 40.0,
|
|
19
|
+
"llama3.2:1b": 1.3,
|
|
20
|
+
"llama3.2:3b": 2.0,
|
|
21
|
+
"llama3.1:8b": 4.7,
|
|
22
|
+
"llama3.1:70b": 40.0,
|
|
23
|
+
"mistral:7b": 4.4,
|
|
24
|
+
"mixtral:8x7b": 26.0
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Detect available VRAM (GPU) and RAM for fit checks. */
|
|
28
|
+
export async function detectCapacity() {
|
|
29
|
+
try {
|
|
30
|
+
const { detectGpus, detectHost } = await import("@infernetprotocol/gpu");
|
|
31
|
+
const [gpus, host] = await Promise.all([detectGpus(), Promise.resolve(detectHost())]);
|
|
32
|
+
const vramGb = gpus.reduce((a, g) => a + (Number.isFinite(g.vram_mb) ? g.vram_mb / 1024 : 0), 0);
|
|
33
|
+
const ramGb = host.total_ram_mb / 1024;
|
|
34
|
+
return { vram_gb: vramGb, ram_gb: ramGb };
|
|
35
|
+
} catch {
|
|
36
|
+
return { vram_gb: 0, ram_gb: 0 };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Returns { ok, mode, have_gb, ceiling_gb }.
|
|
42
|
+
* GPU box: model fits if size ≤ 85% of VRAM.
|
|
43
|
+
* CPU box: model fits if size ≤ 60% of RAM.
|
|
44
|
+
*/
|
|
45
|
+
export function checkFits({ size_gb, vram_gb, ram_gb }) {
|
|
46
|
+
if (vram_gb > 0) {
|
|
47
|
+
const ceiling = vram_gb * 0.85;
|
|
48
|
+
return { ok: size_gb <= ceiling, mode: "gpu", have_gb: +vram_gb.toFixed(2), ceiling_gb: +ceiling.toFixed(2) };
|
|
49
|
+
}
|
|
50
|
+
if (ram_gb > 0) {
|
|
51
|
+
const ceiling = ram_gb * 0.6;
|
|
52
|
+
return { ok: size_gb <= ceiling, mode: "cpu", have_gb: +ram_gb.toFixed(2), ceiling_gb: +ceiling.toFixed(2) };
|
|
53
|
+
}
|
|
54
|
+
return { ok: true, mode: "unknown", have_gb: 0, ceiling_gb: null };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Run a capacity check for a named model. Returns null if the model
|
|
59
|
+
* size is unknown (can't check). Returns { ok, mode, have_gb,
|
|
60
|
+
* ceiling_gb, size_gb } otherwise.
|
|
61
|
+
*/
|
|
62
|
+
export async function checkModelFits(name) {
|
|
63
|
+
const size_gb = KNOWN_MODEL_SIZES[name];
|
|
64
|
+
if (!Number.isFinite(size_gb)) return null;
|
|
65
|
+
const cap = await detectCapacity();
|
|
66
|
+
return { size_gb, ...checkFits({ size_gb, ...cap }) };
|
|
67
|
+
}
|
package/lib/model-key.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-model secp256k1 keypair management (IPIP-0028 Phase 1).
|
|
3
|
+
*
|
|
4
|
+
* Each model served by a node gets its own keypair stored under
|
|
5
|
+
* config.engine.model_keys[modelName]. Consumers can encrypt
|
|
6
|
+
* to the model's pubkey rather than the node's pubkey, limiting
|
|
7
|
+
* blast radius to a single model if a key is ever compromised.
|
|
8
|
+
*
|
|
9
|
+
* Keys are generated lazily on first use and persisted to config.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { generateKeyPair } from '@infernetprotocol/auth';
|
|
13
|
+
import { loadConfig, saveConfig } from './config.js';
|
|
14
|
+
|
|
15
|
+
/** Get or generate a keypair for `modelName`. Persists in config. */
|
|
16
|
+
export async function getOrCreateModelKey(modelName) {
|
|
17
|
+
if (!modelName || typeof modelName !== 'string') return null;
|
|
18
|
+
const config = (await loadConfig()) ?? {};
|
|
19
|
+
const existing = config.engine?.model_keys?.[modelName];
|
|
20
|
+
if (existing?.publicKey && existing?.privateKey) return existing;
|
|
21
|
+
const keypair = generateKeyPair();
|
|
22
|
+
const updated = {
|
|
23
|
+
...config,
|
|
24
|
+
engine: {
|
|
25
|
+
...(config.engine ?? {}),
|
|
26
|
+
model_keys: {
|
|
27
|
+
...(config.engine?.model_keys ?? {}),
|
|
28
|
+
[modelName]: keypair
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
await saveConfig(updated);
|
|
33
|
+
return keypair;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Return `{ modelName: publicKey }` for all models that have keys. */
|
|
37
|
+
export async function getModelPublicKeys() {
|
|
38
|
+
const config = (await loadConfig()) ?? {};
|
|
39
|
+
const modelKeys = config.engine?.model_keys ?? {};
|
|
40
|
+
const out = {};
|
|
41
|
+
for (const [name, kp] of Object.entries(modelKeys)) {
|
|
42
|
+
if (kp?.publicKey) out[name] = kp.publicKey;
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Return the full `{ publicKey, privateKey }` for `modelName`, or null. */
|
|
48
|
+
export async function getModelKeyPair(modelName) {
|
|
49
|
+
if (!modelName) return null;
|
|
50
|
+
const config = (await loadConfig()) ?? {};
|
|
51
|
+
return config.engine?.model_keys?.[modelName] ?? null;
|
|
52
|
+
}
|
package/lib/network.js
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Network defaults + local address helpers for the Infernet CLI.
|
|
3
|
+
*
|
|
4
|
+
* The P2P port is the well-known TCP port where an Infernet node listens
|
|
5
|
+
* for peer connections (not to be confused with the Unix-domain IPC
|
|
6
|
+
* socket, which is local-only). Other nodes in the network reach this
|
|
7
|
+
* node at `ip:P2P_PORT` (v4 or v6).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_P2P_PORT = 46337;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Pick a sensible port: config.node.port → env INFERNET_P2P_PORT → default.
|
|
16
|
+
*/
|
|
17
|
+
export function resolveP2pPort(config) {
|
|
18
|
+
const fromConfig = config?.node?.port;
|
|
19
|
+
if (Number.isFinite(fromConfig) && fromConfig > 0) return fromConfig;
|
|
20
|
+
|
|
21
|
+
const fromEnv = Number.parseInt(process.env.INFERNET_P2P_PORT ?? '', 10);
|
|
22
|
+
if (Number.isFinite(fromEnv) && fromEnv > 0) return fromEnv;
|
|
23
|
+
|
|
24
|
+
return DEFAULT_P2P_PORT;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Interface name patterns that indicate a virtual / container bridge.
|
|
28
|
+
// Skipped during local-address scanning — even a non-loopback IP on
|
|
29
|
+
// docker0 is unreachable from the outside world.
|
|
30
|
+
const VIRTUAL_IFACE_PATTERNS = [
|
|
31
|
+
/^docker\d*$/i, // docker0, docker1
|
|
32
|
+
/^br-[0-9a-f]+$/i, // user-defined docker networks
|
|
33
|
+
/^veth/i, // container veth pair host side
|
|
34
|
+
/^cni\d*$/i, // k8s CNI bridge
|
|
35
|
+
/^flannel/i,
|
|
36
|
+
/^cali/i, // Calico
|
|
37
|
+
/^weave/i,
|
|
38
|
+
/^kube-/i,
|
|
39
|
+
/^lo$/i,
|
|
40
|
+
/^tailscale\d*$/i, // tailscale virtual iface — public via tailscale, but
|
|
41
|
+
// not useful for advertising on the open internet
|
|
42
|
+
/^tun\d*$/i,
|
|
43
|
+
/^tap\d*$/i,
|
|
44
|
+
/^virbr\d*$/i, // libvirt
|
|
45
|
+
/^vmnet\d*$/i // VMware
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
function isVirtualInterface(name) {
|
|
49
|
+
return VIRTUAL_IFACE_PATTERNS.some((rx) => rx.test(name));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* IPv4 ranges that are plausibly the Docker default bridge subnet
|
|
54
|
+
* (172.17.0.0 – 172.31.255.255 — Docker's default-bridge pool sits in
|
|
55
|
+
* 172.17/16 and user networks creep up through 172.31). On a
|
|
56
|
+
* containerized box (Vast.ai, RunPod, etc.) the only assigned address
|
|
57
|
+
* is often inside this range, even if the interface name is plain
|
|
58
|
+
* `eth0` — the address itself is the cleanest signal.
|
|
59
|
+
*
|
|
60
|
+
* Note: 172.16/12 is RFC 1918 and legitimately used for some on-prem
|
|
61
|
+
* LANs. We deliberately only flag the Docker-typical 172.17–172.31
|
|
62
|
+
* subset to avoid false positives.
|
|
63
|
+
*/
|
|
64
|
+
function isDockerSubnet(ip) {
|
|
65
|
+
const parts = ip.split('.').map(Number);
|
|
66
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n))) return false;
|
|
67
|
+
if (parts[0] !== 172) return false;
|
|
68
|
+
return parts[1] >= 17 && parts[1] <= 31;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isPrivateIPv4(ip) {
|
|
72
|
+
const parts = ip.split('.').map(Number);
|
|
73
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n))) return false;
|
|
74
|
+
if (parts[0] === 10) return true;
|
|
75
|
+
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
|
|
76
|
+
if (parts[0] === 192 && parts[1] === 168) return true;
|
|
77
|
+
if (parts[0] === 169 && parts[1] === 254) return true; // link-local
|
|
78
|
+
if (parts[0] === 127) return true; // loopback
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Hosting platforms NAT containers — the in-container interface holds
|
|
84
|
+
* a docker-bridge IP, while the public IP lives on the host. Each
|
|
85
|
+
* platform exposes the public IP through a different env var.
|
|
86
|
+
*
|
|
87
|
+
* RunPod : RUNPOD_PUBLIC_IP
|
|
88
|
+
* Vast.ai : PUBLIC_IPADDR (set by the Vast launcher in the container env)
|
|
89
|
+
*
|
|
90
|
+
* install.sh additionally sets INFERNET_PUBLIC_ADDRESS to whichever it
|
|
91
|
+
* resolved — that takes priority because the operator may also have
|
|
92
|
+
* passed it explicitly.
|
|
93
|
+
*/
|
|
94
|
+
function platformPublicAddress() {
|
|
95
|
+
const env = process.env;
|
|
96
|
+
const explicit = env.INFERNET_PUBLIC_ADDRESS;
|
|
97
|
+
if (explicit && explicit.trim()) return explicit.trim();
|
|
98
|
+
if (env.RUNPOD_PUBLIC_IP && env.RUNPOD_PUBLIC_IP.trim()) return env.RUNPOD_PUBLIC_IP.trim();
|
|
99
|
+
if (env.PUBLIC_IPADDR && env.PUBLIC_IPADDR.trim()) return env.PUBLIC_IPADDR.trim();
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Walk os.networkInterfaces() and return the best candidate address
|
|
105
|
+
* found locally, plus a hint about its quality:
|
|
106
|
+
* - 'public' routable IPv4 (ignoring the Docker subnet)
|
|
107
|
+
* - 'private' RFC1918 LAN (10/8, 192.168/16, 172.16-172.31 ex docker)
|
|
108
|
+
* - 'docker' 172.17-172.31 — almost certainly a container bridge
|
|
109
|
+
* - 'ipv6' non-link-local IPv6 (no v4 found)
|
|
110
|
+
* - 'none' nothing usable
|
|
111
|
+
*/
|
|
112
|
+
function scanInterfaces() {
|
|
113
|
+
const ifaces = os.networkInterfaces();
|
|
114
|
+
let publicV4 = null;
|
|
115
|
+
let privateV4 = null;
|
|
116
|
+
let dockerV4 = null;
|
|
117
|
+
let v6 = null;
|
|
118
|
+
for (const name of Object.keys(ifaces)) {
|
|
119
|
+
if (isVirtualInterface(name)) continue;
|
|
120
|
+
for (const info of ifaces[name] ?? []) {
|
|
121
|
+
if (info.internal) continue;
|
|
122
|
+
if (info.family === 'IPv4') {
|
|
123
|
+
if (isDockerSubnet(info.address)) {
|
|
124
|
+
dockerV4 ??= info.address;
|
|
125
|
+
} else if (isPrivateIPv4(info.address)) {
|
|
126
|
+
privateV4 ??= info.address;
|
|
127
|
+
} else {
|
|
128
|
+
publicV4 ??= info.address;
|
|
129
|
+
}
|
|
130
|
+
} else if (info.family === 'IPv6' && !v6) {
|
|
131
|
+
if (info.address.toLowerCase().startsWith('fe80')) continue;
|
|
132
|
+
v6 = info.address;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (publicV4) return { address: publicV4, kind: 'public' };
|
|
137
|
+
if (privateV4) return { address: privateV4, kind: 'private' };
|
|
138
|
+
if (dockerV4) return { address: dockerV4, kind: 'docker' };
|
|
139
|
+
if (v6) return { address: v6, kind: 'ipv6' };
|
|
140
|
+
return { address: null, kind: 'none' };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Probe a public echo service to learn the egress IPv4 address. Used
|
|
145
|
+
* only as a last resort when local interface scanning produced a
|
|
146
|
+
* Docker-subnet IP — i.e. we're inside a container that doesn't have
|
|
147
|
+
* its public IP on any local interface.
|
|
148
|
+
*
|
|
149
|
+
* Short timeout, never throws — returns null on any failure.
|
|
150
|
+
*/
|
|
151
|
+
async function probePublicAddress({ timeoutMs = 2500 } = {}) {
|
|
152
|
+
const endpoints = [
|
|
153
|
+
'https://api.ipify.org',
|
|
154
|
+
'https://icanhazip.com',
|
|
155
|
+
'https://ifconfig.me/ip'
|
|
156
|
+
];
|
|
157
|
+
for (const url of endpoints) {
|
|
158
|
+
try {
|
|
159
|
+
const ctrl = new AbortController();
|
|
160
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
161
|
+
let res;
|
|
162
|
+
try {
|
|
163
|
+
res = await fetch(url, { signal: ctrl.signal });
|
|
164
|
+
} finally {
|
|
165
|
+
clearTimeout(timer);
|
|
166
|
+
}
|
|
167
|
+
if (!res.ok) continue;
|
|
168
|
+
const txt = (await res.text()).trim();
|
|
169
|
+
// Sanity check — must look like an IPv4 address.
|
|
170
|
+
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(txt)) return txt;
|
|
171
|
+
} catch {
|
|
172
|
+
// try next endpoint
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Sync local-only address scan. Useful where async isn't an option
|
|
180
|
+
* (signal handlers, log lines). Honors env overrides but never makes
|
|
181
|
+
* a network call.
|
|
182
|
+
*/
|
|
183
|
+
export function detectLocalAddressSync() {
|
|
184
|
+
const platform = platformPublicAddress();
|
|
185
|
+
if (platform) return platform;
|
|
186
|
+
const { address } = scanInterfaces();
|
|
187
|
+
return address;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Best public/advertise address for THIS node. Resolution order:
|
|
192
|
+
*
|
|
193
|
+
* 1. INFERNET_PUBLIC_ADDRESS / RUNPOD_PUBLIC_IP / PUBLIC_IPADDR env
|
|
194
|
+
* 2. A non-Docker, non-private local IPv4
|
|
195
|
+
* 3. A private (LAN) local IPv4 — fine for home/office, peers reach
|
|
196
|
+
* it inside the same network
|
|
197
|
+
* 4. If we'd otherwise advertise a Docker-bridge IP (172.17-172.31),
|
|
198
|
+
* probe icanhazip / ipify / ifconfig.me for the actual egress IP
|
|
199
|
+
* 5. IPv6 fallback
|
|
200
|
+
*
|
|
201
|
+
* Returns null if nothing usable was found.
|
|
202
|
+
*/
|
|
203
|
+
export async function detectLocalAddress() {
|
|
204
|
+
const platform = platformPublicAddress();
|
|
205
|
+
if (platform) return platform;
|
|
206
|
+
|
|
207
|
+
const scan = scanInterfaces();
|
|
208
|
+
if (scan.kind === 'public' || scan.kind === 'private') return scan.address;
|
|
209
|
+
|
|
210
|
+
if (scan.kind === 'docker' || scan.kind === 'none') {
|
|
211
|
+
const probed = await probePublicAddress();
|
|
212
|
+
if (probed) return probed;
|
|
213
|
+
// Fall through to whatever local hint we had — even a
|
|
214
|
+
// docker-bridge IP is more useful than null in dashboards.
|
|
215
|
+
if (scan.address) return scan.address;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return scan.address; // ipv6 case, or null
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Format an endpoint string, bracketing IPv6 per RFC 3986:
|
|
223
|
+
* 192.0.2.1:46337 -> "192.0.2.1:46337"
|
|
224
|
+
* 2001:db8::1, port 46337 -> "[2001:db8::1]:46337"
|
|
225
|
+
*/
|
|
226
|
+
export function formatEndpoint(address, port) {
|
|
227
|
+
if (!address) return `:${port}`;
|
|
228
|
+
if (address.includes(':')) return `[${address}]:${port}`;
|
|
229
|
+
return `${address}:${port}`;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Internals exported for tests.
|
|
233
|
+
export const __internals = {
|
|
234
|
+
isVirtualInterface,
|
|
235
|
+
isDockerSubnet,
|
|
236
|
+
isPrivateIPv4,
|
|
237
|
+
platformPublicAddress,
|
|
238
|
+
scanInterfaces,
|
|
239
|
+
probePublicAddress
|
|
240
|
+
};
|
package/lib/nip44.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NIP-44 v2 — ECDH key agreement + ChaCha20 + HMAC-SHA256.
|
|
3
|
+
*
|
|
4
|
+
* Spec: https://github.com/nostr-protocol/nips/blob/master/44.md
|
|
5
|
+
*
|
|
6
|
+
* Key derivation:
|
|
7
|
+
* shared_x = secp256k1.getSharedSecret(privA, compressedPubB)[1:33]
|
|
8
|
+
* conversation_key = HKDF-SHA256(ikm=shared_x, salt=utf8("nip44-v2"), info="", len=32)
|
|
9
|
+
*
|
|
10
|
+
* Per-message encrypt(conversationKey, plaintext):
|
|
11
|
+
* nonce = random 32 bytes
|
|
12
|
+
* message_keys = HKDF-SHA256(ikm=conversationKey, salt=nonce, info=utf8("encryption"), len=76)
|
|
13
|
+
* chacha_key = message_keys[0:32]
|
|
14
|
+
* chacha_nonce = message_keys[32:44]
|
|
15
|
+
* hmac_key = message_keys[44:76]
|
|
16
|
+
* ciphertext = ChaCha20(plaintext, chacha_key, chacha_nonce)
|
|
17
|
+
* mac = HMAC-SHA256(hmac_key, nonce || ciphertext)
|
|
18
|
+
* payload = base64(version(1 byte=2) || nonce || ciphertext || mac)
|
|
19
|
+
*
|
|
20
|
+
* Works in both Node.js and modern browsers.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
24
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
25
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
26
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
27
|
+
import { randomBytes } from "@noble/hashes/utils.js";
|
|
28
|
+
import { chacha20 } from "@noble/ciphers/chacha.js";
|
|
29
|
+
|
|
30
|
+
const VERSION = 2;
|
|
31
|
+
const NONCE_BYTES = 32;
|
|
32
|
+
const MAC_BYTES = 32;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Derive a conversation key from one side's privkey + other side's pubkey.
|
|
36
|
+
* Both are 64-hex Nostr / BIP-340 x-only keys.
|
|
37
|
+
*/
|
|
38
|
+
export function getConversationKey(privkeyHex, pubkeyHex) {
|
|
39
|
+
const privBytes = _hex(privkeyHex);
|
|
40
|
+
const pubBytes = _toCompressed(pubkeyHex);
|
|
41
|
+
const shared = secp256k1.getSharedSecret(privBytes, pubBytes);
|
|
42
|
+
const sharedX = shared.slice(1, 33); // x-coordinate only
|
|
43
|
+
return hkdf(sha256, sharedX, _utf8("nip44-v2"), new Uint8Array(0), 32);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Encrypt plaintext string → base64 payload. */
|
|
47
|
+
export function encrypt(conversationKey, plaintext) {
|
|
48
|
+
const nonce = randomBytes(NONCE_BYTES);
|
|
49
|
+
const { chachaKey, chachaNonce, hmacKey } = _messageKeys(conversationKey, nonce);
|
|
50
|
+
|
|
51
|
+
const plain = _utf8(plaintext);
|
|
52
|
+
const ciphertext = chacha20(chachaKey, chachaNonce, plain);
|
|
53
|
+
const mac = hmac(sha256, hmacKey, _concat(nonce, ciphertext));
|
|
54
|
+
|
|
55
|
+
return _toBase64(_concat(new Uint8Array([VERSION]), nonce, ciphertext, mac));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Decrypt base64 payload → plaintext string. Throws on MAC failure. */
|
|
59
|
+
export function decrypt(conversationKey, payloadBase64) {
|
|
60
|
+
const payload = _fromBase64(payloadBase64);
|
|
61
|
+
if (payload[0] !== VERSION) throw new Error(`nip44: unsupported version ${payload[0]}`);
|
|
62
|
+
|
|
63
|
+
const nonce = payload.slice(1, 1 + NONCE_BYTES);
|
|
64
|
+
const mac = payload.slice(payload.length - MAC_BYTES);
|
|
65
|
+
const ciphertext = payload.slice(1 + NONCE_BYTES, payload.length - MAC_BYTES);
|
|
66
|
+
|
|
67
|
+
if (ciphertext.length === 0) throw new Error("nip44: empty ciphertext");
|
|
68
|
+
|
|
69
|
+
const { chachaKey, chachaNonce, hmacKey } = _messageKeys(conversationKey, nonce);
|
|
70
|
+
const expectedMac = hmac(sha256, hmacKey, _concat(nonce, ciphertext));
|
|
71
|
+
|
|
72
|
+
if (!_timingSafeEqual(expectedMac, mac)) throw new Error("nip44: authentication failed");
|
|
73
|
+
|
|
74
|
+
const plain = chacha20(chachaKey, chachaNonce, ciphertext);
|
|
75
|
+
return new TextDecoder().decode(plain);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ─── internal ────────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
function _messageKeys(conversationKey, nonce) {
|
|
81
|
+
const keys = hkdf(sha256, conversationKey, nonce, _utf8("encryption"), 76);
|
|
82
|
+
return {
|
|
83
|
+
chachaKey: keys.slice(0, 32),
|
|
84
|
+
chachaNonce: keys.slice(32, 44),
|
|
85
|
+
hmacKey: keys.slice(44, 76)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function _utf8(str) { return new TextEncoder().encode(str); }
|
|
90
|
+
|
|
91
|
+
function _hex(hex) {
|
|
92
|
+
const b = new Uint8Array(hex.length / 2);
|
|
93
|
+
for (let i = 0; i < b.length; i++) b[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
94
|
+
return b;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function _concat(...arrays) {
|
|
98
|
+
const n = arrays.reduce((s, a) => s + a.length, 0);
|
|
99
|
+
const out = new Uint8Array(n);
|
|
100
|
+
let off = 0;
|
|
101
|
+
for (const a of arrays) { out.set(a, off); off += a.length; }
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function _toBase64(bytes) {
|
|
106
|
+
if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
|
|
107
|
+
return btoa(String.fromCharCode(...bytes));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function _fromBase64(b64) {
|
|
111
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(b64, "base64"));
|
|
112
|
+
return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function _timingSafeEqual(a, b) {
|
|
116
|
+
if (a.length !== b.length) return false;
|
|
117
|
+
let d = 0;
|
|
118
|
+
for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
|
|
119
|
+
return d === 0;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Nostr BIP-340 x-only pubkeys (32 bytes / 64 hex) need a 0x02 prefix
|
|
124
|
+
* to be passed to secp256k1.getSharedSecret as a compressed point.
|
|
125
|
+
*/
|
|
126
|
+
function _toCompressed(pubkeyHex) {
|
|
127
|
+
if (pubkeyHex.length === 64) return _hex("02" + pubkeyHex);
|
|
128
|
+
if (pubkeyHex.length === 66) return _hex(pubkeyHex);
|
|
129
|
+
throw new Error("nip44: pubkey must be 32 or 33 bytes hex");
|
|
130
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node-side client for the Infernet control-plane API.
|
|
3
|
+
*
|
|
4
|
+
* Every call is signed with the node's Nostr privkey (Schnorr / BIP-340)
|
|
5
|
+
* and carries an X-Infernet-Auth envelope the server verifies. The node
|
|
6
|
+
* never learns any DB credential — proof of ownership is the signature.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { signRequest, AUTH_HEADER } from '@infernetprotocol/auth';
|
|
10
|
+
|
|
11
|
+
function trimTrailingSlash(url) {
|
|
12
|
+
return url.endsWith('/') ? url.slice(0, -1) : url;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {Object} ClientConfig
|
|
17
|
+
* @property {string} url - control-plane base URL
|
|
18
|
+
* @property {string} publicKey - 64-char hex Nostr pubkey
|
|
19
|
+
* @property {string} privateKey - 64-char hex Nostr privkey
|
|
20
|
+
* @property {string} [role] - provider | aggregator | client
|
|
21
|
+
* @property {number} [timeoutMs] - per-request timeout (default 15000)
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export function createNodeClient({ url, publicKey, privateKey, role, timeoutMs = 15000 }) {
|
|
25
|
+
if (!url) throw new Error('node client: url is required');
|
|
26
|
+
if (!publicKey || !privateKey) throw new Error('node client: publicKey + privateKey are required');
|
|
27
|
+
const base = trimTrailingSlash(url);
|
|
28
|
+
|
|
29
|
+
async function signedFetch(path, body) {
|
|
30
|
+
const bodyText = body === undefined ? '' : JSON.stringify(body);
|
|
31
|
+
const { header } = signRequest({
|
|
32
|
+
method: 'POST',
|
|
33
|
+
path,
|
|
34
|
+
body: bodyText,
|
|
35
|
+
publicKey,
|
|
36
|
+
privateKey
|
|
37
|
+
});
|
|
38
|
+
const controller = new AbortController();
|
|
39
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
40
|
+
let res;
|
|
41
|
+
try {
|
|
42
|
+
res = await fetch(base + path, {
|
|
43
|
+
method: 'POST',
|
|
44
|
+
headers: {
|
|
45
|
+
'content-type': 'application/json',
|
|
46
|
+
[AUTH_HEADER]: header
|
|
47
|
+
},
|
|
48
|
+
body: bodyText,
|
|
49
|
+
signal: controller.signal
|
|
50
|
+
});
|
|
51
|
+
} finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
let payload = null;
|
|
56
|
+
const text = await res.text();
|
|
57
|
+
if (text) {
|
|
58
|
+
try { payload = JSON.parse(text); } catch { payload = { raw: text }; }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (!res.ok) {
|
|
62
|
+
const msg = payload?.error ?? `HTTP ${res.status}`;
|
|
63
|
+
const err = new Error(`${path} failed: ${msg}`);
|
|
64
|
+
err.status = res.status;
|
|
65
|
+
err.body = payload;
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
return payload?.data ?? null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
base,
|
|
73
|
+
publicKey,
|
|
74
|
+
role,
|
|
75
|
+
signedFetch,
|
|
76
|
+
|
|
77
|
+
register(input) {
|
|
78
|
+
return signedFetch('/api/v1/node/register', { role, ...input });
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
heartbeat(input = {}) {
|
|
82
|
+
return signedFetch('/api/v1/node/heartbeat', { role, ...input });
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
pollJobs(input = {}) {
|
|
86
|
+
return signedFetch('/api/v1/node/jobs/poll', input);
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
completeJob(jobId, input = {}) {
|
|
90
|
+
return signedFetch(`/api/v1/node/jobs/${encodeURIComponent(jobId)}/complete`, input);
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
failJob(jobId, error) {
|
|
94
|
+
return signedFetch(`/api/v1/node/jobs/${encodeURIComponent(jobId)}/complete`, {
|
|
95
|
+
status: 'failed',
|
|
96
|
+
error: typeof error === 'string' ? error : String(error?.message ?? error)
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
postJobEvents(jobId, events) {
|
|
101
|
+
return signedFetch(`/api/v1/node/jobs/${encodeURIComponent(jobId)}/events`, { events });
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
remove() {
|
|
105
|
+
return signedFetch('/api/v1/node/remove', { role });
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
me() {
|
|
109
|
+
return signedFetch('/api/v1/node/me', { role });
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
listPayments(limit = 20) {
|
|
113
|
+
return signedFetch('/api/v1/node/payments/list', { role, limit });
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
pollCommands(limit = 5) {
|
|
117
|
+
return signedFetch('/api/v1/node/commands/poll', { limit });
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
completeCommand(commandId, { status, result, error: errorMessage } = {}) {
|
|
121
|
+
return signedFetch(
|
|
122
|
+
`/api/v1/node/commands/${encodeURIComponent(commandId)}/complete`,
|
|
123
|
+
{ status, result, error: errorMessage }
|
|
124
|
+
);
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
listPayouts() {
|
|
128
|
+
return signedFetch('/api/v1/node/payouts/list', {});
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
setPayout({ coin, network, address }) {
|
|
132
|
+
return signedFetch('/api/v1/node/payouts/set', { coin, network, address });
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function createNodeClientFromConfig(config) {
|
|
138
|
+
const node = config?.node ?? {};
|
|
139
|
+
const url = config?.controlPlane?.url ?? config?.supabase?.url;
|
|
140
|
+
if (!url) {
|
|
141
|
+
throw new Error('config.controlPlane.url is not set; run `infernet login` to set the control-plane URL');
|
|
142
|
+
}
|
|
143
|
+
if (!node.publicKey || !node.privateKey) {
|
|
144
|
+
throw new Error('config.node is missing Nostr keypair; run `infernet init`');
|
|
145
|
+
}
|
|
146
|
+
return createNodeClient({
|
|
147
|
+
url,
|
|
148
|
+
publicKey: node.publicKey,
|
|
149
|
+
privateKey: node.privateKey,
|
|
150
|
+
role: node.role
|
|
151
|
+
});
|
|
152
|
+
}
|