@zainriazdev/zpatch 0.6.2 → 0.6.4
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 +4 -2
- package/build/zpatch.js +114 -25
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,13 +13,15 @@ zpatch login
|
|
|
13
13
|
zpatch --version
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
Running `zpatch` starts setup on first use and opens the native CLI after installation. The launcher opens your default browser for sign-in and also prints the link. Approve access there, then return to the same terminal to see sign-in, download, and verification progress. Use `zpatch login --no-browser` to open the link yourself. The browser must be able to reach the launcher’s loopback listener on the same computer. You can [verify your email in zpatch](https://zpatch-auth.zainriaz.dev/account/email).
|
|
17
|
+
|
|
18
|
+
The launcher checks your system and install location, downloads the matching native bundle, and verifies its size and SHA-256 before installation.
|
|
17
19
|
|
|
18
20
|
## Everyday commands
|
|
19
21
|
|
|
20
22
|
| Command | What it does |
|
|
21
23
|
| --- | --- |
|
|
22
|
-
| `zpatch doctor` |
|
|
24
|
+
| `zpatch doctor` | Reports the OS, Node.js and hardware architecture, available CPU threads, RAM, Linux libc, disk headroom, and installation integrity. `missing` is expected before the first login. |
|
|
23
25
|
| `zpatch login` | Signs in through the browser and installs the current native release. |
|
|
24
26
|
| `zpatch update` | Downloads and verifies the current native release. It reuses a valid sign-in when available. |
|
|
25
27
|
| `zpatch --version` | Prints the installed native version, which can differ from the npm launcher version. |
|
package/build/zpatch.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
import { createReadStream, createWriteStream } from "node:fs";
|
|
4
|
-
import { lstat, mkdir, mkdtemp, readFile, rename, rm, statfs, writeFile, realpath } from "node:fs/promises";
|
|
4
|
+
import { access, lstat, mkdir, mkdtemp, readFile, rename, rm, statfs, writeFile, realpath } from "node:fs/promises";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
|
-
import { homedir } from "node:os";
|
|
6
|
+
import { availableParallelism, homedir, machine, release, totalmem } from "node:os";
|
|
7
|
+
import { constants } from "node:fs";
|
|
7
8
|
import { dirname, join, resolve } from "node:path";
|
|
8
9
|
import { Writable, Readable, Transform } from "node:stream";
|
|
9
10
|
import { pipeline } from "node:stream/promises";
|
|
@@ -16,7 +17,7 @@ const bin = join(base, "bin");
|
|
|
16
17
|
const credentials = join(base, "credentials.json");
|
|
17
18
|
const sha256 = /^[0-9a-f]{64}$/;
|
|
18
19
|
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 secureNames = /^(?:BREVO_API_KEY|GOOGLE_APPLICATION_CREDENTIALS|GOOGLE_API_KEY|CLOUDFLARE_API_TOKEN|APPWRITE_API_KEY|ZPATCH_LICENSE|ZPATCH_TOKEN|ZPATCH_SIGNING_KEY|ZPATCH_BRIDGE_SECRET|ZPATCH_GCS_.*)$/;
|
|
20
21
|
const gatewayDefault = "https://usnode.zainriaz.dev";
|
|
21
22
|
export function detectDevice(os, arch, glibc, objects = "") {
|
|
22
23
|
const platform = os + "-" + arch;
|
|
@@ -103,7 +104,32 @@ async function privateInput(label) {
|
|
|
103
104
|
process.stderr.write("\n");
|
|
104
105
|
}
|
|
105
106
|
}
|
|
106
|
-
export
|
|
107
|
+
export function browserCommand(platform, url, env) {
|
|
108
|
+
if (env.SSH_CONNECTION || env.SSH_TTY || env.SSH_CLIENT)
|
|
109
|
+
return null;
|
|
110
|
+
if (platform === "win32")
|
|
111
|
+
return ["rundll32.exe", "url.dll,FileProtocolHandler", url];
|
|
112
|
+
if (platform === "darwin")
|
|
113
|
+
return ["open", url];
|
|
114
|
+
if (env.WSL_DISTRO_NAME)
|
|
115
|
+
return ["rundll32.exe", "url.dll,FileProtocolHandler", url];
|
|
116
|
+
if (env.DISPLAY || env.WAYLAND_DISPLAY)
|
|
117
|
+
return ["xdg-open", url];
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
function openBrowser(url) {
|
|
121
|
+
const command = browserCommand(process.platform, url.href, process.env);
|
|
122
|
+
if (!command)
|
|
123
|
+
return Promise.resolve(false);
|
|
124
|
+
const [program, ...args] = command;
|
|
125
|
+
return new Promise(resolve => {
|
|
126
|
+
const child = spawn(program, args, { stdio: "ignore", windowsHide: true });
|
|
127
|
+
child.once("error", () => resolve(false));
|
|
128
|
+
child.once("spawn", () => resolve(true));
|
|
129
|
+
child.unref();
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
export async function oauth(server, launchBrowser = openBrowser) {
|
|
107
133
|
const resource = new URL("/mcp", server).href;
|
|
108
134
|
const prm = await jsonRequest(new URL("/.well-known/oauth-protected-resource/mcp", server));
|
|
109
135
|
if (prm.resource !== resource || typeof prm.authorization_servers?.[0] !== "string")
|
|
@@ -127,22 +153,32 @@ export async function oauth(server) {
|
|
|
127
153
|
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
128
154
|
let receive;
|
|
129
155
|
let decline;
|
|
156
|
+
let accepted = false;
|
|
130
157
|
const callback = createServer((request, response) => {
|
|
131
|
-
const url = new URL(
|
|
132
|
-
const valid = request.method === "GET" && request.headers.host === callbackHost &&
|
|
133
|
-
url.pathname === "/callback" && url.searchParams.
|
|
134
|
-
|
|
158
|
+
const url = new URL("http://127.0.0.1/" + (request.url ?? "").replace(/^\/+/, ""));
|
|
159
|
+
const valid = request.method === "GET" && request.headers.host === callbackHost && !accepted && receive &&
|
|
160
|
+
url.pathname === "/callback" && url.searchParams.getAll("state").length === 1 &&
|
|
161
|
+
url.searchParams.get("state") === state && url.searchParams.getAll("iss").length === 1 &&
|
|
162
|
+
url.searchParams.get("iss") === issuer.origin;
|
|
163
|
+
const codes = url.searchParams.getAll("code");
|
|
135
164
|
response.setHeader("Connection", "close");
|
|
165
|
+
response.setHeader("Cache-Control", "no-store");
|
|
166
|
+
response.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
136
167
|
if (!valid) {
|
|
137
168
|
response.writeHead(400).end("Invalid callback.");
|
|
138
169
|
}
|
|
139
|
-
else if (!
|
|
170
|
+
else if (!codes.length && url.searchParams.has("error")) {
|
|
171
|
+
accepted = true;
|
|
140
172
|
response.writeHead(400).end("Sign-in was not completed. Return to the terminal.");
|
|
141
173
|
decline?.(Error("sign-in denied"));
|
|
142
174
|
}
|
|
175
|
+
else if (codes.length !== 1 || !codes[0] || url.searchParams.has("error")) {
|
|
176
|
+
response.writeHead(400).end("Invalid callback.");
|
|
177
|
+
}
|
|
143
178
|
else {
|
|
144
|
-
|
|
145
|
-
|
|
179
|
+
accepted = true;
|
|
180
|
+
response.writeHead(200).end("Approval received. Return to your terminal to see download and verification progress.");
|
|
181
|
+
receive?.(codes[0]);
|
|
146
182
|
}
|
|
147
183
|
});
|
|
148
184
|
let callbackHost = "";
|
|
@@ -168,11 +204,18 @@ export async function oauth(server) {
|
|
|
168
204
|
response_type: "code", scope: "zpatch:read", code_challenge: challenge, code_challenge_method: "S256",
|
|
169
205
|
}).toString();
|
|
170
206
|
const code = await new Promise((accept, reject) => {
|
|
171
|
-
const timer = setTimeout(() => reject(Error("
|
|
207
|
+
const timer = setTimeout(() => reject(Error("Browser approval did not reach this terminal. Open the link on the same machine and network namespace, then retry `zpatch login`.")), 180_000);
|
|
172
208
|
receive = value => { clearTimeout(timer); accept(value); };
|
|
173
209
|
decline = error => { clearTimeout(timer); reject(error); };
|
|
174
|
-
|
|
210
|
+
if (launchBrowser) {
|
|
211
|
+
void launchBrowser(authorize).catch(() => false).then(opened => {
|
|
212
|
+
if (!accepted)
|
|
213
|
+
console.error(opened ? "Opened your default browser. Waiting for approval." : "Open the link on this machine to approve. Waiting for approval.");
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
console.error("Sign-in link for this terminal:\n" + authorize.href);
|
|
175
217
|
});
|
|
218
|
+
console.error("Browser approval received. Completing sign-in…");
|
|
176
219
|
const session = await jsonRequest(oauthEndpoint(metadata.token_endpoint), {
|
|
177
220
|
method: "POST", body: new URLSearchParams({
|
|
178
221
|
grant_type: "authorization_code", client_id: registration.client_id, code,
|
|
@@ -184,17 +227,17 @@ export async function oauth(server) {
|
|
|
184
227
|
return { token: session.access_token, expires: Math.floor(Date.now() / 1000) + session.expires_in };
|
|
185
228
|
}
|
|
186
229
|
finally {
|
|
187
|
-
callback.closeAllConnections();
|
|
188
230
|
callback.close();
|
|
231
|
+
callback.closeIdleConnections();
|
|
189
232
|
}
|
|
190
233
|
}
|
|
191
|
-
async function authenticate(server, saved) {
|
|
234
|
+
async function authenticate(server, saved, noBrowser = false) {
|
|
192
235
|
if (process.env.ZPATCH_TOKEN)
|
|
193
236
|
return { token: process.env.ZPATCH_TOKEN, expires: 0 };
|
|
194
237
|
if (saved?.gateway === server.origin && saved.expires > Date.now() / 1000 + 10)
|
|
195
238
|
return { token: saved.token, expires: saved.expires };
|
|
196
239
|
if (!loopback(server) && !process.env.ZPATCH_LICENSE)
|
|
197
|
-
return oauth(server);
|
|
240
|
+
return oauth(server, noBrowser ? false : openBrowser);
|
|
198
241
|
const license = process.env.ZPATCH_LICENSE || await privateInput("License: ");
|
|
199
242
|
const session = await jsonRequest(new URL("/auth/login", server), post({ license }));
|
|
200
243
|
if (typeof session.token !== "string" || !Number.isFinite(session.expires))
|
|
@@ -316,13 +359,31 @@ async function extractBundle(path, destination, limit) {
|
|
|
316
359
|
archive.destroy();
|
|
317
360
|
}
|
|
318
361
|
}
|
|
319
|
-
async function
|
|
362
|
+
async function installDirectory() {
|
|
363
|
+
let current = base;
|
|
364
|
+
for (;;) {
|
|
365
|
+
try {
|
|
366
|
+
await access(current, constants.F_OK);
|
|
367
|
+
return current;
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
if (error.code !== "ENOENT" || current === dirname(current))
|
|
371
|
+
throw error;
|
|
372
|
+
current = dirname(current);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async function install(deviceInfo, saved, noBrowser = false) {
|
|
320
377
|
const { platform, arch } = deviceInfo;
|
|
321
378
|
const server = endpoint(process.env.ZPATCH_GATEWAY || saved?.gateway || gatewayDefault);
|
|
322
|
-
const session = await authenticate(server, saved);
|
|
323
379
|
const requested = process.env.ZPATCH_VERSION;
|
|
324
380
|
if (requested && !versionPattern.test(requested))
|
|
325
381
|
throw Error("invalid version");
|
|
382
|
+
const directory = await installDirectory();
|
|
383
|
+
await access(directory, constants.W_OK);
|
|
384
|
+
await checkSpace(directory, 16n << 20n);
|
|
385
|
+
console.error(`Preparing zpatch for ${platform}${deviceInfo.libc ? ` (${deviceInfo.libc})` : ""} with Node.js ${process.versions.node}.`);
|
|
386
|
+
const session = await authenticate(server, saved, noBrowser);
|
|
326
387
|
const release = requested ? "/releases/" + platform + "/" + requested : "/releases/latest?platform=" + platform;
|
|
327
388
|
const meta = await jsonRequest(new URL(release, server), { headers: { Authorization: "Bearer " + session.token } });
|
|
328
389
|
const size = meta.size_bytes ?? meta.bytes;
|
|
@@ -341,6 +402,7 @@ async function install(deviceInfo, saved) {
|
|
|
341
402
|
await privateDirectory(bin);
|
|
342
403
|
await checkSpace(bin, BigInt(size) + BigInt(unpacked) + BigInt(16 << 20));
|
|
343
404
|
const url = downloadURL(meta.url, server);
|
|
405
|
+
console.error(`Downloading zpatch ${version} for ${platform} (${(size / 1048576).toFixed(1)} MiB)…`);
|
|
344
406
|
const locked = await mkdtemp(join(bin, "release-"));
|
|
345
407
|
const stage = await mkdtemp(join(bin, ".download-")).catch(async (error) => {
|
|
346
408
|
await rm(locked, { recursive: true, force: true });
|
|
@@ -361,19 +423,25 @@ async function install(deviceInfo, saved) {
|
|
|
361
423
|
throw Error("download failed");
|
|
362
424
|
}
|
|
363
425
|
const hash = createHash("sha256");
|
|
364
|
-
let received = 0;
|
|
426
|
+
let received = 0, reported = 0;
|
|
365
427
|
const meter = new Transform({
|
|
366
428
|
transform(chunk, _encoding, done) {
|
|
367
429
|
received += chunk.length;
|
|
368
430
|
if (received > size)
|
|
369
431
|
return done(Error("oversized download"));
|
|
370
432
|
hash.update(chunk);
|
|
433
|
+
const progress = Math.floor(received * 100 / size);
|
|
434
|
+
if (process.stderr.isTTY && progress >= reported + 10 && progress < 100) {
|
|
435
|
+
reported = progress;
|
|
436
|
+
console.error(`Downloaded ${progress}%`);
|
|
437
|
+
}
|
|
371
438
|
done(null, chunk);
|
|
372
439
|
},
|
|
373
440
|
});
|
|
374
441
|
await pipeline(Readable.fromWeb(response.body), meter, createWriteStream(tmp, { flags: "wx", mode: 0o700 }));
|
|
375
442
|
if (received !== size || hash.digest("hex") !== meta.sha256)
|
|
376
443
|
throw Error("binary SHA-256 mismatch");
|
|
444
|
+
console.error("Download verified. Installing zpatch…");
|
|
377
445
|
const executable = join(locked, process.platform === "win32" ? "zpatch.exe" : "zpatch");
|
|
378
446
|
if (isBundle)
|
|
379
447
|
await extractBundle(tmp, locked, unpacked);
|
|
@@ -410,27 +478,48 @@ async function installed(config, platform) {
|
|
|
410
478
|
return executable;
|
|
411
479
|
}
|
|
412
480
|
async function main() {
|
|
481
|
+
if (Number(process.versions.node.split(".")[0]) < 22)
|
|
482
|
+
throw Error("Install Node.js 22 or newer to run zpatch.");
|
|
413
483
|
const args = process.argv.slice(2);
|
|
414
484
|
const system = await device();
|
|
485
|
+
const noBrowser = args.length === 1 && args[0] === "--no-browser" ||
|
|
486
|
+
args.length === 2 && ["login", "update"].includes(args[0]) && args[1] === "--no-browser";
|
|
415
487
|
if (args[0] === "login")
|
|
416
|
-
return install(system);
|
|
488
|
+
return install(system, undefined, noBrowser);
|
|
417
489
|
if (args[0] === "update") {
|
|
418
490
|
const saved = await readFile(credentials, "utf8").then(content => JSON.parse(content)).catch(() => undefined);
|
|
419
|
-
return install(system, saved);
|
|
491
|
+
return install(system, saved, noBrowser);
|
|
420
492
|
}
|
|
421
493
|
if (args[0] === "doctor") {
|
|
422
|
-
const directory = await
|
|
494
|
+
const directory = await installDirectory();
|
|
423
495
|
const space = await statfs(directory, { bigint: true });
|
|
496
|
+
const writable = await access(directory, constants.W_OK).then(() => true, () => false);
|
|
424
497
|
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,
|
|
498
|
+
console.log(JSON.stringify({ ...system, os: process.platform, os_release: release(), hardware_arch: machine(),
|
|
499
|
+
node_version: process.versions.node, logical_cpus: availableParallelism(), memory_bytes: totalmem(),
|
|
500
|
+
free_bytes: (space.bavail * space.bsize).toString(), install_directory_writable: writable, installation: health }));
|
|
426
501
|
if (health === "invalid")
|
|
427
502
|
process.exitCode = 3;
|
|
428
503
|
return;
|
|
429
504
|
}
|
|
430
|
-
|
|
505
|
+
let content = await readFile(credentials, "utf8").catch((error) => {
|
|
506
|
+
if (error.code === "ENOENT")
|
|
507
|
+
return null;
|
|
508
|
+
throw error;
|
|
509
|
+
});
|
|
510
|
+
if (content === null) {
|
|
511
|
+
const setup = "Run `zpatch login` to sign in and install zpatch. Then run `zpatch` again.";
|
|
512
|
+
if (args.length === 1 && ["--help", "-h"].includes(args[0]))
|
|
513
|
+
return console.log(setup);
|
|
514
|
+
if (args.length && !noBrowser)
|
|
515
|
+
throw Error(setup);
|
|
516
|
+
await install(system, undefined, noBrowser);
|
|
517
|
+
content = await readFile(credentials, "utf8");
|
|
518
|
+
}
|
|
519
|
+
const config = JSON.parse(content);
|
|
431
520
|
const executable = await installed(config, system.platform);
|
|
432
521
|
const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !secureNames.test(key)));
|
|
433
|
-
const child = spawn(executable, args, { stdio: "inherit", env: cleanEnv });
|
|
522
|
+
const child = spawn(executable, noBrowser ? [] : args, { stdio: "inherit", env: cleanEnv });
|
|
434
523
|
for (const signal of ["SIGINT", "SIGTERM"])
|
|
435
524
|
process.on(signal, () => child.kill(signal));
|
|
436
525
|
process.exitCode = await new Promise((resolveExit, reject) => {
|