-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.ts
More file actions
921 lines (852 loc) · 26.8 KB
/
binary.ts
File metadata and controls
921 lines (852 loc) · 26.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/** @fileoverview DLX binary execution utilities for Socket ecosystem. */
import process from 'node:process'
import { getArch, WIN32 } from '../constants/platform'
import { DLX_BINARY_CACHE_TTL } from '../constants/time'
import { isDir, readJson, safeDelete, safeMkdir } from '../fs'
import { httpDownload } from '../http-request'
import { isObjectObject } from '../objects'
import { normalizePath } from '../paths/normalize'
import { getSocketDlxDir } from '../paths/socket'
import { processLock } from '../process-lock'
import { spawn } from '../spawn'
import { generateCacheKey } from './cache'
import { normalizeHash } from './integrity'
import type { HashSpec } from './integrity'
import type { SpawnExtra, SpawnOptions } from '../spawn'
let _crypto: typeof import('node:crypto') | undefined
/**
* Lazily load the crypto module to avoid Webpack errors.
* Uses non-'node:' prefixed require to prevent Webpack bundling issues.
*
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getCrypto() {
if (_crypto === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_crypto = /*@__PURE__*/ require('node:crypto')
}
return _crypto as typeof import('node:crypto')
}
let _fs: typeof import('node:fs') | undefined
/**
* Lazily load the fs module to avoid Webpack errors.
* Uses non-'node:' prefixed require to prevent Webpack bundling issues.
*
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getFs() {
if (_fs === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_fs = /*@__PURE__*/ require('node:fs')
}
return _fs as typeof import('node:fs')
}
let _path: typeof import('node:path') | undefined
/**
* Lazily load the path module to avoid Webpack errors.
* Uses non-'node:' prefixed require to prevent Webpack bundling issues.
*
* @returns The Node.js path module
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getPath() {
if (_path === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_path = /*@__PURE__*/ require('node:path')
}
return _path as typeof import('node:path')
}
export interface DlxBinaryOptions {
/**
* URL to download the binary from.
*/
url: string
/**
* Optional name for the cached binary (defaults to URL hash).
*/
name?: string | undefined
/**
* Expected hash for verification. Accepts either:
* - A bare sha512 SRI string (`sha512-<base64>`), sniffed as integrity.
* - A bare sha256 hex string (64 hex chars), sniffed as checksum.
* - An explicit `{ type: 'integrity' | 'checksum', value }` object.
*
* This is the preferred field. `integrity` and `sha256` remain as
* lower-level escapes; if both `hash` and one of those is set, `hash`
* wins for the matching flavor.
*/
hash?: HashSpec | undefined
/**
* Expected SRI integrity hash (sha512-<base64>) for verification.
* Lower-level alternative to `hash`.
*/
integrity?: string | undefined
/**
* Expected SHA-256 hex checksum for verification.
* Passed to httpDownload for inline verification during download.
* This is more secure than post-download verification as it fails early.
* Lower-level alternative to `hash`.
*/
sha256?: string | undefined
/**
* Cache TTL in milliseconds (default: 7 days).
*/
cacheTtl?: number | undefined
/**
* Force re-download even if cached.
* Aligns with npm/npx --force flag.
*/
force?: boolean | undefined
/**
* Skip confirmation prompts (auto-approve).
* Aligns with npx --yes/-y flag.
*/
yes?: boolean | undefined
/**
* Suppress output (quiet mode).
* Aligns with npx --quiet/-q and pnpm --silent/-s flags.
*/
quiet?: boolean | undefined
/**
* Additional spawn options.
*/
spawnOptions?: SpawnOptions | undefined
}
export interface DlxBinaryResult {
/** Path to the cached binary. */
binaryPath: string
/** Whether the binary was newly downloaded. */
downloaded: boolean
/** The spawn promise for the running process. */
spawnPromise: ReturnType<typeof spawn>
}
/**
* Metadata structure for cached binaries (.dlx-metadata.json).
* Unified schema shared across TypeScript (dlxBinary) and C++ stub extractor.
*
* Fields:
* - version: Schema version (currently "1.0.0")
* - cache_key: First 16 chars of SHA-512 hash (matches directory name)
* - timestamp: Unix timestamp in milliseconds
* - integrity: SRI hash (sha512-<base64>, aligned with npm)
* - size: Size of cached binary in bytes
* - source: Origin information
* - type: "download" | "extract" | "package"
* - url: Download URL (if type is "download")
* - path: Source binary path (if type is "extract")
* - spec: Package spec (if type is "package")
* - update_check: Update checking metadata (optional)
* - last_check: Timestamp of last update check
* - last_notification: Timestamp of last user notification
* - latest_known: Latest known version string
*
* Example:
* ```json
* {
* "version": "1.0.0",
* "cache_key": "a1b2c3d4e5f67890",
* "timestamp": 1730332800000,
* "integrity": "sha512-abc123base64...",
* "size": 15000000,
* "source": {
* "type": "download",
* "url": "https://example.com/binary"
* },
* "update_check": {
* "last_check": 1730332800000,
* "last_notification": 1730246400000,
* "latest_known": "2.1.0"
* }
* }
* ```
*
* @internal This interface documents the metadata file format.
*/
export interface DlxMetadata {
version: string
cache_key: string
timestamp: number
integrity: string
size: number
source?: {
type: 'download' | 'extract' | 'package'
url?: string
path?: string
spec?: string
}
update_check?: {
last_check: number
last_notification: number
latest_known: string
}
}
/**
* Clean expired entries from the DLX cache.
*
* @example
* ```typescript
* // Remove cache entries older than the default TTL
* const removed = await cleanDlxCache()
*
* // Remove entries older than 1 hour
* const removed2 = await cleanDlxCache(60 * 60 * 1000)
* ```
*/
export async function cleanDlxCache(
maxAge: number = DLX_BINARY_CACHE_TTL,
): Promise<number> {
const cacheDir = getDlxCachePath()
const fs = getFs()
if (!fs.existsSync(cacheDir)) {
return 0
}
let cleaned = 0
const now = Date.now()
const path = getPath()
const entries = await fs.promises.readdir(cacheDir)
for (const entry of entries) {
const entryPath = path.join(cacheDir, entry)
const metaPath = getBinaryCacheMetadataPath(entryPath)
try {
// eslint-disable-next-line no-await-in-loop
if (!(await isDir(entryPath))) {
continue
}
// eslint-disable-next-line no-await-in-loop
const metadata = await readJson(metaPath, { throws: false })
if (
!metadata ||
typeof metadata !== 'object' ||
Array.isArray(metadata)
) {
continue
}
const timestamp = (metadata as Record<string, unknown>)['timestamp']
// If timestamp is missing or invalid, treat as expired (age = infinity)
const age =
typeof timestamp === 'number' && timestamp > 0
? now - timestamp
: Number.POSITIVE_INFINITY
// Treat future timestamps (clock skew) as expired
if (age < 0 || age > maxAge) {
// Remove entire cache entry directory.
// eslint-disable-next-line no-await-in-loop
await safeDelete(entryPath, { force: true, recursive: true })
cleaned += 1
}
} catch {
// If we can't read metadata, check if directory is empty or corrupted.
try {
// eslint-disable-next-line no-await-in-loop
const contents = await fs.promises.readdir(entryPath)
if (!contents.length) {
// Remove empty directory.
// eslint-disable-next-line no-await-in-loop
await safeDelete(entryPath)
cleaned += 1
}
} catch {}
}
}
return cleaned
}
/**
* Download and execute a binary from a URL with caching.
*
* @example
* ```typescript
* const result = await dlxBinary(['--version'], {
* url: 'https://example.com/tool-linux-x64',
* name: 'tool',
* })
* await result.spawnPromise
* ```
*/
export async function dlxBinary(
args: readonly string[] | string[],
options?: DlxBinaryOptions | undefined,
spawnExtra?: SpawnExtra | undefined,
): Promise<DlxBinaryResult> {
const {
cacheTtl = DLX_BINARY_CACHE_TTL,
force: userForce = false,
hash,
integrity: rawIntegrity,
name,
sha256: rawSha256,
spawnOptions,
url,
yes,
} = { __proto__: null, ...options } as DlxBinaryOptions
let integrity = rawIntegrity
let sha256 = rawSha256
if (hash !== undefined) {
const normalized = normalizeHash(hash)
if (normalized.type === 'integrity') {
integrity = normalized.value
} else {
sha256 = normalized.value
}
}
const fs = getFs()
const path = getPath()
// Map --yes flag to force behavior (auto-approve/skip prompts)
const force = yes === true ? true : userForce
// Generate cache paths similar to pnpm/npx structure.
const cacheDir = getDlxCachePath()
const binaryName = name || `binary-${process.platform}-${getArch()}`
// Create spec from URL and binary name for unique cache identity.
const spec = `${url}:${binaryName}`
const cacheKey = generateCacheKey(spec)
const cacheEntryDir = path.join(cacheDir, cacheKey)
const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))
let downloaded = false
let computedIntegrity = integrity
// Check if we need to download.
if (
!force &&
fs.existsSync(cacheEntryDir) &&
(await isBinaryCacheValid(cacheEntryDir, cacheTtl))
) {
// Binary is cached and valid, read the integrity from metadata.
try {
const metaPath = getBinaryCacheMetadataPath(cacheEntryDir)
const metadata = await readJson(metaPath, { throws: false })
if (
metadata &&
typeof metadata === 'object' &&
!Array.isArray(metadata) &&
typeof (metadata as Record<string, unknown>)['integrity'] === 'string'
) {
computedIntegrity = (metadata as Record<string, unknown>)[
'integrity'
] as string
// Re-check binary exists after reading metadata (TOCTOU protection).
// Prevents race where binary is deleted between validity check and use.
if (!fs.existsSync(binaryPath)) {
downloaded = true
}
} else {
// If metadata is invalid, re-download.
downloaded = true
}
} catch {
// If we can't read metadata, re-download.
downloaded = true
}
} else {
downloaded = true
}
if (downloaded) {
// Ensure cache directory exists before downloading.
try {
await safeMkdir(cacheEntryDir)
} catch (e) {
const code = (e as NodeJS.ErrnoException).code
if (code === 'EACCES' || code === 'EPERM') {
throw new Error(
`Permission denied creating binary cache directory: ${cacheEntryDir}\n` +
'Please check directory permissions or run with appropriate access.',
{ cause: e },
)
}
if (code === 'EROFS') {
throw new Error(
`Cannot create binary cache directory on read-only filesystem: ${cacheEntryDir}\n` +
'Ensure the filesystem is writable or set SOCKET_DLX_DIR to a writable location.',
{ cause: e },
)
}
throw new Error(
`Failed to create binary cache directory: ${cacheEntryDir}`,
{ cause: e },
)
}
// Download the binary.
computedIntegrity = await downloadBinaryFile(
url,
binaryPath,
integrity,
sha256,
)
// Get file size for metadata.
const stats = await fs.promises.stat(binaryPath)
await writeBinaryCacheMetadata(
cacheEntryDir,
cacheKey,
url,
computedIntegrity || '',
stats.size,
)
}
// Execute the binary.
// On Windows, script files (.bat, .cmd, .ps1) require shell: true because
// they are not executable on their own and must be run through cmd.exe.
// Note: .exe files are actual binaries and don't need shell mode.
const needsShell = WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath)
// Windows cmd.exe PATH resolution behavior:
// When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically
// strip the full path down to just the basename without extension (e.g.,
// C:\cache\test.cmd becomes just "test"). Windows cmd.exe then searches for "test"
// in directories listed in PATH, trying each extension from PATHEXT environment
// variable (.COM, .EXE, .BAT, .CMD, etc.) until it finds a match.
//
// Since our binaries are downloaded to a custom cache directory that's not in PATH
// (unlike system package managers like npm/pnpm/yarn which are already in PATH),
// we must prepend the cache directory to PATH so cmd.exe can locate the binary.
//
// This approach is consistent with how other tools handle Windows command execution:
// - npm's promise-spawn: uses which.sync() to find commands in PATH
// - cross-spawn: spawns cmd.exe with escaped arguments
// - Node.js spawn with shell: true: delegates to cmd.exe which uses PATH
const finalSpawnOptions = needsShell
? {
...spawnOptions,
env: {
...spawnOptions?.env,
PATH: `${cacheEntryDir}${getPath().delimiter}${process.env['PATH'] || ''}`,
},
shell: true,
}
: spawnOptions
const spawnPromise = spawn(binaryPath, args, finalSpawnOptions, spawnExtra)
return {
binaryPath,
downloaded,
spawnPromise,
}
}
/**
* Download a binary from a URL with caching (without execution).
* Similar to downloadPackage from dlx-package.
*
* @returns Object containing the path to the cached binary and whether it was downloaded
*
* @example
* ```typescript
* const { binaryPath, downloaded } = await downloadBinary({
* url: 'https://example.com/tool-linux-x64',
* name: 'tool',
* })
* console.log(`Binary at: ${binaryPath}, fresh: ${downloaded}`)
* ```
*/
export async function downloadBinary(
options: Omit<DlxBinaryOptions, 'spawnOptions'>,
): Promise<{ binaryPath: string; downloaded: boolean }> {
const {
cacheTtl = DLX_BINARY_CACHE_TTL,
force = false,
hash,
integrity: rawIntegrity,
name,
sha256: rawSha256,
url,
} = { __proto__: null, ...options } as DlxBinaryOptions
let integrity = rawIntegrity
let sha256 = rawSha256
if (hash !== undefined) {
const normalized = normalizeHash(hash)
if (normalized.type === 'integrity') {
integrity = normalized.value
} else {
sha256 = normalized.value
}
}
const fs = getFs()
const path = getPath()
// Generate cache paths similar to pnpm/npx structure.
const cacheDir = getDlxCachePath()
const binaryName = name || `binary-${process.platform}-${getArch()}`
// Create spec from URL and binary name for unique cache identity.
const spec = `${url}:${binaryName}`
const cacheKey = generateCacheKey(spec)
const cacheEntryDir = path.join(cacheDir, cacheKey)
const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))
let downloaded = false
// Check if we need to download.
if (
!force &&
fs.existsSync(cacheEntryDir) &&
(await isBinaryCacheValid(cacheEntryDir, cacheTtl))
) {
// Binary is cached and valid.
downloaded = false
} else {
// Ensure cache directory exists before downloading.
try {
await safeMkdir(cacheEntryDir)
} catch (e) {
const code = (e as NodeJS.ErrnoException).code
if (code === 'EACCES' || code === 'EPERM') {
throw new Error(
`Permission denied creating binary cache directory: ${cacheEntryDir}\n` +
'Please check directory permissions or run with appropriate access.',
{ cause: e },
)
}
if (code === 'EROFS') {
throw new Error(
`Cannot create binary cache directory on read-only filesystem: ${cacheEntryDir}\n` +
'Ensure the filesystem is writable or set SOCKET_DLX_DIR to a writable location.',
{ cause: e },
)
}
throw new Error(
`Failed to create binary cache directory: ${cacheEntryDir}`,
{ cause: e },
)
}
// Download the binary.
const computedIntegrity = await downloadBinaryFile(
url,
binaryPath,
integrity,
sha256,
)
// Get file size for metadata.
const stats = await fs.promises.stat(binaryPath)
await writeBinaryCacheMetadata(
cacheEntryDir,
cacheKey,
url,
computedIntegrity || '',
stats.size,
)
downloaded = true
}
return {
binaryPath,
downloaded,
}
}
/**
* Download a file from a URL with integrity checking and concurrent download protection.
* Uses processLock to prevent multiple processes from downloading the same binary simultaneously.
* Internal helper function for downloading binary files.
*
* Supports two integrity verification methods:
* - sha256: Hex SHA-256 checksum (verified inline during download via httpDownload)
* - integrity: SRI format sha512-<base64> (verified post-download)
*
* The sha256 option is preferred as it fails early during download if the checksum doesn't match.
*
* @example
* ```typescript
* const integrity = await downloadBinaryFile(
* 'https://example.com/tool-linux-x64',
* '/tmp/dlx-cache/tool'
* )
* console.log(`Integrity: ${integrity}`)
* ```
*/
export async function downloadBinaryFile(
url: string,
destPath: string,
integrity?: string | undefined,
sha256?: string | undefined,
): Promise<string> {
// Use process lock to prevent concurrent downloads.
// Lock is placed in the cache entry directory as 'concurrency.lock'.
const crypto = getCrypto()
const fs = getFs()
const path = getPath()
const cacheEntryDir = path.dirname(destPath)
const lockPath = path.join(cacheEntryDir, 'concurrency.lock')
return await processLock.withLock(
lockPath,
async () => {
// Check if file was downloaded while waiting for lock.
if (fs.existsSync(destPath)) {
const stats = await fs.promises.stat(destPath)
if (stats.size > 0) {
// File exists, compute and return SRI integrity hash.
const fileBuffer = await fs.promises.readFile(destPath)
const hash = crypto
.createHash('sha512')
.update(fileBuffer)
.digest('base64')
return `sha512-${hash}`
}
}
// Download the file with optional SHA-256 verification.
// The sha256 option enables inline verification during download,
// which is more secure as it fails early if the checksum doesn't match.
try {
await httpDownload(url, destPath, sha256 ? { sha256 } : undefined)
} catch (e) {
throw new Error(
`Failed to download binary from ${url}\n` +
`Destination: ${destPath}\n` +
'Check your internet connection or verify the URL is accessible.',
{ cause: e },
)
}
// Compute SRI integrity hash of downloaded file.
const fileBuffer = await fs.promises.readFile(destPath)
const hash = crypto
.createHash('sha512')
.update(fileBuffer)
.digest('base64')
const actualIntegrity = `sha512-${hash}`
// Verify integrity if provided (constant-time comparison).
if (integrity) {
const integrityMatch =
actualIntegrity.length === integrity.length &&
crypto.timingSafeEqual(
Buffer.from(actualIntegrity),
Buffer.from(integrity),
)
if (!integrityMatch) {
// Clean up invalid file.
await safeDelete(destPath)
throw new Error(
`Integrity mismatch: expected ${integrity}, got ${actualIntegrity}`,
)
}
}
// Make executable on POSIX systems.
if (!WIN32) {
await fs.promises.chmod(destPath, 0o755)
}
return actualIntegrity
},
{
// Align with npm npx locking strategy.
staleMs: 5000,
touchIntervalMs: 2000,
},
)
}
/**
* Execute a cached binary without re-downloading.
* Similar to executePackage from dlx-package.
* Binary must have been previously downloaded via downloadBinary or dlxBinary.
*
* @param binaryPath Path to the cached binary (from downloadBinary result)
* @param args Arguments to pass to the binary
* @param spawnOptions Spawn options for execution
* @param spawnExtra Extra spawn configuration
* @returns The spawn promise for the running process
*
* @example
* ```typescript
* const { binaryPath } = await downloadBinary({
* url: 'https://example.com/tool-linux-x64',
* name: 'tool',
* })
* const result = executeBinary(binaryPath, ['--help'])
* ```
*/
export function executeBinary(
binaryPath: string,
args: readonly string[] | string[],
spawnOptions?: SpawnOptions | undefined,
spawnExtra?: SpawnExtra | undefined,
): ReturnType<typeof spawn> {
// On Windows, script files (.bat, .cmd, .ps1) require shell: true because
// they are not executable on their own and must be run through cmd.exe.
// Note: .exe files are actual binaries and don't need shell mode.
const needsShell = WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath)
// Windows cmd.exe PATH resolution behavior:
// When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically
// strip the full path down to just the basename without extension. Windows cmd.exe
// then searches for the binary in directories listed in PATH.
//
// Since our binaries are downloaded to a custom cache directory that's not in PATH,
// we must prepend the cache directory to PATH so cmd.exe can locate the binary.
const path = getPath()
const cacheEntryDir = path.dirname(binaryPath)
const finalSpawnOptions = needsShell
? {
...spawnOptions,
env: {
...spawnOptions?.env,
PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,
},
shell: true,
}
: spawnOptions
return spawn(binaryPath, args, finalSpawnOptions, spawnExtra)
}
/**
* Get metadata file path for a cached binary.
*
* @example
* ```typescript
* const metaPath = getBinaryCacheMetadataPath('/tmp/dlx-cache/a1b2c3d4')
* // '/tmp/dlx-cache/a1b2c3d4/.dlx-metadata.json'
* ```
*/
export function getBinaryCacheMetadataPath(cacheEntryPath: string): string {
return getPath().join(cacheEntryPath, '.dlx-metadata.json')
}
/**
* Get the DLX binary cache directory path.
* Alias of `getSocketDlxDir` — DLX binary cache uses the same directory
* as dlx-package for unified DLX storage.
*
* @example
* ```typescript
* const cachePath = getDlxCachePath()
* ```
*/
export const getDlxCachePath = getSocketDlxDir
/**
* Check if a cached binary is still valid.
*
* @example
* ```typescript
* const ttl = 7 * 24 * 60 * 60 * 1000
* const valid = await isBinaryCacheValid('/tmp/dlx-cache/a1b2c3d4', ttl)
* if (!valid) {
* // Re-download the binary
* }
* ```
*/
export async function isBinaryCacheValid(
cacheEntryPath: string,
cacheTtl: number,
): Promise<boolean> {
const fs = getFs()
try {
const metaPath = getBinaryCacheMetadataPath(cacheEntryPath)
if (!fs.existsSync(metaPath)) {
return false
}
const metadata = await readJson(metaPath, { throws: false })
if (!isObjectObject(metadata)) {
return false
}
const now = Date.now()
const timestamp = (metadata as Record<string, unknown>)['timestamp']
// If timestamp is missing or invalid, cache is invalid
if (typeof timestamp !== 'number' || timestamp <= 0) {
return false
}
const age = now - timestamp
// Reject future timestamps (clock skew or corruption)
if (age < 0) {
return false
}
return age < cacheTtl
} catch {
return false
}
}
/**
* Get information about cached binaries.
*
* @example
* ```typescript
* const entries = await listDlxCache()
* for (const entry of entries) {
* console.log(`${entry.name}: ${entry.size} bytes`)
* }
* ```
*/
export async function listDlxCache(): Promise<
Array<{
age: number
integrity: string
name: string
size: number
url: string
}>
> {
const cacheDir = getDlxCachePath()
const fs = getFs()
if (!fs.existsSync(cacheDir)) {
return []
}
const results = []
const now = Date.now()
const path = getPath()
const entries = await fs.promises.readdir(cacheDir)
for (const entry of entries) {
const entryPath = path.join(cacheDir, entry)
try {
// eslint-disable-next-line no-await-in-loop
if (!(await isDir(entryPath))) {
continue
}
const metaPath = getBinaryCacheMetadataPath(entryPath)
// eslint-disable-next-line no-await-in-loop
const metadata = await readJson(metaPath, { throws: false })
if (
!metadata ||
typeof metadata !== 'object' ||
Array.isArray(metadata)
) {
continue
}
const metaObj = metadata as Record<string, unknown>
// Get URL from unified schema (source.url) or legacy schema (url).
// Allow empty URL for backward compatibility with partial metadata.
const source = metaObj['source'] as Record<string, unknown> | undefined
const url =
(source?.['url'] as string) || (metaObj['url'] as string) || ''
// Find the binary file in the directory.
// eslint-disable-next-line no-await-in-loop
const files = await fs.promises.readdir(entryPath)
const binaryFile = files.find(f => !f.startsWith('.'))
if (binaryFile) {
const binaryPath = path.join(entryPath, binaryFile)
// eslint-disable-next-line no-await-in-loop
const binaryStats = await fs.promises.stat(binaryPath)
results.push({
age: now - ((metaObj['timestamp'] as number) || 0),
integrity: (metaObj['integrity'] as string) || '',
name: binaryFile,
size: binaryStats.size,
url,
})
}
} catch {}
}
return results
}
/**
* Write metadata for a cached binary.
* Uses unified schema shared with C++ decompressor and CLI dlxBinary.
* Schema documentation: See DlxMetadata interface in this file (exported).
*
* @example
* ```typescript
* await writeBinaryCacheMetadata(
* '/tmp/dlx-cache/a1b2c3d4',
* 'a1b2c3d4',
* 'https://example.com/tool',
* 'sha512-abc123...',
* 15000000
* )
* ```
*/
export async function writeBinaryCacheMetadata(
cacheEntryPath: string,
cacheKey: string,
url: string,
integrity: string,
size: number,
): Promise<void> {
const metaPath = getBinaryCacheMetadataPath(cacheEntryPath)
const metadata: DlxMetadata = {
version: '1.0.0',
cache_key: cacheKey,
timestamp: Date.now(),
integrity,
size,
source: {
type: 'download',
url,
},
}
const fs = getFs()
// Use atomic write-then-rename pattern to prevent corruption on crash
const tmpPath = `${metaPath}.tmp.${process.pid}`
await fs.promises.writeFile(tmpPath, JSON.stringify(metadata, null, 2))
await fs.promises.rename(tmpPath, metaPath)
}