@git-stunts/git-cas 1.6.2 → 2.0.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/CHANGELOG.md +33 -0
- package/README.md +21 -0
- package/index.d.ts +16 -2
- package/index.js +36 -3
- package/package.json +1 -1
- package/src/domain/schemas/ManifestSchema.d.ts +27 -0
- package/src/domain/schemas/ManifestSchema.js +27 -0
- package/src/domain/services/CasService.d.ts +29 -1
- package/src/domain/services/CasService.js +253 -30
- package/src/domain/value-objects/Manifest.d.ts +30 -0
- package/src/domain/value-objects/Manifest.js +6 -0
- package/src/infrastructure/adapters/BunCryptoAdapter.js +35 -2
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +40 -1
- package/src/infrastructure/adapters/WebCryptoAdapter.js +58 -0
- package/src/ports/CryptoPort.js +17 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.0.0] — M7 Horizon (2026-02-08)
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- **Compression support** (Task 7.1): Optional gzip compression pipeline via `compression: { algorithm: 'gzip' }` option on `store()`. Compression is applied before encryption when both are enabled. Manifests include a new optional `compression` field. Decompression on `restore()` is automatic.
|
|
14
|
+
- **KDF support** (Task 7.2): Passphrase-based encryption using PBKDF2 or scrypt via `deriveKey()` method and `passphrase` option on `store()`/`restore()`. KDF parameters are stored in `manifest.encryption.kdf` for deterministic re-derivation. All three crypto adapters (Node, Bun, Web) implement `deriveKey()`.
|
|
15
|
+
- **Merkle tree manifests** (Task 7.3): Large manifests (chunk count exceeding `merkleThreshold`, default 1000) are automatically split into sub-manifests stored as separate blobs. Root manifest uses `version: 2` with `subManifests` references. `readManifest()` transparently reconstitutes v2 manifests into flat chunk lists. Full backward compatibility with v1 manifests.
|
|
16
|
+
- New schema fields: `version`, `compression`, `subManifests` on `ManifestSchema`; `kdf` on `EncryptionSchema`.
|
|
17
|
+
- New error code: `INVALID_OPTIONS` for mutually exclusive options or unsupported option values.
|
|
18
|
+
- 62 new unit tests across three new test suites (compression, KDF, Merkle) plus expanded error tests.
|
|
19
|
+
- Updated API reference (`docs/API.md`), guide (`GUIDE.md`), and README with v2.0.0 feature documentation.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
- **BREAKING**: Manifest schema now includes `version` field (defaults to 1). Existing v1 manifests are fully backward-compatible.
|
|
23
|
+
- `CasService` constructor accepts new `merkleThreshold` option (must be a positive integer).
|
|
24
|
+
- `ContentAddressableStore` constructor now accepts and forwards `merkleThreshold` to `CasService`.
|
|
25
|
+
- `store()` and `storeFile()` accept `passphrase`, `kdfOptions`, and `compression` options.
|
|
26
|
+
- `restore()` accepts `passphrase` option.
|
|
27
|
+
- Static imports for `createGzip` and `Readable` in `CasService` (previously dynamic imports on every call).
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
- **Sub-manifest blobs are now included as tree entries** (`sub-manifest-N.json`), preventing them from being garbage-collected by `git gc`.
|
|
31
|
+
- `storeFile()` now forwards `passphrase`, `kdfOptions`, and `compression` options to `store()` (previously silently dropped).
|
|
32
|
+
- `store()` and `restore()` reject when both `passphrase` and `encryptionKey` are provided (`INVALID_OPTIONS`).
|
|
33
|
+
- `store()` rejects unsupported compression algorithms (`INVALID_OPTIONS`).
|
|
34
|
+
- `restore()` throws a descriptive error when passphrase is provided but manifest lacks KDF metadata.
|
|
35
|
+
- Decompression errors are now wrapped as `CasError` with code `INTEGRITY_ERROR` (previously raw zlib errors).
|
|
36
|
+
- `NodeCryptoAdapter.deriveKey()` uses `Buffer.from(salt)` for base64 encoding, preventing corrupt output when salt is a `Uint8Array`.
|
|
37
|
+
- `WebCryptoAdapter.deriveKey()` now validates KDF algorithm and throws for unsupported values instead of silently falling through to scrypt.
|
|
38
|
+
- `WebCryptoAdapter` scrypt derivation now throws a descriptive error when `node:crypto` is unavailable (e.g. in browsers).
|
|
39
|
+
- Orphaned JSDoc blocks for `restore()`, `verifyIntegrity()`, and `store()` reattached to their correct methods.
|
|
40
|
+
- Stale cross-reference in GUIDE.md ("Section 10" → "Section 13").
|
|
41
|
+
- API.md method signatures updated to include all v2 parameters.
|
|
42
|
+
|
|
10
43
|
## [1.6.2] — OIDC publishing + JSR docs coverage (2026-02-07)
|
|
11
44
|
|
|
12
45
|
### Added
|
package/README.md
CHANGED
|
@@ -21,6 +21,9 @@ We use the object database.
|
|
|
21
21
|
- **Dedupe for free** Git already hashes objects. We just lean into it.
|
|
22
22
|
- **Chunked storage** big files become stable, reusable blobs.
|
|
23
23
|
- **Optional AES-256-GCM encryption** store secrets without leaking plaintext into the ODB.
|
|
24
|
+
- **Compression** gzip before encryption — smaller blobs, same round-trip.
|
|
25
|
+
- **Passphrase encryption** derive keys from passphrases via PBKDF2 or scrypt — no raw key management.
|
|
26
|
+
- **Merkle manifests** large files auto-split into sub-manifests for scalability.
|
|
24
27
|
- **Manifests** a tiny explicit index of chunks + metadata (JSON/CBOR).
|
|
25
28
|
- **Tree output** generates standard Git trees so assets snap into commits cleanly.
|
|
26
29
|
- **Full round-trip** store, tree, and restore — get your bytes back, verified.
|
|
@@ -28,6 +31,16 @@ We use the object database.
|
|
|
28
31
|
|
|
29
32
|
**Use it for:** binary assets, build artifacts, model weights, data packs, secret bundles, weird experiments, etc.
|
|
30
33
|
|
|
34
|
+
## What's new in v2.0.0
|
|
35
|
+
|
|
36
|
+
**Compression** — `compression: { algorithm: 'gzip' }` on `store()`. Compression runs before encryption. Decompression on `restore()` is automatic.
|
|
37
|
+
|
|
38
|
+
**Passphrase-based encryption** — Pass `passphrase` instead of `encryptionKey`. Keys are derived via PBKDF2 (default) or scrypt. KDF parameters are stored in the manifest for deterministic re-derivation. Use `deriveKey()` directly for manual control.
|
|
39
|
+
|
|
40
|
+
**Merkle tree manifests** — When chunk count exceeds `merkleThreshold` (default: 1000), manifests are automatically split into sub-manifests stored as separate blobs. `readManifest()` transparently reconstitutes them. Full backward compatibility with v1 manifests.
|
|
41
|
+
|
|
42
|
+
See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
|
|
43
|
+
|
|
31
44
|
## Usage (Node API)
|
|
32
45
|
|
|
33
46
|
```js
|
|
@@ -56,6 +69,14 @@ const m = await cas.readManifest({ treeOid });
|
|
|
56
69
|
// Lifecycle: inspect deletion impact, find orphaned chunks
|
|
57
70
|
const { slug, chunksOrphaned } = await cas.deleteAsset({ treeOid });
|
|
58
71
|
const { referenced, total } = await cas.findOrphanedChunks({ treeOids: [treeOid] });
|
|
72
|
+
|
|
73
|
+
// v2.0.0: Compressed + passphrase-encrypted store
|
|
74
|
+
const manifest2 = await cas.storeFile({
|
|
75
|
+
filePath: './image.png',
|
|
76
|
+
slug: 'my-image',
|
|
77
|
+
passphrase: 'my secret passphrase',
|
|
78
|
+
compression: { algorithm: 'gzip' },
|
|
79
|
+
});
|
|
59
80
|
```
|
|
60
81
|
|
|
61
82
|
## CLI (git plugin)
|
package/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import Manifest from "./src/domain/value-objects/Manifest.js";
|
|
7
|
-
import type { EncryptionMeta, ManifestData } from "./src/domain/value-objects/Manifest.js";
|
|
7
|
+
import type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef } from "./src/domain/value-objects/Manifest.js";
|
|
8
8
|
import Chunk from "./src/domain/value-objects/Chunk.js";
|
|
9
9
|
import CasService from "./src/domain/services/CasService.js";
|
|
10
10
|
import type {
|
|
@@ -12,10 +12,12 @@ import type {
|
|
|
12
12
|
CodecPort,
|
|
13
13
|
GitPersistencePort,
|
|
14
14
|
CasServiceOptions,
|
|
15
|
+
DeriveKeyOptions,
|
|
16
|
+
DeriveKeyResult,
|
|
15
17
|
} from "./src/domain/services/CasService.js";
|
|
16
18
|
|
|
17
19
|
export { CasService, Manifest, Chunk };
|
|
18
|
-
export type { EncryptionMeta, ManifestData, CryptoPort, CodecPort, GitPersistencePort, CasServiceOptions };
|
|
20
|
+
export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, CryptoPort, CodecPort, GitPersistencePort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
|
|
19
21
|
|
|
20
22
|
/** Abstract port for cryptographic operations. */
|
|
21
23
|
export declare class CryptoPortBase {
|
|
@@ -30,6 +32,7 @@ export declare class CryptoPortBase {
|
|
|
30
32
|
encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>;
|
|
31
33
|
finalize: () => EncryptionMeta;
|
|
32
34
|
};
|
|
35
|
+
deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
|
|
33
36
|
}
|
|
34
37
|
|
|
35
38
|
/** Abstract port for persisting data to Git's object database. */
|
|
@@ -76,6 +79,7 @@ export interface ContentAddressableStoreOptions {
|
|
|
76
79
|
codec?: CodecPort;
|
|
77
80
|
crypto?: CryptoPort;
|
|
78
81
|
policy?: unknown;
|
|
82
|
+
merkleThreshold?: number;
|
|
79
83
|
}
|
|
80
84
|
|
|
81
85
|
/**
|
|
@@ -119,6 +123,9 @@ export default class ContentAddressableStore {
|
|
|
119
123
|
slug: string;
|
|
120
124
|
filename?: string;
|
|
121
125
|
encryptionKey?: Buffer;
|
|
126
|
+
passphrase?: string;
|
|
127
|
+
kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
|
|
128
|
+
compression?: { algorithm: "gzip" };
|
|
122
129
|
}): Promise<Manifest>;
|
|
123
130
|
|
|
124
131
|
store(options: {
|
|
@@ -126,17 +133,22 @@ export default class ContentAddressableStore {
|
|
|
126
133
|
slug: string;
|
|
127
134
|
filename: string;
|
|
128
135
|
encryptionKey?: Buffer;
|
|
136
|
+
passphrase?: string;
|
|
137
|
+
kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
|
|
138
|
+
compression?: { algorithm: "gzip" };
|
|
129
139
|
}): Promise<Manifest>;
|
|
130
140
|
|
|
131
141
|
restoreFile(options: {
|
|
132
142
|
manifest: Manifest;
|
|
133
143
|
encryptionKey?: Buffer;
|
|
144
|
+
passphrase?: string;
|
|
134
145
|
outputPath: string;
|
|
135
146
|
}): Promise<{ bytesWritten: number }>;
|
|
136
147
|
|
|
137
148
|
restore(options: {
|
|
138
149
|
manifest: Manifest;
|
|
139
150
|
encryptionKey?: Buffer;
|
|
151
|
+
passphrase?: string;
|
|
140
152
|
}): Promise<{ buffer: Buffer; bytesWritten: number }>;
|
|
141
153
|
|
|
142
154
|
createTree(options: { manifest: Manifest }): Promise<string>;
|
|
@@ -152,4 +164,6 @@ export default class ContentAddressableStore {
|
|
|
152
164
|
findOrphanedChunks(options: {
|
|
153
165
|
treeOids: string[];
|
|
154
166
|
}): Promise<{ referenced: Set<string>; total: number }>;
|
|
167
|
+
|
|
168
|
+
deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
|
|
155
169
|
}
|
package/index.js
CHANGED
|
@@ -55,13 +55,15 @@ export default class ContentAddressableStore {
|
|
|
55
55
|
* @param {import('./src/ports/CodecPort.js').default} [options.codec] - Manifest codec (default JsonCodec).
|
|
56
56
|
* @param {import('./src/ports/CryptoPort.js').default} [options.crypto] - Crypto adapter (auto-detected if omitted).
|
|
57
57
|
* @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy for Git I/O.
|
|
58
|
+
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
58
59
|
*/
|
|
59
|
-
constructor({ plumbing, chunkSize, codec, policy, crypto }) {
|
|
60
|
+
constructor({ plumbing, chunkSize, codec, policy, crypto, merkleThreshold }) {
|
|
60
61
|
this.plumbing = plumbing;
|
|
61
62
|
this.chunkSizeConfig = chunkSize;
|
|
62
63
|
this.codecConfig = codec;
|
|
63
64
|
this.policyConfig = policy;
|
|
64
65
|
this.cryptoConfig = crypto;
|
|
66
|
+
this.merkleThresholdConfig = merkleThreshold;
|
|
65
67
|
this.service = null;
|
|
66
68
|
this.#servicePromise = null;
|
|
67
69
|
}
|
|
@@ -96,6 +98,7 @@ export default class ContentAddressableStore {
|
|
|
96
98
|
chunkSize: this.chunkSizeConfig,
|
|
97
99
|
codec: this.codecConfig || new JsonCodec(),
|
|
98
100
|
crypto,
|
|
101
|
+
merkleThreshold: this.merkleThresholdConfig,
|
|
99
102
|
});
|
|
100
103
|
return this.service;
|
|
101
104
|
}
|
|
@@ -176,9 +179,12 @@ export default class ContentAddressableStore {
|
|
|
176
179
|
* @param {string} options.slug - Logical identifier for the stored asset.
|
|
177
180
|
* @param {string} [options.filename] - Override filename (defaults to basename of filePath).
|
|
178
181
|
* @param {Buffer} [options.encryptionKey] - 32-byte key for AES-256-GCM encryption.
|
|
182
|
+
* @param {string} [options.passphrase] - Derive encryption key from passphrase.
|
|
183
|
+
* @param {Object} [options.kdfOptions] - KDF options when using passphrase.
|
|
184
|
+
* @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
|
|
179
185
|
* @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
|
|
180
186
|
*/
|
|
181
|
-
async storeFile({ filePath, slug, filename, encryptionKey }) {
|
|
187
|
+
async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
|
|
182
188
|
const source = createReadStream(filePath);
|
|
183
189
|
const service = await this.#getService();
|
|
184
190
|
return await service.store({
|
|
@@ -186,6 +192,9 @@ export default class ContentAddressableStore {
|
|
|
186
192
|
slug,
|
|
187
193
|
filename: filename || path.basename(filePath),
|
|
188
194
|
encryptionKey,
|
|
195
|
+
passphrase,
|
|
196
|
+
kdfOptions,
|
|
197
|
+
compression,
|
|
189
198
|
});
|
|
190
199
|
}
|
|
191
200
|
|
|
@@ -196,6 +205,9 @@ export default class ContentAddressableStore {
|
|
|
196
205
|
* @param {string} options.slug - Logical identifier for the stored asset.
|
|
197
206
|
* @param {string} options.filename - Filename for the manifest.
|
|
198
207
|
* @param {Buffer} [options.encryptionKey] - 32-byte key for AES-256-GCM encryption.
|
|
208
|
+
* @param {string} [options.passphrase] - Derive encryption key from passphrase.
|
|
209
|
+
* @param {Object} [options.kdfOptions] - KDF options when using passphrase.
|
|
210
|
+
* @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
|
|
199
211
|
* @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
|
|
200
212
|
*/
|
|
201
213
|
async store(options) {
|
|
@@ -208,14 +220,16 @@ export default class ContentAddressableStore {
|
|
|
208
220
|
* @param {Object} options
|
|
209
221
|
* @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
210
222
|
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
223
|
+
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
211
224
|
* @param {string} options.outputPath - Destination file path.
|
|
212
225
|
* @returns {Promise<{ bytesWritten: number }>}
|
|
213
226
|
*/
|
|
214
|
-
async restoreFile({ manifest, encryptionKey, outputPath }) {
|
|
227
|
+
async restoreFile({ manifest, encryptionKey, passphrase, outputPath }) {
|
|
215
228
|
const service = await this.#getService();
|
|
216
229
|
const { buffer, bytesWritten } = await service.restore({
|
|
217
230
|
manifest,
|
|
218
231
|
encryptionKey,
|
|
232
|
+
passphrase,
|
|
219
233
|
});
|
|
220
234
|
writeFileSync(outputPath, buffer);
|
|
221
235
|
return { bytesWritten };
|
|
@@ -226,6 +240,7 @@ export default class ContentAddressableStore {
|
|
|
226
240
|
* @param {Object} options
|
|
227
241
|
* @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
228
242
|
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
243
|
+
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
229
244
|
* @returns {Promise<{ buffer: Buffer, bytesWritten: number }>}
|
|
230
245
|
*/
|
|
231
246
|
async restore(options) {
|
|
@@ -288,4 +303,22 @@ export default class ContentAddressableStore {
|
|
|
288
303
|
const service = await this.#getService();
|
|
289
304
|
return await service.findOrphanedChunks(options);
|
|
290
305
|
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Derives an encryption key from a passphrase using PBKDF2 or scrypt.
|
|
309
|
+
* @param {Object} options
|
|
310
|
+
* @param {string} options.passphrase - The passphrase.
|
|
311
|
+
* @param {Buffer} [options.salt] - Salt (random if omitted).
|
|
312
|
+
* @param {'pbkdf2'|'scrypt'} [options.algorithm='pbkdf2'] - KDF algorithm.
|
|
313
|
+
* @param {number} [options.iterations] - PBKDF2 iterations.
|
|
314
|
+
* @param {number} [options.cost] - scrypt cost (N).
|
|
315
|
+
* @param {number} [options.blockSize] - scrypt block size (r).
|
|
316
|
+
* @param {number} [options.parallelization] - scrypt parallelization (p).
|
|
317
|
+
* @param {number} [options.keyLength=32] - Derived key length.
|
|
318
|
+
* @returns {Promise<{ key: Buffer, salt: Buffer, params: Object }>}
|
|
319
|
+
*/
|
|
320
|
+
async deriveKey(options) {
|
|
321
|
+
const service = await this.#getService();
|
|
322
|
+
return await service.deriveKey(options);
|
|
323
|
+
}
|
|
291
324
|
}
|
package/package.json
CHANGED
|
@@ -13,19 +13,46 @@ export declare const ChunkSchema: z.ZodObject<{
|
|
|
13
13
|
blob: z.ZodString;
|
|
14
14
|
}>;
|
|
15
15
|
|
|
16
|
+
/** Validates KDF parameters stored alongside encryption metadata. */
|
|
17
|
+
export declare const KdfSchema: z.ZodObject<{
|
|
18
|
+
algorithm: z.ZodEnum<["pbkdf2", "scrypt"]>;
|
|
19
|
+
salt: z.ZodString;
|
|
20
|
+
iterations: z.ZodOptional<z.ZodNumber>;
|
|
21
|
+
cost: z.ZodOptional<z.ZodNumber>;
|
|
22
|
+
blockSize: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
parallelization: z.ZodOptional<z.ZodNumber>;
|
|
24
|
+
keyLength: z.ZodDefault<z.ZodNumber>;
|
|
25
|
+
}>;
|
|
26
|
+
|
|
16
27
|
/** Validates the encryption metadata attached to an encrypted manifest. */
|
|
17
28
|
export declare const EncryptionSchema: z.ZodObject<{
|
|
18
29
|
algorithm: z.ZodString;
|
|
19
30
|
nonce: z.ZodString;
|
|
20
31
|
tag: z.ZodString;
|
|
21
32
|
encrypted: z.ZodDefault<z.ZodBoolean>;
|
|
33
|
+
kdf: z.ZodOptional<typeof KdfSchema>;
|
|
34
|
+
}>;
|
|
35
|
+
|
|
36
|
+
/** Validates compression metadata. */
|
|
37
|
+
export declare const CompressionSchema: z.ZodObject<{
|
|
38
|
+
algorithm: z.ZodEnum<["gzip"]>;
|
|
39
|
+
}>;
|
|
40
|
+
|
|
41
|
+
/** Validates a sub-manifest reference in a v2 Merkle manifest. */
|
|
42
|
+
export declare const SubManifestRefSchema: z.ZodObject<{
|
|
43
|
+
oid: z.ZodString;
|
|
44
|
+
chunkCount: z.ZodNumber;
|
|
45
|
+
startIndex: z.ZodNumber;
|
|
22
46
|
}>;
|
|
23
47
|
|
|
24
48
|
/** Validates a complete file manifest. */
|
|
25
49
|
export declare const ManifestSchema: z.ZodObject<{
|
|
50
|
+
version: z.ZodDefault<z.ZodNumber>;
|
|
26
51
|
slug: z.ZodString;
|
|
27
52
|
filename: z.ZodString;
|
|
28
53
|
size: z.ZodNumber;
|
|
29
54
|
chunks: z.ZodArray<typeof ChunkSchema>;
|
|
30
55
|
encryption: z.ZodOptional<typeof EncryptionSchema>;
|
|
56
|
+
compression: z.ZodOptional<typeof CompressionSchema>;
|
|
57
|
+
subManifests: z.ZodOptional<z.ZodArray<typeof SubManifestRefSchema>>;
|
|
31
58
|
}>;
|
|
@@ -13,19 +13,46 @@ export const ChunkSchema = z.object({
|
|
|
13
13
|
blob: z.string().min(1), // Git OID
|
|
14
14
|
});
|
|
15
15
|
|
|
16
|
+
/** Validates KDF parameters stored alongside encryption metadata. */
|
|
17
|
+
export const KdfSchema = z.object({
|
|
18
|
+
algorithm: z.enum(['pbkdf2', 'scrypt']),
|
|
19
|
+
salt: z.string().min(1),
|
|
20
|
+
iterations: z.number().int().positive().optional(),
|
|
21
|
+
cost: z.number().int().positive().optional(),
|
|
22
|
+
blockSize: z.number().int().positive().optional(),
|
|
23
|
+
parallelization: z.number().int().positive().optional(),
|
|
24
|
+
keyLength: z.number().int().positive().default(32),
|
|
25
|
+
});
|
|
26
|
+
|
|
16
27
|
/** Validates the encryption metadata attached to an encrypted manifest. */
|
|
17
28
|
export const EncryptionSchema = z.object({
|
|
18
29
|
algorithm: z.string(),
|
|
19
30
|
nonce: z.string(),
|
|
20
31
|
tag: z.string(),
|
|
21
32
|
encrypted: z.boolean().default(true),
|
|
33
|
+
kdf: KdfSchema.optional(),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/** Validates compression metadata. */
|
|
37
|
+
export const CompressionSchema = z.object({
|
|
38
|
+
algorithm: z.enum(['gzip']),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/** Validates a sub-manifest reference in a v2 Merkle manifest. */
|
|
42
|
+
export const SubManifestRefSchema = z.object({
|
|
43
|
+
oid: z.string().min(1),
|
|
44
|
+
chunkCount: z.number().int().positive(),
|
|
45
|
+
startIndex: z.number().int().min(0),
|
|
22
46
|
});
|
|
23
47
|
|
|
24
48
|
/** Validates a complete file manifest. */
|
|
25
49
|
export const ManifestSchema = z.object({
|
|
50
|
+
version: z.number().int().min(1).max(2).default(1),
|
|
26
51
|
slug: z.string().min(1),
|
|
27
52
|
filename: z.string().min(1),
|
|
28
53
|
size: z.number().int().min(0),
|
|
29
54
|
chunks: z.array(ChunkSchema),
|
|
30
55
|
encryption: EncryptionSchema.optional(),
|
|
56
|
+
compression: CompressionSchema.optional(),
|
|
57
|
+
subManifests: z.array(SubManifestRefSchema).optional(),
|
|
31
58
|
});
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { EventEmitter } from "node:events";
|
|
7
7
|
import Manifest from "../value-objects/Manifest.js";
|
|
8
|
-
import type { EncryptionMeta } from "../value-objects/Manifest.js";
|
|
8
|
+
import type { EncryptionMeta, CompressionMeta, KdfParams } from "../value-objects/Manifest.js";
|
|
9
9
|
|
|
10
10
|
/** Port interface for cryptographic operations (hashing, encryption, random bytes). */
|
|
11
11
|
export interface CryptoPort {
|
|
@@ -20,6 +20,7 @@ export interface CryptoPort {
|
|
|
20
20
|
encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>;
|
|
21
21
|
finalize: () => EncryptionMeta;
|
|
22
22
|
};
|
|
23
|
+
deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
/** Port interface for encoding and decoding manifest data. */
|
|
@@ -45,6 +46,26 @@ export interface CasServiceOptions {
|
|
|
45
46
|
codec: CodecPort;
|
|
46
47
|
crypto: CryptoPort;
|
|
47
48
|
chunkSize?: number;
|
|
49
|
+
merkleThreshold?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Options for key derivation. */
|
|
53
|
+
export interface DeriveKeyOptions {
|
|
54
|
+
passphrase: string;
|
|
55
|
+
salt?: Buffer;
|
|
56
|
+
algorithm?: "pbkdf2" | "scrypt";
|
|
57
|
+
iterations?: number;
|
|
58
|
+
cost?: number;
|
|
59
|
+
blockSize?: number;
|
|
60
|
+
parallelization?: number;
|
|
61
|
+
keyLength?: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Result from key derivation. */
|
|
65
|
+
export interface DeriveKeyResult {
|
|
66
|
+
key: Buffer;
|
|
67
|
+
salt: Buffer;
|
|
68
|
+
params: KdfParams;
|
|
48
69
|
}
|
|
49
70
|
|
|
50
71
|
/**
|
|
@@ -58,6 +79,7 @@ export default class CasService extends EventEmitter {
|
|
|
58
79
|
readonly codec: CodecPort;
|
|
59
80
|
readonly crypto: CryptoPort;
|
|
60
81
|
readonly chunkSize: number;
|
|
82
|
+
readonly merkleThreshold: number;
|
|
61
83
|
|
|
62
84
|
constructor(options: CasServiceOptions);
|
|
63
85
|
|
|
@@ -77,6 +99,9 @@ export default class CasService extends EventEmitter {
|
|
|
77
99
|
slug: string;
|
|
78
100
|
filename: string;
|
|
79
101
|
encryptionKey?: Buffer;
|
|
102
|
+
passphrase?: string;
|
|
103
|
+
kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
|
|
104
|
+
compression?: { algorithm: "gzip" };
|
|
80
105
|
}): Promise<Manifest>;
|
|
81
106
|
|
|
82
107
|
createTree(options: { manifest: Manifest }): Promise<string>;
|
|
@@ -84,6 +109,7 @@ export default class CasService extends EventEmitter {
|
|
|
84
109
|
restore(options: {
|
|
85
110
|
manifest: Manifest;
|
|
86
111
|
encryptionKey?: Buffer;
|
|
112
|
+
passphrase?: string;
|
|
87
113
|
}): Promise<{ buffer: Buffer; bytesWritten: number }>;
|
|
88
114
|
|
|
89
115
|
readManifest(options: { treeOid: string }): Promise<Manifest>;
|
|
@@ -97,4 +123,6 @@ export default class CasService extends EventEmitter {
|
|
|
97
123
|
}): Promise<{ referenced: Set<string>; total: number }>;
|
|
98
124
|
|
|
99
125
|
verifyIntegrity(manifest: Manifest): Promise<boolean>;
|
|
126
|
+
|
|
127
|
+
deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
|
|
100
128
|
}
|
|
@@ -4,9 +4,14 @@
|
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
6
|
import { EventEmitter } from 'node:events';
|
|
7
|
+
import { gunzip, createGzip } from 'node:zlib';
|
|
8
|
+
import { Readable } from 'node:stream';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
7
10
|
import Manifest from '../value-objects/Manifest.js';
|
|
8
11
|
import CasError from '../errors/CasError.js';
|
|
9
12
|
|
|
13
|
+
const gunzipAsync = promisify(gunzip);
|
|
14
|
+
|
|
10
15
|
/**
|
|
11
16
|
* Domain service for Content Addressable Storage operations.
|
|
12
17
|
*
|
|
@@ -29,8 +34,9 @@ export default class CasService extends EventEmitter {
|
|
|
29
34
|
* @param {import('../../ports/CodecPort.js').default} options.codec
|
|
30
35
|
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
31
36
|
* @param {number} [options.chunkSize=262144] - 256 KiB
|
|
37
|
+
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
32
38
|
*/
|
|
33
|
-
constructor({ persistence, codec, crypto, chunkSize = 256 * 1024 }) {
|
|
39
|
+
constructor({ persistence, codec, crypto, chunkSize = 256 * 1024, merkleThreshold = 1000 }) {
|
|
34
40
|
super();
|
|
35
41
|
if (chunkSize < 1024) {
|
|
36
42
|
throw new Error('Chunk size must be at least 1024 bytes');
|
|
@@ -39,6 +45,10 @@ export default class CasService extends EventEmitter {
|
|
|
39
45
|
this.codec = codec;
|
|
40
46
|
this.crypto = crypto;
|
|
41
47
|
this.chunkSize = chunkSize;
|
|
48
|
+
if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
|
|
49
|
+
throw new Error('Merkle threshold must be a positive integer');
|
|
50
|
+
}
|
|
51
|
+
this.merkleThreshold = merkleThreshold;
|
|
42
52
|
}
|
|
43
53
|
|
|
44
54
|
/**
|
|
@@ -159,6 +169,47 @@ export default class CasService extends EventEmitter {
|
|
|
159
169
|
}
|
|
160
170
|
}
|
|
161
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Wraps an async iterable through gzip compression.
|
|
174
|
+
* @private
|
|
175
|
+
* @param {AsyncIterable<Buffer>} source
|
|
176
|
+
* @returns {AsyncIterable<Buffer>}
|
|
177
|
+
*/
|
|
178
|
+
async *_compressStream(source) {
|
|
179
|
+
const gz = createGzip();
|
|
180
|
+
const input = Readable.from(source);
|
|
181
|
+
const compressed = input.pipe(gz);
|
|
182
|
+
for await (const chunk of compressed) {
|
|
183
|
+
yield chunk;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Validates that passphrase and encryptionKey are not both provided.
|
|
189
|
+
* @private
|
|
190
|
+
*/
|
|
191
|
+
_validateKeySourceExclusive(encryptionKey, passphrase) {
|
|
192
|
+
if (passphrase && encryptionKey) {
|
|
193
|
+
throw new CasError(
|
|
194
|
+
'Provide either encryptionKey or passphrase, not both',
|
|
195
|
+
'INVALID_OPTIONS',
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Validates and normalizes compression options.
|
|
202
|
+
* @private
|
|
203
|
+
*/
|
|
204
|
+
_validateCompression(compression) {
|
|
205
|
+
if (compression?.algorithm && compression.algorithm !== 'gzip') {
|
|
206
|
+
throw new CasError(
|
|
207
|
+
`Unsupported compression algorithm: ${compression.algorithm}`,
|
|
208
|
+
'INVALID_OPTIONS',
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
162
213
|
/**
|
|
163
214
|
* Chunks an async iterable source and stores it in Git.
|
|
164
215
|
*
|
|
@@ -170,26 +221,44 @@ export default class CasService extends EventEmitter {
|
|
|
170
221
|
* @param {string} options.slug
|
|
171
222
|
* @param {string} options.filename
|
|
172
223
|
* @param {Buffer} [options.encryptionKey]
|
|
224
|
+
* @param {string} [options.passphrase] - Derive encryption key from passphrase instead.
|
|
225
|
+
* @param {Object} [options.kdfOptions] - KDF options when using passphrase.
|
|
226
|
+
* @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
|
|
173
227
|
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
174
228
|
*/
|
|
175
|
-
async store({ source, slug, filename, encryptionKey }) {
|
|
229
|
+
async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
|
|
230
|
+
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
231
|
+
this._validateCompression(compression);
|
|
232
|
+
|
|
233
|
+
let kdfParams;
|
|
234
|
+
if (passphrase) {
|
|
235
|
+
const derived = await this.deriveKey({ passphrase, ...kdfOptions });
|
|
236
|
+
encryptionKey = derived.key;
|
|
237
|
+
kdfParams = derived.params;
|
|
238
|
+
}
|
|
239
|
+
|
|
176
240
|
if (encryptionKey) {
|
|
177
241
|
this._validateKey(encryptionKey);
|
|
178
242
|
}
|
|
179
243
|
|
|
180
|
-
const manifestData = {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
244
|
+
const manifestData = { slug, filename, size: 0, chunks: [] };
|
|
245
|
+
|
|
246
|
+
let processedSource = source;
|
|
247
|
+
if (compression) {
|
|
248
|
+
processedSource = this._compressStream(processedSource);
|
|
249
|
+
manifestData.compression = { algorithm: 'gzip' };
|
|
250
|
+
}
|
|
186
251
|
|
|
187
252
|
if (encryptionKey) {
|
|
188
253
|
const { encrypt, finalize } = this.crypto.createEncryptionStream(encryptionKey);
|
|
189
|
-
await this._chunkAndStore(encrypt(
|
|
190
|
-
|
|
254
|
+
await this._chunkAndStore(encrypt(processedSource), manifestData);
|
|
255
|
+
const encMeta = finalize();
|
|
256
|
+
if (kdfParams) {
|
|
257
|
+
encMeta.kdf = kdfParams;
|
|
258
|
+
}
|
|
259
|
+
manifestData.encryption = encMeta;
|
|
191
260
|
} else {
|
|
192
|
-
await this._chunkAndStore(
|
|
261
|
+
await this._chunkAndStore(processedSource, manifestData);
|
|
193
262
|
}
|
|
194
263
|
|
|
195
264
|
const manifest = new Manifest(manifestData);
|
|
@@ -210,12 +279,70 @@ export default class CasService extends EventEmitter {
|
|
|
210
279
|
* @returns {Promise<string>} Git OID of the created tree.
|
|
211
280
|
*/
|
|
212
281
|
async createTree({ manifest }) {
|
|
282
|
+
const chunks = manifest.chunks;
|
|
283
|
+
|
|
284
|
+
if (chunks.length > this.merkleThreshold) {
|
|
285
|
+
return await this._createMerkleTree({ manifest });
|
|
286
|
+
}
|
|
287
|
+
|
|
213
288
|
const serializedManifest = this.codec.encode(manifest.toJSON());
|
|
214
289
|
const manifestOid = await this.persistence.writeBlob(serializedManifest);
|
|
215
290
|
|
|
216
291
|
const treeEntries = [
|
|
217
292
|
`100644 blob ${manifestOid}\tmanifest.${this.codec.extension}`,
|
|
218
|
-
...
|
|
293
|
+
...chunks.map((c) => `100644 blob ${c.blob}\t${c.digest}`),
|
|
294
|
+
];
|
|
295
|
+
|
|
296
|
+
return await this.persistence.writeTree(treeEntries);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Creates a Merkle tree by splitting chunks into sub-manifests.
|
|
301
|
+
* @private
|
|
302
|
+
* @param {Object} options
|
|
303
|
+
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
304
|
+
* @returns {Promise<string>} Git tree OID.
|
|
305
|
+
*/
|
|
306
|
+
async _createMerkleTree({ manifest }) {
|
|
307
|
+
const chunks = [...manifest.chunks];
|
|
308
|
+
const subManifestRefs = [];
|
|
309
|
+
const chunkBlobEntries = [];
|
|
310
|
+
|
|
311
|
+
for (let i = 0; i < chunks.length; i += this.merkleThreshold) {
|
|
312
|
+
const group = chunks.slice(i, i + this.merkleThreshold);
|
|
313
|
+
const subManifestData = { chunks: group.map((c) => ({ index: c.index, size: c.size, digest: c.digest, blob: c.blob })) };
|
|
314
|
+
const serialized = this.codec.encode(subManifestData);
|
|
315
|
+
const oid = await this.persistence.writeBlob(serialized);
|
|
316
|
+
|
|
317
|
+
subManifestRefs.push({
|
|
318
|
+
oid,
|
|
319
|
+
chunkCount: group.length,
|
|
320
|
+
startIndex: i,
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
for (const c of group) {
|
|
324
|
+
chunkBlobEntries.push(`100644 blob ${c.blob}\t${c.digest}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const rootManifestData = {
|
|
329
|
+
...manifest.toJSON(),
|
|
330
|
+
version: 2,
|
|
331
|
+
chunks: [],
|
|
332
|
+
subManifests: subManifestRefs,
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
const serializedRoot = this.codec.encode(rootManifestData);
|
|
336
|
+
const rootOid = await this.persistence.writeBlob(serializedRoot);
|
|
337
|
+
|
|
338
|
+
const subManifestEntries = subManifestRefs.map(
|
|
339
|
+
(ref, idx) => `100644 blob ${ref.oid}\tsub-manifest-${idx}.${this.codec.extension}`,
|
|
340
|
+
);
|
|
341
|
+
|
|
342
|
+
const treeEntries = [
|
|
343
|
+
`100644 blob ${rootOid}\tmanifest.${this.codec.extension}`,
|
|
344
|
+
...subManifestEntries,
|
|
345
|
+
...chunkBlobEntries,
|
|
219
346
|
];
|
|
220
347
|
|
|
221
348
|
return await this.persistence.writeTree(treeEntries);
|
|
@@ -250,6 +377,50 @@ export default class CasService extends EventEmitter {
|
|
|
250
377
|
return buffers;
|
|
251
378
|
}
|
|
252
379
|
|
|
380
|
+
/**
|
|
381
|
+
* Resolves the encryption key from a passphrase using KDF params from the manifest.
|
|
382
|
+
* @private
|
|
383
|
+
* @param {string} passphrase
|
|
384
|
+
* @param {Object} kdf - KDF params from manifest.encryption.kdf.
|
|
385
|
+
* @returns {Promise<Buffer>}
|
|
386
|
+
*/
|
|
387
|
+
async _resolveKeyFromPassphrase(passphrase, kdf) {
|
|
388
|
+
const { key } = await this.deriveKey({
|
|
389
|
+
passphrase,
|
|
390
|
+
salt: Buffer.from(kdf.salt, 'base64'),
|
|
391
|
+
algorithm: kdf.algorithm,
|
|
392
|
+
iterations: kdf.iterations,
|
|
393
|
+
cost: kdf.cost,
|
|
394
|
+
blockSize: kdf.blockSize,
|
|
395
|
+
parallelization: kdf.parallelization,
|
|
396
|
+
});
|
|
397
|
+
return key;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Resolves the encryption key from passphrase or validates the provided key.
|
|
402
|
+
* @private
|
|
403
|
+
*/
|
|
404
|
+
async _resolveEncryptionKey(manifest, encryptionKey, passphrase) {
|
|
405
|
+
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
406
|
+
|
|
407
|
+
if (passphrase) {
|
|
408
|
+
if (manifest.encryption?.kdf) {
|
|
409
|
+
return this._resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
|
|
410
|
+
}
|
|
411
|
+
throw new CasError(
|
|
412
|
+
'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
|
|
413
|
+
'MISSING_KEY',
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
if (encryptionKey) {
|
|
417
|
+
this._validateKey(encryptionKey);
|
|
418
|
+
} else if (manifest.encryption?.encrypted) {
|
|
419
|
+
throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
|
|
420
|
+
}
|
|
421
|
+
return encryptionKey;
|
|
422
|
+
}
|
|
423
|
+
|
|
253
424
|
/**
|
|
254
425
|
* Restores a file from its manifest by reading and reassembling chunks.
|
|
255
426
|
*
|
|
@@ -259,35 +430,31 @@ export default class CasService extends EventEmitter {
|
|
|
259
430
|
* @param {Object} options
|
|
260
431
|
* @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
261
432
|
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
433
|
+
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
262
434
|
* @returns {Promise<{ buffer: Buffer, bytesWritten: number }>}
|
|
263
435
|
* @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
|
|
264
436
|
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
265
437
|
*/
|
|
266
|
-
async restore({ manifest, encryptionKey }) {
|
|
267
|
-
|
|
268
|
-
this._validateKey(encryptionKey);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
if (manifest.encryption?.encrypted && !encryptionKey) {
|
|
272
|
-
throw new CasError(
|
|
273
|
-
'Encryption key required to restore encrypted content',
|
|
274
|
-
'MISSING_KEY',
|
|
275
|
-
);
|
|
276
|
-
}
|
|
438
|
+
async restore({ manifest, encryptionKey, passphrase }) {
|
|
439
|
+
const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
|
|
277
440
|
|
|
278
441
|
if (manifest.chunks.length === 0) {
|
|
279
442
|
return { buffer: Buffer.alloc(0), bytesWritten: 0 };
|
|
280
443
|
}
|
|
281
444
|
|
|
282
|
-
|
|
283
|
-
let buffer = Buffer.concat(chunks);
|
|
445
|
+
let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
|
|
284
446
|
|
|
285
447
|
if (manifest.encryption?.encrypted) {
|
|
286
|
-
buffer = await this.decrypt({
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
448
|
+
buffer = await this.decrypt({ buffer, key, meta: manifest.encryption });
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if (manifest.compression) {
|
|
452
|
+
try {
|
|
453
|
+
buffer = await gunzipAsync(buffer);
|
|
454
|
+
} catch (err) {
|
|
455
|
+
if (err instanceof CasError) { throw err; }
|
|
456
|
+
throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
|
|
457
|
+
}
|
|
291
458
|
}
|
|
292
459
|
|
|
293
460
|
this.emit('file:restored', {
|
|
@@ -342,9 +509,48 @@ export default class CasService extends EventEmitter {
|
|
|
342
509
|
}
|
|
343
510
|
|
|
344
511
|
const decoded = this.codec.decode(blob);
|
|
512
|
+
|
|
513
|
+
if (decoded.version === 2 && decoded.subManifests?.length > 0) {
|
|
514
|
+
decoded.chunks = await this._resolveSubManifests(decoded.subManifests, treeOid);
|
|
515
|
+
}
|
|
516
|
+
|
|
345
517
|
return new Manifest(decoded);
|
|
346
518
|
}
|
|
347
519
|
|
|
520
|
+
/**
|
|
521
|
+
* Reads and flattens sub-manifest blobs into a single chunk array.
|
|
522
|
+
* @private
|
|
523
|
+
* @param {Array<{ oid: string }>} subManifests - Sub-manifest references.
|
|
524
|
+
* @param {string} treeOid - Parent tree OID (for error context).
|
|
525
|
+
* @returns {Promise<Array>} Flattened chunk entries.
|
|
526
|
+
*/
|
|
527
|
+
async _resolveSubManifests(subManifests, treeOid) {
|
|
528
|
+
const allChunks = [];
|
|
529
|
+
for (const ref of subManifests) {
|
|
530
|
+
const subBlob = await this._readSubManifestBlob(ref.oid, treeOid);
|
|
531
|
+
const subDecoded = this.codec.decode(subBlob);
|
|
532
|
+
allChunks.push(...subDecoded.chunks);
|
|
533
|
+
}
|
|
534
|
+
return allChunks;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Reads a sub-manifest blob, wrapping errors as GIT_ERROR.
|
|
539
|
+
* @private
|
|
540
|
+
*/
|
|
541
|
+
async _readSubManifestBlob(oid, treeOid) {
|
|
542
|
+
try {
|
|
543
|
+
return await this.persistence.readBlob(oid);
|
|
544
|
+
} catch (err) {
|
|
545
|
+
if (err instanceof CasError) { throw err; }
|
|
546
|
+
throw new CasError(
|
|
547
|
+
`Failed to read sub-manifest blob ${oid}: ${err.message}`,
|
|
548
|
+
'GIT_ERROR',
|
|
549
|
+
{ treeOid, subManifestOid: oid, originalError: err },
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
348
554
|
/**
|
|
349
555
|
* Returns deletion metadata for an asset stored in a Git tree.
|
|
350
556
|
* Does not perform any destructive Git operations.
|
|
@@ -386,6 +592,23 @@ export default class CasService extends EventEmitter {
|
|
|
386
592
|
return { referenced, total };
|
|
387
593
|
}
|
|
388
594
|
|
|
595
|
+
/**
|
|
596
|
+
* Derives an encryption key from a passphrase using PBKDF2 or scrypt.
|
|
597
|
+
* @param {Object} options
|
|
598
|
+
* @param {string} options.passphrase - The passphrase to derive a key from.
|
|
599
|
+
* @param {Buffer} [options.salt] - Salt (random if omitted).
|
|
600
|
+
* @param {'pbkdf2'|'scrypt'} [options.algorithm='pbkdf2'] - KDF algorithm.
|
|
601
|
+
* @param {number} [options.iterations] - PBKDF2 iterations.
|
|
602
|
+
* @param {number} [options.cost] - scrypt cost (N).
|
|
603
|
+
* @param {number} [options.blockSize] - scrypt block size (r).
|
|
604
|
+
* @param {number} [options.parallelization] - scrypt parallelization (p).
|
|
605
|
+
* @param {number} [options.keyLength=32] - Derived key length.
|
|
606
|
+
* @returns {Promise<{ key: Buffer, salt: Buffer, params: Object }>}
|
|
607
|
+
*/
|
|
608
|
+
async deriveKey(options) {
|
|
609
|
+
return await this.crypto.deriveKey(options);
|
|
610
|
+
}
|
|
611
|
+
|
|
389
612
|
/**
|
|
390
613
|
* Verifies the integrity of a stored file by re-hashing its chunks.
|
|
391
614
|
* @param {import('../value-objects/Manifest.js').default} manifest
|
|
@@ -1,31 +1,61 @@
|
|
|
1
1
|
import Chunk from "./Chunk.js";
|
|
2
2
|
|
|
3
|
+
/** KDF parameters stored alongside encryption metadata. */
|
|
4
|
+
export interface KdfParams {
|
|
5
|
+
algorithm: "pbkdf2" | "scrypt";
|
|
6
|
+
salt: string;
|
|
7
|
+
iterations?: number;
|
|
8
|
+
cost?: number;
|
|
9
|
+
blockSize?: number;
|
|
10
|
+
parallelization?: number;
|
|
11
|
+
keyLength: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
3
14
|
/** AES-256-GCM encryption metadata attached to an encrypted manifest. */
|
|
4
15
|
export interface EncryptionMeta {
|
|
5
16
|
algorithm: string;
|
|
6
17
|
nonce: string;
|
|
7
18
|
tag: string;
|
|
8
19
|
encrypted: boolean;
|
|
20
|
+
kdf?: KdfParams;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Compression metadata. */
|
|
24
|
+
export interface CompressionMeta {
|
|
25
|
+
algorithm: "gzip";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Sub-manifest reference in a v2 Merkle manifest. */
|
|
29
|
+
export interface SubManifestRef {
|
|
30
|
+
oid: string;
|
|
31
|
+
chunkCount: number;
|
|
32
|
+
startIndex: number;
|
|
9
33
|
}
|
|
10
34
|
|
|
11
35
|
/** Raw manifest data accepted by the {@link Manifest} constructor. */
|
|
12
36
|
export interface ManifestData {
|
|
37
|
+
version?: number;
|
|
13
38
|
slug: string;
|
|
14
39
|
filename: string;
|
|
15
40
|
size: number;
|
|
16
41
|
chunks: Array<{ index: number; size: number; digest: string; blob: string }>;
|
|
17
42
|
encryption?: EncryptionMeta;
|
|
43
|
+
compression?: CompressionMeta;
|
|
44
|
+
subManifests?: SubManifestRef[];
|
|
18
45
|
}
|
|
19
46
|
|
|
20
47
|
/**
|
|
21
48
|
* Immutable value object representing a file manifest.
|
|
22
49
|
*/
|
|
23
50
|
export default class Manifest {
|
|
51
|
+
readonly version: number;
|
|
24
52
|
readonly slug: string;
|
|
25
53
|
readonly filename: string;
|
|
26
54
|
readonly size: number;
|
|
27
55
|
readonly chunks: readonly Chunk[];
|
|
28
56
|
readonly encryption?: EncryptionMeta;
|
|
57
|
+
readonly compression?: CompressionMeta;
|
|
58
|
+
readonly subManifests?: readonly SubManifestRef[];
|
|
29
59
|
|
|
30
60
|
constructor(data: ManifestData);
|
|
31
61
|
|
|
@@ -22,11 +22,14 @@ export default class Manifest {
|
|
|
22
22
|
constructor(data) {
|
|
23
23
|
try {
|
|
24
24
|
ManifestSchema.parse(data);
|
|
25
|
+
this.version = data.version || 1;
|
|
25
26
|
this.slug = data.slug;
|
|
26
27
|
this.filename = data.filename;
|
|
27
28
|
this.size = data.size;
|
|
28
29
|
this.chunks = data.chunks.map((c) => new Chunk(c));
|
|
29
30
|
this.encryption = data.encryption ? { ...data.encryption } : undefined;
|
|
31
|
+
this.compression = data.compression ? { ...data.compression } : undefined;
|
|
32
|
+
this.subManifests = data.subManifests ? data.subManifests.map((s) => ({ ...s })) : undefined;
|
|
30
33
|
Object.freeze(this);
|
|
31
34
|
} catch (error) {
|
|
32
35
|
if (error instanceof ZodError) {
|
|
@@ -42,11 +45,14 @@ export default class Manifest {
|
|
|
42
45
|
*/
|
|
43
46
|
toJSON() {
|
|
44
47
|
return {
|
|
48
|
+
version: this.version,
|
|
45
49
|
slug: this.slug,
|
|
46
50
|
filename: this.filename,
|
|
47
51
|
size: this.size,
|
|
48
52
|
chunks: this.chunks,
|
|
49
53
|
encryption: this.encryption,
|
|
54
|
+
compression: this.compression,
|
|
55
|
+
subManifests: this.subManifests,
|
|
50
56
|
};
|
|
51
57
|
}
|
|
52
58
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { CryptoHasher } from 'bun';
|
|
2
2
|
import CryptoPort from '../../ports/CryptoPort.js';
|
|
3
3
|
import CasError from '../../domain/errors/CasError.js';
|
|
4
|
-
// We still use node:crypto for AES-GCM because Bun's native implementation
|
|
4
|
+
// We still use node:crypto for AES-GCM because Bun's native implementation
|
|
5
5
|
// is heavily optimized for these specific Node APIs.
|
|
6
|
-
import { createCipheriv, createDecipheriv } from 'node:crypto';
|
|
6
|
+
import { createCipheriv, createDecipheriv, pbkdf2, scrypt } from 'node:crypto';
|
|
7
|
+
import { promisify } from 'node:util';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Bun-native {@link CryptoPort} implementation.
|
|
@@ -82,6 +83,38 @@ export default class BunCryptoAdapter extends CryptoPort {
|
|
|
82
83
|
return { encrypt, finalize };
|
|
83
84
|
}
|
|
84
85
|
|
|
86
|
+
/** @override */
|
|
87
|
+
async deriveKey({
|
|
88
|
+
passphrase,
|
|
89
|
+
salt,
|
|
90
|
+
algorithm = 'pbkdf2',
|
|
91
|
+
iterations = 100_000,
|
|
92
|
+
cost = 16384,
|
|
93
|
+
blockSize = 8,
|
|
94
|
+
parallelization = 1,
|
|
95
|
+
keyLength = 32,
|
|
96
|
+
}) {
|
|
97
|
+
const saltBuf = salt || this.randomBytes(32);
|
|
98
|
+
let key;
|
|
99
|
+
const params = { algorithm, salt: Buffer.from(saltBuf).toString('base64'), keyLength };
|
|
100
|
+
|
|
101
|
+
if (algorithm === 'pbkdf2') {
|
|
102
|
+
key = await promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
|
|
103
|
+
params.iterations = iterations;
|
|
104
|
+
} else if (algorithm === 'scrypt') {
|
|
105
|
+
key = await promisify(scrypt)(passphrase, saltBuf, keyLength, {
|
|
106
|
+
N: cost, r: blockSize, p: parallelization,
|
|
107
|
+
});
|
|
108
|
+
params.cost = cost;
|
|
109
|
+
params.blockSize = blockSize;
|
|
110
|
+
params.parallelization = parallelization;
|
|
111
|
+
} else {
|
|
112
|
+
throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return { key, salt: Buffer.from(saltBuf), params };
|
|
116
|
+
}
|
|
117
|
+
|
|
85
118
|
/**
|
|
86
119
|
* Validates that a key is a 32-byte Buffer or Uint8Array.
|
|
87
120
|
* @param {Buffer|Uint8Array} key
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
1
|
+
import { createHash, createCipheriv, createDecipheriv, randomBytes, pbkdf2, scrypt } from 'node:crypto';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
2
3
|
import CryptoPort from '../../ports/CryptoPort.js';
|
|
3
4
|
import CasError from '../../domain/errors/CasError.js';
|
|
4
5
|
|
|
@@ -65,6 +66,44 @@ export default class NodeCryptoAdapter extends CryptoPort {
|
|
|
65
66
|
return { encrypt, finalize };
|
|
66
67
|
}
|
|
67
68
|
|
|
69
|
+
/** @override */
|
|
70
|
+
async deriveKey({
|
|
71
|
+
passphrase,
|
|
72
|
+
salt,
|
|
73
|
+
algorithm = 'pbkdf2',
|
|
74
|
+
iterations = 100_000,
|
|
75
|
+
cost = 16384,
|
|
76
|
+
blockSize = 8,
|
|
77
|
+
parallelization = 1,
|
|
78
|
+
keyLength = 32,
|
|
79
|
+
}) {
|
|
80
|
+
const saltBuf = salt || randomBytes(32);
|
|
81
|
+
let key;
|
|
82
|
+
const params = {
|
|
83
|
+
algorithm,
|
|
84
|
+
salt: Buffer.from(saltBuf).toString('base64'),
|
|
85
|
+
keyLength,
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
if (algorithm === 'pbkdf2') {
|
|
89
|
+
key = await promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
|
|
90
|
+
params.iterations = iterations;
|
|
91
|
+
} else if (algorithm === 'scrypt') {
|
|
92
|
+
key = await promisify(scrypt)(passphrase, saltBuf, keyLength, {
|
|
93
|
+
N: cost,
|
|
94
|
+
r: blockSize,
|
|
95
|
+
p: parallelization,
|
|
96
|
+
});
|
|
97
|
+
params.cost = cost;
|
|
98
|
+
params.blockSize = blockSize;
|
|
99
|
+
params.parallelization = parallelization;
|
|
100
|
+
} else {
|
|
101
|
+
throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return { key, salt: Buffer.from(saltBuf), params };
|
|
105
|
+
}
|
|
106
|
+
|
|
68
107
|
/**
|
|
69
108
|
* Validates that a key is a 32-byte Buffer.
|
|
70
109
|
* @param {Buffer} key
|
|
@@ -117,6 +117,64 @@ export default class WebCryptoAdapter extends CryptoPort {
|
|
|
117
117
|
return { encrypt, finalize };
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/** @override */
|
|
121
|
+
async deriveKey({
|
|
122
|
+
passphrase,
|
|
123
|
+
salt,
|
|
124
|
+
algorithm = 'pbkdf2',
|
|
125
|
+
iterations = 100_000,
|
|
126
|
+
cost = 16384,
|
|
127
|
+
blockSize = 8,
|
|
128
|
+
parallelization = 1,
|
|
129
|
+
keyLength = 32,
|
|
130
|
+
}) {
|
|
131
|
+
const saltBuf = salt || this.randomBytes(32);
|
|
132
|
+
const params = { algorithm, salt: this.#toBase64(saltBuf), keyLength };
|
|
133
|
+
|
|
134
|
+
const opts = { passphrase, saltBuf, iterations, cost, blockSize, parallelization, keyLength, params };
|
|
135
|
+
let key;
|
|
136
|
+
if (algorithm === 'pbkdf2') {
|
|
137
|
+
key = await this.#derivePbkdf2(opts);
|
|
138
|
+
} else if (algorithm === 'scrypt') {
|
|
139
|
+
key = await this.#deriveScrypt(opts);
|
|
140
|
+
} else {
|
|
141
|
+
throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return { key: Buffer.from(key), salt: Buffer.from(saltBuf), params };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async #derivePbkdf2({ passphrase, saltBuf, iterations, keyLength, params }) {
|
|
148
|
+
const enc = new globalThis.TextEncoder();
|
|
149
|
+
const baseKey = await globalThis.crypto.subtle.importKey(
|
|
150
|
+
'raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveBits'],
|
|
151
|
+
);
|
|
152
|
+
const bits = await globalThis.crypto.subtle.deriveBits(
|
|
153
|
+
{ name: 'PBKDF2', salt: saltBuf, iterations, hash: 'SHA-512' },
|
|
154
|
+
baseKey, keyLength * 8,
|
|
155
|
+
);
|
|
156
|
+
params.iterations = iterations;
|
|
157
|
+
return Buffer.from(bits);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async #deriveScrypt({ passphrase, saltBuf, cost, blockSize, parallelization, keyLength, params }) {
|
|
161
|
+
let scryptCb;
|
|
162
|
+
let promisifyFn;
|
|
163
|
+
try {
|
|
164
|
+
({ scrypt: scryptCb } = await import('node:crypto'));
|
|
165
|
+
({ promisify: promisifyFn } = await import('node:util'));
|
|
166
|
+
} catch {
|
|
167
|
+
throw new Error('scrypt KDF requires a Node.js-compatible runtime (node:crypto unavailable)');
|
|
168
|
+
}
|
|
169
|
+
const key = await promisifyFn(scryptCb)(passphrase, saltBuf, keyLength, {
|
|
170
|
+
N: cost, r: blockSize, p: parallelization,
|
|
171
|
+
});
|
|
172
|
+
params.cost = cost;
|
|
173
|
+
params.blockSize = blockSize;
|
|
174
|
+
params.parallelization = parallelization;
|
|
175
|
+
return key;
|
|
176
|
+
}
|
|
177
|
+
|
|
120
178
|
/**
|
|
121
179
|
* Imports a raw key for use with Web Crypto AES-GCM operations.
|
|
122
180
|
* @param {Buffer|Uint8Array} rawKey - 32-byte raw key material.
|
package/src/ports/CryptoPort.js
CHANGED
|
@@ -51,4 +51,21 @@ export default class CryptoPort {
|
|
|
51
51
|
createEncryptionStream(_key) {
|
|
52
52
|
throw new Error('Not implemented');
|
|
53
53
|
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Derives an encryption key from a passphrase using a KDF.
|
|
57
|
+
* @param {Object} options
|
|
58
|
+
* @param {string} options.passphrase - The passphrase to derive a key from.
|
|
59
|
+
* @param {Buffer} [options.salt] - Salt for the KDF (random if omitted).
|
|
60
|
+
* @param {'pbkdf2'|'scrypt'} [options.algorithm='pbkdf2'] - KDF algorithm.
|
|
61
|
+
* @param {number} [options.iterations=100000] - PBKDF2 iteration count.
|
|
62
|
+
* @param {number} [options.cost=16384] - scrypt cost parameter (N).
|
|
63
|
+
* @param {number} [options.blockSize=8] - scrypt block size (r).
|
|
64
|
+
* @param {number} [options.parallelization=1] - scrypt parallelization (p).
|
|
65
|
+
* @param {number} [options.keyLength=32] - Derived key length in bytes.
|
|
66
|
+
* @returns {Promise<{ key: Buffer, salt: Buffer, params: { algorithm: string, salt: string, iterations?: number, cost?: number, blockSize?: number, parallelization?: number, keyLength: number } }>}
|
|
67
|
+
*/
|
|
68
|
+
deriveKey(_options) {
|
|
69
|
+
throw new Error('Not implemented');
|
|
70
|
+
}
|
|
54
71
|
}
|