novence 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -75,13 +75,27 @@ novence checks [project] # Lighthouse / axe / link results for the last dep
75
75
  novence domains add <host> # attach a custom domain, prints the DNS records
76
76
  novence domains status # custom domain state
77
77
  novence keys list # API keys on the account
78
+ novence keys create <name> # extra named key (e.g. ci) that survives login --recover
78
79
  novence keys revoke <id> # revoke a key (--force to revoke the one in use)
79
80
  novence projects # list projects and their URLs
80
81
  novence login # sign in, verify email, or --recover a key
81
82
  novence claim # attach an email to an anonymous deploy
82
83
  novence whoami # plan, verification, usage against quota
84
+ novence dashboard # local account console (alias: novence console)
83
85
  ```
84
86
 
87
+ ## Dashboard
88
+
89
+ `novence dashboard` fetches your console-kit, writes `~/.novence/console/novence-console.html`
90
+ (mode 0600), serves it on the first free `127.0.0.1` port from 8765, and opens the browser at
91
+ that exact URL. Press Ctrl+C to stop; the file (it holds a live `mgmt_` token) is deleted.
92
+
93
+ - Uses your saved API key. Without one, it signs you in with an email code instead.
94
+ - `--port <n>` first port to try, `--no-open` print the URL only, `--email <email>` skip the prompt.
95
+ - `--ttl <minutes>` session length 5–480 (default 30). Sessions over 30 minutes can view usage
96
+ and open billing, but cannot manage team members.
97
+ - In the page, **Switch account** signs in with an email code when the session expires.
98
+
85
99
  Every command accepts `--json`. Unknown flags are rejected rather than ignored,
86
100
  so a typo like `--nmae` fails loudly instead of silently deploying under the
87
101
  default name.
@@ -0,0 +1,2 @@
1
+ import { type ParsedArgs } from "../lib/args.js";
2
+ export declare function dashboardCommand(args: ParsedArgs): Promise<void>;
@@ -0,0 +1,182 @@
1
+ import { chmodSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { CONSOLE_INJECT_MARKER, Novence, requestSessionOtp, verifySessionOtp, } from "@novence/sdk";
6
+ import { flagBool, flagString } from "../lib/args.js";
7
+ import { openInBrowser } from "../lib/browser.js";
8
+ import { loadApiKey, resolveApiBase } from "../lib/config.js";
9
+ import { explain } from "../lib/errors.js";
10
+ import { fail, isJsonMode, json, prompt, result, step, withSpin } from "../lib/ui.js";
11
+ const DEFAULT_PORT = 8765;
12
+ /** Ports tried after the first before falling back to an ephemeral one. */
13
+ const PORT_SCAN = 20;
14
+ const CONSOLE_FILE = "novence-console.html";
15
+ const CONSOLE_DIR = join(homedir(), ".novence", "console");
16
+ export async function dashboardCommand(args) {
17
+ const apiBase = resolveApiBase(flagString(args.flags, "api"));
18
+ const startPort = parsePort(flagString(args.flags, "port"));
19
+ const ttlMinutes = parseTtl(flagString(args.flags, "ttl"));
20
+ let loaded;
21
+ try {
22
+ loaded = await loadKit(args, apiBase, ttlMinutes);
23
+ }
24
+ catch (err) {
25
+ fail(explain(err, { apiBase }));
26
+ }
27
+ const html = injectConsole(loaded.kit, loaded.token);
28
+ const filePath = writeConsoleFile(html);
29
+ const server = createServer((req, res) => serveConsole(req, res, html, server));
30
+ const port = await listenOnFreePort(server, startPort);
31
+ const url = `http://127.0.0.1:${port}/${CONSOLE_FILE}`;
32
+ const shutdown = () => {
33
+ server.close();
34
+ rmSync(filePath, { force: true });
35
+ process.exit(0);
36
+ };
37
+ process.on("SIGINT", shutdown);
38
+ process.on("SIGTERM", shutdown);
39
+ if (isJsonMode()) {
40
+ json({ ok: true, url, port, file: filePath, expiresAt: loaded.kit.session?.expiresAt ?? null });
41
+ }
42
+ else {
43
+ if (port !== startPort)
44
+ step(`Port ${startPort} is busy — using ${port}.`);
45
+ step(`Serving your console on 127.0.0.1:${port}. Press Ctrl+C to stop (deletes ${filePath}).`);
46
+ result(url);
47
+ }
48
+ if (!flagBool(args.flags, "no-open") && !openInBrowser(url)) {
49
+ step("Could not launch a browser — open the URL above.");
50
+ }
51
+ }
52
+ async function loadKit(args, apiBase, ttlMinutes) {
53
+ const apiKey = loadApiKey();
54
+ if (apiKey) {
55
+ const keyClient = new Novence({ apiKey, baseUrl: apiBase });
56
+ if (ttlMinutes === undefined) {
57
+ const kit = await withSpin("Fetching your console…", () => keyClient.account.consoleKit());
58
+ if (!kit.session?.token)
59
+ throw new Error("console-kit did not return a session token");
60
+ return { kit, token: kit.session.token };
61
+ }
62
+ const session = await keyClient.account.createSession({ ttlMinutes });
63
+ return kitForSession(session.token, apiBase);
64
+ }
65
+ if (isJsonMode() || flagBool(args.flags, "no-input")) {
66
+ fail("No saved API key. Set NOVENCE_API_KEY, run `novence login`, or run `novence dashboard` interactively to sign in with an email code.");
67
+ }
68
+ step("No saved API key — sign in with an email code instead.");
69
+ const email = flagString(args.flags, "email") ?? (await prompt(" Email: "));
70
+ if (!email.includes("@"))
71
+ fail(`Not a valid email: ${email}`);
72
+ await withSpin(`Sending a code to ${email}…`, () => requestSessionOtp(email, apiBase));
73
+ const code = await prompt(" 6-digit code from your email: ");
74
+ if (!/^[0-9]{6}$/.test(code))
75
+ fail("Enter the 6-digit code from the email.");
76
+ const session = await verifySessionOtp(email, code, { ttlMinutes, baseUrl: apiBase });
77
+ return kitForSession(session.token, apiBase);
78
+ }
79
+ /** console-kit with a mgmt_ token reuses that session instead of minting another. */
80
+ async function kitForSession(token, apiBase) {
81
+ const mgmtClient = new Novence({ apiKey: token, baseUrl: apiBase });
82
+ const kit = await withSpin("Fetching your console…", () => mgmtClient.account.consoleKit());
83
+ return { kit, token };
84
+ }
85
+ function injectConsole(kit, token) {
86
+ const template = kit.htmlTemplate;
87
+ if (!template?.includes(CONSOLE_INJECT_MARKER)) {
88
+ fail("The console template is missing its injection marker. Update the CLI: npm i -g novence@latest");
89
+ }
90
+ const payload = `window.__NOVENCE_SNAPSHOT__=${scriptJson(kit.snapshot ?? null)};` +
91
+ `window.__NOVENCE_MGMT_TOKEN__=${scriptJson(token)};`;
92
+ return template.replace(CONSOLE_INJECT_MARKER, () => payload);
93
+ }
94
+ /** JSON that cannot close the surrounding <script> tag. */
95
+ function scriptJson(value) {
96
+ return JSON.stringify(value)
97
+ .replace(/</g, "\\u003c")
98
+ .replace(/\u2028/g, "\\u2028")
99
+ .replace(/\u2029/g, "\\u2029");
100
+ }
101
+ /** Outside the working directory (agents commit scratch dirs); holds a live token, so 0600. */
102
+ function writeConsoleFile(html) {
103
+ mkdirSync(CONSOLE_DIR, { recursive: true, mode: 0o700 });
104
+ const filePath = join(CONSOLE_DIR, CONSOLE_FILE);
105
+ writeFileSync(filePath, html, { mode: 0o600 });
106
+ chmodSync(filePath, 0o600);
107
+ return filePath;
108
+ }
109
+ function serveConsole(req, res, html, server) {
110
+ const port = server.address().port;
111
+ // DNS rebinding: a hostile page can resolve its own name to 127.0.0.1 and read this response.
112
+ const allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
113
+ if (!allowedHosts.has(req.headers.host ?? "")) {
114
+ res.writeHead(403, { "Content-Type": "text/plain" }).end("Forbidden");
115
+ return;
116
+ }
117
+ if (req.method !== "GET" && req.method !== "HEAD") {
118
+ res.writeHead(405, { Allow: "GET, HEAD" }).end();
119
+ return;
120
+ }
121
+ const path = (req.url ?? "/").split("?")[0];
122
+ if (path === "/") {
123
+ res.writeHead(302, { Location: `/${CONSOLE_FILE}` }).end();
124
+ return;
125
+ }
126
+ if (path !== `/${CONSOLE_FILE}`) {
127
+ res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
128
+ return;
129
+ }
130
+ res.writeHead(200, {
131
+ "Content-Type": "text/html; charset=utf-8",
132
+ "Cache-Control": "no-store",
133
+ "X-Content-Type-Options": "nosniff",
134
+ "Referrer-Policy": "no-referrer",
135
+ });
136
+ res.end(req.method === "HEAD" ? undefined : html);
137
+ }
138
+ async function listenOnFreePort(server, startPort) {
139
+ const candidates = Array.from({ length: PORT_SCAN + 1 }, (_, i) => startPort + i).filter((p) => p <= 65535);
140
+ for (const port of [...candidates, 0]) {
141
+ try {
142
+ return await listen(server, port);
143
+ }
144
+ catch (err) {
145
+ if (err.code !== "EADDRINUSE")
146
+ throw err;
147
+ }
148
+ }
149
+ fail("Could not bind a local port for the console.");
150
+ }
151
+ function listen(server, port) {
152
+ return new Promise((resolve, reject) => {
153
+ const onError = (err) => {
154
+ server.off("listening", onListening);
155
+ reject(err);
156
+ };
157
+ const onListening = () => {
158
+ server.off("error", onError);
159
+ resolve(server.address().port);
160
+ };
161
+ server.once("error", onError);
162
+ server.once("listening", onListening);
163
+ server.listen(port, "127.0.0.1");
164
+ });
165
+ }
166
+ function parsePort(raw) {
167
+ if (raw === undefined)
168
+ return DEFAULT_PORT;
169
+ const port = Number(raw);
170
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
171
+ fail(`Invalid --port: ${raw}`);
172
+ return port;
173
+ }
174
+ function parseTtl(raw) {
175
+ if (raw === undefined)
176
+ return undefined;
177
+ const minutes = Number(raw);
178
+ if (!Number.isInteger(minutes) || minutes < 5 || minutes > 480) {
179
+ fail(`Invalid --ttl: ${raw} (minutes, 5–480)`);
180
+ }
181
+ return minutes;
182
+ }
@@ -42,9 +42,12 @@ async function waitUntilLive(client, projectId) {
42
42
  let lastStatus = "";
43
43
  while (Date.now() - startedAt < POLL_TIMEOUT_MS) {
44
44
  const { deployment } = await client.deployments.latest(projectId);
45
- if (deployment.status !== lastStatus) {
46
- spinner.update(`${deployment.status}…`);
47
- lastStatus = deployment.status;
45
+ const label = deployment.status === "queued" && deployment.queuePosition
46
+ ? `queued for checks (position ${deployment.queuePosition})`
47
+ : deployment.status;
48
+ if (label !== lastStatus) {
49
+ spinner.update(`${label}…`);
50
+ lastStatus = label;
48
51
  }
49
52
  if (deployment.status === "live") {
50
53
  spinner.stop("Live");
@@ -81,6 +84,8 @@ function reportChecks(deployment) {
81
84
  else if (checks.passed === true) {
82
85
  step("Checks passed");
83
86
  }
87
+ for (const warning of checks.warnings ?? [])
88
+ warn(warning);
84
89
  }
85
90
  export async function deployCommand(args) {
86
91
  const apiBase = resolveApiBase(flagString(args.flags, "api"));
@@ -33,6 +33,20 @@ export async function keysCommand(args) {
33
33
  }
34
34
  return;
35
35
  }
36
+ if (sub === "create") {
37
+ const name = args.positionals[1];
38
+ if (!name)
39
+ fail("Usage: novence keys create <name> [--project <id>]\n e.g. novence keys create ci");
40
+ const res = await client.apiKeys.create({ name, projectId: flagString(args.flags, "project") });
41
+ if (isJsonMode()) {
42
+ json({ ok: true, ...res });
43
+ return;
44
+ }
45
+ result(res.apiKey);
46
+ step(`Key "${res.key.name}" (${res.key.scope}) — shown once. Store it in a secret manager or NOVENCE_API_KEY.`);
47
+ step("It keeps working when `novence login --recover` replaces your primary key.");
48
+ return;
49
+ }
36
50
  if (sub === "revoke") {
37
51
  const id = args.positionals[1];
38
52
  if (!id)
@@ -48,7 +62,7 @@ export async function keysCommand(args) {
48
62
  step("That was the key this machine uses — run `novence login` to get a new one.");
49
63
  return;
50
64
  }
51
- fail(`Unknown subcommand: ${sub}\n Usage: novence keys list | novence keys revoke <id>`);
65
+ fail(`Unknown subcommand: ${sub}\n Usage: novence keys list | novence keys create <name> | novence keys revoke <id>`);
52
66
  }
53
67
  catch (err) {
54
68
  fail(explain(err, { apiBase }));
@@ -2,8 +2,8 @@ import { Novence } from "@novence/sdk";
2
2
  import { claimAndMaybeVerify, ensureApiKey } from "../lib/auth.js";
3
3
  import { credentialsPath, loadApiKey, resolveApiBase, saveApiKey } from "../lib/config.js";
4
4
  import { reissueApiKey, resendVerification, verifyEmail } from "@novence/sdk";
5
- import { flagString } from "../lib/args.js";
6
- import { fail, prompt, result, withSpin } from "../lib/ui.js";
5
+ import { flagBool, flagString } from "../lib/args.js";
6
+ import { fail, prompt, result, step, withSpin } from "../lib/ui.js";
7
7
  export async function loginCommand(args) {
8
8
  const apiBase = resolveApiBase(flagString(args.flags, "api"));
9
9
  const emailFlag = flagString(args.flags, "email");
@@ -29,9 +29,15 @@ export async function loginCommand(args) {
29
29
  if (!code)
30
30
  fail("No code entered.");
31
31
  if (flagString(args.flags, "recover") !== undefined || args.flags.recover === true) {
32
- const issued = await reissueApiKey(address, code, apiBase);
32
+ const issued = await reissueApiKey(address, code, apiBase, {
33
+ revokeAll: flagBool(args.flags, "revoke-all"),
34
+ });
33
35
  saveApiKey(issued.apiKey);
34
36
  result(`Key reissued for account ${issued.accountId} → ${credentialsPath()}`);
37
+ if (issued.remainingKeys.length) {
38
+ step(`Still active: ${issued.remainingKeys.map((k) => `${k.name} (${k.keyPrefix})`).join(", ")}. ` +
39
+ "Use --revoke-all if a key may have leaked.");
40
+ }
35
41
  return;
36
42
  }
37
43
  await verifyEmail(address, code, apiBase);
@@ -1,21 +1,9 @@
1
- import { spawn } from "node:child_process";
2
1
  import { Novence } from "@novence/sdk";
3
2
  import { loadApiKey, resolveApiBase } from "../lib/config.js";
4
3
  import { flagString } from "../lib/args.js";
4
+ import { openInBrowser } from "../lib/browser.js";
5
5
  import { explain } from "../lib/errors.js";
6
6
  import { fail, isJsonMode, json, result, siteUrl, step } from "../lib/ui.js";
7
- /** Platform opener; falls back to printing the URL when there is no GUI. */
8
- function openInBrowser(url) {
9
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
10
- try {
11
- const child = spawn(cmd, [url], { stdio: "ignore", detached: true });
12
- child.unref();
13
- return true;
14
- }
15
- catch {
16
- return false;
17
- }
18
- }
19
7
  export async function openCommand(args) {
20
8
  const apiBase = resolveApiBase(flagString(args.flags, "api"));
21
9
  const apiKey = loadApiKey();
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ import { checksCommand } from "./commands/checks.js";
18
18
  import { rollbackCommand } from "./commands/rollback.js";
19
19
  import { dataCommand } from "./commands/data.js";
20
20
  import { siteMcpCommand } from "./commands/site-mcp.js";
21
+ import { dashboardCommand } from "./commands/dashboard.js";
21
22
  const HELP = `
22
23
  novence — deploy a static site to the edge
23
24
 
@@ -31,11 +32,20 @@ const HELP = `
31
32
  novence domains add <host> Attach a custom domain (prints DNS records)
32
33
  novence domains status Custom domain state
33
34
  novence keys list API keys on the account
35
+ novence keys create <name> Extra named key (e.g. ci) that survives login --recover
34
36
  novence keys revoke <id> Revoke a key
35
37
  novence projects List projects and their URLs
36
38
  novence login Sign in, verify email, or recover a key
37
39
  novence claim Attach an email to an anonymous deploy
38
40
  novence whoami Plan, verification, and usage
41
+ novence dashboard Open your local account console (alias: console)
42
+
43
+ Dashboard
44
+ novence dashboard Serve the console on the first free 127.0.0.1 port from 8765
45
+ --port <n> First port to try (default 8765)
46
+ --no-open Print the URL without opening a browser
47
+ --email <email> Email for code sign-in when no API key is saved
48
+ --ttl <minutes> Session length 5–480 (default 30; >30 drops member management)
39
49
 
40
50
  Deploy
41
51
  novence deploy Auto-detects dist, build, out, public, _site
@@ -100,11 +110,13 @@ async function main() {
100
110
  keys: ["project", "include-revoked", "force"],
101
111
  projects: [],
102
112
  ls: [],
103
- login: ["email", "recover"],
113
+ login: ["email", "recover", "revoke-all"],
104
114
  whoami: [],
105
115
  rollback: ["project", "deployment"],
106
116
  data: ["project"],
107
117
  "site-mcp": ["project"],
118
+ dashboard: ["port", "no-open", "email", "ttl"],
119
+ console: ["port", "no-open", "email", "ttl"],
108
120
  };
109
121
  const allowed = ALLOWED[args.command];
110
122
  if (allowed) {
@@ -138,6 +150,9 @@ async function main() {
138
150
  return dataCommand(args);
139
151
  case "site-mcp":
140
152
  return siteMcpCommand(args);
153
+ case "dashboard":
154
+ case "console":
155
+ return dashboardCommand(args);
141
156
  default:
142
157
  fail(`Unknown command: ${args.command}\n Run \`novence --help\` for usage.`);
143
158
  }
@@ -0,0 +1,2 @@
1
+ /** Platform opener; falls back to printing the URL when there is no GUI. */
2
+ export declare function openInBrowser(url: string): boolean;
@@ -0,0 +1,13 @@
1
+ import { spawn } from "node:child_process";
2
+ /** Platform opener; falls back to printing the URL when there is no GUI. */
3
+ export function openInBrowser(url) {
4
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
5
+ try {
6
+ const child = spawn(cmd, [url], { stdio: "ignore", detached: true });
7
+ child.unref();
8
+ return true;
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "novence",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "CLI for Novence — deploy a static site to the edge in one command.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -40,7 +40,7 @@
40
40
  "access": "public"
41
41
  },
42
42
  "dependencies": {
43
- "@novence/sdk": "^0.2.6"
43
+ "@novence/sdk": "^0.3.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/node": "^22.10.2",