@git-stunts/git-cas 5.3.2 → 6.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.
Files changed (173) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  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 +998 -214
  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 +296 -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 +2224 -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 +208 -65
  60. package/index.js +163 -54
  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 +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -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 +178 -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 +3 -1
  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
@@ -1,8 +1,12 @@
1
1
  import CasError from '../domain/errors/CasError.js';
2
+ import { normalizeKdfOptions, assertKdfPolicy } from '../helpers/kdfPolicy.js';
3
+ import { encodeBase64 } from '../domain/encoding/base64.js';
4
+ import { ErrorCodes } from '../domain/errors/index.js';
2
5
 
3
6
  /**
4
7
  * Encryption metadata returned by AES-256-GCM operations.
5
8
  * @typedef {Object} EncryptionMeta
9
+ * @property {string} [scheme] - Payload framing scheme identifier (e.g. `'whole'`).
6
10
  * @property {string} algorithm - Cipher algorithm identifier (e.g. `'aes-256-gcm'`).
7
11
  * @property {string} nonce - Base64-encoded 12-byte nonce.
8
12
  * @property {string} tag - Base64-encoded 16-byte GCM authentication tag.
@@ -37,9 +41,19 @@ import CasError from '../domain/errors/CasError.js';
37
41
  * @abstract
38
42
  */
