-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathinstall.js
More file actions
348 lines (311 loc) · 10.3 KB
/
Copy pathinstall.js
File metadata and controls
348 lines (311 loc) · 10.3 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
#!/usr/bin/env node
const https = require("https");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const REPO = "tawanorg/claude-sync";
// Release downloads start at github.com and redirect to a GitHub-run asset CDN.
// That CDN host is not stable — it was objects.githubusercontent.com and is now
// release-assets.githubusercontent.com — so pinning exact hostnames breaks the
// installer whenever GitHub moves it. Match the githubusercontent.com parent
// domain instead, which stays scoped to GitHub-controlled hosts.
const ALLOWED_HOSTS = ["github.com", "api.github.com"];
const ALLOWED_HOST_SUFFIX = ".githubusercontent.com";
const MAX_REDIRECTS = 5;
function getPlatform() {
const platform = process.platform;
switch (platform) {
case "darwin":
return "darwin";
case "linux":
return "linux";
case "win32":
return "windows";
default:
throw new Error(`Unsupported platform: ${platform}`);
}
}
function getArch() {
const arch = process.arch;
switch (arch) {
case "x64":
return "amd64";
case "arm64":
return "arm64";
default:
throw new Error(`Unsupported architecture: ${arch}`);
}
}
function getBinaryName() {
const platform = getPlatform();
const arch = getArch();
const ext = platform === "windows" ? ".exe" : "";
return `claude-sync-${platform}-${arch}${ext}`;
}
function getLatestVersion() {
return new Promise((resolve, reject) => {
const options = {
hostname: "api.github.com",
path: `/repos/${REPO}/releases/latest`,
headers: {
"User-Agent": "claude-sync-installer",
},
};
https
.get(options, (response) => {
let data = "";
response.on("data", (chunk) => (data += chunk));
response.on("end", () => {
try {
const release = JSON.parse(data);
if (release.tag_name) {
// Remove 'v' prefix if present
resolve(release.tag_name.replace(/^v/, ""));
} else {
reject(new Error("No release found"));
}
} catch (e) {
reject(e);
}
});
})
.on("error", reject);
});
}
function getDownloadUrl(version) {
const binaryName = getBinaryName();
return `https://github.com/${REPO}/releases/download/v${version}/${binaryName}`;
}
function getChecksumsUrl(version) {
return `https://github.com/${REPO}/releases/download/v${version}/checksums.txt`;
}
/**
* Validates that a URL's host is in the allowed list.
*/
function isAllowedHost(url) {
try {
const parsed = new URL(url);
// https only: without this an http:// redirect to an allowed host would
// downgrade the transport and defeat the checksum's purpose.
if (parsed.protocol !== "https:") {
return false;
}
if (ALLOWED_HOSTS.includes(parsed.hostname)) {
return true;
}
// Suffix match, not endsWith on the bare domain: "evilgithubusercontent.com"
// must not pass, so the leading dot is required.
return parsed.hostname.endsWith(ALLOWED_HOST_SUFFIX);
} catch {
return false;
}
}
/**
* Downloads a URL to a buffer with redirect handling.
*/
function downloadToBuffer(url, redirectCount = 0) {
return new Promise((resolve, reject) => {
if (redirectCount > MAX_REDIRECTS) {
reject(new Error(`Too many redirects (max ${MAX_REDIRECTS})`));
return;
}
if (!isAllowedHost(url)) {
reject(new Error(`Redirect to untrusted host: ${url}`));
return;
}
https
.get(url, (response) => {
// Handle redirects
if (response.statusCode === 302 || response.statusCode === 301) {
const location = response.headers.location;
if (!location) {
reject(new Error("Redirect without location header"));
return;
}
downloadToBuffer(location, redirectCount + 1)
.then(resolve)
.catch(reject);
return;
}
if (response.statusCode !== 200) {
reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
return;
}
const chunks = [];
response.on("data", (chunk) => chunks.push(chunk));
response.on("end", () => resolve(Buffer.concat(chunks)));
response.on("error", reject);
})
.on("error", reject);
});
}
/**
* Parses checksums.txt and returns the expected hash for a given filename.
*/
function parseChecksum(checksumsContent, filename) {
const lines = checksumsContent.toString().split("\n");
for (const line of lines) {
// Format: "hash filename" or "hash *filename" (binary mode)
const match = line.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/);
if (match && match[2].trim() === filename) {
return match[1].toLowerCase();
}
}
return null;
}
/**
* Downloads a file to disk with redirect handling.
*/
function download(url, dest, redirectCount = 0) {
return new Promise((resolve, reject) => {
if (redirectCount > MAX_REDIRECTS) {
reject(new Error(`Too many redirects (max ${MAX_REDIRECTS})`));
return;
}
if (!isAllowedHost(url)) {
reject(new Error(`Redirect to untrusted host: ${url}`));
return;
}
const file = fs.createWriteStream(dest);
https
.get(url, (response) => {
// Handle redirects
if (response.statusCode === 302 || response.statusCode === 301) {
file.close();
fs.unlinkSync(dest);
const location = response.headers.location;
if (!location) {
reject(new Error("Redirect without location header"));
return;
}
download(location, dest, redirectCount + 1)
.then(resolve)
.catch(reject);
return;
}
if (response.statusCode !== 200) {
file.close();
fs.unlinkSync(dest);
reject(new Error(`Failed to download: HTTP ${response.statusCode}`));
return;
}
response.pipe(file);
file.on("finish", () => {
file.close();
resolve();
});
})
.on("error", (err) => {
file.close();
fs.unlink(dest, () => {});
reject(err);
});
});
}
/**
* Computes SHA256 hash of a file.
*/
function hashFile(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash("sha256");
const stream = fs.createReadStream(filePath);
stream.on("data", (data) => hash.update(data));
stream.on("end", () => resolve(hash.digest("hex")));
stream.on("error", reject);
});
}
// Platform-specific packages ship the binary as an optionalDependency, which
// installs faster and works offline. This download is the fallback for when one
// of them is missing — a platform npm publish that failed, an install with
// --no-optional, or a platform we have not packaged. Both paths write to the
// same place bin/claude-sync.js looks, so either satisfies the wrapper.
const PLATFORM_PACKAGES = {
"darwin-arm64": "@tawandotorg/claude-sync-darwin-arm64",
"darwin-x64": "@tawandotorg/claude-sync-darwin-x64",
"linux-arm64": "@tawandotorg/claude-sync-linux-arm64",
"linux-x64": "@tawandotorg/claude-sync-linux-x64",
"win32-arm64": "@tawandotorg/claude-sync-win32-arm64",
"win32-x64": "@tawandotorg/claude-sync-win32-x64",
};
// platformPackageBinary returns the path to a binary already provided by the
// matching optionalDependency, or null when none is installed.
function platformPackageBinary() {
const packageName = PLATFORM_PACKAGES[`${process.platform}-${process.arch}`];
if (!packageName) {
return null;
}
try {
const packageDir = path.dirname(require.resolve(`${packageName}/package.json`));
const binaryName = process.platform === "win32" ? "claude-sync.exe" : "claude-sync";
const binaryPath = path.join(packageDir, binaryName);
return fs.existsSync(binaryPath) ? binaryPath : null;
} catch (e) {
return null;
}
}
async function install() {
const binDir = path.join(__dirname, "bin");
const platform = getPlatform();
const binaryName = platform === "windows" ? "claude-sync.exe" : "claude-sync";
const binaryPath = path.join(binDir, binaryName);
const assetName = getBinaryName();
const fromPackage = platformPackageBinary();
if (fromPackage) {
console.log(`✓ Using platform package binary: ${fromPackage}`);
return;
}
// Create bin directory
if (!fs.existsSync(binDir)) {
fs.mkdirSync(binDir, { recursive: true });
}
try {
console.log("Fetching latest version...");
const version = await getLatestVersion();
const url = getDownloadUrl(version);
const checksumsUrl = getChecksumsUrl(version);
console.log(`Downloading claude-sync v${version}...`);
console.log(` Platform: ${getPlatform()}-${getArch()}`);
// Download checksums first
let expectedHash = null;
try {
console.log(" Fetching checksums...");
const checksumsData = await downloadToBuffer(checksumsUrl);
expectedHash = parseChecksum(checksumsData, assetName);
if (expectedHash) {
console.log(` Expected SHA256: ${expectedHash.substring(0, 16)}...`);
}
} catch (err) {
console.warn(` Warning: Could not fetch checksums.txt: ${err.message}`);
console.warn(" Proceeding without checksum verification.");
}
// Download binary
await download(url, binaryPath);
// Verify checksum if available
if (expectedHash) {
console.log(" Verifying checksum...");
const actualHash = await hashFile(binaryPath);
if (actualHash !== expectedHash) {
fs.unlinkSync(binaryPath);
throw new Error(
`Checksum mismatch!\n` +
` Expected: ${expectedHash}\n` +
` Actual: ${actualHash}\n` +
`This could indicate a corrupted download or tampering.`
);
}
console.log(" Checksum verified!");
}
// Make executable on Unix
if (platform !== "windows") {
fs.chmodSync(binaryPath, 0o755);
}
console.log(` Installed to: ${binaryPath}`);
console.log(`\n✓ claude-sync v${version} installed successfully!`);
} catch (err) {
console.error(`\n✗ Failed to install claude-sync: ${err.message}`);
console.error(`\nYou can manually download from:`);
console.error(` https://github.com/${REPO}/releases/latest`);
process.exit(1);
}
}
install();