@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/commands/help.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `infernet help` — top-level usage.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const USAGE = `infernet — GPU node control plane for the Infernet Protocol
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
infernet [prompt] Chat with the network (default verb)
|
|
9
|
+
infernet <command> [args] Run an explicit subcommand
|
|
10
|
+
echo "..." | infernet Chat with the piped input
|
|
11
|
+
|
|
12
|
+
Setup:
|
|
13
|
+
setup Bootstrap environment (Ollama + model + firewall + config)
|
|
14
|
+
model Manage models (list / pull / remove / use / hf: prefix for HuggingFace)
|
|
15
|
+
uncensored Download an uncensored LLM (auto-picks by VRAM, serve via vLLM)
|
|
16
|
+
|
|
17
|
+
Node lifecycle:
|
|
18
|
+
init Configure this node (control-plane URL, role, Nostr identity)
|
|
19
|
+
login Update the control-plane URL
|
|
20
|
+
register Register this node with the control plane (signed)
|
|
21
|
+
update Push current capability/status to the control plane (signed)
|
|
22
|
+
upgrade Re-run the curl installer to pull the latest CLI, then re-register
|
|
23
|
+
remove Deregister this node, wipe local config, and uninstall the CLI
|
|
24
|
+
|
|
25
|
+
Daemon:
|
|
26
|
+
start Start the node daemon (detached by default)
|
|
27
|
+
stop Stop the running daemon
|
|
28
|
+
status Show this node's current state (remote row + live daemon)
|
|
29
|
+
stats Live in-memory stats from the running daemon (via IPC)
|
|
30
|
+
logs Show / tail the daemon log (~/.config/infernet/daemon.log)
|
|
31
|
+
service Userland systemd unit (Linux): install / enable / status / logs
|
|
32
|
+
|
|
33
|
+
Diagnostics:
|
|
34
|
+
gpu Inspect local GPUs (nvidia-smi / rocm-smi / system_profiler)
|
|
35
|
+
firewall Print commands to open the P2P port on your firewall
|
|
36
|
+
chat Run an inference (P2P network or --local engine)
|
|
37
|
+
tui Live terminal dashboard (system / jobs / engine / peers)
|
|
38
|
+
doctor End-to-end health check across all three sides
|
|
39
|
+
|
|
40
|
+
Payments:
|
|
41
|
+
payout Manage payout coin/address
|
|
42
|
+
payments Show recent payment transactions
|
|
43
|
+
|
|
44
|
+
Other:
|
|
45
|
+
help Show this help
|
|
46
|
+
|
|
47
|
+
Run \`infernet <command> --help\` for per-command help.
|
|
48
|
+
`;
|
|
49
|
+
|
|
50
|
+
export default async function help() {
|
|
51
|
+
process.stdout.write(USAGE);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { USAGE };
|
package/commands/init.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `infernet init`
|
|
3
|
+
*
|
|
4
|
+
* Creates the CLI config at ~/.config/infernet/config.json. The node talks
|
|
5
|
+
* to the control plane through signed HTTP requests (Nostr / BIP-340) — no
|
|
6
|
+
* database credentials are stored locally, so init only needs the control
|
|
7
|
+
* plane URL plus a Nostr keypair (generated if the operator doesn't bring one).
|
|
8
|
+
*
|
|
9
|
+
* Supported flags:
|
|
10
|
+
* --url <url> Control-plane base URL (default: https://infernetprotocol.com)
|
|
11
|
+
* --role provider|aggregator|client
|
|
12
|
+
* --name <human-name>
|
|
13
|
+
* --nostr-pubkey <hex64>
|
|
14
|
+
* --nostr-privkey <hex64> (optional; otherwise generated)
|
|
15
|
+
* --p2p-port <n> TCP port for peer connections
|
|
16
|
+
* --address <host> Address to advertise (blank = don't advertise)
|
|
17
|
+
* --no-advertise Don't advertise an address or port at all
|
|
18
|
+
* --force Overwrite existing config
|
|
19
|
+
* --help
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import crypto from 'node:crypto';
|
|
23
|
+
import os from 'node:os';
|
|
24
|
+
|
|
25
|
+
import { getConfigPath, loadConfig, saveConfig } from '../lib/config.js';
|
|
26
|
+
import { question } from '../lib/prompt.js';
|
|
27
|
+
import {
|
|
28
|
+
generateNostrKeyPair,
|
|
29
|
+
derivePublicKey,
|
|
30
|
+
keyPairIsValid,
|
|
31
|
+
isHex64
|
|
32
|
+
} from '../lib/identity.js';
|
|
33
|
+
import { DEFAULT_P2P_PORT, detectLocalAddress } from '../lib/network.js';
|
|
34
|
+
import {
|
|
35
|
+
applyFirewallRule,
|
|
36
|
+
describeFirewallHowTo,
|
|
37
|
+
detectFirewall,
|
|
38
|
+
printFirewallHint
|
|
39
|
+
} from '../lib/firewall.js';
|
|
40
|
+
import { detectGpus, formatGpuLine } from '@infernetprotocol/gpu';
|
|
41
|
+
|
|
42
|
+
const DEFAULT_CONTROL_PLANE = 'https://infernetprotocol.com';
|
|
43
|
+
|
|
44
|
+
const HELP = `infernet init — configure this node
|
|
45
|
+
|
|
46
|
+
Usage:
|
|
47
|
+
infernet init [flags]
|
|
48
|
+
|
|
49
|
+
Flags:
|
|
50
|
+
--url <url> Control-plane base URL (default: ${DEFAULT_CONTROL_PLANE})
|
|
51
|
+
--role <provider|aggregator|client>
|
|
52
|
+
--name <human-name>
|
|
53
|
+
--nostr-pubkey <hex64> Nostr public key (hex, 64 chars)
|
|
54
|
+
--nostr-privkey <hex64> Nostr private key (hex, 64 chars); generated if omitted
|
|
55
|
+
--p2p-port <n> TCP port for peer connections (default ${DEFAULT_P2P_PORT})
|
|
56
|
+
--address <host> Address to advertise to peers (auto-detected if omitted)
|
|
57
|
+
--no-advertise Don't advertise an address or port at all
|
|
58
|
+
--skip-firewall-hint Don't print firewall instructions
|
|
59
|
+
--force Overwrite an existing config
|
|
60
|
+
--help Show this help
|
|
61
|
+
|
|
62
|
+
Nodes authenticate to the control plane with Nostr-signed requests. No
|
|
63
|
+
database credentials are stored in this config.
|
|
64
|
+
`;
|
|
65
|
+
|
|
66
|
+
const VALID_ROLES = new Set(['provider', 'aggregator', 'client']);
|
|
67
|
+
|
|
68
|
+
function makeNodeId(role) {
|
|
69
|
+
const slug = crypto.randomBytes(4).toString('hex');
|
|
70
|
+
return `${role}-${slug}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export default async function init(args) {
|
|
74
|
+
if (args.has('help') || args.has('h')) {
|
|
75
|
+
process.stdout.write(HELP);
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const existing = await loadConfig();
|
|
80
|
+
const yes = args.has('yes');
|
|
81
|
+
const force = args.has('force');
|
|
82
|
+
// A config is "complete" once it has both a Nostr keypair AND a
|
|
83
|
+
// control-plane URL.
|
|
84
|
+
//
|
|
85
|
+
// Behavior on re-run:
|
|
86
|
+
// --force → wipe + regenerate identity (last resort)
|
|
87
|
+
// --yes → upgrade in place: preserve keys + url + role,
|
|
88
|
+
// regenerate name if it matches a stale auto-
|
|
89
|
+
// generated pattern (so install.sh re-runs
|
|
90
|
+
// refresh the display name without losing keys)
|
|
91
|
+
// neither, complete → bail and ask for --force
|
|
92
|
+
// neither, partial → fill in the gaps
|
|
93
|
+
const hasKey = !!(existing?.node?.publicKey && existing?.node?.privateKey);
|
|
94
|
+
const hasUrl = !!existing?.controlPlane?.url;
|
|
95
|
+
const upgradeInPlace = existing && hasKey && hasUrl && yes && !force;
|
|
96
|
+
|
|
97
|
+
if (existing && hasKey && hasUrl && !force && !yes) {
|
|
98
|
+
process.stderr.write(
|
|
99
|
+
`Config already exists at ${getConfigPath()}. Re-run with --force to overwrite, or --yes to upgrade in place.\n`
|
|
100
|
+
);
|
|
101
|
+
return 1;
|
|
102
|
+
}
|
|
103
|
+
if (existing && !force && !upgradeInPlace) {
|
|
104
|
+
process.stdout.write(
|
|
105
|
+
`Found partial config at ${getConfigPath()} — finishing initialization.\n`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
if (upgradeInPlace) {
|
|
109
|
+
process.stdout.write(
|
|
110
|
+
`Upgrading existing config in place at ${getConfigPath()} (keys preserved).\n`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let url = args.get('url') ?? (upgradeInPlace ? existing.controlPlane.url : undefined);
|
|
115
|
+
let role = args.get('role') ?? (upgradeInPlace ? existing.node.role : undefined);
|
|
116
|
+
let name = args.get('name');
|
|
117
|
+
let pubkey = args.get('nostr-pubkey') ?? (upgradeInPlace ? existing.node.publicKey : undefined);
|
|
118
|
+
let privkey = args.get('nostr-privkey') ?? (upgradeInPlace ? existing.node.privateKey : undefined);
|
|
119
|
+
let portArg = args.get('p2p-port');
|
|
120
|
+
let addressArg = args.get('address');
|
|
121
|
+
const noAdvertise = args.has('no-advertise');
|
|
122
|
+
|
|
123
|
+
if (!url) {
|
|
124
|
+
url = await question('Control-plane URL', { default: DEFAULT_CONTROL_PLANE });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!role) {
|
|
128
|
+
role = (await question('Node role (provider|aggregator|client)', {
|
|
129
|
+
default: 'provider'
|
|
130
|
+
})).toLowerCase();
|
|
131
|
+
} else {
|
|
132
|
+
role = role.toLowerCase();
|
|
133
|
+
}
|
|
134
|
+
if (!VALID_ROLES.has(role)) {
|
|
135
|
+
process.stderr.write(
|
|
136
|
+
`Invalid role "${role}". Must be one of: provider, aggregator, client.\n`
|
|
137
|
+
);
|
|
138
|
+
return 1;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (privkey && !isHex64(privkey)) {
|
|
142
|
+
process.stderr.write('Nostr private key must be 64 hex characters.\n');
|
|
143
|
+
return 1;
|
|
144
|
+
}
|
|
145
|
+
if (pubkey && !isHex64(pubkey)) {
|
|
146
|
+
process.stderr.write('Nostr public key must be 64 hex characters.\n');
|
|
147
|
+
return 1;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (privkey && !pubkey) {
|
|
151
|
+
pubkey = derivePublicKey(privkey);
|
|
152
|
+
} else if (!privkey) {
|
|
153
|
+
const generated = generateNostrKeyPair();
|
|
154
|
+
privkey = generated.privateKey;
|
|
155
|
+
pubkey = generated.publicKey;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (!keyPairIsValid(pubkey, privkey)) {
|
|
159
|
+
process.stderr.write('Nostr pubkey does not match privkey (failed BIP-340 derivation check).\n');
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// P2P port — default 46337. Only prompt when neither flag nor env is set.
|
|
164
|
+
let port = Number.parseInt(portArg ?? '', 10);
|
|
165
|
+
if (!Number.isFinite(port) || port <= 0) port = DEFAULT_P2P_PORT;
|
|
166
|
+
|
|
167
|
+
const address = noAdvertise ? null : (addressArg ?? await detectLocalAddress());
|
|
168
|
+
|
|
169
|
+
// Generate nodeId BEFORE defaulting the name so we can append its
|
|
170
|
+
// hash slug to the name (gives "user@host:0f44326c"-style identifiers
|
|
171
|
+
// that are both human-readable and unique across multiple nodes
|
|
172
|
+
// running on the same box).
|
|
173
|
+
const nodeId = existing?.node?.nodeId ?? makeNodeId(role);
|
|
174
|
+
const id = existing?.node?.id ?? null;
|
|
175
|
+
|
|
176
|
+
// Compute the default before the existing-name check so we can
|
|
177
|
+
// also use it for stale-name detection.
|
|
178
|
+
const userPart = process.env.USER ?? (() => {
|
|
179
|
+
try { return os.userInfo().username; } catch { return null; }
|
|
180
|
+
})() ?? role;
|
|
181
|
+
const slug = nodeId.includes('-') ? nodeId.split('-').slice(1).join('-') : nodeId.slice(0, 8);
|
|
182
|
+
const hostname = os.hostname();
|
|
183
|
+
const defaultName = `${userPart}@${hostname}:${slug}`;
|
|
184
|
+
|
|
185
|
+
// A name "looks auto-generated" if it matches a pattern produced
|
|
186
|
+
// by a previous version of this CLI (just hostname; role@hostname
|
|
187
|
+
// without slug; the makeNodeId form). Operator-chosen names with
|
|
188
|
+
// their own structure are preserved as-is.
|
|
189
|
+
const isStaleAutoName = (n) => {
|
|
190
|
+
if (!n) return true;
|
|
191
|
+
if (n === hostname) return true;
|
|
192
|
+
if (n === `${role}@${hostname}`) return true;
|
|
193
|
+
if (/^(provider|aggregator|client)-[0-9a-f]{8}$/.test(n)) return true;
|
|
194
|
+
return false;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
if (!name) {
|
|
198
|
+
if (upgradeInPlace && existing?.node?.name && !isStaleAutoName(existing.node.name)) {
|
|
199
|
+
// Operator picked this name themselves — keep it.
|
|
200
|
+
name = existing.node.name;
|
|
201
|
+
} else {
|
|
202
|
+
// No name yet, OR existing name is a stale auto-default →
|
|
203
|
+
// regenerate as user@host:slug. Prompts in interactive mode;
|
|
204
|
+
// in --yes mode, question() returns the default so this is
|
|
205
|
+
// a silent self-heal.
|
|
206
|
+
name = await question('Human-readable node name', {
|
|
207
|
+
default: defaultName
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Merge with any existing config so engine.*, payment.*, and any
|
|
213
|
+
// other top-level sections survive re-running init or running it
|
|
214
|
+
// after `infernet setup`. Only the controlPlane and node fields
|
|
215
|
+
// that init manages are replaced.
|
|
216
|
+
const config = {
|
|
217
|
+
...(existing ?? {}),
|
|
218
|
+
controlPlane: { ...(existing?.controlPlane ?? {}), url },
|
|
219
|
+
node: {
|
|
220
|
+
...(existing?.node ?? {}),
|
|
221
|
+
id,
|
|
222
|
+
nodeId,
|
|
223
|
+
role,
|
|
224
|
+
name,
|
|
225
|
+
publicKey: pubkey,
|
|
226
|
+
privateKey: privkey,
|
|
227
|
+
address: noAdvertise ? null : (address ?? null),
|
|
228
|
+
port: noAdvertise ? null : port
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const written = await saveConfig(config);
|
|
233
|
+
process.stdout.write(`Wrote ${written}\n`);
|
|
234
|
+
process.stdout.write(`Control plane: ${url}\n`);
|
|
235
|
+
process.stdout.write(`Node id: ${nodeId}\n`);
|
|
236
|
+
process.stdout.write(`Role: ${role}\n`);
|
|
237
|
+
process.stdout.write(`Name: ${name}\n`);
|
|
238
|
+
process.stdout.write(`Pubkey: ${pubkey}\n`);
|
|
239
|
+
if (noAdvertise) {
|
|
240
|
+
process.stdout.write(`P2P: disabled (outbound-only)\n`);
|
|
241
|
+
} else {
|
|
242
|
+
process.stdout.write(`P2P: ${address ?? '(address not detected)'}:${port}\n`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// GPU detection — purely informational during init; the actual coarse
|
|
246
|
+
// capability is re-gathered on `register` and heartbeat.
|
|
247
|
+
try {
|
|
248
|
+
const gpus = await detectGpus();
|
|
249
|
+
if (gpus.length > 0) {
|
|
250
|
+
process.stdout.write(`GPUs: ${gpus.length} detected\n`);
|
|
251
|
+
for (const g of gpus) {
|
|
252
|
+
process.stdout.write(` - ${formatGpuLine(g)}\n`);
|
|
253
|
+
}
|
|
254
|
+
} else {
|
|
255
|
+
process.stdout.write('GPUs: none detected (CPU-only provider)\n');
|
|
256
|
+
}
|
|
257
|
+
} catch (err) {
|
|
258
|
+
process.stderr.write(`GPU detection failed: ${err?.message ?? err}\n`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (!args.has('skip-firewall-hint') && role !== 'client' && !noAdvertise) {
|
|
262
|
+
process.stdout.write('\n');
|
|
263
|
+
const detected = detectFirewall();
|
|
264
|
+
if (detected.length === 0 || process.platform !== 'linux') {
|
|
265
|
+
// Print-only: pf / netsh / no-detected — nothing safe to auto-apply.
|
|
266
|
+
printFirewallHint(port, 'init');
|
|
267
|
+
} else {
|
|
268
|
+
const tool = detected[0];
|
|
269
|
+
const { lines } = describeFirewallHowTo(port);
|
|
270
|
+
process.stdout.write(`-- firewall (init, port ${port}) --\n`);
|
|
271
|
+
process.stdout.write(`Detected: ${tool}\n`);
|
|
272
|
+
for (const line of lines.slice(0, 4)) process.stdout.write(`${line}\n`);
|
|
273
|
+
const yes =
|
|
274
|
+
args.has('yes') ||
|
|
275
|
+
args.has('confirm') ||
|
|
276
|
+
process.env.INFERNET_NONINTERACTIVE === '1';
|
|
277
|
+
let proceed = yes;
|
|
278
|
+
if (!yes) {
|
|
279
|
+
const ans = await question('Apply firewall rule now (will sudo)?', { default: 'y' });
|
|
280
|
+
proceed = ans.toLowerCase().startsWith('y');
|
|
281
|
+
}
|
|
282
|
+
if (proceed) {
|
|
283
|
+
try {
|
|
284
|
+
const result = await applyFirewallRule(port, { tool });
|
|
285
|
+
if (result.applied) {
|
|
286
|
+
process.stdout.write(`Firewall: ✓ rule applied via ${result.tool}\n`);
|
|
287
|
+
} else {
|
|
288
|
+
process.stdout.write(`Firewall: ! ${result.reason ?? 'skipped'}\n`);
|
|
289
|
+
}
|
|
290
|
+
} catch (err) {
|
|
291
|
+
process.stderr.write(`firewall rule failed: ${err?.message ?? err}\n`);
|
|
292
|
+
process.stderr.write('Re-run later or apply the command manually.\n');
|
|
293
|
+
}
|
|
294
|
+
} else {
|
|
295
|
+
process.stdout.write('Firewall: skipped — run `infernet firewall` to print the commands\n');
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
process.stdout.write('Next: run `infernet register` to announce this node.\n');
|
|
301
|
+
return 0;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export { HELP };
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `infernet login` — sign in to the control plane (device-code flow).
|
|
3
|
+
*
|
|
4
|
+
* Three modes:
|
|
5
|
+
* infernet login Open browser, poll for authorization,
|
|
6
|
+
* save bearer token to ~/.config/infernet/config.json
|
|
7
|
+
* infernet login --url <url> Change the control-plane URL (legacy use case;
|
|
8
|
+
* doesn't touch saved auth)
|
|
9
|
+
* infernet login --token <jwt> Paste a token directly (for headless setups)
|
|
10
|
+
* infernet login --status Show who's signed in
|
|
11
|
+
* infernet login --logout Forget the saved bearer
|
|
12
|
+
*
|
|
13
|
+
* The device-code flow:
|
|
14
|
+
* 1. POST <controlPlane>/api/auth/cli/start → { code, verify_url, poll_url }
|
|
15
|
+
* 2. Print verify_url; try to xdg-open / open / start it
|
|
16
|
+
* 3. User completes signup / signin in browser, lands on /auth/cli/<code>
|
|
17
|
+
* 4. CLI polls poll_url every 2s until status=authorized → save the token
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { spawn } from "node:child_process";
|
|
21
|
+
import { loadConfig, saveConfig, getConfigPath } from "../lib/config.js";
|
|
22
|
+
import pubkeyCommand from "./pubkey.js";
|
|
23
|
+
|
|
24
|
+
const HELP = `infernet login — sign in to the control plane
|
|
25
|
+
|
|
26
|
+
Usage:
|
|
27
|
+
infernet login Device-code login (opens browser, polls)
|
|
28
|
+
infernet login --url <url> Set controlPlane.url (no auth change)
|
|
29
|
+
infernet login --token <jwt> Save a paste-in token (skip browser flow)
|
|
30
|
+
infernet login --status Print current auth state
|
|
31
|
+
infernet login --logout Clear the saved bearer
|
|
32
|
+
infernet login --help
|
|
33
|
+
|
|
34
|
+
Notes:
|
|
35
|
+
- Auth tokens are HMAC-signed JWTs scoped to the CLI tier (IPIP-0003).
|
|
36
|
+
- Stored in ~/.config/infernet/config.json under auth.* (mode 0600).
|
|
37
|
+
- Token TTL is 5 years; re-run \`infernet login\` only if you rotate secrets.
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
function tryOpenBrowser(url) {
|
|
41
|
+
const opener =
|
|
42
|
+
process.platform === "darwin" ? "open" :
|
|
43
|
+
process.platform === "win32" ? "cmd" :
|
|
44
|
+
"xdg-open";
|
|
45
|
+
const args =
|
|
46
|
+
process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
47
|
+
try {
|
|
48
|
+
const child = spawn(opener, args, { stdio: "ignore", detached: true });
|
|
49
|
+
child.on("error", () => {});
|
|
50
|
+
child.unref?.();
|
|
51
|
+
} catch {
|
|
52
|
+
/* ignore — operator can copy/paste the URL */
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function decodeJwtPayload(token) {
|
|
57
|
+
try {
|
|
58
|
+
const parts = token.split(".");
|
|
59
|
+
if (parts.length !== 3) return null;
|
|
60
|
+
const json = Buffer.from(parts[1], "base64url").toString("utf8");
|
|
61
|
+
return JSON.parse(json);
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function saveAuth(config, { token, userId, email, expiresAt }) {
|
|
68
|
+
const next = {
|
|
69
|
+
...config,
|
|
70
|
+
auth: {
|
|
71
|
+
userId,
|
|
72
|
+
email: email ?? null,
|
|
73
|
+
bearerToken: token,
|
|
74
|
+
issuedAt: new Date().toISOString(),
|
|
75
|
+
expiresAt: expiresAt ?? null
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const path = await saveConfig(next);
|
|
79
|
+
return path;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Best-effort: after a successful login, if this CLI also holds a
|
|
84
|
+
* Nostr keypair (i.e. the user ran `infernet init` / `setup` already),
|
|
85
|
+
* claim that pubkey under the freshly-authenticated user. Failures are
|
|
86
|
+
* logged and ignored — `infernet pubkey link` can be re-run any time.
|
|
87
|
+
*/
|
|
88
|
+
async function autoLinkPubkey() {
|
|
89
|
+
const config = (await loadConfig()) ?? {};
|
|
90
|
+
const hasNode = !!(config?.node?.publicKey && config?.node?.privateKey && config?.node?.role);
|
|
91
|
+
const hasAuth = !!config?.auth?.bearerToken;
|
|
92
|
+
if (!hasNode || !hasAuth) return;
|
|
93
|
+
|
|
94
|
+
const fakeArgs = {
|
|
95
|
+
positional: ["link"],
|
|
96
|
+
flags: new Map(),
|
|
97
|
+
has() { return false; },
|
|
98
|
+
get() { return undefined; }
|
|
99
|
+
};
|
|
100
|
+
process.stdout.write("\nLinking this node's pubkey to your account...\n ");
|
|
101
|
+
try {
|
|
102
|
+
await pubkeyCommand(fakeArgs);
|
|
103
|
+
} catch (err) {
|
|
104
|
+
process.stderr.write(`(auto-link failed: ${err?.message ?? err}; run \`infernet pubkey link\` manually.)\n`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function statusCmd(config) {
|
|
109
|
+
const a = config?.auth;
|
|
110
|
+
if (!a?.bearerToken) {
|
|
111
|
+
process.stdout.write("Not signed in. Run `infernet login` to start.\n");
|
|
112
|
+
return 1;
|
|
113
|
+
}
|
|
114
|
+
process.stdout.write(`Signed in as ${a.email ?? "(no email)"}\n`);
|
|
115
|
+
process.stdout.write(` user id: ${a.userId}\n`);
|
|
116
|
+
process.stdout.write(` issued: ${a.issuedAt}\n`);
|
|
117
|
+
if (a.expiresAt) process.stdout.write(` expires: ${a.expiresAt}\n`);
|
|
118
|
+
process.stdout.write(` config: ${getConfigPath()}\n`);
|
|
119
|
+
return 0;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function logoutCmd(config) {
|
|
123
|
+
if (!config?.auth) {
|
|
124
|
+
process.stdout.write("Already signed out.\n");
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
const next = { ...config };
|
|
128
|
+
delete next.auth;
|
|
129
|
+
await saveConfig(next);
|
|
130
|
+
process.stdout.write("Signed out. Bearer cleared from local config.\n");
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function urlCmd(config, newUrl) {
|
|
135
|
+
const next = {
|
|
136
|
+
...config,
|
|
137
|
+
controlPlane: { ...(config?.controlPlane ?? {}), url: String(newUrl) }
|
|
138
|
+
};
|
|
139
|
+
const path = await saveConfig(next);
|
|
140
|
+
process.stdout.write(`Control plane: ${newUrl}\nConfig: ${path}\n`);
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function tokenCmd(config, tokenStr) {
|
|
145
|
+
const claims = decodeJwtPayload(tokenStr);
|
|
146
|
+
if (!claims || !claims.sub) {
|
|
147
|
+
process.stderr.write("error: token doesn't look like a CLI JWT\n");
|
|
148
|
+
return 2;
|
|
149
|
+
}
|
|
150
|
+
const path = await saveAuth(config, {
|
|
151
|
+
token: tokenStr,
|
|
152
|
+
userId: claims.sub,
|
|
153
|
+
email: claims.email ?? null,
|
|
154
|
+
expiresAt: claims.exp ? new Date(claims.exp * 1000).toISOString() : null
|
|
155
|
+
});
|
|
156
|
+
process.stdout.write(`✓ Signed in${claims.email ? ` as ${claims.email}` : ""}\n saved to ${path}\n`);
|
|
157
|
+
await autoLinkPubkey();
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function deviceCodeFlow(config) {
|
|
162
|
+
const baseUrl = config?.controlPlane?.url;
|
|
163
|
+
if (!baseUrl) {
|
|
164
|
+
process.stderr.write(
|
|
165
|
+
"error: no control plane configured. Run `infernet init` first (or pass --url <url>).\n"
|
|
166
|
+
);
|
|
167
|
+
return 1;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
let startResp;
|
|
171
|
+
try {
|
|
172
|
+
const res = await fetch(new URL("/api/auth/cli/start", baseUrl), {
|
|
173
|
+
method: "POST",
|
|
174
|
+
headers: { accept: "application/json" }
|
|
175
|
+
});
|
|
176
|
+
if (!res.ok) {
|
|
177
|
+
process.stderr.write(`error: /api/auth/cli/start → HTTP ${res.status}\n`);
|
|
178
|
+
return 1;
|
|
179
|
+
}
|
|
180
|
+
startResp = await res.json();
|
|
181
|
+
} catch (err) {
|
|
182
|
+
process.stderr.write(`error: could not reach ${baseUrl}: ${err?.message ?? err}\n`);
|
|
183
|
+
return 1;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const verifyUrl = startResp.verify_url;
|
|
187
|
+
const pollUrl = new URL(startResp.poll_url, baseUrl).toString();
|
|
188
|
+
|
|
189
|
+
process.stdout.write(`\nOpen this URL to sign in:\n ${verifyUrl}\n`);
|
|
190
|
+
process.stdout.write(`(expires ${startResp.expires_at})\n\n`);
|
|
191
|
+
tryOpenBrowser(verifyUrl);
|
|
192
|
+
process.stdout.write("Waiting for browser sign-in...\n");
|
|
193
|
+
|
|
194
|
+
const startedAt = Date.now();
|
|
195
|
+
const timeoutMs = 10 * 60 * 1000;
|
|
196
|
+
let dotted = 0;
|
|
197
|
+
while (Date.now() - startedAt < timeoutMs) {
|
|
198
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
199
|
+
let body;
|
|
200
|
+
try {
|
|
201
|
+
const res = await fetch(pollUrl, { headers: { accept: "application/json" } });
|
|
202
|
+
if (!res.ok) {
|
|
203
|
+
if (res.status === 404) {
|
|
204
|
+
process.stderr.write("\nerror: session not found server-side\n");
|
|
205
|
+
return 1;
|
|
206
|
+
}
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
body = await res.json();
|
|
210
|
+
} catch {
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (body.status === "expired") {
|
|
215
|
+
process.stderr.write("\nLogin link expired. Run `infernet login` again.\n");
|
|
216
|
+
return 1;
|
|
217
|
+
}
|
|
218
|
+
if (body.status === "consumed") {
|
|
219
|
+
process.stderr.write("\nThis login session was already consumed.\n");
|
|
220
|
+
return 1;
|
|
221
|
+
}
|
|
222
|
+
if (body.status === "authorized" && body.token) {
|
|
223
|
+
const path = await saveAuth(config, {
|
|
224
|
+
token: body.token,
|
|
225
|
+
userId: body.userId,
|
|
226
|
+
email: body.email ?? null,
|
|
227
|
+
expiresAt: body.expiresAt ?? null
|
|
228
|
+
});
|
|
229
|
+
process.stdout.write(`\n✓ Signed in${body.email ? ` as ${body.email}` : ""}\n saved to ${path}\n`);
|
|
230
|
+
await autoLinkPubkey();
|
|
231
|
+
return 0;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// pending — show a heartbeat dot every 6 seconds
|
|
235
|
+
dotted += 1;
|
|
236
|
+
if (dotted % 3 === 0) process.stdout.write(".");
|
|
237
|
+
}
|
|
238
|
+
process.stderr.write("\nLogin timed out after 10 minutes.\n");
|
|
239
|
+
return 1;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Obtain a bearer token autonomously using the node's Nostr keypair.
|
|
244
|
+
* Hits POST /api/auth/cli/node-token — no browser, no prompts.
|
|
245
|
+
* Returns 0 on success, non-zero on failure.
|
|
246
|
+
*/
|
|
247
|
+
export async function nodeTokenLogin(config) {
|
|
248
|
+
const baseUrl = config?.controlPlane?.url;
|
|
249
|
+
const privKey = config?.node?.privateKey;
|
|
250
|
+
const pubKey = config?.node?.publicKey;
|
|
251
|
+
if (!baseUrl || !privKey || !pubKey) return 1;
|
|
252
|
+
|
|
253
|
+
let res;
|
|
254
|
+
try {
|
|
255
|
+
const { signRequest } = await import("@infernetprotocol/auth");
|
|
256
|
+
const path = "/api/auth/cli/node-token";
|
|
257
|
+
const url = new URL(path, baseUrl).toString();
|
|
258
|
+
const body = JSON.stringify({ ts: Date.now() });
|
|
259
|
+
const { header } = signRequest({ method: "POST", path, body, privateKey: privKey, publicKey: pubKey });
|
|
260
|
+
res = await fetch(url, {
|
|
261
|
+
method: "POST",
|
|
262
|
+
headers: { "X-Infernet-Auth": header, "content-type": "application/json" },
|
|
263
|
+
body
|
|
264
|
+
});
|
|
265
|
+
} catch (err) {
|
|
266
|
+
process.stderr.write(`[login] node-token fetch failed: ${err?.message ?? err}\n`);
|
|
267
|
+
return 1;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (!res.ok) {
|
|
271
|
+
const msg = await res.text().catch(() => res.status);
|
|
272
|
+
process.stderr.write(`[login] node-token → ${res.status}: ${msg}\n`);
|
|
273
|
+
return 1;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const data = await res.json();
|
|
277
|
+
await saveAuth(config, {
|
|
278
|
+
token: data.token,
|
|
279
|
+
userId: data.userId,
|
|
280
|
+
email: data.email ?? null,
|
|
281
|
+
expiresAt: data.expiresAt ?? null
|
|
282
|
+
});
|
|
283
|
+
process.stdout.write(`[login] bearer token refreshed (expires ${data.expiresAt})\n`);
|
|
284
|
+
return 0;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export default async function login(args) {
|
|
288
|
+
if (args.has("help") || args.has("h")) {
|
|
289
|
+
process.stdout.write(HELP);
|
|
290
|
+
return 0;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const config = (await loadConfig()) ?? {};
|
|
294
|
+
|
|
295
|
+
if (args.has("status")) return statusCmd(config);
|
|
296
|
+
if (args.has("logout")) return logoutCmd(config);
|
|
297
|
+
|
|
298
|
+
const newUrl = args.get("url");
|
|
299
|
+
if (newUrl) return urlCmd(config, newUrl);
|
|
300
|
+
|
|
301
|
+
const tokenArg = args.get("token");
|
|
302
|
+
if (tokenArg) return tokenCmd(config, String(tokenArg));
|
|
303
|
+
|
|
304
|
+
return deviceCodeFlow(config);
|
|
305
|
+
}
|