@decryption/cosmology-compat 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
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,93 @@
1
+ # @decryption/cosmology-compat
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/decryption/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/decryption/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@decryption/cosmology-compat"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/decryption?filename=packages%2Fcosmology-compat%2Fpackage.json"/></a>
12
+ </p>
13
+
14
+
15
+ > **Deprecated by design.** This package exists so data written by the cosmology CLI
16
+ > stays readable. Do not use it to encrypt anything new — use
17
+ > [`@decryption/core`](../core) instead.
18
+
19
+ ## Why it is weak
20
+
21
+ The old scheme was `CryptoJS.AES.encrypt(text, SHA256(salt).toString())`, which means:
22
+
23
+ - keys derived with OpenSSL `EVP_BytesToKey` — **MD5, a single iteration**, no work factor;
24
+ - AES-256-CBC with **no authentication tag**, so tampering is undetectable;
25
+ - a wrong passphrase yields an empty string in CryptoJS rather than an error.
26
+
27
+ This package reimplements the format byte-for-byte on top of `@decryption/ciphers` (no `crypto-js`
28
+ dependency), and turns the silent-failure case into a thrown `WrongPassphraseError`.
29
+
30
+ ## Usage
31
+
32
+ ```typescript
33
+ import { decrypt, decryptWithEncryptedSalt, upgradeEnvelopeToString } from '@decryption/cosmology-compat';
34
+
35
+ // Single-layer blobs
36
+ const plaintext = decrypt(salt, oldCiphertext);
37
+
38
+ // The demo's two-layer scheme (encrypted salt wrapping the real salt)
39
+ const mnemonic = decryptWithEncryptedSalt(salt, encryptedSalt, encryptedWallet);
40
+
41
+ // One-way door onto the modern format
42
+ const modern = upgradeEnvelopeToString(oldCiphertext, salt, newPassphrase);
43
+ ```
44
+
45
+ Raw CryptoJS compatibility, if you have blobs that never went through `@cosmology/core`:
46
+
47
+ ```typescript
48
+ import { cryptoJsEncrypt, cryptoJsDecrypt } from '@decryption/cosmology-compat';
49
+
50
+ cryptoJsDecrypt(base64Ciphertext, passphrase); // throws instead of returning ''
51
+ ```
52
+
53
+ ## Verified compatibility
54
+
55
+ The test suite encrypts with the real `crypto-js` package and decrypts with this one (and vice
56
+ versa), so the byte compatibility claim is checked on every run rather than assumed.
57
+
58
+ ---
59
+
60
+ ## Development
61
+
62
+ ### Setup
63
+
64
+ 1. Clone the repository:
65
+
66
+ ```bash
67
+ git clone https://github.com/constructive-io/decryption.git
68
+ ```
69
+
70
+ 2. Install dependencies:
71
+
72
+ ```bash
73
+ cd decryption
74
+ pnpm install
75
+ pnpm build
76
+ ```
77
+
78
+ 3. Test the package of interest:
79
+
80
+ ```bash
81
+ cd packages/<packagename>
82
+ pnpm test:watch
83
+ ```
84
+
85
+ ## Credits
86
+
87
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
88
+
89
+ ## Disclaimer
90
+
91
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
92
+
93
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/cosmology.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The `@cosmology/core` crypt/decrypt pair, reimplemented byte-for-byte.
3
+ *
4
+ * The original hashed the caller's salt with SHA-256 and used the *hex string* of that digest as
5
+ * the CryptoJS passphrase. Reproduced exactly so old blobs remain readable.
6
+ *
7
+ * @deprecated Use `@decryption/core` for anything new.
8
+ */
9
+ /** SHA-256 of the salt, hex-encoded — the passphrase actually handed to CryptoJS. */
10
+ export declare const legacyPassphrase: (salt: string) => string;
11
+ /** Legacy `crypt(salt, text)` from `@cosmology/core`. */
12
+ export declare const crypt: (salt: string, text: string) => string;
13
+ /** Legacy `decrypt(salt, encoded)` from `@cosmology/core`. */
14
+ export declare const decrypt: (salt: string, encoded: string) => string;
15
+ /**
16
+ * Two-layer scheme used by the old encryption demo and CLI: a random "real" salt is encrypted
17
+ * under the user's salt, and the secret is encrypted under the real salt. Decrypting therefore
18
+ * requires unwrapping twice.
19
+ */
20
+ export declare const decryptWithEncryptedSalt: (salt: string, encryptedSalt: string, encoded: string) => string;
21
+ /** Encrypting counterpart of {@link decryptWithEncryptedSalt}. */
22
+ export declare const encryptWithEncryptedSalt: (salt: string, encryptedSalt: string, text: string) => string;
23
+ /** Legacy `utf8ToHex` helper, preserved for byte-compatibility with old Shamir shares. */
24
+ export declare const utf8ToHex: (str: string) => string;
25
+ /** Legacy `hexToUtf8` helper. */
26
+ export declare const hexToUtf8: (hex: string) => string;
27
+ /** Legacy `utf8ArrayToString` helper — despite the name, it base64-encodes bytes. */
28
+ export declare const utf8ArrayToString: (arr: Uint8Array | number[]) => string;
29
+ /** Legacy `stringToUtf8Array` helper — decodes base64 back into bytes. */
30
+ export declare const stringToUtf8Array: (str: string) => Uint8Array;
package/cosmology.js ADDED
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stringToUtf8Array = exports.utf8ArrayToString = exports.hexToUtf8 = exports.utf8ToHex = exports.encryptWithEncryptedSalt = exports.decryptWithEncryptedSalt = exports.decrypt = exports.crypt = exports.legacyPassphrase = void 0;
4
+ const sha2_1 = require("@decryption/hashes/sha2");
5
+ const utils_1 = require("@decryption/hashes/utils");
6
+ const cryptojs_1 = require("./cryptojs");
7
+ /**
8
+ * The `@cosmology/core` crypt/decrypt pair, reimplemented byte-for-byte.
9
+ *
10
+ * The original hashed the caller's salt with SHA-256 and used the *hex string* of that digest as
11
+ * the CryptoJS passphrase. Reproduced exactly so old blobs remain readable.
12
+ *
13
+ * @deprecated Use `@decryption/core` for anything new.
14
+ */
15
+ /** SHA-256 of the salt, hex-encoded — the passphrase actually handed to CryptoJS. */
16
+ const legacyPassphrase = (salt) => (0, utils_1.bytesToHex)((0, sha2_1.sha256)((0, utils_1.utf8ToBytes)(salt)));
17
+ exports.legacyPassphrase = legacyPassphrase;
18
+ /** Legacy `crypt(salt, text)` from `@cosmology/core`. */
19
+ const crypt = (salt, text) => (0, cryptojs_1.cryptoJsEncrypt)(text, (0, exports.legacyPassphrase)(salt));
20
+ exports.crypt = crypt;
21
+ /** Legacy `decrypt(salt, encoded)` from `@cosmology/core`. */
22
+ const decrypt = (salt, encoded) => (0, cryptojs_1.cryptoJsDecrypt)(encoded, (0, exports.legacyPassphrase)(salt));
23
+ exports.decrypt = decrypt;
24
+ /**
25
+ * Two-layer scheme used by the old encryption demo and CLI: a random "real" salt is encrypted
26
+ * under the user's salt, and the secret is encrypted under the real salt. Decrypting therefore
27
+ * requires unwrapping twice.
28
+ */
29
+ const decryptWithEncryptedSalt = (salt, encryptedSalt, encoded) => (0, exports.decrypt)((0, exports.decrypt)(salt, encryptedSalt), encoded);
30
+ exports.decryptWithEncryptedSalt = decryptWithEncryptedSalt;
31
+ /** Encrypting counterpart of {@link decryptWithEncryptedSalt}. */
32
+ const encryptWithEncryptedSalt = (salt, encryptedSalt, text) => (0, exports.crypt)((0, exports.decrypt)(salt, encryptedSalt), text);
33
+ exports.encryptWithEncryptedSalt = encryptWithEncryptedSalt;
34
+ /** Legacy `utf8ToHex` helper, preserved for byte-compatibility with old Shamir shares. */
35
+ const utf8ToHex = (str) => Array.from(str)
36
+ .map((c) => c.charCodeAt(0) < 128
37
+ ? c.charCodeAt(0).toString(16)
38
+ : encodeURIComponent(c).replace(/%/g, '').toLowerCase())
39
+ .join('');
40
+ exports.utf8ToHex = utf8ToHex;
41
+ /** Legacy `hexToUtf8` helper. */
42
+ const hexToUtf8 = (hex) => {
43
+ const pairs = hex.match(/.{1,2}/g);
44
+ if (!pairs)
45
+ return '';
46
+ return decodeURIComponent('%' + pairs.join('%'));
47
+ };
48
+ exports.hexToUtf8 = hexToUtf8;
49
+ /** Legacy `utf8ArrayToString` helper — despite the name, it base64-encodes bytes. */
50
+ const utf8ArrayToString = (arr) => Buffer.from(arr).toString('base64');
51
+ exports.utf8ArrayToString = utf8ArrayToString;
52
+ /** Legacy `stringToUtf8Array` helper — decodes base64 back into bytes. */
53
+ const stringToUtf8Array = (str) => new Uint8Array(Buffer.from(str, 'base64'));
54
+ exports.stringToUtf8Array = stringToUtf8Array;
package/cryptojs.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Byte-compatible reimplementation of `CryptoJS.AES.encrypt(message, passphraseString)`.
3
+ *
4
+ * **Deprecated by design.** This scheme is only here so data written by the old encryption demo
5
+ * and `@cosmology/core` stays readable. It is weak: the key is derived with OpenSSL's
6
+ * `EVP_BytesToKey` (MD5, a single iteration) and AES-CBC provides no authentication, so a wrong
7
+ * passphrase is only detectable by heuristics. Re-encrypt anything you open with
8
+ * `@decryption/core` — see {@link upgradeEnvelope}.
9
+ */
10
+ /** OpenSSL's `Salted__` magic prefix, emitted by CryptoJS for passphrase-based encryption. */
11
+ export declare const OPENSSL_MAGIC: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>;
12
+ /**
13
+ * OpenSSL `EVP_BytesToKey` with MD5 and one iteration — what CryptoJS uses to turn a passphrase
14
+ * string into an AES-256 key and IV.
15
+ */
16
+ export declare const evpBytesToKey: (passphrase: Uint8Array, salt: Uint8Array) => {
17
+ key: Uint8Array;
18
+ iv: Uint8Array;
19
+ };
20
+ /** Encrypts exactly like `CryptoJS.AES.encrypt(...).toString()` — base64 of `Salted__|salt|ct`. */
21
+ export declare const cryptoJsEncrypt: (message: string, passphrase: string, salt?: Uint8Array) => string;
22
+ /**
23
+ * Decrypts a `CryptoJS.AES` passphrase ciphertext. Unlike CryptoJS — which returns an empty
24
+ * string when the passphrase is wrong — this throws {@link WrongPassphraseError}.
25
+ */
26
+ export declare const cryptoJsDecrypt: (ciphertext: string, passphrase: string) => string;
package/cryptojs.js ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cryptoJsDecrypt = exports.cryptoJsEncrypt = exports.evpBytesToKey = exports.OPENSSL_MAGIC = void 0;
4
+ const base_1 = require("@decryption/base");
5
+ const aes_1 = require("@decryption/ciphers/aes");
6
+ const core_1 = require("@decryption/core");
7
+ const legacy_1 = require("@decryption/hashes/legacy");
8
+ const utils_1 = require("@decryption/hashes/utils");
9
+ /**
10
+ * Byte-compatible reimplementation of `CryptoJS.AES.encrypt(message, passphraseString)`.
11
+ *
12
+ * **Deprecated by design.** This scheme is only here so data written by the old encryption demo
13
+ * and `@cosmology/core` stays readable. It is weak: the key is derived with OpenSSL's
14
+ * `EVP_BytesToKey` (MD5, a single iteration) and AES-CBC provides no authentication, so a wrong
15
+ * passphrase is only detectable by heuristics. Re-encrypt anything you open with
16
+ * `@decryption/core` — see {@link upgradeEnvelope}.
17
+ */
18
+ /** OpenSSL's `Salted__` magic prefix, emitted by CryptoJS for passphrase-based encryption. */
19
+ exports.OPENSSL_MAGIC = (0, utils_1.utf8ToBytes)('Salted__');
20
+ const SALT_LENGTH = 8;
21
+ const KEY_LENGTH = 32;
22
+ const IV_LENGTH = 16;
23
+ /**
24
+ * OpenSSL `EVP_BytesToKey` with MD5 and one iteration — what CryptoJS uses to turn a passphrase
25
+ * string into an AES-256 key and IV.
26
+ */
27
+ const evpBytesToKey = (passphrase, salt) => {
28
+ const target = KEY_LENGTH + IV_LENGTH;
29
+ let derived = new Uint8Array(0);
30
+ let block = new Uint8Array(0);
31
+ while (derived.length < target) {
32
+ block = (0, legacy_1.md5)((0, utils_1.concatBytes)(block, passphrase, salt));
33
+ derived = (0, utils_1.concatBytes)(derived, block);
34
+ }
35
+ return { key: derived.slice(0, KEY_LENGTH), iv: derived.slice(KEY_LENGTH, target) };
36
+ };
37
+ exports.evpBytesToKey = evpBytesToKey;
38
+ /** Encrypts exactly like `CryptoJS.AES.encrypt(...).toString()` — base64 of `Salted__|salt|ct`. */
39
+ const cryptoJsEncrypt = (message, passphrase, salt = randomSalt()) => {
40
+ if (salt.length !== SALT_LENGTH) {
41
+ throw new Error(`openssl salt must be ${SALT_LENGTH} bytes, got ${salt.length}`);
42
+ }
43
+ const { key, iv } = (0, exports.evpBytesToKey)((0, utils_1.utf8ToBytes)(passphrase), salt);
44
+ const ciphertext = (0, aes_1.cbc)(key, iv).encrypt((0, utils_1.utf8ToBytes)(message));
45
+ return base_1.base64.encode((0, utils_1.concatBytes)(exports.OPENSSL_MAGIC, salt, ciphertext));
46
+ };
47
+ exports.cryptoJsEncrypt = cryptoJsEncrypt;
48
+ /**
49
+ * Decrypts a `CryptoJS.AES` passphrase ciphertext. Unlike CryptoJS — which returns an empty
50
+ * string when the passphrase is wrong — this throws {@link WrongPassphraseError}.
51
+ */
52
+ const cryptoJsDecrypt = (ciphertext, passphrase) => {
53
+ let payload;
54
+ try {
55
+ payload = base_1.base64.decode(ciphertext.trim());
56
+ }
57
+ catch {
58
+ throw new core_1.WrongPassphraseError('legacy ciphertext is not valid base64');
59
+ }
60
+ if (payload.length <= exports.OPENSSL_MAGIC.length + SALT_LENGTH) {
61
+ throw new core_1.WrongPassphraseError('legacy ciphertext is truncated');
62
+ }
63
+ for (let i = 0; i < exports.OPENSSL_MAGIC.length; i++) {
64
+ if (payload[i] !== exports.OPENSSL_MAGIC[i]) {
65
+ throw new core_1.WrongPassphraseError('legacy ciphertext is missing the OpenSSL "Salted__" prefix');
66
+ }
67
+ }
68
+ const salt = payload.slice(exports.OPENSSL_MAGIC.length, exports.OPENSSL_MAGIC.length + SALT_LENGTH);
69
+ const body = payload.slice(exports.OPENSSL_MAGIC.length + SALT_LENGTH);
70
+ const { key, iv } = (0, exports.evpBytesToKey)((0, utils_1.utf8ToBytes)(passphrase), salt);
71
+ let plaintext;
72
+ try {
73
+ plaintext = (0, aes_1.cbc)(key, iv).decrypt(body);
74
+ }
75
+ catch {
76
+ // A bad passphrase usually produces invalid PKCS#7 padding.
77
+ throw new core_1.WrongPassphraseError('you probably have the wrong salt or passphrase');
78
+ }
79
+ try {
80
+ return new TextDecoder('utf-8', { fatal: true }).decode(plaintext);
81
+ }
82
+ catch {
83
+ throw new core_1.WrongPassphraseError('decrypted bytes are not valid UTF-8; wrong passphrase');
84
+ }
85
+ };
86
+ exports.cryptoJsDecrypt = cryptoJsDecrypt;
87
+ const randomSalt = () => {
88
+ const salt = new Uint8Array(SALT_LENGTH);
89
+ crypto.getRandomValues(salt);
90
+ return salt;
91
+ };
@@ -0,0 +1,42 @@
1
+ import { sha256 } from '@decryption/hashes/sha2';
2
+ import { bytesToHex, utf8ToBytes } from '@decryption/hashes/utils';
3
+ import { cryptoJsDecrypt, cryptoJsEncrypt } from './cryptojs';
4
+ /**
5
+ * The `@cosmology/core` crypt/decrypt pair, reimplemented byte-for-byte.
6
+ *
7
+ * The original hashed the caller's salt with SHA-256 and used the *hex string* of that digest as
8
+ * the CryptoJS passphrase. Reproduced exactly so old blobs remain readable.
9
+ *
10
+ * @deprecated Use `@decryption/core` for anything new.
11
+ */
12
+ /** SHA-256 of the salt, hex-encoded — the passphrase actually handed to CryptoJS. */
13
+ export const legacyPassphrase = (salt) => bytesToHex(sha256(utf8ToBytes(salt)));
14
+ /** Legacy `crypt(salt, text)` from `@cosmology/core`. */
15
+ export const crypt = (salt, text) => cryptoJsEncrypt(text, legacyPassphrase(salt));
16
+ /** Legacy `decrypt(salt, encoded)` from `@cosmology/core`. */
17
+ export const decrypt = (salt, encoded) => cryptoJsDecrypt(encoded, legacyPassphrase(salt));
18
+ /**
19
+ * Two-layer scheme used by the old encryption demo and CLI: a random "real" salt is encrypted
20
+ * under the user's salt, and the secret is encrypted under the real salt. Decrypting therefore
21
+ * requires unwrapping twice.
22
+ */
23
+ export const decryptWithEncryptedSalt = (salt, encryptedSalt, encoded) => decrypt(decrypt(salt, encryptedSalt), encoded);
24
+ /** Encrypting counterpart of {@link decryptWithEncryptedSalt}. */
25
+ export const encryptWithEncryptedSalt = (salt, encryptedSalt, text) => crypt(decrypt(salt, encryptedSalt), text);
26
+ /** Legacy `utf8ToHex` helper, preserved for byte-compatibility with old Shamir shares. */
27
+ export const utf8ToHex = (str) => Array.from(str)
28
+ .map((c) => c.charCodeAt(0) < 128
29
+ ? c.charCodeAt(0).toString(16)
30
+ : encodeURIComponent(c).replace(/%/g, '').toLowerCase())
31
+ .join('');
32
+ /** Legacy `hexToUtf8` helper. */
33
+ export const hexToUtf8 = (hex) => {
34
+ const pairs = hex.match(/.{1,2}/g);
35
+ if (!pairs)
36
+ return '';
37
+ return decodeURIComponent('%' + pairs.join('%'));
38
+ };
39
+ /** Legacy `utf8ArrayToString` helper — despite the name, it base64-encodes bytes. */
40
+ export const utf8ArrayToString = (arr) => Buffer.from(arr).toString('base64');
41
+ /** Legacy `stringToUtf8Array` helper — decodes base64 back into bytes. */
42
+ export const stringToUtf8Array = (str) => new Uint8Array(Buffer.from(str, 'base64'));
@@ -0,0 +1,85 @@
1
+ import { base64 } from '@decryption/base';
2
+ import { cbc } from '@decryption/ciphers/aes';
3
+ import { WrongPassphraseError } from '@decryption/core';
4
+ import { md5 } from '@decryption/hashes/legacy';
5
+ import { concatBytes, utf8ToBytes } from '@decryption/hashes/utils';
6
+ /**
7
+ * Byte-compatible reimplementation of `CryptoJS.AES.encrypt(message, passphraseString)`.
8
+ *
9
+ * **Deprecated by design.** This scheme is only here so data written by the old encryption demo
10
+ * and `@cosmology/core` stays readable. It is weak: the key is derived with OpenSSL's
11
+ * `EVP_BytesToKey` (MD5, a single iteration) and AES-CBC provides no authentication, so a wrong
12
+ * passphrase is only detectable by heuristics. Re-encrypt anything you open with
13
+ * `@decryption/core` — see {@link upgradeEnvelope}.
14
+ */
15
+ /** OpenSSL's `Salted__` magic prefix, emitted by CryptoJS for passphrase-based encryption. */
16
+ export const OPENSSL_MAGIC = utf8ToBytes('Salted__');
17
+ const SALT_LENGTH = 8;
18
+ const KEY_LENGTH = 32;
19
+ const IV_LENGTH = 16;
20
+ /**
21
+ * OpenSSL `EVP_BytesToKey` with MD5 and one iteration — what CryptoJS uses to turn a passphrase
22
+ * string into an AES-256 key and IV.
23
+ */
24
+ export const evpBytesToKey = (passphrase, salt) => {
25
+ const target = KEY_LENGTH + IV_LENGTH;
26
+ let derived = new Uint8Array(0);
27
+ let block = new Uint8Array(0);
28
+ while (derived.length < target) {
29
+ block = md5(concatBytes(block, passphrase, salt));
30
+ derived = concatBytes(derived, block);
31
+ }
32
+ return { key: derived.slice(0, KEY_LENGTH), iv: derived.slice(KEY_LENGTH, target) };
33
+ };
34
+ /** Encrypts exactly like `CryptoJS.AES.encrypt(...).toString()` — base64 of `Salted__|salt|ct`. */
35
+ export const cryptoJsEncrypt = (message, passphrase, salt = randomSalt()) => {
36
+ if (salt.length !== SALT_LENGTH) {
37
+ throw new Error(`openssl salt must be ${SALT_LENGTH} bytes, got ${salt.length}`);
38
+ }
39
+ const { key, iv } = evpBytesToKey(utf8ToBytes(passphrase), salt);
40
+ const ciphertext = cbc(key, iv).encrypt(utf8ToBytes(message));
41
+ return base64.encode(concatBytes(OPENSSL_MAGIC, salt, ciphertext));
42
+ };
43
+ /**
44
+ * Decrypts a `CryptoJS.AES` passphrase ciphertext. Unlike CryptoJS — which returns an empty
45
+ * string when the passphrase is wrong — this throws {@link WrongPassphraseError}.
46
+ */
47
+ export const cryptoJsDecrypt = (ciphertext, passphrase) => {
48
+ let payload;
49
+ try {
50
+ payload = base64.decode(ciphertext.trim());
51
+ }
52
+ catch {
53
+ throw new WrongPassphraseError('legacy ciphertext is not valid base64');
54
+ }
55
+ if (payload.length <= OPENSSL_MAGIC.length + SALT_LENGTH) {
56
+ throw new WrongPassphraseError('legacy ciphertext is truncated');
57
+ }
58
+ for (let i = 0; i < OPENSSL_MAGIC.length; i++) {
59
+ if (payload[i] !== OPENSSL_MAGIC[i]) {
60
+ throw new WrongPassphraseError('legacy ciphertext is missing the OpenSSL "Salted__" prefix');
61
+ }
62
+ }
63
+ const salt = payload.slice(OPENSSL_MAGIC.length, OPENSSL_MAGIC.length + SALT_LENGTH);
64
+ const body = payload.slice(OPENSSL_MAGIC.length + SALT_LENGTH);
65
+ const { key, iv } = evpBytesToKey(utf8ToBytes(passphrase), salt);
66
+ let plaintext;
67
+ try {
68
+ plaintext = cbc(key, iv).decrypt(body);
69
+ }
70
+ catch {
71
+ // A bad passphrase usually produces invalid PKCS#7 padding.
72
+ throw new WrongPassphraseError('you probably have the wrong salt or passphrase');
73
+ }
74
+ try {
75
+ return new TextDecoder('utf-8', { fatal: true }).decode(plaintext);
76
+ }
77
+ catch {
78
+ throw new WrongPassphraseError('decrypted bytes are not valid UTF-8; wrong passphrase');
79
+ }
80
+ };
81
+ const randomSalt = () => {
82
+ const salt = new Uint8Array(SALT_LENGTH);
83
+ crypto.getRandomValues(salt);
84
+ return salt;
85
+ };
package/esm/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './cosmology';
2
+ export * from './cryptojs';
3
+ export * from './upgrade';
package/esm/upgrade.js ADDED
@@ -0,0 +1,11 @@
1
+ import { armor, encrypt } from '@decryption/core';
2
+ import { decrypt, decryptWithEncryptedSalt } from './cosmology';
3
+ /**
4
+ * Reads a legacy `@cosmology/core` blob and re-encrypts it as a modern, authenticated
5
+ * `@decryption/core` envelope. This is the one-way door out of the CryptoJS scheme.
6
+ */
7
+ export const upgradeEnvelope = (legacyCiphertext, legacySalt, passphrase, options) => encrypt(decrypt(legacySalt, legacyCiphertext), passphrase, options);
8
+ /** {@link upgradeEnvelope} for the two-layer (salt + encrypted salt) variant. */
9
+ export const upgradeTwoLayerEnvelope = (legacyCiphertext, legacySalt, legacyEncryptedSalt, passphrase, options) => encrypt(decryptWithEncryptedSalt(legacySalt, legacyEncryptedSalt, legacyCiphertext), passphrase, options);
10
+ /** {@link upgradeEnvelope}, returning the armored text form. */
11
+ export const upgradeEnvelopeToString = (legacyCiphertext, legacySalt, passphrase, options) => armor(upgradeEnvelope(legacyCiphertext, legacySalt, passphrase, options));
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './cosmology';
2
+ export * from './cryptojs';
3
+ export * from './upgrade';
package/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./cosmology"), exports);
18
+ __exportStar(require("./cryptojs"), exports);
19
+ __exportStar(require("./upgrade"), exports);
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@decryption/cosmology-compat",
3
+ "version": "0.4.0",
4
+ "description": "Read data written by the cosmology CLI encryption scheme, and upgrade it",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/decryption",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/decryption"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/decryption/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "keywords": [
32
+ "cryptojs",
33
+ "cosmology",
34
+ "compat",
35
+ "aes",
36
+ "migration"
37
+ ],
38
+ "dependencies": {
39
+ "@decryption/base": "0.4.0",
40
+ "@decryption/ciphers": "0.4.0",
41
+ "@decryption/core": "0.4.0",
42
+ "@decryption/hashes": "0.4.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/crypto-js": "^4.2.2",
46
+ "crypto-js": "^4.2.0",
47
+ "makage": "0.3.0"
48
+ },
49
+ "gitHead": "49eff05f5fa934d2d045372f0ddb4626190822dd"
50
+ }
package/upgrade.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { EncryptOptions } from '@decryption/core';
2
+ /**
3
+ * Reads a legacy `@cosmology/core` blob and re-encrypts it as a modern, authenticated
4
+ * `@decryption/core` envelope. This is the one-way door out of the CryptoJS scheme.
5
+ */
6
+ export declare const upgradeEnvelope: (legacyCiphertext: string, legacySalt: string, passphrase: string, options?: EncryptOptions) => Uint8Array;
7
+ /** {@link upgradeEnvelope} for the two-layer (salt + encrypted salt) variant. */
8
+ export declare const upgradeTwoLayerEnvelope: (legacyCiphertext: string, legacySalt: string, legacyEncryptedSalt: string, passphrase: string, options?: EncryptOptions) => Uint8Array;
9
+ /** {@link upgradeEnvelope}, returning the armored text form. */
10
+ export declare const upgradeEnvelopeToString: (legacyCiphertext: string, legacySalt: string, passphrase: string, options?: EncryptOptions) => string;
package/upgrade.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.upgradeEnvelopeToString = exports.upgradeTwoLayerEnvelope = exports.upgradeEnvelope = void 0;
4
+ const core_1 = require("@decryption/core");
5
+ const cosmology_1 = require("./cosmology");
6
+ /**
7
+ * Reads a legacy `@cosmology/core` blob and re-encrypts it as a modern, authenticated
8
+ * `@decryption/core` envelope. This is the one-way door out of the CryptoJS scheme.
9
+ */
10
+ const upgradeEnvelope = (legacyCiphertext, legacySalt, passphrase, options) => (0, core_1.encrypt)((0, cosmology_1.decrypt)(legacySalt, legacyCiphertext), passphrase, options);
11
+ exports.upgradeEnvelope = upgradeEnvelope;
12
+ /** {@link upgradeEnvelope} for the two-layer (salt + encrypted salt) variant. */
13
+ const upgradeTwoLayerEnvelope = (legacyCiphertext, legacySalt, legacyEncryptedSalt, passphrase, options) => (0, core_1.encrypt)((0, cosmology_1.decryptWithEncryptedSalt)(legacySalt, legacyEncryptedSalt, legacyCiphertext), passphrase, options);
14
+ exports.upgradeTwoLayerEnvelope = upgradeTwoLayerEnvelope;
15
+ /** {@link upgradeEnvelope}, returning the armored text form. */
16
+ const upgradeEnvelopeToString = (legacyCiphertext, legacySalt, passphrase, options) => (0, core_1.armor)((0, exports.upgradeEnvelope)(legacyCiphertext, legacySalt, passphrase, options));
17
+ exports.upgradeEnvelopeToString = upgradeEnvelopeToString;