@jazz_010/lockenv 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jazminsoto1234
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,125 @@
1
- # Temporary Holding Version
1
+ # lockenv
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
+ Share `.env` files without pasting secrets into Slack.
4
+
5
+ lockenv encrypts a `.env` file on your machine for one specific person and gives you a link. The link opens once, expires on its own, and only that person can decrypt it. The server never sees your variables.
6
+
7
+ > Status: beta. It works end to end, but expect changes before 1.0.
8
+
9
+ ## Why
10
+
11
+ Most teams still share `.env` files through chat or email. Those messages stay in history forever, get synced to every device, and end up in backups and search indexes.
12
+
13
+ lockenv keeps the same speed (one command, one link) and removes the copy that lives forever.
14
+
15
+ | | Chat / email | One-time link tools | lockenv |
16
+ | ----------------------- | ------------ | ------------------- | ------- |
17
+ | Stays in history | Yes | No | No |
18
+ | Anyone with the link can read it | Yes | Yes | No, only the recipient's key |
19
+ | Server can read it | Yes | Depends | No |
20
+ | Opens only once | No | Yes | Yes |
21
+
22
+ ## Install
23
+
24
+ Requires Node.js 22.13 or later.
25
+
26
+ ```sh
27
+ npm install -g @jazz_010/lockenv
28
+ ```
29
+
30
+ ## Quick start
31
+
32
+ Say Ana wants to send you a `.env`.
33
+
34
+ **1. You create your key (once).**
35
+
36
+ ```sh
37
+ lockenv keygen
38
+ ```
39
+
40
+ It prints your public key, a long text that starts with `age1`. Send it to Ana. It is safe to share: it can only lock files, not open them.
41
+
42
+ **2. Ana saves your key as a contact (once).**
43
+
44
+ ```sh
45
+ lockenv contacts add you age1...
46
+ ```
47
+
48
+ lockenv shows a short fingerprint like `953B 4EFB 7258 2B13`. Ana checks it with you over a call or in person, so she knows the key really is yours.
49
+
50
+ **3. Ana sends the file.**
51
+
52
+ ```sh
53
+ lockenv send .env --to you
54
+ ```
55
+
56
+ She gets a link and sends it to you over any private channel.
57
+
58
+ **4. You open it.**
59
+
60
+ ```sh
61
+ lockenv receive "https://.../s/...#..." -o .env
62
+ ```
63
+
64
+ The file is written to disk and the link stops working.
65
+
66
+ After the first time, sharing is just steps 3 and 4.
67
+
68
+ ## How it works
69
+
70
+ Think of it as a locked box sent through a post office.
71
+
72
+ 1. **Your public key is a padlock.** You give copies of it to anyone. It can lock a box, but it cannot open one.
73
+ 2. **Your private key is the only key that opens that padlock.** It never leaves your computer.
74
+ 3. **Ana locks the `.env` in a box with your padlock** on her computer. From this point on, only your key can open it.
75
+ 4. **The locked box goes to the lockenv server**, and Ana gets a link that says where it is.
76
+ 5. **Ana sends you the link.** Anyone who sees it only gets a locked box they cannot open.
77
+ 6. **You open the link.** The server hands the box over and destroys its copy in the same moment, so nobody can pick it up a second time.
78
+ 7. **lockenv opens the box with your key** and saves the `.env` on your computer.
79
+
80
+ What this means in practice:
81
+
82
+ - **The server never sees your variables.** It only ever holds the locked box.
83
+ - **The link works once.** If it no longer works and you did not open it, it expired, was cancelled, or someone else opened it. Tell the sender.
84
+ - **Unopened links expire after 24 hours.**
85
+ - **The sender can cancel a link** before you open it with `lockenv revoke <id>`.
86
+
87
+ Under the hood, encryption uses [age](https://age-encryption.org) with hybrid post-quantum keys, and the server stores only a hash of the link's token.
88
+
89
+ ## Commands
90
+
91
+ | Command | What it does |
92
+ | ------- | ------------ |
93
+ | `lockenv keygen` | Create your key (first time only) |
94
+ | `lockenv contacts add <alias> <key>` | Save someone else's public key |
95
+ | `lockenv contacts list` | List your contacts and their fingerprints |
96
+ | `lockenv send <file> --to <alias>` | Encrypt a file and create a link |
97
+ | `lockenv receive <link> [-o <output>]` | Open a link and save the file (default `.env`) |
98
+ | `lockenv revoke <id>` | Cancel a link before it is opened |
99
+
100
+ ## Security notes
101
+
102
+ - **Values are never printed.** `receive` writes straight to a file with private permissions and only shows variable names. This keeps secrets out of terminal logs and out of the context of AI coding agents.
103
+ - **A person confirms every action.** `send`, `receive` and `contacts add` ask for confirmation and refuse to run without an interactive terminal, so an agent or script cannot run them silently.
104
+ - **Links must use https.** Plain `http` is only accepted for `localhost`.
105
+ - **Check fingerprints.** Anyone can encrypt a file for your public key. Only accept links from people you trust, through a channel you trust.
106
+ - **Protect your key.** It is stored in `~/.lockenv` and can be protected with a passphrase. If you lose it, files sent to you cannot be opened.
107
+ - **lockenv does not rotate secrets.** If a `.env` already leaked, rotate the credentials at their source.
108
+
109
+ ## Limits
110
+
111
+ - Files up to 16 KB after encryption. A typical `.env` is 1 to 2 KB.
112
+ - Links expire after 24 hours.
113
+ - The public server is rate limited.
114
+
115
+ ## Using your own server
116
+
117
+ The CLI talks to the public lockenv server by default. To use another one:
118
+
119
+ ```sh
120
+ export LOCKENV_API=https://your-server.example.com
121
+ ```
122
+
123
+ ## License
124
+
125
+ [MIT](LICENSE)
@@ -0,0 +1,53 @@
1
+ const RUTA_SECRETOS = "/v1/secrets";
2
+ async function pedir(url, opciones) {
3
+ try {
4
+ return await fetch(url, opciones);
5
+ }
6
+ catch (error) {
7
+ throw new Error(`Could not reach the server (${url}). Check your connection and try again.`, { cause: error });
8
+ }
9
+ }
10
+ async function codigoDeError(respuesta) {
11
+ try {
12
+ const cuerpo = (await respuesta.json());
13
+ return typeof cuerpo.error === "string" ? cuerpo.error : String(respuesta.status);
14
+ }
15
+ catch {
16
+ return String(respuesta.status);
17
+ }
18
+ }
19
+ export async function subirSecreto(api, solicitud) {
20
+ const respuesta = await pedir(`${api}${RUTA_SECRETOS}`, {
21
+ method: "POST",
22
+ headers: { "content-type": "application/json" },
23
+ body: JSON.stringify(solicitud),
24
+ });
25
+ if (respuesta.status !== 201) {
26
+ throw new Error(`The server could not store the file (${respuesta.status} ${await codigoDeError(respuesta)}). Try again in a moment.`);
27
+ }
28
+ const cuerpo = (await respuesta.json());
29
+ return { id: cuerpo.id, expiresAt: cuerpo.expires_at };
30
+ }
31
+ export async function bajarSecreto(api, id, token) {
32
+ const respuesta = await pedir(`${api}${RUTA_SECRETOS}/${encodeURIComponent(id)}`, {
33
+ method: "GET",
34
+ headers: { authorization: `Bearer ${token}` },
35
+ });
36
+ if (respuesta.status === 404) {
37
+ return null;
38
+ }
39
+ if (respuesta.status !== 200) {
40
+ throw new Error(`The server had a problem (${respuesta.status} ${await codigoDeError(respuesta)}). Try again in a moment.`);
41
+ }
42
+ const cuerpo = (await respuesta.json());
43
+ return { ciphertext: cuerpo.ciphertext, recipientFingerprint: cuerpo.recipient_fingerprint, createdAt: cuerpo.created_at };
44
+ }
45
+ export async function revocarSecreto(api, id, token) {
46
+ const respuesta = await pedir(`${api}${RUTA_SECRETOS}/${encodeURIComponent(id)}`, {
47
+ method: "DELETE",
48
+ headers: { authorization: `Bearer ${token}` },
49
+ });
50
+ if (respuesta.status !== 204) {
51
+ throw new Error(`The server had a problem (${respuesta.status} ${await codigoDeError(respuesta)}). Try again in a moment.`);
52
+ }
53
+ }
@@ -0,0 +1,17 @@
1
+ import { esOrigenSeguro } from "./origin.js";
2
+ export const TAMANO_MAXIMO_CIFRADO = 16384;
3
+ const API_POR_DEFECTO = "https://gvxpvpj6ql.execute-api.us-east-2.amazonaws.com"; //aws
4
+ export function urlApi() {
5
+ const api = (process.env.LOCKENV_API ?? API_POR_DEFECTO).replace(/\/+$/, "");
6
+ let url;
7
+ try {
8
+ url = new URL(api);
9
+ }
10
+ catch {
11
+ throw new Error("LOCKENV_API is not a valid URL.");
12
+ }
13
+ if (!esOrigenSeguro(url)) {
14
+ throw new Error("LOCKENV_API must use https (http is only allowed for localhost).");
15
+ }
16
+ return api;
17
+ }
@@ -0,0 +1,25 @@
1
+ import { esOrigenSeguro } from "./origin.js";
2
+ const RUTA_ENLACE = "/s/";
3
+ export function armarEnlace(api, id, token) {
4
+ return `${api}${RUTA_ENLACE}${encodeURIComponent(id)}#${token}`;
5
+ }
6
+ export function leerEnlace(texto) {
7
+ let url;
8
+ try {
9
+ url = new URL(texto.trim());
10
+ }
11
+ catch {
12
+ throw new Error("This link cannot be read. Make sure you copied all of it, including the part after #.");
13
+ }
14
+ if (!esOrigenSeguro(url)) {
15
+ throw new Error("This link is not secure (it does not use https). Ask the sender for a new one.");
16
+ }
17
+ const posicion = url.pathname.lastIndexOf(RUTA_ENLACE);
18
+ const id = posicion >= 0 ? decodeURIComponent(url.pathname.slice(posicion + RUTA_ENLACE.length)) : "";
19
+ const token = url.hash.slice(1);
20
+ if (!id || id.includes("/") || !token) {
21
+ throw new Error("This link is missing a part. Make sure you copied all of it, including the part after #.");
22
+ }
23
+ const api = url.origin + url.pathname.slice(0, posicion);
24
+ return { api, id, token };
25
+ }
@@ -0,0 +1,7 @@
1
+ const HOSTS_LOCALES = new Set(["localhost", "127.0.0.1", "[::1]"]);
2
+ export function esOrigenSeguro(url) {
3
+ if (url.protocol === "https:") {
4
+ return true;
5
+ }
6
+ return url.protocol === "http:" && HOSTS_LOCALES.has(url.hostname);
7
+ }
@@ -0,0 +1,41 @@
1
+ import { obtenerHuellaCorta } from "../crypto/fingerprint.js";
2
+ import { validarLlavePublica } from "../crypto/keys.js";
3
+ import { guardarContacto, listarContactos, validarAlias } from "../storage/contacts.js";
4
+ import { agruparHuella } from "../format/fingerprint.js";
5
+ import { SANGRIA, escribirCampos, escribirLineas, saltoDeLinea } from "../tty/output.js";
6
+ import { tenue, verde } from "../tty/style.js";
7
+ import { confirmar, exigirTerminal } from "../tty/terminal.js";
8
+ export async function contactsAdd(alias, recipient) {
9
+ exigirTerminal();
10
+ const nombre = validarAlias(alias);
11
+ const llave = validarLlavePublica(recipient);
12
+ const huella = await obtenerHuellaCorta(llave);
13
+ saltoDeLinea();
14
+ escribirCampos([
15
+ ["Contact", nombre],
16
+ ["Fingerprint", agruparHuella(huella)],
17
+ ]);
18
+ saltoDeLinea();
19
+ if (!(await confirmar(`Does this fingerprint match the one ${nombre} sees on their device?`))) {
20
+ throw new Error("Cancelled");
21
+ }
22
+ await guardarContacto(nombre, llave);
23
+ saltoDeLinea();
24
+ escribirLineas(`${verde("Contact saved.")} ${tenue(`To send them a file: lockenv send <file> --to ${nombre}`)}`, "");
25
+ }
26
+ export async function contactsList() {
27
+ const contactos = await listarContactos();
28
+ const nombres = Object.keys(contactos).sort();
29
+ if (nombres.length === 0) {
30
+ saltoDeLinea();
31
+ escribirLineas("You have no contacts yet.", tenue("To add one: lockenv contacts add <alias> <key>"), "");
32
+ return;
33
+ }
34
+ const ancho = Math.max(...nombres.map((nombre) => nombre.length)) + 3;
35
+ process.stdout.write("\n");
36
+ for (const nombre of nombres) {
37
+ const huella = agruparHuella(await obtenerHuellaCorta(contactos[nombre].recipient));
38
+ process.stdout.write(`${SANGRIA}${nombre.padEnd(ancho)}${tenue(huella, process.stdout)}\n`);
39
+ }
40
+ process.stdout.write("\n");
41
+ }
@@ -0,0 +1,43 @@
1
+ import { generarParDeLlaves } from "../crypto/keys.js";
2
+ import { obtenerHuellaCorta } from "../crypto/fingerprint.js";
3
+ import { protegerIdentidad } from "../crypto/passphrase.js";
4
+ import { existeIdentidad, guardarIdentidad } from "../storage/identity.js";
5
+ import { rutaIdentidad } from "../storage/paths.js";
6
+ import { leerOculto } from "../tty/hidden-input.js";
7
+ import { agruparHuella } from "../format/fingerprint.js";
8
+ import { escribirCampos, escribirLineas, escribirResultado, saltoDeLinea } from "../tty/output.js";
9
+ import { tenue, verde } from "../tty/style.js";
10
+ import { confirmar, exigirTerminal } from "../tty/terminal.js";
11
+ async function pedirFraseNueva() {
12
+ const frase = await leerOculto("Passphrase to protect your key (Enter to skip): ");
13
+ if (frase === "") {
14
+ return "";
15
+ }
16
+ if ((await leerOculto("Repeat the passphrase: ")) !== frase) {
17
+ throw new Error("The passphrases do not match. Run lockenv keygen again.");
18
+ }
19
+ return frase;
20
+ }
21
+ export async function keygen() {
22
+ exigirTerminal();
23
+ if (await existeIdentidad()) {
24
+ throw new Error(`A key already exists at ${rutaIdentidad()}. Replacing it would lock you out of files sent to you.`);
25
+ }
26
+ const { identity, recipient } = await generarParDeLlaves();
27
+ saltoDeLinea();
28
+ const frase = await pedirFraseNueva();
29
+ if (frase !== "") {
30
+ await guardarIdentidad(await protegerIdentidad(identity, frase));
31
+ }
32
+ else {
33
+ if (!(await confirmar("Save the key without a passphrase? Anyone with access to this computer could use it."))) {
34
+ throw new Error("Cancelled");
35
+ }
36
+ await guardarIdentidad(identity + "\n");
37
+ }
38
+ saltoDeLinea();
39
+ escribirLineas(`${verde("Key created.")} ${tenue(`Saved to ${rutaIdentidad()}`)}`, "");
40
+ escribirCampos([["Fingerprint", agruparHuella(await obtenerHuellaCorta(recipient))]]);
41
+ escribirLineas("", "Share this key with anyone who will send you files:", "");
42
+ escribirResultado(recipient);
43
+ }
@@ -0,0 +1,30 @@
1
+ import { bajarSecreto } from "../api/client.js";
2
+ import { leerEnlace } from "../api/link.js";
3
+ import { desencriptar } from "../crypto/decrypt.js";
4
+ import { nombresDeVariables } from "../env/variables.js";
5
+ import { cargarIdentidad } from "../storage/identity.js";
6
+ import { escribirPrivado, existe } from "../storage/secure-file.js";
7
+ import { leerOculto } from "../tty/hidden-input.js";
8
+ import { SANGRIA, escribirLineas, escribirProgreso, saltoDeLinea } from "../tty/output.js";
9
+ import { negrita, tenue, verde } from "../tty/style.js";
10
+ import { confirmar, exigirTerminal } from "../tty/terminal.js";
11
+ export async function receive(textoEnlace, salida) {
12
+ exigirTerminal();
13
+ const { api, id, token } = leerEnlace(textoEnlace);
14
+ const pregunta = (await existe(salida)) ? `${salida} already exists. Replace it?` : `Save to ${salida}?`;
15
+ saltoDeLinea();
16
+ if (!(await confirmar(pregunta))) {
17
+ throw new Error("Cancelled");
18
+ }
19
+ const identity = await cargarIdentidad(() => leerOculto("Passphrase for your key: "));
20
+ escribirProgreso("Downloading and decrypting...");
21
+ const secreto = await bajarSecreto(api, id, token);
22
+ if (!secreto) {
23
+ throw new Error("This link no longer works. It was already opened, it expired, or it was cancelled. If you did not open it before, tell the sender: someone else may have seen it.");
24
+ }
25
+ const texto = await desencriptar(new Uint8Array(Buffer.from(secreto.ciphertext, "base64url")), identity);
26
+ await escribirPrivado(salida, texto);
27
+ const variables = nombresDeVariables(texto);
28
+ saltoDeLinea();
29
+ escribirLineas(`${verde("File received.")} ${tenue(`Saved to ${salida}`)}`, "", negrita(`Variables (${variables.length})`), ...variables.map((variable) => SANGRIA + variable), "");
30
+ }
@@ -0,0 +1,11 @@
1
+ import { revocarSecreto } from "../api/client.js";
2
+ import { borrarEnviado, buscarEnviado } from "../storage/sent.js";
3
+ import { escribirLineas, saltoDeLinea } from "../tty/output.js";
4
+ import { verde } from "../tty/style.js";
5
+ export async function revoke(id) {
6
+ const { api, revokeToken } = await buscarEnviado(id);
7
+ await revocarSecreto(api, id, revokeToken);
8
+ await borrarEnviado(id);
9
+ saltoDeLinea();
10
+ escribirLineas(`${verde("Link cancelled.")} It can no longer be opened.`, "");
11
+ }
@@ -0,0 +1,51 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { subirSecreto } from "../api/client.js";
3
+ import { TAMANO_MAXIMO_CIFRADO, urlApi } from "../api/config.js";
4
+ import { armarEnlace } from "../api/link.js";
5
+ import { encriptar } from "../crypto/encrypt.js";
6
+ import { obtenerHuellaCorta, obtenerHuellaParaServidor } from "../crypto/fingerprint.js";
7
+ import { generarToken, hashearToken } from "../crypto/tokens.js";
8
+ import { nombresDeVariables } from "../env/variables.js";
9
+ import { fechaLocal, horasRestantes } from "../format/date.js";
10
+ import { agruparHuella } from "../format/fingerprint.js";
11
+ import { buscarContacto, validarAlias } from "../storage/contacts.js";
12
+ import { guardarEnviado } from "../storage/sent.js";
13
+ import { escribirCampos, escribirLineas, escribirProgreso, escribirResultado, saltoDeLinea } from "../tty/output.js";
14
+ import { tenue, verde } from "../tty/style.js";
15
+ import { confirmar, exigirTerminal } from "../tty/terminal.js";
16
+ export async function send(archivo, alias) {
17
+ exigirTerminal();
18
+ const nombre = validarAlias(alias);
19
+ const contacto = await buscarContacto(nombre);
20
+ const texto = await readFile(archivo, "utf8");
21
+ const variables = nombresDeVariables(texto);
22
+ saltoDeLinea();
23
+ escribirCampos([
24
+ ["File", `${archivo} ${tenue(`(${variables.length} variables)`)}`],
25
+ ["To", nombre],
26
+ ["Fingerprint", agruparHuella(await obtenerHuellaCorta(contacto.recipient))],
27
+ ]);
28
+ saltoDeLinea();
29
+ if (!(await confirmar(`Encrypt and upload ${archivo} for ${nombre}?`))) {
30
+ throw new Error("Cancelled");
31
+ }
32
+ escribirProgreso("Encrypting and uploading...");
33
+ const cifrado = await encriptar(texto, contacto.recipient);
34
+ if (cifrado.byteLength > TAMANO_MAXIMO_CIFRADO) {
35
+ throw new Error(`The file is too large (${Math.ceil(cifrado.byteLength / 1024)} KB encrypted). The limit is ${TAMANO_MAXIMO_CIFRADO / 1024} KB.`);
36
+ }
37
+ const readToken = generarToken();
38
+ const revokeToken = generarToken();
39
+ const api = urlApi();
40
+ const { id, expiresAt } = await subirSecreto(api, {
41
+ ciphertext: Buffer.from(cifrado).toString("base64url"),
42
+ recipient_fingerprint: await obtenerHuellaParaServidor(contacto.recipient),
43
+ read_token_hash: hashearToken(readToken),
44
+ revoke_token_hash: hashearToken(revokeToken),
45
+ });
46
+ await guardarEnviado(id, { api, revokeToken });
47
+ saltoDeLinea();
48
+ escribirLineas(`${verde("Done.")} It can be opened once and expires ${fechaLocal(expiresAt)} (in ${horasRestantes(expiresAt)} hours).`, "", "Share this link over a private channel:", "");
49
+ escribirResultado(armarEnlace(api, id, readToken));
50
+ escribirLineas(tenue(`To cancel it before it is opened: lockenv revoke ${id}`), "");
51
+ }
@@ -0,0 +1,12 @@
1
+ import * as age from "age-encryption";
2
+ import { validarLlavePrivada } from "./keys.js";
3
+ export async function desencriptar(ciphertext, identity) {
4
+ const d = new age.Decrypter();
5
+ d.addIdentity(validarLlavePrivada(identity));
6
+ try {
7
+ return await d.decrypt(ciphertext, "text");
8
+ }
9
+ catch (error) {
10
+ throw new Error("Could not decrypt the file. This link was not made for your key, or the content is damaged.", { cause: error });
11
+ }
12
+ }
@@ -0,0 +1,7 @@
1
+ import * as age from "age-encryption";
2
+ import { validarLlavePublica } from "./keys.js";
3
+ export async function encriptar(mensaje, recipient) {
4
+ const e = new age.Encrypter();
5
+ e.addRecipient(validarLlavePublica(recipient));
6
+ return await e.encrypt(mensaje);
7
+ }
@@ -0,0 +1,15 @@
1
+ import { validarLlavePublica } from "./keys.js";
2
+ export async function obtenerHuellaCorta(clavePublica, longitud = 16) {
3
+ const data = new TextEncoder().encode(validarLlavePublica(clavePublica));
4
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
5
+ return Array.from(new Uint8Array(hashBuffer))
6
+ .map((b) => b.toString(16).padStart(2, "0"))
7
+ .join("")
8
+ .toUpperCase()
9
+ .slice(0, longitud);
10
+ }
11
+ export const PREFIJO_HUELLA_SERVIDOR = "lk1:";
12
+ export async function obtenerHuellaParaServidor(clavePublica) {
13
+ const huella = await obtenerHuellaCorta(clavePublica);
14
+ return PREFIJO_HUELLA_SERVIDOR + huella.toLowerCase();
15
+ }
@@ -0,0 +1,20 @@
1
+ import * as age from "age-encryption";
2
+ export async function generarParDeLlaves() {
3
+ const identity = await age.generateHybridIdentity();
4
+ const recipient = await age.identityToRecipient(identity);
5
+ return { identity, recipient };
6
+ }
7
+ export function validarLlavePublica(recipient) {
8
+ const limpia = recipient.trim();
9
+ if (!/^age1[0-9a-z]+$/.test(limpia)) {
10
+ throw new Error("That key is not valid. Make sure you copied all of it; it starts with age1.");
11
+ }
12
+ return limpia;
13
+ }
14
+ export function validarLlavePrivada(identity) {
15
+ const limpia = identity.trim();
16
+ if (!/^AGE-SECRET-KEY-[0-9A-Z-]+$/.test(limpia)) {
17
+ throw new Error("Your saved key cannot be read.");
18
+ }
19
+ return limpia;
20
+ }
@@ -0,0 +1,19 @@
1
+ import * as age from "age-encryption";
2
+ import { validarLlavePrivada } from "./keys.js";
3
+ export async function protegerIdentidad(identity, frase) {
4
+ const e = new age.Encrypter();
5
+ e.setPassphrase(frase);
6
+ return await e.encrypt(validarLlavePrivada(identity));
7
+ }
8
+ export async function abrirIdentidad(protegida, frase) {
9
+ const d = new age.Decrypter();
10
+ d.addPassphrase(frase);
11
+ let texto;
12
+ try {
13
+ texto = await d.decrypt(protegida, "text");
14
+ }
15
+ catch (error) {
16
+ throw new Error("Wrong passphrase.", { cause: error });
17
+ }
18
+ return validarLlavePrivada(texto);
19
+ }
@@ -0,0 +1,9 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ const BYTES_TOKEN = 32;
3
+ const PREFIJO_HASH = "sha256:";
4
+ export function generarToken() {
5
+ return randomBytes(BYTES_TOKEN).toString("base64url");
6
+ }
7
+ export function hashearToken(token) {
8
+ return PREFIJO_HASH + createHash("sha256").update(token, "utf8").digest("hex");
9
+ }
@@ -0,0 +1,10 @@
1
+ export function nombresDeVariables(texto) {
2
+ const nombres = [];
3
+ for (const linea of texto.split(/\r?\n/)) {
4
+ const coincidencia = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=/.exec(linea);
5
+ if (coincidencia) {
6
+ nombres.push(coincidencia[1]);
7
+ }
8
+ }
9
+ return nombres;
10
+ }
@@ -0,0 +1,8 @@
1
+ const FORMATO_FECHA = new Intl.DateTimeFormat("en", { day: "numeric", month: "long", hour: "2-digit", minute: "2-digit" });
2
+ const MILISEGUNDOS_POR_HORA = 3_600_000;
3
+ export function fechaLocal(iso) {
4
+ return FORMATO_FECHA.format(new Date(iso));
5
+ }
6
+ export function horasRestantes(iso) {
7
+ return Math.max(0, Math.round((new Date(iso).getTime() - Date.now()) / MILISEGUNDOS_POR_HORA));
8
+ }
@@ -0,0 +1,3 @@
1
+ export function agruparHuella(huella) {
2
+ return (huella.match(/.{1,4}/g) ?? [huella]).join(" ");
3
+ }
package/dist/help.js ADDED
@@ -0,0 +1,26 @@
1
+ import { SANGRIA } from "./tty/output.js";
2
+ import { cian, negrita, tenue } from "./tty/style.js";
3
+ const COMANDOS = [
4
+ ["lockenv keygen", "Create your key (first time only)"],
5
+ ["lockenv contacts add <alias> <key>", "Save someone else's key"],
6
+ ["lockenv contacts list", "List your contacts"],
7
+ ["lockenv send <file> --to <alias>", "Encrypt a file and create a link"],
8
+ ["lockenv receive <link> [-o <output>]", "Open a link and save the file"],
9
+ ["lockenv revoke <id>", "Cancel a link before it is opened"],
10
+ ];
11
+ export function textoAyuda() {
12
+ const salida = process.stdout;
13
+ const ancho = Math.max(...COMANDOS.map(([comando]) => comando.length)) + 3;
14
+ const filas = COMANDOS.map(([comando, descripcion]) => `${SANGRIA}${SANGRIA}${cian(comando.padEnd(ancho), salida)}${tenue(descripcion, salida)}`);
15
+ return [
16
+ "",
17
+ `${SANGRIA}${negrita("lockenv", salida)} ${tenue("share encrypted, one-time .env files", salida)}`,
18
+ "",
19
+ `${SANGRIA}${negrita("Usage", salida)}`,
20
+ ...filas,
21
+ "",
22
+ `${SANGRIA}${tenue("To use another server, set LOCKENV_API.", salida)}`,
23
+ "",
24
+ "",
25
+ ].join("\n");
26
+ }
package/dist/main.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { contactsAdd, contactsList } from "./commands/contacts.js";
4
+ import { keygen } from "./commands/keygen.js";
5
+ import { receive } from "./commands/receive.js";
6
+ import { revoke } from "./commands/revoke.js";
7
+ import { send } from "./commands/send.js";
8
+ import { textoAyuda } from "./help.js";
9
+ import { escribirError } from "./tty/output.js";
10
+ async function ejecutar(argumentos) {
11
+ if (argumentos[0] === "revoke" && argumentos.length === 2) {
12
+ return await revoke(argumentos[1]);
13
+ }
14
+ const { values, positionals } = parseArgs({
15
+ args: argumentos,
16
+ allowPositionals: true,
17
+ strict: true,
18
+ options: {
19
+ to: { type: "string" },
20
+ output: { type: "string", short: "o" },
21
+ help: { type: "boolean", short: "h" },
22
+ },
23
+ });
24
+ const [comando, ...resto] = positionals;
25
+ if (values.help || !comando) {
26
+ process.stdout.write(textoAyuda());
27
+ return;
28
+ }
29
+ if (comando === "keygen" && resto.length === 0) {
30
+ return await keygen();
31
+ }
32
+ if (comando === "contacts" && resto[0] === "add" && resto.length === 3) {
33
+ return await contactsAdd(resto[1], resto[2]);
34
+ }
35
+ if (comando === "contacts" && resto[0] === "list" && resto.length === 1) {
36
+ return await contactsList();
37
+ }
38
+ if (comando === "send" && resto.length === 1 && values.to) {
39
+ return await send(resto[0], values.to);
40
+ }
41
+ if (comando === "receive" && resto.length === 1) {
42
+ return await receive(resto[0], values.output ?? ".env");
43
+ }
44
+ if (comando === "revoke" && resto.length === 1) {
45
+ return await revoke(resto[0]);
46
+ }
47
+ throw new Error("Unknown command. Run lockenv --help to see the list.");
48
+ }
49
+ ejecutar(process.argv.slice(2)).catch((error) => {
50
+ escribirError(error instanceof Error ? error.message : "Unknown error.");
51
+ process.exitCode = 1;
52
+ });
@@ -0,0 +1,48 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { validarLlavePublica } from "../crypto/keys.js";
3
+ import { directorioBase, rutaContactos } from "./paths.js";
4
+ import { asegurarDirectorioPrivado, escribirPrivado } from "./secure-file.js";
5
+ export function validarAlias(alias) {
6
+ const limpio = alias.trim();
7
+ if (!/^[a-zA-Z0-9_-]{1,32}$/.test(limpio)) {
8
+ throw new Error("An alias can only use letters, numbers, - and _ (up to 32).");
9
+ }
10
+ return limpio;
11
+ }
12
+ export async function listarContactos() {
13
+ let texto;
14
+ try {
15
+ texto = await readFile(rutaContactos(), "utf8");
16
+ }
17
+ catch (error) {
18
+ if (error.code === "ENOENT") {
19
+ return {};
20
+ }
21
+ throw error;
22
+ }
23
+ const datos = JSON.parse(texto);
24
+ if (typeof datos !== "object" || datos === null || Array.isArray(datos)) {
25
+ throw new Error(`Your contact list cannot be read (${rutaContactos()}).`);
26
+ }
27
+ return datos;
28
+ }
29
+ export async function guardarContacto(alias, recipient) {
30
+ const nombre = validarAlias(alias);
31
+ const contactos = await listarContactos();
32
+ if (contactos[nombre]) {
33
+ throw new Error(`A contact named ${nombre} already exists. Pick another alias.`);
34
+ }
35
+ const contacto = { recipient: validarLlavePublica(recipient), agregado: new Date().toISOString() };
36
+ contactos[nombre] = contacto;
37
+ await asegurarDirectorioPrivado(directorioBase());
38
+ await escribirPrivado(rutaContactos(), JSON.stringify(contactos, null, 2) + "\n");
39
+ return contacto;
40
+ }
41
+ export async function buscarContacto(alias) {
42
+ const nombre = validarAlias(alias);
43
+ const contacto = (await listarContactos())[nombre];
44
+ if (!contacto) {
45
+ throw new Error(`No contact named ${nombre}. To add one: lockenv contacts add ${nombre} <key>`);
46
+ }
47
+ return { recipient: validarLlavePublica(contacto.recipient), agregado: contacto.agregado };
48
+ }
@@ -0,0 +1,35 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { abrirIdentidad } from "../crypto/passphrase.js";
3
+ import { validarLlavePrivada } from "../crypto/keys.js";
4
+ import { directorioBase, rutaIdentidad } from "./paths.js";
5
+ import { asegurarDirectorioPrivado, escribirPrivado, existe } from "./secure-file.js";
6
+ const PREFIJO_PLANO = "AGE-SECRET-KEY-";
7
+ export async function existeIdentidad() {
8
+ return await existe(rutaIdentidad());
9
+ }
10
+ export async function guardarIdentidad(contenido) {
11
+ if (await existeIdentidad()) {
12
+ throw new Error(`A key already exists at ${rutaIdentidad()}`);
13
+ }
14
+ await asegurarDirectorioPrivado(directorioBase());
15
+ await escribirPrivado(rutaIdentidad(), contenido);
16
+ }
17
+ export async function estaProtegida() {
18
+ const bytes = await leerBytes();
19
+ return !new TextDecoder().decode(bytes.subarray(0, PREFIJO_PLANO.length)).startsWith(PREFIJO_PLANO);
20
+ }
21
+ export async function cargarIdentidad(pedirFrase) {
22
+ const bytes = await leerBytes();
23
+ if (!(await estaProtegida())) {
24
+ return validarLlavePrivada(new TextDecoder().decode(bytes));
25
+ }
26
+ return await abrirIdentidad(bytes, await pedirFrase());
27
+ }
28
+ async function leerBytes() {
29
+ try {
30
+ return new Uint8Array(await readFile(rutaIdentidad()));
31
+ }
32
+ catch {
33
+ throw new Error(`You do not have a key yet. Create one with: lockenv keygen`);
34
+ }
35
+ }
@@ -0,0 +1,17 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ export function directorioBase() {
4
+ return process.env.LOCKENV_HOME ?? join(homedir(), ".lockenv");
5
+ }
6
+ export function rutaIdentidad() {
7
+ return join(directorioBase(), "identity");
8
+ }
9
+ export function rutaContactos() {
10
+ return join(directorioBase(), "contacts");
11
+ }
12
+ export function directorioEnviados() {
13
+ return join(directorioBase(), "sent");
14
+ }
15
+ export function rutaEnviado(id) {
16
+ return join(directorioEnviados(), id);
17
+ }
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { access, chmod, mkdir, open, rename, rm } from "node:fs/promises";
4
+ import { userInfo } from "node:os";
5
+ function restringirEnWindows(ruta, esDirectorio) {
6
+ if (process.platform !== "win32") {
7
+ return;
8
+ }
9
+ const permiso = esDirectorio ? "(OI)(CI)F" : "F";
10
+ execFileSync("icacls", [ruta, "/inheritance:r", "/grant:r", `${userInfo().username}:${permiso}`], { stdio: "ignore" });
11
+ }
12
+ export async function existe(ruta) {
13
+ try {
14
+ await access(ruta);
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ export async function asegurarDirectorioPrivado(ruta) {
22
+ await mkdir(ruta, { recursive: true, mode: 0o700 });
23
+ if (process.platform !== "win32") {
24
+ await chmod(ruta, 0o700);
25
+ }
26
+ restringirEnWindows(ruta, true);
27
+ }
28
+ export async function escribirPrivado(ruta, contenido) {
29
+ const temporal = `${ruta}.${randomBytes(6).toString("hex")}.tmp`;
30
+ const archivo = await open(temporal, "wx", 0o600);
31
+ try {
32
+ restringirEnWindows(temporal, false);
33
+ await archivo.writeFile(contenido);
34
+ await archivo.sync();
35
+ }
36
+ catch (error) {
37
+ await archivo.close();
38
+ await rm(temporal, { force: true });
39
+ throw error;
40
+ }
41
+ await archivo.close();
42
+ if (process.platform !== "win32") {
43
+ await chmod(temporal, 0o600);
44
+ }
45
+ await rename(temporal, ruta);
46
+ }
@@ -0,0 +1,29 @@
1
+ import { readFile, rm } from "node:fs/promises";
2
+ import { directorioBase, directorioEnviados, rutaEnviado } from "./paths.js";
3
+ import { asegurarDirectorioPrivado, escribirPrivado } from "./secure-file.js";
4
+ const ID_VALIDO = /^[A-Za-z0-9_-]+$/;
5
+ function validarId(id) {
6
+ if (!ID_VALIDO.test(id)) {
7
+ throw new Error("That id does not exist. Check that you copied it correctly.");
8
+ }
9
+ return id;
10
+ }
11
+ export async function guardarEnviado(id, enviado) {
12
+ await asegurarDirectorioPrivado(directorioBase());
13
+ await asegurarDirectorioPrivado(directorioEnviados());
14
+ await escribirPrivado(rutaEnviado(validarId(id)), JSON.stringify({ api: enviado.api, revoke_token: enviado.revokeToken }) + "\n");
15
+ }
16
+ export async function buscarEnviado(id) {
17
+ let texto;
18
+ try {
19
+ texto = await readFile(rutaEnviado(validarId(id)), "utf8");
20
+ }
21
+ catch {
22
+ throw new Error(`No link of yours has the id ${id}. Check that you copied it correctly.`);
23
+ }
24
+ const datos = JSON.parse(texto);
25
+ return { api: datos.api, revokeToken: datos.revoke_token };
26
+ }
27
+ export async function borrarEnviado(id) {
28
+ await rm(rutaEnviado(validarId(id)), { force: true });
29
+ }
@@ -0,0 +1,37 @@
1
+ import { SANGRIA } from "./output.js";
2
+ export function leerOculto(pregunta) {
3
+ const stdin = process.stdin;
4
+ return new Promise((resolve, reject) => {
5
+ let valor = "";
6
+ const terminar = () => {
7
+ stdin.off("data", alRecibir);
8
+ stdin.setRawMode(false);
9
+ stdin.pause();
10
+ process.stderr.write("\n");
11
+ };
12
+ const alRecibir = (datos) => {
13
+ for (const caracter of datos.toString("utf8")) {
14
+ if (caracter === "\r" || caracter === "\n") {
15
+ terminar();
16
+ resolve(valor);
17
+ return;
18
+ }
19
+ if (caracter === "\u0003" || caracter === "\u0004") {
20
+ terminar();
21
+ reject(new Error("Cancelled"));
22
+ return;
23
+ }
24
+ if (caracter === "\u007f" || caracter === "\b") {
25
+ valor = valor.slice(0, -1);
26
+ }
27
+ else {
28
+ valor += caracter;
29
+ }
30
+ }
31
+ };
32
+ process.stderr.write(SANGRIA + pregunta);
33
+ stdin.setRawMode(true);
34
+ stdin.resume();
35
+ stdin.on("data", alRecibir);
36
+ });
37
+ }
@@ -0,0 +1,27 @@
1
+ import { amarillo, cian, rojo, tenue } from "./style.js";
2
+ export const SANGRIA = " ";
3
+ export function saltoDeLinea() {
4
+ process.stderr.write("\n");
5
+ }
6
+ export function escribirLineas(...lineas) {
7
+ process.stderr.write(lineas.map((linea) => (linea === "" ? "" : SANGRIA + linea)).join("\n") + "\n");
8
+ }
9
+ export function escribirCampos(campos) {
10
+ const ancho = Math.max(...campos.map(([etiqueta]) => etiqueta.length)) + 3;
11
+ escribirLineas(...campos.map(([etiqueta, valor]) => tenue(etiqueta.padEnd(ancho)) + valor));
12
+ }
13
+ export function escribirResultado(texto) {
14
+ if (process.stdout.isTTY) {
15
+ process.stdout.write(`${SANGRIA}${cian(texto, process.stdout)}\n\n`);
16
+ return;
17
+ }
18
+ process.stdout.write(`${texto}\n`);
19
+ }
20
+ export function escribirProgreso(texto) {
21
+ escribirLineas(tenue(texto));
22
+ }
23
+ export function escribirError(mensaje) {
24
+ const etiqueta = mensaje === "Cancelled" ? amarillo("Cancelled.") : rojo("Error:");
25
+ const detalle = mensaje === "Cancelled" ? "" : ` ${mensaje}`;
26
+ process.stderr.write(`\n${SANGRIA}${etiqueta}${detalle}\n\n`);
27
+ }
@@ -0,0 +1,22 @@
1
+ import { styleText } from "node:util";
2
+ function pintar(formato, texto, salida) {
3
+ return styleText(formato, texto, { stream: salida });
4
+ }
5
+ export function negrita(texto, salida = process.stderr) {
6
+ return pintar("bold", texto, salida);
7
+ }
8
+ export function tenue(texto, salida = process.stderr) {
9
+ return pintar("dim", texto, salida);
10
+ }
11
+ export function verde(texto, salida = process.stderr) {
12
+ return pintar("green", texto, salida);
13
+ }
14
+ export function rojo(texto, salida = process.stderr) {
15
+ return pintar("red", texto, salida);
16
+ }
17
+ export function amarillo(texto, salida = process.stderr) {
18
+ return pintar("yellow", texto, salida);
19
+ }
20
+ export function cian(texto, salida = process.stderr) {
21
+ return pintar("cyan", texto, salida);
22
+ }
@@ -0,0 +1,18 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { SANGRIA } from "./output.js";
3
+ import { tenue } from "./style.js";
4
+ export function exigirTerminal() {
5
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
6
+ throw new Error("This command asks questions, so it only works in a terminal.");
7
+ }
8
+ }
9
+ export async function confirmar(pregunta) {
10
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
11
+ try {
12
+ const respuesta = await rl.question(`${SANGRIA}${pregunta} ${tenue("[y/N]")} `);
13
+ return /^(y|yes)$/i.test(respuesta.trim());
14
+ }
15
+ finally {
16
+ rl.close();
17
+ }
18
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@jazz_010/lockenv",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Share encrypted, one-time .env files from the terminal",
5
+ "keywords": [
6
+ "env",
7
+ "dotenv",
8
+ "secrets",
9
+ "encryption",
10
+ "age",
11
+ "post-quantum",
12
+ "one-time",
13
+ "cli"
14
+ ],
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "bin": {
18
+ "lockenv": "dist/main.js"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "scripts": {
24
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
25
+ "build": "npm run clean && tsc -p .",
26
+ "typecheck": "tsc -p . --noEmit",
27
+ "test": "vitest run",
28
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
29
+ },
30
+ "engines": {
31
+ "node": ">=22.13"
32
+ },
33
+ "dependencies": {
34
+ "age-encryption": "^0.3.1"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^24.0.0",
38
+ "typescript": "^7.0.2",
39
+ "vitest": "^5.1.2"
40
+ }
41
+ }