@zaxilabs/cryptx-cli 0.0.0-stage → 0.3.4

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 CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # CryptX CLI (`@zaxilabs/cryptx-cli`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-knowledge CLI for **CryptX**. Decrypt your `env_bundle` secrets locally in memory and inject them directly into any command—without writing plaintext `.env` files to disk.
4
+
5
+ ## Quick Start (3 Steps)
6
+
7
+ 1. **Install the CLI**
8
+
9
+ ```bash
10
+ npm install -g @zaxilabs/cryptx-cli
11
+ ```
12
+
13
+ *(Or run without installing globally via `npx @zaxilabs/cryptx-cli`.)*
14
+
15
+ 2. **Authenticate your CryptX account**
16
+
17
+ ```bash
18
+ cryptx login
19
+ ```
20
+
21
+ Your Supabase auth session is stored locally in `~/.cryptx/session.json` (`0600`). Your Master Password, KEK, and VEK are **never** written to disk.
22
+
23
+ 3. **Run your app with in-memory secrets**
24
+
25
+ ```bash
26
+ cryptx run --project "<name>" --env <environment> -- <command>
27
+ ```
28
+
29
+ Example:
30
+
31
+ ```bash
32
+ cryptx run --project "my-app" --env development -- npm run dev
33
+ ```
34
+
35
+ ## How Zero-Knowledge In-Memory Decryption Works
36
+
37
+ - `cryptx run` fetches your encrypted `env_bundle` ciphertext from CryptX and prompts for your **Vault Master Password**.
38
+ - Your Master Password derives your KEK locally via Argon2id and unwraps your VEK in memory (`libsodium`).
39
+ - Decrypted `KEY=VALUE` pairs are passed directly to the child process's `env` in memory and the VEK is zeroed immediately—no `.env` file is ever created on disk.
40
+
41
+ ## Additional Commands
42
+
43
+ - `cryptx init --project <slug> [--env development|staging|production] [--out .env.local]` — Create a `cryptx.json` project config in the current directory.
44
+ - `cryptx pull [--project <slug>] [--env <environment>] [--out .env.local]` — Decrypt and write an `.env` file atomically (`0600`).
45
+ - `cryptx push [--project <slug>] [--env <environment>] [--file .env.local]` — Encrypt and upload an `.env` file to your vault.
46
+ - `cryptx logout` — Remove the local `~/.cryptx/session.json` file.
47
+
48
+ ## Self-Hosted / Custom Supabase Overrides
49
+
50
+ By default, `@zaxilabs/cryptx-cli` connects to the production CryptX backend with zero configuration. For self-hosted or local Supabase instances, override via environment variables or `~/.cryptx/config.json`:
51
+
52
+ ```bash
53
+ export CRYPTX_SUPABASE_URL="https://your-project.supabase.co"
54
+ export CRYPTX_SUPABASE_ANON_KEY="your-anon-key"
55
+ ```
@@ -0,0 +1,619 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import sodium from 'libsodium-wrappers-sumo';
5
+
6
+ export const DEFAULT_SUPABASE_URL = 'https://xgvsxpnerrzxapkdlyut.supabase.co';
7
+ export const DEFAULT_SUPABASE_ANON_KEY =
8
+ 'sb_publishable_mpEK_rInsHAeWAMjSffiXw_2dZM8BkW';
9
+
10
+ const PADDING_BLOCK_SIZE = 256;
11
+ const CRYPTO_ENC_VERSION = 1;
12
+ const KDF_CONTEXT_VAULT_KEK = 'VAULTKEK';
13
+ const KDF_SUBKEY_ID_KEK = 1;
14
+ const SYMMETRIC_KEY_BYTES = 32;
15
+
16
+ const VALID_ENVIRONMENTS = new Set(['development', 'staging', 'production']);
17
+
18
+ function padIso7816_4(data, blockSize = PADDING_BLOCK_SIZE) {
19
+ const remainder = data.length % blockSize;
20
+ const padLen = remainder === 0 ? blockSize : blockSize - remainder;
21
+ const out = new Uint8Array(data.length + padLen);
22
+ out.set(data, 0);
23
+ out[data.length] = 0x80;
24
+ return out;
25
+ }
26
+
27
+ function unpadIso7816_4(padded, blockSize = PADDING_BLOCK_SIZE) {
28
+ if (padded.length === 0 || padded.length % blockSize !== 0) {
29
+ throw new Error('Invalid padded payload length.');
30
+ }
31
+ let idx = padded.length - 1;
32
+ while (idx >= 0 && padded[idx] === 0x00) {
33
+ idx -= 1;
34
+ }
35
+ if (idx < 0 || padded[idx] !== 0x80) {
36
+ throw new Error('Invalid ISO/IEC 7816-4 padding.');
37
+ }
38
+ const padLen = padded.length - idx;
39
+ if (padLen > blockSize) {
40
+ throw new Error('Invalid ISO/IEC 7816-4 padding block length.');
41
+ }
42
+ return padded.slice(0, idx);
43
+ }
44
+
45
+ const textEncoder = new TextEncoder();
46
+ const textDecoder = new TextDecoder('utf-8', { fatal: true });
47
+
48
+ function memzeroAll(s, ...buffers) {
49
+ for (const buf of buffers) {
50
+ if (buf instanceof Uint8Array && buf.byteLength > 0) {
51
+ s.memzero(buf);
52
+ }
53
+ }
54
+ }
55
+
56
+ export function resolveProjectConfig({ cwd, projectArg, envArg, outArg }) {
57
+ const configPath = path.join(cwd, 'cryptx.json');
58
+ let fileConfig = {};
59
+ if (fs.existsSync(configPath)) {
60
+ const raw = fs.readFileSync(configPath, 'utf8');
61
+ fileConfig = JSON.parse(raw);
62
+ }
63
+
64
+ const project = (projectArg ?? fileConfig.project ?? '').trim();
65
+ const environment = (envArg ?? fileConfig.environment ?? 'development').trim();
66
+ const outFile = (outArg ?? fileConfig.outFile ?? '.env.local').trim();
67
+
68
+ if (!project) {
69
+ throw new Error('Project slug is required (pass --project <slug> or run `cryptx init`).');
70
+ }
71
+ if (!VALID_ENVIRONMENTS.has(environment)) {
72
+ throw new Error('Environment must be one of: development, staging, production.');
73
+ }
74
+
75
+ return { project, environment, outFile };
76
+ }
77
+
78
+ export function writeProjectConfig({ cwd, project, environment, outFile = '.env.local' }) {
79
+ if (!project || !project.trim()) {
80
+ throw new Error('Project slug is required.');
81
+ }
82
+ if (!VALID_ENVIRONMENTS.has(environment)) {
83
+ throw new Error('Environment must be one of: development, staging, production.');
84
+ }
85
+ const configPath = path.join(cwd, 'cryptx.json');
86
+ const payload = {
87
+ project: project.trim(),
88
+ environment,
89
+ outFile,
90
+ };
91
+ fs.writeFileSync(configPath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8' });
92
+ return configPath;
93
+ }
94
+
95
+ export function resolveSupabaseConfig({ env = process.env, homeDir }) {
96
+ let fileCfg = {};
97
+ if (homeDir) {
98
+ const cfgPath = path.join(homeDir, '.cryptx', 'config.json');
99
+ if (fs.existsSync(cfgPath)) {
100
+ fileCfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
101
+ }
102
+ }
103
+
104
+ const supabaseUrl = (
105
+ env.CRYPTX_SUPABASE_URL ??
106
+ env.SUPABASE_URL ??
107
+ env.VITE_SUPABASE_URL ??
108
+ fileCfg.supabaseUrl ??
109
+ DEFAULT_SUPABASE_URL
110
+ ).trim();
111
+ const supabaseAnonKey = (
112
+ env.CRYPTX_SUPABASE_ANON_KEY ??
113
+ env.SUPABASE_ANON_KEY ??
114
+ env.VITE_SUPABASE_ANON_KEY ??
115
+ fileCfg.supabaseAnonKey ??
116
+ DEFAULT_SUPABASE_ANON_KEY
117
+ ).trim();
118
+
119
+ if (!supabaseUrl || !supabaseAnonKey) {
120
+ throw new Error(
121
+ 'Missing CRYPTX_SUPABASE_URL / CRYPTX_SUPABASE_ANON_KEY.',
122
+ );
123
+ }
124
+
125
+ return {
126
+ supabaseUrl: supabaseUrl.replace(/\/+$/, ''),
127
+ supabaseAnonKey,
128
+ };
129
+ }
130
+
131
+ export function getSessionPath(homeDir) {
132
+ return path.join(homeDir, '.cryptx', 'session.json');
133
+ }
134
+
135
+ export function saveSession({ homeDir, session }) {
136
+ const dir = path.join(homeDir, '.cryptx');
137
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
138
+ const sessionPath = getSessionPath(homeDir);
139
+ const payload = {
140
+ email: session.email,
141
+ userId: session.userId,
142
+ accessToken: session.accessToken,
143
+ refreshToken: session.refreshToken ?? null,
144
+ supabaseUrl: session.supabaseUrl,
145
+ };
146
+ fs.writeFileSync(sessionPath, `${JSON.stringify(payload, null, 2)}\n`, {
147
+ encoding: 'utf8',
148
+ mode: 0o600,
149
+ });
150
+ try {
151
+ fs.chmodSync(sessionPath, 0o600);
152
+ } catch {
153
+ // chmod may be a no-op on some Windows filesystems
154
+ }
155
+ return sessionPath;
156
+ }
157
+
158
+ export function loadSession({ homeDir, supabaseUrl }) {
159
+ if (!homeDir) return null;
160
+ const sessionPath = getSessionPath(homeDir);
161
+ if (!fs.existsSync(sessionPath)) return null;
162
+ try {
163
+ const parsed = JSON.parse(fs.readFileSync(sessionPath, 'utf8'));
164
+ if (!parsed?.accessToken || !parsed?.userId) return null;
165
+ if (supabaseUrl && parsed.supabaseUrl && parsed.supabaseUrl !== supabaseUrl) {
166
+ return null;
167
+ }
168
+ return parsed;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ export function clearSession({ homeDir }) {
175
+ if (!homeDir) return false;
176
+ const sessionPath = getSessionPath(homeDir);
177
+ if (fs.existsSync(sessionPath)) {
178
+ fs.rmSync(sessionPath, { force: true });
179
+ return true;
180
+ }
181
+ return false;
182
+ }
183
+
184
+ export async function loginWithPassword({
185
+ supabaseUrl,
186
+ supabaseAnonKey,
187
+ email,
188
+ accountPassword,
189
+ fetchImpl = fetch,
190
+ }) {
191
+ const authRes = await fetchImpl(`${supabaseUrl}/auth/v1/token?grant_type=password`, {
192
+ method: 'POST',
193
+ headers: {
194
+ 'Content-Type': 'application/json',
195
+ apikey: supabaseAnonKey,
196
+ },
197
+ body: JSON.stringify({ email, password: accountPassword }),
198
+ });
199
+
200
+ if (!authRes.ok) {
201
+ const errText = await authRes.text();
202
+ throw new Error(`Supabase authentication failed (${String(authRes.status)}): ${errText}`);
203
+ }
204
+
205
+ const authData = await authRes.json();
206
+ const accessToken = authData.access_token;
207
+ const refreshToken = authData.refresh_token ?? null;
208
+ const userId = authData.user?.id;
209
+ if (!accessToken || !userId) {
210
+ throw new Error('Invalid Supabase auth response.');
211
+ }
212
+
213
+ return {
214
+ email: authData.user?.email ?? email,
215
+ userId,
216
+ accessToken,
217
+ refreshToken,
218
+ supabaseUrl,
219
+ };
220
+ }
221
+
222
+ export async function refreshAuthSession({
223
+ supabaseUrl,
224
+ supabaseAnonKey,
225
+ refreshToken,
226
+ fetchImpl = fetch,
227
+ }) {
228
+ const authRes = await fetchImpl(`${supabaseUrl}/auth/v1/token?grant_type=refresh_token`, {
229
+ method: 'POST',
230
+ headers: {
231
+ 'Content-Type': 'application/json',
232
+ apikey: supabaseAnonKey,
233
+ },
234
+ body: JSON.stringify({ refresh_token: refreshToken }),
235
+ });
236
+
237
+ if (!authRes.ok) {
238
+ return null;
239
+ }
240
+
241
+ const authData = await authRes.json();
242
+ const accessToken = authData.access_token;
243
+ const userId = authData.user?.id;
244
+ if (!accessToken || !userId) {
245
+ return null;
246
+ }
247
+
248
+ return {
249
+ email: authData.user?.email ?? '',
250
+ userId,
251
+ accessToken,
252
+ refreshToken: authData.refresh_token ?? refreshToken,
253
+ supabaseUrl,
254
+ };
255
+ }
256
+
257
+ export function parseEnvContent(envContent) {
258
+ const entries = {};
259
+ const lines = envContent.split(/\r?\n/);
260
+
261
+ for (const rawLine of lines) {
262
+ const trimmed = rawLine.trim();
263
+ if (!trimmed || trimmed.startsWith('#')) {
264
+ continue;
265
+ }
266
+
267
+ const withoutExport = trimmed.startsWith('export ')
268
+ ? trimmed.slice('export '.length).trim()
269
+ : trimmed;
270
+
271
+ const eqIdx = withoutExport.indexOf('=');
272
+ if (eqIdx <= 0) {
273
+ continue;
274
+ }
275
+
276
+ const key = withoutExport.slice(0, eqIdx).trim();
277
+ let value = withoutExport.slice(eqIdx + 1).trim();
278
+
279
+ if (
280
+ (value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
281
+ (value.startsWith("'") && value.endsWith("'") && value.length >= 2)
282
+ ) {
283
+ value = value.slice(1, -1);
284
+ }
285
+
286
+ if (key) {
287
+ entries[key] = value;
288
+ }
289
+ }
290
+
291
+ return entries;
292
+ }
293
+
294
+ async function authenticateAndUnwrapVek({
295
+ supabaseUrl,
296
+ supabaseAnonKey,
297
+ email,
298
+ accountPassword,
299
+ masterPassword,
300
+ accessToken: providedAccessToken,
301
+ userId: providedUserId,
302
+ fetchImpl = fetch,
303
+ }) {
304
+ await sodium.ready;
305
+ const s = sodium;
306
+
307
+ let accessToken = providedAccessToken;
308
+ let userId = providedUserId;
309
+
310
+ if (!accessToken || !userId) {
311
+ const auth = await loginWithPassword({
312
+ supabaseUrl,
313
+ supabaseAnonKey,
314
+ email,
315
+ accountPassword,
316
+ fetchImpl,
317
+ });
318
+ accessToken = auth.accessToken;
319
+ userId = auth.userId;
320
+ }
321
+
322
+ const profRes = await fetchImpl(
323
+ `${supabaseUrl}/rest/v1/user_security_profiles?user_id=eq.${encodeURIComponent(userId)}&select=*`,
324
+ {
325
+ method: 'GET',
326
+ headers: {
327
+ apikey: supabaseAnonKey,
328
+ Authorization: `Bearer ${accessToken}`,
329
+ },
330
+ },
331
+ );
332
+ if (!profRes.ok) {
333
+ throw new Error(`Failed to fetch security profile (${String(profRes.status)}).`);
334
+ }
335
+ const profiles = await profRes.json();
336
+ const profile = Array.isArray(profiles) ? profiles[0] : null;
337
+ if (!profile) {
338
+ throw new Error('No security profile found for this account.');
339
+ }
340
+
341
+ const pwBytes = textEncoder.encode(masterPassword);
342
+ let mk = null;
343
+ let kek = null;
344
+
345
+ try {
346
+ const salt = s.from_base64(profile.kdf_salt, s.base64_variants.ORIGINAL);
347
+ mk = s.crypto_pwhash(
348
+ SYMMETRIC_KEY_BYTES,
349
+ pwBytes,
350
+ salt,
351
+ profile.kdf_iterations,
352
+ profile.kdf_memory_kib * 1024,
353
+ s.crypto_pwhash_ALG_ARGON2ID13,
354
+ );
355
+ kek = s.crypto_kdf_derive_from_key(
356
+ SYMMETRIC_KEY_BYTES,
357
+ KDF_SUBKEY_ID_KEK,
358
+ KDF_CONTEXT_VAULT_KEK,
359
+ mk,
360
+ );
361
+
362
+ const wrappedVek = s.from_base64(profile.wrapped_vek, s.base64_variants.ORIGINAL);
363
+ const vekNonce = s.from_base64(profile.vek_nonce, s.base64_variants.ORIGINAL);
364
+ const vekAad = textEncoder.encode(
365
+ `${userId.toLowerCase()}:vek:${String(profile.vek_enc_version)}:${String(profile.vault_revision)}`,
366
+ );
367
+
368
+ const vek = s.crypto_aead_xchacha20poly1305_ietf_decrypt(
369
+ null,
370
+ wrappedVek,
371
+ vekAad,
372
+ vekNonce,
373
+ kek,
374
+ );
375
+
376
+ return { s, accessToken, userId, vek };
377
+ } finally {
378
+ memzeroAll(s, pwBytes, mk, kek);
379
+ }
380
+ }
381
+
382
+ function decryptVaultRow(s, row, vek, userId) {
383
+ const nonce = s.from_base64(row.nonce, s.base64_variants.ORIGINAL);
384
+ const ciphertext = s.from_base64(row.ciphertext, s.base64_variants.ORIGINAL);
385
+ const aad = textEncoder.encode(
386
+ `${userId.toLowerCase()}:${row.id.toLowerCase()}:${String(row.enc_version)}:${String(row.revision)}`,
387
+ );
388
+ const padded = s.crypto_aead_xchacha20poly1305_ietf_decrypt(null, ciphertext, aad, nonce, vek);
389
+ const plainBytes = unpadIso7816_4(padded, PADDING_BLOCK_SIZE);
390
+ try {
391
+ return JSON.parse(textDecoder.decode(plainBytes));
392
+ } finally {
393
+ memzeroAll(s, padded, plainBytes);
394
+ }
395
+ }
396
+
397
+ function encryptVaultPayload(s, payload, vek, userId, recordId, revision) {
398
+ const rawBytes = textEncoder.encode(JSON.stringify(payload));
399
+ const padded = padIso7816_4(rawBytes, PADDING_BLOCK_SIZE);
400
+ const nonce = s.randombytes_buf(s.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
401
+ const aad = textEncoder.encode(
402
+ `${userId.toLowerCase()}:${recordId.toLowerCase()}:${String(CRYPTO_ENC_VERSION)}:${String(revision)}`,
403
+ );
404
+ try {
405
+ const ciphertext = s.crypto_aead_xchacha20poly1305_ietf_encrypt(
406
+ padded,
407
+ aad,
408
+ null,
409
+ nonce,
410
+ vek,
411
+ );
412
+ return {
413
+ enc_version: CRYPTO_ENC_VERSION,
414
+ nonce: s.to_base64(nonce, s.base64_variants.ORIGINAL),
415
+ ciphertext: s.to_base64(ciphertext, s.base64_variants.ORIGINAL),
416
+ };
417
+ } finally {
418
+ memzeroAll(s, rawBytes, padded);
419
+ }
420
+ }
421
+
422
+ export async function pullEnvBundle({
423
+ supabaseUrl,
424
+ supabaseAnonKey,
425
+ email,
426
+ accountPassword,
427
+ masterPassword,
428
+ accessToken,
429
+ userId,
430
+ project,
431
+ environment,
432
+ fetchImpl = fetch,
433
+ }) {
434
+ const { s, accessToken: resolvedToken, userId: resolvedUserId, vek } =
435
+ await authenticateAndUnwrapVek({
436
+ supabaseUrl,
437
+ supabaseAnonKey,
438
+ email,
439
+ accountPassword,
440
+ masterPassword,
441
+ accessToken,
442
+ userId,
443
+ fetchImpl,
444
+ });
445
+
446
+ try {
447
+ const itemsRes = await fetchImpl(
448
+ `${supabaseUrl}/rest/v1/vault_items?user_id=eq.${encodeURIComponent(resolvedUserId)}&vault_scope=eq.primary&deleted_at=is.null&select=*`,
449
+ {
450
+ method: 'GET',
451
+ headers: {
452
+ apikey: supabaseAnonKey,
453
+ Authorization: `Bearer ${resolvedToken}`,
454
+ },
455
+ },
456
+ );
457
+ if (!itemsRes.ok) {
458
+ throw new Error(`Failed to fetch vault items (${String(itemsRes.status)}).`);
459
+ }
460
+
461
+ const rows = await itemsRes.json();
462
+ for (const row of rows) {
463
+ const payload = decryptVaultRow(s, row, vek, resolvedUserId);
464
+ if (
465
+ payload.type === 'env_bundle' &&
466
+ payload.projectSlug === project &&
467
+ payload.environment === environment
468
+ ) {
469
+ return {
470
+ envContent: payload.envContent,
471
+ itemId: row.id,
472
+ revision: row.revision,
473
+ };
474
+ }
475
+ }
476
+
477
+ throw new Error(`No env_bundle found for project "${project}" (${environment}).`);
478
+ } finally {
479
+ memzeroAll(s, vek);
480
+ }
481
+ }
482
+
483
+ export async function pushEnvBundle({
484
+ supabaseUrl,
485
+ supabaseAnonKey,
486
+ email,
487
+ accountPassword,
488
+ masterPassword,
489
+ accessToken,
490
+ userId,
491
+ project,
492
+ environment,
493
+ envContent,
494
+ fetchImpl = fetch,
495
+ }) {
496
+ const { s, accessToken: resolvedToken, userId: resolvedUserId, vek } =
497
+ await authenticateAndUnwrapVek({
498
+ supabaseUrl,
499
+ supabaseAnonKey,
500
+ email,
501
+ accountPassword,
502
+ masterPassword,
503
+ accessToken,
504
+ userId,
505
+ fetchImpl,
506
+ });
507
+
508
+ try {
509
+ const itemsRes = await fetchImpl(
510
+ `${supabaseUrl}/rest/v1/vault_items?user_id=eq.${encodeURIComponent(resolvedUserId)}&vault_scope=eq.primary&deleted_at=is.null&select=*`,
511
+ {
512
+ method: 'GET',
513
+ headers: {
514
+ apikey: supabaseAnonKey,
515
+ Authorization: `Bearer ${resolvedToken}`,
516
+ },
517
+ },
518
+ );
519
+ if (!itemsRes.ok) {
520
+ throw new Error(`Failed to fetch vault items (${String(itemsRes.status)}).`);
521
+ }
522
+
523
+ const rows = await itemsRes.json();
524
+ let existingRow = null;
525
+ let existingPayload = null;
526
+ for (const row of rows) {
527
+ const payload = decryptVaultRow(s, row, vek, resolvedUserId);
528
+ if (
529
+ payload.type === 'env_bundle' &&
530
+ payload.projectSlug === project &&
531
+ payload.environment === environment
532
+ ) {
533
+ existingRow = row;
534
+ existingPayload = payload;
535
+ break;
536
+ }
537
+ }
538
+
539
+ if (existingRow && existingPayload) {
540
+ const nextRevision = existingRow.revision + 1;
541
+ const nextPayload = {
542
+ ...existingPayload,
543
+ envContent,
544
+ };
545
+ const enc = encryptVaultPayload(
546
+ s,
547
+ nextPayload,
548
+ vek,
549
+ resolvedUserId,
550
+ existingRow.id,
551
+ nextRevision,
552
+ );
553
+ const patchRes = await fetchImpl(
554
+ `${supabaseUrl}/rest/v1/vault_items?id=eq.${encodeURIComponent(existingRow.id)}&user_id=eq.${encodeURIComponent(resolvedUserId)}&revision=eq.${String(existingRow.revision)}`,
555
+ {
556
+ method: 'PATCH',
557
+ headers: {
558
+ 'Content-Type': 'application/json',
559
+ apikey: supabaseAnonKey,
560
+ Authorization: `Bearer ${resolvedToken}`,
561
+ },
562
+ body: JSON.stringify({
563
+ ...enc,
564
+ revision: nextRevision,
565
+ }),
566
+ },
567
+ );
568
+ if (!patchRes.ok) {
569
+ throw new Error(`Failed to update env_bundle (${String(patchRes.status)}).`);
570
+ }
571
+ return { itemId: existingRow.id, revision: nextRevision, action: 'updated' };
572
+ }
573
+
574
+ const newId = crypto.randomUUID();
575
+ const newPayload = {
576
+ type: 'env_bundle',
577
+ title: `${project} (${environment})`,
578
+ projectSlug: project,
579
+ environment,
580
+ envContent,
581
+ isFavorite: false,
582
+ };
583
+ const enc = encryptVaultPayload(s, newPayload, vek, resolvedUserId, newId, 1);
584
+ const postRes = await fetchImpl(`${supabaseUrl}/rest/v1/vault_items`, {
585
+ method: 'POST',
586
+ headers: {
587
+ 'Content-Type': 'application/json',
588
+ apikey: supabaseAnonKey,
589
+ Authorization: `Bearer ${resolvedToken}`,
590
+ },
591
+ body: JSON.stringify({
592
+ id: newId,
593
+ user_id: resolvedUserId,
594
+ folder_id: null,
595
+ ...enc,
596
+ revision: 1,
597
+ vault_scope: 'primary',
598
+ }),
599
+ });
600
+ if (!postRes.ok) {
601
+ throw new Error(`Failed to create env_bundle (${String(postRes.status)}).`);
602
+ }
603
+ return { itemId: newId, revision: 1, action: 'created' };
604
+ } finally {
605
+ memzeroAll(s, vek);
606
+ }
607
+ }
608
+
609
+ export function writeEnvFileAtomic(targetPath, envContent) {
610
+ const dir = path.dirname(targetPath);
611
+ const tmpPath = path.join(dir, `.cryptx.tmp.${String(process.pid)}`);
612
+ fs.writeFileSync(tmpPath, envContent, { encoding: 'utf8', mode: 0o600 });
613
+ fs.renameSync(tmpPath, targetPath);
614
+ try {
615
+ fs.chmodSync(targetPath, 0o600);
616
+ } catch {
617
+ // chmod may be a no-op on some Windows filesystems
618
+ }
619
+ }
package/dist/index.js ADDED
@@ -0,0 +1,257 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import readline from 'node:readline';
7
+ import {
8
+ clearSession,
9
+ loadSession,
10
+ loginWithPassword,
11
+ parseEnvContent,
12
+ pullEnvBundle,
13
+ pushEnvBundle,
14
+ refreshAuthSession,
15
+ resolveProjectConfig,
16
+ resolveSupabaseConfig,
17
+ saveSession,
18
+ writeEnvFileAtomic,
19
+ writeProjectConfig,
20
+ } from './cryptxCore.mjs';
21
+
22
+ function parseArgs(argv) {
23
+ const command = argv[0];
24
+ const flags = {};
25
+ let passthrough = [];
26
+ const ddIdx = argv.indexOf('--');
27
+ const cliArgs = ddIdx === -1 ? argv.slice(1) : argv.slice(1, ddIdx);
28
+ if (ddIdx !== -1) {
29
+ passthrough = argv.slice(ddIdx + 1);
30
+ }
31
+ for (let i = 0; i < cliArgs.length; i += 1) {
32
+ const arg = cliArgs[i];
33
+ if (arg && arg.startsWith('--')) {
34
+ const key = arg.slice(2);
35
+ const val = cliArgs[i + 1];
36
+ if (val && !val.startsWith('--')) {
37
+ flags[key] = val;
38
+ i += 1;
39
+ } else {
40
+ flags[key] = 'true';
41
+ }
42
+ }
43
+ }
44
+ return { command, flags, passthrough };
45
+ }
46
+
47
+ function promptLine(question, { masked = false } = {}) {
48
+ return new Promise((resolve) => {
49
+ const rl = readline.createInterface({
50
+ input: process.stdin,
51
+ output: process.stdout,
52
+ terminal: true,
53
+ });
54
+ if (masked && process.stdout.isTTY) {
55
+ const origWrite = rl._writeToOutput;
56
+ rl._writeToOutput = function writeMasked(str) {
57
+ if (str.includes(question)) {
58
+ origWrite.call(rl, question);
59
+ } else if (str.includes('\n') || str.includes('\r')) {
60
+ origWrite.call(rl, str);
61
+ } else {
62
+ origWrite.call(rl, '*');
63
+ }
64
+ };
65
+ }
66
+ rl.question(question, (answer) => {
67
+ rl.close();
68
+ resolve(answer);
69
+ });
70
+ });
71
+ }
72
+
73
+ async function resolveAuthOrPrompt({ supabaseUrl, supabaseAnonKey, homeDir }) {
74
+ const saved = loadSession({ homeDir, supabaseUrl });
75
+ if (saved) {
76
+ if (saved.refreshToken) {
77
+ const refreshed = await refreshAuthSession({
78
+ supabaseUrl,
79
+ supabaseAnonKey,
80
+ refreshToken: saved.refreshToken,
81
+ });
82
+ if (refreshed) {
83
+ saveSession({ homeDir, session: refreshed });
84
+ return { accessToken: refreshed.accessToken, userId: refreshed.userId };
85
+ }
86
+ }
87
+ return { accessToken: saved.accessToken, userId: saved.userId };
88
+ }
89
+
90
+ const email = (await promptLine('CryptX Account Email: ')).trim();
91
+ const accountPassword = await promptLine('Account Password: ', { masked: true });
92
+ return { email, accountPassword };
93
+ }
94
+
95
+ async function main() {
96
+ const { command, flags, passthrough } = parseArgs(process.argv.slice(2));
97
+ const cwd = process.cwd();
98
+ const homeDir = os.homedir();
99
+
100
+ if (!command || command === '--help' || command === '-h') {
101
+ console.log(
102
+ [
103
+ 'CryptX Zero-Knowledge CLI (v0.3.4)',
104
+ '',
105
+ 'Usage:',
106
+ ' cryptx login [--email <email>]',
107
+ ' cryptx logout',
108
+ ' cryptx run --project <slug> [--env development|staging|production] -- <command>',
109
+ ' cryptx init --project <slug> [--env development|staging|production] [--out .env.local]',
110
+ ' cryptx pull [--project <slug>] [--env <environment>] [--out .env.local]',
111
+ ' cryptx push [--project <slug>] [--env <environment>] [--file .env.local]',
112
+ ].join('\n'),
113
+ );
114
+ return;
115
+ }
116
+
117
+ if (command === 'init') {
118
+ const cfgPath = writeProjectConfig({
119
+ cwd,
120
+ project: flags.project ?? '',
121
+ environment: flags.env ?? 'development',
122
+ outFile: flags.out ?? '.env.local',
123
+ });
124
+ console.log(`Initialized CryptX project config at ${cfgPath}`);
125
+ return;
126
+ }
127
+
128
+ if (command === 'logout') {
129
+ const removed = clearSession({ homeDir });
130
+ console.log(removed ? 'Logged out and cleared local CryptX session.' : 'No active session.');
131
+ return;
132
+ }
133
+
134
+ if (command === 'login') {
135
+ const { supabaseUrl, supabaseAnonKey } = resolveSupabaseConfig({
136
+ env: process.env,
137
+ homeDir,
138
+ });
139
+ const email = (flags.email ?? (await promptLine('CryptX Account Email: '))).trim();
140
+ const accountPassword = await promptLine('Account Password: ', { masked: true });
141
+ const session = await loginWithPassword({
142
+ supabaseUrl,
143
+ supabaseAnonKey,
144
+ email,
145
+ accountPassword,
146
+ });
147
+ const sessionPath = saveSession({ homeDir, session });
148
+ console.log(`Logged in as ${session.email}. Session saved to ${sessionPath} (0600).`);
149
+ return;
150
+ }
151
+
152
+ if (command === 'run') {
153
+ if (passthrough.length === 0) {
154
+ throw new Error(
155
+ 'Missing command after `--`. Example: cryptx run --project my-app --env development -- npm run dev',
156
+ );
157
+ }
158
+ const projectCfg = resolveProjectConfig({
159
+ cwd,
160
+ projectArg: flags.project,
161
+ envArg: flags.env,
162
+ });
163
+ const { supabaseUrl, supabaseAnonKey } = resolveSupabaseConfig({
164
+ env: process.env,
165
+ homeDir,
166
+ });
167
+ const auth = await resolveAuthOrPrompt({ supabaseUrl, supabaseAnonKey, homeDir });
168
+ const masterPassword = await promptLine('Vault Master Password: ', { masked: true });
169
+
170
+ const result = await pullEnvBundle({
171
+ supabaseUrl,
172
+ supabaseAnonKey,
173
+ ...auth,
174
+ masterPassword,
175
+ project: projectCfg.project,
176
+ environment: projectCfg.environment,
177
+ });
178
+
179
+ const injectedVars = parseEnvContent(result.envContent);
180
+ const [cmd, ...cmdArgs] = passthrough;
181
+ const child = spawn(cmd, cmdArgs, {
182
+ stdio: 'inherit',
183
+ shell: process.platform === 'win32',
184
+ env: {
185
+ ...process.env,
186
+ ...injectedVars,
187
+ },
188
+ });
189
+ await new Promise((resolve, reject) => {
190
+ child.on('error', reject);
191
+ child.on('exit', (code) => {
192
+ process.exitCode = code ?? 1;
193
+ resolve();
194
+ });
195
+ });
196
+ return;
197
+ }
198
+
199
+ if (command === 'pull' || command === 'push') {
200
+ const projectCfg = resolveProjectConfig({
201
+ cwd,
202
+ projectArg: flags.project,
203
+ envArg: flags.env,
204
+ outArg: flags.out ?? flags.file,
205
+ });
206
+ const { supabaseUrl, supabaseAnonKey } = resolveSupabaseConfig({
207
+ env: process.env,
208
+ homeDir,
209
+ });
210
+
211
+ const auth = await resolveAuthOrPrompt({ supabaseUrl, supabaseAnonKey, homeDir });
212
+ const masterPassword = await promptLine('Vault Master Password: ', { masked: true });
213
+
214
+ if (command === 'pull') {
215
+ const result = await pullEnvBundle({
216
+ supabaseUrl,
217
+ supabaseAnonKey,
218
+ ...auth,
219
+ masterPassword,
220
+ project: projectCfg.project,
221
+ environment: projectCfg.environment,
222
+ });
223
+ const outPath = path.resolve(cwd, projectCfg.outFile);
224
+ writeEnvFileAtomic(outPath, result.envContent);
225
+ console.log(
226
+ `Decrypted ${projectCfg.project} (${projectCfg.environment}) to ${outPath} (0600).`,
227
+ );
228
+ return;
229
+ }
230
+
231
+ const inPath = path.resolve(cwd, flags.file ?? projectCfg.outFile);
232
+ if (!fs.existsSync(inPath)) {
233
+ throw new Error(`Input file not found: ${inPath}`);
234
+ }
235
+ const envContent = fs.readFileSync(inPath, 'utf8');
236
+ const result = await pushEnvBundle({
237
+ supabaseUrl,
238
+ supabaseAnonKey,
239
+ ...auth,
240
+ masterPassword,
241
+ project: projectCfg.project,
242
+ environment: projectCfg.environment,
243
+ envContent,
244
+ });
245
+ console.log(
246
+ `Encrypted and ${result.action} ${projectCfg.project} (${projectCfg.environment}) [rev ${String(result.revision)}].`,
247
+ );
248
+ return;
249
+ }
250
+
251
+ throw new Error(`Unknown command: ${command}`);
252
+ }
253
+
254
+ main().catch((err) => {
255
+ console.error(err instanceof Error ? err.message : String(err));
256
+ process.exit(1);
257
+ });
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@zaxilabs/cryptx-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.4",
4
+ "description": "Zero-knowledge CLI for CryptX — inject encrypted .env secrets into memory without writing plaintext files to disk.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "bin": {
8
+ "cryptx": "./dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "scripts": {
18
+ "build": "node build.mjs",
19
+ "test": "node build.mjs && node ./dist/index.js --help",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "keywords": [
23
+ "cryptx",
24
+ "secrets",
25
+ "env",
26
+ "zero-knowledge",
27
+ "cli",
28
+ "encryption"
29
+ ],
30
+ "license": "MIT",
31
+ "engines": {
32
+ "node": ">=18.0.0"
33
+ },
34
+ "dependencies": {
35
+ "libsodium-wrappers-sumo": "^0.8.4"
36
+ }
37
+ }