@socketsecurity/lib 5.6.0 → 5.8.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 (49) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/README.md +190 -18
  3. package/dist/archives.d.ts +58 -0
  4. package/dist/archives.js +313 -0
  5. package/dist/arrays.js +2 -3
  6. package/dist/cache-with-ttl.js +25 -6
  7. package/dist/constants/node.js +2 -1
  8. package/dist/cover/formatters.js +5 -3
  9. package/dist/dlx/binary.d.ts +20 -0
  10. package/dist/dlx/binary.js +115 -99
  11. package/dist/dlx/detect.d.ts +8 -8
  12. package/dist/dlx/detect.js +18 -18
  13. package/dist/dlx/manifest.d.ts +32 -31
  14. package/dist/dlx/manifest.js +114 -112
  15. package/dist/dlx/package.d.ts +55 -0
  16. package/dist/dlx/package.js +90 -80
  17. package/dist/env/ci.js +1 -2
  18. package/dist/env/rewire.d.ts +33 -22
  19. package/dist/env/rewire.js +20 -7
  20. package/dist/env/socket-cli.d.ts +24 -24
  21. package/dist/env/socket-cli.js +12 -12
  22. package/dist/env/temp-dir.d.ts +6 -6
  23. package/dist/env/temp-dir.js +4 -4
  24. package/dist/env/windows.d.ts +6 -6
  25. package/dist/env/windows.js +4 -4
  26. package/dist/external/@npmcli/package-json.js +352 -824
  27. package/dist/external/adm-zip.js +2695 -0
  28. package/dist/external/debug.js +183 -7
  29. package/dist/external/external-pack.js +19 -1409
  30. package/dist/external/libnpmexec.js +2 -2
  31. package/dist/external/npm-pack.js +18777 -19997
  32. package/dist/external/pico-pack.js +29 -5
  33. package/dist/external/spdx-pack.js +41 -263
  34. package/dist/external/tar-fs.js +3053 -0
  35. package/dist/git.js +22 -4
  36. package/dist/github.js +17 -9
  37. package/dist/globs.js +20 -1
  38. package/dist/http-request.js +1 -1
  39. package/dist/memoization.js +22 -13
  40. package/dist/package-extensions.js +4 -2
  41. package/dist/packages/normalize.js +3 -0
  42. package/dist/packages/specs.js +1 -1
  43. package/dist/process-lock.js +4 -2
  44. package/dist/releases/github.d.ts +55 -4
  45. package/dist/releases/github.js +203 -101
  46. package/dist/spawn.js +1 -1
  47. package/dist/spinner.js +1 -1
  48. package/dist/stdio/progress.js +2 -2
  49. package/package.json +38 -15
