@elumixor/devkit 0.3.1 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elumixor/devkit",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Dev orchestrator for bun monorepos — free ports, run apps side-by-side, open the browser when ready",
5
5
  "author": "elumixor",
6
6
  "license": "ISC",
package/src/clone.ts CHANGED
@@ -4,24 +4,34 @@ import { resolve } from "node:path";
4
4
  import { pullSecrets } from "./secrets.ts";
5
5
  import { runSetup } from "./setup.ts";
6
6
 
7
+ /** Fail early and actionably, rather than midway through with a raw ENOENT. */
8
+ async function checkPrereqs() {
9
+ if (!Bun.which("gh")) {
10
+ throw new Error("`gh` is not installed.\n\n brew install gh (or see cli.github.com)");
11
+ }
12
+ if ((await $`gh auth status`.nothrow().quiet()).exitCode !== 0) {
13
+ throw new Error("Not logged in to GitHub.\n\n gh auth login");
14
+ }
15
+ }
16
+
7
17
  /**
8
- * Clone a repo and make it runnable in one step: `gh repo clone`, decrypt its
9
- * secrets, then run setup. The whole point is that a new machine needs nothing
10
- * but `gh auth login` and the age identity.
18
+ * Clone a repo and make it runnable in one step: clone, decrypt its secrets, set up.
19
+ * A new machine needs `gh auth login` and the secrets passphrase — nothing else.
11
20
  */
