@git-stunts/git-cas 1.6.0 → 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 CHANGED
@@ -7,6 +7,59 @@ 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
+
43
+ ## [1.6.2] — OIDC publishing + JSR docs coverage (2026-02-07)
44
+
45
+ ### Added
46
+ - JSDoc comments on all exported TypeScript interfaces (`CryptoPort`, `CodecPort`, `GitPersistencePort`, `CasServiceOptions`, `EncryptionMeta`, `ManifestData`, `ContentAddressableStoreOptions`) to reach 100% JSR symbol documentation coverage.
47
+
48
+ ### Fixed
49
+ - npm publish workflow now uses OIDC trusted publishing (no stored token). Upgrades npm to >=11.5.1 at publish time since pnpm does not yet support OIDC natively.
50
+
51
+ ## [1.6.1] — JSR quality fixes (2026-02-07)
52
+
53
+ ### Added
54
+ - TypeScript declaration files (`.d.ts`) for all three entrypoints and shared value objects, resolving JSR "slow types" scoring penalty.
55
+ - `@ts-self-types` directives in `index.js`, `CasService.js`, and `ManifestSchema.js`.
56
+ - `@fileoverview` module doc to `CasService.js` (required by JSR for module docs scoring).
57
+
58
+ ### Fixed
59
+ - JSR package name corrected to `@git-stunts/git-cas`.
60
+ - JSR publication now excludes tests, docs, CI configs, and other non-distribution files via `jsr.json` exclude list.
61
+ - `index.d.ts` added to `package.json` files array for npm distribution.
62
+
10
63
  ## [1.6.0] — M4 Compass + M5 Sonar + M6 Cartographer (2026-02-06)
11
64
 
12
65
  ### 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 ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @module