39
43
  export default class CryptoPort {
44
+ /**
45
+ * Returns true if the adapter supports the given capability.
46
+ * @param {'scrypt'} capability
47
+ * @returns {boolean}
48
+ */
49
+ supports(capability) {
50
+ if (capability === 'scrypt') { return true; }
51
+ return false;
52
+ }
53
+
40
54
  /**
41
55
  * Returns the SHA-256 hex digest of a buffer.
42
- * @param {Buffer|Uint8Array} _buf - Data to hash.
56
+ * @param {Uint8Array} _buf - Data to hash.
43
57
  * @returns {Promise<string>} 64-char hex digest.
44
58
  */
45
59
  sha256(_buf) {
@@ -47,9 +61,9 @@ export default class CryptoPort {
47
61
  }
48
62
 
49
63
  /**
50
- * Returns a Buffer of n cryptographically random bytes.
64
+ * Returns cryptographically random bytes.
51
65
  * @param {number} _n - Number of random bytes.
52
- * @returns {Buffer|Uint8Array}
66
+ * @returns {Uint8Array}
53
67
  */
54
68
  randomBytes(_n) {
55
69
  throw new Error('Not implemented');
@@ -57,32 +71,49 @@ export default class CryptoPort {
57
71
 
58
72
  /**
59
73
  * Encrypts a buffer using AES-256-GCM.
60
- * @param {Buffer|Uint8Array} _buffer - Plaintext to encrypt.
61
- * @param {Buffer|Uint8Array} _key - 32-byte encryption key.
62
- * @returns {{ buf: Buffer, meta: EncryptionMeta }|Promise<{ buf: Buffer, meta: EncryptionMeta }>}
74
+ * @param {Uint8Array} _buffer - Plaintext to encrypt.
75
+ * @param {Uint8Array} _key - 32-byte encryption key.
76
+ * @param {Uint8Array} [_aad] - Optional additional authenticated data (AAD).
77
+ * @returns {{ buf: Uint8Array, meta: EncryptionMeta }|Promise<{ buf: Uint8Array, meta: EncryptionMeta }>}
63
78
  */
64
- encryptBuffer(_buffer, _key) {
79
+ encryptBuffer(_buffer, _key, _aad) {
65
80
  throw new Error('Not implemented');
66
81
  }
67
82
 
68
83
  /**
69
84
  * Decrypts a buffer using AES-256-GCM.
70
- * @param {Buffer|Uint8Array} _buffer - Ciphertext to decrypt.
71
- * @param {Buffer|Uint8Array} _key - 32-byte encryption key.
85
+ * @param {Uint8Array} _buffer - Ciphertext to decrypt.
86
+ * @param {Uint8Array} _key - 32-byte encryption key.
72
87
  * @param {EncryptionMeta} _meta - Encryption metadata from the encrypt operation.
73
- * @returns {Buffer|Promise<Buffer>}
88
+ * @param {Uint8Array} [_aad] - Optional additional authenticated data (AAD). Must match the AAD used during encryption.
89
+ * @returns {Uint8Array|Promise<Uint8Array>}
74
90
  * @throws on authentication failure.
75
91
  */
76
- decryptBuffer(_buffer, _key, _meta) {
92
+ decryptBuffer(_buffer, _key, _meta, _aad) { // eslint-disable-line max-params
77
93
  throw new Error('Not implemented');
78
94
  }
79
95
 
80
96
  /**
81
97
  * Creates a streaming encryption context.
82
- * @param {Buffer|Uint8Array} _key - 32-byte encryption key.
83
- * @returns {{ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>, finalize: () => EncryptionMeta }}
98
+ * @param {Uint8Array} _key - 32-byte encryption key.
99
+ * @param {Uint8Array} [_aad] - Optional additional authenticated data (AAD).
100
+ * @returns {{ encrypt: (source: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array>, finalize: () => EncryptionMeta }}
84
101
  */
85
- createEncryptionStream(_key) {
102
+ createEncryptionStream(_key, _aad) {
103
+ throw new Error('Not implemented');
104
+ }
105
+
106
+ /**
107
+ * Creates a streaming decryption context.
108
+ * The returned stream may yield tentative plaintext before final auth
109
+ * succeeds, so callers must control publication semantics themselves.
110
+ *
111
+ * @param {Uint8Array} _key - 32-byte encryption key.
112
+ * @param {EncryptionMeta} _meta - Encryption metadata from the encrypt operation.
113
+ * @param {Uint8Array} [_aad] - Optional additional authenticated data (AAD). Must match the AAD used during encryption.
114
+ * @returns {{ decrypt: (source: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array> }}
115
+ */
116
+ createDecryptionStream(_key, _meta, _aad) {
86
117
  throw new Error('Not implemented');
87
118
  }
88
119
 
@@ -94,85 +125,140 @@ export default class CryptoPort {
94
125
  *
95
126
  * @param {Object} options
96
127
  * @param {string} options.passphrase - The passphrase to derive a key from.
97
- * @param {Buffer|Uint8Array} [options.salt] - Salt for the KDF (random if omitted).
128
+ * @param {Uint8Array} [options.salt] - Salt for the KDF (random if omitted).
98
129
  * @param {'pbkdf2'|'scrypt'} [options.algorithm='pbkdf2'] - KDF algorithm.
99
- * @param {number} [options.iterations=100000] - PBKDF2 iteration count.
100
- * @param {number} [options.cost=16384] - scrypt cost parameter (N).
130
+ * @param {number} [options.iterations=600000] - PBKDF2 iteration count.
131
+ * @param {number} [options.cost=131072] - scrypt cost parameter (N).
101
132
  * @param {number} [options.blockSize=8] - scrypt block size (r).
102
133
  * @param {number} [options.parallelization=1] - scrypt parallelization (p).
103
134
  * @param {number} [options.keyLength=32] - Derived key length in bytes.
104
- * @returns {Promise<{ key: Buffer, salt: Buffer, params: KdfParamSet }>}
135
+ * @returns {Promise<{ key: Uint8Array, salt: Uint8Array, params: KdfParamSet }>}
105
136
  */
106
137
  async deriveKey({
107
138
  passphrase,
108
139
  salt,
109
140
  algorithm = 'pbkdf2',
110
- iterations = 100_000,
111
- cost = 16384,
112
- blockSize = 8,
113
- parallelization = 1,
114
- keyLength = 32,
141
+ iterations,
142
+ cost,
143
+ blockSize,
144
+ parallelization,
145
+ keyLength,
115
146
  }) {
147
+ const normalized = normalizeKdfOptions({
148
+ algorithm,
149
+ iterations,
150
+ cost,
151
+ blockSize,
152
+ parallelization,
153
+ keyLength,
154
+ });
155
+ assertKdfPolicy(normalized, { source: 'deriveKey' });
116
156
  const saltBuf = salt || this.randomBytes(32);
117
157
 
118
158
  /** @type {KdfParamSet} */
119
159
  const params = {
120
- algorithm,
121
- salt: Buffer.from(saltBuf).toString('base64'),
122
- keyLength,
160
+ algorithm: normalized.algorithm,
161
+ salt: encodeBase64(saltBuf),
162
+ keyLength: normalized.keyLength,
123
163
  };
124
164
 
125
- if (algorithm === 'pbkdf2') {
126
- params.iterations = iterations;
127
- } else if (algorithm === 'scrypt') {
128
- params.cost = cost;
129
- params.blockSize = blockSize;
130
- params.parallelization = parallelization;
165
+ if (normalized.algorithm === 'pbkdf2') {
166
+ params.iterations = normalized.iterations;
167
+ } else if (normalized.algorithm === 'scrypt') {
168
+ params.cost = normalized.cost;
169
+ params.blockSize = normalized.blockSize;
170
+ params.parallelization = normalized.parallelization;
131
171
  } else {
132
- throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
172
+ throw new Error(`Unsupported KDF algorithm: ${normalized.algorithm}`);
133
173
  }
134
174
 
135
175
  const key = await this._doDeriveKey(passphrase, saltBuf, {
136
- algorithm,
137
- iterations,
138
- cost,
139
- blockSize,
140
- parallelization,
141
- keyLength,
176
+ algorithm: normalized.algorithm,
177
+ iterations: normalized.iterations,
178
+ cost: normalized.cost,
179
+ blockSize: normalized.blockSize,
180
+ parallelization: normalized.parallelization,
181
+ keyLength: normalized.keyLength,
142
182
  });
143
183
 
144
- return { key: Buffer.from(key), salt: Buffer.from(saltBuf), params };
184
+ return { key, salt: saltBuf, params };
145
185
  }
146
186
 
147
187
  /**
148
188
  * Adapter-specific key derivation. Override in subclasses.
149
189
  * @abstract
150
190
  * @param {string} _passphrase - The passphrase.
151
- * @param {Buffer|Uint8Array} _saltBuf - Salt bytes.
191
+ * @param {Uint8Array} _saltBuf - Salt bytes.
152
192
  * @param {DeriveKeyParams} _params - Normalized KDF parameters.
153
- * @returns {Promise<Buffer|Uint8Array>} Derived key bytes.
193
+ * @returns {Promise<Uint8Array>} Derived key bytes.
154
194
  */
155
195
  async _doDeriveKey(_passphrase, _saltBuf, _params) {
156
196
  throw new Error('Not implemented');
157
197
  }
158
198
 
159
199
  /**
160
- * Validates that a key is a 32-byte Buffer or Uint8Array.
161
- * @param {Buffer|Uint8Array} key - Key to validate.
162
- * @throws {CasError} INVALID_KEY_TYPE if key is not a Buffer or Uint8Array.
200
+ * Computes HMAC-SHA256 of the given data with the given key.
201
+ *
202
+ * @abstract
203
+ * @param {Uint8Array} key - HMAC key.
204
+ * @param {Uint8Array} data - Data to authenticate.
205
+ * @returns {Uint8Array|Promise<Uint8Array>} 32-byte HMAC digest.
206
+ */
207
+ hmacSha256(_key, _data) {
208
+ throw new Error('Not implemented');
209
+ }
210
+
211
+ /**
212
+ * Encrypts a buffer using AES-256-GCM with a caller-provided nonce.
213
+ *
214
+ * Used by convergent encryption where the nonce must be deterministic
215
+ * (derived from content hash) to enable deduplication.
216
+ *
217
+ * @abstract
218
+ * @param {Uint8Array} _buffer - Plaintext to encrypt.
219
+ * @param {Uint8Array} _key - 32-byte encryption key.
220
+ * @param {Uint8Array} _nonce - 12-byte nonce (IV).
221
+ * @returns {{ buf: Uint8Array, tag: Uint8Array }|Promise<{ buf: Uint8Array, tag: Uint8Array }>}
222
+ */
223
+ encryptBufferWithNonce(_buffer, _key, _nonce) {
224
+ throw new Error('Not implemented');
225
+ }
226
+
227
+ /**
228
+ * Decrypts a buffer using AES-256-GCM with explicit nonce and tag.
229
+ *
230
+ * Used by convergent encryption to decrypt per-chunk ciphertext
231
+ * where the nonce and tag are stored/derived externally.
232
+ *
233
+ * @abstract
234
+ * @param {Uint8Array} _buffer - Ciphertext to decrypt.
235
+ * @param {Uint8Array} _key - 32-byte encryption key.
236
+ * @param {Uint8Array} _nonce - 12-byte nonce (IV).
237
+ * @param {Uint8Array} _tag - 16-byte GCM authentication tag.
238
+ * @returns {Uint8Array|Promise<Uint8Array>}
239
+ * @throws on authentication failure.
240
+ */
241
+ decryptBufferWithNonceTag(_buffer, _key, _nonce, _tag) { // eslint-disable-line max-params
242
+ throw new Error('Not implemented');
243
+ }
244
+
245
+ /**
246
+ * Validates that a key is a 32-byte Uint8Array.
247
+ * @param {Uint8Array} key - Key to validate.
248
+ * @throws {CasError} INVALID_KEY_TYPE if key is not a Uint8Array.
163
249
  * @throws {CasError} INVALID_KEY_LENGTH if key is not 32 bytes.
164
250
  */
165
251
  _validateKey(key) {
166
- if (!globalThis.Buffer?.isBuffer(key) && !(key instanceof Uint8Array)) {
252
+ if (!(key instanceof Uint8Array)) {
167
253
  throw new CasError(
168
- 'Encryption key must be a Buffer or Uint8Array',
169
- 'INVALID_KEY_TYPE',
254
+ 'Encryption key must be a Uint8Array',
255
+ ErrorCodes.INVALID_KEY_TYPE,
170
256
  );
171
257
  }
172
258
  if (key.length !== 32) {
173
259
  throw new CasError(
174
260
  `Encryption key must be 32 bytes, got ${key.length}`,
175
- 'INVALID_KEY_LENGTH',
261
+ ErrorCodes.INVALID_KEY_LENGTH,
176
262
  { expected: 32, actual: key.length },
177
263
  );
178
264
  }
@@ -182,10 +268,12 @@ export default class CryptoPort {
182
268
  * Builds the encryption metadata object from base64-encoded nonce and tag.
183
269
  * @param {string} nonce64 - Base64-encoded 12-byte AES-GCM nonce.
184
270
  * @param {string} tag64 - Base64-encoded 16-byte GCM authentication tag.
271
+ * @param {string} [scheme='whole'] - Payload framing scheme identifier.
185
272
  * @returns {EncryptionMeta}
186
273
  */
187
- _buildMeta(nonce64, tag64) {
274
+ _buildMeta(nonce64, tag64, scheme = 'whole') {
188
275
  return {
276
+ scheme,
189
277
  algorithm: 'aes-256-gcm',
190
278
  nonce: nonce64,
191
279
  tag: tag64,
@@ -5,7 +5,7 @@
5
5
  export default class GitPersistencePort {
6
6
  /**
7
7
  * Writes content as a Git blob object.
8
- * @param {Buffer|string} _content - Data to store.
8
+ * @param {Uint8Array} _content - Data to store.
9
9
  * @returns {Promise<string>} The Git OID of the stored blob.
10
10
  */
11
11
  async writeBlob(_content) {
@@ -24,12 +24,23 @@ export default class GitPersistencePort {
24
24
  /**
25
25
  * Reads a Git blob by its OID.
26
26
  * @param {string} _oid - Git object ID.
27
- * @returns {Promise<Buffer>} The blob content.
27
+ * @returns {Promise<Uint8Array>} The blob content.
28
28
  */
29
29
  async readBlob(_oid) {
30
30
  throw new Error('Not implemented');
31
31
  }
32
32
 
33
+ /**
34
+ * Reads a Git blob by its OID as an async byte stream.
35
+ * Required for hard-limited buffered restore modes. `readBlob()` remains a
36
+ * compatibility fallback for plaintext restore only.
37
+ * @param {string} _oid - Git object ID.
38
+ * @returns {Promise<AsyncIterable<Uint8Array>>} The blob byte stream.
39
+ */
40
+ async readBlobStream(_oid) {
41
+ throw new Error('Not implemented');
42
+ }
43
+
33
44
  /**
34
45
  * Reads and parses a Git tree object.
35
46
  * @param {string} _treeOid - Git tree OID.
@@ -38,4 +49,23 @@ export default class GitPersistencePort {
38
49
  async readTree(_treeOid) {
39
50
  throw new Error('Not implemented');
40
51
  }
52
+
53
+ /**
54
+ * Reads one Git tree entry by path without enumerating the full tree.
55
+ * @param {string} _treeOid - Git tree OID.
56
+ * @param {string} _treePath - Tree entry path/name to resolve.
57
+ * @returns {Promise<{ mode: string, type: string, oid: string, name: string }|null>} Parsed entry or null.
58
+ */
59
+ async readTreeEntry(_treeOid, _treePath) {
60
+ throw new Error('Not implemented');
61
+ }
62
+
63
+ /**
64
+ * Streams parsed Git tree entries.
65
+ * @param {string} _treeOid - Git tree OID.
66
+ * @returns {AsyncIterable<{ mode: string, type: string, oid: string, name: string }>}
67
+ */
68
+ iterateTree(_treeOid) {
69
+ throw new Error('Not implemented');
70
+ }
41
71
  }
@@ -0,0 +1,16 @@
1
+ import PortNotImplementedError from '../domain/errors/PortNotImplementedError.js';
2
+
3
+ export default class GitPlumbingFactoryPort {
4
+ /**
5
+ * Creates a Git command executor for the requested working tree.
6
+ *
7
+ * @param {{ cwd?: string, env?: string }} _options
8
+ * @returns {Promise<{ execute: Function, executeStream: Function }>}
9
+ */
10
+ async create(_options = {}) {
11
+ throw new PortNotImplementedError('GitPlumbingFactoryPort.create() must be implemented', {
12
+ port: 'GitPlumbingFactoryPort',
13
+ method: 'create',
14
+ });
15
+ }
16
+ }
@@ -39,7 +39,7 @@ export default class GitRefPort {
39
39
  * @param {Object} _options
40
40
  * @param {string} _options.ref - Git ref to update.
41
41
  * @param {string} _options.newOid - New OID to set.
42
- * @param {string|null} [_options.expectedOldOid] - Expected current OID for CAS.
42
+ * @param {string|null} [_options.expectedOldOid] - Expected current OID for CAS; `null` means the ref must not exist.
43
43
  * @returns {Promise<void>}
44
44
  */
45
45
  async updateRef(_options) {
@@ -5,23 +5,28 @@
5
5
  declare module '@git-stunts/plumbing' {
6
6
  interface ExecuteOptions {
7
7
  args: string[];
8
- input?: string | Buffer;
8
+ input?: string | Uint8Array;
9
+ env?: Record<string, string | undefined>;
9
10
  }
10
11
 
11
12
  interface StreamResult {
12
- collect(options?: { asString?: boolean }): Promise<Uint8Array>;
13
+ collect(options?: { asString?: boolean; maxBytes?: number }): Promise<string | Uint8Array>;
13
14
  }
14
15
 
15
- interface ShellRunner {
16
- run(command: string, args: string[], options?: Record<string, unknown>): Promise<unknown>;
17
- }
16
+ type ShellRunner = (options: Record<string, unknown>) => Promise<unknown>;
18
17
 
19
18
  export class ShellRunnerFactory {
19
+ static ENV_BUN: 'bun';
20
+ static ENV_DENO: 'deno';
21
+ static ENV_NODE: 'node';
20
22
  static create(options?: Record<string, unknown>): ShellRunner;
23
+ static validateCwd(cwd: string): Promise<string>;
21
24
  }
22
25
 
23
26
  export default class GitPlumbing {
24
27
  constructor(options: { runner: ShellRunner; cwd?: string });
28
+ static createDefault(options?: { cwd?: string; env?: string }): Promise<GitPlumbing>;
29
+ static createRepository(options?: { cwd?: string; env?: string }): Promise<unknown>;
25
30
  execute(options: ExecuteOptions): Promise<string>;
26
31
  executeStream(options: ExecuteOptions): Promise<StreamResult>;
27
32
  }
@@ -0,0 +1,94 @@
1
+ # Test Conventions
2
+
3
+ Rules for writing deterministic, cross-runtime tests. All tests must pass
4
+ on Node.js, Bun, and Deno.
5
+
6
+ ## Time and Scheduling
7
+
8
+ **Never assert wall-clock timing.** `Date.now()` deltas are
9
+ nondeterministic — they flake under CI load and vary across runtimes.
10
+
11
+ **Inject delay/timer dependencies.** If production code uses `setTimeout`
12
+ or similar scheduling, accept the delay function as a parameter:
13
+
14
+ ```js
15
+ // production: injectable dependency with a real default
16
+ export function runAction(fn, getJson, { delay = defaultDelay } = {}) { ... }
17
+
18
+ // test: inject a spy — no global patching needed
19
+ const delaySpy = vi.fn().mockResolvedValue(undefined);
20
+ const action = runAction(fn, getJson, { delay: delaySpy });
21
+ await action();
22
+ expect(delaySpy).toHaveBeenCalledWith(1000);
23
+ ```
24
+
25
+ **Avoid `vi.useFakeTimers()`.** Vitest fake timers rely on
26
+ `@sinonjs/fake-timers`, which patches globals differently across runtimes.
27
+ Prefer dependency injection over global monkey-patching.
28
+
29
+ ## File Permissions
30
+
31
+ **Use `chmod()` after `writeFile()`, not `writeFile({ mode })`.** The
32
+ `mode` parameter is filtered through `process.umask()`. A restrictive
33
+ umask (e.g., `0o077`) silently strips the bits you requested, making
34
+ permission-sensitive tests environment-dependent.
35
+
36
+ ```js
37
+ // wrong — umask can mask the requested mode
38
+ await writeFile(path, 'data', { mode: 0o644 });
39
+
40
+ // correct — chmod sets the exact mode regardless of umask
41
+ await writeFile(path, 'data');
42
+ await chmod(path, 0o644);
43
+ ```
44
+
45
+ This applies to macOS and Linux (our supported platforms). Permission
46
+ bits are a Unix concept — `chmod` is a no-op on Windows.
47
+
48
+ ## General Principles
49
+
50
+ - **Test behavior, not timing.** Assert that a function was called, not
51
+ how long it took.
52
+ - **Inject infrastructure.** Clocks, filesystems, network — anything that
53
+ varies across environments should be injectable through constructor
54
+ parameters or function arguments.
55
+ - **No global state patching when injection is available.** If you control
56
+ the code under test, add a parameter. Only patch globals for third-party
57
+ code you cannot modify.
58
+
59
+ ## Git Tree Assertions
60
+
61
+ **Git tree reads are filename-sorted.** Git returns tree entries in name
62
+ order, not in the original write order. Integration tests that round-trip
63
+ through `readTree()` must therefore assert membership, uniqueness, and Git's
64
+ sorted output semantics instead of assuming first-seen insertion order.
65
+
66
+ If insertion order matters, assert it at the lower-level boundary that builds
67
+ the tree entries before they are handed to Git.
68
+
69
+ ## Integration Runtime Policy
70
+
71
+ **Integration suites are Docker-only.** The integration tests intentionally
72
+ refuse to run on the host and require `GIT_STUNTS_DOCKER=1` so Git, Bun, and
73
+ Deno run in a consistent environment.
74
+
75
+ **Integration files run with `fileParallelism: false`.** These tests spawn real
76
+ Git and CLI subprocesses, so the integration workspace is intentionally kept to
77
+ single-file execution. Do not re-enable file-level parallelism unless the
78
+ subprocess model changes and Bun/Deno are re-validated.
79
+
80
+ ## Subprocess Helpers
81
+
82
+ **Use direct argv execution, never shell-wrapped commands.** CLI and Git
83
+ integration helpers must call `spawnSync()` / `spawn()` with an explicit binary
84
+ and argv array. Avoid `/bin/sh -c`, command-string helpers, or concatenated
85
+ shell fragments because they introduce quoting drift and runtime-specific I/O
86
+ differences.
87
+
88
+ ```js
89
+ // preferred
90
+ spawnSync('git', ['init', '--bare'], { cwd, encoding: 'utf8' });
91
+
92
+ // avoid
93
+ spawnSync('/bin/sh', ['-c', 'git init --bare'], { cwd, encoding: 'utf8' });
94
+ ```
@@ -0,0 +1,13 @@
1
+ # Cycle Tests
2
+
3
+ Cycle-owned playback, regression, and spec tests live here when the cycle
4
+ benefits from a dedicated test namespace.
5
+
6
+ This does not replace the normal unit and integration suite.
7
+
8
+ Use this directory when a cycle has:
9
+
10
+ - a clear protocol or playback contract
11
+ - a bounded regression surface worth naming directly
12
+ - test fixtures or helper structure that belong to the cycle more than to a
13
+ package