@git-stunts/git-cas 5.3.2 → 6.0.1

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.
Files changed (173) hide show
  1. package/ADVANCED_GUIDE.md +1027 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +449 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +926 -0
  6. package/README.md +106 -366
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +1255 -212
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +367 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2254 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +273 -80
  60. package/index.js +220 -59
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +153 -53
  103. package/src/domain/services/CasService.js +322 -837
  104. package/src/domain/services/ChunkRepository.js +268 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +180 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +10 -6
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
@@ -0,0 +1,33 @@
1
+ # git-cas Encryption Modes
2
+
3
+ `git-cas` supports three distinct envelope encryption schemes, each optimized for different security and performance profiles.
4
+
5
+ | Mode | Integrity | Privacy | Deduplication | Use Case |
6
+ | :--- | :--- | :--- | :--- | :--- |
7
+ | **Whole** | Full Object | High | None | Small sensitive files (keys, configs). |
8
+ | **Framed** | Per-Frame | High | None | Standard large assets. Prevents blob swapping. |
9
+ | **Convergent**| Block-Level | Medium | **High** | Shared libraries or public binaries where storage cost is priority. |
10
+
11
+ ## 1. Whole-Object Encryption (`whole`)
12
+ The entire file is encrypted as a single ciphertext.
13
+ - **Mechanism:** AES-256-GCM with a random 96-bit nonce.
14
+ - **Deduplication:** None (each store creates a unique ciphertext even for identical content).
15
+ - **Integrity:** The GCM auth tag covers the entire object.
16
+
17
+ ## 2. Framed Encryption (`framed`)
18
+ The default for v6.0.0. The file is split into chunks, and each chunk is encrypted as an independent AES-GCM "frame".
19
+ - **Mechanism:** AES-256-GCM. The frame index is bound to the AAD (Additional Authenticated Data).
20
+ - **Integrity Guarantee:** Prevents "Replay Attacks" or blob-swapping between different manifests, as each frame's metadata is cryptographically bound to its position in the asset.
21
+ - **Deduplication:** None.
22
+
23
+ ## 3. Convergent Encryption (`convergent`)
24
+ Allows deduplication across different files or versions while still providing encryption at rest.
25
+ - **Mechanism:** The encryption key is derived from the SHA-256 hash of the content itself.
26
+ - **Trade-off:** Vulnerable to "Confirmation Attacks" (an attacker who guesses the content can verify its presence in the CAS).
27
+ - **Deduplication:** **Global**. Identical chunks across any file share the same ciphertext and OID.
28
+
29
+ ## Key Management
30
+ All modes use **Envelope Encryption**:
31
+ 1. A **Data Encryption Key (DEK)** is generated per asset (or per chunk).
32
+ 2. The DEK is encrypted for one or more **Key Encryption Keys (KEKs)** (e.g., passphrases or OS keys).
33
+ 3. The encrypted DEK is stored in the manifest or vault metadata.
@@ -0,0 +1,174 @@
1
+ # Extending `git-cas`
2
+
3
+ This guide describes supported extension points for applications that need
4
+ custom persistence, codecs, chunking, compression, crypto, or observability.
5
+
6
+ Most users should start with the facade:
7
+
8
+ ```js
9
+ import GitPlumbing from '@git-stunts/plumbing';
10
+ import ContentAddressableStore from '@git-stunts/git-cas';
11
+
12
+ const plumbing = await GitPlumbing.createDefault({ cwd: '.' });
13
+ const cas = ContentAddressableStore.createJson({ plumbing });
14
+ ```
15
+
16
+ Construct `CasService` directly only when you own the complete adapter boundary
17
+ or are writing focused tests.
18
+
19
+ ## Extension Points
20
+
21
+ | Area | Preferred Entry | Contract |
22
+ | --- | --- | --- |
23
+ | Persistence | Custom `GitPersistencePort` implementation | Blob/tree read and write, plus streaming reads |
24
+ | Refs | Custom `GitRefPort` implementation | Ref resolution, commit creation, atomic updates |
25
+ | Codecs | `codec` option or direct `CasService` injection | `encode()`, `decode()`, and `extension` |
26
+ | Chunking | Facade chunking config or `ChunkingPort` injection | Async chunk iteration with stable strategy metadata |
27
+ | Compression | `compressionAdapter` injection | gzip-compatible buffer and stream methods |
28
+ | Crypto | `crypto` injection | SHA-256, AES-GCM, HMAC, KDF, and stream capability reporting |
29
+ | Observability | `observability` injection | `metric()`, `log()`, and `span()` |
30
+
31
+ See [ADVANCED_GUIDE.md](../ADVANCED_GUIDE.md#direct-casservice-and-custom-port-contracts)
32
+ for the full direct-construction contract and
33
+ [docs/API.md](./API.md#ports) for method-level API details.
34
+
35
+ ## Direct Service Construction
36
+
37
+ Direct construction requires every domain dependency. The facade supplies these
38
+ defaults for normal Git-backed use; direct callers must supply them explicitly.
39
+
40
+ ```js
41
+ import {
42
+ FixedChunker,
43
+ JsonCodec,
44
+ NodeCompressionAdapter,
45
+ NodeCryptoAdapter,
46
+ SilentObserver,
47
+ } from '@git-stunts/git-cas';
48
+ import CasService from '@git-stunts/git-cas/service';
49
+
50
+ const service = new CasService({
51
+ persistence,
52
+ codec: new JsonCodec(),
53
+ crypto: new NodeCryptoAdapter(),
54
+ observability: new SilentObserver(),
55
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
56
+ compressionAdapter: new NodeCompressionAdapter(),
57
+ formatVersion: '6.0.0',
58
+ });
59
+ ```
60
+
61
+ The domain byte contract is `Uint8Array`. Node `Buffer` values work at Node
62
+ boundaries because `Buffer` extends `Uint8Array`, but portable adapters should
63
+ not require Buffer-only APIs.
64
+
65
+ ## Persistence Adapter Requirements
66
+
67
+ Custom persistence adapters must preserve Git-like object semantics:
68
+
69
+ - `writeBlob(bytes)` stores immutable bytes and returns the blob OID
70
+ - `readBlob(oid, maxBytes?)` returns the exact bytes written for that OID and
71
+ should reject invalid positive-integer limits before opening the blob stream
72
+ - `writeTree(entries)` writes named tree entries and returns a tree OID
73
+ - `readTree(treeOid)` returns mode/type/OID/name entries
74
+ - `readBlobStream(oid)` returns an async iterable or readable stream of bytes
75
+ - `setMaxBlobSize(maxBlobSize)` optionally applies the service-level metadata
76
+ blob safety limit inside adapters that can enforce it natively
77
+
78
+ `readBlobStream()` is required for bounded restore paths. Encrypted or
79
+ compressed restores can otherwise require full ciphertext buffering and will
80
+ fail with `PERSISTENCE_CAPABILITY_REQUIRED` when the adapter cannot provide the
81
+ streaming read capability safely.
82
+
83
+ ## Codec Requirements
84
+
85
+ A codec serializes and deserializes manifest objects:
86
+
87
+ ```js
88
+ const encoder = new TextEncoder();
89
+ const decoder = new TextDecoder();
90
+
91
+ class MyCodec {
92
+ get extension() {
93
+ return 'myfmt';
94
+ }
95
+
96
+ encode(value) {
97
+ return encoder.encode(JSON.stringify(value));
98
+ }
99
+
100
+ decode(bytes) {
101
+ return JSON.parse(decoder.decode(bytes));
102
+ }
103
+ }
104
+ ```
105
+
106
+ Codec output is part of the manifest integrity hash. Keep encoding
107
+ deterministic across platforms and versions. If a codec changes its canonical
108
+ output, old manifests may fail integrity verification.
109
+
110
+ ## Chunking Requirements
111
+
112
+ Chunkers expose `chunk(source)` and return ordered chunks with byte content and
113
+ metadata. Stable ordering is mandatory because manifests record chunk order.
114
+
115
+ Use `FixedChunker` for predictable block boundaries. Use `CdcChunker` for
116
+ deduplication workloads where insertions and deletions should not shift every
117
+ downstream chunk.
118
+
119
+ ## Compression Adapter Requirements
120
+
121
+ Compression adapters provide both buffer and stream forms:
122
+
123
+ - `compressBuffer(bytes)`
124
+ - `decompressBuffer(bytes)`
125
+ - `compressStream(source)`
126
+ - `decompressStream(source)`
127
+
128
+ The manifest schema currently supports `gzip`. Custom adapters should preserve
129
+ the same algorithm name unless a future schema explicitly adds another
130
+ compression algorithm.
131
+
132
+ ## Crypto Adapter Requirements
133
+
134
+ Crypto adapters implement hashing, random bytes, AES-256-GCM, HMAC, KDF, and
135
+ stream encryption/decryption where supported. Runtime limitations must surface
136
+ as explicit capability errors rather than silent fallback.
137
+
138
+ Notable requirements:
139
+
140
+ - AES-GCM nonces are 12 bytes.
141
+ - GCM tags are 16 bytes.
142
+ - PBKDF2 must derive 32-byte keys with policy-bounded parameters.
143
+ - scrypt support is runtime-dependent; Web Crypto runtimes should report a
144
+ capability error instead of pretending to support it.
145
+
146
+ ## Observability Adapter Requirements
147
+
148
+ Observability is intentionally narrow:
149
+
150
+ ```js
151
+ const observer = {
152
+ metric(name, value, tags) {},
153
+ log(level, message, context) {},
154
+ span(name, context) {
155
+ return { end(status) {} };
156
+ },
157
+ };
158
+ ```
159
+
160
+ Use this for progress, warnings, and release-readiness telemetry. Do not put
161
+ business logic in observers; observers should be replaceable without changing
162
+ storage behavior.
163
+
164
+ ## Compatibility Checklist
165
+
166
+ Before shipping a custom adapter:
167
+
168
+ - run the relevant unit tests against the adapter
169
+ - verify `storeFile()` and `restoreFile()` round trips with binary data
170
+ - verify encrypted `whole`, `framed`, and `convergent` restores
171
+ - verify gzip restore if compression is enabled
172
+ - verify large restores do not exceed configured buffer limits
173
+ - verify errors are `CasError` instances with actionable `code` values
174
+ - document runtime-specific limits and unsupported methods
@@ -0,0 +1,199 @@
1
+ # Store And Restore Pipeline State Machines
2
+
3
+ This document is the maintainer map for the `CasService` store and restore
4
+ paths. It explains the behavioral states that must remain stable while
5
+ `CasService.js` is being decomposed into smaller services.
6
+
7
+ The public facade (`ContentAddressableStore`) wires adapters and convenience
8
+ file helpers. The domain service owns byte validation, chunk dispatch,
9
+ encryption routing, manifest construction, integrity checks, and restore plan
10
+ selection. Git tree publication and vault mutation are adjacent workflows, not
11
+ part of the core byte pipeline.
12
+
13
+ ## Store State Machine
14
+
15
+ The store pipeline begins at `CasService.store()` and ends with a `Manifest`
16
+ value object. It does not publish a Git tree or update the vault by itself.
17
+
18
+ ### State: Validate Input
19
+
20
+ Inputs are validated before any Git object is written. The service verifies that
21
+ the source is async-iterable, the slug and filename are usable manifest values,
22
+ compression options are supported, and encryption key sources are mutually
23
+ exclusive. This state must remain side-effect free.
24
+
25
+ Exit conditions:
26
+
27
+ - Invalid source, slug, filename, compression, or credential combinations fail
28
+ before chunk writes begin.
29
+ - Valid inputs advance to key and scheme resolution.
30
+
31
+ ### State: Resolve Encryption
32
+
33
+ The key resolver converts store credentials into either no key, a direct key, a
34
+ passphrase-derived key, or envelope recipient metadata. The encryption scheme is
35
+ then selected.
36
+
37
+ Scheme rules:
38
+
39
+ - No key means plaintext storage.
40
+ - Fixed chunking plus encryption defaults to `framed`.
41
+ - CDC chunking plus encryption defaults to deterministic `convergent`.
42
+ - Explicit `whole`, `framed`, or `convergent` scheme selections win.
43
+ - `encryption.convergent: false` opts CDC callers out of convergent mode and
44
+ uses `framed`.
45
+
46
+ Required warnings:
47
+
48
+ - CDC plus implicit `convergent` emits a warning because deterministic
49
+ ciphertext can reveal content equality.
50
+ - CDC plus non-convergent encryption emits a warning because ciphertext defeats
51
+ CDC deduplication.
52
+
53
+ ### State: Prepare Source
54
+
55
+ The source remains streaming unless compression or encryption requires a
56
+ specific transform. Compression wraps the source before encryption selection is
57
+ dispatched. This keeps the manifest model consistent: manifests describe the
58
+ stored byte shape, not just the caller's original input bytes.
59
+
60
+ Exit conditions:
61
+
62
+ - Plain and convergent stores pass the prepared source into chunk dispatch.
63
+ - Framed stores transform the source into authenticated frame records before
64
+ chunk dispatch.
65
+ - Whole encryption buffers the prepared source before writing encrypted bytes.
66
+
67
+ ### State: Dispatch Chunks
68
+
69
+ The chunk dispatcher is responsible for concurrency, chunk indexing, digest
70
+ calculation, blob writes, orphan tracking, and `chunk:stored` metrics. It is the
71
+ shared path for plaintext, convergent, framed, compressed, and most transformed
72
+ stores.
73
+
74
+ Invariants:
75
+
76
+ - Manifest chunk order follows source order even when blob writes run with
77
+ concurrency.
78
+ - `STORE_ERROR` includes failed-index and orphaned-blob metadata when writes
79
+ fail after earlier chunks were persisted.
80
+ - Convergent mode encrypts each plaintext chunk after calculating its plaintext
81
+ digest, then writes the ciphertext plus authentication tag.
82
+ - Plain and framed modes write the bytes they receive from their upstream
83
+ source transform.
84
+
85
+ ### State: Finalize Manifest
86
+
87
+ The manifest is finalized only after chunk dispatch succeeds. Store metadata is
88
+ assembled from the chosen chunker, compression settings, encryption metadata,
89
+ format version, size totals, and chunk references.
90
+
91
+ Exit conditions:
92
+
93
+ - A successful store returns a `Manifest`.
94
+ - `file:stored` is emitted after the manifest is constructed.
95
+ - No tree or vault state is changed by `store()`.
96
+
97
+ ## Restore State Machine
98
+
99
+ The restore pipeline begins with a manifest and produces either an async byte
100
+ stream, an in-memory `Uint8Array`, or a verified file on disk.
101
+
102
+ ### State: Validate Manifest
103
+
104
+ Restore first validates encryption metadata, compression metadata, and key
105
+ requirements. Invalid or legacy scheme metadata fails before chunk reads begin.
106
+
107
+ Exit conditions:
108
+
109
+ - Plain manifests can restore without credentials.
110
+ - Encrypted manifests require a matching direct key, passphrase-derived key, or
111
+ recipient-unwrapped key.
112
+ - Legacy scheme identifiers fail in normal mode and require migration.
113
+
114
+ ### State: Select Restore Plan
115
+
116
+ Restore selects one of the named restore plans based on encryption,
117
+ compression, and available adapter capabilities.
118
+
119
+ Plan families:
120
+
121
+ - `streaming`: plaintext uncompressed data streams chunk-by-chunk.
122
+ - `compressed-streaming`: plaintext compressed data streams through the
123
+ compression adapter.
124
+ - `framed`: framed encrypted data authenticates each frame while streaming.
125
+ - `framed-compressed`: framed encrypted compressed data authenticates frames,
126
+ then decompresses.
127
+ - `convergent`: convergent encrypted chunks decrypt and verify independently.
128
+ - `convergent-compressed`: convergent decrypts chunk-by-chunk, then
129
+ decompresses.
130
+ - `buffered`: whole-object encrypted or compression-buffered data enforces
131
+ `maxRestoreBufferSize`.
132
+
133
+ ### State: Verify And Emit Bytes
134
+
135
+ Every restore plan verifies chunk digests or authentication before exposing the
136
+ corresponding plaintext bytes to the caller. `restoreStream()` emits verified
137
+ chunks as they become available. `restore()` materializes those bytes into a
138
+ single `Uint8Array`. `restoreFile()` writes tentative output and only renames it
139
+ into place after verification succeeds.
140
+
141
+ Invariants:
142
+
143
+ - Wrong keys fail with integrity errors.
144
+ - Oversized buffered restore paths fail before unbounded memory growth.
145
+ - `chunk:restored`, `file:restored`, `integrity:pass`, `integrity:fail`, and
146
+ `error` events remain observable at the same semantic points.
147
+ - Callers never receive unauthenticated encrypted plaintext as final output.
148
+
149
+ ## Tree And Vault Publication Boundaries
150
+
151
+ `createTree()` publishes a manifest and chunk references as a Git tree. It is a
152
+ separate state machine from `store()` because callers may inspect, diff, or
153
+ discard a manifest before publication.
154
+
155
+ Tree publication states:
156
+
157
+ - Encode manifest data with the selected codec.
158
+ - Add manifest integrity hash before writing manifest bytes.
159
+ - Write flat trees when the chunk count is below `merkleThreshold`.
160
+ - Write sub-manifests and a root Merkle manifest when the chunk count exceeds
161
+ `merkleThreshold`.
162
+ - Write chunk entries using Git tree-entry formatting.
163
+
164
+ Vault publication states:
165
+
166
+ - `initVault()` creates or reuses the vault ref.
167
+ - `addToVault()` records a slug-to-tree mapping and commits it under
168
+ `refs/cas/vault`.
169
+ - `removeFromVault()` deletes a mapping.
170
+ - Encrypted or privacy-enabled vaults require credential-derived metadata and
171
+ must maintain nonce accounting.
172
+ - Vault mutations use optimistic retry and must not be folded into store or
173
+ restore byte-processing services.
174
+
175
+ ## Extraction Guidance
176
+
177
+ Future decomposition should preserve the state-machine boundaries above.
178
+
179
+ Current extracted boundaries:
180
+
181
+ - `StorePipeline` owns chunk dispatch, write-side backpressure, in-flight write
182
+ tracking, ordered manifest entry append, and store error metadata.
183
+ - `RestorePipeline` owns restore strategy classification and handler dispatch.
184
+ The authentication-sensitive restore byte executors still live behind
185
+ `CasService` methods and should move only in a dedicated follow-up.
186
+
187
+ Recommended service boundaries:
188
+
189
+ - Store policy coordinator: validation, key resolution, scheme resolution, and
190
+ manifest finalization.
191
+ - Chunk writer: digesting, blob writes, and orphan metadata.
192
+ - Restore planner: capability checks and file-restore planning.
193
+ - Restore executors: streaming, framed, convergent, compressed, and buffered
194
+ execution paths.
195
+ - Tree publisher: manifest hashing, manifest blob writes, Merkle sub-manifest
196
+ layout, and Git tree-entry construction.
197
+
198
+ The most important rule is that extraction must not change the sequence of
199
+ validation, warning emission, writes, authentication, or observer events.
@@ -0,0 +1,269 @@
1
+ # Threat Model
2
+
3
+ This document describes the security boundary of `git-cas`.
4
+
5
+ It answers a different question than [SECURITY.md](../SECURITY.md).
6
+
7
+ - [SECURITY.md](../SECURITY.md)
8
+ - cryptographic design, limits, and security-relevant implementation notes
9
+ - this document
10
+ - attacker models, protected assets, exposed metadata, trust boundaries, and
11
+ explicit non-goals
12
+
13
+ `git-cas` is a content-addressed storage system with optional encryption.
14
+ It is not a full secret-management platform, access-control system, or secure
15
+ deletion system.
16
+
17
+ ## System Under Evaluation
18
+
19
+ At a high level, `git-cas`:
20
+
21
+ 1. stores content as Git blobs
22
+ 2. records reconstruction metadata in manifests
23
+ 3. emits Git trees that keep manifests and chunk blobs reachable
24
+ 4. optionally indexes trees by slug through `refs/cas/vault`
25
+
26
+ Optional protections include:
27
+
28
+ - AES-256-GCM encryption for stored content
29
+ - passphrase-derived keys through PBKDF2 or scrypt
30
+ - envelope encryption for multi-recipient access
31
+ - SHA-256 chunk verification during restore and verify flows
32
+
33
+ ## Assets
34
+
35
+ ### Assets `git-cas` Can Protect
36
+
37
+ - plaintext content bytes when encryption is enabled and keys remain secret
38
+ - integrity of stored and restored content through digest verification and
39
+ authenticated decryption
40
+ - long-term reachability of stored assets through Git trees and the vault ref
41
+
42
+ ### Assets `git-cas` Does Not Fully Hide
43
+
44
+ The following are not fully confidential simply because encryption is enabled:
45
+
46
+ - slugs
47
+ - filenames
48
+ - manifest structure
49
+ - chunk counts
50
+ - chunk sizes
51
+ - tree and blob object IDs
52
+ - recipient labels
53
+ - wrapped-recipient records and related encryption metadata
54
+ - vault metadata in `.vault.json`
55
+ - the existence of stored assets and their relationship to particular slugs
56
+
57
+ When `convergent` encryption is active, identical plaintext chunks encrypted
58
+ with the same master key produce identical ciphertext blobs. An attacker with
59
+ read access to the Git object database can observe that two manifests reference
60
+ the same blob OID, inferring that those chunks contain identical plaintext. This
61
+ is the well-known limitation of convergent encryption (Tahoe-LAFS, etc.). For
62
+ scenarios where content equality itself is sensitive, use `framed` or `whole`
63
+ instead.
64
+
65
+ Legacy scheme identifiers such as `convergent-v1`, `framed-v2`, and `whole-v2`
66
+ can appear in pre-v6 manifests only. They are migration inputs, not active
67
+ scheme choices for new v6 writes.
68
+
69
+ This is especially important for repository exposure scenarios: encrypted
70
+ content can remain confidential while metadata remains visible.
71
+
72
+ ## Trust Boundaries
73
+
74
+ The main trust boundaries are:
75
+
76
+ - the Git repository and its object database
77
+ - the local host running `git-cas`
78
+ - the key and passphrase sources used by callers
79
+ - any logs, terminals, CI systems, or automation layers handling secrets
80
+
81
+ `git-cas` controls how bytes are chunked, verified, encrypted, and indexed.
82
+ It does not control who can read the repository, who can inspect the host, or
83
+ how callers store and transport keys.
84
+
85
+ ## Attacker Models
86
+
87
+ ### A1. Repository Reader Without Keys
88
+
89
+ This attacker can read Git objects, manifests, trees, and `refs/cas/vault`, but
90
+ does not have the relevant encryption key or passphrase.
91
+
92
+ What `git-cas` does protect:
93
+
94
+ - encrypted content bytes remain confidential
95
+ - tampering with encrypted content is detected during decryption
96
+ - chunk corruption or substitution is detected during verification and restore
97
+
98
+ What remains exposed:
99
+
100
+ - asset existence
101
+ - slugs and filenames
102
+ - manifest structure and object relationships
103
+ - chunk sizes and counts
104
+ - recipient labels and wrapped-recipient metadata
105
+ - vault metadata including KDF parameters
106
+
107
+ ### A2. Repository Reader With Keys Or Passphrases
108
+
109
+ This attacker can read the repository and also has the relevant key material.
110
+
111
+ What `git-cas` protects:
112
+
113
+ - integrity verification still detects accidental or malicious corruption
114
+
115
+ What it does not protect:
116
+
117
+ - confidentiality of encrypted content
118
+
119
+ Once the attacker has both repository access and valid key material, `git-cas`
120
+ is not an access-control barrier.
121
+
122
+ ### A3. Repository Writer Without Keys
123
+
124
+ This attacker can alter Git objects or refs but does not possess the key
125
+ material.
126
+
127
+ What `git-cas` does protect:
128
+
129
+ - SHA-256 chunk verification detects chunk substitution or corruption
130
+ - AES-GCM authentication detects encrypted-content tampering
131
+ - encrypted restore rejects downgraded manifest metadata instead of silently
132
+ returning ciphertext
133
+ - encrypted `verifyIntegrity()` only passes when ciphertext authentication also
134
+ succeeds with valid credentials
135
+
136
+ What it does not protect:
137
+
138
+ - availability
139
+ - ref deletion
140
+ - denial-of-service through repository damage or object removal
141
+
142
+ An attacker who can mutate or delete repository state can still break restores
143
+ or make content unavailable.
144
+
145
+ ### A4. Host Compromise
146
+
147
+ This attacker can inspect process memory, local files, terminals, environment
148
+ variables, CI logs, or the working tree on a host where `git-cas` is used.
149
+
150
+ What `git-cas` does not protect:
151
+
152
+ - plaintext present on the host during normal file input or restore flows
153
+ - keys or passphrases stored in files, environment variables, or process memory
154
+ - passphrase prompts captured by compromised terminals or host tooling
155
+
156
+ Host compromise defeats the core confidentiality boundary. `git-cas` is not a
157
+ host-hardening system.
158
+
159
+ ### A5. Lost Keys Or Passphrases
160
+
161
+ This is not an attacker, but it is a relevant failure mode.
162
+
163
+ What `git-cas` does not provide:
164
+
165
+ - key escrow
166
+ - recovery service
167
+ - passphrase reset
168
+ - alternate recovery path for encrypted content
169
+
170
+ If the relevant key material is lost, encrypted content may become permanently
171
+ unrecoverable.
172
+
173
+ ## Scenario Notes
174
+
175
+ ### Exposure Of `refs/cas/vault` Without The Passphrase
176
+
177
+ Exposing `refs/cas/vault` does not by itself expose encrypted content bytes.
178
+
179
+ It does expose:
180
+
181
+ - the existence of the vault
182
+ - the slug-to-tree mapping
183
+ - `.vault.json` metadata, including KDF parameters
184
+ - the audit trail of vault commits
185
+
186
+ The vault passphrase does not make the vault index itself opaque. It provides
187
+ KDF-backed key derivation context used by vault-oriented encryption workflows.
188
+ Encrypted vault metadata includes a verifier so clients can reject an incorrect
189
+ derived vault key even when the vault has no entries. That verifier is not a
190
+ secret container: an offline attacker who can read `.vault.json` can still run
191
+ password guesses against the stored KDF parameters and verifier, so vault
192
+ passphrases need high entropy.
193
+
194
+ ### Manifest Exposure
195
+
196
+ Manifests are written as ordinary Git blobs through the configured codec.
197
+ They are not themselves wrapped in a second confidential container.
198
+
199
+ That means repository readers can still inspect manifest metadata even when the
200
+ content chunks are encrypted.
201
+
202
+ ### Envelope Encryption
203
+
204
+ Envelope encryption protects the data encryption key by wrapping it per
205
+ recipient, but it does not hide:
206
+
207
+ - the fact that envelope encryption is in use
208
+ - recipient labels
209
+ - the presence of wrapped DEK records in the manifest
210
+
211
+ It improves key distribution and rotation behavior. It is not metadata
212
+ obfuscation.
213
+
214
+ ### Vault Passphrase Rotation
215
+
216
+ Vault passphrase rotation does not re-encrypt arbitrary repository metadata.
217
+
218
+ It re-wraps envelope-encrypted vault entries with a new KEK derived from the new
219
+ passphrase and updates the vault KDF metadata. Non-envelope entries are skipped.
220
+
221
+ ## Security Guarantees
222
+
223
+ When used correctly, `git-cas` aims to provide:
224
+
225
+ - confidentiality of encrypted content at rest against repository readers who
226
+ lack the relevant key material
227
+ - integrity checking for stored and restored content
228
+ - explicit failure on ciphertext tampering, digest mismatch, and key mismatch
229
+ - durable reachability of stored assets through trees and the vault ref
230
+
231
+ These guarantees depend on:
232
+
233
+ - strong keys or passphrases
234
+ - correct operator handling of key material
235
+ - a non-compromised host
236
+ - intact repository state
237
+
238
+ ## Explicit Non-Goals
239
+
240
+ `git-cas` does not attempt to provide:
241
+
242
+ - authorization or ACL enforcement
243
+ - user identity management
244
+ - key custody or centralized key management
245
+ - secure deletion from Git history or all storage backends
246
+ - metadata confidentiality
247
+ - protection against host compromise
248
+ - protection against compromised CI systems, terminals, or logs
249
+ - remote attestation or hardware-backed execution guarantees
250
+
251
+ ## Operator Responsibilities
252
+
253
+ Operators are responsible for:
254
+
255
+ - generating and storing strong keys and passphrases
256
+ - avoiding secret leakage in environment variables, logs, and shell history
257
+ - treating local hosts and CI runners as part of the trust boundary
258
+ - understanding that encrypted content may still have visible metadata
259
+ - establishing backup and recovery procedures for key material
260
+ - rotating keys or passphrases before operational limits are approached
261
+
262
+ ## How To Read This With Other Docs
263
+
264
+ - [SECURITY.md](../SECURITY.md)
265
+ - crypto design, nonce limits, KDF guidance, and error semantics
266
+ - [ARCHITECTURE.md](../ARCHITECTURE.md)
267
+ - system shape, storage layout, and service boundaries
268
+ - [docs/API.md](./API.md)
269
+ - library and CLI reference