@decryption/core 0.2.0 → 0.5.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/README.md CHANGED
@@ -1,9 +1,31 @@
1
1
  # @decryption/core
2
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/core"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/decryption?filename=packages%2Fcore%2Fpackage.json"/></a>
12
+ </p>
13
+
14
+
3
15
  <p align="center">
4
- Authenticated, self-describing envelope encryption — Argon2id + XChaCha20-Poly1305.
16
+ Authenticated, self-describing envelope encryption — Argon2id + XChaCha20-Poly1305, with a
17
+ chunked file format for payloads of any size.
5
18
  </p>
6
19
 
20
+ Two formats share the `DCRYPT` magic and a version byte:
21
+
22
+ | Version | For | Shape |
23
+ |---------|-----|-------|
24
+ | 1 | short secrets: a value, a mnemonic, a key | one AEAD over the whole payload, held in memory |
25
+ | 2 | files of any size, one or many ways to unlock | header + 64 KiB authenticated chunks, streamable |
26
+
27
+ Runs anywhere `Uint8Array` does: this package has no Node.js dependency.
28
+
7
29
  ## Installation
8
30
 
9
31
  ```bash
@@ -38,7 +60,50 @@ decrypt(value, passphrase, { aad: 'DATABASE_URL' }); // ok
38
60
  decrypt(value, passphrase, { aad: 'STRIPE_KEY' }); // throws WrongPassphraseError
39
61
  ```
40
62
 
41
- ## Envelope format
63
+ ## Files of any size
64
+
65
+ ```typescript
66
+ import { encryptFile, decryptFile } from '@decryption/core';
67
+
68
+ const file = encryptFile(bytes, passphrase); // Uint8Array, version 2
69
+ const back = decryptFile(file, passphrase);
70
+ ```
71
+
72
+ When the payload does not fit in memory, drive the cipher yourself. It is a plain
73
+ `update()` / `finish()` object, so it fits any stream API:
74
+
75
+ ```typescript
76
+ import {
77
+ createFileEncryptor,
78
+ createFileDecryptor,
79
+ generateFileKey,
80
+ tryParseFileHeader,
81
+ unwrapWithPassphrase,
82
+ wrapWithPassphrase,
83
+ } from '@decryption/core';
84
+
85
+ const fileKey = generateFileKey();
86
+ const { header, stream } = createFileEncryptor(fileKey, [wrapWithPassphrase(fileKey, passphrase)]);
87
+
88
+ write(header);
89
+ for await (const piece of source) write(stream.update(piece));
90
+ write(stream.finish());
91
+
92
+ // reading: the header first (undefined until enough bytes have arrived), then the chunks
93
+ const parsed = tryParseFileHeader(prefix);
94
+ const decryptor = createFileDecryptor(parsed, unwrapWithPassphrase(parsed, passphrase));
95
+ emit(decryptor.update(prefix.subarray(parsed.length)));
96
+ for await (const piece of rest) emit(decryptor.update(piece));
97
+ emit(decryptor.finish()); // throws if the file was truncated
98
+ ```
99
+
100
+ Plaintext returned by `update()` is authenticated chunk by chunk, but the file is only known to be
101
+ complete once `finish()` returns. Treat streamed output as provisional until then — write it to a
102
+ temporary file and rename it afterwards, as the `dcrypt` CLI does.
103
+
104
+ For recipients instead of a passphrase, see [`@decryption/keys`](../keys).
105
+
106
+ ## Envelope format (version 1)
42
107
 
