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
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "redwax-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "redwax-cli",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Self-hostable secret management for dev teams — CLI and server in one package",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"redwax": "src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"env",
|
|
12
|
+
"dotenv",
|
|
13
|
+
"secrets",
|
|
14
|
+
"redwax",
|
|
15
|
+
"secret-management",
|
|
16
|
+
"self-hosted",
|
|
17
|
+
"vault",
|
|
18
|
+
"dotenv-vault"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"src",
|
|
25
|
+
"server",
|
|
26
|
+
"dashboard",
|
|
27
|
+
"scripts",
|
|
28
|
+
"README.md"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "vitest run",
|
|
32
|
+
"prepack": "node scripts/bundle.cjs",
|
|
33
|
+
"postpack": "node scripts/bundle.cjs --clean"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@redwax/shared": "^1.0.0",
|
|
37
|
+
"axios": "^1.7.9",
|
|
38
|
+
"bcryptjs": "^2.4.3",
|
|
39
|
+
"commander": "^12.1.0",
|
|
40
|
+
"cookie-parser": "^1.4.7",
|
|
41
|
+
"cors": "^2.8.5",
|
|
42
|
+
"express": "^5.1.0",
|
|
43
|
+
"express-rate-limit": "^7.5.0",
|
|
44
|
+
"helmet": "^8.0.0",
|
|
45
|
+
"jsonwebtoken": "^9.0.2",
|
|
46
|
+
"mongoose": "^8.9.5",
|
|
47
|
+
"morgan": "^1.10.0",
|
|
48
|
+
"picocolors": "^1.1.1",
|
|
49
|
+
"swagger-ui-express": "^5.0.1",
|
|
50
|
+
"winston": "^3.17.0",
|
|
51
|
+
"zod": "^4.6.7"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@redwax/server": "*",
|
|
55
|
+
"mongodb-memory-server": "^10.1.3",
|
|
56
|
+
"mongoose": "^8.9.5",
|
|
57
|
+
"vitest": "^2.1.8"
|
|
58
|
+
},
|
|
59
|
+
"repository": {
|
|
60
|
+
"type": "git",
|
|
61
|
+
"url": "git+https://github.com/anonymousknight07/redwax.git",
|
|
62
|
+
"directory": "packages/cli"
|
|
63
|
+
},
|
|
64
|
+
"homepage": "https://redwax.website",
|
|
65
|
+
"bugs": {
|
|
66
|
+
"url": "https://github.com/anonymousknight07/redwax/issues"
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Packs the server and the built dashboard into this package, so the one
|
|
3
|
+
* `redwax` package on npm can run `redwax server` with no other install.
|
|
4
|
+
*
|
|
5
|
+
* node scripts/bundle.cjs build the dashboard, copy both in (prepack)
|
|
6
|
+
* node scripts/bundle.cjs --clean remove the copies again (postpack)
|
|
7
|
+
*
|
|
8
|
+
* The copies are removed after packing so that, inside the repo, the CLI keeps
|
|
9
|
+
* running the live apps/server code rather than a stale snapshot.
|
|
10
|
+
*/
|
|
11
|
+
const fs = require('fs');
|
|
12
|
+
const path = require('path');
|
|
13
|
+
const { execSync } = require('child_process');
|
|
14
|
+
|
|
15
|
+
const CLI = path.resolve(__dirname, '..');
|
|
16
|
+
const REPO = path.resolve(CLI, '..', '..');
|
|
17
|
+
const SERVER_OUT = path.join(CLI, 'server');
|
|
18
|
+
const DASH_OUT = path.join(CLI, 'dashboard');
|
|
19
|
+
|
|
20
|
+
const clean = () => {
|
|
21
|
+
fs.rmSync(SERVER_OUT, { recursive: true, force: true });
|
|
22
|
+
fs.rmSync(DASH_OUT, { recursive: true, force: true });
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
if (process.argv.includes('--clean')) {
|
|
26
|
+
clean();
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
clean();
|
|
31
|
+
|
|
32
|
+
// 1. Every server runtime dependency must be a dependency of this package,
|
|
33
|
+
// or `npx redwax-cli server` would fail on a clean machine.
|
|
34
|
+
const serverPkg = require(path.join(REPO, 'apps', 'server', 'package.json'));
|
|
35
|
+
const cliPkg = require(path.join(CLI, 'package.json'));
|
|
36
|
+
const missing = Object.entries(serverPkg.dependencies).filter(([name, range]) =>
|
|
37
|
+
name === '@redwax/shared' ? !cliPkg.dependencies[name] : cliPkg.dependencies[name] !== range
|
|
38
|
+
);
|
|
39
|
+
if (missing.length) {
|
|
40
|
+
console.error('packages/cli/package.json is missing server dependencies (or has different ranges):');
|
|
41
|
+
missing.forEach(([name, range]) => console.error(` "${name}": "${range}"`));
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// 2. Server code.
|
|
46
|
+
fs.cpSync(path.join(REPO, 'apps', 'server', 'src'), path.join(SERVER_OUT, 'src'), { recursive: true });
|
|
47
|
+
fs.writeFileSync(
|
|
48
|
+
path.join(SERVER_OUT, 'package.json'),
|
|
49
|
+
JSON.stringify({ name: '@redwax/server', version: serverPkg.version, private: true }, null, 2)
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
// 3. Dashboard, freshly built.
|
|
53
|
+
execSync('npm run build --workspace @redwax/client', { cwd: REPO, stdio: 'inherit' });
|
|
54
|
+
fs.cpSync(path.join(REPO, 'apps', 'client', 'dist'), DASH_OUT, { recursive: true });
|
|
55
|
+
|
|
56
|
+
console.log('Bundled server and dashboard into the redwax package.');
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const helmet = require('helmet');
|
|
3
|
+
const cors = require('cors');
|
|
4
|
+
const morgan = require('morgan');
|
|
5
|
+
const cookieParser = require('cookie-parser');
|
|
6
|
+
const swaggerUi = require('swagger-ui-express');
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
|
|
10
|
+
const logger = require('./utils/logger');
|
|
11
|
+
const ApiError = require('./utils/apiError');
|
|
12
|
+
const openapi = require('./config/openapi');
|
|
13
|
+
const { metricsMiddleware, metricsHandler } = require('./config/metrics');
|
|
14
|
+
const { globalLimiter } = require('./middleware/rateLimit.middleware');
|
|
15
|
+
const store = require('./store');
|
|
16
|
+
const { CLIENT_URL, NODE_ENV, TRUST_PROXY, DASHBOARD_DIR } = require('./config/env');
|
|
17
|
+
|
|
18
|
+
const authRoutes = require('./routes/auth.routes');
|
|
19
|
+
const projectRoutes = require('./routes/project.routes');
|
|
20
|
+
|
|
21
|
+
const API_PREFIX = '/api/v1';
|
|
22
|
+
|
|
23
|
+
function createApp() {
|
|
24
|
+
const app = express();
|
|
25
|
+
|
|
26
|
+
// Required for correct req.ip in audit records when behind a reverse proxy.
|
|
27
|
+
if (TRUST_PROXY) app.set('trust proxy', 1);
|
|
28
|
+
app.disable('x-powered-by');
|
|
29
|
+
|
|
30
|
+
app.use(
|
|
31
|
+
helmet({
|
|
32
|
+
hsts: { maxAge: 31_536_000, includeSubDomains: true, preload: true },
|
|
33
|
+
// The dashboard (served here in single-process mode) and Swagger UI load
|
|
34
|
+
// third-party fonts and inline styles; a strict CSP would break both.
|
|
35
|
+
contentSecurityPolicy: false,
|
|
36
|
+
crossOriginEmbedderPolicy: false,
|
|
37
|
+
})
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
app.use(cors({ origin: CLIENT_URL, credentials: true }));
|
|
41
|
+
app.use(express.json({ limit: '2mb' }));
|
|
42
|
+
app.use(cookieParser());
|
|
43
|
+
app.use(metricsMiddleware);
|
|
44
|
+
|
|
45
|
+
if (NODE_ENV !== 'test') {
|
|
46
|
+
app.use(morgan('combined', { stream: { write: (msg) => logger.info(msg.trim()) } }));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/* ── operational endpoints (unauthenticated, unrated) ─────────────────── */
|
|
50
|
+
|
|
51
|
+
app.get('/health', (_req, res) => {
|
|
52
|
+
const up = store.isConnected();
|
|
53
|
+
res.status(up ? 200 : 503).json({
|
|
54
|
+
status: up ? 'ok' : 'degraded',
|
|
55
|
+
database: up ? 'connected' : 'disconnected',
|
|
56
|
+
store: up ? store.kind : null,
|
|
57
|
+
uptime: process.uptime(),
|
|
58
|
+
version: require('../package.json').version,
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
app.get('/metrics', metricsHandler);
|
|
63
|
+
|
|
64
|
+
app.get('/api-docs.json', (_req, res) => res.json(openapi));
|
|
65
|
+
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openapi, { customSiteTitle: 'Redwax API' }));
|
|
66
|
+
|
|
67
|
+
/* ── API ──────────────────────────────────────────────────────────────── */
|
|
68
|
+
|
|
69
|
+
// Responses carry decrypted secrets and tokens — keep them out of browser
|
|
70
|
+
// and intermediary caches.
|
|
71
|
+
app.use(API_PREFIX, (_req, res, next) => {
|
|
72
|
+
res.set('Cache-Control', 'no-store');
|
|
73
|
+
res.set('Pragma', 'no-cache');
|
|
74
|
+
next();
|
|
75
|
+
});
|
|
76
|
+
app.use(API_PREFIX, globalLimiter);
|
|
77
|
+
app.use(`${API_PREFIX}/auth`, authRoutes);
|
|
78
|
+
app.use(`${API_PREFIX}/projects`, projectRoutes);
|
|
79
|
+
|
|
80
|
+
/* ── dashboard (single-process mode) ──────────────────────────────────── */
|
|
81
|
+
|
|
82
|
+
// With DASHBOARD_DIR set, this one port serves the UI as well as the API,
|
|
83
|
+
// which is what lets `npx redwax-cli server` run without nginx or Docker.
|
|
84
|
+
const dashboardIndex = DASHBOARD_DIR && path.join(DASHBOARD_DIR, 'index.html');
|
|
85
|
+
if (dashboardIndex && fs.existsSync(dashboardIndex)) {
|
|
86
|
+
// Hashed asset filenames, so they can be cached indefinitely.
|
|
87
|
+
app.use('/assets', express.static(path.join(DASHBOARD_DIR, 'assets'), { immutable: true, maxAge: '1y' }));
|
|
88
|
+
app.use(express.static(DASHBOARD_DIR, { index: false }));
|
|
89
|
+
|
|
90
|
+
// Client-side routes (/projects/…, /login) all resolve to index.html,
|
|
91
|
+
// which must never be cached or clients pin to a stale bundle.
|
|
92
|
+
const reserved = /^\/(api|health|metrics|api-docs)(\/|$|\.)/;
|
|
93
|
+
app.get(/.*/, (req, res, next) => {
|
|
94
|
+
if (reserved.test(req.path) || !req.accepts('html')) return next();
|
|
95
|
+
res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
|
|
96
|
+
res.sendFile(dashboardIndex);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/* ── 404 + error handling ─────────────────────────────────────────────── */
|
|
101
|
+
|
|
102
|
+
app.use((req, _res, next) => {
|
|
103
|
+
next(new ApiError(404, `Cannot ${req.method} ${req.originalUrl}`));
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
// eslint-disable-next-line no-unused-vars -- Express identifies error handlers by arity
|
|
107
|
+
app.use((err, _req, res, _next) => {
|
|
108
|
+
// body-parser errors (malformed JSON, oversized body) carry `status`.
|
|
109
|
+
let status = err.statusCode || err.status || 500;
|
|
110
|
+
let message = err.message;
|
|
111
|
+
|
|
112
|
+
if (err.name === 'ValidationError') {
|
|
113
|
+
status = 400;
|
|
114
|
+
message = Object.values(err.errors || {}).map((e) => e.message).join(', ') || message;
|
|
115
|
+
} else if (err.name === 'CastError') {
|
|
116
|
+
status = 400;
|
|
117
|
+
message = `Invalid value for '${err.path}'`;
|
|
118
|
+
} else if (err.code === 11000) {
|
|
119
|
+
status = 409;
|
|
120
|
+
message = `Duplicate value for ${Object.keys(err.keyValue || {}).join(', ')}`;
|
|
121
|
+
} else if (err.name === 'ZodError') {
|
|
122
|
+
status = 400;
|
|
123
|
+
message = err.issues.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (status >= 500) {
|
|
127
|
+
logger.error('Unhandled error', { message: err.message, stack: err.stack });
|
|
128
|
+
} else {
|
|
129
|
+
logger.warn('Request failed', { status, message });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
res.status(status).json({
|
|
133
|
+
// Never leak internal error details (driver messages etc.) in production.
|
|
134
|
+
error: status >= 500 && NODE_ENV === 'production' ? 'Internal server error' : message,
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
return app;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = createApp;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const { z } = require('zod');
|
|
2
|
+
|
|
3
|
+
// z.coerce.boolean() turns any non-empty string into true, so 'false' would
|
|
4
|
+
// enable the flag. Parse the usual spellings explicitly instead.
|
|
5
|
+
const envBoolean = (fallback) =>
|
|
6
|
+
z
|
|
7
|
+
.union([z.boolean(), z.string()])
|
|
8
|
+
.optional()
|
|
9
|
+
.transform((v, ctx) => {
|
|
10
|
+
if (v === undefined || v === '') return fallback;
|
|
11
|
+
if (typeof v === 'boolean') return v;
|
|
12
|
+
const normalized = v.trim().toLowerCase();
|
|
13
|
+
if (['true', '1', 'yes', 'on'].includes(normalized)) return true;
|
|
14
|
+
if (['false', '0', 'no', 'off'].includes(normalized)) return false;
|
|
15
|
+
ctx.addIssue({ code: 'custom', message: 'Expected true or false' });
|
|
16
|
+
return z.NEVER;
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const path = require('path');
|
|
20
|
+
|
|
21
|
+
const optionalString = z.preprocess((v) => (v === '' ? undefined : v), z.string().optional());
|
|
22
|
+
|
|
23
|
+
const schema = z.object({
|
|
24
|
+
PORT: z.coerce.number().int().positive().default(4000),
|
|
25
|
+
// Interface to listen on. Unset means Node's default (all interfaces), which
|
|
26
|
+
// is what Docker needs; `redwax server` passes 127.0.0.1 unless --share.
|
|
27
|
+
HOST: optionalString,
|
|
28
|
+
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
|
|
29
|
+
LOG_LEVEL: z.string().default('info'),
|
|
30
|
+
|
|
31
|
+
// ── database ─────────────────────────────────────────────────────────────
|
|
32
|
+
// `sqlite` keeps everything in one local file and needs no database server.
|
|
33
|
+
// `mongo` uses MONGO_URI. When DATABASE is unset, MONGO_URI decides.
|
|
34
|
+
DATABASE: z.preprocess((v) => (v === '' ? undefined : v), z.enum(['sqlite', 'mongo']).optional()),
|
|
35
|
+
MONGO_URI: optionalString,
|
|
36
|
+
SQLITE_PATH: optionalString,
|
|
37
|
+
|
|
38
|
+
// Built dashboard to serve from this process (apps/client/dist). When set,
|
|
39
|
+
// one port serves both the API and the UI — no nginx required.
|
|
40
|
+
DASHBOARD_DIR: optionalString,
|
|
41
|
+
|
|
42
|
+
// 32-byte AES-256 key, hex encoded.
|
|
43
|
+
MASTER_KEY: z.string().regex(/^[a-f\d]{64}$/i, 'MASTER_KEY must be 64 hex characters (32 bytes)'),
|
|
44
|
+
|
|
45
|
+
// RS256 keypair. Optional — generated on first boot when absent (see config/keys.js).
|
|
46
|
+
JWT_PRIVATE_KEY: z.string().optional(),
|
|
47
|
+
JWT_PUBLIC_KEY: z.string().optional(),
|
|
48
|
+
JWT_KEYS_DIR: z.string().optional(),
|
|
49
|
+
|
|
50
|
+
JWT_EXPIRES_IN: z.string().default('15m'),
|
|
51
|
+
REFRESH_TOKEN_EXPIRES_IN: z.string().default('7d'),
|
|
52
|
+
|
|
53
|
+
CLIENT_URL: z.string().url().default('http://localhost:3000'),
|
|
54
|
+
TRUST_PROXY: envBoolean(false),
|
|
55
|
+
|
|
56
|
+
// Set to false to close sign-up once your team has registered.
|
|
57
|
+
ALLOW_REGISTRATION: envBoolean(true),
|
|
58
|
+
|
|
59
|
+
// Bearer token required by /metrics. Without it /metrics is open outside
|
|
60
|
+
// production and disabled in production.
|
|
61
|
+
METRICS_TOKEN: z.preprocess(
|
|
62
|
+
(v) => (v === '' ? undefined : v),
|
|
63
|
+
z.string().min(16, 'METRICS_TOKEN must be at least 16 characters').optional()
|
|
64
|
+
),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/** Resolve the database choice once, so every caller agrees on it. */
|
|
68
|
+
const resolved = schema
|
|
69
|
+
.transform((env) => {
|
|
70
|
+
const DATABASE = env.DATABASE || (env.MONGO_URI ? 'mongo' : 'sqlite');
|
|
71
|
+
const SQLITE_PATH =
|
|
72
|
+
env.SQLITE_PATH === ':memory:'
|
|
73
|
+
? ':memory:'
|
|
74
|
+
: path.resolve(env.SQLITE_PATH || path.join(process.cwd(), 'data', 'redwax.db'));
|
|
75
|
+
return { ...env, DATABASE, SQLITE_PATH };
|
|
76
|
+
})
|
|
77
|
+
.superRefine((env, ctx) => {
|
|
78
|
+
if (env.DATABASE === 'mongo' && !env.MONGO_URI) {
|
|
79
|
+
ctx.addIssue({
|
|
80
|
+
code: 'custom',
|
|
81
|
+
path: ['MONGO_URI'],
|
|
82
|
+
message: 'DATABASE=mongo needs MONGO_URI (or leave DATABASE unset to use the built-in SQLite file)',
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const parsed = resolved.safeParse(process.env);
|
|
88
|
+
|
|
89
|
+
if (!parsed.success) {
|
|
90
|
+
const details = JSON.stringify(z.flattenError(parsed.error).fieldErrors, null, 2);
|
|
91
|
+
// In tests we throw so the runner reports it; elsewhere a clean exit is friendlier.
|
|
92
|
+
if (process.env.NODE_ENV === 'test') {
|
|
93
|
+
throw new Error(`Invalid environment variables:\n${details}`);
|
|
94
|
+
}
|
|
95
|
+
console.error('X Invalid environment variables:');
|
|
96
|
+
console.error(details);
|
|
97
|
+
console.error('\nCopy .env.example to .env and run: npm run generate:key');
|
|
98
|
+
console.error('No Docker or MongoDB? `npx redwax-cli server` sets all of this up for you.');
|
|
99
|
+
process.exit(1);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = parsed.data;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
|
|
5
|
+
const { JWT_PRIVATE_KEY, JWT_PUBLIC_KEY, JWT_KEYS_DIR } = require('./env');
|
|
6
|
+
const logger = require('../utils/logger');
|
|
7
|
+
|
|
8
|
+
const KEYS_DIR = JWT_KEYS_DIR || path.resolve(__dirname, '..', '..', 'keys');
|
|
9
|
+
const PRIVATE_PATH = path.join(KEYS_DIR, 'jwt.private.pem');
|
|
10
|
+
const PUBLIC_PATH = path.join(KEYS_DIR, 'jwt.public.pem');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Env vars can hold a raw PEM (with literal \n escapes, as in .env files) or a
|
|
14
|
+
* base64-encoded PEM, whichever is easier for the deployment platform.
|
|
15
|
+
*/
|
|
16
|
+
function normalizePem(value) {
|
|
17
|
+
if (!value) return null;
|
|
18
|
+
const unescaped = value.replace(/\\n/g, '\n');
|
|
19
|
+
if (unescaped.includes('-----BEGIN')) return unescaped;
|
|
20
|
+
try {
|
|
21
|
+
const decoded = Buffer.from(value, 'base64').toString('utf8');
|
|
22
|
+
return decoded.includes('-----BEGIN') ? decoded : null;
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function fromEnv() {
|
|
29
|
+
const privateKey = normalizePem(JWT_PRIVATE_KEY);
|
|
30
|
+
const publicKey = normalizePem(JWT_PUBLIC_KEY);
|
|
31
|
+
if (privateKey && publicKey) return { privateKey, publicKey, source: 'env' };
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fromDisk() {
|
|
36
|
+
try {
|
|
37
|
+
if (fs.existsSync(PRIVATE_PATH) && fs.existsSync(PUBLIC_PATH)) {
|
|
38
|
+
return {
|
|
39
|
+
privateKey: fs.readFileSync(PRIVATE_PATH, 'utf8'),
|
|
40
|
+
publicKey: fs.readFileSync(PUBLIC_PATH, 'utf8'),
|
|
41
|
+
source: 'disk',
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
} catch (err) {
|
|
45
|
+
logger.warn('Could not read JWT keypair from disk', { error: err.message });
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function generate() {
|
|
51
|
+
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
|
|
52
|
+
modulusLength: 2048,
|
|
53
|
+
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
|
54
|
+
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// Persist so tokens survive a restart. A read-only filesystem is not fatal —
|
|
58
|
+
// the keypair simply lives for the lifetime of the process.
|
|
59
|
+
try {
|
|
60
|
+
fs.mkdirSync(KEYS_DIR, { recursive: true });
|
|
61
|
+
fs.writeFileSync(PRIVATE_PATH, privateKey, { mode: 0o600 });
|
|
62
|
+
fs.writeFileSync(PUBLIC_PATH, publicKey, { mode: 0o644 });
|
|
63
|
+
logger.info('Generated a new RS256 JWT keypair', { dir: KEYS_DIR });
|
|
64
|
+
} catch (err) {
|
|
65
|
+
logger.warn('Generated an ephemeral JWT keypair — could not persist it. Tokens will not survive a restart.', {
|
|
66
|
+
error: err.message,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return { privateKey, publicKey, source: 'generated' };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const keys = fromEnv() || fromDisk() || generate();
|
|
74
|
+
|
|
75
|
+
module.exports = {
|
|
76
|
+
privateKey: keys.privateKey,
|
|
77
|
+
publicKey: keys.publicKey,
|
|
78
|
+
source: keys.source,
|
|
79
|
+
// Exported for testing.
|
|
80
|
+
normalizePem,
|
|
81
|
+
};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* A minimal Prometheus exporter — just what this server reports, with no
|
|
5
|
+
* dependency. It replaced prom-client, which is deprecated and made every
|
|
6
|
+
* `npx redwax-cli` install print a warning. Output follows the Prometheus text
|
|
7
|
+
* exposition format 0.0.4, so existing scrape configs keep working.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
|
|
11
|
+
const DEFAULT_LABELS = { app: 'redwax' };
|
|
12
|
+
|
|
13
|
+
// Prometheus label values escape backslash, newline and double quote.
|
|
14
|
+
const escapeLabel = (v) => String(v).replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
|
|
15
|
+
const formatLabels = (labels) => {
|
|
16
|
+
const entries = Object.entries({ ...DEFAULT_LABELS, ...labels });
|
|
17
|
+
return `{${entries.map(([k, v]) => `${k}="${escapeLabel(v)}"`).join(',')}}`;
|
|
18
|
+
};
|
|
19
|
+
const keyOf = (labelNames, labels) => JSON.stringify(labelNames.map((n) => String(labels[n] ?? '')));
|
|
20
|
+
const fromKey = (labelNames, key) => Object.fromEntries(JSON.parse(key).map((v, i) => [labelNames[i], v]));
|
|
21
|
+
|
|
22
|
+
class Counter {
|
|
23
|
+
constructor({ name, help, labelNames = [] }) {
|
|
24
|
+
Object.assign(this, { name, help, labelNames, values: new Map() });
|
|
25
|
+
}
|
|
26
|
+
inc(labels = {}, by = 1) {
|
|
27
|
+
const key = keyOf(this.labelNames, labels);
|
|
28
|
+
this.values.set(key, (this.values.get(key) || 0) + by);
|
|
29
|
+
}
|
|
30
|
+
render() {
|
|
31
|
+
const lines = [`# HELP ${this.name} ${this.help}`, `# TYPE ${this.name} counter`];
|
|
32
|
+
for (const [key, value] of this.values) lines.push(`${this.name}${formatLabels(fromKey(this.labelNames, key))} ${value}`);
|
|
33
|
+
return lines;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
class Histogram {
|
|
38
|
+
constructor({ name, help, labelNames = [], buckets }) {
|
|
39
|
+
Object.assign(this, { name, help, labelNames, buckets: [...buckets].sort((x, y) => x - y), series: new Map() });
|
|
40
|
+
}
|
|
41
|
+
observe(labels, seconds) {
|
|
42
|
+
const key = keyOf(this.labelNames, labels);
|
|
43
|
+
let s = this.series.get(key);
|
|
44
|
+
if (!s) this.series.set(key, (s = { counts: this.buckets.map(() => 0), sum: 0, count: 0 }));
|
|
45
|
+
this.buckets.forEach((le, i) => { if (seconds <= le) s.counts[i] += 1; });
|
|
46
|
+
s.sum += seconds;
|
|
47
|
+
s.count += 1;
|
|
48
|
+
}
|
|
49
|
+
startTimer() {
|
|
50
|
+
const start = process.hrtime.bigint();
|
|
51
|
+
return (labels) => this.observe(labels, Number(process.hrtime.bigint() - start) / 1e9);
|
|
52
|
+
}
|
|
53
|
+
render() {
|
|
54
|
+
const lines = [`# HELP ${this.name} ${this.help}`, `# TYPE ${this.name} histogram`];
|
|
55
|
+
for (const [key, s] of this.series) {
|
|
56
|
+
const labels = fromKey(this.labelNames, key);
|
|
57
|
+
this.buckets.forEach((le, i) => lines.push(`${this.name}_bucket${formatLabels({ ...labels, le })} ${s.counts[i]}`));
|
|
58
|
+
lines.push(`${this.name}_bucket${formatLabels({ ...labels, le: '+Inf' })} ${s.count}`);
|
|
59
|
+
lines.push(`${this.name}_sum${formatLabels(labels)} ${s.sum}`);
|
|
60
|
+
lines.push(`${this.name}_count${formatLabels(labels)} ${s.count}`);
|
|
61
|
+
}
|
|
62
|
+
return lines;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Standard process gauges, named as prom-client named them. */
|
|
67
|
+
function processMetrics() {
|
|
68
|
+
const mem = process.memoryUsage();
|
|
69
|
+
const cpu = process.cpuUsage();
|
|
70
|
+
const gauge = (name, help, value, type = 'gauge') => [`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, `${name}${formatLabels({})} ${value}`];
|
|
71
|
+
return [
|
|
72
|
+
...gauge('process_cpu_user_seconds_total', 'User CPU time spent in seconds.', cpu.user / 1e6, 'counter'),
|
|
73
|
+
...gauge('process_cpu_system_seconds_total', 'System CPU time spent in seconds.', cpu.system / 1e6, 'counter'),
|
|
74
|
+
...gauge('process_resident_memory_bytes', 'Resident memory size in bytes.', mem.rss),
|
|
75
|
+
...gauge('nodejs_heap_size_used_bytes', 'Process heap size used from Node.js in bytes.', mem.heapUsed),
|
|
76
|
+
...gauge('nodejs_heap_size_total_bytes', 'Process heap size from Node.js in bytes.', mem.heapTotal),
|
|
77
|
+
...gauge('process_start_time_seconds', 'Start time of the process since unix epoch in seconds.', Math.round(Date.now() / 1000 - process.uptime())),
|
|
78
|
+
];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const httpRequestDuration = new Histogram({
|
|
82
|
+
name: 'http_request_duration_seconds',
|
|
83
|
+
help: 'HTTP request duration in seconds',
|
|
84
|
+
labelNames: ['method', 'route', 'status'],
|
|
85
|
+
// Tuned around the p95 < 200ms target for secret reads and writes.
|
|
86
|
+
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.5, 1, 2, 5],
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const httpRequestsTotal = new Counter({
|
|
90
|
+
name: 'http_requests_total',
|
|
91
|
+
help: 'Total HTTP requests',
|
|
92
|
+
labelNames: ['method', 'route', 'status'],
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const secretOperations = new Counter({
|
|
96
|
+
name: 'redwax_secret_operations_total',
|
|
97
|
+
help: 'Secret reads, writes and deletes',
|
|
98
|
+
labelNames: ['operation'],
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const registry = {
|
|
102
|
+
contentType: CONTENT_TYPE,
|
|
103
|
+
async metrics() {
|
|
104
|
+
const lines = [
|
|
105
|
+
...processMetrics(),
|
|
106
|
+
...httpRequestDuration.render(),
|
|
107
|
+
...httpRequestsTotal.render(),
|
|
108
|
+
...secretOperations.render(),
|
|
109
|
+
];
|
|
110
|
+
return `${lines.join('\n')}\n`;
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Label by the matched route pattern rather than the raw URL, so secret keys
|
|
116
|
+
* and project ids never become metric labels (that would explode cardinality
|
|
117
|
+
* and leak key names into the metrics endpoint).
|
|
118
|
+
*/
|
|
119
|
+
function routeLabel(req) {
|
|
120
|
+
const mounted = req.baseUrl || '';
|
|
121
|
+
const matched = req.route?.path;
|
|
122
|
+
if (matched) return `${mounted}${matched === '/' ? '' : matched}` || '/';
|
|
123
|
+
return mounted || 'unmatched';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function metricsMiddleware(req, res, next) {
|
|
127
|
+
const endTimer = httpRequestDuration.startTimer();
|
|
128
|
+
res.on('finish', () => {
|
|
129
|
+
const labels = { method: req.method, route: routeLabel(req), status: res.statusCode };
|
|
130
|
+
endTimer(labels);
|
|
131
|
+
httpRequestsTotal.inc(labels);
|
|
132
|
+
});
|
|
133
|
+
next();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* /metrics exposes process and traffic details, so it is not public:
|
|
138
|
+
* with METRICS_TOKEN set a matching Bearer token is required; without one it
|
|
139
|
+
* is only served outside production.
|
|
140
|
+
*/
|
|
141
|
+
function metricsAuthorized(req) {
|
|
142
|
+
const { METRICS_TOKEN, NODE_ENV } = require('./env');
|
|
143
|
+
if (!METRICS_TOKEN) return NODE_ENV !== 'production';
|
|
144
|
+
|
|
145
|
+
const header = req.get('authorization') || '';
|
|
146
|
+
if (!header.startsWith('Bearer ')) return false;
|
|
147
|
+
const presented = Buffer.from(header.slice('Bearer '.length).trim());
|
|
148
|
+
const expected = Buffer.from(METRICS_TOKEN);
|
|
149
|
+
return presented.length === expected.length && crypto.timingSafeEqual(presented, expected);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function metricsHandler(req, res) {
|
|
153
|
+
if (!metricsAuthorized(req)) {
|
|
154
|
+
res.status(404).json({ error: 'Not found' });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
res.set('Content-Type', registry.contentType);
|
|
158
|
+
res.end(await registry.metrics());
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
module.exports = { registry, metricsMiddleware, metricsHandler, secretOperations, routeLabel, Counter, Histogram };
|