@zainriazdev/zpatch 0.0.0-stage → 0.6.2
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.
- package/README.md +29 -2
- package/build/zpatch.js +446 -0
- package/package.json +31 -4
package/README.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
#
|
|
1
|
+
# zpatch launcher
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Install and run zpatch, a command-line tool for updating entries across ZIP and ZIP64 archives. The public npm package installs the launcher. A verified zpatch account is required to download the private native release.
|
|
4
|
+
|
|
5
|
+
## Get started
|
|
6
|
+
|
|
7
|
+
Use Node.js 22 or later on Windows x64, Linux x64 or ARM64, or macOS with Apple silicon.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --global @zainriazdev/zpatch
|
|
11
|
+
zpatch doctor
|
|
12
|
+
zpatch login
|
|
13
|
+
zpatch --version
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Open the sign-in link on the same computer, sign in to zpatch, and approve access. The launcher detects your platform, downloads the matching bundle, and verifies its size and SHA-256 before installing it. You can [verify your email in zpatch](https://zpatch-auth.zainriaz.dev/account/email).
|
|
17
|
+
|
|
18
|
+
## Everyday commands
|
|
19
|
+
|
|
20
|
+
| Command | What it does |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| `zpatch doctor` | Shows your platform, free disk space, and whether the installed binary passes its checksum check. `missing` is expected before the first login. |
|
|
23
|
+
| `zpatch login` | Signs in through the browser and installs the current native release. |
|
|
24
|
+
| `zpatch update` | Downloads and verifies the current native release. It reuses a valid sign-in when available. |
|
|
25
|
+
| `zpatch --version` | Prints the installed native version, which can differ from the npm launcher version. |
|
|
26
|
+
| `zpatch --help` | Shows the installed CLI's commands and options. |
|
|
27
|
+
|
|
28
|
+
The launcher stores the native release under `~/.zpatch/bin/` by default and checks the installed binary's SHA-256 before running it. The npm package has no install-time scripts, runtime dependencies, native binaries, or credentials. GitHub Actions publishes the launcher through npm Trusted Publishing with provenance. [Launcher source](https://github.com/zainriaz-dev/zpatch-cli)
|
|
29
|
+
|
|
30
|
+
Report security issues privately to the maintainers.
|
package/build/zpatch.js
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
4
|
+
import { lstat, mkdir, mkdtemp, readFile, rename, rm, statfs, writeFile, realpath } from "node:fs/promises";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, join, resolve } from "node:path";
|
|
8
|
+
import { Writable, Readable, Transform } from "node:stream";
|
|
9
|
+
import { pipeline } from "node:stream/promises";
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import { createInterface } from "node:readline/promises";
|
|
12
|
+
import { pathToFileURL } from "node:url";
|
|
13
|
+
import { createGunzip } from "node:zlib";
|
|
14
|
+
const base = resolve(process.env.ZPATCH_HOME || join(homedir(), ".zpatch"));
|
|
15
|
+
const bin = join(base, "bin");
|
|
16
|
+
const credentials = join(base, "credentials.json");
|
|
17
|
+
const sha256 = /^[0-9a-f]{64}$/;
|
|
18
|
+
const versionPattern = /^[a-zA-Z0-9][\w.-]{0,63}$/;
|
|
19
|
+
const secureNames = /^(?:BREVO_API_KEY|GOOGLE_APPLICATION_CREDENTIALS|GOOGLE_API_KEY|CLOUDFLARE_API_TOKEN|APPWRITE_API_KEY|ZPATCH_LICENSE|ZPATCH_SIGNING_KEY|ZPATCH_BRIDGE_SECRET|ZPATCH_GCS_.*)$/;
|
|
20
|
+
const gatewayDefault = "https://usnode.zainriaz.dev";
|
|
21
|
+
export function detectDevice(os, arch, glibc, objects = "") {
|
|
22
|
+
const platform = os + "-" + arch;
|
|
23
|
+
if (!["linux-x64", "linux-arm64", "darwin-arm64", "win32-x64"].includes(platform))
|
|
24
|
+
throw Error("supported platforms are linux-x64, linux-arm64, darwin-arm64 and win32-x64");
|
|
25
|
+
if (os !== "linux")
|
|
26
|
+
return { platform, arch, libc: null };
|
|
27
|
+
const libc = glibc ? "glibc" : /(?:ld-musl-|libc\.musl-)/.test(objects) ? "musl" : null;
|
|
28
|
+
if (!libc)
|
|
29
|
+
throw Error("could not determine Linux libc");
|
|
30
|
+
return { platform, arch, libc };
|
|
31
|
+
}
|
|
32
|
+
async function device() {
|
|
33
|
+
if (process.platform !== "linux")
|
|
34
|
+
return detectDevice(process.platform, process.arch);
|
|
35
|
+
const report = process.report.getReport();
|
|
36
|
+
const maps = report.header?.glibcVersionRuntime ? "" : await readFile("/proc/self/maps", "utf8").catch(() => "");
|
|
37
|
+
return detectDevice(process.platform, process.arch, report.header?.glibcVersionRuntime, [...(report.sharedObjects ?? []), maps].join("\n"));
|
|
38
|
+
}
|
|
39
|
+
async function digest(path) {
|
|
40
|
+
const hash = createHash("sha256");
|
|
41
|
+
for await (const chunk of createReadStream(path))
|
|
42
|
+
hash.update(chunk);
|
|
43
|
+
return hash.digest("hex");
|
|
44
|
+
}
|
|
45
|
+
function loopback(url) {
|
|
46
|
+
return ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
47
|
+
}
|
|
48
|
+
function endpoint(raw) {
|
|
49
|
+
const url = new URL(raw);
|
|
50
|
+
if ((url.protocol !== "https:" && !(url.protocol === "http:" && loopback(url))) ||
|
|
51
|
+
url.username || url.password || url.search || url.hash || url.pathname !== "/")
|
|
52
|
+
throw Error("gateway and issuer must be HTTPS origins (HTTP is allowed on loopback)");
|
|
53
|
+
return url;
|
|
54
|
+
}
|
|
55
|
+
async function jsonRequest(url, opts = {}) {
|
|
56
|
+
const response = await fetch(url, { ...opts, redirect: "error", signal: AbortSignal.timeout(20_000) });
|
|
57
|
+
if (!response.ok) {
|
|
58
|
+
await response.body?.cancel();
|
|
59
|
+
throw Error("request failed with HTTP " + response.status);
|
|
60
|
+
}
|
|
61
|
+
const chunks = [];
|
|
62
|
+
let size = 0;
|
|
63
|
+
if (!response.body)
|
|
64
|
+
throw Error("missing JSON response");
|
|
65
|
+
const reader = response.body.getReader();
|
|
66
|
+
try {
|
|
67
|
+
for (;;) {
|
|
68
|
+
const { done, value } = await reader.read();
|
|
69
|
+
if (done)
|
|
70
|
+
break;
|
|
71
|
+
size += value.length;
|
|
72
|
+
if (size > 128 * 1024)
|
|
73
|
+
throw Error("oversized JSON response");
|
|
74
|
+
chunks.push(value);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await reader.cancel();
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw Error("invalid JSON response");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function post(payload) {
|
|
88
|
+
return { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) };
|
|
89
|
+
}
|
|
90
|
+
async function privateInput(label) {
|
|
91
|
+
if (!process.stdin.isTTY)
|
|
92
|
+
throw Error("set ZPATCH_TOKEN or ZPATCH_LICENSE for unattended login");
|
|
93
|
+
process.stderr.write(label);
|
|
94
|
+
const prompt = createInterface({
|
|
95
|
+
input: process.stdin, terminal: true,
|
|
96
|
+
output: new Writable({ write(_chunk, _encoding, done) { done(); } }),
|
|
97
|
+
});
|
|
98
|
+
try {
|
|
99
|
+
return await prompt.question("");
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
prompt.close();
|
|
103
|
+
process.stderr.write("\n");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export async function oauth(server) {
|
|
107
|
+
const resource = new URL("/mcp", server).href;
|
|
108
|
+
const prm = await jsonRequest(new URL("/.well-known/oauth-protected-resource/mcp", server));
|
|
109
|
+
if (prm.resource !== resource || typeof prm.authorization_servers?.[0] !== "string")
|
|
110
|
+
throw Error("gateway did not identify its OAuth issuer");
|
|
111
|
+
const issuer = endpoint(prm.authorization_servers[0]);
|
|
112
|
+
if (server.protocol === "https:" && issuer.protocol !== "https:")
|
|
113
|
+
throw Error("remote OAuth requires HTTPS");
|
|
114
|
+
const metadata = await jsonRequest(new URL("/.well-known/oauth-authorization-server", issuer));
|
|
115
|
+
if (metadata.issuer !== issuer.origin)
|
|
116
|
+
throw Error("unexpected OAuth issuer");
|
|
117
|
+
function oauthEndpoint(value) {
|
|
118
|
+
if (typeof value !== "string")
|
|
119
|
+
throw Error("OAuth endpoint unavailable");
|
|
120
|
+
const url = new URL(value);
|
|
121
|
+
if (url.origin !== issuer.origin || url.username || url.password || url.hash)
|
|
122
|
+
throw Error("unexpected OAuth endpoint");
|
|
123
|
+
return url;
|
|
124
|
+
}
|
|
125
|
+
const state = randomBytes(32).toString("base64url");
|
|
126
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
127
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
128
|
+
let receive;
|
|
129
|
+
let decline;
|
|
130
|
+
const callback = createServer((request, response) => {
|
|
131
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
132
|
+
const valid = request.method === "GET" && request.headers.host === callbackHost &&
|
|
133
|
+
url.pathname === "/callback" && url.searchParams.get("state") === state && url.searchParams.get("iss") === issuer.origin;
|
|
134
|
+
const code = url.searchParams.get("code");
|
|
135
|
+
response.setHeader("Connection", "close");
|
|
136
|
+
if (!valid) {
|
|
137
|
+
response.writeHead(400).end("Invalid callback.");
|
|
138
|
+
}
|
|
139
|
+
else if (!code) {
|
|
140
|
+
response.writeHead(400).end("Sign-in was not completed. Return to the terminal.");
|
|
141
|
+
decline?.(Error("sign-in denied"));
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
response.writeHead(200).end("Sign-in received. Return to the terminal.");
|
|
145
|
+
receive?.(code);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
let callbackHost = "";
|
|
149
|
+
try {
|
|
150
|
+
await new Promise((ready, fail) => {
|
|
151
|
+
callback.once("error", fail);
|
|
152
|
+
callback.listen(0, "127.0.0.1", ready);
|
|
153
|
+
});
|
|
154
|
+
const address = callback.address();
|
|
155
|
+
if (!address || typeof address === "string")
|
|
156
|
+
throw Error("cannot start OAuth callback");
|
|
157
|
+
callbackHost = "127.0.0.1:" + address.port;
|
|
158
|
+
const redirect = "http://" + callbackHost + "/callback";
|
|
159
|
+
const registration = await jsonRequest(oauthEndpoint(metadata.registration_endpoint), post({
|
|
160
|
+
client_name: "zpatch launcher", redirect_uris: [redirect], token_endpoint_auth_method: "none",
|
|
161
|
+
grant_types: ["authorization_code", "refresh_token"], response_types: ["code"],
|
|
162
|
+
}));
|
|
163
|
+
if (typeof registration.client_id !== "string")
|
|
164
|
+
throw Error("OAuth registration rejected");
|
|
165
|
+
const authorize = oauthEndpoint(metadata.authorization_endpoint);
|
|
166
|
+
authorize.search = new URLSearchParams({
|
|
167
|
+
client_id: registration.client_id, redirect_uri: redirect, resource, state,
|
|
168
|
+
response_type: "code", scope: "zpatch:read", code_challenge: challenge, code_challenge_method: "S256",
|
|
169
|
+
}).toString();
|
|
170
|
+
const code = await new Promise((accept, reject) => {
|
|
171
|
+
const timer = setTimeout(() => reject(Error("browser sign-in timed out")), 180_000);
|
|
172
|
+
receive = value => { clearTimeout(timer); accept(value); };
|
|
173
|
+
decline = error => { clearTimeout(timer); reject(error); };
|
|
174
|
+
console.error("Open this address to sign in:\n" + authorize.href);
|
|
175
|
+
});
|
|
176
|
+
const session = await jsonRequest(oauthEndpoint(metadata.token_endpoint), {
|
|
177
|
+
method: "POST", body: new URLSearchParams({
|
|
178
|
+
grant_type: "authorization_code", client_id: registration.client_id, code,
|
|
179
|
+
redirect_uri: redirect, resource, code_verifier: verifier,
|
|
180
|
+
}),
|
|
181
|
+
});
|
|
182
|
+
if (typeof session.access_token !== "string" || !Number.isFinite(session.expires_in))
|
|
183
|
+
throw Error("invalid OAuth token response");
|
|
184
|
+
return { token: session.access_token, expires: Math.floor(Date.now() / 1000) + session.expires_in };
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
callback.closeAllConnections();
|
|
188
|
+
callback.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async function authenticate(server, saved) {
|
|
192
|
+
if (process.env.ZPATCH_TOKEN)
|
|
193
|
+
return { token: process.env.ZPATCH_TOKEN, expires: 0 };
|
|
194
|
+
if (saved?.gateway === server.origin && saved.expires > Date.now() / 1000 + 10)
|
|
195
|
+
return { token: saved.token, expires: saved.expires };
|
|
196
|
+
if (!loopback(server) && !process.env.ZPATCH_LICENSE)
|
|
197
|
+
return oauth(server);
|
|
198
|
+
const license = process.env.ZPATCH_LICENSE || await privateInput("License: ");
|
|
199
|
+
const session = await jsonRequest(new URL("/auth/login", server), post({ license }));
|
|
200
|
+
if (typeof session.token !== "string" || !Number.isFinite(session.expires))
|
|
201
|
+
throw Error("invalid login response");
|
|
202
|
+
return session;
|
|
203
|
+
}
|
|
204
|
+
async function privateDirectory(path, create = true) {
|
|
205
|
+
if (create)
|
|
206
|
+
await mkdir(path, { recursive: true, mode: 0o700 });
|
|
207
|
+
const st = await lstat(path);
|
|
208
|
+
if (!st.isDirectory() || (process.platform !== "win32" &&
|
|
209
|
+
(st.uid !== process.getuid?.() || (st.mode & 0o077) !== 0)))
|
|
210
|
+
throw Error("installation directories must be private and owned by the current user (0700)");
|
|
211
|
+
}
|
|
212
|
+
function downloadURL(raw, server) {
|
|
213
|
+
if (typeof raw !== "string")
|
|
214
|
+
throw Error("invalid download URL");
|
|
215
|
+
const url = new URL(raw, server);
|
|
216
|
+
const gcs = url.origin === "https://storage.googleapis.com" &&
|
|
217
|
+
/^\/[a-z0-9][a-z0-9.-]+\/releases\/(?:linux-x64|linux-arm64|darwin-arm64|win32-x64)\/[0-9A-Za-z.-]+\/bundle\.tar\.gz$/.test(url.pathname) &&
|
|
218
|
+
url.searchParams.get("X-Goog-Algorithm") === "GOOG4-RSA-SHA256" && url.searchParams.has("X-Goog-Signature");
|
|
219
|
+
const local = url.origin === server.origin && url.pathname.startsWith("/download/");
|
|
220
|
+
if ((!gcs && !local) || url.username || url.password || url.hash)
|
|
221
|
+
throw Error("unexpected download origin or path");
|
|
222
|
+
return url;
|
|
223
|
+
}
|
|
224
|
+
async function checkSpace(directory, need) {
|
|
225
|
+
const info = await statfs(directory, { bigint: true });
|
|
226
|
+
const free = info.bavail * info.bsize;
|
|
227
|
+
if (free < need)
|
|
228
|
+
throw Error("insufficient disk space for download and extraction");
|
|
229
|
+
return free;
|
|
230
|
+
}
|
|
231
|
+
async function extractBundle(path, destination, limit) {
|
|
232
|
+
const input = createReadStream(path);
|
|
233
|
+
const archive = createGunzip();
|
|
234
|
+
const onError = (error) => archive.destroy(error);
|
|
235
|
+
input.on("error", onError);
|
|
236
|
+
input.pipe(archive);
|
|
237
|
+
const iterator = archive[Symbol.asyncIterator]();
|
|
238
|
+
let current = Buffer.alloc(0);
|
|
239
|
+
let at = 0;
|
|
240
|
+
const names = new Set();
|
|
241
|
+
async function read(n) {
|
|
242
|
+
const result = Buffer.allocUnsafe(n);
|
|
243
|
+
let used = 0;
|
|
244
|
+
while (used < n) {
|
|
245
|
+
if (at === current.length) {
|
|
246
|
+
const next = await iterator.next();
|
|
247
|
+
if (next.done)
|
|
248
|
+
throw Error("truncated release archive");
|
|
249
|
+
current = next.value;
|
|
250
|
+
at = 0;
|
|
251
|
+
}
|
|
252
|
+
const size = Math.min(current.length - at, n - used);
|
|
253
|
+
current.copy(result, used, at, at + size);
|
|
254
|
+
at += size;
|
|
255
|
+
used += size;
|
|
256
|
+
}
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
function field(header, start, end) {
|
|
260
|
+
return header.subarray(start, end).toString("ascii").split("\0")[0];
|
|
261
|
+
}
|
|
262
|
+
function number(header, start, end) {
|
|
263
|
+
const value = field(header, start, end).trim();
|
|
264
|
+
if (!/^[0-7]+$/.test(value))
|
|
265
|
+
throw Error("invalid release archive header");
|
|
266
|
+
return parseInt(value, 8);
|
|
267
|
+
}
|
|
268
|
+
let extracted = 0;
|
|
269
|
+
try {
|
|
270
|
+
for (;;) {
|
|
271
|
+
const header = await read(512);
|
|
272
|
+
if (header.every(byte => byte === 0)) {
|
|
273
|
+
if (!(await read(512)).every(byte => byte === 0))
|
|
274
|
+
throw Error("invalid archive terminator");
|
|
275
|
+
if (!current.subarray(at).every(byte => byte === 0))
|
|
276
|
+
throw Error("unexpected archive content");
|
|
277
|
+
let trailing = current.length - at;
|
|
278
|
+
for (let next = await iterator.next(); !next.done; next = await iterator.next()) {
|
|
279
|
+
trailing += next.value.length;
|
|
280
|
+
if (trailing > 1 << 20 || !next.value.every((byte) => byte === 0))
|
|
281
|
+
throw Error("unexpected archive content");
|
|
282
|
+
}
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
const type = header[156];
|
|
286
|
+
const name = field(header, 0, 100);
|
|
287
|
+
const parts = name.split("/");
|
|
288
|
+
const size = number(header, 124, 136);
|
|
289
|
+
const mode = number(header, 100, 108);
|
|
290
|
+
extracted += size;
|
|
291
|
+
const checksum = header.reduce((sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte), 0);
|
|
292
|
+
if (number(header, 148, 156) !== checksum || size < 0 || extracted > limit ||
|
|
293
|
+
field(header, 345, 500) || (type !== 0 && type !== 48) ||
|
|
294
|
+
parts.some(part => !/^[A-Za-z0-9_.@-]+$/.test(part) || part === "." || part.endsWith(".") ||
|
|
295
|
+
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)) ||
|
|
296
|
+
names.has(name.toLowerCase()) || names.size >= 4096)
|
|
297
|
+
throw Error("invalid or oversized release archive entry");
|
|
298
|
+
names.add(name.toLowerCase());
|
|
299
|
+
const target = join(destination, ...parts);
|
|
300
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
301
|
+
async function* payload() {
|
|
302
|
+
for (let remaining = size; remaining > 0;) {
|
|
303
|
+
const length = Math.min(remaining, 65536);
|
|
304
|
+
yield await read(length);
|
|
305
|
+
remaining -= length;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
await pipeline(payload(), createWriteStream(target, { flags: "wx", mode: (mode & 0o111) ? 0o700 : 0o600 }));
|
|
309
|
+
const padding = (512 - size % 512) % 512;
|
|
310
|
+
if (padding)
|
|
311
|
+
await read(padding);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
input.destroy();
|
|
316
|
+
archive.destroy();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
async function install(deviceInfo, saved) {
|
|
320
|
+
const { platform, arch } = deviceInfo;
|
|
321
|
+
const server = endpoint(process.env.ZPATCH_GATEWAY || saved?.gateway || gatewayDefault);
|
|
322
|
+
const session = await authenticate(server, saved);
|
|
323
|
+
const requested = process.env.ZPATCH_VERSION;
|
|
324
|
+
if (requested && !versionPattern.test(requested))
|
|
325
|
+
throw Error("invalid version");
|
|
326
|
+
const release = requested ? "/releases/" + platform + "/" + requested : "/releases/latest?platform=" + platform;
|
|
327
|
+
const meta = await jsonRequest(new URL(release, server), { headers: { Authorization: "Bearer " + session.token } });
|
|
328
|
+
const size = meta.size_bytes ?? meta.bytes;
|
|
329
|
+
const version = meta.version ?? requested;
|
|
330
|
+
if (typeof version !== "string" || !versionPattern.test(version) || (requested && version !== requested) ||
|
|
331
|
+
(meta.platform !== undefined && meta.platform !== platform) || (meta.arch !== undefined && meta.arch !== arch) ||
|
|
332
|
+
(meta.format !== undefined && !["bundle.tar.gz", "zpatch"].includes(meta.format)) ||
|
|
333
|
+
!sha256.test(meta.sha256) || !Number.isSafeInteger(size) || size <= 0 ||
|
|
334
|
+
(meta.expires_at !== undefined && !(Date.parse(meta.expires_at) > Date.now())))
|
|
335
|
+
throw Error("invalid release manifest");
|
|
336
|
+
const isBundle = meta.format === "bundle.tar.gz";
|
|
337
|
+
const unpacked = meta.unpacked_bytes ?? (isBundle ? size * 20 + (64 << 20) : size);
|
|
338
|
+
if (!Number.isSafeInteger(unpacked) || unpacked <= 0)
|
|
339
|
+
throw Error("invalid extraction size");
|
|
340
|
+
await privateDirectory(base);
|
|
341
|
+
await privateDirectory(bin);
|
|
342
|
+
await checkSpace(bin, BigInt(size) + BigInt(unpacked) + BigInt(16 << 20));
|
|
343
|
+
const url = downloadURL(meta.url, server);
|
|
344
|
+
const locked = await mkdtemp(join(bin, "release-"));
|
|
345
|
+
const stage = await mkdtemp(join(bin, ".download-")).catch(async (error) => {
|
|
346
|
+
await rm(locked, { recursive: true, force: true });
|
|
347
|
+
throw error;
|
|
348
|
+
});
|
|
349
|
+
const tmp = join(stage, "download"), cred = join(stage, "credentials.json");
|
|
350
|
+
let committed = false;
|
|
351
|
+
try {
|
|
352
|
+
let response;
|
|
353
|
+
try {
|
|
354
|
+
response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(600_000) });
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
throw Error("download failed");
|
|
358
|
+
}
|
|
359
|
+
if (!response.ok || !response.body) {
|
|
360
|
+
await response.body?.cancel();
|
|
361
|
+
throw Error("download failed");
|
|
362
|
+
}
|
|
363
|
+
const hash = createHash("sha256");
|
|
364
|
+
let received = 0;
|
|
365
|
+
const meter = new Transform({
|
|
366
|
+
transform(chunk, _encoding, done) {
|
|
367
|
+
received += chunk.length;
|
|
368
|
+
if (received > size)
|
|
369
|
+
return done(Error("oversized download"));
|
|
370
|
+
hash.update(chunk);
|
|
371
|
+
done(null, chunk);
|
|
372
|
+
},
|
|
373
|
+
});
|
|
374
|
+
await pipeline(Readable.fromWeb(response.body), meter, createWriteStream(tmp, { flags: "wx", mode: 0o700 }));
|
|
375
|
+
if (received !== size || hash.digest("hex") !== meta.sha256)
|
|
376
|
+
throw Error("binary SHA-256 mismatch");
|
|
377
|
+
const executable = join(locked, process.platform === "win32" ? "zpatch.exe" : "zpatch");
|
|
378
|
+
if (isBundle)
|
|
379
|
+
await extractBundle(tmp, locked, unpacked);
|
|
380
|
+
else
|
|
381
|
+
await rename(tmp, executable);
|
|
382
|
+
if (!(await lstat(executable)).isFile())
|
|
383
|
+
throw Error("release has no regular zpatch binary");
|
|
384
|
+
await writeFile(cred, JSON.stringify({ gateway: server.origin, version, platform, sha256: await digest(executable),
|
|
385
|
+
install: locked, ...session }), { flag: "wx", mode: 0o600 });
|
|
386
|
+
await rename(cred, credentials);
|
|
387
|
+
committed = true;
|
|
388
|
+
console.log("Installed zpatch " + version + " for " + platform);
|
|
389
|
+
}
|
|
390
|
+
finally {
|
|
391
|
+
await rm(stage, { recursive: true, force: true });
|
|
392
|
+
if (!committed)
|
|
393
|
+
await rm(locked, { recursive: true, force: true });
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async function installed(config, platform) {
|
|
397
|
+
await privateDirectory(base, false);
|
|
398
|
+
if (config.platform !== platform || !sha256.test(config.sha256))
|
|
399
|
+
throw Error("invalid installation; run zpatch login");
|
|
400
|
+
const dir = config.install;
|
|
401
|
+
if (dir && ![base, bin].includes(dirname(resolve(dir))))
|
|
402
|
+
throw Error("invalid installation directory");
|
|
403
|
+
if (dir && dirname(resolve(dir)) === bin)
|
|
404
|
+
await privateDirectory(bin, false);
|
|
405
|
+
if (dir)
|
|
406
|
+
await privateDirectory(dir, false);
|
|
407
|
+
const executable = dir ? join(dir, process.platform === "win32" ? "zpatch.exe" : "zpatch") : join(base, "zpatch-" + config.sha256);
|
|
408
|
+
if (!(await lstat(executable)).isFile() || (await digest(executable)) !== config.sha256)
|
|
409
|
+
throw Error("installed binary checksum mismatch");
|
|
410
|
+
return executable;
|
|
411
|
+
}
|
|
412
|
+
async function main() {
|
|
413
|
+
const args = process.argv.slice(2);
|
|
414
|
+
const system = await device();
|
|
415
|
+
if (args[0] === "login")
|
|
416
|
+
return install(system);
|
|
417
|
+
if (args[0] === "update") {
|
|
418
|
+
const saved = await readFile(credentials, "utf8").then(content => JSON.parse(content)).catch(() => undefined);
|
|
419
|
+
return install(system, saved);
|
|
420
|
+
}
|
|
421
|
+
if (args[0] === "doctor") {
|
|
422
|
+
const directory = await lstat(base).then(() => base).catch(() => dirname(base));
|
|
423
|
+
const space = await statfs(directory, { bigint: true });
|
|
424
|
+
const health = await readFile(credentials, "utf8").then(content => installed(JSON.parse(content), system.platform)).then(() => "verified").catch((error) => error.code === "ENOENT" ? "missing" : "invalid");
|
|
425
|
+
console.log(JSON.stringify({ ...system, free_bytes: (space.bavail * space.bsize).toString(), installation: health }));
|
|
426
|
+
if (health === "invalid")
|
|
427
|
+
process.exitCode = 3;
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const config = JSON.parse(await readFile(credentials, "utf8"));
|
|
431
|
+
const executable = await installed(config, system.platform);
|
|
432
|
+
const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !secureNames.test(key)));
|
|
433
|
+
const child = spawn(executable, args, { stdio: "inherit", env: cleanEnv });
|
|
434
|
+
for (const signal of ["SIGINT", "SIGTERM"])
|
|
435
|
+
process.on(signal, () => child.kill(signal));
|
|
436
|
+
process.exitCode = await new Promise((resolveExit, reject) => {
|
|
437
|
+
child.once("error", reject);
|
|
438
|
+
child.once("exit", (code, signal) => resolveExit(code ?? (signal === "SIGINT" ? 130 : 143)));
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
if (process.argv[1] && pathToFileURL(await realpath(process.argv[1])).href === import.meta.url) {
|
|
442
|
+
main().catch((error) => {
|
|
443
|
+
console.error(error.message);
|
|
444
|
+
process.exitCode = 3;
|
|
445
|
+
});
|
|
446
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zainriazdev/zpatch",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.6.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Authenticated launcher for the standalone ZIP64 batch patcher",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/zainriaz-dev/zpatch-cli.git",
|
|
9
|
+
"directory": "packages/npm-cli"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"zpatch": "build/zpatch.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"build/zpatch.js",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc -p tsconfig.json",
|
|
26
|
+
"test": "npm run build && node --test test/*.test.mjs",
|
|
27
|
+
"prepack": "npm run build"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"typescript": "~5.9.3",
|
|
31
|
+
"@types/node": "^22.19.0"
|
|
32
|
+
}
|
|
33
|
+
}
|