3
+ * Content Addressable Store — Managed blob storage in Git.
4
+ */
5
+
6
+ import Manifest from "./src/domain/value-objects/Manifest.js";
7
+ import type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef } from "./src/domain/value-objects/Manifest.js";
8
+ import Chunk from "./src/domain/value-objects/Chunk.js";
9
+ import CasService from "./src/domain/services/CasService.js";
10
+ import type {
11
+ CryptoPort,
12
+ CodecPort,
13
+ GitPersistencePort,
14
+ CasServiceOptions,
15
+ DeriveKeyOptions,
16
+ DeriveKeyResult,
17
+ } from "./src/domain/services/CasService.js";
18
+
19
+ export { CasService, Manifest, Chunk };
20
+ export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, CryptoPort, CodecPort, GitPersistencePort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
21
+
22
+ /** Abstract port for cryptographic operations. */
23
+ export declare class CryptoPortBase {
24
+ sha256(buf: Buffer): string | Promise<string>;
25
+ randomBytes(n: number): Buffer;
26
+ encryptBuffer(
27
+ buffer: Buffer,
28
+ key: Buffer,
29
+ ): { buf: Buffer; meta: EncryptionMeta } | Promise<{ buf: Buffer; meta: EncryptionMeta }>;
30
+ decryptBuffer(buffer: Buffer, key: Buffer, meta: EncryptionMeta): Buffer | Promise<Buffer>;
31
+ createEncryptionStream(key: Buffer): {
32
+ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>;
33
+ finalize: () => EncryptionMeta;
34
+ };
35
+ deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
36
+ }
37
+
38
+ /** Abstract port for persisting data to Git's object database. */
39
+ export declare class GitPersistencePortBase {
40
+ writeBlob(content: Buffer | string): Promise<string>;
41
+ writeTree(entries: string[]): Promise<string>;
42
+ readBlob(oid: string): Promise<Buffer>;
43
+ readTree(
44
+ treeOid: string,
45
+ ): Promise<Array<{ mode: string; type: string; oid: string; name: string }>>;
46
+ }
47
+
48
+ /** Git-backed implementation of the persistence port. */
49
+ export declare class GitPersistenceAdapter extends GitPersistencePortBase {
50
+ constructor(options: { plumbing: unknown; policy?: unknown });
51
+ }
52
+
53
+ /** Node.js crypto implementation of CryptoPort. */
54
+ export declare class NodeCryptoAdapter extends CryptoPortBase {
55
+ constructor();
56
+ }
57
+
58
+ /** Abstract codec interface for manifest serialization. */
59
+ export declare class CodecPortBase {
60
+ encode(data: object): Buffer | string;
61
+ decode(buffer: Buffer | string): object;
62
+ get extension(): string;
63
+ }
64
+
65
+ /** JSON codec for manifest serialization. */
66
+ export declare class JsonCodec extends CodecPortBase {
67
+ constructor();
68
+ }
69
+
70
+ /** CBOR codec for manifest serialization. */
71
+ export declare class CborCodec extends CodecPortBase {
72
+ constructor();
73
+ }
74
+
75
+ /** Constructor options for {@link ContentAddressableStore}. */
76
+ export interface ContentAddressableStoreOptions {
77
+ plumbing: unknown;
78
+ chunkSize?: number;
79
+ codec?: CodecPort;
80
+ crypto?: CryptoPort;
81
+ policy?: unknown;
82
+ merkleThreshold?: number;
83
+ }
84
+
85
+ /**
86
+ * High-level facade for the Content Addressable Store library.
87
+ *
88
+ * Wraps CasService with lazy initialization, runtime-adaptive crypto
89
+ * selection, and convenience helpers for file I/O.
90
+ */
91
+ export default class ContentAddressableStore {
92
+ constructor(options: ContentAddressableStoreOptions);
93
+
94
+ get chunkSize(): number;
95
+
96
+ getService(): Promise<CasService>;
97
+
98
+ static createJson(options: {
99
+ plumbing: unknown;
100
+ chunkSize?: number;
101
+ policy?: unknown;
102
+ }): ContentAddressableStore;
103
+
104
+ static createCbor(options: {
105
+ plumbing: unknown;
106
+ chunkSize?: number;
107
+ policy?: unknown;
108
+ }): ContentAddressableStore;
109
+
110
+ encrypt(options: {
111
+ buffer: Buffer;
112
+ key: Buffer;
113
+ }): Promise<{ buf: Buffer; meta: EncryptionMeta }>;
114
+
115
+ decrypt(options: {
116
+ buffer: Buffer;
117
+ key: Buffer;
118
+ meta: EncryptionMeta;
119
+ }): Promise<Buffer>;
120
+
121
+ storeFile(options: {
122
+ filePath: string;
123
+ slug: string;
124
+ filename?: string;
125
+ encryptionKey?: Buffer;
126
+ passphrase?: string;
127
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
128
+ compression?: { algorithm: "gzip" };
129
+ }): Promise<Manifest>;
130
+
131
+ store(options: {
132
+ source: AsyncIterable<Buffer>;
133
+ slug: string;
134
+ filename: string;
135
+ encryptionKey?: Buffer;
136
+ passphrase?: string;
137
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
138
+ compression?: { algorithm: "gzip" };
139
+ }): Promise<Manifest>;
140
+
141
+ restoreFile(options: {
142
+ manifest: Manifest;
143
+ encryptionKey?: Buffer;
144
+ passphrase?: string;
145
+ outputPath: string;
146
+ }): Promise<{ bytesWritten: number }>;
147
+
148
+ restore(options: {
149
+ manifest: Manifest;
150
+ encryptionKey?: Buffer;
151
+ passphrase?: string;
152
+ }): Promise<{ buffer: Buffer; bytesWritten: number }>;
153
+
154
+ createTree(options: { manifest: Manifest }): Promise<string>;
155
+
156
+ verifyIntegrity(manifest: Manifest): Promise<boolean>;
157
+
158
+ readManifest(options: { treeOid: string }): Promise<Manifest>;
159
+
160
+ deleteAsset(options: {
161
+ treeOid: string;
162
+ }): Promise<{ slug: string; chunksOrphaned: number }>;
163
+
164
+ findOrphanedChunks(options: {
165
+ treeOids: string[];
166
+ }): Promise<{ referenced: Set<string>; total: number }>;
167
+
168
+ deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
169
+ }
package/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ /* @ts-self-types="./index.d.ts" */
1
2
  /**
2
3
  * @fileoverview Content Addressable Store - Managed blob storage in Git.
3
4
  */
