depops 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +130 -2
- package/bin/depops.js +4 -0
- package/package.json +39 -4
- package/src/cli.js +925 -0
- package/src/compose.js +121 -0
- package/src/presets.js +39 -0
- package/src/ssh.js +188 -0
- package/src/vault.js +121 -0
package/src/compose.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Docker Compose helpers: find projects, read build info, and produce the server copy of the compose file.
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import YAML from 'yaml';
|
|
5
|
+
|
|
6
|
+
export const COMPOSE_NAMES = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];
|
|
7
|
+
const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'vendor', '.git']);
|
|
8
|
+
|
|
9
|
+
export async function findCompose(dir) {
|
|
10
|
+
for (const name of COMPOSE_NAMES) {
|
|
11
|
+
if (await fs.stat(path.join(dir, name)).then((s) => s.isFile(), () => false)) return name;
|
|
12
|
+
}
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Root compose → one project. Every sub-folder (up to 2 levels, e.g. backend/, apps/web/) with its own
|
|
18
|
+
* compose file → one more project. Any number of projects is supported.
|
|
19
|
+
*/
|
|
20
|
+
export async function detectProjects(root, maxDepth = 2) {
|
|
21
|
+
const found = [];
|
|
22
|
+
const walk = async (rel, depth) => {
|
|
23
|
+
const abs = path.join(root, rel);
|
|
24
|
+
const c = await findCompose(abs);
|
|
25
|
+
if (c) found.push({ name: rel === '.' ? path.basename(path.resolve(root)) : path.basename(rel), localDir: rel, composeFile: c });
|
|
26
|
+
if (depth >= maxDepth) return;
|
|
27
|
+
for (const entry of await fs.readdir(abs, { withFileTypes: true }).catch(() => [])) {
|
|
28
|
+
if (!entry.isDirectory() || entry.name.startsWith('.') || SKIP_DIRS.has(entry.name)) continue;
|
|
29
|
+
await walk(rel === '.' ? entry.name : `${rel}/${entry.name}`, depth + 1);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
await walk('.', 0);
|
|
33
|
+
// Same folder name in two places (apps/api, services/api) → use the full path as the name.
|
|
34
|
+
for (const f of found) if (found.filter((x) => x.name === f.name).length > 1) f.name = f.localDir.replace(/\//g, '-');
|
|
35
|
+
return found;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function loadCompose(file) {
|
|
39
|
+
const doc = YAML.parse(await fs.readFile(file, 'utf8'));
|
|
40
|
+
if (!doc || typeof doc.services !== 'object') throw new Error(`${file} has no "services" section.`);
|
|
41
|
+
return doc;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Compose-style ${VAR}, ${VAR:-default}, ${VAR-default}, $VAR substitution. */
|
|
45
|
+
export function interpolate(value, env) {
|
|
46
|
+
return String(value).replace(/\$\$|\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (m, a, op, def, b) => {
|
|
47
|
+
if (m === '$$') return '$';
|
|
48
|
+
const v = env[a || b];
|
|
49
|
+
if (op === ':-') return v ? v : def;
|
|
50
|
+
if (op === '-') return v !== undefined ? v : def;
|
|
51
|
+
return v ?? '';
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function argsToObject(args, env) {
|
|
56
|
+
const out = {};
|
|
57
|
+
if (Array.isArray(args)) {
|
|
58
|
+
for (const item of args) {
|
|
59
|
+
const [k, ...rest] = String(item).split('=');
|
|
60
|
+
out[k] = rest.length ? rest.join('=') : env[k] ?? '';
|
|
61
|
+
}
|
|
62
|
+
} else if (args && typeof args === 'object') {
|
|
63
|
+
for (const [k, v] of Object.entries(args)) out[k] = v == null ? env[k] ?? '' : v;
|
|
64
|
+
}
|
|
65
|
+
for (const k of Object.keys(out)) out[k] = interpolate(out[k], env);
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Everything that must be built locally and pushed, plus problems that would break a "pull only" server.
|
|
71
|
+
*/
|
|
72
|
+
export function analyze(doc, env = {}) {
|
|
73
|
+
const builds = [];
|
|
74
|
+
const problems = [];
|
|
75
|
+
const warnings = [];
|
|
76
|
+
for (const [service, svc] of Object.entries(doc.services || {})) {
|
|
77
|
+
const image = svc.image ? interpolate(svc.image, env) : '';
|
|
78
|
+
if (svc.build) {
|
|
79
|
+
if (!image) {
|
|
80
|
+
problems.push(`Service "${service}" has "build:" but no "image:". Add e.g. image: youruser/${service}:latest`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const b = typeof svc.build === 'string' ? { context: svc.build } : svc.build;
|
|
84
|
+
builds.push({
|
|
85
|
+
service,
|
|
86
|
+
image,
|
|
87
|
+
context: interpolate(b.context || '.', env),
|
|
88
|
+
dockerfile: b.dockerfile ? interpolate(b.dockerfile, env) : null,
|
|
89
|
+
target: b.target ? interpolate(b.target, env) : null,
|
|
90
|
+
args: argsToObject(b.args, env),
|
|
91
|
+
});
|
|
92
|
+
} else if (!image) {
|
|
93
|
+
problems.push(`Service "${service}" has neither "image:" nor "build:".`);
|
|
94
|
+
}
|
|
95
|
+
const envFiles = [].concat(svc.env_file ?? []).map((e) => (typeof e === 'string' ? e : e?.path));
|
|
96
|
+
for (const e of envFiles) {
|
|
97
|
+
if (e && path.posix.normalize(e) !== '.env') {
|
|
98
|
+
warnings.push(`Service "${service}" uses env_file "${e}". The server only gets ".env" — change it to env_file: .env`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { builds, problems, warnings };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** docker buildx argv for one service (no shell, so nothing needs quoting). */
|
|
106
|
+
export function buildArgv(projectDir, b, platform) {
|
|
107
|
+
const context = path.resolve(projectDir, b.context);
|
|
108
|
+
const argv = ['buildx', 'build', '--platform', platform, '-t', b.image];
|
|
109
|
+
if (b.dockerfile) argv.push('-f', path.resolve(context, b.dockerfile));
|
|
110
|
+
if (b.target) argv.push('--target', b.target);
|
|
111
|
+
for (const [k, v] of Object.entries(b.args)) argv.push('--build-arg', `${k}=${v}`);
|
|
112
|
+
argv.push('--push', context);
|
|
113
|
+
return argv;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The copy that goes to the server: same file without "build:" so the server only pulls images. */
|
|
117
|
+
export function serverCompose(doc) {
|
|
118
|
+
const copy = structuredClone(doc);
|
|
119
|
+
for (const svc of Object.values(copy.services || {})) delete svc.build;
|
|
120
|
+
return '# Generated by depops from your project compose file. Edit the original, not this copy.\n' + YAML.stringify(copy);
|
|
121
|
+
}
|
package/src/presets.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Deployment presets. Every preset only fills in default steps; users can edit them later (`depops edit`).
|
|
2
|
+
export const APP_TYPES = [
|
|
3
|
+
{ value: 'docker-registry', label: 'Docker: build here → push → server only gets docker-compose.yml + .env', hint: 'recommended' },
|
|
4
|
+
{ value: 'docker-build', label: 'Docker: git pull + build on the server (source code on server)' },
|
|
5
|
+
{ value: 'pm2', label: 'Node.js with PM2 (git pull + npm ci + build + reload)' },
|
|
6
|
+
{ value: 'static', label: 'Static site (build here → upload folder)' },
|
|
7
|
+
{ value: 'custom', label: 'Custom commands (Python, PHP, Go, systemd, anything)' },
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
export function presetSteps(type, opts = {}) {
|
|
11
|
+
switch (type) {
|
|
12
|
+
case 'docker-registry':
|
|
13
|
+
// Images are built from the compose file automatically; the server only pulls.
|
|
14
|
+
return {
|
|
15
|
+
localSteps: [],
|
|
16
|
+
remoteSteps: ['docker compose pull', 'docker compose up -d --remove-orphans --no-build', 'docker image prune -f', 'docker compose ps'],
|
|
17
|
+
};
|
|
18
|
+
case 'docker-build':
|
|
19
|
+
return {
|
|
20
|
+
localSteps: [],
|
|
21
|
+
remoteSteps: ['git pull --ff-only', 'docker compose up -d --build --remove-orphans', 'docker image prune -f', 'docker compose ps'],
|
|
22
|
+
};
|
|
23
|
+
case 'pm2':
|
|
24
|
+
return {
|
|
25
|
+
localSteps: [],
|
|
26
|
+
remoteSteps: [
|
|
27
|
+
'git pull --ff-only',
|
|
28
|
+
'npm ci',
|
|
29
|
+
'npm run build --if-present',
|
|
30
|
+
'pm2 startOrReload ecosystem.config.js --update-env',
|
|
31
|
+
'pm2 save',
|
|
32
|
+
],
|
|
33
|
+
};
|
|
34
|
+
case 'static':
|
|
35
|
+
return { localSteps: [opts.buildCmd || 'npm run build'], remoteSteps: [] };
|
|
36
|
+
default:
|
|
37
|
+
return { localSteps: [], remoteSteps: [] };
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/ssh.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import ssh2 from 'ssh2';
|
|
2
|
+
const { Client, utils } = ssh2;
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
export function shQuote(s) {
|
|
8
|
+
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function fingerprint(keyBuf) {
|
|
12
|
+
return 'SHA256:' + createHash('sha256').update(keyBuf).digest('base64').replace(/=+$/, '');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Strip host/IP/port/user from error messages so they never end up in logs or screenshots.
|
|
16
|
+
export function scrub(msg, server) {
|
|
17
|
+
let out = String(msg ?? '');
|
|
18
|
+
for (const v of [server?.host, server?.username, server?.port && String(server.port)]) {
|
|
19
|
+
if (v && String(v).length > 1) out = out.split(String(v)).join('<hidden>');
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function generateKeyPair(comment = 'depops') {
|
|
25
|
+
const { private: priv, public: pub } = utils.generateKeyPairSync('ed25519', { comment });
|
|
26
|
+
return { privateKey: priv, publicKey: pub };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function agentSocket() {
|
|
30
|
+
if (process.env.SSH_AUTH_SOCK) return process.env.SSH_AUTH_SOCK;
|
|
31
|
+
if (process.platform === 'win32') return '\\\\.\\pipe\\openssh-ssh-agent';
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Connect with strict host-key checking.
|
|
37
|
+
* - server.hostKey set: the server's key must match exactly, otherwise the connection is refused.
|
|
38
|
+
* - server.hostKey unset (first connect only): onNewHostKey(fp) decides whether to trust it.
|
|
39
|
+
*/
|
|
40
|
+
export function connect(server, { onNewHostKey, authOverride } = {}) {
|
|
41
|
+
const auth = authOverride ?? server.auth;
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const conn = new Client();
|
|
44
|
+
let seenKey = null;
|
|
45
|
+
let hostKeyMismatch = false;
|
|
46
|
+
const cfg = {
|
|
47
|
+
host: server.host,
|
|
48
|
+
port: Number(server.port) || 22,
|
|
49
|
+
username: server.username,
|
|
50
|
+
readyTimeout: 20000,
|
|
51
|
+
keepaliveInterval: 15000,
|
|
52
|
+
hostVerifier: (key) => {
|
|
53
|
+
seenKey = fingerprint(key);
|
|
54
|
+
if (server.hostKey) {
|
|
55
|
+
hostKeyMismatch = seenKey !== server.hostKey;
|
|
56
|
+
return !hostKeyMismatch;
|
|
57
|
+
}
|
|
58
|
+
return onNewHostKey ? true : false;
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
if (auth.type === 'key') {
|
|
62
|
+
cfg.privateKey = auth.privateKey;
|
|
63
|
+
if (auth.passphrase) cfg.passphrase = auth.passphrase;
|
|
64
|
+
} else if (auth.type === 'password') {
|
|
65
|
+
cfg.password = auth.password;
|
|
66
|
+
cfg.tryKeyboard = true;
|
|
67
|
+
conn.on('keyboard-interactive', (_n, _i, _l, prompts, finish) => finish(prompts.map(() => auth.password)));
|
|
68
|
+
} else if (auth.type === 'agent') {
|
|
69
|
+
cfg.agent = agentSocket();
|
|
70
|
+
if (!cfg.agent) return reject(new Error('No SSH agent found (SSH_AUTH_SOCK is not set).'));
|
|
71
|
+
} else {
|
|
72
|
+
return reject(new Error(`Unknown auth type: ${auth.type}`));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
conn
|
|
76
|
+
.on('ready', async () => {
|
|
77
|
+
if (!server.hostKey && onNewHostKey) {
|
|
78
|
+
let ok = false;
|
|
79
|
+
try {
|
|
80
|
+
ok = await onNewHostKey(seenKey);
|
|
81
|
+
} catch {}
|
|
82
|
+
if (!ok) {
|
|
83
|
+
conn.end();
|
|
84
|
+
return reject(new Error('Server host key was not trusted. Aborted.'));
|
|
85
|
+
}
|
|
86
|
+
conn.hostKey = seenKey;
|
|
87
|
+
}
|
|
88
|
+
resolve(conn);
|
|
89
|
+
})
|
|
90
|
+
.on('error', (err) => {
|
|
91
|
+
if (hostKeyMismatch) {
|
|
92
|
+
return reject(
|
|
93
|
+
new Error(
|
|
94
|
+
'HOST KEY MISMATCH! The server identity changed. This can be a man-in-the-middle attack.\n' +
|
|
95
|
+
'If you rebuilt the server on purpose, run `depops edit` and re-trust the host key.',
|
|
96
|
+
),
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
reject(new Error(scrub(err.message, server)));
|
|
100
|
+
})
|
|
101
|
+
.connect(cfg);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Run one command. Output streams to the terminal unless capture=true. */
|
|
106
|
+
export function exec(conn, command, { stdin, capture = false } = {}) {
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
conn.exec(command, (err, ch) => {
|
|
109
|
+
if (err) return reject(err);
|
|
110
|
+
let stdout = '';
|
|
111
|
+
let stderr = '';
|
|
112
|
+
ch.on('data', (d) => (capture ? (stdout += d) : process.stdout.write(d)));
|
|
113
|
+
ch.stderr.on('data', (d) => (capture ? (stderr += d) : process.stderr.write(d)));
|
|
114
|
+
ch.on('close', (code) => resolve({ code: code ?? 0, stdout, stderr }));
|
|
115
|
+
if (stdin != null) ch.end(stdin);
|
|
116
|
+
else ch.end();
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Run a bash script on the server without putting secrets on the command line:
|
|
123
|
+
* the script goes to a private temp file (0600) via stdin, the sudo password goes via stdin,
|
|
124
|
+
* and the file is always deleted afterwards.
|
|
125
|
+
*/
|
|
126
|
+
export async function runScript(conn, script, { sudo = null } = {}) {
|
|
127
|
+
const mk = await exec(conn, 'umask 077; f=$(mktemp /tmp/depops.XXXXXXXXXX) && cat > "$f" && printf %s "$f"', {
|
|
128
|
+
stdin: script,
|
|
129
|
+
capture: true,
|
|
130
|
+
});
|
|
131
|
+
const file = mk.stdout.trim();
|
|
132
|
+
if (mk.code !== 0 || !/^\/tmp\/depops\.[A-Za-z0-9]+$/.test(file)) {
|
|
133
|
+
throw new Error(`Could not create a temp file on the server. ${mk.stderr.trim()}`);
|
|
134
|
+
}
|
|
135
|
+
// `exec </dev/null` makes sure no command in the script can read the sudo password from stdin.
|
|
136
|
+
const inner = shQuote('exec </dev/null; bash "$0"; rc=$?; rm -f -- "$0"; exit $rc');
|
|
137
|
+
try {
|
|
138
|
+
if (sudo?.enabled) {
|
|
139
|
+
const res = await exec(conn, `sudo -S -p '' -- bash -c ${inner} ${shQuote(file)}`, {
|
|
140
|
+
stdin: sudo.password ? sudo.password + '\n' : '',
|
|
141
|
+
});
|
|
142
|
+
return res.code;
|
|
143
|
+
}
|
|
144
|
+
return (await exec(conn, `bash -c ${inner} ${shQuote(file)}`)).code;
|
|
145
|
+
} finally {
|
|
146
|
+
await exec(conn, `rm -f -- ${shQuote(file)}`, { capture: true }).catch(() => {});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function installPublicKey(conn, publicKey) {
|
|
151
|
+
const cmd =
|
|
152
|
+
'umask 077; read -r K; mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod 700 ~/.ssh && ' +
|
|
153
|
+
'chmod 600 ~/.ssh/authorized_keys && (grep -qxF "$K" ~/.ssh/authorized_keys || printf "%s\\n" "$K" >> ~/.ssh/authorized_keys)';
|
|
154
|
+
const res = await exec(conn, cmd, { stdin: publicKey.trim() + '\n', capture: true });
|
|
155
|
+
if (res.code !== 0) throw new Error(`Could not install SSH key: ${res.stderr.trim()}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function sftpOf(conn) {
|
|
159
|
+
return new Promise((resolve, reject) => conn.sftp((err, sftp) => (err ? reject(err) : resolve(sftp))));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const p = (fn) => (...args) => new Promise((res, rej) => fn(...args, (err, v) => (err ? rej(err) : res(v))));
|
|
163
|
+
|
|
164
|
+
/** Upload a local file or folder (recursively) to a remote path. Existing files are overwritten. */
|
|
165
|
+
export async function upload(conn, localPath, remotePath, onFile = () => {}) {
|
|
166
|
+
const sftp = await sftpOf(conn);
|
|
167
|
+
const mkdir = async (dir) => {
|
|
168
|
+
try {
|
|
169
|
+
await p(sftp.mkdir.bind(sftp))(dir);
|
|
170
|
+
} catch {}
|
|
171
|
+
};
|
|
172
|
+
const put = p(sftp.fastPut.bind(sftp));
|
|
173
|
+
const walk = async (src, dst) => {
|
|
174
|
+
const st = await fs.stat(src);
|
|
175
|
+
if (st.isDirectory()) {
|
|
176
|
+
await mkdir(dst);
|
|
177
|
+
for (const name of await fs.readdir(src)) await walk(path.join(src, name), `${dst}/${name}`);
|
|
178
|
+
} else {
|
|
179
|
+
await put(src, dst);
|
|
180
|
+
onFile(src);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
try {
|
|
184
|
+
await walk(localPath, remotePath.replace(/\/+$/, ''));
|
|
185
|
+
} finally {
|
|
186
|
+
sftp.end();
|
|
187
|
+
}
|
|
188
|
+
}
|
package/src/vault.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Encrypted vault: scrypt (memory-hard KDF) + AES-256-GCM (authenticated).
|
|
2
|
+
// Uses only Node's built-in crypto so it works the same on macOS, Linux and Windows.
|
|
3
|
+
import { randomBytes, scrypt, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
export const VAULT_FILE = '.depops.vault';
|
|
8
|
+
const MAGIC = 'depops-vault';
|
|
9
|
+
const FORMAT_VERSION = 1;
|
|
10
|
+
// 2^17 * 8 * 128 bytes = 128 MiB of memory per guess: makes offline brute force very expensive.
|
|
11
|
+
const DEFAULT_KDF = { name: 'scrypt', N: 2 ** 17, r: 8, p: 1 };
|
|
12
|
+
// Hard caps so a tampered vault file cannot make us burn unlimited CPU/RAM.
|
|
13
|
+
const KDF_LIMITS = { N: 2 ** 20, r: 16, p: 4 };
|
|
14
|
+
|
|
15
|
+
export class VaultError extends Error {}
|
|
16
|
+
|
|
17
|
+
function deriveKey(password, salt, { N, r, p }) {
|
|
18
|
+
if (N > KDF_LIMITS.N || r > KDF_LIMITS.r || p > KDF_LIMITS.p) {
|
|
19
|
+
throw new VaultError('Vault KDF parameters are out of the allowed range (file may be tampered).');
|
|
20
|
+
}
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
scrypt(password.normalize('NFKC'), salt, 32, { N, r, p, maxmem: 256 * N * r + 32 * 1024 * 1024 }, (err, key) =>
|
|
23
|
+
err ? reject(err) : resolve(key),
|
|
24
|
+
);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// The header is authenticated as AAD, so any change to it breaks decryption.
|
|
29
|
+
function headerOf(obj) {
|
|
30
|
+
return {
|
|
31
|
+
magic: obj.magic,
|
|
32
|
+
v: obj.v,
|
|
33
|
+
kdf: { name: obj.kdf.name, N: obj.kdf.N, r: obj.kdf.r, p: obj.kdf.p, salt: obj.kdf.salt },
|
|
34
|
+
cipher: obj.cipher,
|
|
35
|
+
iv: obj.iv,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function encrypt(data, password) {
|
|
40
|
+
const salt = randomBytes(16);
|
|
41
|
+
const iv = randomBytes(12);
|
|
42
|
+
const header = headerOf({
|
|
43
|
+
magic: MAGIC,
|
|
44
|
+
v: FORMAT_VERSION,
|
|
45
|
+
kdf: { ...DEFAULT_KDF, salt: salt.toString('base64') },
|
|
46
|
+
cipher: 'aes-256-gcm',
|
|
47
|
+
iv: iv.toString('base64'),
|
|
48
|
+
});
|
|
49
|
+
const key = await deriveKey(password, salt, header.kdf);
|
|
50
|
+
try {
|
|
51
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
52
|
+
cipher.setAAD(Buffer.from(JSON.stringify(header)));
|
|
53
|
+
const plain = Buffer.from(JSON.stringify(data), 'utf8');
|
|
54
|
+
const ct = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
55
|
+
plain.fill(0);
|
|
56
|
+
return JSON.stringify({ ...header, tag: cipher.getAuthTag().toString('base64'), data: ct.toString('base64') }, null, 2) + '\n';
|
|
57
|
+
} finally {
|
|
58
|
+
key.fill(0);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function decrypt(text, password) {
|
|
63
|
+
let obj;
|
|
64
|
+
try {
|
|
65
|
+
obj = JSON.parse(text);
|
|
66
|
+
} catch {
|
|
67
|
+
throw new VaultError('Vault file is corrupted (not valid JSON).');
|
|
68
|
+
}
|
|
69
|
+
if (obj?.magic !== MAGIC || obj.v !== FORMAT_VERSION || obj.cipher !== 'aes-256-gcm' || obj.kdf?.name !== 'scrypt') {
|
|
70
|
+
throw new VaultError('Unsupported or corrupted vault file.');
|
|
71
|
+
}
|
|
72
|
+
const header = headerOf(obj);
|
|
73
|
+
const key = await deriveKey(password, Buffer.from(obj.kdf.salt, 'base64'), header.kdf);
|
|
74
|
+
try {
|
|
75
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(obj.iv, 'base64'));
|
|
76
|
+
decipher.setAAD(Buffer.from(JSON.stringify(header)));
|
|
77
|
+
decipher.setAuthTag(Buffer.from(obj.tag, 'base64'));
|
|
78
|
+
const plain = Buffer.concat([decipher.update(Buffer.from(obj.data, 'base64')), decipher.final()]);
|
|
79
|
+
const data = JSON.parse(plain.toString('utf8'));
|
|
80
|
+
plain.fill(0);
|
|
81
|
+
return data;
|
|
82
|
+
} catch {
|
|
83
|
+
throw new VaultError('Wrong password, or the vault file was modified.');
|
|
84
|
+
} finally {
|
|
85
|
+
key.fill(0);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function findVault(start = process.cwd()) {
|
|
90
|
+
let dir = path.resolve(start);
|
|
91
|
+
for (;;) {
|
|
92
|
+
const file = path.join(dir, VAULT_FILE);
|
|
93
|
+
try {
|
|
94
|
+
await fs.access(file);
|
|
95
|
+
return file;
|
|
96
|
+
} catch {}
|
|
97
|
+
const parent = path.dirname(dir);
|
|
98
|
+
if (parent === dir) return null;
|
|
99
|
+
dir = parent;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function readVault(file, password) {
|
|
104
|
+
return decrypt(await fs.readFile(file, 'utf8'), password);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Atomic write: never leaves a half-written vault behind.
|
|
108
|
+
export async function writeVault(file, data, password) {
|
|
109
|
+
const text = await encrypt(data, password);
|
|
110
|
+
const tmp = `${file}.${randomBytes(4).toString('hex')}.tmp`;
|
|
111
|
+
await fs.writeFile(tmp, text, { mode: 0o644 });
|
|
112
|
+
await fs.rename(tmp, file);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function checkPasswordStrength(pw) {
|
|
116
|
+
if (pw.length < 12) return 'At least 12 characters required.';
|
|
117
|
+
const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((re) => re.test(pw)).length;
|
|
118
|
+
if (pw.length < 16 && classes < 3) return 'Use 16+ characters, or mix upper/lower case, digits and symbols.';
|
|
119
|
+
if (/^(.)\1+$/.test(pw)) return 'Password is too repetitive.';
|
|
120
|
+
return null;
|
|
121
|
+
}
|