@neon-pixels/crypto 0.0.0 → 0.3.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 Neon Pixels Studio
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 ADDED
@@ -0,0 +1,78 @@
1
+ # @neon-pixels/crypto
2
+
3
+ Encrypt secrets you store (API tokens, credentials) with AES-256-GCM. Payloads are versioned and name the key that wrote them, so you can rotate keys without breaking old values. Uses only Node's built-in `crypto`; nothing is read from `process.env`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @neon-pixels/crypto
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Keys are passed in as arguments. Generate one with `openssl rand -base64 32`, load it from your own config, and decode it with `decodeKey`.
14
+
15
+ ```ts
16
+ import { decodeKey, decrypt, encrypt } from "@neon-pixels/crypto";
17
+
18
+ const keys = { primary: decodeKey(process.env.MY_APP_KEY ?? "") };
19
+
20
+ // Associated data is optional. Pass something that identifies where the
21
+ // value is stored; decrypting with a different value fails.
22
+ const payload = encrypt("api-token", keys, `integration:${rowId}`);
23
+ const token = decrypt(payload, keys, `integration:${rowId}`);
24
+ ```
25
+
26
+ ### API
27
+
28
+ - `encrypt(plaintext, keys, associatedData?)` returns a payload string, written with `keys.primary`.
29
+ - `decrypt(payload, keys, associatedData?)` returns the plaintext. The payload names its key, so it decrypts with any key in the set.
30
+ - `isEncryptedWithPrimaryKey(payload, keys)` is `true` when the payload was written with the primary key.
31
+ - `reencrypt(payload, keys, associatedData?)` returns the value encrypted under the primary key. A payload already on the primary key is returned unchanged without being decrypted, so its associated data is not checked.
32
+ - `decodeKey(base64)` turns a base64 string into a 32-byte key and rejects anything else.
33
+ - `deriveKeyId(key)` returns the key id stored in payloads.
34
+ - `KeySet` is `{ primary: Uint8Array; previous?: readonly Uint8Array[] }`. Keys must be exactly 32 bytes.
35
+
36
+ Empty associated data is rejected, so "empty" and "none" can never differ between encrypt and decrypt.
37
+
38
+ ### Errors
39
+
40
+ Every failure throws `SecretCryptoError` with a `code`: `invalid-key`, `invalid-associated-data`, `invalid-plaintext`, `malformed-payload`, `unsupported-version`, `unknown-key`, or `decryption-failed`. Messages are fixed text and never include keys, plaintext, or payload contents.
41
+
42
+ ## Payload format
43
+
44
+ One string of five `:`-separated segments:
45
+
46
+ ```
47
+ v2:<keyId>:<iv>:<authTag>:<ciphertext>
48
+ ```
49
+
50
+ - `v2` is the format version. Any other version is rejected.
51
+ - `keyId` is the first 8 hex characters of the SHA-256 of the key. It is not secret and cannot be reversed to the key.
52
+ - `iv` is a random 12-byte IV, base64.
53
+ - `authTag` is the 16-byte GCM tag, base64.
54
+ - `ciphertext` is the AES-256-GCM output, base64.
55
+
56
+ Associated data is authenticated through GCM's AAD but is not stored in the payload.
57
+
58
+ ## Rotating a key
59
+
60
+ 1. Generate a new key and add it to your config next to the current one.
61
+ 2. Deploy with the new key as `primary` and the old key in `previous`. New writes use the new key; old values still decrypt.
62
+
63
+ ```ts
64
+ const keys = { primary: newKey, previous: [oldKey] };
65
+ ```
66
+
67
+ 3. Re-encrypt stored values with `reencrypt`, passing the same associated data each was written with:
68
+
69
+ ```ts
70
+ for (const row of rows) {
71
+ if (!isEncryptedWithPrimaryKey(row.secret, keys)) {
72
+ row.secret = reencrypt(row.secret, keys, `integration:${row.id}`);
73
+ await save(row);
74
+ }
75
+ }
76
+ ```
77
+
78
+ 4. When no stored value uses the old key, remove it from `previous`. Values still on it would then fail with `unknown-key`.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The keys an app passes in. `primary` encrypts. `previous` keys only
3
+ * decrypt, so values written before a rotation still read.
4
+ */
5
+ interface KeySet {
6
+ primary: Uint8Array;
7
+ previous?: readonly Uint8Array[];
8
+ }
9
+ /**
10
+ * Decodes a base64 string (for example from a secret store) into a key.
11
+ * Rejects text that is not valid base64 or does not decode to 32 bytes.
12
+ */
13
+ export declare function decodeKey(base64Key: string): Uint8Array;
14
+ /**
15
+ * A short non-secret identifier stored in each payload so decrypt can pick
16
+ * the right key. A truncated SHA-256 of the key: it cannot be reversed and
17
+ * needs no configuration to keep in sync.
18
+ */
19
+ export declare function deriveKeyId(key: Uint8Array): string;
20
+ /**
21
+ * Encrypts `plaintext` under `keys.primary` and returns one opaque string:
22
+ * `v2:<keyId>:<base64 iv>:<base64 authTag>:<base64 ciphertext>`.
23
+ *
24
+ * `associatedData` is authenticated, not encrypted. Pass something that
25
+ * identifies where the value lives (a row id, for example) and the same
26
+ * value must be passed to decrypt, so a ciphertext moved elsewhere fails.
27
+ */
28
+ export declare function encrypt(plaintext: string, keys: KeySet, associatedData?: string): string;
29
+ /**
30
+ * Reverses `encrypt`. The payload names its key, so any key in the set
31
+ * (primary or previous) can decrypt it. Throws `SecretCryptoError` for a
32
+ * malformed payload, an unknown key, mismatched associated data, or
33
+ * tampering.
34
+ */
35
+ export declare function decrypt(payload: string, keys: KeySet, associatedData?: string): string;
36
+ /** True when the payload was written with the primary key and needs no re-encrypting. */
37
+ export declare function isEncryptedWithPrimaryKey(payload: string, keys: KeySet): boolean;
38
+ /**
39
+ * Re-encrypts a payload under the primary key, for rotation. A payload that
40
+ * already uses the primary key is returned unchanged. The associated data
41
+ * must match the original and is reused for the new payload. A payload
42
+ * already on the primary key is not decrypted, so its associated data is not
43
+ * checked.
44
+ */
45
+ export declare function reencrypt(payload: string, keys: KeySet, associatedData?: string): string;
46
+ type SecretCryptoErrorCode = "invalid-key" | "invalid-associated-data" | "invalid-plaintext" | "malformed-payload" | "unsupported-version" | "unknown-key" | "decryption-failed";
47
+ /**
48
+ * The only error this package throws. Messages are fixed text: they never
49
+ * include key material, plaintext, or any part of a payload.
50
+ */
51
+ export declare class SecretCryptoError extends Error {
52
+ name: string;
53
+ readonly code: SecretCryptoErrorCode;
54
+ constructor(code: SecretCryptoErrorCode, message: string);
55
+ }
56
+ export type { KeySet, SecretCryptoErrorCode };
package/dist/index.js ADDED
@@ -0,0 +1,179 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
2
+ // src/errors.ts
3
+ /**
4
+ * The only error this package throws. Messages are fixed text: they never
5
+ * include key material, plaintext, or any part of a payload.
6
+ */
7
+ var SecretCryptoError = class extends Error {
8
+ name = "SecretCryptoError";
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ };
15
+ // src/base64.ts
16
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
17
+ const BASE64_GROUP_LENGTH = 4;
18
+ /** Decodes canonical base64 only: invalid characters and non-canonical padding return null. */
19
+ function decodeStrictBase64(text) {
20
+ if (!BASE64_PATTERN.test(text)) return null;
21
+ const decoded = Buffer.from(text, "base64");
22
+ return decoded.toString("base64") === text ? decoded : null;
23
+ }
24
+ /** Restores the padding that some secret stores strip. */
25
+ function padBase64(text) {
26
+ if (/={3,}$/.test(text)) return text;
27
+ const unpadded = text.replace(/={1,2}$/, "");
28
+ const missing = (BASE64_GROUP_LENGTH - unpadded.length % BASE64_GROUP_LENGTH) % BASE64_GROUP_LENGTH;
29
+ return unpadded + "=".repeat(missing);
30
+ }
31
+ function assertKey(key) {
32
+ if (!(key instanceof Uint8Array) || key.byteLength !== 32) throw new SecretCryptoError("invalid-key", `Encryption key must be 32 bytes.`);
33
+ }
34
+ /** Validates every key in the set and returns them, primary first. */
35
+ function listKeys(keys) {
36
+ if (typeof keys !== "object" || keys === null) throw new SecretCryptoError("invalid-key", "A key set is required.");
37
+ if (keys.previous !== void 0 && !Array.isArray(keys.previous)) throw new SecretCryptoError("invalid-key", "Previous keys must be an array.");
38
+ const allKeys = [keys.primary, ...keys.previous ?? []];
39
+ allKeys.forEach(assertKey);
40
+ return allKeys;
41
+ }
42
+ function assertKeySet(keys) {
43
+ listKeys(keys);
44
+ }
45
+ /**
46
+ * Decodes a base64 string (for example from a secret store) into a key.
47
+ * Rejects text that is not valid base64 or does not decode to 32 bytes.
48
+ */
49
+ function decodeKey(base64Key) {
50
+ const decodedKey = typeof base64Key === "string" ? decodeStrictBase64(padBase64(base64Key.trim())) : null;
51
+ if (decodedKey === null) throw new SecretCryptoError("invalid-key", "Encryption key is not valid base64.");
52
+ assertKey(decodedKey);
53
+ return new Uint8Array(decodedKey);
54
+ }
55
+ /**
56
+ * A short non-secret identifier stored in each payload so decrypt can pick
57
+ * the right key. A truncated SHA-256 of the key: it cannot be reversed and
58
+ * needs no configuration to keep in sync.
59
+ */
60
+ function deriveKeyId(key) {
61
+ assertKey(key);
62
+ return createHash("sha256").update(key).digest("hex").slice(0, 8);
63
+ }
64
+ const PAYLOAD_SEPARATOR = ":";
65
+ function formatPayload(parts) {
66
+ return [
67
+ "v2",
68
+ parts.keyId,
69
+ parts.iv.toString("base64"),
70
+ parts.authTag.toString("base64"),
71
+ parts.ciphertext.toString("base64")
72
+ ].join(PAYLOAD_SEPARATOR);
73
+ }
74
+ function malformed() {
75
+ return new SecretCryptoError("malformed-payload", "Malformed encrypted payload.");
76
+ }
77
+ const VERSION_PATTERN = /^v\d+$/;
78
+ const KEY_ID_PATTERN = new RegExp(`^[0-9a-f]{8}$`);
79
+ function parsePayload(payload) {
80
+ if (typeof payload !== "string") throw malformed();
81
+ const [version, keyId, ivBase64, authTagBase64, ciphertextBase64, ...rest] = payload.split(PAYLOAD_SEPARATOR);
82
+ if (version === void 0 || !VERSION_PATTERN.test(version)) throw malformed();
83
+ if (version !== "v2") throw new SecretCryptoError("unsupported-version", "Unsupported encrypted payload version.");
84
+ if (rest.length > 0 || ciphertextBase64 === void 0 || !keyId || !KEY_ID_PATTERN.test(keyId)) throw malformed();
85
+ const iv = decodeStrictBase64(ivBase64 ?? "");
86
+ const authTag = decodeStrictBase64(authTagBase64 ?? "");
87
+ const ciphertext = decodeStrictBase64(ciphertextBase64);
88
+ if (!(iv?.byteLength === 12 && authTag?.byteLength === 16 && ciphertext !== null)) throw malformed();
89
+ return {
90
+ keyId,
91
+ iv,
92
+ authTag,
93
+ ciphertext
94
+ };
95
+ }
96
+ // src/cipher.ts
97
+ const CIPHER_ALGORITHM = "aes-256-gcm";
98
+ function assertAssociatedData(associatedData) {
99
+ if (associatedData === void 0) return;
100
+ if (typeof associatedData !== "string") throw new SecretCryptoError("invalid-associated-data", "Associated data must be a string.");
101
+ if (!associatedData.isWellFormed()) throw new SecretCryptoError("invalid-associated-data", "Associated data must be well-formed Unicode.");
102
+ if (associatedData.length === 0) throw new SecretCryptoError("invalid-associated-data", "Associated data was provided but empty. Pass a value or omit it.");
103
+ }
104
+ function assertPlaintext(plaintext) {
105
+ if (typeof plaintext !== "string") throw new SecretCryptoError("invalid-plaintext", "Plaintext must be a string.");
106
+ if (!plaintext.isWellFormed()) throw new SecretCryptoError("invalid-plaintext", "Plaintext must be well-formed Unicode.");
107
+ }
108
+ function applyAssociatedData(cipher, associatedData) {
109
+ if (associatedData === void 0) return;
110
+ cipher.setAAD(Buffer.from(associatedData, "utf8"));
111
+ }
112
+ /**
113
+ * Encrypts `plaintext` under `keys.primary` and returns one opaque string:
114
+ * `v2:<keyId>:<base64 iv>:<base64 authTag>:<base64 ciphertext>`.
115
+ *
116
+ * `associatedData` is authenticated, not encrypted. Pass something that
117
+ * identifies where the value lives (a row id, for example) and the same
118
+ * value must be passed to decrypt, so a ciphertext moved elsewhere fails.
119
+ */
120
+ function encrypt(plaintext, keys, associatedData) {
121
+ assertKeySet(keys);
122
+ assertAssociatedData(associatedData);
123
+ assertPlaintext(plaintext);
124
+ const iv = randomBytes(12);
125
+ const cipher = createCipheriv(CIPHER_ALGORITHM, keys.primary, iv, { authTagLength: 16 });
126
+ applyAssociatedData(cipher, associatedData);
127
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
128
+ return formatPayload({
129
+ keyId: deriveKeyId(keys.primary),
130
+ iv,
131
+ authTag: cipher.getAuthTag(),
132
+ ciphertext
133
+ });
134
+ }
135
+ function findKey(allKeys, keyId) {
136
+ const matchingKey = allKeys.find((key) => deriveKeyId(key) === keyId);
137
+ if (!matchingKey) throw new SecretCryptoError("unknown-key", "No key in the key set matches the payload's key id.");
138
+ return matchingKey;
139
+ }
140
+ function decipherPayload(key, parsed, associatedData) {
141
+ try {
142
+ const decipher = createDecipheriv(CIPHER_ALGORITHM, key, parsed.iv, { authTagLength: 16 });
143
+ decipher.setAuthTag(parsed.authTag);
144
+ applyAssociatedData(decipher, associatedData);
145
+ return Buffer.concat([decipher.update(parsed.ciphertext), decipher.final()]).toString("utf8");
146
+ } catch {
147
+ throw new SecretCryptoError("decryption-failed", "Failed to decrypt: wrong key, wrong associated data, or tampered payload.");
148
+ }
149
+ }
150
+ /**
151
+ * Reverses `encrypt`. The payload names its key, so any key in the set
152
+ * (primary or previous) can decrypt it. Throws `SecretCryptoError` for a
153
+ * malformed payload, an unknown key, mismatched associated data, or
154
+ * tampering.
155
+ */
156
+ function decrypt(payload, keys, associatedData) {
157
+ const allKeys = listKeys(keys);
158
+ assertAssociatedData(associatedData);
159
+ const parsed = parsePayload(payload);
160
+ return decipherPayload(findKey(allKeys, parsed.keyId), parsed, associatedData);
161
+ }
162
+ /** True when the payload was written with the primary key and needs no re-encrypting. */
163
+ function isEncryptedWithPrimaryKey(payload, keys) {
164
+ assertKeySet(keys);
165
+ return parsePayload(payload).keyId === deriveKeyId(keys.primary);
166
+ }
167
+ /**
168
+ * Re-encrypts a payload under the primary key, for rotation. A payload that
169
+ * already uses the primary key is returned unchanged. The associated data
170
+ * must match the original and is reused for the new payload. A payload
171
+ * already on the primary key is not decrypted, so its associated data is not
172
+ * checked.
173
+ */
174
+ function reencrypt(payload, keys, associatedData) {
175
+ assertAssociatedData(associatedData);
176
+ if (isEncryptedWithPrimaryKey(payload, keys)) return payload;
177
+ return encrypt(decrypt(payload, keys, associatedData), keys, associatedData);
178
+ }
179
+ export { SecretCryptoError, decodeKey, decrypt, deriveKeyId, encrypt, isEncryptedWithPrimaryKey, reencrypt };
package/package.json CHANGED
@@ -1 +1,32 @@
1
- {"name":"@neon-pixels/crypto","version":"0.0.0","description":"Placeholder. The first real release follows.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/neonpixels-studio/packages.git"}}
1
+ {
2
+ "name": "@neon-pixels/crypto",
3
+ "version": "0.3.0",
4
+ "description": "Encrypt stored secrets with AES-256-GCM, versioned payloads, and key rotation.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/crypto"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "tsdown",
30
+ "typecheck": "tsc --noEmit -p tsconfig.json"
31
+ }
32
+ }