@zainriazdev/zpatch 0.6.4 → 0.6.7

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 CHANGED
@@ -13,7 +13,11 @@ zpatch login
13
13
  zpatch --version
14
14
  ```
15
15
 
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).
16
+ The first interactive sign-in opens setup after the download is verified. Choose local archives, an SSH connection, or MCP node deployment. Later runs of bare `zpatch` open the cockpit overview. Type `/setup` to revisit the choices.
17
+
18
+ On your computer, the launcher opens your default browser and waits for approval. Over SSH or on a headless server, it prints a link you can open on another device. Approve access, choose **Copy authorization code**, and paste it into the waiting terminal. The code works once and expires in five minutes. The approval page can also send the code to your verified email when email delivery is available. [Verify your zpatch email](https://zpatch-auth.zainriaz.dev/account/email)
19
+
20
+ Use `zpatch login --copy-code` to select the copy-and-paste flow on your computer, or add `--no-browser` to open the sign-in link yourself. If an automatic callback fails, paste the full URL from that browser tab into the waiting terminal when prompted.
17
21
 
18
22
  The launcher checks your system and install location, downloads the matching native bundle, and verifies its size and SHA-256 before installation.
19
23
 
@@ -26,6 +30,10 @@ The launcher checks your system and install location, downloads the matching nat
26
30
  | `zpatch update` | Downloads and verifies the current native release. It reuses a valid sign-in when available. |
27
31
  | `zpatch --version` | Prints the installed native version, which can differ from the npm launcher version. |
28
32
  | `zpatch --help` | Shows the installed CLI's commands and options. |
33
+ | `zpatch config get default-target --json` | Shows the effective archive member and its source. Works offline before login. |
34
+ | `zpatch config set default-target NAME` | Saves the local default. `zpatch config reset default-target` clears it. |
35
+
36
+ Use `zpatch run --file sample.zip --replace replacement.txt --dry-run --json` for a single archive. The target comes from `--target`, `ZPATCH_DEFAULT_TARGET`, local config, or `123.txt`, in that order.
29
37
 
30
38
  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)
31
39
 
package/build/zpatch.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { createReadStream, createWriteStream } from "node:fs";
4
- import { access, lstat, mkdir, mkdtemp, readFile, rename, rm, statfs, writeFile, realpath } from "node:fs/promises";
4
+ import { access, lstat, mkdir, mkdtemp, open, readFile, rename, rm, statfs, writeFile, realpath } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
6
  import { availableParallelism, homedir, machine, release, totalmem } from "node:os";
7
7
  import { constants } from "node:fs";
@@ -88,16 +88,25 @@ async function jsonRequest(url, opts = {}) {
88
88
  function post(payload) {
89
89
  return { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) };
90
90
  }
91
- async function privateInput(label) {
91
+ async function privateInput(label, signal) {
92
92
  if (!process.stdin.isTTY)
93
93
  throw Error("set ZPATCH_TOKEN or ZPATCH_LICENSE for unattended login");
94
- process.stderr.write(label);
95
94
  const prompt = createInterface({
96
95
  input: process.stdin, terminal: true,
97
96
  output: new Writable({ write(_chunk, _encoding, done) { done(); } }),
98
97
  });
98
+ const cancelled = new AbortController();
99
+ prompt.once("SIGINT", () => cancelled.abort());
100
+ prompt.once("close", () => cancelled.abort());
99
101
  try {
100
- return await prompt.question("");
102
+ const answer = prompt.question("", { signal: signal ? AbortSignal.any([signal, cancelled.signal]) : cancelled.signal });
103
+ process.stderr.write(label);
104
+ return await answer;
105
+ }
106
+ catch (error) {
107
+ if (cancelled.signal.aborted && !signal?.aborted)
108
+ throw Error("Sign-in cancelled.");
109
+ throw error;
101
110
  }
102
111
  finally {
103
112
  prompt.close();
@@ -129,7 +138,46 @@ function openBrowser(url) {
129
138
  child.unref();
130
139
  });
131
140
  }
132
- export async function oauth(server, launchBrowser = openBrowser) {
141
+ export function terminalCode(input, redirect, issuer, state) {
142
+ const value = input.trim();
143
+ if (value.length > 2048)
144
+ return;
145
+ try {
146
+ if (redirect.protocol === "https:") {
147
+ if (!/^[A-Za-z0-9_-]+$/.test(value))
148
+ return;
149
+ const result = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
150
+ if (result?.iss === issuer && result?.state === state && typeof result?.code === "string" &&
151
+ /^[A-Za-z0-9_-]{43}$/.test(result.code))
152
+ return result.code;
153
+ }
154
+ else {
155
+ const url = new URL(value);
156
+ if (url.origin === redirect.origin && url.pathname === redirect.pathname && !url.username && !url.password &&
157
+ !url.hash && !url.searchParams.has("error") &&
158
+ url.searchParams.getAll("state").length === 1 && url.searchParams.get("state") === state &&
159
+ url.searchParams.getAll("iss").length === 1 && url.searchParams.get("iss") === issuer &&
160
+ url.searchParams.getAll("code").length === 1) {
161
+ const code = url.searchParams.get("code");
162
+ if (code && /^[A-Za-z0-9_-]{43}$/.test(code))
163
+ return code;
164
+ }
165
+ }
166
+ }
167
+ catch { /* Ask for a code from the current sign-in attempt. */ }
168
+ }
169
+ async function readTerminalCode(redirect, issuer, state, signal) {
170
+ const manual = redirect.protocol === "https:";
171
+ for (;;) {
172
+ const input = await privateInput(manual ? "Paste authorization code (hidden), then press Enter: " :
173
+ "If the browser cannot return here, paste the full callback URL (hidden), then press Enter: ", signal);
174
+ const code = terminalCode(input, redirect, issuer, state);
175
+ if (code)
176
+ return code;
177
+ console.error("That response does not match this sign-in. Copy it from the browser or verified email for this terminal.");
178
+ }
179
+ }
180
+ export async function oauth(server, launchBrowser = openBrowser, forceCode = false) {
133
181
  const resource = new URL("/mcp", server).href;
134
182
  const prm = await jsonRequest(new URL("/.well-known/oauth-protected-resource/mcp", server));
135
183
  if (prm.resource !== resource || typeof prm.authorization_servers?.[0] !== "string")
@@ -151,6 +199,14 @@ export async function oauth(server, launchBrowser = openBrowser) {
151
199
  const state = randomBytes(32).toString("base64url");
152
200
  const verifier = randomBytes(32).toString("base64url");
153
201
  const challenge = createHash("sha256").update(verifier).digest("base64url");
202
+ if (forceCode && !process.stdin.isTTY)
203
+ throw Error("Copy-code sign-in requires an interactive terminal.");
204
+ const remote = process.stdin.isTTY && !browserCommand(process.platform, issuer.href, process.env);
205
+ let redirect;
206
+ const handoff = metadata.zpatch_terminal_redirect_uri;
207
+ const manual = (forceCode || remote) && handoff !== undefined;
208
+ if (forceCode && !manual)
209
+ throw Error("This sign-in server does not support copy-code sign-in.");
154
210
  let receive;
155
211
  let decline;
156
212
  let accepted = false;
@@ -183,43 +239,60 @@ export async function oauth(server, launchBrowser = openBrowser) {
183
239
  });
184
240
  let callbackHost = "";
185
241
  try {
186
- await new Promise((ready, fail) => {
187
- callback.once("error", fail);
188
- callback.listen(0, "127.0.0.1", ready);
189
- });
190
- const address = callback.address();
191
- if (!address || typeof address === "string")
192
- throw Error("cannot start OAuth callback");
193
- callbackHost = "127.0.0.1:" + address.port;
194
- const redirect = "http://" + callbackHost + "/callback";
242
+ if (manual) {
243
+ redirect = oauthEndpoint(handoff);
244
+ if (redirect.protocol !== "https:" || redirect.pathname !== "/cli/terminal" || redirect.search)
245
+ throw Error("unexpected terminal sign-in endpoint");
246
+ }
247
+ else {
248
+ await new Promise((ready, fail) => {
249
+ callback.once("error", fail);
250
+ callback.listen(0, "127.0.0.1", ready);
251
+ });
252
+ const address = callback.address();
253
+ if (!address || typeof address === "string")
254
+ throw Error("cannot start OAuth callback");
255
+ callbackHost = "127.0.0.1:" + address.port;
256
+ redirect = new URL("http://" + callbackHost + "/callback");
257
+ }
195
258
  const registration = await jsonRequest(oauthEndpoint(metadata.registration_endpoint), post({
196
- client_name: "zpatch launcher", redirect_uris: [redirect], token_endpoint_auth_method: "none",
259
+ client_name: "zpatch launcher", redirect_uris: [redirect.href], token_endpoint_auth_method: "none",
197
260
  grant_types: ["authorization_code", "refresh_token"], response_types: ["code"],
198
261
  }));
199
262
  if (typeof registration.client_id !== "string")
200
263
  throw Error("OAuth registration rejected");
201
264
  const authorize = oauthEndpoint(metadata.authorization_endpoint);
202
265
  authorize.search = new URLSearchParams({
203
- client_id: registration.client_id, redirect_uri: redirect, resource, state,
266
+ client_id: registration.client_id, redirect_uri: redirect.href, resource, state,
204
267
  response_type: "code", scope: "zpatch:read", code_challenge: challenge, code_challenge_method: "S256",
205
268
  }).toString();
206
- const code = await new Promise((accept, reject) => {
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);
208
- receive = value => { clearTimeout(timer); accept(value); };
209
- decline = error => { clearTimeout(timer); reject(error); };
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);
217
- });
269
+ console.error("Sign-in link for this terminal:\n" + authorize.href);
270
+ if (manual)
271
+ console.error("Open the link on any device and approve access. Copy the code shown after approval.");
272
+ const input = new AbortController();
273
+ const waiting = new Promise((accept, reject) => { receive = accept; decline = reject; });
274
+ const timer = setTimeout(() => decline?.(Error("Sign-in timed out. Start a new attempt with `zpatch login`.")), manual ? 10 * 60_000 : 180_000);
275
+ if (launchBrowser && !(manual && remote)) {
276
+ void launchBrowser(authorize).catch(() => false).then(opened => {
277
+ if (!accepted && !input.signal.aborted)
278
+ console.error(opened ? "Opened your default browser. Waiting for approval." : "Open the sign-in link to approve.");
279
+ });
280
+ }
281
+ let code;
282
+ try {
283
+ code = await (process.stdin.isTTY ?
284
+ Promise.race([waiting, readTerminalCode(redirect, issuer.origin, state, input.signal)]) : waiting);
285
+ }
286
+ finally {
287
+ accepted = true;
288
+ clearTimeout(timer);
289
+ input.abort();
290
+ }
218
291
  console.error("Browser approval received. Completing sign-in…");
219
292
  const session = await jsonRequest(oauthEndpoint(metadata.token_endpoint), {
220
293
  method: "POST", body: new URLSearchParams({
221
294
  grant_type: "authorization_code", client_id: registration.client_id, code,
222
- redirect_uri: redirect, resource, code_verifier: verifier,
295
+ redirect_uri: redirect.href, resource, code_verifier: verifier,
223
296
  }),
224
297
  });
225
298
  if (typeof session.access_token !== "string" || !Number.isFinite(session.expires_in))
@@ -231,13 +304,13 @@ export async function oauth(server, launchBrowser = openBrowser) {
231
304
  callback.closeIdleConnections();
232
305
  }
233
306
  }
234
- async function authenticate(server, saved, noBrowser = false) {
307
+ async function authenticate(server, saved, noBrowser = false, forceCode = false) {
235
308
  if (process.env.ZPATCH_TOKEN)
236
309
  return { token: process.env.ZPATCH_TOKEN, expires: 0 };
237
310
  if (saved?.gateway === server.origin && saved.expires > Date.now() / 1000 + 10)
238
311
  return { token: saved.token, expires: saved.expires };
239
312
  if (!loopback(server) && !process.env.ZPATCH_LICENSE)
240
- return oauth(server, noBrowser ? false : openBrowser);
313
+ return oauth(server, noBrowser ? false : openBrowser, forceCode);
241
314
  const license = process.env.ZPATCH_LICENSE || await privateInput("License: ");
242
315
  const session = await jsonRequest(new URL("/auth/login", server), post({ license }));
243
316
  if (typeof session.token !== "string" || !Number.isFinite(session.expires))
@@ -373,7 +446,7 @@ async function installDirectory() {
373
446
  }
374
447
  }
375
448
  }
376
- async function install(deviceInfo, saved, noBrowser = false) {
449
+ async function install(deviceInfo, saved, noBrowser = false, forceCode = false) {
377
450
  const { platform, arch } = deviceInfo;
378
451
  const server = endpoint(process.env.ZPATCH_GATEWAY || saved?.gateway || gatewayDefault);
379
452
  const requested = process.env.ZPATCH_VERSION;
@@ -383,7 +456,7 @@ async function install(deviceInfo, saved, noBrowser = false) {
383
456
  await access(directory, constants.W_OK);
384
457
  await checkSpace(directory, 16n << 20n);
385
458
  console.error(`Preparing zpatch for ${platform}${deviceInfo.libc ? ` (${deviceInfo.libc})` : ""} with Node.js ${process.versions.node}.`);
386
- const session = await authenticate(server, saved, noBrowser);
459
+ const session = await authenticate(server, saved, noBrowser, forceCode);
387
460
  const release = requested ? "/releases/" + platform + "/" + requested : "/releases/latest?platform=" + platform;
388
461
  const meta = await jsonRequest(new URL(release, server), { headers: { Authorization: "Bearer " + session.token } });
389
462
  const size = meta.size_bytes ?? meta.bytes;
@@ -477,18 +550,93 @@ async function installed(config, platform) {
477
550
  throw Error("installed binary checksum mismatch");
478
551
  return executable;
479
552
  }
553
+ function validateTarget(value) {
554
+ if (typeof value !== "string" || Buffer.from(value).toString("utf8") !== value || Buffer.byteLength(value, "utf8") > 65535 ||
555
+ /[\\:\p{Cc}]/u.test(value) || value.split("/").some(part => !part.trim() || part === "." || part === ".."))
556
+ throw Error("invalid ZIP target: use a filename or a relative internal path");
557
+ }
558
+ async function archiveConfig(args) {
559
+ const [action, key, value] = args;
560
+ if (key !== "default-target" || !(action === "set" && args.length === 3 ||
561
+ action === "reset" && args.length === 2 ||
562
+ action === "get" && (args.length === 2 || args.length === 3 && value === "--json")))
563
+ throw Error("Usage: zpatch config get default-target [--json], set default-target <name>, or reset default-target");
564
+ const configured = join(base, "config.json");
565
+ const readConfig = async () => {
566
+ const raw = await readFile(configured, "utf8").catch((error) => {
567
+ if (error.code === "ENOENT")
568
+ return "{}";
569
+ throw error;
570
+ });
571
+ const data = JSON.parse(raw);
572
+ if (!data || typeof data !== "object" || Array.isArray(data))
573
+ throw Error("config.json must contain a JSON object");
574
+ return data;
575
+ };
576
+ if (action === "get") {
577
+ let target = process.env.ZPATCH_DEFAULT_TARGET ?? process.env.ZPATCH_TARGET;
578
+ let source = "env";
579
+ if (target === undefined) {
580
+ const config = await readConfig();
581
+ const present = Object.hasOwn(config, "default_target");
582
+ target = present ? config.default_target : "123.txt";
583
+ source = present ? "config" : "builtin_default";
584
+ }
585
+ validateTarget(target);
586
+ console.log(value === "--json" ? JSON.stringify({ target, target_source: source }) : target);
587
+ return;
588
+ }
589
+ if (action === "set")
590
+ validateTarget(value);
591
+ await privateDirectory(base, true);
592
+ const data = await readConfig();
593
+ if (action === "set")
594
+ data.default_target = value;
595
+ else if (!Object.hasOwn(data, "default_target"))
596
+ return;
597
+ else
598
+ delete data.default_target;
599
+ const tmp = join(base, ".config-" + randomBytes(12).toString("hex"));
600
+ try {
601
+ const out = await open(tmp, "wx", 0o600);
602
+ try {
603
+ await out.writeFile(JSON.stringify(data, null, 2) + "\n");
604
+ await out.sync();
605
+ }
606
+ finally {
607
+ await out.close();
608
+ }
609
+ await rename(tmp, configured);
610
+ }
611
+ finally {
612
+ await rm(tmp, { force: true });
613
+ }
614
+ }
480
615
  async function main() {
481
616
  if (Number(process.versions.node.split(".")[0]) < 22)
482
617
  throw Error("Install Node.js 22 or newer to run zpatch.");
483
618
  const args = process.argv.slice(2);
619
+ if (args[0] === "config")
620
+ return archiveConfig(args.slice(1));
484
621
  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";
487
- if (args[0] === "login")
488
- return install(system, undefined, noBrowser);
622
+ const login = args[0] === "login";
623
+ const installFlags = login || args[0] === "update" ? args.slice(1) : args;
624
+ const installOnlyFlags = installFlags.length > 0 && installFlags.every(arg => arg === "--no-browser" || arg === "--copy-code");
625
+ const noBrowser = installOnlyFlags && installFlags.includes("--no-browser");
626
+ const forceCode = installOnlyFlags && installFlags.includes("--copy-code");
627
+ const interactive = process.stdin.isTTY && process.stdout.isTTY;
628
+ let onboard = false;
629
+ if (login) {
630
+ if (installFlags.length && !installOnlyFlags)
631
+ throw Error("Usage: zpatch login [--no-browser] [--copy-code]");
632
+ await install(system, undefined, noBrowser, forceCode);
633
+ if (!interactive)
634
+ return;
635
+ onboard = true;
636
+ }
489
637
  if (args[0] === "update") {
490
638
  const saved = await readFile(credentials, "utf8").then(content => JSON.parse(content)).catch(() => undefined);
491
- return install(system, saved, noBrowser);
639
+ return install(system, saved, noBrowser, forceCode);
492
640
  }
493
641
  if (args[0] === "doctor") {
494
642
  const directory = await installDirectory();
@@ -511,15 +659,16 @@ async function main() {
511
659
  const setup = "Run `zpatch login` to sign in and install zpatch. Then run `zpatch` again.";
512
660
  if (args.length === 1 && ["--help", "-h"].includes(args[0]))
513
661
  return console.log(setup);
514
- if (args.length && !noBrowser)
662
+ if (args.length && !installOnlyFlags)
515
663
  throw Error(setup);
516
- await install(system, undefined, noBrowser);
664
+ await install(system, undefined, noBrowser, forceCode);
665
+ onboard = interactive;
517
666
  content = await readFile(credentials, "utf8");
518
667
  }
519
668
  const config = JSON.parse(content);
520
669
  const executable = await installed(config, system.platform);
521
670
  const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !secureNames.test(key)));
522
- const child = spawn(executable, noBrowser ? [] : args, { stdio: "inherit", env: cleanEnv });
671
+ const child = spawn(executable, onboard ? ["onboard"] : installOnlyFlags ? [] : args, { stdio: "inherit", env: cleanEnv });
523
672
  for (const signal of ["SIGINT", "SIGTERM"])
524
673
  process.on(signal, () => child.kill(signal));
525
674
  process.exitCode = await new Promise((resolveExit, reject) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zainriazdev/zpatch",
3
- "version": "0.6.4",
3
+ "version": "0.6.7",
4
4
  "type": "module",
5
5
  "description": "Authenticated launcher for the standalone ZIP64 batch patcher",
6
6
  "repository": {