@@ -54,13 +55,15 @@ export default class ContentAddressableStore {
54
55
  * @param {import('./src/ports/CodecPort.js').default} [options.codec] - Manifest codec (default JsonCodec).
55
56
  * @param {import('./src/ports/CryptoPort.js').default} [options.crypto] - Crypto adapter (auto-detected if omitted).
56
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.
57
59
  */
58
- constructor({ plumbing, chunkSize, codec, policy, crypto }) {
60
+ constructor({ plumbing, chunkSize, codec, policy, crypto, merkleThreshold }) {
59
61
  this.plumbing = plumbing;
60
62
  this.chunkSizeConfig = chunkSize;
61
63
  this.codecConfig = codec;
62
64
  this.policyConfig = policy;
63
65
  this.cryptoConfig = crypto;
66
+ this.merkleThresholdConfig = merkleThreshold;
64
67
  this.service = null;
65
68
  this.#servicePromise = null;
66
69
  }
@@ -95,6 +98,7 @@ export default class ContentAddressableStore {
95
98
  chunkSize: this.chunkSizeConfig,
96
99
  codec: this.codecConfig || new JsonCodec(),
97
100
  crypto,
101
+ merkleThreshold: this.merkleThresholdConfig,
98
102
  });
99
103
  return this.service;
100
104
  }
