@networkbase/cli 1.0.3 → 2.0.0-next.3

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/lib/api.mjs ADDED
@@ -0,0 +1,163 @@
1
+ // Talking to NetworkBase (report A12.1, A12.2, A2.4, A2.6). Retries reads and keyed writes on network errors,
2
+ // 408/429/5xx with backoff and Retry-After; every write carries one Idempotency-Key for all its attempts, so a
3
+ // retry never writes twice (finding 72). Errors come back as CliError with the server's code and a next step.
4
+ import crypto from "node:crypto";
5
+
6
+ import { CliError } from "./errors.mjs";
7
+
8
+ const RETRY_STATUS = new Set([408, 429, 500, 502, 503, 504]);
9
+ const MAX_ATTEMPTS = 5;
10
+ const RETRY_BUDGET_MS = 60_000;
11
+
12
+ const sleep = (/** @type {number} */ ms) => new Promise((resolve) => setTimeout(resolve, ms));
13
+
14
+ /** Next step for common server codes (A4.7: every error ends with what to do). */
15
+ const HINTS = /** @type {Record<string, string>} */ ({
16
+ NEEDS_CONFIRMATION: "Show this to the person; if they agree, run the same command again with --confirm <token> (in --json: error.details.confirmToken)",
17
+ UNAUTHORIZED: "Run nb login",
18
+ SCOPE_MISSING: "This token can't do that; sign in again with nb login, or make a token with more access in Settings → Integrations",
19
+ FORBIDDEN: "Check you're a member of this workspace with nb whoami",
20
+ RATE_LIMITED: "Wait a minute and try again",
21
+ VERSION_CONFLICT: "Run nb pull, then push again — or nb resolve <path>",
22
+ SECRET_DETECTED: "Remove the secret, or push again with --confirm-secrets if it's safe to share",
23
+ CLIENT_TOO_OLD: "Update: npm i -g @networkbase/cli@latest (or use npx @networkbase/cli@latest)",
24
+ });
25
+
26
+ /**
27
+ * @param {{ origin: string, token: string | null, version: string, fetchImpl?: typeof fetch, onRetry?: (info: { attempt: number, waitMs: number, reason: string }) => void, confirmToken?: string | null, onUndo?: (u: { token: string, method: string, path: string, summary: string | null }) => void }} options
28
+ * confirmToken: the person's yes for a held agent change (sent as X-NB-Confirm); onUndo: called with every undo
29
+ * token a write returns, so `nb undo` can use it (report A2.8, A2.9).
30
+ */
31
+ export function createApi({ origin, token, version, fetchImpl = fetch, onRetry, confirmToken = null, onUndo }) {
32
+ /**
33
+ * @param {"GET" | "POST" | "PUT" | "PATCH" | "DELETE"} method
34
+ * @param {string} path
35
+ * @param {{ query?: Record<string, string | number | boolean | undefined | null>, body?: unknown, key?: string, timeoutMs?: number, auth?: boolean, headers?: Record<string, string> }} [options]
36
+ */
37
+ async function request(method, path, options = {}) {
38
+ if (options.auth !== false && !token) {
39
+ throw new CliError("NOT_SIGNED_IN", `You're not signed in to ${new URL(origin).host}`, { hint: "Run nb login" });
40
+ }
41
+ const url = new URL(path, origin);
42
+ for (const [k, v] of Object.entries(options.query ?? {})) if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
43
+ const body = options.body === undefined ? undefined : JSON.stringify(options.body);
44
+ const key = method === "GET" ? null : options.key ?? crypto.randomUUID();
45
+ const timeoutMs = options.timeoutMs ?? 20_000 + Math.ceil((body?.length ?? 0) / (256 * 1024)) * 1000;
46
+ /** @type {Record<string, string>} */
47
+ const headers = {
48
+ accept: "application/json",
49
+ "user-agent": `networkbase-cli/${version} (${process.platform}-${process.arch}; node ${process.versions.node})`,
50
+ "x-nb-client": `cli/${version}`,
51
+ // Kept for the 1.x session table's device details.
52
+ "x-extension-version": version,
53
+ "x-editor-host": "cli",
54
+ "x-editor-name": "NetworkBase CLI",
55
+ "x-editor-platform": `${process.platform}-${process.arch}`,
56
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
57
+ ...(token && options.auth !== false ? { authorization: `Bearer ${token}` } : {}),
58
+ ...(key ? { "idempotency-key": key } : {}),
59
+ ...(confirmToken && method !== "GET" ? { "x-nb-confirm": confirmToken } : {}),
60
+ ...options.headers,
61
+ };
62
+
63
+ const started = Date.now();
64
+ let lastReason = "";
65
+ for (let attempt = 1; ; attempt++) {
66
+ /** @type {Response} */
67
+ let response;
68
+ try {
69
+ response = await fetchImpl(url, { method, headers, body, signal: AbortSignal.timeout(timeoutMs) });
70
+ } catch (error) {
71
+ lastReason = describeNetworkError(error, timeoutMs);
72
+ if (attempt < MAX_ATTEMPTS && Date.now() - started < RETRY_BUDGET_MS) {
73
+ await backoff(attempt, null, lastReason);
74
+ continue;
75
+ }
76
+ throw new CliError("OFFLINE", `Can't reach ${url.host}: ${lastReason}`, { hint: "Check your connection, or run nb doctor" });
77
+ }
78
+
79
+ if (RETRY_STATUS.has(response.status) && attempt < MAX_ATTEMPTS && Date.now() - started < RETRY_BUDGET_MS) {
80
+ lastReason = `HTTP ${response.status}`;
81
+ await backoff(attempt, response.headers.get("retry-after"), lastReason);
82
+ continue;
83
+ }
84
+ if (response.status === 304) return { notModified: true };
85
+ const text = await response.text();
86
+ /** @type {any} */
87
+ let payload = null;
88
+ try {
89
+ payload = text ? JSON.parse(text) : null;
90
+ } catch {
91
+ if (!response.ok) throw new CliError("SERVER_ERROR", `${url.host} answered HTTP ${response.status}`, { status: response.status, hint: response.status >= 500 ? "Try again in a minute" : undefined });
92
+ throw new CliError("SERVER_ERROR", `${url.host} sent an answer the CLI can't read`, { status: response.status });
93
+ }
94
+ if (!response.ok || payload?.success === false) {
95
+ const code = response.status === 401 ? "UNAUTHORIZED" : payload?.errorCode ?? `HTTP_${response.status}`;
96
+ const message = payload?.message ?? `${url.host} answered HTTP ${response.status}`;
97
+ throw new CliError(code, message, { status: response.status, details: payload?.details, hint: HINTS[code] });
98
+ }
99
+ const data = payload?.data !== undefined ? payload.data : payload;
100
+ if (method !== "GET" && data && typeof data.undoToken === "string") onUndo?.({ token: data.undoToken, method, path: url.pathname, summary: typeof data.undone === "string" ? data.undone : null });
101
+ return data;
102
+ }
103
+
104
+ /** @param {number} attempt @param {string | null} retryAfter @param {string} reason */
105
+ async function backoff(attempt, retryAfter, reason) {
106
+ const fromHeader = retryAfter ? (/^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now()) : NaN;
107
+ const waitMs = Number.isFinite(fromHeader) && fromHeader > 0 ? Math.min(fromHeader, 30_000) : Math.round(500 * 2 ** (attempt - 1) * (0.5 + Math.random()));
108
+ onRetry?.({ attempt, waitMs, reason });
109
+ await sleep(waitMs);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * A streamed download (file bytes), retried on network errors and 5xx like any read.
115
+ * @param {string} path @param {Record<string, string>} query
116
+ * @returns {Promise<Response>}
117
+ */
118
+ async function download(path, query) {
119
+ if (!token) throw new CliError("NOT_SIGNED_IN", `You're not signed in to ${new URL(origin).host}`, { hint: "Run nb login" });
120
+ const url = new URL(path, origin);
121
+ for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
122
+ const started = Date.now();
123
+ for (let attempt = 1; ; attempt++) {
124
+ try {
125
+ const response = await fetchImpl(url, { headers: { authorization: `Bearer ${token}`, "user-agent": `networkbase-cli/${version}`, "x-nb-client": `cli/${version}` }, signal: AbortSignal.timeout(10 * 60_000) });
126
+ if (response.ok) return response;
127
+ if (!RETRY_STATUS.has(response.status) || attempt >= MAX_ATTEMPTS || Date.now() - started > RETRY_BUDGET_MS) {
128
+ const payload = /** @type {any} */ (await response.json().catch(() => null));
129
+ throw new CliError(payload?.errorCode ?? `HTTP_${response.status}`, payload?.message ?? `Download failed (HTTP ${response.status})`, { status: response.status });
130
+ }
131
+ } catch (error) {
132
+ if (error instanceof CliError) throw error;
133
+ if (attempt >= MAX_ATTEMPTS || Date.now() - started > RETRY_BUDGET_MS) throw new CliError("OFFLINE", `Can't reach ${url.host}: ${describeNetworkError(error, 600_000)}`, { hint: "Check your connection" });
134
+ }
135
+ await sleep(Math.round(500 * 2 ** (attempt - 1) * (0.5 + Math.random())));
136
+ }
137
+ }
138
+
139
+ return {
140
+ origin,
141
+ request,
142
+ download,
143
+ /** @param {string} path @param {Parameters<typeof request>[2]} [o] */
144
+ get: (path, o) => request("GET", path, o),
145
+ /** @param {string} path @param {unknown} body @param {Parameters<typeof request>[2]} [o] */
146
+ post: (path, body, o) => request("POST", path, { ...o, body }),
147
+ /** @param {string} path @param {unknown} body @param {Parameters<typeof request>[2]} [o] */
148
+ patch: (path, body, o) => request("PATCH", path, { ...o, body }),
149
+ };
150
+ }
151
+
152
+ /** @param {unknown} error @param {number} timeoutMs */
153
+ function describeNetworkError(error, timeoutMs) {
154
+ const e = /** @type {any} */ (error);
155
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") return `no answer after ${Math.round(timeoutMs / 1000)} s`;
156
+ const code = e?.cause?.code ?? e?.code;
157
+ if (code === "ENOTFOUND") return "the server name doesn't resolve";
158
+ if (code === "ECONNREFUSED") return "connection refused";
159
+ if (code === "UNABLE_TO_GET_ISSUER_CERT_LOCALLY" || code === "SELF_SIGNED_CERT_IN_CHAIN") return "your network's certificate isn't trusted (set NODE_EXTRA_CA_CERTS)";
160
+ return code ? String(code) : e?.message ?? "network error";
161
+ }
162
+
163
+ /** @typedef {ReturnType<typeof createApi>} Api */
package/lib/args.mjs ADDED
@@ -0,0 +1,140 @@
1
+ // Command lookup, strict flag parsing and help (report A4.2, A4.6). Uses Node's util.parseArgs; unknown
2
+ // flags and commands are errors with a "did you mean", never silently ignored (finding 81).
3
+ import { parseArgs } from "node:util";
4
+
5
+ import { ALIASES, COMMANDS, GLOBAL_FLAGS, REMOVED } from "./commands/table.mjs";
6
+ import { CliError, usage } from "./errors.mjs";
7
+
8
+ /** @typedef {import("./commands/table.mjs").CommandSpec} CommandSpec */
9
+
10
+ /** @param {string} a @param {string} b */
11
+ function distance(a, b) {
12
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
13
+ for (let j = 1; j <= b.length; j++) dp[0][j] = j;
14
+ for (let i = 1; i <= a.length; i++)
15
+ for (let j = 1; j <= b.length; j++)
16
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
17
+ return dp[a.length][b.length];
18
+ }
19
+
20
+ /** Closest candidate within 2 edits, or null. @param {string} word @param {string[]} candidates */
21
+ export function didYouMean(word, candidates) {
22
+ let best = null;
23
+ let bestScore = 3;
24
+ for (const c of candidates) {
25
+ const score = distance(word, c);
26
+ if (score < bestScore) { best = c; bestScore = score; }
27
+ }
28
+ return best;
29
+ }
30
+
31
+ const TASK_REF = /^(#?\d+|T-\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
32
+
33
+ /**
34
+ * Finds the command in argv. `nb task 4` is a shortcut for `nb task view 4`.
35
+ * @param {string[]} argv
36
+ * @returns {{ spec: CommandSpec | null, rest: string[], alias: { from: string, to: string } | null }}
37
+ */
38
+ export function resolveCommand(argv) {
39
+ const words = [];
40
+ for (const token of argv) {
41
+ if (token.startsWith("-")) break;
42
+ words.push(token);
43
+ }
44
+ if (words.length === 0) return { spec: null, rest: argv, alias: null };
45
+ for (let n = Math.min(3, words.length); n >= 1; n--) {
46
+ const name = words.slice(0, n).join(" ");
47
+ if (name in REMOVED) throw new CliError("USAGE", /** @type {Record<string, string>} */ (REMOVED)[name]);
48
+ const target = /** @type {Record<string, string>} */ (ALIASES)[name] ?? name;
49
+ const spec = COMMANDS.find((c) => c.name === target);
50
+ if (spec) return { spec, rest: argv.slice(n), alias: target !== name ? { from: name, to: target } : null };
51
+ }
52
+ if (words[0] === "task" && words[1] && TASK_REF.test(words[1])) {
53
+ return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "task view")), rest: argv.slice(1), alias: null };
54
+ }
55
+ const tried = words.slice(0, 2).join(" ");
56
+ const names = COMMANDS.map((c) => c.name);
57
+ const guess = didYouMean(tried, names) ?? didYouMean(words[0] ?? "", names);
58
+ throw new CliError("UNKNOWN_COMMAND", `nb ${tried} isn't a command`, { hint: guess ? `Did you mean: nb ${guess}?` : "See nb help" });
59
+ }
60
+
61
+ /**
62
+ * @param {CommandSpec} spec
63
+ * @param {string[]} rest
64
+ * @returns {{ positionals: string[], flags: Record<string, any> }}
65
+ */
66
+ export function parseFlags(spec, rest) {
67
+ const all = { ...GLOBAL_FLAGS, ...(spec.flags ?? {}) };
68
+ /** @type {import("node:util").ParseArgsConfig["options"]} */
69
+ const options = {};
70
+ for (const [name, f] of Object.entries(all)) {
71
+ options[name] = { type: f.type, ...(f.short ? { short: f.short } : {}), ...(f.multiple ? { multiple: true } : {}) };
72
+ }
73
+ try {
74
+ const { values, positionals } = parseArgs({ args: rest, options, allowPositionals: true, strict: true });
75
+ return { positionals, flags: values };
76
+ } catch (error) {
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ const unknown = /Unknown option '(-{1,2})([^']+)'/.exec(message);
79
+ if (unknown) {
80
+ const guess = didYouMean(unknown[2] ?? "", Object.keys(all));
81
+ throw new CliError("UNKNOWN_FLAG", `nb ${spec.name} has no ${unknown[1]}${unknown[2]} flag`, {
82
+ hint: guess ? `Did you mean --${guess}? See nb ${spec.name} --help` : `See nb ${spec.name} --help`,
83
+ });
84
+ }
85
+ throw usage(message.replace(/\. To specify a positional argument.*$/, ""), `See nb ${spec.name} --help`);
86
+ }
87
+ }
88
+
89
+ /** Help for one command (A4.6). @param {CommandSpec} spec */
90
+ export function commandHelp(spec) {
91
+ const flags = Object.entries({ ...(spec.flags ?? {}), ...GLOBAL_FLAGS }).filter(([name, f]) => name !== "help" && !f.hidden);
92
+ const label = (/** @type {string} */ name, /** @type {any} */ f) => `${f.short ? `-${f.short}, ` : " "}--${name}${f.type === "string" ? ` <${f.valueName ?? "value"}>` : ""}`;
93
+ const w = Math.max(...flags.map(([n, f]) => label(n, f).length));
94
+ const lines = [`nb ${spec.name} — ${spec.summary}`, "", "Usage", ` ${spec.usage}`, "", "Flags"];
95
+ for (const [name, f] of flags) lines.push(` ${label(name, f).padEnd(w)} ${f.describe}`);
96
+ if (spec.examples?.length) lines.push("", "Examples", ...spec.examples.map((e) => ` ${e}`));
97
+ if (spec.exit?.length) lines.push("", `Exit codes ${spec.exit.map((code) => `${code} ${EXIT_WORDS[code] ?? ""}`.trim()).join(" · ")}`);
98
+ return lines.join("\n");
99
+ }
100
+
101
+ const EXIT_WORDS = /** @type {Record<number, string>} */ ({ 0: "ok", 1: "error", 2: "usage", 3: "not signed in", 4: "conflict", 5: "blocked", 6: "needs input", 7: "needs confirmation", 8: "offline (queued)" });
102
+
103
+ /** Words wrapped to `width` columns. @param {string} text @param {number} width */
104
+ const wrap = (text, width) => text.split(" ").reduce((/** @type {string[]} */ out, word) => {
105
+ const last = out.at(-1);
106
+ if (last !== undefined && last.length + 1 + word.length <= width) out[out.length - 1] = `${last} ${word}`;
107
+ else out.push(word);
108
+ return out;
109
+ }, []);
110
+
111
+ /** Overview help: every command by group, summaries wrapped to the terminal. @param {number} [columns] */
112
+ export function overviewHelp(columns = 80) {
113
+ const groups = new Map();
114
+ for (const c of COMMANDS) {
115
+ if (c.hidden) continue;
116
+ if (!groups.has(c.group)) groups.set(c.group, []);
117
+ groups.get(c.group).push(c);
118
+ }
119
+ const w = Math.max(...COMMANDS.map((c) => c.name.length));
120
+ const lines = ["NetworkBase CLI", "", "Usage", " nb <command> [flags]", ""];
121
+ for (const [group, cmds] of groups) {
122
+ lines.push(group);
123
+ for (const c of cmds) {
124
+ const [first = "", ...rest] = wrap(c.summary, Math.max(16, (columns || 80) - w - 4));
125
+ lines.push(` ${c.name.padEnd(w)} ${first}`, ...rest.map((l) => ` ${" ".repeat(w)} ${l}`));
126
+ }
127
+ lines.push("");
128
+ }
129
+ lines.push(...wrap("Every command takes --json, --quiet, --plain and --help.", columns || 80), "Docs: https://networkbase.in/docs/cli");
130
+ return lines.join("\n");
131
+ }
132
+
133
+ /** The command table as data, for agents and completions (`nb help --json`). */
134
+ export function helpData() {
135
+ return {
136
+ commands: COMMANDS.filter((c) => !c.hidden).map((c) => ({ name: c.name, summary: c.summary, usage: c.usage, flags: Object.fromEntries(Object.entries(c.flags ?? {}).filter(([, f]) => !f.hidden)), examples: c.examples ?? [], exitCodes: c.exit ?? [0, 1] })),
137
+ globalFlags: GLOBAL_FLAGS,
138
+ aliases: ALIASES,
139
+ };
140
+ }
@@ -0,0 +1,293 @@
1
+ // login, logout, whoami (report A3.1, A3.9, A3.14, A3.16).
2
+ import crypto from "node:crypto";
3
+ import http from "node:http";
4
+ import os from "node:os";
5
+
6
+ import { createApi } from "../api.mjs";
7
+ import { listProfiles, saveProfile } from "../config.mjs";
8
+ import { CliError, usage } from "../errors.mjs";
9
+ import { storageWords } from "../keychain.mjs";
10
+ import { safe } from "../print/style.mjs";
11
+ import { openInBrowser } from "./misc.mjs";
12
+
13
+ /** @typedef {import("../context.mjs").Context} Context */
14
+
15
+ const TOKEN_SHAPE = /^nb_(dev|pat|agt)_[A-Za-z0-9_-]{16,}$/;
16
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
17
+
18
+ /** @param {Context} ctx @param {string} token */
19
+ async function whoIs(ctx, token) {
20
+ const api = createApi({ origin: ctx.profile.origin, token, version: ctx.version });
21
+ return /** @type {any} */ (await api.get("/api/v1/me"));
22
+ }
23
+
24
+ /** Saves a token under a profile after checking it works. @param {Context} ctx @param {string} profileName @param {string} token */
25
+ export async function saveToken(ctx, profileName, token) {
26
+ const me = await whoIs(ctx, token);
27
+ saveProfile(profileName, { origin: ctx.profile.origin, token, user: { id: me.user.id, username: me.user.username, email: me.user.email } }, ctx.env);
28
+ return me;
29
+ }
30
+
31
+ /** @param {Context} ctx @param {string} token @param {string} method */
32
+ async function finish(ctx, token, method) {
33
+ const me = await whoIs(ctx, token);
34
+ saveProfile(ctx.profile.name, { origin: ctx.profile.origin, token, user: { id: me.user.id, username: me.user.username, email: me.user.email } }, ctx.env);
35
+ ctx.out.result("nb.login/1", { method, origin: ctx.profile.origin, profile: ctx.profile.name, user: me.user, scopes: me.credential.scopes }, (d) =>
36
+ `${ctx.out.c.success(ctx.out.sym.done)} Signed in as ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)} on ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`);
37
+ }
38
+
39
+ /** Over SSH, or on Linux without a display, a browser can't open here, so the code flow is used (A3.1). @param {NodeJS.ProcessEnv} env */
40
+ const noBrowserHere = (env) => Boolean(env.SSH_CONNECTION || env.SSH_TTY || (process.platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY));
41
+
42
+ /**
43
+ * Sign-in with a code (report A3.1): the server gives a code, the person approves it at /device on any device
44
+ * where they're signed in, and this terminal polls until then (10 minutes at most).
45
+ * @param {Context} ctx
46
+ * @returns {Promise<string>}
47
+ */
48
+ export async function deviceLogin(ctx, agentName = /** @type {string | null} */ (null)) {
49
+ const api = createApi({ origin: ctx.profile.origin, token: null, version: ctx.version });
50
+ const agent = agentName ?? (typeof ctx.flags.agent === "string" ? ctx.flags.agent.trim() : "");
51
+ const start = /** @type {any} */ (await api.post("/api/v1/device/code", {
52
+ clientName: "NetworkBase CLI",
53
+ deviceName: os.hostname().slice(0, 120) || "terminal",
54
+ clientVersion: ctx.version,
55
+ platform: `${process.platform} ${process.arch}`,
56
+ type: agent ? "agent" : "device",
57
+ ...(agent ? { agentName: agent } : {}),
58
+ }, { auth: false }));
59
+ const { c } = ctx.out;
60
+ ctx.out.note(`Open ${c.bold(start.verificationUri)} and enter ${c.bold(start.userCode)}`);
61
+ ctx.out.note(c.muted(` or go straight to ${start.verificationUriComplete}`));
62
+ ctx.out.note(c.muted(`Waiting for you to approve… (code works for ${Math.round(start.expiresIn / 60)} minutes; Ctrl+C to cancel)`));
63
+ let interval = Number(start.interval ?? 5);
64
+ const until = Date.now() + Number(start.expiresIn ?? 600) * 1000;
65
+ while (Date.now() < until) {
66
+ await new Promise((resolve) => setTimeout(resolve, interval * 1000));
67
+ const res = /** @type {any} */ (await api.post("/api/v1/device/token", { deviceCode: start.deviceCode }, { auth: false }).catch((/** @type {unknown} */ error) => {
68
+ if (error instanceof CliError && error.status === 403) throw new CliError("CANCELLED", "Sign-in was denied in the browser");
69
+ if (error instanceof CliError && error.status === 410) throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
70
+ throw error;
71
+ }));
72
+ if (res.status === "approved") {
73
+ if (res.tokenType === "agent") ctx.out.note(c.muted("Signed in as an agent: this token only reaches the workspace you picked."));
74
+ return String(res.token);
75
+ }
76
+ if (res.status === "slow_down") interval += 5;
77
+ }
78
+ throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
79
+ }
80
+
81
+ /** @param {NodeJS.ReadStream} stream */
82
+ async function readAll(stream) {
83
+ const chunks = [];
84
+ for await (const chunk of stream) chunks.push(chunk);
85
+ return Buffer.concat(chunks).toString("utf8").trim();
86
+ }
87
+
88
+ /** @param {Context} ctx */
89
+ export async function login(ctx) {
90
+ if (ctx.env.NB_TOKEN || ctx.env.NETWORKBASE_TOKEN) {
91
+ throw usage("A token is set in the environment (NETWORKBASE_TOKEN), so nb already uses it", "Unset it to sign in with the browser");
92
+ }
93
+ if (ctx.flags["with-token"]) {
94
+ if (process.stdin.isTTY) throw usage("Pipe the token in: echo $TOKEN | nb login --with-token", "Tokens on the command line end up in shell history");
95
+ const token = await readAll(process.stdin);
96
+ if (!TOKEN_SHAPE.test(token)) throw usage("That doesn't look like a NetworkBase token (nb_pat_…, nb_dev_…)");
97
+ return finish(ctx, token, "token");
98
+ }
99
+ if (ctx.flags.device || ctx.flags.agent || noBrowserHere(ctx.env)) {
100
+ const token = await deviceLogin(ctx);
101
+ return finish(ctx, token, "device");
102
+ }
103
+ if (!process.stdin.isTTY && !ctx.env.NB_FORCE_BROWSER_LOGIN) {
104
+ throw new CliError("NEEDS_INPUT", "Browser sign-in needs a terminal", { hint: "Use nb login --device to sign in with a code; in CI: echo $TOKEN | nb login --with-token, or set NETWORKBASE_TOKEN" });
105
+ }
106
+ const token = await browserLogin(ctx);
107
+ return finish(ctx, token, "browser");
108
+ }
109
+
110
+ /**
111
+ * Loopback sign-in with PKCE (report A3.1, A3.14): a one-time listener on 127.0.0.1, an exact-origin CORS
112
+ * check, an escaped page, and a code that only works with this terminal's verifier.
113
+ * @param {Context} ctx
114
+ * @returns {Promise<string>}
115
+ */
116
+ function browserLogin(ctx) {
117
+ const origin = ctx.profile.origin;
118
+ const state = crypto.randomBytes(24).toString("hex");
119
+ const verifier = crypto.randomBytes(32).toString("base64url");
120
+ const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
121
+
122
+ return new Promise((resolve, reject) => {
123
+ let settled = false;
124
+ /** @type {NodeJS.Timeout} */
125
+ let timer;
126
+ const server = http.createServer(async (req, res) => {
127
+ const requestOrigin = req.headers.origin ?? "";
128
+ /** @type {Record<string, string>} */
129
+ const cors = requestOrigin === origin ? { "access-control-allow-origin": origin, "access-control-allow-methods": "GET", vary: "origin" } : {};
130
+ if (req.method === "OPTIONS") { res.writeHead(204, cors); res.end(); return; }
131
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
132
+ if (req.method !== "GET" || url.pathname !== "/auth-callback") { res.writeHead(404, cors); res.end(); return; }
133
+ const wantsJson = (req.headers.accept ?? "").includes("application/json") || req.headers["sec-fetch-mode"] === "cors";
134
+ const reply = (/** @type {number} */ status, /** @type {string} */ title, /** @type {string} */ text) => {
135
+ if (wantsJson) { res.writeHead(status, { ...cors, "content-type": "application/json" }); res.end(JSON.stringify({ ok: status === 200, message: text })); return; }
136
+ res.writeHead(status, { ...cors, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
137
+ res.end(page(title, text));
138
+ };
139
+ if (settled) return reply(410, "Already used", "This sign-in link was already used. Start again from your terminal.");
140
+ if (url.searchParams.get("error")) {
141
+ reply(400, "Sign-in cancelled", "You can close this window and try again from your terminal.");
142
+ return done(new CliError("CANCELLED", "Sign-in was cancelled in the browser"));
143
+ }
144
+ const code = url.searchParams.get("code");
145
+ if (!code || url.searchParams.get("state") !== state) return reply(400, "Not this sign-in", "This window doesn't match the sign-in your terminal started.");
146
+ try {
147
+ const api = createApi({ origin, token: null, version: ctx.version });
148
+ const exchanged = /** @type {any} */ (await api.post("/api/v1/extension/auth-code", { code, state, codeVerifier: verifier }, { auth: false }));
149
+ reply(200, "Signed in", "Your terminal is signed in. You can close this window.");
150
+ done(null, exchanged.token);
151
+ } catch (error) {
152
+ reply(400, "Sign-in failed", "Start again from your terminal.");
153
+ done(error);
154
+ }
155
+ });
156
+
157
+ /** @param {unknown} error @param {string} [token] */
158
+ function done(error, token) {
159
+ if (settled) return;
160
+ settled = true;
161
+ clearTimeout(timer);
162
+ server.close();
163
+ if (error) reject(error);
164
+ else resolve(/** @type {string} */ (token));
165
+ }
166
+
167
+ server.listen(0, "127.0.0.1", async () => {
168
+ const address = server.address();
169
+ const port = typeof address === "object" && address ? address.port : 0;
170
+ const authorize = new URL("/authorize", origin);
171
+ authorize.searchParams.set("callback", `http://127.0.0.1:${port}/auth-callback`);
172
+ authorize.searchParams.set("state", state);
173
+ authorize.searchParams.set("code_challenge", challenge);
174
+ authorize.searchParams.set("code_challenge_method", "S256");
175
+ const opened = await openInBrowser(authorize.toString());
176
+ ctx.out.note(`${opened ? "Opened your browser to sign in" : "Open this link to sign in"} on ${new URL(origin).host}:`);
177
+ ctx.out.note(` ${authorize.toString()}`);
178
+ ctx.out.note(ctx.out.c.muted("Waiting for you to approve… (Ctrl+C to cancel)"));
179
+ timer = setTimeout(() => done(new CliError("TIMEOUT", "Sign-in wasn't approved within 5 minutes", { hint: "Run nb login again" })), LOGIN_TIMEOUT_MS);
180
+ });
181
+ });
182
+ }
183
+
184
+ const ESCAPE = /** @type {Record<string, string>} */ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" });
185
+ /** @param {string} s */
186
+ const esc = (s) => s.replace(/[&<>"']/g, (ch) => ESCAPE[ch] ?? ch);
187
+ /** One small page, every value escaped (finding 35). @param {string} title @param {string} text */
188
+ const page = (title, text) =>
189
+ `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${esc(title)} · NetworkBase</title>` +
190
+ `<body style="font:15px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:Canvas;color:CanvasText">` +
191
+ `<main style="max-width:420px;padding:24px;text-align:center"><h1 style="font-size:18px">${esc(title)}</h1><p>${esc(text)}</p></main>`;
192
+
193
+ /** @param {Context} ctx */
194
+ export async function logout(ctx) {
195
+ if (ctx.flags.all) {
196
+ // Signing out everywhere revokes every device and agent; that needs the browser's fresh check (report A3.9).
197
+ const url = `${ctx.profile.origin}/settings?tab=integrations`;
198
+ const opened = await openInBrowser(url);
199
+ return ctx.out.result("nb.logout.all/1", { url, opened }, (d) => [`${d.opened ? "Opened" : "Open"} ${d.url}`, ctx.out.c.muted(" Choose \"Sign out all devices\" there; it asks you to confirm it's you. Or revoke one with nb token revoke <id>.")]);
200
+ }
201
+ if (!ctx.profile.token) throw new CliError("NOT_SIGNED_IN", `You're not signed in to ${new URL(ctx.profile.origin).host}`);
202
+ if (ctx.profile.profile?.source === "env") throw usage("The token comes from NETWORKBASE_TOKEN; unset it to sign out");
203
+ let revoked = true;
204
+ /** @type {string | null} */
205
+ let reason = null;
206
+ try {
207
+ await ctx.api.post("/api/v1/extension/session", {});
208
+ } catch (error) {
209
+ revoked = false;
210
+ reason = error instanceof Error ? error.message : String(error);
211
+ }
212
+ saveProfile(ctx.profile.name, null, ctx.env);
213
+ // Honest about what happened (finding 42): local sign-out always works; server revocation may not.
214
+ ctx.out.result("nb.logout/1", { revoked, signedOutLocally: true, reason }, (d) =>
215
+ d.revoked ? `${ctx.out.c.success(ctx.out.sym.done)} Signed out and revoked this device's token` : [`${ctx.out.c.warning(ctx.out.sym.warn)} Signed out here, but the server didn't revoke the token: ${safe(d.reason)}`, ctx.out.c.muted(" Revoke it in Settings → Integrations → Signed-in devices")]);
216
+ }
217
+
218
+ /** @param {Context} ctx */
219
+ export async function whoami(ctx) {
220
+ if (ctx.flags.all) return whoamiAll(ctx);
221
+ const me = /** @type {any} */ (await ctx.api.get("/api/v1/me"));
222
+ const data = { origin: ctx.profile.origin, profile: ctx.profile.name, tokenSource: ctx.profile.profile?.source ?? null, storage: ctx.profile.profile?.storage ?? "file", ...me };
223
+ ctx.out.result("nb.whoami/1", data, (d) => [
224
+ `${ctx.out.c.brand(ctx.out.sym.brand)} ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)}${d.user.fullName ? ` · ${safe(d.user.fullName)}` : ""}`,
225
+ ` server ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`,
226
+ ` token ${d.credential.type ? `${d.credential.type === "agent" ? "agent" : d.credential.type === "pat" ? "personal access" : "device"} · ` : ""}${d.tokenSource === "env" ? "from NETWORKBASE_TOKEN" : `kept in ${storageWords(d.storage)}`} · ${d.credential.scopes.length} permissions${d.credential.workspaceId ? " · one workspace only" : ""}`,
227
+ ` files up to ${Math.round(d.limits.largestFileBytes / 1024 / 1024)} MB each`,
228
+ ...(ctx.flags.verbose ? [` can ${d.credential.scopes.join(", ")}`] : []),
229
+ ]);
230
+ }
231
+
232
+ /** Every saved profile with who it is and where (`nb whoami --all`, report A3.5). @param {Context} ctx */
233
+ export async function whoamiAll(ctx) {
234
+ const profiles = Object.entries(listProfiles(ctx.env));
235
+ const rows = [];
236
+ for (const [name, p] of profiles) {
237
+ const { currentProfile } = await import("../config.mjs");
238
+ const prof = currentProfile({ flags: { profile: name, "api-url": p.origin }, env: { ...ctx.env, NB_TOKEN: "", NETWORKBASE_TOKEN: "" } });
239
+ let user = p.user?.username ?? p.user?.email ?? null;
240
+ let ok = false;
241
+ if (prof.token) {
242
+ try {
243
+ const me = /** @type {any} */ (await createApi({ origin: p.origin, token: prof.token, version: ctx.version }).get("/api/v1/me"));
244
+ user = me.user.username ?? me.user.email ?? user;
245
+ ok = true;
246
+ } catch {
247
+ ok = false;
248
+ }
249
+ }
250
+ rows.push({ profile: name, server: new URL(p.origin).host, user, signedIn: ok, storage: p.storage ?? "file", current: name === ctx.profile.name });
251
+ }
252
+ ctx.out.result("nb.whoami.all/1", { profiles: rows }, (d) =>
253
+ d.profiles.length
254
+ ? ctx.out.table([
255
+ { title: "", value: (r) => (r.current ? ctx.out.c.brand(ctx.out.sym.brand) : " ") },
256
+ { title: "Profile", value: (r) => safe(r.profile) },
257
+ { title: "Server", value: (r) => r.server, flex: true },
258
+ { title: "User", value: (r) => (r.user ? safe(r.user) : "—") },
259
+ { title: "Status", value: (r) => (r.signedIn ? ctx.out.c.success("signed in") : ctx.out.c.warning("sign in again")) },
260
+ ], d.profiles)
261
+ : "No saved sign-ins. Run nb login");
262
+ }
263
+
264
+ /** Your signed-in devices, agents and personal tokens (`nb token list`, report A3.9). @param {Context} ctx */
265
+ export async function tokenList(ctx) {
266
+ const { tokens } = /** @type {any} */ (await ctx.api.get("/api/v1/tokens"));
267
+ ctx.out.result("nb.token.list/1", { tokens }, (d) =>
268
+ d.tokens.length
269
+ ? ctx.out.table([
270
+ { title: "", value: (t) => (t.current ? ctx.out.c.brand(ctx.out.sym.brand) : " ") },
271
+ { title: "Id", value: (t) => String(t.id).slice(0, 8) },
272
+ { title: "Type", value: (t) => t.type },
273
+ { title: "Name", value: (t) => safe(t.type === "agent" && t.agentName ? `${t.agentName} on ${t.name}` : t.name), flex: true },
274
+ { title: "Workspace", value: (t) => (t.workspace ? safe(t.workspace) : "all"), optional: true },
275
+ { title: "Last used", value: (t) => (t.lastUsedAt ? String(t.lastUsedAt).slice(0, 10) : "—"), optional: true },
276
+ ], d.tokens)
277
+ : "No signed-in devices or tokens");
278
+ }
279
+
280
+ /** @param {Context} ctx */
281
+ export async function tokenRevoke(ctx) {
282
+ const id = ctx.positionals[0];
283
+ if (!id) throw usage("nb token revoke <id> (ids from nb token list)");
284
+ const { tokens } = /** @type {any} */ (await ctx.api.get("/api/v1/tokens"));
285
+ const hit = tokens.filter((/** @type {any} */ t) => String(t.id).startsWith(id));
286
+ if (hit.length !== 1) throw new CliError("NOT_FOUND", hit.length ? `${id} matches ${hit.length} tokens; give more of the id` : `No token ${id}`, { hint: "nb token list" });
287
+ const t = hit[0];
288
+ const { confirm } = await import("../tui/ask.mjs");
289
+ if (!(await confirm(ctx, { key: "revoke", question: `Revoke ${t.type === "agent" ? `${t.agentName ?? "the agent"} on ${t.name}` : t.name}${t.current ? " (this one: you'll be signed out here)" : ""}?`, yesLabel: "Revoke", defaultYes: false }))) return 130;
290
+ await ctx.api.post(`/api/v1/tokens/${t.id}/revoke`, {});
291
+ if (t.current) saveProfile(ctx.profile.name, null, ctx.env);
292
+ ctx.out.result("nb.token.revoke/1", { id: t.id, type: t.type }, () => `${ctx.out.c.success(ctx.out.sym.done)} Revoked`);
293
+ }