12
21
  export async function runClone(repo: string, dir?: string) {
22
+ await checkPrereqs();
23
+
13
24
  const target = resolve(dir ?? repo.split("/").pop() ?? repo);
14
25
 
15
- if (existsSync(target)) {
16
- console.log(`${target} already exists — skipping clone.`);
17
- } else {
26
+ if (existsSync(target)) console.log(`${target} already exists — skipping clone.`);
27
+ else {
18
28
  console.log(`Cloning ${repo}…`);
19
29
  await $`gh repo clone ${repo} ${target}`;
20
30
  }
21
31
 
22
32
  process.chdir(target);
23
33
 
24
- console.log("\nFetching secrets…");
34
+ console.log("\nRestoring secrets…");
25
35
  await pullSecrets(target);
26
36
 
27
37
  console.log("");
package/src/secrets.ts CHANGED
@@ -1,39 +1,96 @@
1
1
  import { $ } from "bun";
2
+ import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
2
3
  import { existsSync } from "node:fs";
3
- import { mkdir } from "node:fs/promises";
4
+ import { chmod, mkdir } from "node:fs/promises";
4
5
  import { homedir } from "node:os";
5
6
  import { dirname, join, resolve } from "node:path";
6
7
  import { loadConfig } from "./config.ts";
7
8
 
8
9
  /**
9
10
  * Secrets that cannot be regenerated from any host (.env, terraform.tfvars) are
10
- * age-encrypted into a private git repo, one directory per project.
11
+ * encrypted into a private git repo, one bundle per project.
11
12
  *
12
- * The only thing a new machine must carry is the age identity. Everything else
13
- * follows from `gh auth login`.
13
+ * The only thing you need on a new machine is `gh auth login` and one passphrase.
14
+ * No key file to carry, no OS-specific keychain, no external crypto binary — which
15
+ * is why this uses node:crypto rather than shelling out to `age`.
14
16
  */
15
- export const KEY_PATH = join(homedir(), ".config/age/key.txt");
16
17
  const CACHE = join(homedir(), ".cache/devkit/secrets");
18
+ const PASSPHRASE_FILE = join(homedir(), ".config/devkit/passphrase");
17
19
  const DEFAULT_REPO = "elumixor/secrets";
18
20
 
19
- /** `recipients.txt` lets any machine holding *a* key encrypt for *all* keys. */
20
- const RECIPIENTS = "recipients.txt";
21
+ /** scrypt is deliberately slow; these are the Node defaults raised for a user-chosen passphrase. */
22
+ const SCRYPT = { N: 2 ** 16, r: 8, p: 1, maxmem: 128 * 2 ** 16 * 8 * 2 };
23
+ const KEY_LEN = 32;
24
+ const SALT_LEN = 16;
25
+ const IV_LEN = 12;
21
26
 
22
- function requireKey() {
23
- if (existsSync(KEY_PATH)) return;
24
- throw new Error(
25
- `No age identity at ${KEY_PATH}.\n\n` +
26
- `It is the one thing that must be carried to a new machine — without it the\n` +
27
- `encrypted secrets cannot be read. Copy it over, or create a new identity with\n` +
28
- `\`age-keygen -o ${KEY_PATH}\` and re-encrypt from a machine that still has the old one.`,
29
- );
27
+ /** Read a passphrase without echoing it. `stty` beats a bare prompt(), which would print it. */
28
+ async function ask(question: string) {
29
+ process.stdout.write(question);
30
+ const result = await $`sh -c ${'stty -echo 2>/dev/null; read -r p; stty echo 2>/dev/null; printf "%s" "$p"'}`
31
+ .nothrow()
32
+ .text();
33
+ process.stdout.write("\n");
34
+ return result.trim();
35
+ }
36
+
37
+ /**
38
+ * The passphrase, cached per-machine after first use. Cached in plaintext on purpose:
39
+ * it guards the *transport*, and the files it protects sit in the working tree in
40
+ * plaintext anyway, so encrypting the cache would be theatre.
41
+ */
42
+ async function passphrase(confirm = false) {
43
+ const fromEnv = process.env.DEVKIT_PASSPHRASE;
44
+ if (fromEnv) return fromEnv;
45
+
46
+ if (existsSync(PASSPHRASE_FILE)) return (await Bun.file(PASSPHRASE_FILE).text()).trim();
47
+
48
+ const entered = await ask("Secrets passphrase: ");
49
+ if (!entered) throw new Error("No passphrase given.");
50
+ if (confirm && (await ask("Confirm passphrase: ")) !== entered) {
51
+ throw new Error("Passphrases do not match.");
52
+ }
53
+
54
+ await mkdir(dirname(PASSPHRASE_FILE), { recursive: true });
55
+ await Bun.write(PASSPHRASE_FILE, `${entered}\n`);
56
+ await chmod(PASSPHRASE_FILE, 0o600);
57
+ console.log(` cached in ${PASSPHRASE_FILE} — you won't be asked again on this machine`);
58
+ return entered;
59
+ }
60
+
61
+ /** salt | iv | tag | ciphertext, base64 — one self-contained blob, diffable enough for git. */
62
+ function encrypt(plaintext: string, secret: string) {
63
+ const salt = randomBytes(SALT_LEN);
64
+ const iv = randomBytes(IV_LEN);
65
+ const key = scryptSync(secret, salt, KEY_LEN, SCRYPT);
66
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
67
+ const body = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
68
+ return Buffer.concat([salt, iv, cipher.getAuthTag(), body]).toString("base64");
69
+ }
70
+
71
+ function decrypt(blob: string, secret: string) {
72
+ const raw = Buffer.from(blob, "base64");
73
+ const salt = raw.subarray(0, SALT_LEN);
74
+ const iv = raw.subarray(SALT_LEN, SALT_LEN + IV_LEN);
75
+ const tag = raw.subarray(SALT_LEN + IV_LEN, SALT_LEN + IV_LEN + 16);
76
+ const body = raw.subarray(SALT_LEN + IV_LEN + 16);
77
+ const key = scryptSync(secret, salt, KEY_LEN, SCRYPT);
78
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
79
+ decipher.setAuthTag(tag);
80
+ try {
81
+ return Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8");
82
+ } catch {
83
+ // GCM's auth tag is what catches this; there is no other way to be "wrong".
84
+ throw new Error(
85
+ `Could not decrypt — wrong passphrase.\n\nClear the cached one and retry:\n rm ${PASSPHRASE_FILE}`,
86
+ );
87
+ }
30
88
  }
31
89
 
32
90
  /** Clone the secrets repo on first use, otherwise fast-forward it. */
33
91
  async function syncCache(repo: string) {
34
- if (existsSync(join(CACHE, ".git"))) {
35
- await $`git pull --quiet --ff-only`.cwd(CACHE);
36
- } else {
92
+ if (existsSync(join(CACHE, ".git"))) await $`git pull --quiet --ff-only`.cwd(CACHE).quiet();
93
+ else {
37
94
  await mkdir(dirname(CACHE), { recursive: true });
38
95
  await $`gh repo clone ${repo} ${CACHE} -- --quiet`.quiet();
39
96
  }
@@ -45,8 +102,7 @@ async function projectName(root: string) {
45
102
  const remote = await $`git -C ${root} remote get-url origin`.quiet().nothrow().text();
46
103
  const name = remote.trim().replace(/\.git$/, "").split("/").pop();
47
104
  if (name) return name;
48
- const pkg = await Bun.file(resolve(root, "package.json")).json();
49
- return pkg.name as string;
105
+ return (await Bun.file(resolve(root, "package.json")).json()).name as string;
50
106
  }
51
107
 
52
108
  function config(root: string) {
@@ -56,59 +112,62 @@ function config(root: string) {
56
112
  return { files, repo: setup.secretsRepo ?? DEFAULT_REPO };
57
113
  }
58
114
 
59
- /** Encrypt the project's secret files into the secrets repo and push. */
115
+ /** Encrypt the project's secret files into one bundle and push it. */
60
116
  export async function pushSecrets(root = process.cwd()) {
61
- requireKey();
62
117
  const { files, repo } = config(root);
63
118
  const cache = await syncCache(repo);
64
119
  const project = await projectName(root);
120
+ const bundlePath = join(cache, `${project}.enc`);
65
121
 
66
- // Seed recipients.txt on first push so other machines can encrypt for this key too.
67
- const recipientsPath = join(cache, RECIPIENTS);
68
- if (!existsSync(recipientsPath)) {
69
- await Bun.write(recipientsPath, `${(await $`age-keygen -y ${KEY_PATH}`.text()).trim()}\n`);
70
- }
122
+ // Only confirm when creating a project's first bundle — a typo there would be
123
+ // unrecoverable, whereas a typo on a later push just fails to decrypt the old one.
124
+ const secret = await passphrase(!existsSync(bundlePath));
71
125
 
72
- let pushed = 0;
126
+ const bundle: Record<string, string> = {};
73
127
  for (const file of files) {
74
128
  const source = resolve(root, file);
75
129
  if (!existsSync(source)) {
76
130
  console.log(` skip ${file} (not present)`);
77
131
  continue;
78
132
  }
79
- const target = join(cache, project, `${file}.age`);
80
- await mkdir(dirname(target), { recursive: true });
81
- await $`age --encrypt --recipients-file ${recipientsPath} --output ${target} ${source}`;
82
- console.log(` encrypted ${file}`);
83
- pushed++;
133
+ bundle[file] = await Bun.file(source).text();
134
+ console.log(` packed ${file}`);
84
135
  }
85
- if (!pushed) return console.log("Nothing to push.");
136
+ if (!Object.keys(bundle).length) return console.log("Nothing to push.");
86
137
 
87
- await $`git add -A`.cwd(cache);
88
- const clean = await $`git diff --cached --quiet`.cwd(cache).nothrow();
89
- if (clean.exitCode === 0) return console.log("Already up to date.");
138
+ await Bun.write(bundlePath, `${encrypt(JSON.stringify(bundle), secret)}\n`);
90
139
 
91
- await $`git commit --quiet -m ${`secrets: update ${project}`}`.cwd(cache);
92
- await $`git push --quiet`.cwd(cache);
93
- console.log(`Pushed ${pushed} file(s) for ${project} to ${repo}.`);
140
+ await $`git add -A`.cwd(cache).quiet();
141
+ if ((await $`git diff --cached --quiet`.cwd(cache).nothrow()).exitCode === 0) {
142
+ return console.log("Already up to date.");
143
+ }
144
+ await $`git commit --quiet -m ${`secrets: update ${project}`}`.cwd(cache).quiet();
145
+ await $`git push --quiet`.cwd(cache).quiet();
146
+ console.log(`Pushed ${Object.keys(bundle).length} file(s) for ${project} to ${repo}.`);
94
147
  }
95
148
 
96
- /** Decrypt this project's secret files from the secrets repo into the working tree. */
149
+ /** Decrypt this project's bundle into the working tree. */
97
150
  export async function pullSecrets(root = process.cwd()) {
98
- requireKey();
99
- const { files, repo } = config(root);
151
+ const { repo } = config(root);
100
152
  const cache = await syncCache(repo);
101
153
  const project = await projectName(root);
154
+ const bundlePath = join(cache, `${project}.enc`);
102
155
 
103
- for (const file of files) {
104
- const source = join(cache, project, `${file}.age`);
105
- if (!existsSync(source)) {
106
- console.log(` skip ${file} (not in ${repo}/${project})`);
107
- continue;
108
- }
156
+ if (!existsSync(bundlePath)) {
157
+ console.log(` no secrets stored for ${project} in ${repo} — run \`devkit secrets push\` first`);
158
+ return;
159
+ }
160
+
161
+ const secret = await passphrase();
162
+ const bundle: Record<string, string> = JSON.parse(
163
+ decrypt(await Bun.file(bundlePath).text(), secret),
164
+ );
165
+
166
+ for (const [file, contents] of Object.entries(bundle)) {
109
167
  const target = resolve(root, file);
110
168
  await mkdir(dirname(target), { recursive: true });
111
- await $`age --decrypt --identity ${KEY_PATH} --output ${target} ${source}`;
112
- console.log(` decrypted ${file}`);
169
+ await Bun.write(target, contents);
170
+ await chmod(target, 0o600);
171
+ console.log(` restored ${file}`);
113
172
  }
114
173
  }