package/CHANGELOG.md CHANGED
@@ -5,6 +5,92 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [5.8.0](https://github.com/SocketDev/socket-lib/releases/tag/v5.8.0) - 2026-03-10
9
+
10
+ ### Added
11
+
12
+ - **archives**: Added secure archive extraction utilities with support for ZIP, TAR, TAR.GZ, and TGZ formats
13
+ - Configurable limits: `maxFileSize` (default 100MB), `maxTotalSize` (default 1GB)
14
+ - Cross-platform path normalization
15
+ - External dependencies: adm-zip@0.5.16, tar-fs@3.1.2 (bundled, +212KB)
16
+ - Security features: path traversal protection, file size limits, total size limits, symlink blocking
17
+ - Strip option to remove leading path components (like tar `--strip-components`)
18
+ - `detectArchiveFormat()` - Detect archive type from file extension
19
+ - `extractArchive()` - Generic extraction with auto-format detection
20
+ - `extractTar()`, `extractTarGz()`, `extractZip()` - Format-specific extractors
21
+
22
+ - **releases/github**: Added archive extraction support for GitHub releases
23
+ - Auto-detects format from asset filename
24
+ - Enhanced `downloadAndExtractZip()` to use generic archive helpers
25
+ - Supports ZIP, TAR, TAR.GZ, and TGZ assets
26
+ - `downloadAndExtractArchive()` - Generic archive download and extraction
27
+
28
+ ### Changed
29
+
30
+ - **dependencies**: Deduplicated 14 external bundle packages to single versions using pnpm overrides and patches
31
+
32
+ ## [5.7.0](https://github.com/SocketDev/socket-lib/releases/tag/v5.7.0) - 2026-02-12
33
+
34
+ ### Added
35
+
36
+ - **env**: Added `isInEnv()` helper function to check if an environment variable key exists, regardless of its value
37
+ - Returns `true` even for empty strings, `"false"`, `"0"`, etc.
38
+ - Follows same override resolution order as `getEnvValue()` (isolated overrides → shared overrides → process.env)
39
+ - Useful for detecting presence of environment variables independent of their value
40
+
41
+ - **dlx**: Added new exported helper functions
42
+ - `downloadBinaryFile()` - Downloads a binary file from a URL to the dlx cache directory
43
+ - `ensurePackageInstalled()` - Ensures an npm package is installed and cached via Arborist
44
+ - `getBinaryCacheMetadataPath()` - Gets the file path to dlx binary cache metadata (`.dlx-metadata.json`)
45
+ - `isBinaryCacheValid()` - Checks if a cached dlx binary is still valid based on TTL and timestamp
46
+ - `makePackageBinsExecutable()` - Makes npm package binaries executable on Unix systems
47
+ - `parsePackageSpec()` - Parses npm package spec strings (e.g., `pkg@1.0.0`) into name and version
48
+ - `resolveBinaryPath()` - Resolves the absolute path to a binary within an installed package
49
+ - `writeBinaryCacheMetadata()` - Writes dlx binary cache metadata with integrity, size, and source info
50
+
51
+ - **releases**: Added `createAssetMatcher()` utility function for GitHub release asset pattern matching
52
+ - Creates matcher functions that test strings against glob patterns, prefix/suffix, or RegExp
53
+ - Used for dynamic asset discovery in GitHub releases (e.g., matching platform-specific binaries)
54
+
55
+ ### Changed
56
+
57
+ - **env**: Updated `getCI()` to use `isInEnv()` for more accurate CI detection
58
+ - Now returns `true` whenever the `CI` key exists in the environment, not just when truthy
59
+ - Matches standard CI detection behavior where the presence of the key (not its value) indicates a CI environment
60
+
61
+ ### Fixed
62
+
63
+ - **github**: Fixed JSON parsing crash vulnerability by adding try-catch around `JSON.parse()` in GitHub API responses
64
+ - Prevents crashes on malformed, incomplete, or binary responses
65
+ - Error messages now include the response URL for better debugging
66
+
67
+ - **dlx/binary**: Fixed clock skew vulnerabilities in cache validation
68
+ - Cache entries with future timestamps (clock skew) are now treated as expired
69
+ - Metadata writes now use atomic write-then-rename pattern to prevent corruption
70
+ - Added TOCTOU race protection by re-checking binary existence after metadata read
71
+
72
+ - **dlx/cache cleanup**: Fixed handling of future timestamps during cache cleanup
73
+ - Entries with future timestamps (due to clock skew) are now properly treated as expired
74
+
75
+ - **dlx/package**: Fixed scoped package parsing bug where `@scope/package` was incorrectly parsed
76
+ - Changed condition from `startsWith('@')` to `atIndex === 0` for more precise detection
77
+ - Fixes installation failures for scoped packages like `@socketregistry/lib`
78
+
79
+ - **cache-with-ttl**: Added clock skew detection to TTL cache
80
+ - Far-future `expiresAt` values (>2x TTL) are now treated as expired
81
+ - Protects against cache poisoning from clock skew
82
+
83
+ - **packages/specs**: Fixed unconditional `.git` truncation in Git URL parsing
84
+ - Now only removes `.git` suffix when URL actually ends with `.git`
85
+ - Prevents incorrect truncation of URLs containing `.git` in the middle
86
+
87
+ - **releases/github**: Fixed TOCTOU race condition in binary download verification
88
+ - Re-checks binary existence after reading version file
89
+ - Ensures binary is re-downloaded if missing despite version file presence
90
+
91
+ - **provenance**: Fixed incorrect package name in provenance workflow
92
+ - Changed from `@socketregistry/lib` to `@socketsecurity/lib`
93
+
8
94
  ## [5.6.0](https://github.com/SocketDev/socket-lib/releases/tag/v5.6.0) - 2026-02-08
9
95
 
10
96
  ### Added
@@ -811,7 +897,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
811
897
 
812
898
  ### Changed
813
899
 
814
- - **DLX binary metadata structure**: Updated `writeMetadata()` to use unified schema with additional fields
900
+ - **DLX binary metadata structure**: Updated `writeBinaryCacheMetadata()` to use unified schema with additional fields
815
901
  - Now includes `cache_key` (first 16 chars of SHA-512 hash)
816
902
  - Added `size` field for cached binary size
817
903
  - Added `checksum_algorithm` field (currently "sha256")
@@ -1010,6 +1096,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
1096
  This release completely refactors the environment variable system, consolidating 60+ individual env constant files into grouped getter modules with AsyncLocalStorage-based test rewiring.
1011
1097
 
1012
1098
  **Consolidated env files** - Individual files replaced with grouped modules:
1099
+
1013
1100
  - `env/github.ts` - All GitHub-related env vars (GITHUB_TOKEN, GH_TOKEN, GITHUB_API_URL, etc.)
1014
1101
  - `env/socket.ts` - Socket-specific env vars (SOCKET_API_TOKEN, SOCKET_CACACHE_DIR, etc.)
1015
1102
  - `env/socket-cli.ts` - Socket CLI env vars (SOCKET_CLI_API_TOKEN, SOCKET_CLI_CONFIG, etc.)
@@ -1021,6 +1108,7 @@ This release completely refactors the environment variable system, consolidating
1021
1108
  - `env/test.ts` - Test framework env vars (VITEST, JEST_WORKER_ID)
1022
1109
 
1023
1110
  **Constants → Getter functions** - All env constants converted to functions:
1111
+
1024
1112
  ```typescript
1025
1113
  // Before (v1.x):
1026
1114
  import { GITHUB_TOKEN } from '#env/github-token'
@@ -1030,6 +1118,7 @@ import { getGithubToken } from '#env/github'
1030
1118
  ```
1031
1119
 
1032
1120
  **Deleted files** - Removed 60+ individual env constant files:
1121
+
1033
1122
  - `env/github-token.ts`, `env/socket-api-token.ts`, etc. → Consolidated into grouped files
1034
1123
  - `env/getters.ts` → Functions moved to their respective grouped files
1035
1124
 
@@ -1059,6 +1148,7 @@ afterEach(() => {
1059
1148
  ```
1060
1149
 
1061
1150
  **Features:**
1151
+
1062
1152
  - Allows toggling between snapshot and live behavior
1063
1153
  - Compatible with `vi.stubEnv()` as fallback
1064
1154
 
@@ -1161,7 +1251,7 @@ afterEach(() => {
1161
1251
  ### Added
1162
1252
 
1163
1253
  - Added `dlx-package` module for installing and executing npm packages directly
1164
- - Content-addressed caching using SHA256 hash (like npm's _npx)
1254
+ - Content-addressed caching using SHA256 hash (like npm's \_npx)
1165
1255
  - Auto-force for version ranges (^, ~, >, <) to get latest within range
1166
1256
  - Cross-platform support with comprehensive tests (30 tests)
1167
1257
  - Parses scoped and unscoped package specs correctly
package/README.md CHANGED
@@ -7,47 +7,219 @@
7
7
  [![Follow @SocketSecurity](https://img.shields.io/twitter/follow/SocketSecurity?style=social)](https://twitter.com/SocketSecurity)
8
8
  [![Follow @socket.dev on Bluesky](https://img.shields.io/badge/Follow-@socket.dev-1DA1F2?style=social&logo=bluesky)](https://bsky.app/profile/socket.dev)
9
9
 
10
- Core library for [Socket.dev](https://socket.dev/) tools.
10
+ Core infrastructure library for [Socket.dev](https://socket.dev/) security tools. Provides utilities for file system operations, process spawning, HTTP requests, environment detection, logging, spinners, and more.
11
+
12
+ ## Prerequisites
13
+
14
+ **Node.js 22 or higher** is required.
11
15
 
12
16
  ## Install
13
17
 
14
18
  ```bash
19
+ # Using pnpm (recommended)
15
20
  pnpm add @socketsecurity/lib
21
+
22
+ # Using npm
23
+ npm install @socketsecurity/lib
24
+
25
+ # Using yarn
26
+ yarn add @socketsecurity/lib
16
27
  ```
17
28
 
18
- ## Usage
29
+ ## Quick Start
19
30
 
20
31
  ```typescript
21
- // Tree-shakeable exports
22
32
  import { Spinner } from '@socketsecurity/lib/spinner'
23
- import { readJsonFile } from '@socketsecurity/lib/fs'
24
- import { NODE_MODULES } from '@socketsecurity/lib/constants/packages'
33
+ import { getDefaultLogger } from '@socketsecurity/lib/logger'
34
+ import { readJson } from '@socketsecurity/lib/fs'
35
+
36
+ const logger = getDefaultLogger()
37
+ const spinner = Spinner({ text: 'Loading package.json...' })
25
38
 
26
- const spinner = Spinner({ text: 'Loading...' })
27
39
  spinner.start()
28
- const pkg = await readJsonFile('./package.json')
29
- spinner.stop()
40
+ const pkg = await readJson('./package.json')
41
+ spinner.successAndStop('Loaded successfully')
42
+
43
+ logger.success(`Package: ${pkg.name}@${pkg.version}`)
30
44
  ```
31
45
 
46
+ ## Documentation
47
+
48
+ - [Getting Started](./docs/getting-started.md) - Prerequisites, installation, and first examples
49
+ - [Visual Effects](./docs/visual-effects.md) - Spinners, loggers, themes, and progress indicators
50
+ - [File System](./docs/file-system.md) - File operations, globs, paths, and safe deletion
51
+ - [HTTP Utilities](./docs/http-utilities.md) - Making requests, downloading files, and retry logic
52
+ - [Process Utilities](./docs/process-utilities.md) - Spawning processes, IPC, and locks
53
+ - [Package Management](./docs/package-management.md) - npm/pnpm/yarn detection and operations
54
+ - [Environment](./docs/environment.md) - CI detection, env getters, and platform checks
55
+ - [Constants](./docs/constants.md) - Node versions, npm URLs, and platform values
56
+ - [Examples](./docs/examples.md) - Real-world usage patterns
57
+ - [Troubleshooting](./docs/troubleshooting.md) - Common issues and solutions
58
+
32
59
  ## What's Inside
33
60
 
34
- - **Visual Effects** → logger, spinner, themes
35
- - **File System** → fs, globs, paths
36
- - **Package Management** → dlx, npm, pnpm, yarn
37
- - **Process & Spawn** → process spawning
38
- - **Environment** env getters
39
- - **Constants** node, npm, platform
40
- - **Utilities** arrays, objects, promises, strings
61
+ ### Visual Effects
62
+
63
+ Spinners, colored loggers, themes, progress bars, and terminal output formatting.
64
+
65
+ - `Spinner` - Animated CLI spinners with progress tracking
66
+ - `getDefaultLogger()` - Colored console logger with symbols
67
+ - `LOG_SYMBOLS` - Colored terminal symbols (✓, ✗, ⚠, ℹ, →)
68
+ - `setTheme()` - Customize colors across the library
69
+
70
+ ### File System
71
+
72
+ Cross-platform file operations with safe deletion and convenient wrappers.
73
+
74
+ - `readFileUtf8()`, `readFileBinary()` - Read files as text or binary
75
+ - `readJson()`, `writeJson()` - Parse and format JSON files
76
+ - `safeDelete()` - Protected deletion with safety checks
77
+ - `findUp()`, `findUpSync()` - Traverse up to find files
78
+ - `safeMkdir()` - Create directories without EEXIST errors
79
+ - `validateFiles()` - Check file readability (useful for Yarn PnP, pnpm)
80
+
81
+ ### HTTP Utilities
82
+
83
+ Native Node.js HTTP/HTTPS requests with retry logic and redirects.
84
+
85
+ - `httpJson()` - Fetch and parse JSON from APIs
86
+ - `httpText()` - Fetch text/HTML content
87
+ - `httpDownload()` - Download files with progress callbacks
88
+ - `httpRequest()` - Full control over requests and responses
89
+ - Automatic redirects, exponential backoff retries, timeout support
90
+
91
+ ### Process Management
92
+
93
+ Spawn child processes safely with cross-platform support.
94
+
95
+ - `spawn()` - Promise-based process spawning with output capture
96
+ - `spawnSync()` - Synchronous version for blocking operations
97
+ - Array-based arguments prevent command injection
98
+ - Automatic Windows `.cmd`/`.bat` handling
99
+ - `ProcessLock` - Ensure only one instance runs at a time
100
+ - `setupIPC()` - Inter-process communication
101
+
102
+ ### Environment Detection
103
+
104
+ Type-safe environment variable access and platform detection.
105
+
106
+ - `getCI()` - Detect CI environment
107
+ - `getNodeEnv()` - Get NODE_ENV value
108
+ - `isTest()` - Check if running tests
109
+ - `getHome()` - Home directory (Unix/Linux/macOS)
110
+ - Test rewiring with `setEnv()`, `resetEnv()`
111
+
112
+ ### Package Management
113
+
114
+ Detect and work with npm, pnpm, and yarn.
115
+
116
+ - `detectPackageManager()` - Identify package manager from lock files
117
+ - Package manifest operations
118
+ - Lock file management
119
+
120
+ ### Constants
121
+
122
+ Pre-defined values for Node.js, npm, and platform detection.
123
+
124
+ - `getNodeMajorVersion()` - Get current Node.js major version
125
+ - `WIN32`, `DARWIN` - Platform booleans (use `!WIN32 && !DARWIN` for Linux)
126
+ - `getAbortSignal()` - Global abort signal
127
+
128
+ ### Utilities
129
+
130
+ Helpers for arrays, objects, strings, promises, sorting, and more.
131
+
132
+ - Arrays, objects, strings manipulation
133
+ - Promise utilities and queues
134
+ - Natural sorting
135
+ - Version comparison
136
+ - Error handling with causes
137
+
138
+ ## Features
139
+
140
+ - **Tree-shakeable exports** - Import only what you need
141
+ - **Cross-platform** - Works on Windows, macOS, and Linux
142
+ - **TypeScript-first** - Full type safety with .d.ts files
143
+ - **Zero dependencies** (for core HTTP - uses Node.js native modules)
144
+ - **Well-tested** - 84% coverage with comprehensive test suite
145
+ - **Security-focused** - Safe defaults, command injection protection
146
+ - **CommonJS output** - Compatible with Node.js tooling
147
+
148
+ ## Common Use Cases
149
+
150
+ ### Running Shell Commands
151
+
152
+ ```typescript
153
+ import { spawn } from '@socketsecurity/lib/spawn'
154
+
155
+ const result = await spawn('git', ['status'])
156
+ console.log(result.stdout)
157
+ ```
158
+
159
+ ### Making API Requests
160
+
161
+ ```typescript
162
+ import { httpJson } from '@socketsecurity/lib/http-request'
163
+
164
+ const data = await httpJson('https://api.example.com/data')
165
+ ```
166
+
167
+ ### Visual Feedback
168
+
169
+ ```typescript
170
+ import { Spinner } from '@socketsecurity/lib/spinner'
171
+
172
+ const spinner = Spinner({ text: 'Processing...' })
173
+ spinner.start()
174
+ // ... do work ...
175
+ spinner.successAndStop('Complete!')
176
+ ```
177
+
178
+ ### Safe File Deletion
179
+
180
+ ```typescript
181
+ import { safeDelete } from '@socketsecurity/lib/fs'
182
+
183
+ // Protected against deleting parent directories
184
+ await safeDelete('./build')
185
+ ```
186
+
187
+ ## Troubleshooting
188
+
189
+ **Module not found**: Verify you're importing from the correct path:
190
+
191
+ ```typescript
192
+ // Correct
193
+ import { Spinner } from '@socketsecurity/lib/spinner'
194
+
195
+ // Wrong
196
+ import { Spinner } from '@socketsecurity/lib'
197
+ ```
198
+
199
+ **Node version error**: This library requires Node.js 22+. Check your version:
200
+
201
+ ```bash
202
+ node --version
203
+ ```
204
+
205
+ For more issues, see the [Troubleshooting Guide](./docs/troubleshooting.md).
41
206
 
42
207
  ## Development
43
208
 
44
209
  ```bash
45
- pnpm install # Install
46
- pnpm build # Build
47
- pnpm test # Test
210
+ pnpm install # Install dependencies
211
+ pnpm build # Build the library
212
+ pnpm test # Run tests
213
+ pnpm run cover # Run tests with coverage
48
214
  pnpm dev # Watch mode
215
+ pnpm run lint # Check code style
216
+ pnpm run fix # Fix formatting issues
49
217
  ```
50
218
 
219
+ ## Contributing
220
+
221
+ Contributions are welcome! Please read the [CLAUDE.md](./CLAUDE.md) file for development guidelines and coding standards.
222
+
51
223
  ## License
52
224
 
53
225
  MIT
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Archive format type.
3
+ */
4
+ export type ArchiveFormat = 'tar' | 'tar.gz' | 'tgz' | 'zip';
5
+ /**
6
+ * Options for archive extraction.
7
+ */
8
+ export interface ExtractOptions {
9
+ /** Suppress log messages */
10
+ quiet?: boolean;
11
+ /** Strip leading path components (like tar --strip-components) */
12
+ strip?: number;
13
+ /** Maximum size of a single extracted file in bytes (default: 100MB) */
14
+ maxFileSize?: number;
15
+ /** Maximum total extracted size in bytes (default: 1GB) */
16
+ maxTotalSize?: number;
17
+ }
18
+ /**
19
+ * Detect archive format from file path.
20
+ *
21
+ * @param filePath - Path to archive file
22
+ * @returns Archive format or null if unknown
23
+ */
24
+ export declare function detectArchiveFormat(filePath: string): ArchiveFormat | null;
25
+ /**
26
+ * Extract a tar archive to a directory.
27
+ *
28
+ * @param archivePath - Path to tar file
29
+ * @param outputDir - Directory to extract to
30
+ * @param options - Extraction options
31
+ */
32
+ export declare function extractTar(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;
33
+ /**
34
+ * Extract a gzipped tar archive to a directory.
35
+ *
36
+ * @param archivePath - Path to tar.gz or tgz file
37
+ * @param outputDir - Directory to extract to
38
+ * @param options - Extraction options
39
+ */
40
+ export declare function extractTarGz(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;
41
+ /**
42
+ * Extract a zip archive to a directory.
43
+ *
44
+ * @param archivePath - Path to zip file
45
+ * @param outputDir - Directory to extract to
46
+ * @param options - Extraction options
47
+ */
48
+ export declare function extractZip(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;
49
+ /**
50
+ * Extract an archive to a directory.
51
+ * Automatically detects format from file extension.
52
+ *
53
+ * @param archivePath - Path to archive file
54
+ * @param outputDir - Directory to extract to
55
+ * @param options - Extraction options
56
+ * @throws Error if archive format is not supported
57
+ */
58
+ export declare function extractArchive(archivePath: string, outputDir: string, options?: ExtractOptions): Promise<void>;