43
108
  ```text
44
109
  | magic | ver | suite | t | m | p | salt | nonce | ciphertext || tag |
@@ -51,6 +116,50 @@ decrypt(value, passphrase, { aad: 'STRIPE_KEY' }); // throws WrongPassphraseEr
51
116
  - Salt and nonce are drawn from the platform CSPRNG for every encryption.
52
117
  - Suite and version bytes make future algorithm changes additive rather than breaking.
53
118
 
119
+ ## File format (version 2)
120
+
121
+ ```text
122
+ | magic | ver | suite | count | stanza … stanza | header MAC | nonce | chunk … chunk |
123
+ | DCRYPT | 2 | 2 | u16 | | 32 B | 16 B | |
124
+ |<------------- authenticated by the MAC ------->|
125
+
126
+ stanza: | type u8 | length u16 | body |
127
+ chunk: ChaCha20-Poly1305( ≤ 64 KiB of plaintext ) — ciphertext || 16-byte tag
128
+ ```
129
+
130
+ The design is the [age file format](https://age-encryption.org/v1) with binary fields in place of
131
+ text lines. It is deliberately not a new construction:
132
+
133
+ - A random 32-byte **file key** encrypts the payload. Each **stanza** holds one wrapped copy of it:
134
+ type `1` under a passphrase (Argon2id parameters, salt, then the key sealed with
135
+ XChaCha20-Poly1305), type `2` for an X25519 recipient ([`@decryption/keys`](../keys)). A
136
+ passphrase stanza must be the only stanza, as with age's scrypt recipient.
137
+ - The **header MAC** is `HMAC-SHA256` under `HKDF-SHA256(file key, info = "header")`. It is checked
138
+ before any payload is decrypted, so stanzas and KDF costs cannot be edited or downgraded.
139
+ - The **payload** is age's STREAM: the key is
140
+ `HKDF-SHA256(file key, salt = nonce, info = "payload")`; each chunk's 12-byte nonce is an 11-byte
141
+ big-endian counter followed by a flag byte, `0x01` on the last chunk and `0x00` otherwise. The last
142
+ chunk may be short, and may be empty only if the whole payload is.
143
+
144
+ Because the counter and the last-chunk flag are part of every nonce, a chunk that is reordered,
145
+ duplicated, dropped or cut off fails authentication. The decryptor here is stricter than a minimal
146
+ reader: it never releases a chunk as non-final unless more ciphertext follows it. The test suite
147
+ decrypts age's own STREAM vectors ([C2SP/CCTV](https://github.com/C2SP/CCTV/tree/main/age)) with this
148
+ code.
149
+
150
+ Unlocking a file a new way means adding a stanza type; the payload never changes. Readers keep
151
+ stanzas they do not recognise, and bound what they will buffer (1024 stanzas of at most 1024 bytes).
152
+
153
+ `armorFile` / `dearmorFile` give the text form, `dcrypt.v2.<base64>`, for small files that have to
154
+ live in text. Version 2 has no associated-data option.
155
+
156
+ ### What is audited
157
+
158
+ The primitives underneath — ChaCha20-Poly1305, XChaCha20-Poly1305, HKDF, HMAC, SHA-256 — come from
159
+ `@noble`, which has been audited upstream. Argon2id is outside that audit's scope, and neither
160
+ envelope format, nor this STREAM implementation, has been audited by a third party. The exact
161
+ boundary is in the [repository README](../../README.md#audit-status).
162
+
54
163
  ## KDF profiles
55
164
 
56
165
  | Profile | Memory | Passes | Use for |
@@ -68,7 +177,7 @@ Every failure mode has a distinct type — decryption never silently returns an
68
177
  | Error | Meaning |
69
178
  |-------|---------|
70
179
  | `WrongPassphraseError` | Passphrase is wrong or the ciphertext was tampered with |
71
- | `CorruptEnvelopeError` | Not a `dcrypt` envelope, or truncated |
180
+ | `CorruptEnvelopeError` | Not a `dcrypt` envelope, truncated, or a file chunk failed authentication |
72
181
  | `UnsupportedEnvelopeError` | Newer format version or unknown algorithm suite |
73
182
  | `InvalidParametersError` | Caller passed arguments that cannot be secure |
74
183
 
package/bytes.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Copies a range into a plain Uint8Array. `Buffer.prototype.slice` returns a view of the caller's
3
+ * memory rather than a copy, so `bytes.slice()` must not be relied on to detach from the input.
4
+ */
5
+ export declare const copyBytes: (bytes: Uint8Array, start?: number, end?: number) => Uint8Array;
package/bytes.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.copyBytes = void 0;
4
+ /**
5
+ * Copies a range into a plain Uint8Array. `Buffer.prototype.slice` returns a view of the caller's
6
+ * memory rather than a copy, so `bytes.slice()` must not be relied on to detach from the input.
7
+ */
8
+ const copyBytes = (bytes, start = 0, end = bytes.length) => Uint8Array.prototype.slice.call(bytes, start, end);
9
+ exports.copyBytes = copyBytes;
package/envelope.d.ts CHANGED
@@ -4,11 +4,15 @@ export declare const MAGIC: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer
4
4
  /** Envelope format version implemented by this package. */
5
5
  export declare const VERSION = 1;
6
6
  /**
7
- * Algorithm suite identifier. Only one suite exists today; the byte is present so that a future
8
- * suite (say, AES-256-GCM for FIPS environments) can be added without a format break.
7
+ * Algorithm suite identifier. The byte is present so that a future suite (say, AES-256-GCM for
8
+ * FIPS environments) can be added without a format break.
9
+ *
10
+ * - `Argon2idXChaCha20Poly1305` is the single-shot version 1 envelope in this file.
11
+ * - `HkdfSha256ChaCha20Poly1305Stream` is the chunked version 2 file format in `file.ts`.
9
12
  */
10
13
  export declare enum Suite {
11
- Argon2idXChaCha20Poly1305 = 1
14
+ Argon2idXChaCha20Poly1305 = 1,
15
+ HkdfSha256ChaCha20Poly1305Stream = 2
12
16
  }
13
17
  export declare const NONCE_LENGTH = 24;
14
18
  export declare const TAG_LENGTH = 16;
@@ -46,6 +50,24 @@ export declare const parseHeader: (envelope: Uint8Array) => EnvelopeHeader;
46
50
  * The header is authenticated, so cost parameters cannot be downgraded by an attacker.
47
51
  */
48
52
  export declare const encrypt: (plaintext: Uint8Array | string, passphrase: string | Uint8Array, options?: EncryptOptions) => Uint8Array;
53
+ /**
54
+ * A passphrase key derivation kept for reuse. Argon2id is deliberately expensive, so a caller
55
+ * that re-encrypts the same data repeatedly (a vault flushing its snapshot) can derive once and
56
+ * pay only the AEAD cost per write. The salt is part of the derivation and is reused with it;
57
+ * confidentiality still rests on the fresh random nonce chosen for every envelope.
58
+ */
59
+ export interface DerivedEnvelopeKey {
60
+ key: Uint8Array;
61
+ salt: Uint8Array;
62
+ kdf: KdfParams;
63
+ }
64
+ /** Runs the KDF once, yielding a handle usable with {@link encryptWithDerivedKey}. */
65
+ export declare const deriveEnvelopeKey: (passphrase: string | Uint8Array, kdf?: KdfProfile | KdfParams) => DerivedEnvelopeKey;
66
+ /**
67
+ * {@link encrypt} with the KDF already done. Produces an identical envelope — the header still
68
+ * records the salt and cost parameters, so {@link decrypt} opens it with the passphrase alone.
69
+ */
70
+ export declare const encryptWithDerivedKey: (plaintext: Uint8Array | string, derived: DerivedEnvelopeKey, options?: Pick<EncryptOptions, "aad">) => Uint8Array;
49
71
  /**
50
72
  * Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
51
73
  * {@link WrongPassphraseError} — this format never returns an empty string on failure.
package/envelope.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.openWithKey = exports.sealWithKey = exports.decrypt = exports.encrypt = exports.parseHeader = exports.HEADER_LENGTH = exports.TAG_LENGTH = exports.NONCE_LENGTH = exports.Suite = exports.VERSION = exports.MAGIC = void 0;
3
+ exports.openWithKey = exports.sealWithKey = exports.decrypt = exports.encryptWithDerivedKey = exports.deriveEnvelopeKey = exports.encrypt = exports.parseHeader = exports.HEADER_LENGTH = exports.TAG_LENGTH = exports.NONCE_LENGTH = exports.Suite = exports.VERSION = exports.MAGIC = void 0;
4
4
  const chacha_1 = require("@decryption/ciphers/chacha");
5
5
  const utils_1 = require("@decryption/hashes/utils");
6
6
  const errors_1 = require("./errors");
@@ -10,12 +10,16 @@ exports.MAGIC = (0, utils_1.utf8ToBytes)('DCRYPT');
10
10
  /** Envelope format version implemented by this package. */
11
11
  exports.VERSION = 1;
12
12
  /**
13
- * Algorithm suite identifier. Only one suite exists today; the byte is present so that a future
14
- * suite (say, AES-256-GCM for FIPS environments) can be added without a format break.
13
+ * Algorithm suite identifier. The byte is present so that a future suite (say, AES-256-GCM for
14
+ * FIPS environments) can be added without a format break.
15
+ *
16
+ * - `Argon2idXChaCha20Poly1305` is the single-shot version 1 envelope in this file.
17
+ * - `HkdfSha256ChaCha20Poly1305Stream` is the chunked version 2 file format in `file.ts`.
15
18
  */
16
19
  var Suite;
17
20
  (function (Suite) {
18
21
  Suite[Suite["Argon2idXChaCha20Poly1305"] = 1] = "Argon2idXChaCha20Poly1305";
22
+ Suite[Suite["HkdfSha256ChaCha20Poly1305Stream"] = 2] = "HkdfSha256ChaCha20Poly1305Stream";
19
23
  })(Suite || (exports.Suite = Suite = {}));
20
24
  exports.NONCE_LENGTH = 24;
21
25
  exports.TAG_LENGTH = 16;
@@ -97,6 +101,31 @@ const encrypt = (plaintext, passphrase, options = {}) => {
97
101
  }
98
102
  };
99
103
  exports.encrypt = encrypt;
104
+ /** Runs the KDF once, yielding a handle usable with {@link encryptWithDerivedKey}. */
105
+ const deriveEnvelopeKey = (passphrase, kdf = kdf_1.DEFAULT_KDF_PROFILE) => {
106
+ const params = (0, kdf_1.resolveKdfParams)(kdf);
107
+ const salt = (0, kdf_1.generateSalt)();
108
+ return { key: (0, kdf_1.deriveKey)(passphrase, salt, params), salt, kdf: params };
109
+ };
110
+ exports.deriveEnvelopeKey = deriveEnvelopeKey;
111
+ /**
112
+ * {@link encrypt} with the KDF already done. Produces an identical envelope — the header still
113
+ * records the salt and cost parameters, so {@link decrypt} opens it with the passphrase alone.
114
+ */
115
+ const encryptWithDerivedKey = (plaintext, derived, options = {}) => {
116
+ assertKey(derived.key);
117
+ const nonce = (0, utils_1.randomBytes)(exports.NONCE_LENGTH);
118
+ const header = encodeHeader({
119
+ version: exports.VERSION,
120
+ suite: Suite.Argon2idXChaCha20Poly1305,
121
+ kdf: derived.kdf,
122
+ salt: derived.salt,
123
+ nonce,
124
+ });
125
+ const aad = (0, utils_1.concatBytes)(header, toBytes(options.aad));
126
+ return (0, utils_1.concatBytes)(header, (0, chacha_1.xchacha20poly1305)(derived.key, nonce, aad).encrypt(toBytes(plaintext)));
127
+ };
128
+ exports.encryptWithDerivedKey = encryptWithDerivedKey;
100
129
  /**
101
130
  * Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
102
131
  * {@link WrongPassphraseError} — this format never returns an empty string on failure.
package/esm/bytes.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Copies a range into a plain Uint8Array. `Buffer.prototype.slice` returns a view of the caller's
3
+ * memory rather than a copy, so `bytes.slice()` must not be relied on to detach from the input.
4
+ */
5
+ export const copyBytes = (bytes, start = 0, end = bytes.length) => Uint8Array.prototype.slice.call(bytes, start, end);
package/esm/envelope.js CHANGED
@@ -7,12 +7,16 @@ export const MAGIC = utf8ToBytes('DCRYPT');
7
7
  /** Envelope format version implemented by this package. */
8
8
  export const VERSION = 1;
9
9
  /**
10
- * Algorithm suite identifier. Only one suite exists today; the byte is present so that a future
11
- * suite (say, AES-256-GCM for FIPS environments) can be added without a format break.
10
+ * Algorithm suite identifier. The byte is present so that a future suite (say, AES-256-GCM for
11
+ * FIPS environments) can be added without a format break.
12
+ *
13
+ * - `Argon2idXChaCha20Poly1305` is the single-shot version 1 envelope in this file.
14
+ * - `HkdfSha256ChaCha20Poly1305Stream` is the chunked version 2 file format in `file.ts`.
12
15
  */
13
16
  export var Suite;
14
17
  (function (Suite) {
15
18
  Suite[Suite["Argon2idXChaCha20Poly1305"] = 1] = "Argon2idXChaCha20Poly1305";
19
+ Suite[Suite["HkdfSha256ChaCha20Poly1305Stream"] = 2] = "HkdfSha256ChaCha20Poly1305Stream";
16
20
  })(Suite || (Suite = {}));
17
21
  export const NONCE_LENGTH = 24;
18
22
  export const TAG_LENGTH = 16;
@@ -92,6 +96,29 @@ export const encrypt = (plaintext, passphrase, options = {}) => {
92
96
  key.fill(0);
93
97
  }
94
98
  };
99
+ /** Runs the KDF once, yielding a handle usable with {@link encryptWithDerivedKey}. */
100
+ export const deriveEnvelopeKey = (passphrase, kdf = DEFAULT_KDF_PROFILE) => {
101
+ const params = resolveKdfParams(kdf);
102
+ const salt = generateSalt();
103
+ return { key: deriveKey(passphrase, salt, params), salt, kdf: params };
104
+ };
105
+ /**
106
+ * {@link encrypt} with the KDF already done. Produces an identical envelope — the header still
107
+ * records the salt and cost parameters, so {@link decrypt} opens it with the passphrase alone.
108
+ */
109
+ export const encryptWithDerivedKey = (plaintext, derived, options = {}) => {
110
+ assertKey(derived.key);
111
+ const nonce = randomBytes(NONCE_LENGTH);
112
+ const header = encodeHeader({
113
+ version: VERSION,
114
+ suite: Suite.Argon2idXChaCha20Poly1305,
115
+ kdf: derived.kdf,
116
+ salt: derived.salt,
117
+ nonce,
118
+ });
119
+ const aad = concatBytes(header, toBytes(options.aad));
120
+ return concatBytes(header, xchacha20poly1305(derived.key, nonce, aad).encrypt(toBytes(plaintext)));
121
+ };
95
122
  /**
96
123
  * Decrypts an envelope produced by {@link encrypt}. A wrong passphrase raises
97
124
  * {@link WrongPassphraseError} — this format never returns an empty string on failure.
package/esm/file.js ADDED
@@ -0,0 +1,328 @@
1
+ import { base64 } from '@decryption/base';
2
+ import { equalBytes } from '@decryption/ciphers/utils';
3
+ import { hkdf } from '@decryption/hashes/hkdf';
4
+ import { hmac } from '@decryption/hashes/hmac';
5
+ import { sha256 } from '@decryption/hashes/sha2';
6
+ import { concatBytes, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
7
+ import { copyBytes } from './bytes';
8
+ import { MAGIC, NONCE_LENGTH, openWithKey, sealWithKey, Suite, TAG_LENGTH } from './envelope';
9
+ import { CorruptEnvelopeError, InvalidParametersError, UnsupportedEnvelopeError, WrongPassphraseError, } from './errors';
10
+ import { DEFAULT_KDF_PROFILE, deriveKey, generateSalt, resolveKdfParams, SALT_LENGTH, } from './kdf';
11
+ import { deriveStreamKey, generateStreamNonce, STREAM_NONCE_LENGTH, StreamDecryptor, StreamEncryptor, } from './stream';
12
+ /**
13
+ * Version 2 of the dcrypt format: a binary, streamable file envelope.
14
+ *
15
+ * ```text
16
+ * | magic | ver | suite | count | stanza … stanza | header MAC | nonce | STREAM chunks … |
17
+ * | DCRYPT | 2 | 2 | u16 | | 32 B | 16 B | |
18
+ * |<------------- authenticated by the MAC ------->|
19
+ *
20
+ * stanza: | type u8 | length u16 | body |
21
+ * ```
22
+ *
23
+ * The layout follows the age file format: a random file key encrypts the payload, and each
24
+ * stanza holds one wrapped copy of that key (for a passphrase, or for an X25519 recipient). The
25
+ * header is authenticated with `HMAC-SHA256` under `HKDF-SHA256(file key, info = "header")`, and
26
+ * the payload is the STREAM construction in `stream.ts`. Only the encoding differs from age
27
+ * (binary fields instead of text lines), plus the key wrapping, which reuses this package's
28
+ * Argon2id + XChaCha20-Poly1305 and `@decryption/keys`' X25519 stanzas.
29
+ *
30
+ * Adding a way to unlock a file means adding a stanza type; the payload never changes.
31
+ */
32
+ /** Format version written in the seventh byte. Version 1 is the single-shot envelope. */
33
+ export const FILE_VERSION = 2;
34
+ /** Length of the random file key. */
35
+ export const FILE_KEY_LENGTH = 32;
36
+ /** Length of the header MAC. */
37
+ export const FILE_MAC_LENGTH = 32;
38
+ /** Prefix of the text (armored) form of a version 2 file, e.g. `dcrypt.v2.<base64>`. */
39
+ export const FILE_ARMOR_PREFIX = 'dcrypt.v2.';
40
+ /** Upper bounds accepted when reading, so a hostile header cannot make a reader buffer forever. */
41
+ export const MAX_STANZAS = 1024;
42
+ export const MAX_STANZA_BODY_LENGTH = 1024;
43
+ /** Known stanza types. Readers keep stanzas of unknown type so newer writers stay readable. */
44
+ export var StanzaType;
45
+ (function (StanzaType) {
46
+ /** Argon2id-derived key wraps the file key. Must be the only stanza, as with age's scrypt. */
47
+ StanzaType[StanzaType["Passphrase"] = 1] = "Passphrase";
48
+ /** X25519 recipient, produced by `@decryption/keys`. */
49
+ StanzaType[StanzaType["X25519"] = 2] = "X25519";
50
+ })(StanzaType || (StanzaType = {}));
51
+ const FIXED_LENGTH = MAGIC.length + 1 + 1 + 2;
52
+ const TRAILER_LENGTH = FILE_MAC_LENGTH + STREAM_NONCE_LENGTH;
53
+ const HEADER_INFO = utf8ToBytes('header');
54
+ const PASSPHRASE_PARAMS_LENGTH = 4 + 4 + 1 + SALT_LENGTH;
55
+ const WRAPPED_KEY_LENGTH = NONCE_LENGTH + FILE_KEY_LENGTH + TAG_LENGTH;
56
+ const PASSPHRASE_CONTEXT = utf8ToBytes('dcrypt-file-passphrase-v2');
57
+ const assertFileKey = (fileKey) => {
58
+ if (fileKey.length !== FILE_KEY_LENGTH) {
59
+ throw new InvalidParametersError(`file key must be ${FILE_KEY_LENGTH} bytes, got ${fileKey.length}`);
60
+ }
61
+ };
62
+ const assertStanzas = (stanzas, Failure) => {
63
+ if (stanzas.length === 0)
64
+ throw new Failure('a file needs at least one stanza');
65
+ if (stanzas.length > MAX_STANZAS)
66
+ throw new Failure(`a file can hold at most ${MAX_STANZAS} stanzas`);
67
+ for (const stanza of stanzas) {
68
+ if (!Number.isInteger(stanza.type) || stanza.type < 1 || stanza.type > 255) {
69
+ throw new Failure(`invalid stanza type ${stanza.type}`);
70
+ }
71
+ if (stanza.body.length > MAX_STANZA_BODY_LENGTH) {
72
+ throw new Failure(`stanza body is longer than ${MAX_STANZA_BODY_LENGTH} bytes`);
73
+ }
74
+ }
75
+ if (stanzas.length > 1 && stanzas.some((stanza) => stanza.type === StanzaType.Passphrase)) {
76
+ throw new Failure('a passphrase stanza must be the only stanza in a file');
77
+ }
78
+ };
79
+ const headerMac = (fileKey, authenticated) => {
80
+ const macKey = hkdf(sha256, fileKey, undefined, HEADER_INFO, 32);
81
+ try {
82
+ return hmac(sha256, macKey, authenticated);
83
+ }
84
+ finally {
85
+ macKey.fill(0);
86
+ }
87
+ };
88
+ /** Draws a fresh random file key. Never reuse one: it is the root of a single file's keys. */
89
+ export const generateFileKey = () => randomBytes(FILE_KEY_LENGTH);
90
+ /** True when `bytes` begin like a version 2 file. Eight bytes are enough to tell. */
91
+ export const isFileEnvelope = (bytes) => {
92
+ if (bytes.length < MAGIC.length + 1)
93
+ return false;
94
+ for (let i = 0; i < MAGIC.length; i++) {
95
+ if (bytes[i] !== MAGIC[i])
96
+ return false;
97
+ }
98
+ return bytes[MAGIC.length] === FILE_VERSION;
99
+ };
100
+ /** Encodes the complete header: stanzas, their MAC, and the payload nonce. */
101
+ export const encodeFileHeader = (fileKey, stanzas, nonce = generateStreamNonce()) => {
102
+ assertFileKey(fileKey);
103
+ assertStanzas(stanzas, InvalidParametersError);
104
+ if (nonce.length !== STREAM_NONCE_LENGTH) {
105
+ throw new InvalidParametersError(`stream nonce must be ${STREAM_NONCE_LENGTH} bytes`);
106
+ }
107
+ const fixed = new Uint8Array(FIXED_LENGTH);
108
+ fixed.set(MAGIC, 0);
109
+ fixed[MAGIC.length] = FILE_VERSION;
110
+ fixed[MAGIC.length + 1] = Suite.HkdfSha256ChaCha20Poly1305Stream;
111
+ new DataView(fixed.buffer).setUint16(MAGIC.length + 2, stanzas.length, false);
112
+ const encoded = stanzas.map((stanza) => {
113
+ const bytes = new Uint8Array(3 + stanza.body.length);
114
+ bytes[0] = stanza.type;
115
+ new DataView(bytes.buffer).setUint16(1, stanza.body.length, false);
116
+ bytes.set(stanza.body, 3);
117
+ return bytes;
118
+ });
119
+ const authenticated = concatBytes(fixed, ...encoded);
120
+ return concatBytes(authenticated, headerMac(fileKey, authenticated), nonce);
121
+ };
122
+ /**
123
+ * Parses a header from the start of `bytes`. Returns `undefined` when more bytes are needed, so
124
+ * a streaming reader can call it again with a longer prefix. Throws {@link CorruptEnvelopeError}
125
+ * for anything that is not a dcrypt file and {@link UnsupportedEnvelopeError} for versions or
126
+ * suites this build cannot open.
127
+ */
128
+ export const tryParseFileHeader = (bytes) => {
129
+ for (let i = 0; i < Math.min(bytes.length, MAGIC.length); i++) {
130
+ if (bytes[i] !== MAGIC[i])
131
+ throw new CorruptEnvelopeError('not a dcrypt envelope');
132
+ }
133
+ if (bytes.length < FIXED_LENGTH)
134
+ return undefined;
135
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
136
+ const version = bytes[MAGIC.length];
137
+ const suite = bytes[MAGIC.length + 1];
138
+ if (version !== FILE_VERSION) {
139
+ throw new UnsupportedEnvelopeError(version === 1
140
+ ? 'this is a version 1 envelope; open it with decrypt()'
141
+ : `unsupported envelope version ${version}; this build understands versions 1 and ${FILE_VERSION}`);
142
+ }
143
+ if (suite !== Suite.HkdfSha256ChaCha20Poly1305Stream) {
144
+ throw new UnsupportedEnvelopeError(`unsupported algorithm suite ${suite}`);
145
+ }
146
+ const count = view.getUint16(MAGIC.length + 2, false);
147
+ if (count === 0 || count > MAX_STANZAS) {
148
+ throw new CorruptEnvelopeError(`invalid stanza count ${count}`);
149
+ }
150
+ const stanzas = [];
151
+ let offset = FIXED_LENGTH;
152
+ for (let i = 0; i < count; i++) {
153
+ if (bytes.length < offset + 3)
154
+ return undefined;
155
+ const type = bytes[offset];
156
+ const length = view.getUint16(offset + 1, false);
157
+ if (type === 0)
158
+ throw new CorruptEnvelopeError('invalid stanza type 0');
159
+ if (length > MAX_STANZA_BODY_LENGTH) {
160
+ throw new CorruptEnvelopeError(`stanza body is longer than ${MAX_STANZA_BODY_LENGTH} bytes`);
161
+ }
162
+ if (bytes.length < offset + 3 + length)
163
+ return undefined;
164
+ stanzas.push({ type, body: copyBytes(bytes, offset + 3, offset + 3 + length) });
165
+ offset += 3 + length;
166
+ }
167
+ if (bytes.length < offset + TRAILER_LENGTH)
168
+ return undefined;
169
+ assertStanzas(stanzas, CorruptEnvelopeError);
170
+ return {
171
+ version,
172
+ suite,
173
+ stanzas,
174
+ mac: copyBytes(bytes, offset, offset + FILE_MAC_LENGTH),
175
+ nonce: copyBytes(bytes, offset + FILE_MAC_LENGTH, offset + TRAILER_LENGTH),
176
+ authenticated: copyBytes(bytes, 0, offset),
177
+ length: offset + TRAILER_LENGTH,
178
+ };
179
+ };
180
+ /** {@link tryParseFileHeader} for callers that hold the whole file: a short header is corrupt. */
181
+ export const parseFileHeader = (bytes) => {
182
+ const header = tryParseFileHeader(bytes);
183
+ if (!header)
184
+ throw new CorruptEnvelopeError('envelope header is truncated');
185
+ return header;
186
+ };
187
+ /**
188
+ * Checks the header MAC with the unwrapped file key. This is what stops an attacker from adding,
189
+ * removing or editing stanzas (for example to lower Argon2id cost parameters) on a file they
190
+ * cannot decrypt. Anyone who can unwrap the file key can also rewrite the header; that is
191
+ * inherent in the design and the same as in age.
192
+ */
193
+ export const verifyFileHeader = (header, fileKey) => {
194
+ assertFileKey(fileKey);
195
+ if (!equalBytes(headerMac(fileKey, header.authenticated), header.mac)) {
196
+ throw new CorruptEnvelopeError('envelope header failed authentication: it was modified');
197
+ }
198
+ };
199
+ /** True when the file is unlocked with a passphrase rather than by recipients. */
200
+ export const isPassphraseFile = (header) => header.stanzas.some((stanza) => stanza.type === StanzaType.Passphrase);
201
+ /** Wraps the file key under an Argon2id-derived key. The cost parameters travel in the stanza. */
202
+ export const wrapWithPassphrase = (fileKey, passphrase, kdf = DEFAULT_KDF_PROFILE) => {
203
+ assertFileKey(fileKey);
204
+ const params = resolveKdfParams(kdf);
205
+ if (params.t > 0xffffffff || params.m > 0xffffffff || params.p > 0xff) {
206
+ throw new InvalidParametersError('kdf parameters do not fit the envelope header');
207
+ }
208
+ const salt = generateSalt();
209
+ const prefix = new Uint8Array(PASSPHRASE_PARAMS_LENGTH);
210
+ const view = new DataView(prefix.buffer);
211
+ view.setUint32(0, params.t, false);
212
+ view.setUint32(4, params.m, false);
213
+ prefix[8] = params.p;
214
+ prefix.set(salt, 9);
215
+ const key = deriveKey(passphrase, salt, params);
216
+ try {
217
+ // The parameters are bound as associated data: lowering them changes the derived key anyway,
218
+ // and this keeps a wrapped key from being lifted into a stanza that claims other parameters.
219
+ const wrapped = sealWithKey(key, fileKey, concatBytes(PASSPHRASE_CONTEXT, prefix));
220
+ return { type: StanzaType.Passphrase, body: concatBytes(prefix, wrapped) };
221
+ }
222
+ finally {
223
+ key.fill(0);
224
+ }
225
+ };
226
+ /** Recovers the file key from a passphrase file. A wrong passphrase raises {@link WrongPassphraseError}. */
227
+ export const unwrapWithPassphrase = (header, passphrase) => {
228
+ const stanza = header.stanzas.find((candidate) => candidate.type === StanzaType.Passphrase);
229
+ if (!stanza) {
230
+ throw new InvalidParametersError('this file is encrypted to recipients, not with a passphrase');
231
+ }
232
+ if (stanza.body.length !== PASSPHRASE_PARAMS_LENGTH + WRAPPED_KEY_LENGTH) {
233
+ throw new CorruptEnvelopeError('passphrase stanza has the wrong length');
234
+ }
235
+ const prefix = copyBytes(stanza.body, 0, PASSPHRASE_PARAMS_LENGTH);
236
+ const view = new DataView(prefix.buffer, prefix.byteOffset, prefix.byteLength);
237
+ let params;
238
+ try {
239
+ params = resolveKdfParams({ t: view.getUint32(0, false), m: view.getUint32(4, false), p: prefix[8] });
240
+ }
241
+ catch (error) {
242
+ throw new CorruptEnvelopeError(`passphrase stanza carries unacceptable kdf parameters: ${error.message}`);
243
+ }
244
+ const key = deriveKey(passphrase, copyBytes(prefix, 9), params);
245
+ try {
246
+ return openWithKey(key, copyBytes(stanza.body, PASSPHRASE_PARAMS_LENGTH), concatBytes(PASSPHRASE_CONTEXT, prefix));
247
+ }
248
+ catch {
249
+ throw new WrongPassphraseError();
250
+ }
251
+ finally {
252
+ key.fill(0);
253
+ }
254
+ };
255
+ /** Starts a file: encodes its header and returns a streaming encryptor for the payload. */
256
+ export const createFileEncryptor = (fileKey, stanzas) => {
257
+ const nonce = generateStreamNonce();
258
+ const header = encodeFileHeader(fileKey, stanzas, nonce);
259
+ const key = deriveStreamKey(fileKey, nonce);
260
+ try {
261
+ return { header, stream: new StreamEncryptor(key) };
262
+ }
263
+ finally {
264
+ key.fill(0);
265
+ }
266
+ };
267
+ /** Verifies the header with `fileKey` and returns a streaming decryptor for the payload. */
268
+ export const createFileDecryptor = (header, fileKey) => {
269
+ verifyFileHeader(header, fileKey);
270
+ const key = deriveStreamKey(fileKey, header.nonce);
271
+ try {
272
+ return new StreamDecryptor(key);
273
+ }
274
+ finally {
275
+ key.fill(0);
276
+ }
277
+ };
278
+ /** Encrypts bytes already in memory under `fileKey`, with the given stanzas in the header. */
279
+ export const sealFile = (plaintext, fileKey, stanzas) => {
280
+ const { header, stream } = createFileEncryptor(fileKey, stanzas);
281
+ const bytes = typeof plaintext === 'string' ? utf8ToBytes(plaintext) : plaintext;
282
+ const head = stream.update(bytes);
283
+ return concatBytes(header, head, stream.finish());
284
+ };
285
+ /**
286
+ * Decrypts a whole file held in memory. `unwrap` turns the parsed header into the file key (with
287
+ * a passphrase, an identity, or anything else). Nothing is returned unless the entire payload
288
+ * authenticates.
289
+ */
290
+ export const openFile = (bytes, unwrap) => {
291
+ const header = parseFileHeader(bytes);
292
+ const fileKey = unwrap(header);
293
+ try {
294
+ const stream = createFileDecryptor(header, fileKey);
295
+ const head = stream.update(bytes.subarray(header.length));
296
+ return concatBytes(head, stream.finish());
297
+ }
298
+ finally {
299
+ fileKey.fill(0);
300
+ }
301
+ };
302
+ /** Passphrase-encrypts bytes into a version 2 file. */
303
+ export const encryptFile = (plaintext, passphrase, options = {}) => {
304
+ const fileKey = generateFileKey();
305
+ try {
306
+ return sealFile(plaintext, fileKey, [wrapWithPassphrase(fileKey, passphrase, options.kdf)]);
307
+ }
308
+ finally {
309
+ fileKey.fill(0);
310
+ }
311
+ };
312
+ /** Inverse of {@link encryptFile}. */
313
+ export const decryptFile = (bytes, passphrase) => openFile(bytes, (header) => unwrapWithPassphrase(header, passphrase));
314
+ /** Text form of a version 2 file, for small payloads that have to live in text. */
315
+ export const armorFile = (file) => FILE_ARMOR_PREFIX + base64.encode(file);
316
+ /** Inverse of {@link armorFile}. */
317
+ export const dearmorFile = (text) => {
318
+ const trimmed = text.trim();
319
+ if (!trimmed.startsWith(FILE_ARMOR_PREFIX)) {
320
+ throw new CorruptEnvelopeError(`armored file must start with "${FILE_ARMOR_PREFIX}"`);
321
+ }
322
+ try {
323
+ return base64.decode(trimmed.slice(FILE_ARMOR_PREFIX.length));
324
+ }
325
+ catch {
326
+ throw new CorruptEnvelopeError('armored file is not valid base64');
327
+ }
328
+ };
package/esm/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from './armor';
2
2
  export * from './envelope';
3
3
  export * from './errors';
4
+ export * from './file';
4
5
  export * from './kdf';
6
+ export * from './stream';