redwax-cli 0.0.0-stage → 1.0.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.
Files changed (64) hide show
  1. package/README.md +90 -3
  2. package/dashboard/apple-touch-icon.png +0 -0
  3. package/dashboard/assets/data-DnUM1Mpn.js +17 -0
  4. package/dashboard/assets/index-Cb3ZdSPZ.js +191 -0
  5. package/dashboard/assets/index-GSeTo6vS.css +1 -0
  6. package/dashboard/assets/radix-Cu8wEyce.js +41 -0
  7. package/dashboard/assets/react-Cnjii2my.js +59 -0
  8. package/dashboard/favicon.svg +12 -0
  9. package/dashboard/index.html +37 -0
  10. package/package.json +68 -6
  11. package/scripts/bundle.cjs +56 -0
  12. package/server/package.json +5 -0
  13. package/server/src/app.js +141 -0
  14. package/server/src/config/env.js +102 -0
  15. package/server/src/config/keys.js +81 -0
  16. package/server/src/config/metrics.js +161 -0
  17. package/server/src/config/openapi.js +507 -0
  18. package/server/src/controllers/auth.controller.js +115 -0
  19. package/server/src/controllers/project.controller.js +154 -0
  20. package/server/src/controllers/secret.controller.js +138 -0
  21. package/server/src/domain.js +49 -0
  22. package/server/src/middleware/auth.middleware.js +26 -0
  23. package/server/src/middleware/rateLimit.middleware.js +49 -0
  24. package/server/src/middleware/rbac.middleware.js +47 -0
  25. package/server/src/middleware/validate.middleware.js +35 -0
  26. package/server/src/models/AuditLog.model.js +32 -0
  27. package/server/src/models/Project.model.js +33 -0
  28. package/server/src/models/Secret.model.js +30 -0
  29. package/server/src/models/SecretVersion.model.js +25 -0
  30. package/server/src/models/User.model.js +31 -0
  31. package/server/src/routes/auth.routes.js +15 -0
  32. package/server/src/routes/project.routes.js +45 -0
  33. package/server/src/routes/secret.routes.js +44 -0
  34. package/server/src/services/audit.service.js +65 -0
  35. package/server/src/services/auth.service.js +130 -0
  36. package/server/src/services/crypto.service.js +73 -0
  37. package/server/src/services/project.service.js +178 -0
  38. package/server/src/services/secret.service.js +198 -0
  39. package/server/src/start.js +49 -0
  40. package/server/src/store/index.js +60 -0
  41. package/server/src/store/mongo.js +336 -0
  42. package/server/src/store/sqlite.js +538 -0
  43. package/server/src/store/sqliteRuntime.js +64 -0
  44. package/server/src/utils/apiError.js +10 -0
  45. package/server/src/utils/asyncHandler.js +8 -0
  46. package/server/src/utils/logger.js +20 -0
  47. package/server/src/utils/requestContext.js +19 -0
  48. package/src/commands/diff.js +64 -0
  49. package/src/commands/history.js +56 -0
  50. package/src/commands/init.js +59 -0
  51. package/src/commands/login.js +53 -0
  52. package/src/commands/logout.js +30 -0
  53. package/src/commands/pull.js +82 -0
  54. package/src/commands/push.js +76 -0
  55. package/src/commands/server.js +313 -0
  56. package/src/commands/whoami.js +26 -0
  57. package/src/index.js +52 -0
  58. package/src/lib/api.js +137 -0
  59. package/src/lib/config.js +36 -0
  60. package/src/lib/credentials.js +43 -0
  61. package/src/lib/dotenv.js +88 -0
  62. package/src/lib/prompt.js +50 -0
  63. package/src/lib/runtime.js +88 -0
  64. package/src/lib/ui.js +68 -0
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Minimal .env reader/writer. Deliberately dependency-free so the CLI stays
3
+ * small, and symmetric with the server's export format.
4
+ */
5
+
6
+ const ESCAPES = { n: '\n', r: '\r', t: '\t', '"': '"', "'": "'", '\\': '\\' };
7
+
8
+ /**
9
+ * Parse a .env file into a key-value object.
10
+ * Handles `export` prefixes, single and double quotes, escape sequences inside
11
+ * double quotes, and trailing inline comments on unquoted values.
12
+ */
13
+ function parse(content) {
14
+ const result = {};
15
+
16
+ for (const rawLine of String(content).split(/\r?\n/)) {
17
+ const line = rawLine.trim();
18
+ if (!line || line.startsWith('#')) continue;
19
+
20
+ const statement = line.startsWith('export ') ? line.slice(7).trim() : line;
21
+ const separator = statement.indexOf('=');
22
+ if (separator < 1) continue;
23
+
24
+ const key = statement.slice(0, separator).trim();
25
+ if (!key) continue;
26
+
27
+ let value = statement.slice(separator + 1).trim();
28
+
29
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
30
+ // Decode in a single left-to-right pass. Chained replaces would corrupt
31
+ // an escaped backslash followed by a letter, e.g. "C:\\path\\to".
32
+ value = value.slice(1, -1).replace(/\\(.)/g, (_, char) => ESCAPES[char] ?? char);
33
+ } else if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
34
+ value = value.slice(1, -1);
35
+ } else {
36
+ // An unquoted value ends at an inline comment.
37
+ const comment = value.indexOf(' #');
38
+ if (comment >= 0) value = value.slice(0, comment).trim();
39
+ }
40
+
41
+ result[key] = value;
42
+ }
43
+
44
+ return result;
45
+ }
46
+
47
+ /** Serialise a key-value object to .env format, keys sorted for stable diffs. */
48
+ function stringify(values) {
49
+ const lines = Object.keys(values)
50
+ .sort()
51
+ .map((key) => {
52
+ const value = String(values[key] ?? '');
53
+ if (value !== '' && !/[\s#"'\\$]/.test(value)) return `${key}=${value}`;
54
+
55
+ const escaped = value
56
+ .replace(/\\/g, '\\\\')
57
+ .replace(/"/g, '\\"')
58
+ .replace(/\n/g, '\\n')
59
+ .replace(/\r/g, '\\r');
60
+ return `${key}="${escaped}"`;
61
+ });
62
+
63
+ return lines.length ? `${lines.join('\n')}\n` : '';
64
+ }
65
+
66
+ /** Categorise the difference between two key-value maps. */
67
+ function diff(local, remote) {
68
+ const keys = [...new Set([...Object.keys(local), ...Object.keys(remote)])].sort();
69
+
70
+ const added = []; // present locally, missing remotely
71
+ const removed = []; // present remotely, missing locally
72
+ const changed = [];
73
+ const unchanged = [];
74
+
75
+ for (const key of keys) {
76
+ const inLocal = Object.prototype.hasOwnProperty.call(local, key);
77
+ const inRemote = Object.prototype.hasOwnProperty.call(remote, key);
78
+
79
+ if (inLocal && !inRemote) added.push(key);
80
+ else if (!inLocal && inRemote) removed.push(key);
81
+ else if (local[key] !== remote[key]) changed.push(key);
82
+ else unchanged.push(key);
83
+ }
84
+
85
+ return { added, removed, changed, unchanged };
86
+ }
87
+
88
+ module.exports = { parse, stringify, diff };
@@ -0,0 +1,50 @@
1
+ const readline = require('readline');
2
+
3
+ /** Ask a question and echo what the user types. */
4
+ function ask(question) {
5
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
6
+ return new Promise((resolve) => {
7
+ rl.question(question, (answer) => {
8
+ rl.close();
9
+ resolve(answer.trim());
10
+ });
11
+ });
12
+ }
13
+
14
+ /**
15
+ * Ask for a secret without echoing it.
16
+ * Intercepts the readline output stream so keystrokes never reach the terminal.
17
+ */
18
+ function askHidden(question) {
19
+ return new Promise((resolve) => {
20
+ let muted = false;
21
+
22
+ const output = new (require('stream').Writable)({
23
+ write(chunk, encoding, callback) {
24
+ if (!muted) process.stdout.write(chunk, encoding);
25
+ callback();
26
+ },
27
+ });
28
+
29
+ const rl = readline.createInterface({ input: process.stdin, output, terminal: true });
30
+
31
+ rl.question(question, (answer) => {
32
+ muted = false;
33
+ rl.close();
34
+ process.stdout.write('\n');
35
+ resolve(answer.trim());
36
+ });
37
+
38
+ muted = true;
39
+ });
40
+ }
41
+
42
+ /** Yes/no confirmation. Returns `fallback` when stdin is not a TTY. */
43
+ async function confirm(question, fallback = false) {
44
+ if (!process.stdin.isTTY) return fallback;
45
+ const answer = (await ask(`${question} ${fallback ? '[Y/n]' : '[y/N]'} `)).toLowerCase();
46
+ if (!answer) return fallback;
47
+ return answer === 'y' || answer === 'yes';
48
+ }
49
+
50
+ module.exports = { ask, askHidden, confirm };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Where things live for `redwax server`, in both layouts it runs in:
3
+ *
4
+ * published node_modules/redwax/{src,server,dashboard} (npx redwax-cli)
5
+ * monorepo packages/cli/src + apps/server + apps/client/dist
6
+ */
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const crypto = require('crypto');
11
+
12
+ const PACKAGE_ROOT = path.resolve(__dirname, '..', '..');
13
+ const REPO_ROOT = path.resolve(PACKAGE_ROOT, '..', '..');
14
+
15
+ /**
16
+ * True only when this file is the one inside the Redwax repository. A
17
+ * published install must never look above node_modules/redwax — the user's
18
+ * own project could have an apps/server, and we would load their code.
19
+ */
20
+ const IN_REPO = path.join(REPO_ROOT, 'packages', 'cli', 'src', 'lib', 'runtime.js') === __filename
21
+ && fs.existsSync(path.join(REPO_ROOT, 'apps', 'server', 'src', 'start.js'));
22
+
23
+ const pick = (bundled, repo) => {
24
+ if (IN_REPO) return fs.existsSync(repo) ? repo : null;
25
+ return fs.existsSync(bundled) ? bundled : null;
26
+ };
27
+
28
+ /** The server code: bundled in the package, or apps/server in the repo. */
29
+ function serverRoot() {
30
+ const root = pick(path.join(PACKAGE_ROOT, 'server'), path.join(REPO_ROOT, 'apps', 'server'));
31
+ if (!root) throw new Error('Could not find the Redwax server code — this install looks incomplete. Reinstall with: npm i -g redwax-cli');
32
+ return root;
33
+ }
34
+
35
+ /** Built dashboard (index.html + assets), or null when it has not been built. */
36
+ function dashboardDir() {
37
+ const dir = pick(path.join(PACKAGE_ROOT, 'dashboard'), path.join(REPO_ROOT, 'apps', 'client', 'dist'));
38
+ return dir && fs.existsSync(path.join(dir, 'index.html')) ? dir : null;
39
+ }
40
+
41
+ /**
42
+ * Per-user data folder, so the server finds the same data whichever directory
43
+ * it is started from: %APPDATA%\redwax\server on Windows, ~/.redwax/server
44
+ * elsewhere. REDWAX_DATA_DIR or --data override it.
45
+ */
46
+ function defaultDataDir() {
47
+ if (process.env.REDWAX_DATA_DIR) return path.resolve(process.env.REDWAX_DATA_DIR);
48
+ if (process.platform === 'win32' && process.env.APPDATA) return path.join(process.env.APPDATA, 'redwax', 'server');
49
+ return path.join(os.homedir(), '.redwax', 'server');
50
+ }
51
+
52
+ function dataPaths(dataDir) {
53
+ return {
54
+ dir: dataDir,
55
+ database: path.join(dataDir, 'redwax.db'),
56
+ masterKey: path.join(dataDir, 'master.key'),
57
+ keysDir: path.join(dataDir, 'keys'),
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Read the master key, creating it on first run. Returns { key, created }.
63
+ * The file is owner-only on POSIX; on Windows the per-user profile folder
64
+ * already restricts it.
65
+ */
66
+ function ensureMasterKey(file) {
67
+ if (fs.existsSync(file)) {
68
+ const key = fs.readFileSync(file, 'utf8').trim();
69
+ if (!/^[a-f\d]{64}$/i.test(key)) {
70
+ throw new Error(`${file} is not a valid master key (expected 64 hex characters). Restore it from your backup.`);
71
+ }
72
+ return { key, created: false };
73
+ }
74
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
75
+ const key = crypto.randomBytes(32).toString('hex');
76
+ fs.writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' });
77
+ return { key, created: true };
78
+ }
79
+
80
+ /** Non-internal IPv4 addresses — what teammates on the same network type in. */
81
+ function lanAddresses() {
82
+ return Object.values(os.networkInterfaces())
83
+ .flat()
84
+ .filter((a) => a && a.family === 'IPv4' && !a.internal)
85
+ .map((a) => a.address);
86
+ }
87
+
88
+ module.exports = { serverRoot, dashboardDir, defaultDataDir, dataPaths, ensureMasterKey, lanAddresses };
package/src/lib/ui.js ADDED
@@ -0,0 +1,68 @@
1
+ const c = require('picocolors');
2
+
3
+ const symbols = {
4
+ ok: c.green('[OK]'),
5
+ fail: c.red('[ERROR]'),
6
+ warn: c.yellow('[WARN]'),
7
+ info: c.cyan('·'),
8
+ add: c.green('+'),
9
+ del: c.red('-'),
10
+ chg: c.yellow('~'),
11
+ };
12
+
13
+ const success = (msg) => console.log(`${symbols.ok} ${msg}`);
14
+ const warn = (msg) => console.log(`${symbols.warn} ${c.yellow(msg)}`);
15
+ const info = (msg) => console.log(`${symbols.info} ${c.dim(msg)}`);
16
+
17
+ /** Print an error and exit non-zero. Every command failure funnels through here. */
18
+ function fail(message, hint) {
19
+ console.error(`${symbols.fail} ${c.red(message)}`);
20
+ if (hint) console.error(` ${c.dim(hint)}`);
21
+ process.exit(1);
22
+ }
23
+
24
+ /**
25
+ * Make server-supplied text safe to print. Values, names and error messages
26
+ * come from other users; raw control characters would let them inject
27
+ * terminal escape sequences (rewrite output, retitle the window, etc.).
28
+ */
29
+ function safe(value) {
30
+ // eslint-disable-next-line no-control-regex -- matching control chars is the point
31
+ return String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, (ch) => {
32
+ if (ch === '\n') return '\\n';
33
+ if (ch === '\r') return '\\r';
34
+ if (ch === '\t') return '\\t';
35
+ return `\\x${ch.charCodeAt(0).toString(16).padStart(2, '0')}`;
36
+ });
37
+ }
38
+
39
+ /** Turn an axios error into something a human can act on. */
40
+ function describeError(err) {
41
+ if (err.response) {
42
+ const body = err.response.data;
43
+ return safe(body?.error || body?.message || `Server responded ${err.response.status}`);
44
+ }
45
+ if (err.code === 'ECONNREFUSED') {
46
+ return 'Could not reach the Redwax server. Is it running? Start one with: npx redwax-cli server';
47
+ }
48
+ if (err.code === 'ETIMEDOUT' || err.code === 'ECONNABORTED') return 'Request to the Redwax server timed out';
49
+ return err.message;
50
+ }
51
+
52
+ /** Render an array of row objects as an aligned table. */
53
+ function table(rows, columns) {
54
+ if (!rows.length) return;
55
+
56
+ const widths = columns.map((col) =>
57
+ Math.max(col.header.length, ...rows.map((r) => String(col.value(r) ?? '').length))
58
+ );
59
+
60
+ const line = (cells, painter = (s) => s) =>
61
+ console.log(cells.map((cell, i) => painter(String(cell ?? '').padEnd(widths[i]))).join(' ').trimEnd());
62
+
63
+ line(columns.map((col) => col.header), c.bold);
64
+ line(widths.map((w) => '-'.repeat(w)), c.dim);
65
+ rows.forEach((row) => line(columns.map((col) => col.value(row))));
66
+ }
67
+
68
+ module.exports = { c, symbols, success, warn, info, fail, describeError, table, safe };