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,64 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
|
|
5
|
+
const { authenticatedClient, requireProject } = require('../lib/api');
|
|
6
|
+
const dotenv = require('../lib/dotenv');
|
|
7
|
+
const { fail, describeError, symbols, c, info, safe } = require('../lib/ui');
|
|
8
|
+
|
|
9
|
+
/** Secrets end up on terminals and in CI logs — never print them in full. */
|
|
10
|
+
function mask(value) {
|
|
11
|
+
if (value === '') return c.dim('(empty)');
|
|
12
|
+
if (value.length <= 8) return c.dim('•'.repeat(value.length));
|
|
13
|
+
return c.dim(`${value.slice(0, 3)}${'•'.repeat(Math.min(12, value.length - 6))}${value.slice(-3)}`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
module.exports = new Command('diff')
|
|
17
|
+
.description('Compare the local .env against the remote environment')
|
|
18
|
+
.option('-e, --env <environment>', 'Environment to compare against (defaults to the linked one)')
|
|
19
|
+
.option('-f, --file <path>', 'Local file', '.env')
|
|
20
|
+
.option('--show-values', 'Print values in full instead of masking them', false)
|
|
21
|
+
.action(async (options) => {
|
|
22
|
+
const config = requireProject();
|
|
23
|
+
const environment = options.env || config.environment;
|
|
24
|
+
const filePath = path.resolve(process.cwd(), options.file);
|
|
25
|
+
|
|
26
|
+
const exists = fs.existsSync(filePath);
|
|
27
|
+
const local = exists ? dotenv.parse(fs.readFileSync(filePath, 'utf8')) : {};
|
|
28
|
+
if (!exists) info(`${options.file} does not exist — treating it as empty.`);
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const { data } = await authenticatedClient().get(`/projects/${config.projectId}/secrets/export`, {
|
|
32
|
+
params: { environment, format: 'json' },
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const remote = data.secrets;
|
|
36
|
+
const { added, removed, changed, unchanged } = dotenv.diff(local, remote);
|
|
37
|
+
const show = (v) => (options.showValues ? safe(v) : mask(v));
|
|
38
|
+
|
|
39
|
+
console.log(`\n${c.bold(options.file)} vs ${c.bold(`${config.slug}/${environment}`)}\n`);
|
|
40
|
+
|
|
41
|
+
if (!added.length && !removed.length && !changed.length) {
|
|
42
|
+
console.log(` ${symbols.ok} In sync — ${unchanged.length} key(s) match.\n`);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
added.forEach((key) => console.log(` ${symbols.add} ${c.green(key)} ${c.dim('local only')} ${show(local[key])}`));
|
|
47
|
+
removed.forEach((key) => console.log(` ${symbols.del} ${c.red(safe(key))} ${c.dim('remote only')} ${show(remote[key])}`));
|
|
48
|
+
changed.forEach((key) => {
|
|
49
|
+
console.log(` ${symbols.chg} ${c.yellow(key)}`);
|
|
50
|
+
console.log(` ${c.dim('local ')} ${show(local[key])}`);
|
|
51
|
+
console.log(` ${c.dim('remote')} ${show(remote[key])}`);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
console.log(
|
|
55
|
+
`\n ${added.length} local-only, ${removed.length} remote-only, ` +
|
|
56
|
+
`${changed.length} changed, ${unchanged.length} identical\n`
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
// Non-zero exit so CI can gate on configuration drift.
|
|
60
|
+
process.exitCode = 1;
|
|
61
|
+
} catch (err) {
|
|
62
|
+
fail(describeError(err));
|
|
63
|
+
}
|
|
64
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const { Command } = require('commander');
|
|
2
|
+
|
|
3
|
+
const { authenticatedClient, requireProject } = require('../lib/api');
|
|
4
|
+
const { fail, describeError, table, c, info, safe } = require('../lib/ui');
|
|
5
|
+
|
|
6
|
+
function truncate(value, max) {
|
|
7
|
+
if (value === null) return c.dim('(deleted)');
|
|
8
|
+
if (value === '') return c.dim('(empty)');
|
|
9
|
+
const clean = safe(value);
|
|
10
|
+
return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
module.exports = new Command('history')
|
|
14
|
+
.description('Show the version history of a single key')
|
|
15
|
+
.argument('<key>', 'Secret key, e.g. DATABASE_URL')
|
|
16
|
+
.option('-e, --env <environment>', 'Environment (defaults to the linked one)')
|
|
17
|
+
.option('-n, --limit <count>', 'Number of versions to show', '20')
|
|
18
|
+
.option('--full', 'Print values in full instead of truncating them', false)
|
|
19
|
+
.action(async (key, options) => {
|
|
20
|
+
const config = requireProject();
|
|
21
|
+
const environment = options.env || config.environment;
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
const { data } = await authenticatedClient().get(
|
|
25
|
+
`/projects/${config.projectId}/secrets/${encodeURIComponent(key)}/history`,
|
|
26
|
+
{ params: { environment } }
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
const limit = Math.max(1, Number(options.limit) || 20);
|
|
30
|
+
const versions = data.versions.slice(0, limit);
|
|
31
|
+
|
|
32
|
+
console.log(
|
|
33
|
+
`\n${c.bold(key)} in ${c.bold(`${config.slug}/${environment}`)} — ` +
|
|
34
|
+
`${data.versions.length} version(s) retained${data.deleted ? c.red(' (deleted)') : ''}\n`
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
table(versions, [
|
|
38
|
+
{ header: 'VERSION', value: (v) => (v.version === data.currentVersion ? `${v.version} *` : String(v.version)) },
|
|
39
|
+
{ header: 'ACTION', value: (v) => safe(v.action) },
|
|
40
|
+
{ header: 'WHEN', value: (v) => new Date(v.changedAt).toISOString().replace('T', ' ').slice(0, 19) },
|
|
41
|
+
{ header: 'WHO', value: (v) => safe(v.changedBy?.email || 'unknown') },
|
|
42
|
+
{ header: 'VALUE', value: (v) => (options.full ? (v.value === null ? c.dim('(deleted)') : safe(v.value)) : truncate(v.value, 40)) },
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
console.log('');
|
|
46
|
+
if (data.versions.length > versions.length) {
|
|
47
|
+
info(`Showing ${versions.length} of ${data.versions.length}. Use --limit to see more.`);
|
|
48
|
+
}
|
|
49
|
+
info('* marks the current version. Up to 50 versions are retained per key.');
|
|
50
|
+
} catch (err) {
|
|
51
|
+
if (err.response?.status === 404) {
|
|
52
|
+
fail(`No secret '${key}' in ${environment}`);
|
|
53
|
+
}
|
|
54
|
+
fail(describeError(err));
|
|
55
|
+
}
|
|
56
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
|
|
5
|
+
const { authenticatedClient, resolveServerUrl } = require('../lib/api');
|
|
6
|
+
const { writeConfig, CONFIG_FILE } = require('../lib/config');
|
|
7
|
+
const { success, info, warn, fail, describeError, c, safe } = require('../lib/ui');
|
|
8
|
+
|
|
9
|
+
/** Warn when .env is not ignored — the whole point is to stop committing it. */
|
|
10
|
+
function checkGitignore(dir) {
|
|
11
|
+
const gitignorePath = path.join(dir, '.gitignore');
|
|
12
|
+
if (!fs.existsSync(path.join(dir, '.git'))) return;
|
|
13
|
+
|
|
14
|
+
const contents = fs.existsSync(gitignorePath) ? fs.readFileSync(gitignorePath, 'utf8') : '';
|
|
15
|
+
const ignored = contents.split(/\r?\n/).some((line) => ['.env', '*.env', '.env*'].includes(line.trim()));
|
|
16
|
+
|
|
17
|
+
if (!ignored) {
|
|
18
|
+
warn('.env is not listed in .gitignore — add it before your next commit.');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module.exports = new Command('init')
|
|
23
|
+
.description('Link this directory to a Redwax project')
|
|
24
|
+
.argument('<project-slug>', 'Project slug, e.g. payments-api')
|
|
25
|
+
.option('-e, --env <environment>', 'Default environment for this directory', 'development')
|
|
26
|
+
.action(async (slug, options) => {
|
|
27
|
+
try {
|
|
28
|
+
const { data } = await authenticatedClient().get(`/projects/slug/${encodeURIComponent(slug)}`);
|
|
29
|
+
const project = data.project;
|
|
30
|
+
|
|
31
|
+
if (!project.environments.includes(options.env)) {
|
|
32
|
+
fail(
|
|
33
|
+
`Project '${project.slug}' has no environment '${options.env}'`,
|
|
34
|
+
`Available: ${project.environments.join(', ')}`
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const target = writeConfig({
|
|
39
|
+
projectId: project.id,
|
|
40
|
+
slug: project.slug,
|
|
41
|
+
environment: options.env,
|
|
42
|
+
serverUrl: resolveServerUrl(),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
success(`Linked to ${c.bold(safe(project.name))} (${safe(project.slug)})`);
|
|
46
|
+
info(`Environment: ${options.env} Role: ${project.role}`);
|
|
47
|
+
info(`Wrote ${path.basename(target)} — commit it so your team shares the link.`);
|
|
48
|
+
|
|
49
|
+
checkGitignore(process.cwd());
|
|
50
|
+
console.log(`\nNext: ${c.cyan('redwax pull')} to fetch secrets, or ${c.cyan('redwax push')} to upload your local .env`);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (err.response?.status === 404) {
|
|
53
|
+
fail(`No project with slug '${slug}', or you are not a member of it`);
|
|
54
|
+
}
|
|
55
|
+
fail(describeError(err));
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
module.exports.CONFIG_FILE = CONFIG_FILE;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const { Command } = require('commander');
|
|
2
|
+
|
|
3
|
+
const { createClient, DEFAULT_SERVER } = require('../lib/api');
|
|
4
|
+
const { saveCredentials } = require('../lib/credentials');
|
|
5
|
+
const { ask, askHidden } = require('../lib/prompt');
|
|
6
|
+
const { success, info, warn, fail, describeError, c } = require('../lib/ui');
|
|
7
|
+
|
|
8
|
+
module.exports = new Command('login')
|
|
9
|
+
.description('Authenticate with your Redwax server')
|
|
10
|
+
.option('-s, --server <url>', 'API base URL', process.env.REDWAX_SERVER || DEFAULT_SERVER)
|
|
11
|
+
.option('-e, --email <email>', 'Email address')
|
|
12
|
+
.action(async (options) => {
|
|
13
|
+
const server = options.server.replace(/\/+$/, '');
|
|
14
|
+
|
|
15
|
+
let parsed;
|
|
16
|
+
try {
|
|
17
|
+
parsed = new URL(server);
|
|
18
|
+
} catch {
|
|
19
|
+
fail(`Invalid server URL: ${server}`);
|
|
20
|
+
}
|
|
21
|
+
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
|
22
|
+
fail(`Server URL must use http or https: ${server}`);
|
|
23
|
+
}
|
|
24
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
|
|
25
|
+
if (parsed.protocol === 'http:' && !local) {
|
|
26
|
+
warn('This server is not using HTTPS — your password, tokens and secrets will cross the network unencrypted.');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// REDWAX_PASSWORD lets CI log in without a TTY.
|
|
30
|
+
const email = options.email || process.env.REDWAX_EMAIL || (await ask('Email: '));
|
|
31
|
+
const password = process.env.REDWAX_PASSWORD || (await askHidden('Password: '));
|
|
32
|
+
|
|
33
|
+
if (!email || !password) fail('Email and password are required');
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
const client = createClient({ baseURL: server, withAuth: false });
|
|
37
|
+
const { data } = await client.post('/auth/login', { email, password });
|
|
38
|
+
|
|
39
|
+
saveCredentials({
|
|
40
|
+
serverUrl: server,
|
|
41
|
+
accessToken: data.accessToken,
|
|
42
|
+
refreshToken: data.refreshToken,
|
|
43
|
+
userId: data.user.id,
|
|
44
|
+
email: data.user.email,
|
|
45
|
+
name: data.user.name,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
success(`Logged in as ${c.bold(data.user.email)}`);
|
|
49
|
+
info(`Server: ${server}`);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
fail(`Login failed: ${describeError(err)}`);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { Command } = require('commander');
|
|
2
|
+
|
|
3
|
+
const { createClient } = require('../lib/api');
|
|
4
|
+
const { getCredentials, clearCredentials } = require('../lib/credentials');
|
|
5
|
+
const { success, info, warn } = require('../lib/ui');
|
|
6
|
+
|
|
7
|
+
module.exports = new Command('logout')
|
|
8
|
+
.description('Sign out and delete the stored credentials')
|
|
9
|
+
.action(async () => {
|
|
10
|
+
const creds = getCredentials();
|
|
11
|
+
|
|
12
|
+
if (!creds) {
|
|
13
|
+
info('You are not logged in.');
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Best effort — the local credentials are cleared either way. The refresh
|
|
18
|
+
// token goes only to the server that issued it, never to whatever the
|
|
19
|
+
// project's .redwax file names.
|
|
20
|
+
try {
|
|
21
|
+
if (!creds.serverUrl || !creds.refreshToken) throw new Error('nothing to revoke');
|
|
22
|
+
await createClient({ baseURL: creds.serverUrl.replace(/\/+$/, ''), withAuth: false })
|
|
23
|
+
.post('/auth/logout', { refreshToken: creds.refreshToken });
|
|
24
|
+
} catch {
|
|
25
|
+
warn('Could not reach the server to invalidate the session — clearing local credentials anyway.');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
clearCredentials();
|
|
29
|
+
success('Logged out');
|
|
30
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
|
|
5
|
+
const { authenticatedClient, requireProject } = require('../lib/api');
|
|
6
|
+
const dotenv = require('../lib/dotenv');
|
|
7
|
+
const { confirm } = require('../lib/prompt');
|
|
8
|
+
const { success, info, fail, describeError, c } = require('../lib/ui');
|
|
9
|
+
|
|
10
|
+
/** Owner-only access for files holding decrypted secrets (no-op on Windows). */
|
|
11
|
+
function restrictPermissions(file) {
|
|
12
|
+
try {
|
|
13
|
+
fs.chmodSync(file, 0o600);
|
|
14
|
+
} catch {
|
|
15
|
+
// Not supported on this platform — the directory ACL still applies.
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
module.exports = new Command('pull')
|
|
20
|
+
.description('Fetch secrets from Redwax and write them to a local .env')
|
|
21
|
+
.option('-e, --env <environment>', 'Source environment (defaults to the linked one)')
|
|
22
|
+
.option('-f, --file <path>', 'Destination file', '.env')
|
|
23
|
+
.option('--force', 'Overwrite without asking', false)
|
|
24
|
+
.option('--stdout', 'Print to stdout instead of writing a file', false)
|
|
25
|
+
.option('--no-backup', 'Skip writing a .backup copy of the existing file')
|
|
26
|
+
.action(async (options) => {
|
|
27
|
+
const config = requireProject();
|
|
28
|
+
const environment = options.env || config.environment;
|
|
29
|
+
const filePath = path.resolve(process.cwd(), options.file);
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
const { data } = await authenticatedClient().get(`/projects/${config.projectId}/secrets/export`, {
|
|
33
|
+
params: { environment, format: 'json' },
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const contents = dotenv.stringify(data.secrets);
|
|
37
|
+
const count = Object.keys(data.secrets).length;
|
|
38
|
+
|
|
39
|
+
if (options.stdout) {
|
|
40
|
+
process.stdout.write(contents);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (fs.existsSync(filePath) && !options.force) {
|
|
45
|
+
const existing = dotenv.parse(fs.readFileSync(filePath, 'utf8'));
|
|
46
|
+
const changes = dotenv.diff(existing, data.secrets);
|
|
47
|
+
const willChange = changes.added.length + changes.removed.length + changes.changed.length;
|
|
48
|
+
|
|
49
|
+
if (willChange === 0) {
|
|
50
|
+
success(`${options.file} is already up to date (${count} key(s))`);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
info(
|
|
55
|
+
`${options.file} exists and differs: ` +
|
|
56
|
+
`${changes.removed.length} to add, ${changes.changed.length} to change, ` +
|
|
57
|
+
`${changes.added.length} local-only key(s) will be lost.`
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
const proceed = await confirm(`Overwrite ${options.file}?`, false);
|
|
61
|
+
if (!proceed) {
|
|
62
|
+
fail('Aborted — nothing was written.', 'Run `redwax diff` to inspect, or pass --force.');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (options.backup) {
|
|
66
|
+
fs.copyFileSync(filePath, `${filePath}.backup`);
|
|
67
|
+
restrictPermissions(`${filePath}.backup`);
|
|
68
|
+
info(`Backed up to ${path.basename(filePath)}.backup`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// `mode` only applies when the file is created; tighten an existing one too.
|
|
73
|
+
fs.writeFileSync(filePath, contents, { mode: 0o600 });
|
|
74
|
+
restrictPermissions(filePath);
|
|
75
|
+
success(`Pulled ${count} secret(s) from ${c.bold(`${config.slug}/${environment}`)} into ${options.file}`);
|
|
76
|
+
} catch (err) {
|
|
77
|
+
if (err.response?.status === 404) {
|
|
78
|
+
fail(describeError(err), 'Check the environment name — try: redwax pull --env production');
|
|
79
|
+
}
|
|
80
|
+
fail(describeError(err));
|
|
81
|
+
}
|
|
82
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
|
|
5
|
+
const { authenticatedClient, requireProject } = require('../lib/api');
|
|
6
|
+
const dotenv = require('../lib/dotenv');
|
|
7
|
+
const { success, info, fail, describeError, symbols, c } = require('../lib/ui');
|
|
8
|
+
|
|
9
|
+
module.exports = new Command('push')
|
|
10
|
+
.description('Encrypt and upload the local .env to Redwax')
|
|
11
|
+
.option('-e, --env <environment>', 'Target environment (defaults to the linked one)')
|
|
12
|
+
.option('-f, --file <path>', 'Source file', '.env')
|
|
13
|
+
.option('--prune', 'Delete remote keys that are absent from the local file', false)
|
|
14
|
+
.option('--dry-run', 'Show what would change without writing', false)
|
|
15
|
+
.action(async (options) => {
|
|
16
|
+
const config = requireProject();
|
|
17
|
+
const environment = options.env || config.environment;
|
|
18
|
+
const filePath = path.resolve(process.cwd(), options.file);
|
|
19
|
+
|
|
20
|
+
if (!fs.existsSync(filePath)) {
|
|
21
|
+
fail(`No such file: ${options.file}`, 'Pass --file to point at a different .env');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const local = dotenv.parse(fs.readFileSync(filePath, 'utf8'));
|
|
25
|
+
const keys = Object.keys(local);
|
|
26
|
+
if (!keys.length) fail(`${options.file} contains no key-value pairs`);
|
|
27
|
+
|
|
28
|
+
const client = authenticatedClient();
|
|
29
|
+
const base = `/projects/${config.projectId}/secrets`;
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
if (options.dryRun) {
|
|
33
|
+
const { data } = await client.get(`${base}/export`, { params: { environment, format: 'json' } });
|
|
34
|
+
const changes = dotenv.diff(local, data.secrets);
|
|
35
|
+
|
|
36
|
+
console.log(c.bold(`\nPlanned changes for ${environment}:\n`));
|
|
37
|
+
changes.added.forEach((k) => console.log(` ${symbols.add} ${k} ${c.dim('(new)')}`));
|
|
38
|
+
changes.changed.forEach((k) => console.log(` ${symbols.chg} ${k} ${c.dim('(updated)')}`));
|
|
39
|
+
if (options.prune) changes.removed.forEach((k) => console.log(` ${symbols.del} ${k} ${c.dim('(deleted)')}`));
|
|
40
|
+
|
|
41
|
+
const total = changes.added.length + changes.changed.length + (options.prune ? changes.removed.length : 0);
|
|
42
|
+
console.log(total ? '' : c.dim(' Nothing to do — already in sync.\n'));
|
|
43
|
+
info(`${changes.unchanged.length} unchanged. Dry run — nothing was written.`);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const { data } = await client.post(`${base}/bulk`, {
|
|
48
|
+
environment,
|
|
49
|
+
prune: options.prune,
|
|
50
|
+
secrets: keys.map((key) => ({ key, value: local[key] })),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const parts = [
|
|
54
|
+
data.created && `${data.created} created`,
|
|
55
|
+
data.updated && `${data.updated} updated`,
|
|
56
|
+
data.restored && `${data.restored} restored`,
|
|
57
|
+
data.deleted && `${data.deleted} deleted`,
|
|
58
|
+
data.unchanged && `${data.unchanged} unchanged`,
|
|
59
|
+
].filter(Boolean);
|
|
60
|
+
|
|
61
|
+
success(`Pushed ${keys.length} key(s) to ${c.bold(`${config.slug}/${environment}`)}`);
|
|
62
|
+
info(parts.length ? parts.join(', ') : 'no changes');
|
|
63
|
+
|
|
64
|
+
if (!options.prune && data.unchanged === keys.length && data.created === 0) {
|
|
65
|
+
info('Remote keys missing locally were left alone. Use --prune to remove them.');
|
|
66
|
+
}
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (err.response?.status === 403) {
|
|
69
|
+
fail(describeError(err), 'Pushing needs the developer role or higher; --prune also needs delete rights.');
|
|
70
|
+
}
|
|
71
|
+
if (err.response?.status === 400) {
|
|
72
|
+
fail(describeError(err), 'Keys must be SCREAMING_SNAKE_CASE, e.g. DATABASE_URL');
|
|
73
|
+
}
|
|
74
|
+
fail(describeError(err));
|
|
75
|
+
}
|
|
76
|
+
});
|