@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,619 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import ContentAddressableStore from '../../index.js';
5
+ import Slug from '../../src/domain/value-objects/Slug.js';
6
+ import { createGitPlumbing } from '../../src/infrastructure/createGitPlumbing.js';
7
+ import {
8
+ hasAgentVaultPassphraseSource,
9
+ readKeyFile as readCredentialKeyFile,
10
+ validateAgentCredentialSources,
11
+ } from '../credentials.js';
12
+
13
+ const REQUEST_OPTION = { request: { type: 'string' } };
14
+ const INPUT_ALIAS_MAP = Object.freeze({
15
+ passphrase: 'passphrase',
16
+ passphraseFile: 'passphrase-file',
17
+ keyFile: 'key-file',
18
+ oldKeyFile: 'old-key-file',
19
+ newKeyFile: 'new-key-file',
20
+ existingKeyFile: 'existing-key-file',
21
+ oldPassphrase: 'old-passphrase',
22
+ newPassphrase: 'new-passphrase',
23
+ oldPassphraseFile: 'old-passphrase-file',
24
+ newPassphraseFile: 'new-passphrase-file',
25
+ vaultPassphrase: 'vault-passphrase',
26
+ vaultPassphraseFile: 'vault-passphrase-file',
27
+ osKeychainTarget: 'os-keychain-target',
28
+ osKeychainAccount: 'os-keychain-account',
29
+ oldOsKeychainTarget: 'old-os-keychain-target',
30
+ oldOsKeychainAccount: 'old-os-keychain-account',
31
+ newOsKeychainTarget: 'new-os-keychain-target',
32
+ newOsKeychainAccount: 'new-os-keychain-account',
33
+ });
34
+
35
+ const START_REDACTED_FIELDS = new Set([
36
+ 'passphrase',
37
+ 'passphraseFile',
38
+ 'keyFile',
39
+ 'oldKeyFile',
40
+ 'newKeyFile',
41
+ 'existingKeyFile',
42
+ 'oldPassphrase',
43
+ 'newPassphrase',
44
+ 'oldPassphraseFile',
45
+ 'newPassphraseFile',
46
+ 'vaultPassphrase',
47
+ 'vaultPassphraseFile',
48
+ 'osKeychainTarget',
49
+ 'osKeychainAccount',
50
+ 'oldOsKeychainTarget',
51
+ 'oldOsKeychainAccount',
52
+ 'newOsKeychainTarget',
53
+ 'newOsKeychainAccount',
54
+ ]);
55
+
56
+ const LOCAL_INPUT_ERROR_CODES = new Set(['ENOENT', 'EISDIR', 'ENOTDIR', 'EACCES', 'EPERM']);
57
+
58
+ /**
59
+ * @param {string | undefined} requestSource
60
+ * @returns {'inline' | 'file' | 'stdin' | undefined}
61
+ */
62
+ function normalizeRequestSourceKind(requestSource) {
63
+ if (!requestSource) {
64
+ return undefined;
65
+ }
66
+ if (requestSource === '-') {
67
+ return 'stdin';
68
+ }
69
+ if (requestSource.startsWith('@')) {
70
+ return 'file';
71
+ }
72
+ return 'inline';
73
+ }
74
+
75
+ /**
76
+ * @param {string | undefined} key
77
+ * @param {unknown} value
78
+ * @returns {{ handled: boolean, value?: unknown }}
79
+ */
80
+ function sanitizeSpecialStartValue(key, value) {
81
+ if (!key) {
82
+ return { handled: false };
83
+ }
84
+
85
+ if (key.includes('-')) {
86
+ return { handled: true };
87
+ }
88
+
89
+ if (key === 'requestSource') {
90
+ return {
91
+ handled: true,
92
+ value: normalizeRequestSourceKind(/** @type {string | undefined} */ (value)),
93
+ };
94
+ }
95
+
96
+ if (key === 'manifest') {
97
+ return {
98
+ handled: true,
99
+ value: {
100
+ provided: true,
101
+ source: typeof value === 'string' ? 'file' : 'inline',
102
+ },
103
+ };
104
+ }
105
+
106
+ if (START_REDACTED_FIELDS.has(key)) {
107
+ return { handled: true, value: true };
108
+ }
109
+
110
+ return { handled: false };
111
+ }
112
+
113
+ /**
114
+ * @param {Record<string, unknown>} value
115
+ * @returns {Record<string, unknown>}
116
+ */
117
+ function sanitizeStartObject(value) {
118
+ /** @type {Record<string, unknown>} */
119
+ const sanitized = {};
120
+ for (const [nestedKey, nestedValue] of Object.entries(value)) {
121
+ const safeValue = sanitizeStartValue(nestedKey, nestedValue);
122
+ if (safeValue !== undefined) {
123
+ sanitized[nestedKey] = safeValue;
124
+ }
125
+ }
126
+ return sanitized;
127
+ }
128
+
129
+ /**
130
+ * @param {unknown[]} value
131
+ * @returns {unknown[]}
132
+ */
133
+ function sanitizeStartArray(value) {
134
+ return value
135
+ .map((entry) => sanitizeStartValue(undefined, entry))
136
+ .filter((entry) => entry !== undefined);
137
+ }
138
+
139
+ /**
140
+ * @param {string | undefined} key
141
+ * @param {unknown} value
142
+ * @returns {unknown}
143
+ */
144
+ function sanitizeStartValue(key, value) {
145
+ if (value === undefined) {
146
+ return undefined;
147
+ }
148
+
149
+ const special = sanitizeSpecialStartValue(key, value);
150
+ if (special.handled) {
151
+ return special.value;
152
+ }
153
+
154
+ if (Buffer.isBuffer(value)) {
155
+ return true;
156
+ }
157
+
158
+ if (Array.isArray(value)) {
159
+ return sanitizeStartArray(value);
160
+ }
161
+
162
+ if (value && typeof value === 'object') {
163
+ return sanitizeStartObject(/** @type {Record<string, unknown>} */ (value));
164
+ }
165
+
166
+ return value;
167
+ }
168
+
169
+ /**
170
+ * @param {Record<string, any>} input
171
+ * @param {string[]} fields
172
+ * @returns {Record<string, any>}
173
+ */
174
+ export function selectStartInput(input, fields) {
175
+ /** @type {Record<string, any>} */
176
+ const selected = {};
177
+ for (const field of fields) {
178
+ if (input[field] !== undefined) {
179
+ selected[field] = input[field];
180
+ }
181
+ }
182
+ return selected;
183
+ }
184
+
185
+ /**
186
+ * @param {Record<string, any>} input
187
+ * @returns {Record<string, any>}
188
+ */
189
+ function buildAgentStartData(input) {
190
+ const sanitized = sanitizeStartValue(undefined, input);
191
+ if (
192
+ sanitized &&
193
+ typeof sanitized === 'object' &&
194
+ !Array.isArray(sanitized) &&
195
+ Object.keys(sanitized).length > 0
196
+ ) {
197
+ return { input: sanitized };
198
+ }
199
+ return {};
200
+ }
201
+
202
+ /**
203
+ * @param {ReturnType<typeof import('./protocol.js').createAgentSession>} session
204
+ * @param {Record<string, any>} input
205
+ */
206
+ export function writeAgentStart(session, input) {
207
+ session.writeStart(buildAgentStartData(input));
208
+ }
209
+
210
+ /**
211
+ * @param {unknown} err
212
+ * @param {string} label
213
+ * @param {string} filePath
214
+ * @returns {Error}
215
+ */
216
+ function normalizeLocalInputError(err, label, filePath) {
217
+ const resolvedPath = path.resolve(filePath);
218
+
219
+ if (err instanceof SyntaxError) {
220
+ return invalidInput(`Invalid ${label}: ${resolvedPath}: ${err.message}`, {
221
+ filePath: resolvedPath,
222
+ });
223
+ }
224
+
225
+ if (typeof err === 'object' && err && typeof err.code === 'string') {
226
+ if (LOCAL_INPUT_ERROR_CODES.has(err.code)) {
227
+ return invalidInput(`Unable to read ${label}: ${resolvedPath}`, {
228
+ filePath: resolvedPath,
229
+ errorCode: err.code,
230
+ });
231
+ }
232
+ }
233
+
234
+ return err instanceof Error ? err : new Error(String(err));
235
+ }
236
+
237
+ /**
238
+ * @param {string} filePath
239
+ * @param {string} label
240
+ * @returns {Buffer}
241
+ */
242
+ export function readBinaryInputFile(filePath, label) {
243
+ try {
244
+ return readFileSync(filePath);
245
+ } catch (err) {
246
+ throw normalizeLocalInputError(err, label, filePath);
247
+ }
248
+ }
249
+
250
+ /**
251
+ * @param {string} filePath
252
+ * @param {string} label
253
+ * @returns {string}
254
+ */
255
+ export function readTextInputFile(filePath, label) {
256
+ try {
257
+ return readFileSync(path.resolve(filePath), 'utf8');
258
+ } catch (err) {
259
+ throw normalizeLocalInputError(err, label, filePath);
260
+ }
261
+ }
262
+
263
+ /**
264
+ * @param {string} cwd
265
+ * @returns {Promise<ContentAddressableStore>}
266
+ */
267
+ export async function createCas(cwd) {
268
+ const plumbing = await createGitPlumbing({ cwd });
269
+ return new ContentAddressableStore({ plumbing });
270
+ }
271
+
272
+ /**
273
+ * @param {string} message
274
+ * @param {Record<string, any>} [meta]
275
+ * @returns {Error & { code: string, meta?: Record<string, any> }}
276
+ */
277
+ export function invalidInput(message, meta) {
278
+ const err = /** @type {Error & { code: string, meta?: Record<string, any> }} */ (
279
+ new Error(message)
280
+ );
281
+ err.code = 'INVALID_INPUT';
282
+ if (meta) {
283
+ err.meta = meta;
284
+ }
285
+ return err;
286
+ }
287
+
288
+ /**
289
+ * @param {string} message
290
+ * @param {Record<string, any>} [meta]
291
+ * @returns {Error & { code: string, meta?: Record<string, any> }}
292
+ */
293
+ export function needsInput(message, meta) {
294
+ const err = /** @type {Error & { code: string, meta?: Record<string, any> }} */ (
295
+ new Error(message)
296
+ );
297
+ err.code = 'NEEDS_INPUT';
298
+ if (meta) {
299
+ err.meta = meta;
300
+ }
301
+ return err;
302
+ }
303
+
304
+ /**
305
+ * @param {string | undefined} request
306
+ * @param {NodeJS.ReadStream} stdin
307
+ * @returns {Promise<Record<string, any>>}
308
+ */
309
+ async function readRequestPayload(request, stdin) {
310
+ if (!request) {
311
+ return {};
312
+ }
313
+
314
+ let raw;
315
+ if (request === '-') {
316
+ raw = await readStream(stdin);
317
+ } else if (request.startsWith('@')) {
318
+ raw = readTextInputFile(request.slice(1), 'request payload file');
319
+ } else {
320
+ raw = request;
321
+ }
322
+
323
+ if (!raw.trim()) {
324
+ throw invalidInput('Agent request payload must not be empty');
325
+ }
326
+
327
+ let parsed;
328
+ try {
329
+ parsed = JSON.parse(raw);
330
+ } catch (err) {
331
+ throw invalidInput(
332
+ `Invalid JSON request payload: ${err instanceof Error ? err.message : String(err)}`
333
+ );
334
+ }
335
+
336
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
337
+ throw invalidInput('Agent request payload must be a JSON object');
338
+ }
339
+
340
+ return parsed;
341
+ }
342
+
343
+ /**
344
+ * @param {string} key
345
+ * @param {Record<string, { type: 'string' | 'boolean' }>} options
346
+ * @returns {{ type: 'string' | 'boolean' } | undefined}
347
+ */
348
+ function resolveRequestOptionSpec(key, options) {
349
+ if (options[key]) {
350
+ return options[key];
351
+ }
352
+
353
+ const alias = INPUT_ALIAS_MAP[key];
354
+ if (alias && options[alias]) {
355
+ return options[alias];
356
+ }
357
+
358
+ return undefined;
359
+ }
360
+
361
+ /**
362
+ * @param {string} key
363
+ * @param {unknown} value
364
+ * @returns {boolean}
365
+ */
366
+ function allowsStructuredRequestValue(key, value) {
367
+ return key === 'manifest' && Boolean(value) && typeof value === 'object' && !Array.isArray(value);
368
+ }
369
+
370
+ /**
371
+ * @param {string} key
372
+ * @param {unknown} value
373
+ * @param {{ type: 'string' | 'boolean' } | undefined} spec
374
+ */
375
+ function validateRequestFieldType(key, value, spec) {
376
+ if (spec?.type === 'boolean' && typeof value !== 'boolean') {
377
+ throw invalidInput(`Request field "${key}" must be a boolean`);
378
+ }
379
+ if (spec?.type === 'string' && typeof value !== 'string' && !allowsStructuredRequestValue(key, value)) {
380
+ throw invalidInput(`Request field "${key}" must be a string`);
381
+ }
382
+ }
383
+
384
+ /**
385
+ * @param {Record<string, any>} request
386
+ * @param {Record<string, { type: 'string' | 'boolean' }>} options
387
+ * @returns {Record<string, any>}
388
+ */
389
+ function normalizeRequestValues(request, options) {
390
+ /** @type {Record<string, any>} */
391
+ const normalized = {};
392
+
393
+ for (const [key, value] of Object.entries(request)) {
394
+ const spec = resolveRequestOptionSpec(key, options);
395
+ validateRequestFieldType(key, value, spec);
396
+ normalized[key] = value;
397
+ }
398
+
399
+ return normalized;
400
+ }
401
+
402
+ /**
403
+ * @param {NodeJS.ReadStream} stream
404
+ * @returns {Promise<string>}
405
+ */
406
+ async function readStream(stream) {
407
+ if (typeof stream.setEncoding === 'function') {
408
+ stream.setEncoding('utf8');
409
+ }
410
+
411
+ let raw = '';
412
+ for await (const chunk of stream) {
413
+ raw += String(chunk);
414
+ }
415
+ return raw;
416
+ }
417
+
418
+ /**
419
+ * @param {string[]} args
420
+ * @param {Record<string, { type: 'string' | 'boolean' }>} options
421
+ * @param {NodeJS.ReadStream} stdin
422
+ * @returns {Promise<{ values: Record<string, any>, positionals: string[], requestSource?: string }>}
423
+ */
424
+ export async function parseAgentInput(args, options, stdin) {
425
+ const optionSpec = {
426
+ ...options,
427
+ ...REQUEST_OPTION,
428
+ };
429
+
430
+ let parsed;
431
+ try {
432
+ parsed = parseArgs({
433
+ args,
434
+ allowPositionals: true,
435
+ strict: true,
436
+ options: optionSpec,
437
+ });
438
+ } catch (err) {
439
+ throw invalidInput(err instanceof Error ? err.message : String(err));
440
+ }
441
+
442
+ const request = normalizeRequestValues(
443
+ await readRequestPayload(parsed.values.request, stdin),
444
+ optionSpec
445
+ );
446
+ const values = { ...request, ...parsed.values };
447
+ delete values.request;
448
+
449
+ return {
450
+ values,
451
+ positionals: parsed.positionals,
452
+ requestSource: parsed.values.request,
453
+ };
454
+ }
455
+
456
+ /**
457
+ * @param {string[]} positionals
458
+ * @param {string[]} names
459
+ * @returns {Record<string, string>}
460
+ */
461
+ export function assignPositionals(positionals, names) {
462
+ if (positionals.length > names.length) {
463
+ throw invalidInput(
464
+ `Unexpected positional arguments: ${positionals.slice(names.length).join(' ')}`
465
+ );
466
+ }
467
+
468
+ /** @type {Record<string, string>} */
469
+ const assigned = {};
470
+ names.forEach((name, index) => {
471
+ if (positionals[index] !== undefined) {
472
+ assigned[name] = positionals[index];
473
+ }
474
+ });
475
+ return assigned;
476
+ }
477
+
478
+ /**
479
+ * @param {Record<string, any>} input
480
+ * @returns {Record<string, any>}
481
+ */
482
+ export function normalizeInputAliases(input) {
483
+ const normalized = { ...input };
484
+ for (const [key, alias] of Object.entries(INPUT_ALIAS_MAP)) {
485
+ normalized[key] = input[key] ?? input[alias];
486
+ }
487
+ return normalized;
488
+ }
489
+
490
+ /**
491
+ * @param {Record<string, any>} input
492
+ * @returns {{ cwd: string, slug?: string, oid?: string }}
493
+ */
494
+ export function resolveTarget(input) {
495
+ if (input.slug && input.oid) {
496
+ throw invalidInput('Provide --slug or --oid, not both');
497
+ }
498
+ if (!input.slug && !input.oid) {
499
+ throw invalidInput('Provide --slug <slug> or --oid <tree-oid>');
500
+ }
501
+ const slug = input.slug ? Slug.from(input.slug).toString() : undefined;
502
+ return {
503
+ cwd: input.cwd || '.',
504
+ ...(slug ? { slug } : {}),
505
+ ...(input.oid ? { oid: input.oid } : {}),
506
+ };
507
+ }
508
+
509
+ /**
510
+ * @param {Record<string, any>} input
511
+ * @returns {{ cwd: string, slug: string }}
512
+ */
513
+ export function resolveSlugTarget(input) {
514
+ if (!input.slug) {
515
+ throw invalidInput('Provide --slug <slug>');
516
+ }
517
+
518
+ return {
519
+ cwd: input.cwd || '.',
520
+ slug: Slug.from(input.slug).toString(),
521
+ };
522
+ }
523
+
524
+ /**
525
+ * @param {unknown} value
526
+ * @returns {number | undefined}
527
+ */
528
+ export function parsePositiveInteger(value) {
529
+ if (value === undefined) {
530
+ return undefined;
531
+ }
532
+
533
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
534
+ return value;
535
+ }
536
+
537
+ if (typeof value === 'string' && /^\d+$/.test(value)) {
538
+ const parsed = Number(value);
539
+ if (Number.isSafeInteger(parsed) && parsed > 0) {
540
+ return parsed;
541
+ }
542
+ }
543
+
544
+ throw invalidInput('Expected a positive integer');
545
+ }
546
+
547
+ /**
548
+ * @param {{ cwd: string, slug?: string, oid?: string }} input
549
+ * @returns {Promise<{ cas: ContentAddressableStore, treeOid: string }>}
550
+ */
551
+ export async function resolveTree(input) {
552
+ const cas = await createCas(input.cwd);
553
+ const treeOid = input.oid || (await cas.resolveVaultEntry({ slug: input.slug }));
554
+ return { cas, treeOid };
555
+ }
556
+
557
+ /**
558
+ * @param {string} keyFilePath
559
+ * @returns {Buffer}
560
+ */
561
+ export function readKeyFile(keyFilePath) {
562
+ return readCredentialKeyFile(keyFilePath, {
563
+ readFile: (filePath) => readBinaryInputFile(filePath, 'key file'),
564
+ errorFactory: invalidInput,
565
+ });
566
+ }
567
+
568
+ /**
569
+ * @param {string} filePath
570
+ * @param {{ stdin?: NodeJS.ReadStream, onWarning?: (warning: Record<string, any>) => void }} [options]
571
+ * @returns {Promise<string>}
572
+ */
573
+ export async function readAgentPassphraseFile(filePath, { stdin, onWarning } = {}) {
574
+ if (filePath === '-') {
575
+ const raw = await readStream(stdin || process.stdin);
576
+ const trimmed = raw.replace(/\r?\n$/, '');
577
+ if (!trimmed) {
578
+ throw invalidInput('Passphrase must not be empty');
579
+ }
580
+ return trimmed;
581
+ }
582
+
583
+ const resolvedPath = path.resolve(filePath);
584
+ try {
585
+ const stats = statSync(resolvedPath);
586
+ if (stats.mode & 0o077) {
587
+ onWarning?.({
588
+ code: 'INSECURE_FILE_PERMISSIONS',
589
+ message: `${resolvedPath} has insecure permissions`,
590
+ filePath: resolvedPath,
591
+ recommendation: 'chmod 600',
592
+ });
593
+ }
594
+ } catch {
595
+ // Let the file read raise the real error.
596
+ }
597
+
598
+ const trimmed = readTextInputFile(resolvedPath, 'passphrase file').replace(/\r?\n$/, '');
599
+ if (!trimmed) {
600
+ throw invalidInput('Passphrase must not be empty');
601
+ }
602
+
603
+ return trimmed;
604
+ }
605
+
606
+ /**
607
+ * @param {Record<string, any>} input
608
+ * @returns {boolean}
609
+ */
610
+ export function hasVaultPassphraseSource(input) {
611
+ return hasAgentVaultPassphraseSource(input);
612
+ }
613
+
614
+ /**
615
+ * @param {Record<string, any>} input
616
+ */
617
+ export function validateCredentialSources(input) {
618
+ validateAgentCredentialSources(input, { errorFactory: invalidInput });
619
+ }