@@ -175,9 +179,12 @@ export default class ContentAddressableStore {
175
179
  * @param {string} options.slug - Logical identifier for the stored asset.
176
180
  * @param {string} [options.filename] - Override filename (defaults to basename of filePath).
177
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.
178
185
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
179
186
  */
180
- async storeFile({ filePath, slug, filename, encryptionKey }) {
187
+ async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
181
188
  const source = createReadStream(filePath);
182
189
  const service = await this.#getService();
183
190
  return await service.store({
@@ -185,6 +192,9 @@ export default class ContentAddressableStore {
185
192
  slug,
186
193
  filename: filename || path.basename(filePath),
187
194
  encryptionKey,
195
+ passphrase,
196
+ kdfOptions,
197
+ compression,
188
198
  });
189
199
  }
190
200
 
@@ -195,6 +205,9 @@ export default class ContentAddressableStore {
195
205
  * @param {string} options.slug - Logical identifier for the stored asset.
196
206
  * @param {string} options.filename - Filename for the manifest.
197
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.
198
211
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
199
212
  */
200
213
  async store(options) {
@@ -207,14 +220,16 @@ export default class ContentAddressableStore {
207
220
  * @param {Object} options
208
221
  * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
209
222
  * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
223
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
210
224
  * @param {string} options.outputPath - Destination file path.
211
225
  * @returns {Promise<{ bytesWritten: number }>}
212
226
  */
213
- async restoreFile({ manifest, encryptionKey, outputPath }) {
227
+ async restoreFile({ manifest, encryptionKey, passphrase, outputPath }) {
214
228
  const service = await this.#getService();
215
229
  const { buffer, bytesWritten } = await service.restore({
216
230
  manifest,
217
231
  encryptionKey,
232
+ passphrase,
218
233
  });
219
234
  writeFileSync(outputPath, buffer);
220
235
  return { bytesWritten };
@@ -225,6 +240,7 @@ export default class ContentAddressableStore {
225
240
  * @param {Object} options
226
241
  * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
227
242
  * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
243
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
228
244
  * @returns {Promise<{ buffer: Buffer, bytesWritten: number }>}
229
245
  */
230
246
  async restore(options) {
@@ -287,4 +303,22 @@ export default class ContentAddressableStore {
287
303
  const service = await this.#getService();
288
304
  return await service.findOrphanedChunks(options);
289
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
+ }
290
324
  }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "1.6.0",
3
+ "version": "2.0.0",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "bin": {
8
- "git-cas": "./bin/git-cas.js"
8
+ "git-cas": "bin/git-cas.js"
9
9
  },
10
10
  "exports": {
11
11
  ".": "./index.js",
@@ -14,6 +14,7 @@
14
14
  },
15
15
  "files": [
16
16
  "index.js",
17
+ "index.d.ts",
17
18
  "bin/",
18
19
  "src/",
19
20
  "README.md",
@@ -78,4 +79,4 @@
78
79
  "prettier": "^3.4.2",
79
80
  "vitest": "^2.1.8"
80
81
  }
81
- }
82
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @module
3
+ * Zod schemas for validating CAS manifest and chunk data.
4
+ */
5
+
6
+ import { z } from "zod";
7
+
8
+ /** Validates a single chunk entry within a manifest. */
9
+ export declare const ChunkSchema: z.ZodObject<{
10
+ index: z.ZodNumber;
11
+ size: z.ZodNumber;
12
+ digest: z.ZodString;
13
+ blob: z.ZodString;
14
+ }>;
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
+
27
+ /** Validates the encryption metadata attached to an encrypted manifest. */
28
+ export declare const EncryptionSchema: z.ZodObject<{
29
+ algorithm: z.ZodString;
30
+ nonce: z.ZodString;
31
+ tag: z.ZodString;
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;
46
+ }>;
47
+
48
+ /** Validates a complete file manifest. */
49
+ export declare const ManifestSchema: z.ZodObject<{
50
+ version: z.ZodDefault<z.ZodNumber>;
51
+ slug: z.ZodString;
52
+ filename: z.ZodString;
53
+ size: z.ZodNumber;
54
+ chunks: z.ZodArray<typeof ChunkSchema>;
55
+ encryption: z.ZodOptional<typeof EncryptionSchema>;
56
+ compression: z.ZodOptional<typeof CompressionSchema>;
57
+ subManifests: z.ZodOptional<z.ZodArray<typeof SubManifestRefSchema>>;
58
+ }>;
@@ -1,3 +1,4 @@
1
+ /* @ts-self-types="./ManifestSchema.d.ts" */
1
2
  /**
2
3
  * @fileoverview Zod schemas for validating CAS manifest and chunk data.
3
4
  */
@@ -12,19 +13,46 @@ export const ChunkSchema = z.object({
12
13
  blob: z.string().min(1), // Git OID
13
14
  });
14
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
+
15
27
  /** Validates the encryption metadata attached to an encrypted manifest. */
16
28
  export const EncryptionSchema = z.object({
17
29
  algorithm: z.string(),
18
30
  nonce: z.string(),
19
31
  tag: z.string(),
20
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),
21
46
  });
22
47
 
23
48
  /** Validates a complete file manifest. */
24
49
  export const ManifestSchema = z.object({
50
+ version: z.number().int().min(1).max(2).default(1),
25
51
  slug: z.string().min(1),
26
52
  filename: z.string().min(1),
27
53
  size: z.number().int().min(0),
28
54
  chunks: z.array(ChunkSchema),
29
55
  encryption: EncryptionSchema.optional(),
56
+ compression: CompressionSchema.optional(),
57
+ subManifests: z.array(SubManifestRefSchema).optional(),
30
58
  });
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @module
3
+ * Domain service for Content Addressable Storage operations.
4
+ */
5
+
6
+ import { EventEmitter } from "node:events";
7
+ import Manifest from "../value-objects/Manifest.js";
8
+ import type { EncryptionMeta, CompressionMeta, KdfParams } from "../value-objects/Manifest.js";
9
+
10
+ /** Port interface for cryptographic operations (hashing, encryption, random bytes). */
11
+ export interface CryptoPort {
12
+ sha256(buf: Buffer): string | Promise<string>;
13
+ randomBytes(n: number): Buffer;
14
+ encryptBuffer(
15
+ buffer: Buffer,
16
+ key: Buffer,
17
+ ): { buf: Buffer; meta: EncryptionMeta } | Promise<{ buf: Buffer; meta: EncryptionMeta }>;
18
+ decryptBuffer(buffer: Buffer, key: Buffer, meta: EncryptionMeta): Buffer | Promise<Buffer>;
19
+ createEncryptionStream(key: Buffer): {
20
+ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>;
21
+ finalize: () => EncryptionMeta;
22
+ };
23
+ deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
24
+ }
25
+
26
+ /** Port interface for encoding and decoding manifest data. */
27
+ export interface CodecPort {
28
+ encode(data: object): Buffer | string;
29
+ decode(buffer: Buffer | string): object;
30
+ get extension(): string;
31
+ }
32
+
33
+ /** Port interface for persisting data to Git's object database. */
34
+ export interface GitPersistencePort {
35
+ writeBlob(content: Buffer | string): Promise<string>;
36
+ writeTree(entries: string[]): Promise<string>;
37
+ readBlob(oid: string): Promise<Buffer>;
38
+ readTree(
39
+ treeOid: string,
40
+ ): Promise<Array<{ mode: string; type: string; oid: string; name: string }>>;
41
+ }
42
+
43
+ /** Constructor options for {@link CasService}. */
44
+ export interface CasServiceOptions {
45
+ persistence: GitPersistencePort;
46
+ codec: CodecPort;
47
+ crypto: CryptoPort;
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;
69
+ }
70
+
71
+ /**
72
+ * Domain service for Content Addressable Storage operations.
73
+ *
74
+ * Provides chunking, encryption, and integrity verification for storing
75
+ * arbitrary data in Git's object database.
76
+ */
77
+ export default class CasService extends EventEmitter {
78
+ readonly persistence: GitPersistencePort;
79
+ readonly codec: CodecPort;
80
+ readonly crypto: CryptoPort;
81
+ readonly chunkSize: number;
82
+ readonly merkleThreshold: number;
83
+
84
+ constructor(options: CasServiceOptions);
85
+
86
+ encrypt(options: {
87
+ buffer: Buffer;
88
+ key: Buffer;
89
+ }): Promise<{ buf: Buffer; meta: EncryptionMeta }>;
90
+
91
+ decrypt(options: {
92
+ buffer: Buffer;
93
+ key: Buffer;
94
+ meta: EncryptionMeta;
95
+ }): Promise<Buffer>;
96
+
97
+ store(options: {
98
+ source: AsyncIterable<Buffer>;
99
+ slug: string;
100
+ filename: string;
101
+ encryptionKey?: Buffer;
102
+ passphrase?: string;
103
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
104
+ compression?: { algorithm: "gzip" };
105
+ }): Promise<Manifest>;
106
+
107
+ createTree(options: { manifest: Manifest }): Promise<string>;
108
+
109
+ restore(options: {
110
+ manifest: Manifest;
111
+ encryptionKey?: Buffer;
112
+ passphrase?: string;
113
+ }): Promise<{ buffer: Buffer; bytesWritten: number }>;
114
+
115
+ readManifest(options: { treeOid: string }): Promise<Manifest>;
116
+
117
+ deleteAsset(options: {
118
+ treeOid: string;
119
+ }): Promise<{ slug: string; chunksOrphaned: number }>;
120
+
121
+ findOrphanedChunks(options: {
122
+ treeOids: string[];
123
+ }): Promise<{ referenced: Set<string>; total: number }>;
124
+
125
+ verifyIntegrity(manifest: Manifest): Promise<boolean>;
126
+
127
+ deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
128
+ }
@@ -1,7 +1,17 @@
1
+ /* @ts-self-types="./CasService.d.ts" */
2
+ /**
3
+ * @fileoverview Domain service for Content Addressable Storage operations.
4
+ * @module
5
+ */
1
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';
2
10
  import Manifest from '../value-objects/Manifest.js';
3
11
  import CasError from '../errors/CasError.js';
4
12
 
13
+ const gunzipAsync = promisify(gunzip);
14
+
5
15
  /**
6
16
  * Domain service for Content Addressable Storage operations.
7
17
  *
@@ -24,8 +34,9 @@ export default class CasService extends EventEmitter {
24
34
  * @param {import('../../ports/CodecPort.js').default} options.codec
25
35
  * @param {import('../../ports/CryptoPort.js').default} options.crypto
26
36
  * @param {number} [options.chunkSize=262144] - 256 KiB
37
+ * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
27
38
  */
28
- constructor({ persistence, codec, crypto, chunkSize = 256 * 1024 }) {
39
+ constructor({ persistence, codec, crypto, chunkSize = 256 * 1024, merkleThreshold = 1000 }) {
29
40
  super();
30
41
  if (chunkSize < 1024) {
31
42
  throw new Error('Chunk size must be at least 1024 bytes');
@@ -34,6 +45,10 @@ export default class CasService extends EventEmitter {
34
45
  this.codec = codec;
35
46
  this.crypto = crypto;
36
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;
37
52
  }
38
53
 
39
54
  /**
@@ -154,6 +169,47 @@ export default class CasService extends EventEmitter {
154
169
  }
155
170
  }
156
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
+
157
213
  /**
158
214
  * Chunks an async iterable source and stores it in Git.
159
215
  *
@@ -165,26 +221,44 @@ export default class CasService extends EventEmitter {
165
221
  * @param {string} options.slug
166
222
  * @param {string} options.filename
167
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.
168
227
  * @returns {Promise<import('../value-objects/Manifest.js').default>}
169
228
  */
170
- 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
+
171
240
  if (encryptionKey) {
172
241
  this._validateKey(encryptionKey);
173
242
  }
174
243
 
175
- const manifestData = {
176
- slug,
177
- filename,
178
- size: 0,
179
- chunks: [],
180
- };
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
+ }
181
251
 
182
252
  if (encryptionKey) {
183
253
  const { encrypt, finalize } = this.crypto.createEncryptionStream(encryptionKey);
184
- await this._chunkAndStore(encrypt(source), manifestData);
185
- manifestData.encryption = finalize();
254
+ await this._chunkAndStore(encrypt(processedSource), manifestData);
255
+ const encMeta = finalize();
256
+ if (kdfParams) {
257
+ encMeta.kdf = kdfParams;
258
+ }
259
+ manifestData.encryption = encMeta;
186
260
  } else {
187
- await this._chunkAndStore(source, manifestData);
261
+ await this._chunkAndStore(processedSource, manifestData);
188
262
  }
189
263
 
190
264
  const manifest = new Manifest(manifestData);
@@ -205,12 +279,70 @@ export default class CasService extends EventEmitter {
205
279
  * @returns {Promise<string>} Git OID of the created tree.
206
280
  */
207
281
  async createTree({ manifest }) {
282
+ const chunks = manifest.chunks;
283
+
284
+ if (chunks.length > this.merkleThreshold) {
285
+ return await this._createMerkleTree({ manifest });
286
+ }
287
+
208
288
  const serializedManifest = this.codec.encode(manifest.toJSON());
209
289
  const manifestOid = await this.persistence.writeBlob(serializedManifest);
210
290
 
211
291
  const treeEntries = [
212
292
  `100644 blob ${manifestOid}\tmanifest.${this.codec.extension}`,
213
- ...manifest.chunks.map((c) => `100644 blob ${c.blob}\t${c.digest}`),
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,
214
346
  ];
215
347
 
216
348
  return await this.persistence.writeTree(treeEntries);
@@ -245,6 +377,50 @@ export default class CasService extends EventEmitter {
245
377
  return buffers;
246
378
  }
247
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
+
248
424
  /**
249
425
  * Restores a file from its manifest by reading and reassembling chunks.
250
426
  *
@@ -254,35 +430,31 @@ export default class CasService extends EventEmitter {
254
430
  * @param {Object} options
255
431
  * @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
256
432
  * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
433
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
257
434
  * @returns {Promise<{ buffer: Buffer, bytesWritten: number }>}
258
435
  * @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
259
436
  * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
260
437
  */
261
- async restore({ manifest, encryptionKey }) {
262
- if (encryptionKey) {
263
- this._validateKey(encryptionKey);
264
- }
265
-
266
- if (manifest.encryption?.encrypted && !encryptionKey) {
267
- throw new CasError(
268
- 'Encryption key required to restore encrypted content',
269
- 'MISSING_KEY',
270
- );
271
- }
438
+ async restore({ manifest, encryptionKey, passphrase }) {
439
+ const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
272
440
 
273
441
  if (manifest.chunks.length === 0) {
274
442
  return { buffer: Buffer.alloc(0), bytesWritten: 0 };
275
443
  }
276
444
 
277
- const chunks = await this._readAndVerifyChunks(manifest.chunks);
278
- let buffer = Buffer.concat(chunks);
445
+ let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
279
446
 
280
447
  if (manifest.encryption?.encrypted) {
281
- buffer = await this.decrypt({
282
- buffer,
283
- key: encryptionKey,
284
- meta: manifest.encryption,
285
- });
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
+ }
286
458
  }
287
459
 
288
460
  this.emit('file:restored', {
@@ -337,9 +509,48 @@ export default class CasService extends EventEmitter {
337
509
  }
338
510
 
339
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
+
340
517
  return new Manifest(decoded);
341
518
  }
342
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
+
343
554
  /**
344
555
  * Returns deletion metadata for an asset stored in a Git tree.
345
556
  * Does not perform any destructive Git operations.
@@ -381,6 +592,23 @@ export default class CasService extends EventEmitter {
381
592
  return { referenced, total };
382
593
  }
383
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
+
384
612
  /**
385
613
  * Verifies the integrity of a stored file by re-hashing its chunks.
386
614
  * @param {import('../value-objects/Manifest.js').default} manifest
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Immutable value object representing a single content chunk.
3
+ */
4
+ export default class Chunk {
5
+ readonly index: number;
6
+ readonly size: number;
7
+ readonly digest: string;
8
+ readonly blob: string;
9
+
10
+ constructor(data: {
11
+ index: number;
12
+ size: number;
13
+ digest: string;
14
+ blob: string;
15
+ });
16
+ }
@@ -0,0 +1,63 @@
1
+ import Chunk from "./Chunk.js";
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
+
14
+ /** AES-256-GCM encryption metadata attached to an encrypted manifest. */
15
+ export interface EncryptionMeta {
16
+ algorithm: string;
17
+ nonce: string;
18
+ tag: string;
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;
33
+ }
34
+
35
+ /** Raw manifest data accepted by the {@link Manifest} constructor. */
36
+ export interface ManifestData {
37
+ version?: number;
38
+ slug: string;
39
+ filename: string;
40
+ size: number;
41
+ chunks: Array<{ index: number; size: number; digest: string; blob: string }>;
42
+ encryption?: EncryptionMeta;
43
+ compression?: CompressionMeta;
44
+ subManifests?: SubManifestRef[];
45
+ }
46
+
47
+ /**
48
+ * Immutable value object representing a file manifest.
49
+ */
50
+ export default class Manifest {
51
+ readonly version: number;
52
+ readonly slug: string;
53
+ readonly filename: string;
54
+ readonly size: number;
55
+ readonly chunks: readonly Chunk[];
56
+ readonly encryption?: EncryptionMeta;
57
+ readonly compression?: CompressionMeta;
58
+ readonly subManifests?: readonly SubManifestRef[];
59
+
60
+ constructor(data: ManifestData);
61
+
62
+ toJSON(): ManifestData;
63
+ }
@@ -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.
@@ -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
  }