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.
- package/README.md +90 -3
- package/dashboard/apple-touch-icon.png +0 -0
- package/dashboard/assets/data-DnUM1Mpn.js +17 -0
- package/dashboard/assets/index-Cb3ZdSPZ.js +191 -0
- package/dashboard/assets/index-GSeTo6vS.css +1 -0
- package/dashboard/assets/radix-Cu8wEyce.js +41 -0
- package/dashboard/assets/react-Cnjii2my.js +59 -0
- package/dashboard/favicon.svg +12 -0
- package/dashboard/index.html +37 -0
- package/package.json +68 -6
- package/scripts/bundle.cjs +56 -0
- package/server/package.json +5 -0
- package/server/src/app.js +141 -0
- package/server/src/config/env.js +102 -0
- package/server/src/config/keys.js +81 -0
- package/server/src/config/metrics.js +161 -0
- package/server/src/config/openapi.js +507 -0
- package/server/src/controllers/auth.controller.js +115 -0
- package/server/src/controllers/project.controller.js +154 -0
- package/server/src/controllers/secret.controller.js +138 -0
- package/server/src/domain.js +49 -0
- package/server/src/middleware/auth.middleware.js +26 -0
- package/server/src/middleware/rateLimit.middleware.js +49 -0
- package/server/src/middleware/rbac.middleware.js +47 -0
- package/server/src/middleware/validate.middleware.js +35 -0
- package/server/src/models/AuditLog.model.js +32 -0
- package/server/src/models/Project.model.js +33 -0
- package/server/src/models/Secret.model.js +30 -0
- package/server/src/models/SecretVersion.model.js +25 -0
- package/server/src/models/User.model.js +31 -0
- package/server/src/routes/auth.routes.js +15 -0
- package/server/src/routes/project.routes.js +45 -0
- package/server/src/routes/secret.routes.js +44 -0
- package/server/src/services/audit.service.js +65 -0
- package/server/src/services/auth.service.js +130 -0
- package/server/src/services/crypto.service.js +73 -0
- package/server/src/services/project.service.js +178 -0
- package/server/src/services/secret.service.js +198 -0
- package/server/src/start.js +49 -0
- package/server/src/store/index.js +60 -0
- package/server/src/store/mongo.js +336 -0
- package/server/src/store/sqlite.js +538 -0
- package/server/src/store/sqliteRuntime.js +64 -0
- package/server/src/utils/apiError.js +10 -0
- package/server/src/utils/asyncHandler.js +8 -0
- package/server/src/utils/logger.js +20 -0
- package/server/src/utils/requestContext.js +19 -0
- package/src/commands/diff.js +64 -0
- package/src/commands/history.js +56 -0
- package/src/commands/init.js +59 -0
- package/src/commands/login.js +53 -0
- package/src/commands/logout.js +30 -0
- package/src/commands/pull.js +82 -0
- package/src/commands/push.js +76 -0
- package/src/commands/server.js +313 -0
- package/src/commands/whoami.js +26 -0
- package/src/index.js +52 -0
- package/src/lib/api.js +137 -0
- package/src/lib/config.js +36 -0
- package/src/lib/credentials.js +43 -0
- package/src/lib/dotenv.js +88 -0
- package/src/lib/prompt.js +50 -0
- package/src/lib/runtime.js +88 -0
- package/src/lib/ui.js +68 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `redwax server` — run a complete Redwax (API + dashboard + database) with
|
|
3
|
+
* one command and no Docker, MongoDB or config file.
|
|
4
|
+
*
|
|
5
|
+
* First run creates a data folder, a master key and a SQLite database, prints
|
|
6
|
+
* where they are and how to back them up, and opens the dashboard. Every later
|
|
7
|
+
* run picks up the same data.
|
|
8
|
+
*/
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const http = require('http');
|
|
12
|
+
const { spawn } = require('child_process');
|
|
13
|
+
const { Command, Option } = require('commander');
|
|
14
|
+
|
|
15
|
+
const { c, fail, success, warn } = require('../lib/ui');
|
|
16
|
+
const runtime = require('../lib/runtime');
|
|
17
|
+
|
|
18
|
+
/* ── Node version / SQLite flag ─────────────────────────────────────────── */
|
|
19
|
+
|
|
20
|
+
function sqliteRuntime() {
|
|
21
|
+
return require(path.join(runtime.serverRoot(), 'src', 'store', 'sqliteRuntime.js'));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* node:sqlite is behind a flag on Node 22.5–22.12 and 23.0–23.3. Rather than
|
|
26
|
+
* tell people to learn a flag, re-launch this same command with it. Returns
|
|
27
|
+
* true when the current process has handed off to a child.
|
|
28
|
+
*/
|
|
29
|
+
function relaunchWithSqliteFlagIfNeeded() {
|
|
30
|
+
const rt = sqliteRuntime();
|
|
31
|
+
if (!rt.hasSqliteSupport()) {
|
|
32
|
+
fail(
|
|
33
|
+
`Redwax needs Node.js ${rt.MIN_VERSION} or newer to run its built-in database — this is ${process.version}.`,
|
|
34
|
+
'Install the current LTS from https://nodejs.org (takes a minute), then run the same command again.'
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
if (!rt.needsSqliteFlag() || process.env.REDWAX_SQLITE_RELAUNCHED) return false;
|
|
38
|
+
|
|
39
|
+
const child = spawn(
|
|
40
|
+
process.execPath,
|
|
41
|
+
['--experimental-sqlite', '--disable-warning=ExperimentalWarning', ...process.argv.slice(1)],
|
|
42
|
+
{ stdio: 'inherit', env: { ...process.env, REDWAX_SQLITE_RELAUNCHED: '1' } }
|
|
43
|
+
);
|
|
44
|
+
// Ctrl+C reaches both processes; let the child shut down cleanly.
|
|
45
|
+
process.on('SIGINT', () => {});
|
|
46
|
+
process.on('SIGTERM', () => child.kill('SIGTERM'));
|
|
47
|
+
child.on('exit', (code, signal) => process.exit(signal ? 1 : code ?? 0));
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* ── helpers ────────────────────────────────────────────────────────────── */
|
|
52
|
+
|
|
53
|
+
function openBrowser(url) {
|
|
54
|
+
const [cmd, args] =
|
|
55
|
+
process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]]
|
|
56
|
+
: process.platform === 'darwin' ? ['open', [url]]
|
|
57
|
+
: ['xdg-open', [url]];
|
|
58
|
+
try {
|
|
59
|
+
spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true }).on('error', () => {}).unref();
|
|
60
|
+
} catch {
|
|
61
|
+
// No browser available (SSH session, server box) — the URL is printed anyway.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Is something already answering /health on this port, and is it Redwax? */
|
|
66
|
+
function probe(port) {
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
const req = http.get({ host: '127.0.0.1', port, path: '/health', timeout: 1500 }, (res) => {
|
|
69
|
+
let body = '';
|
|
70
|
+
res.on('data', (d) => { body += d; });
|
|
71
|
+
res.on('end', () => {
|
|
72
|
+
try { resolve(JSON.parse(body).status ? 'redwax' : 'other'); } catch { resolve('other'); }
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
req.on('error', () => resolve(null));
|
|
76
|
+
req.on('timeout', () => { req.destroy(); resolve(null); });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const rule = (width = 62) => c.dim('─'.repeat(width));
|
|
81
|
+
|
|
82
|
+
function printFirstRun(paths) {
|
|
83
|
+
console.log('');
|
|
84
|
+
console.log(` ${c.yellow(c.bold('First run — back up your master key'))}`);
|
|
85
|
+
console.log(` ${rule()}`);
|
|
86
|
+
console.log(' Every secret is encrypted with a key that was just created at:');
|
|
87
|
+
console.log(` ${c.bold(paths.masterKey)}`);
|
|
88
|
+
console.log(` ${c.yellow('If it is lost, no one — including you — can decrypt your secrets.')}`);
|
|
89
|
+
console.log(` Make a backup now: ${c.cyan('npx redwax-cli server backup')}`);
|
|
90
|
+
console.log(` ${rule()}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function printRunning({ url, paths, share, port, dashboard, storeLabel }) {
|
|
94
|
+
console.log('');
|
|
95
|
+
console.log(` ${c.red('●')} ${c.bold('Redwax is running')}`);
|
|
96
|
+
console.log('');
|
|
97
|
+
console.log(` ${c.dim('Dashboard')} ${dashboard ? c.cyan(url) : c.yellow('not built — API only (npm run build:client)')}`);
|
|
98
|
+
console.log(` ${c.dim('API')} ${url}/api/v1`);
|
|
99
|
+
console.log(` ${c.dim('Data')} ${paths.dir}`);
|
|
100
|
+
console.log(` ${c.dim('Database')} ${storeLabel}`);
|
|
101
|
+
|
|
102
|
+
if (share) {
|
|
103
|
+
const addresses = runtime.lanAddresses();
|
|
104
|
+
console.log('');
|
|
105
|
+
console.log(` ${c.dim('Teammates')} ${addresses.length ? addresses.map((a) => c.cyan(`http://${a}:${port}`)).join(' ') : c.yellow('no network address found')}`);
|
|
106
|
+
if (addresses[0]) {
|
|
107
|
+
console.log(` ${c.dim('Their CLI')} redwax login --server http://${addresses[0]}:${port}/api/v1`);
|
|
108
|
+
}
|
|
109
|
+
console.log(` ${c.yellow('Plain HTTP on your network. For use over the internet, put it behind HTTPS (see the self-hosting docs).')}`);
|
|
110
|
+
} else {
|
|
111
|
+
console.log('');
|
|
112
|
+
console.log(` ${c.dim('Teammates')} only this computer can connect — add ${c.cyan('--share')} to open it to your network`);
|
|
113
|
+
}
|
|
114
|
+
console.log(` ${c.dim('Stop')} Ctrl+C`);
|
|
115
|
+
console.log('');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/* ── start ──────────────────────────────────────────────────────────────── */
|
|
119
|
+
|
|
120
|
+
async function startServer(options) {
|
|
121
|
+
if (relaunchWithSqliteFlagIfNeeded()) return;
|
|
122
|
+
|
|
123
|
+
const port = Number(options.port);
|
|
124
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) fail(`'${options.port}' is not a valid port.`);
|
|
125
|
+
|
|
126
|
+
const paths = runtime.dataPaths(path.resolve(options.data || runtime.defaultDataDir()));
|
|
127
|
+
const useMongo = Boolean(process.env.MONGO_URI);
|
|
128
|
+
|
|
129
|
+
// Something already on the port? Say what, instead of a raw EADDRINUSE.
|
|
130
|
+
const existing = await probe(port);
|
|
131
|
+
if (existing === 'redwax') {
|
|
132
|
+
const url = `http://localhost:${port}`;
|
|
133
|
+
success(`Redwax is already running at ${url}`);
|
|
134
|
+
if (options.open) openBrowser(url);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (existing === 'other') {
|
|
138
|
+
fail(`Port ${port} is already used by another program.`, `Try another port: npx redwax-cli server --port ${port + 1}`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let keyInfo;
|
|
142
|
+
try {
|
|
143
|
+
fs.mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
|
|
144
|
+
keyInfo = runtime.ensureMasterKey(paths.masterKey);
|
|
145
|
+
} catch (err) {
|
|
146
|
+
fail(err.message);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const dashboard = runtime.dashboardDir();
|
|
150
|
+
|
|
151
|
+
// The server reads its configuration once, when first required, so the
|
|
152
|
+
// environment must be complete before anything below loads it.
|
|
153
|
+
Object.assign(process.env, {
|
|
154
|
+
NODE_ENV: 'production',
|
|
155
|
+
PORT: String(port),
|
|
156
|
+
HOST: options.share ? '0.0.0.0' : '127.0.0.1',
|
|
157
|
+
MASTER_KEY: process.env.MASTER_KEY || keyInfo.key,
|
|
158
|
+
JWT_KEYS_DIR: process.env.JWT_KEYS_DIR || paths.keysDir,
|
|
159
|
+
CLIENT_URL: process.env.CLIENT_URL || `http://localhost:${port}`,
|
|
160
|
+
LOG_LEVEL: options.verbose ? 'info' : process.env.LOG_LEVEL || 'warn',
|
|
161
|
+
ALLOW_REGISTRATION: options.signup ? 'true' : 'false',
|
|
162
|
+
...(dashboard ? { DASHBOARD_DIR: dashboard } : {}),
|
|
163
|
+
...(useMongo ? { DATABASE: 'mongo' } : { DATABASE: 'sqlite', SQLITE_PATH: paths.database }),
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const start = require(path.join(runtime.serverRoot(), 'src', 'start.js'));
|
|
167
|
+
|
|
168
|
+
let running;
|
|
169
|
+
try {
|
|
170
|
+
running = await start({ port, host: process.env.HOST });
|
|
171
|
+
} catch (err) {
|
|
172
|
+
if (err.code === 'EADDRINUSE') {
|
|
173
|
+
fail(`Port ${port} is already in use.`, `Try another port: npx redwax-cli server --port ${port + 1}`);
|
|
174
|
+
}
|
|
175
|
+
if (err.code === 'EACCES') fail(`Not allowed to listen on port ${port}.`, 'Ports below 1024 need admin rights — use 4000 or higher.');
|
|
176
|
+
fail(err.message);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const url = `http://localhost:${running.port}`;
|
|
180
|
+
if (keyInfo.created) printFirstRun(paths);
|
|
181
|
+
printRunning({
|
|
182
|
+
url,
|
|
183
|
+
paths,
|
|
184
|
+
share: options.share,
|
|
185
|
+
port: running.port,
|
|
186
|
+
dashboard,
|
|
187
|
+
storeLabel: useMongo ? `MongoDB (${running.storeInfo.location})` : `built-in SQLite · ${paths.database}`,
|
|
188
|
+
});
|
|
189
|
+
if (!options.signup) warn('Sign-up is closed (--no-signup). Existing accounts can still sign in.');
|
|
190
|
+
|
|
191
|
+
// A first run lands on registration; later runs go straight to sign-in.
|
|
192
|
+
const interactive = process.stdout.isTTY && !process.env.CI;
|
|
193
|
+
if (options.open && interactive && dashboard) openBrowser(keyInfo.created ? `${url}/register` : url);
|
|
194
|
+
|
|
195
|
+
let stopping = false;
|
|
196
|
+
const stop = async () => {
|
|
197
|
+
if (stopping) return;
|
|
198
|
+
stopping = true;
|
|
199
|
+
console.log(c.dim('\n Stopping Redwax…'));
|
|
200
|
+
await running.close();
|
|
201
|
+
process.exit(0);
|
|
202
|
+
};
|
|
203
|
+
process.on('SIGINT', stop);
|
|
204
|
+
process.on('SIGTERM', stop);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/* ── backup ─────────────────────────────────────────────────────────────── */
|
|
208
|
+
|
|
209
|
+
function stamp() {
|
|
210
|
+
const d = new Date();
|
|
211
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
212
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function backup(_options, cmd) {
|
|
216
|
+
// --data may be parsed by the parent `server` command; merge both levels.
|
|
217
|
+
const options = cmd.optsWithGlobals();
|
|
218
|
+
if (relaunchWithSqliteFlagIfNeeded()) return;
|
|
219
|
+
|
|
220
|
+
const paths = runtime.dataPaths(path.resolve(options.data || runtime.defaultDataDir()));
|
|
221
|
+
if (!fs.existsSync(paths.database) || !fs.existsSync(paths.masterKey)) {
|
|
222
|
+
fail(`No Redwax data found in ${paths.dir}`, 'Start the server once with `npx redwax-cli server`, or pass --data <folder>.');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const target = path.resolve(options.out || '.', `redwax-backup-${stamp()}`);
|
|
226
|
+
fs.mkdirSync(target, { recursive: true, mode: 0o700 });
|
|
227
|
+
|
|
228
|
+
// VACUUM INTO takes a consistent snapshot, even while the server is running.
|
|
229
|
+
const { DatabaseSync } = sqliteRuntime().loadSqlite();
|
|
230
|
+
const db = new DatabaseSync(paths.database);
|
|
231
|
+
try {
|
|
232
|
+
db.prepare('VACUUM INTO ?').run(path.join(target, 'redwax.db'));
|
|
233
|
+
} finally {
|
|
234
|
+
db.close();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
fs.copyFileSync(paths.masterKey, path.join(target, 'master.key'));
|
|
238
|
+
if (fs.existsSync(paths.keysDir)) fs.cpSync(paths.keysDir, path.join(target, 'keys'), { recursive: true });
|
|
239
|
+
fs.writeFileSync(
|
|
240
|
+
path.join(target, 'RESTORE.txt'),
|
|
241
|
+
[
|
|
242
|
+
'Redwax backup',
|
|
243
|
+
`Taken ${new Date().toISOString()} from ${paths.dir}`,
|
|
244
|
+
'',
|
|
245
|
+
'To restore:',
|
|
246
|
+
' 1. Stop the server (Ctrl+C).',
|
|
247
|
+
' 2. Copy redwax.db, master.key and keys/ into the data folder',
|
|
248
|
+
` (default: ${runtime.defaultDataDir()}), replacing what is there.`,
|
|
249
|
+
' 3. Start it again: npx redwax-cli server',
|
|
250
|
+
'',
|
|
251
|
+
'This folder contains the master key. Anyone holding it and redwax.db can',
|
|
252
|
+
'read every secret. Keep it somewhere safe, offline, and away from the server.',
|
|
253
|
+
'',
|
|
254
|
+
].join('\n')
|
|
255
|
+
);
|
|
256
|
+
|
|
257
|
+
success(`Backup written to ${c.bold(target)}`);
|
|
258
|
+
warn('It contains your master key — store it somewhere safe and offline, not next to the server.');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/* ── info ───────────────────────────────────────────────────────────────── */
|
|
262
|
+
|
|
263
|
+
function info(_options, cmd) {
|
|
264
|
+
const options = cmd.optsWithGlobals();
|
|
265
|
+
const paths = runtime.dataPaths(path.resolve(options.data || runtime.defaultDataDir()));
|
|
266
|
+
const size = (f) => (fs.existsSync(f) ? `${(fs.statSync(f).size / 1024).toFixed(1)} KB` : c.dim('not created yet'));
|
|
267
|
+
console.log(`${c.bold('Data folder')} ${paths.dir}`);
|
|
268
|
+
console.log(`${c.bold('Database')} ${paths.database} ${c.dim(size(paths.database))}`);
|
|
269
|
+
console.log(`${c.bold('Master key')} ${paths.masterKey} ${fs.existsSync(paths.masterKey) ? c.green('present') : c.dim('not created yet')}`);
|
|
270
|
+
console.log(`${c.bold('Dashboard')} ${runtime.dashboardDir() || c.yellow('not built')}`);
|
|
271
|
+
console.log(`${c.bold('Node.js')} ${process.version}`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/* ── command ────────────────────────────────────────────────────────────── */
|
|
275
|
+
|
|
276
|
+
const dataOption = () => new Option('-d, --data <folder>', 'data folder (default: per-user, see `redwax server info`)');
|
|
277
|
+
|
|
278
|
+
const command = new Command('server')
|
|
279
|
+
.description('Run your own Redwax server — no Docker or database needed')
|
|
280
|
+
.addOption(new Option('-p, --port <port>', 'port to listen on').default('4000'))
|
|
281
|
+
.addOption(dataOption())
|
|
282
|
+
.option('--share', 'let teammates on your network connect (listens on all interfaces)', false)
|
|
283
|
+
.option('--no-open', 'do not open the dashboard in a browser')
|
|
284
|
+
.option('--no-signup', 'close registration — existing accounts can still sign in')
|
|
285
|
+
.option('--verbose', 'log every request', false)
|
|
286
|
+
.addHelpText(
|
|
287
|
+
'after',
|
|
288
|
+
`
|
|
289
|
+
${c.bold('Examples')}
|
|
290
|
+
$ npx redwax-cli server Start on http://localhost:4000
|
|
291
|
+
$ npx redwax-cli server --share Let teammates on your network connect
|
|
292
|
+
$ npx redwax-cli server backup Snapshot the database and master key
|
|
293
|
+
$ npx redwax-cli server info Show where your data lives
|
|
294
|
+
|
|
295
|
+
Uses a built-in SQLite database. Set MONGO_URI to use MongoDB instead.
|
|
296
|
+
Needs Node.js 22.5 or newer.`
|
|
297
|
+
)
|
|
298
|
+
.action(startServer);
|
|
299
|
+
|
|
300
|
+
command
|
|
301
|
+
.command('backup')
|
|
302
|
+
.description('Write a consistent snapshot of the database and master key')
|
|
303
|
+
.option('-o, --out <folder>', 'where to write the backup folder', '.')
|
|
304
|
+
.addOption(dataOption())
|
|
305
|
+
.action(backup);
|
|
306
|
+
|
|
307
|
+
command
|
|
308
|
+
.command('info')
|
|
309
|
+
.description('Show where the server keeps its data')
|
|
310
|
+
.addOption(dataOption())
|
|
311
|
+
.action(info);
|
|
312
|
+
|
|
313
|
+
module.exports = command;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const { Command } = require('commander');
|
|
2
|
+
|
|
3
|
+
const { authenticatedClient, resolveServerUrl } = require('../lib/api');
|
|
4
|
+
const { readConfig } = require('../lib/config');
|
|
5
|
+
const { fail, describeError, c, info, safe } = require('../lib/ui');
|
|
6
|
+
|
|
7
|
+
module.exports = new Command('whoami')
|
|
8
|
+
.description('Show the signed-in user and the linked project')
|
|
9
|
+
.action(async () => {
|
|
10
|
+
try {
|
|
11
|
+
const { data } = await authenticatedClient().get('/auth/me');
|
|
12
|
+
const config = readConfig();
|
|
13
|
+
|
|
14
|
+
console.log(`${c.bold('User')} ${safe(data.user.name)} <${safe(data.user.email)}>`);
|
|
15
|
+
console.log(`${c.bold('Server')} ${resolveServerUrl()}`);
|
|
16
|
+
|
|
17
|
+
if (config?.projectId) {
|
|
18
|
+
console.log(`${c.bold('Project')} ${config.slug || config.projectId}`);
|
|
19
|
+
console.log(`${c.bold('Env')} ${config.environment}`);
|
|
20
|
+
} else {
|
|
21
|
+
info('No project linked in this directory. Run: redwax init <project-slug>');
|
|
22
|
+
}
|
|
23
|
+
} catch (err) {
|
|
24
|
+
fail(describeError(err));
|
|
25
|
+
}
|
|
26
|
+
});
|
package/src/index.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const { Command } = require('commander');
|
|
3
|
+
const { version } = require('../package.json');
|
|
4
|
+
const { c } = require('./lib/ui');
|
|
5
|
+
|
|
6
|
+
const program = new Command();
|
|
7
|
+
|
|
8
|
+
program
|
|
9
|
+
.name('redwax')
|
|
10
|
+
.description('Self-hostable .env manager for dev teams')
|
|
11
|
+
.version(version, '-v, --version')
|
|
12
|
+
.addHelpText(
|
|
13
|
+
'after',
|
|
14
|
+
`
|
|
15
|
+
${c.bold('Run your own server (no Docker needed)')}
|
|
16
|
+
$ npx redwax-cli server API + dashboard on http://localhost:4000
|
|
17
|
+
|
|
18
|
+
${c.bold('Getting started')}
|
|
19
|
+
$ redwax login Authenticate with your server
|
|
20
|
+
$ redwax init payments-api Link this directory to a project
|
|
21
|
+
$ redwax pull Write remote secrets to .env
|
|
22
|
+
$ redwax push Upload your local .env
|
|
23
|
+
|
|
24
|
+
${c.bold('Environment variables')}
|
|
25
|
+
REDWAX_SERVER API base URL (default http://localhost:4000/api/v1)
|
|
26
|
+
REDWAX_EMAIL Email for non-interactive login
|
|
27
|
+
REDWAX_PASSWORD Password for non-interactive login
|
|
28
|
+
REDWAX_HOME Credentials directory (default ~/.redwax)
|
|
29
|
+
`
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
program.addCommand(require('./commands/login'));
|
|
33
|
+
program.addCommand(require('./commands/logout'));
|
|
34
|
+
program.addCommand(require('./commands/whoami'));
|
|
35
|
+
program.addCommand(require('./commands/init'));
|
|
36
|
+
program.addCommand(require('./commands/push'));
|
|
37
|
+
program.addCommand(require('./commands/pull'));
|
|
38
|
+
program.addCommand(require('./commands/diff'));
|
|
39
|
+
program.addCommand(require('./commands/history'));
|
|
40
|
+
program.addCommand(require('./commands/server'));
|
|
41
|
+
|
|
42
|
+
// Anything that escapes a command's own handling lands here rather than
|
|
43
|
+
// printing a raw stack trace at the user.
|
|
44
|
+
process.on('unhandledRejection', (reason) => {
|
|
45
|
+
console.error(`${c.red('[ERROR]')} ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
46
|
+
process.exit(1);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
program.parseAsync(process.argv).catch((err) => {
|
|
50
|
+
console.error(`${c.red('[ERROR]')} ${err.message}`);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
});
|
package/src/lib/api.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
const axios = require('axios');
|
|
2
|
+
const { getCredentials, patchCredentials } = require('./credentials');
|
|
3
|
+
const { readConfig, CONFIG_FILE } = require('./config');
|
|
4
|
+
const { fail } = require('./ui');
|
|
5
|
+
|
|
6
|
+
const DEFAULT_SERVER = 'http://localhost:4000/api/v1';
|
|
7
|
+
const OBJECT_ID = /^[a-f\d]{24}$/i;
|
|
8
|
+
|
|
9
|
+
const normalizeUrl = (url) => String(url).replace(/\/+$/, '');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Resolve the server URL, most specific source first:
|
|
13
|
+
* env var > project .redwax > saved credentials > localhost.
|
|
14
|
+
*/
|
|
15
|
+
function resolveServerUrl() {
|
|
16
|
+
const config = readConfig();
|
|
17
|
+
const creds = getCredentials();
|
|
18
|
+
return normalizeUrl(
|
|
19
|
+
process.env.REDWAX_SERVER ||
|
|
20
|
+
config?.serverUrl ||
|
|
21
|
+
creds?.serverUrl ||
|
|
22
|
+
DEFAULT_SERVER
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The server the saved tokens were issued by. Tokens only ever go there.
|
|
28
|
+
*
|
|
29
|
+
* The project's .redwax file is committed to the repository, so anyone able to
|
|
30
|
+
* edit it could otherwise point serverUrl at their own host and collect the
|
|
31
|
+
* access and refresh tokens — and every pushed secret — of whoever runs the
|
|
32
|
+
* CLI in that checkout. When the project names a different server, stop and
|
|
33
|
+
* make the user log in to it explicitly.
|
|
34
|
+
*/
|
|
35
|
+
function credentialedServerUrl() {
|
|
36
|
+
const creds = getCredentials();
|
|
37
|
+
if (!creds?.serverUrl) return null;
|
|
38
|
+
|
|
39
|
+
const loggedIn = normalizeUrl(creds.serverUrl);
|
|
40
|
+
const wanted = resolveServerUrl();
|
|
41
|
+
if (wanted !== loggedIn) {
|
|
42
|
+
fail(
|
|
43
|
+
`This project targets ${wanted}, but you are logged in to ${loggedIn}.`,
|
|
44
|
+
`If you trust that server, run: redwax login --server ${wanted}`
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return loggedIn;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Build an axios client. Created per call rather than at module load so the
|
|
52
|
+
* credentials on disk are always current — `login` writes them mid-process.
|
|
53
|
+
*/
|
|
54
|
+
function createClient({ baseURL, withAuth = true } = {}) {
|
|
55
|
+
const creds = getCredentials();
|
|
56
|
+
const authServer = withAuth && creds?.accessToken ? credentialedServerUrl() : null;
|
|
57
|
+
|
|
58
|
+
const client = axios.create({
|
|
59
|
+
baseURL: baseURL || authServer || resolveServerUrl(),
|
|
60
|
+
timeout: 30_000,
|
|
61
|
+
headers: { 'X-Redwax-Client': 'cli' },
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
if (authServer) {
|
|
65
|
+
client.defaults.headers.Authorization = `Bearer ${creds.accessToken}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Access tokens live 15 minutes, so a transparent refresh keeps long-lived
|
|
69
|
+
// shells working without a re-login.
|
|
70
|
+
client.interceptors.response.use(
|
|
71
|
+
(res) => res,
|
|
72
|
+
async (err) => {
|
|
73
|
+
const original = err.config;
|
|
74
|
+
const current = getCredentials();
|
|
75
|
+
|
|
76
|
+
if (!authServer || err.response?.status !== 401 || original._retry || !current?.refreshToken) {
|
|
77
|
+
return Promise.reject(err);
|
|
78
|
+
}
|
|
79
|
+
original._retry = true;
|
|
80
|
+
|
|
81
|
+
let refreshed;
|
|
82
|
+
try {
|
|
83
|
+
// Always the issuing server — never the request's (overridable) baseURL.
|
|
84
|
+
const { data } = await axios.post(
|
|
85
|
+
`${authServer}/auth/refresh`,
|
|
86
|
+
{ refreshToken: current.refreshToken },
|
|
87
|
+
{ headers: { 'X-Redwax-Client': 'cli' }, timeout: 30_000 }
|
|
88
|
+
);
|
|
89
|
+
refreshed = data;
|
|
90
|
+
} catch {
|
|
91
|
+
return fail('Your session has expired.', 'Run: redwax login');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
patchCredentials({
|
|
95
|
+
accessToken: refreshed.accessToken,
|
|
96
|
+
refreshToken: refreshed.refreshToken,
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
original.headers = { ...original.headers, Authorization: `Bearer ${refreshed.accessToken}` };
|
|
100
|
+
return client(original);
|
|
101
|
+
}
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
return client;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Client for authenticated commands; exits early when not logged in. */
|
|
108
|
+
function authenticatedClient() {
|
|
109
|
+
const creds = getCredentials();
|
|
110
|
+
if (!creds?.accessToken) {
|
|
111
|
+
fail('You are not logged in.', 'Run: redwax login');
|
|
112
|
+
}
|
|
113
|
+
return createClient();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The linked project from .redwax; exits when the directory is not linked. */
|
|
117
|
+
function requireProject() {
|
|
118
|
+
const config = readConfig();
|
|
119
|
+
if (!config?.projectId) {
|
|
120
|
+
fail('This directory is not linked to a Redwax project.', 'Run: redwax init <project-slug>');
|
|
121
|
+
}
|
|
122
|
+
// The id is interpolated into request paths, so anything but an ObjectId
|
|
123
|
+
// could steer a request (with the user's token) to a different endpoint.
|
|
124
|
+
if (!OBJECT_ID.test(String(config.projectId))) {
|
|
125
|
+
fail(`Invalid projectId in ${CONFIG_FILE}.`, 'Run: redwax init <project-slug>');
|
|
126
|
+
}
|
|
127
|
+
return config;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = {
|
|
131
|
+
createClient,
|
|
132
|
+
authenticatedClient,
|
|
133
|
+
requireProject,
|
|
134
|
+
resolveServerUrl,
|
|
135
|
+
credentialedServerUrl,
|
|
136
|
+
DEFAULT_SERVER,
|
|
137
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
const CONFIG_FILE = '.redwax';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Read the project link file, walking up from `dir` so the CLI works from any
|
|
8
|
+
* subdirectory of the repo — the same way git finds .git.
|
|
9
|
+
*/
|
|
10
|
+
function readConfig(dir = process.cwd()) {
|
|
11
|
+
let current = path.resolve(dir);
|
|
12
|
+
|
|
13
|
+
for (;;) {
|
|
14
|
+
const candidate = path.join(current, CONFIG_FILE);
|
|
15
|
+
if (fs.existsSync(candidate)) {
|
|
16
|
+
try {
|
|
17
|
+
return { ...JSON.parse(fs.readFileSync(candidate, 'utf8')), _dir: current };
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const parent = path.dirname(current);
|
|
24
|
+
if (parent === current) return null;
|
|
25
|
+
current = parent;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function writeConfig(data, dir = process.cwd()) {
|
|
30
|
+
const { _dir, ...rest } = data;
|
|
31
|
+
const target = path.join(dir, CONFIG_FILE);
|
|
32
|
+
fs.writeFileSync(target, `${JSON.stringify(rest, null, 2)}\n`);
|
|
33
|
+
return target;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { readConfig, writeConfig, CONFIG_FILE };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
|
|
5
|
+
const CREDS_DIR = process.env.REDWAX_HOME || path.join(os.homedir(), '.redwax');
|
|
6
|
+
const CREDS_FILE = path.join(CREDS_DIR, 'credentials');
|
|
7
|
+
|
|
8
|
+
function getCredentials() {
|
|
9
|
+
try {
|
|
10
|
+
if (!fs.existsSync(CREDS_FILE)) return null;
|
|
11
|
+
return JSON.parse(fs.readFileSync(CREDS_FILE, 'utf8'));
|
|
12
|
+
} catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Persists tokens with owner-only permissions (FR-AUTH-05).
|
|
19
|
+
* The 0o600 mode is honoured on POSIX; on Windows the file inherits the
|
|
20
|
+
* user-profile ACL, which is equivalent in practice.
|
|
21
|
+
*/
|
|
22
|
+
function saveCredentials(data) {
|
|
23
|
+
fs.mkdirSync(CREDS_DIR, { recursive: true, mode: 0o700 });
|
|
24
|
+
fs.writeFileSync(CREDS_FILE, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
25
|
+
try {
|
|
26
|
+
fs.chmodSync(CREDS_FILE, 0o600);
|
|
27
|
+
} catch {
|
|
28
|
+
// Not supported on this platform — the directory ACL still applies.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function patchCredentials(partial) {
|
|
33
|
+
const current = getCredentials() || {};
|
|
34
|
+
const next = { ...current, ...partial };
|
|
35
|
+
saveCredentials(next);
|
|
36
|
+
return next;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function clearCredentials() {
|
|
40
|
+
if (fs.existsSync(CREDS_FILE)) fs.unlinkSync(CREDS_FILE);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { getCredentials, saveCredentials, patchCredentials, clearCredentials, CREDS_FILE, CREDS_DIR };
|