-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.ts
More file actions
283 lines (265 loc) · 9.24 KB
/
binary.ts
File metadata and controls
283 lines (265 loc) · 9.24 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
/**
* @fileoverview DLX binary execution utilities for Socket ecosystem.
*
* High-level entry points for downloading standalone URL-hosted
* binaries (not npm packages — see `./package` for those) and
* executing them with cross-platform shell handling.
*
* - `dlxBinary` — download (if needed) + execute
* - `executeBinary` — execute an already-cached binary
*
* Supporting surface lives in sibling leaves and is re-exported here
* so existing `dlx/binary` importers keep working unchanged:
*
* - lazy `node:fs` / `node:path` / `node:crypto` + LRU cache — `./_internal`
* - types — `./binary-types`
* - on-disk cache metadata — `./binary-cache`
* - download + integrity verification — `./binary-download`
*/
import process from 'node:process'
import { getArch, WIN32 } from '../constants/platform'
import { DLX_BINARY_CACHE_TTL } from '../constants/time'
import { readJson } from '../fs/read-json'
import { safeMkdir } from '../fs/safe'
import { normalizePath } from '../paths/normalize'
import { spawn } from '../spawn/spawn'
import { generateCacheKey } from './cache'
import { normalizeHash } from './integrity'
import { ArrayIsArray } from '../primordials/array'
import { ErrorCtor } from '../primordials/error'
import { getNodeFs } from '../node/fs'
import { getNodePath } from '../node/path'
import {
getBinaryCacheMetadataPath,
getDlxCachePath,
isBinaryCacheValid,
writeBinaryCacheMetadata,
} from './binary-cache'
import { downloadBinaryFile } from './binary-download'
import type { DlxBinaryOptions, DlxBinaryResult } from './binary-types'
import type { SpawnExtra, SpawnOptions } from '../spawn/types'
/**
* 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 = getNodeFs()
const path = getNodePath()
// 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' &&
!ArrayIsArray(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 ErrorCtor(
`Permission denied creating binary cache directory: ${cacheEntryDir}\n` +
'Please check directory permissions or run with appropriate access.',
{ cause: e },
)
}
if (code === 'EROFS') {
throw new ErrorCtor(
`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 ErrorCtor(
`Failed to create binary cache directory: ${cacheEntryDir}`,
{ cause: e },
)
}
// Download the binary.
computedIntegrity = await downloadBinaryFile(
url,
binaryPath,
integrity,
sha256,
)
// Get file size for metadata (intentional: need stats.size, not just existence).
// oxlint-disable-next-line socket/prefer-exists-sync
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. Windows cmd.exe
// then searches for the binary in directories listed in PATH, trying each extension
// from PATHEXT environment variable 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.
const finalSpawnOptions = needsShell
? {
...spawnOptions,
env: {
...spawnOptions?.env,
PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,
},
shell: true,
}
: spawnOptions
const spawnPromise = spawn(binaryPath, args, finalSpawnOptions, spawnExtra)
return {
binaryPath,
downloaded,
spawnPromise,
}
}
/**
* 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: prepend cache dir to PATH so cmd.exe can locate the binary.
const path = getNodePath()
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)
}
// Re-exports — preserve the historical `dlx/binary` surface so
// downstream importers don't have to chase the split. The lazy
// `node:fs` / `node:path` / `node:crypto` loaders were removed: use
// the canonical `getNodeFs` / `getNodePath` / `getNodeCrypto` from
// `@socketsecurity/lib/node/{fs,path,crypto}` instead.
export {
cleanDlxCache,
getBinaryCacheMetadataPath,
getDlxCachePath,
isBinaryCacheValid,
listDlxCache,
writeBinaryCacheMetadata,
} from './binary-cache'
export { downloadBinary, downloadBinaryFile } from './binary-download'
export type {
DlxBinaryOptions,
DlxBinaryResult,
DlxMetadata,
} from './binary-types'