-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-manager.ts
More file actions
241 lines (208 loc) · 8.33 KB
/
binary-manager.ts
File metadata and controls
241 lines (208 loc) · 8.33 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
import fs from 'fs';
import path from 'path';
import os from 'os';
import crypto from 'crypto';
import axios from 'axios';
import { promisify } from 'util';
import stream from 'stream';
import ora from 'ora';
const pipeline = promisify(stream.pipeline);
// Configuration
const BINARY_NAME = 'capiscio-core';
const REPO_OWNER = 'capiscio';
const REPO_NAME = 'capiscio-core';
// Allow version override via env var or package.json
const DEFAULT_VERSION = 'v2.6.0';
const VERSION = process.env.CAPISCIO_CORE_VERSION || DEFAULT_VERSION;
export class BinaryManager {
private static instance: BinaryManager;
private binaryPath: string;
private installDir: string;
private constructor() {
// Store binary in node_modules/.bin or a local bin directory
// We need to find the package root to ensure we store it in the right place
// regardless of whether we're running from src (dev) or dist (prod)
// Check if running in pkg
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore — 'pkg' is injected by the pkg bundler at runtime
if ('pkg' in process) {
// In pkg, we should store the binary next to the executable
this.installDir = path.dirname(process.execPath);
} else {
const packageRoot = this.findPackageRoot();
this.installDir = path.join(packageRoot, 'bin');
}
// Ensure bin directory exists
if (!fs.existsSync(this.installDir)) {
try {
fs.mkdirSync(this.installDir, { recursive: true });
} catch (_error) {
// If we can't create the directory (e.g. permission denied or read-only fs),
// fallback to a user-writable directory
this.installDir = path.join(os.homedir(), '.capiscio', 'bin');
if (!fs.existsSync(this.installDir)) {
fs.mkdirSync(this.installDir, { recursive: true });
}
}
}
const platform = this.getPlatform();
const ext = platform === 'windows' ? '.exe' : '';
this.binaryPath = path.join(this.installDir, `${BINARY_NAME}${ext}`);
}
private findPackageRoot(): string {
let currentDir = __dirname;
// Look for package.json up the directory tree
// Limit to 5 levels up to prevent infinite loops or going too far
for (let i = 0; i < 5; i++) {
if (fs.existsSync(path.join(currentDir, 'package.json'))) {
return currentDir;
}
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) break;
currentDir = parentDir;
}
// Fallback: assume we are in dist/ or src/utils/ and go up appropriately
// If we can't find package.json, we might be in a bundled environment where it's not included
// In that case, try to use the directory of the main module or process.cwd()
return path.resolve(__dirname, '..');
}
public static getInstance(): BinaryManager {
if (!BinaryManager.instance) {
BinaryManager.instance = new BinaryManager();
}
return BinaryManager.instance;
}
public async getBinaryPath(): Promise<string> {
// Check for environment variable override
if (process.env.CAPISCIO_CORE_PATH) {
if (fs.existsSync(process.env.CAPISCIO_CORE_PATH)) {
return process.env.CAPISCIO_CORE_PATH;
}
console.warn(`Warning: CAPISCIO_CORE_PATH set to '${process.env.CAPISCIO_CORE_PATH}' but file does not exist. Falling back to managed binary.`);
}
if (!fs.existsSync(this.binaryPath)) {
await this.install();
}
return this.binaryPath;
}
private async install(): Promise<void> {
const spinner = ora('Downloading CapiscIO Core binary...').start();
try {
const platform = this.getPlatform();
const arch = this.getArch();
// Construct download URL
// Assets are named: capiscio-{platform}-{arch} (e.g. capiscio-linux-amd64)
// Windows has .exe extension
let assetName = `capiscio-${platform}-${arch}`;
if (platform === 'windows') {
assetName += '.exe';
}
const url = `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${VERSION}/${assetName}`;
// Download
const response = await axios.get(url, { responseType: 'stream' });
// Write directly to a temp file
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'capiscio-'));
const tempFilePath = path.join(tempDir, assetName);
const writer = fs.createWriteStream(tempFilePath);
await pipeline(response.data, writer);
// Verify checksum integrity
await this.verifyChecksum(tempFilePath, assetName);
// Move to install dir
// We rename it to capiscio-core (or .exe) for internal consistency
fs.copyFileSync(tempFilePath, this.binaryPath);
if (platform !== 'windows') {
fs.chmodSync(this.binaryPath, 0o755); // Make executable
}
// Cleanup
fs.rmSync(tempDir, { recursive: true, force: true });
spinner.succeed(`Installed CapiscIO Core ${VERSION}`);
} catch (error: any) {
spinner.fail('Failed to install binary');
if (axios.isAxiosError(error)) {
if (error.response?.status === 404) {
console.error(`\nError: Could not find binary version ${VERSION} for ${this.getPlatform()}/${this.getArch()}`);
console.error('Please check the version and platform support.');
} else {
console.error(`\nNetwork error: ${error.message}`);
}
} else {
console.error(`\nError: ${error.message}`);
}
// Attempt cleanup if tempDir was created (though it's local to try block,
// in a real scenario we'd scope it wider or rely on OS cleanup for temp files)
throw error;
}
}
private async verifyChecksum(filePath: string, assetName: string): Promise<void> {
const requireChecksum = ['1', 'true', 'yes'].includes(
(process.env.CAPISCIO_REQUIRE_CHECKSUM ?? '').toLowerCase()
);
const checksumsUrl = `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${VERSION}/checksums.txt`;
let expectedHash: string | null = null;
try {
const resp = await axios.get(checksumsUrl, { timeout: 30000 });
const lines = (resp.data as string).trim().split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length === 2 && parts[1] === assetName) {
expectedHash = parts[0] ?? null;
break;
}
}
} catch {
if (requireChecksum) {
fs.rmSync(filePath, { force: true });
throw new Error(
'Checksum verification required (CAPISCIO_REQUIRE_CHECKSUM=true) ' +
'but checksums.txt is not available. Cannot verify binary integrity.'
);
}
console.warn('Warning: Could not fetch checksums.txt. Skipping integrity verification.');
return;
}
if (!expectedHash) {
if (requireChecksum) {
fs.rmSync(filePath, { force: true });
throw new Error(
`Checksum verification required (CAPISCIO_REQUIRE_CHECKSUM=true) ` +
`but asset ${assetName} not found in checksums.txt.`
);
}
console.warn(`Warning: Asset ${assetName} not found in checksums.txt. Skipping verification.`);
return;
}
const actualHash = await new Promise<string>((resolve, reject) => {
const hash = crypto.createHash('sha256');
const fileStream = fs.createReadStream(filePath);
fileStream.on('data', (chunk) => hash.update(chunk));
fileStream.on('end', () => resolve(hash.digest('hex')));
fileStream.on('error', reject);
});
if (actualHash !== expectedHash) {
// Remove the tampered file
fs.rmSync(filePath, { force: true });
throw new Error(
`Binary integrity check failed for ${assetName}. ` +
`Expected SHA-256: ${expectedHash}, got: ${actualHash}. ` +
'The downloaded file does not match the published checksum.'
);
}
}
private getPlatform(): string {
const platform = os.platform();
switch (platform) {
case 'darwin': return 'darwin';
case 'linux': return 'linux';
case 'win32': return 'windows';
default: throw new Error(`Unsupported platform: ${platform}`);
}
}
private getArch(): string {
const arch = os.arch();
switch (arch) {
case 'x64': return 'amd64';
case 'arm64': return 'arm64';
default: throw new Error(`Unsupported architecture: ${arch}`);
}
}
}