@crossberryweb/mozhi 3.7.0 → 3.9.0

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/lib/cli.js CHANGED
@@ -13,9 +13,14 @@ const pkgman = require('./pkgman');
13
13
  const scaffold = require('./scaffold');
14
14
  const reg = require('./registry');
15
15
  const publish = require('./publish');
16
+ const appman = require('./appman');
16
17
 
17
- function out(msg) { process.stdout.write(msg + '\n'); }
18
- function err(msg) { process.stderr.write(msg + '\n'); }
18
+ function out(msg) {
19
+ try { process.stdout.write(msg + '\n'); } catch { /* closed pipe (e.g. `| head`) */ }
20
+ }
21
+ function err(msg) {
22
+ try { process.stderr.write(msg + '\n'); } catch { /* closed pipe */ }
23
+ }
19
24
 
20
25
  function pad(s, n) {
21
26
  s = String(s == null ? '' : s);
@@ -25,7 +30,9 @@ function pad(s, n) {
25
30
  function usage() {
26
31
  out('usage:');
27
32
  out(' mz install <name> install a package from the Mozhi registry (resolves dependencies)');
28
- out(' mz install <name>@<tag> install a specific release tag');
33
+ out(' mz install <name>@<tag> install a specific release tag/version');
34
+ out(' mz install nx:<name> install explicitly from NxMirror (also used for unknown registry names)');
35
+ out(' mz install nx:<name>@<version> pin an exact NxMirror version');
29
36
  out(' mz install @user/repo install from any Git repo release');
30
37
  out(' mz install @user/repo@tag install a specific repo release tag');
31
38
  out(' mz install ./pkg.mz.pkg.zip install from a local package zip');
@@ -46,14 +53,26 @@ function usage() {
46
53
  out(' mz pkg new <name> same as mz pkg init <name>');
47
54
  out(' mz pkg zip [dir] same as mz pkg build');
48
55
  out('');
56
+ out('apps (the app platform — like Kotlin -> APK, but for .mz):');
57
+ out(' mz app new <name> scaffold an app project (id, icon, window)');
58
+ out(' mz app check [dir] verify app structure (manifest, entry, icon)');
59
+ out(' mz app build [dir] verify + bundle + dist/<name>-<version>.pkg');
60
+ out(' mz app install <file.pkg|dir> install into the launcher (~/.mozhi/apps/<id>/)');
61
+ out(' mz app list list installed apps');
62
+ out(' mz app open <id|dir> start the app and open its full window');
63
+ out(' mz app home launcher home screen (pick an app to open)');
64
+ out(' mz app uninstall <id> remove an installed app');
65
+ out('');
49
66
  out('options:');
50
67
  out(' --local install into ./.mozhi/pkg instead of ~/.mozhi/pkg');
68
+ out(' --native (pkg build/publish) build the manifest-declared native tool first');
51
69
  out(' --no-deps skip installing declared dependencies');
52
70
  out(' --dry-run (publish) validate and report without releasing');
53
71
  out(' --allow-dirty (publish) release even with uncommitted changes');
54
72
  out('');
55
73
  out('package layout: mozhi.toml (or legacy package.toml) + src/mod.mz; releases carry <name>.mz.pkg.zip');
56
74
  out('registry: ' + reg.DEFAULT_REGISTRY_URL);
75
+ out('fallback: ' + require('./nxmirror').DEFAULT_URL + ' (NxMirror)');
57
76
  }
58
77
 
59
78
  function shortInstallHelp() {
@@ -132,6 +151,20 @@ function findMozhiBinary() {
132
151
  return null;
133
152
  }
134
153
 
154
+ /* Author-requested build only. Install never compiles or executes hooks. */
155
+ function buildNativePackage(dir) {
156
+ dir = path.resolve(dir || '.');
157
+ const mf = pkgman.MANIFESTS.map((m) => path.join(dir, m)).find((p) => fs.existsSync(p));
158
+ if (!mf) throw new Error('native package build needs mozhi.toml');
159
+ const manifest = pkgman.parseManifest(fs.readFileSync(mf, 'utf8'));
160
+ if (!manifest.binary) throw new Error('native package build needs [package] binary = "dist/release/<tool>"');
161
+ pkgman.validateBinaryPath(manifest.binary);
162
+ const bin = findMozhiBinary();
163
+ if (!bin) throw new Error('cannot find mozhi; set MOZHI_BIN for native builds');
164
+ const result = spawnSync(bin, ['build', '--mode', 'native', '--release', '-o', manifest.binary], { cwd: dir, stdio: 'inherit' });
165
+ if (result.error || result.status !== 0) throw new Error('native package build failed' + (result.error ? ': ' + result.error.message : ''));
166
+ }
167
+
135
168
  function cmdPkgTest(args) {
136
169
  const dir = path.resolve(args[0] || '.');
137
170
  const mf = pkgman.MANIFESTS.map((m) => path.join(dir, m)).find((p) => fs.existsSync(p));
@@ -234,6 +267,7 @@ async function cmdPkgUpdate(args, opts) {
234
267
  }
235
268
 
236
269
  async function cmdPkgPublish(args, opts) {
270
+ if (opts.native) buildNativePackage(args[0]);
237
271
  const dir = args[0] || '.';
238
272
  const res = await publish.publishDir(dir, { dryRun: !!opts.dryRun, allowDirty: !!opts.allowDirty });
239
273
  if (res.dryRun) {
@@ -256,7 +290,7 @@ async function cmdPkgPublish(args, opts) {
256
290
  return 0;
257
291
  }
258
292
 
259
- function cmdPkg(args) {
293
+ function cmdPkg(args, opts = {}) {
260
294
  const sub = args[0] || 'help';
261
295
  if (sub === 'new' || sub === 'init') {
262
296
  const name = args[1];
@@ -291,6 +325,7 @@ function cmdPkg(args) {
291
325
  return 0;
292
326
  }
293
327
  if (sub === 'zip' || sub === 'build') {
328
+ if (opts.native) buildNativePackage(args[1]);
294
329
  const res = pkgman.zipDir(args[1] || '.');
295
330
  out('built ' + res.out + ' (' + res.name + (res.version ? ' v' + res.version : '') + ', ' + res.count + ' files)');
296
331
  out('sha256: ' + res.sha256);
@@ -306,6 +341,107 @@ function cmdPkg(args) {
306
341
  return null; // handled by async router (install/search/update/remove/publish)
307
342
  }
308
343
 
344
+ /* -------- mz app ... -------- */
345
+
346
+ function cmdAppSync(args, opts) {
347
+ const sub = args[0] || 'help';
348
+ if (sub === 'new') {
349
+ const rest2 = args.slice(1);
350
+ const flagVals = { '--id': undefined, '--label': undefined, '--port': undefined };
351
+ const positionals = [];
352
+ for (let i = 0; i < rest2.length; i++) {
353
+ if (rest2[i] in flagVals) {
354
+ flagVals[rest2[i]] = rest2[i + 1];
355
+ i++;
356
+ } else {
357
+ positionals.push(rest2[i]);
358
+ }
359
+ }
360
+ const name = positionals[0];
361
+ const dir = positionals[1];
362
+ if (!name) { err("mz: 'app new' needs a name — usage: mz app new <name> [dir] [--id in.you.name] [--label 'My App']"); return 1; }
363
+ const res = appman.scaffoldApp(name, dir, {
364
+ id: flagVals['--id'],
365
+ label: flagVals['--label'],
366
+ port: flagVals['--port'] ? parseInt(flagVals['--port'], 10) : undefined,
367
+ });
368
+ out('created app ' + res.vars.label + ' (' + res.vars.id + ') in ' + res.root + ' (' + res.files + ' files)');
369
+ out('');
370
+ out(' next steps:');
371
+ out(' cd ' + (path.relative(process.cwd(), res.root) || res.root));
372
+ out(' mozhi dev # develop with live reload');
373
+ out(' mozhi test # unit tests');
374
+ out(' mz app build # release: dist/<name>-<version>.pkg');
375
+ out(' mz app install dist/<name>-<version>.pkg');
376
+ out(' mz app open ' + res.vars.id + ' # opens the full app window');
377
+ out(' mz app home # launcher home screen');
378
+ return 0;
379
+ }
380
+ if (sub === 'check') {
381
+ const app = appman.checkAppDir(args[1] || '.');
382
+ out('app structure OK: ' + app.label + ' (' + app.fields.id + ') v' + app.version +
383
+ ' — entry: ' + app.entry + ', icon: ' + app.iconRel + ', window: ' + app.mode + '/' + app.kind);
384
+ return 0;
385
+ }
386
+ if (sub === 'build') {
387
+ const res = appman.buildApp(args[1] || '.');
388
+ out('built ' + res.out);
389
+ out(' app: ' + res.label + ' (' + res.id + ') v' + res.version);
390
+ out(' files: ' + res.count + ' size: ' + res.bytes + ' bytes');
391
+ out(' sha256: ' + res.sha256);
392
+ out('install it with: mz app install ' + res.out);
393
+ return 0;
394
+ }
395
+ if (sub === 'install') {
396
+ if (!args[1]) { err("mz: 'app install' needs a .pkg file or app directory"); return 1; }
397
+ const res = appman.installApp(args[1], opts);
398
+ out('installed ' + res.meta.label + ' v' + res.meta.version + ' (' + res.meta.id + ')');
399
+ out(' location: ' + res.dest);
400
+ out(' launcher: ready — open with `mz app open ' + res.meta.id + '` or pick it in `mz app home`');
401
+ return 0;
402
+ }
403
+ if (sub === 'list' || sub === 'ls') {
404
+ const rows = appman.listApps(opts);
405
+ if (!rows.length) {
406
+ out('no apps installed — try: mz app new my-app');
407
+ return 0;
408
+ }
409
+ out(pad('ID', 26) + pad('NAME', 18) + pad('VERSION', 10) + pad('WINDOW', 12) + 'PATH');
410
+ for (const r of rows) {
411
+ out(pad(trunc(r.id, 25), 26) + pad(trunc(r.label, 17), 18) + pad(r.version, 10) +
412
+ pad(r.window + '/' + r.kind, 12) + r.path);
413
+ }
414
+ return 0;
415
+ }
416
+ if (sub === 'uninstall' || sub === 'remove') {
417
+ if (!args[1]) { err("mz: 'app uninstall' needs an app id (see mz app list)"); return 1; }
418
+ const removed = appman.uninstallApp(args[1], opts);
419
+ out('removed: ' + removed);
420
+ return 0;
421
+ }
422
+ return null;
423
+ }
424
+
425
+ async function cmdApp(args, opts) {
426
+ const sync = cmdAppSync(args, opts);
427
+ if (sync !== null) return sync;
428
+ const sub = args[0] || 'help';
429
+ if (sub === 'open') {
430
+ if (!args[1]) { err("mz: 'app open' needs an app id or app directory (see mz app list)"); return 1; }
431
+ return await appman.openApp(args[1], { noOpen: !!opts.noOpen });
432
+ }
433
+ if (sub === 'home') {
434
+ return await appman.home({ noPrompt: opts.noPrompt, local: opts.local });
435
+ }
436
+ appUsage();
437
+ return sub === 'help' || sub === '--help' ? 0 : 1;
438
+ }
439
+
440
+ function appUsage() {
441
+ out('usage: mz app <new|check|build|install|list|open|home|uninstall>');
442
+ out(' each command: mz app help · docs: docs/APPS.md in the Mozhi repo');
443
+ }
444
+
309
445
  /* Entry point. Returns process exit code. */
310
446
  async function run(argv) {
311
447
  const cmd = argv[0];
@@ -313,10 +449,13 @@ async function run(argv) {
313
449
  const opts = {
314
450
  local: args.includes('--local'),
315
451
  noDeps: args.includes('--no-deps'),
452
+ native: args.includes('--native'),
316
453
  dryRun: args.includes('--dry-run'),
317
454
  allowDirty: args.includes('--allow-dirty'),
455
+ noPrompt: args.includes('--no-prompt') || !process.stdout.isTTY,
456
+ noOpen: args.includes('--no-open'),
318
457
  };
319
- const rest = args.filter((a) => !['--local', '--no-deps', '--dry-run', '--allow-dirty'].includes(a));
458
+ const rest = args.filter((a) => !['--local', '--no-deps', '--native', '--dry-run', '--allow-dirty', '--no-prompt'].includes(a));
320
459
 
321
460
  try {
322
461
  switch (cmd) {
@@ -331,9 +470,12 @@ async function run(argv) {
331
470
  return cmdList();
332
471
  case 'search':
333
472
  return await cmdSearch(rest);
473
+ case 'app':
474
+ case 'apps':
475
+ return await cmdApp(rest, opts);
334
476
  case 'pkg':
335
477
  case 'package': {
336
- const sync = cmdPkg(rest);
478
+ const sync = cmdPkg(rest, opts);
337
479
  if (sync !== null) return sync;
338
480
  const sub = rest[0];
339
481
  if (sub === 'install') return await cmdInstall(rest.slice(1), opts);
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+ // NxMirror's public Mozhi resolver. No account or credentials are needed.
3
+ const DEFAULT_URL = 'https://nxmirror.netlify.app';
4
+ const MAX_ARCHIVE = 8 * 1024 * 1024;
5
+ const validName = (name) => /^[A-Za-z_][A-Za-z0-9_-]*$/.test(name);
6
+
7
+ function baseUrl() {
8
+ return (process.env.MOZHI_NXMIRROR_URL || DEFAULT_URL).replace(/\/+$/, '');
9
+ }
10
+
11
+ async function resolve(name, version) {
12
+ if (!validName(name)) throw new Error('invalid NxMirror package name: ' + name);
13
+ const url = baseUrl() + '/api/registry/mz/resolve/' + encodeURIComponent(name) +
14
+ (version ? '/' + encodeURIComponent(version) : '');
15
+ const res = await fetch(url, { signal: AbortSignal.timeout(15000) });
16
+ if (!res.ok) throw new Error('NxMirror resolve failed for ' + name + ' (HTTP ' + res.status + ')');
17
+ const record = await res.json();
18
+ if (record.success !== true || record.name !== name || typeof record.version !== 'string' ||
19
+ !/^[a-f0-9]{64}$/i.test(record.sha256 || '') || typeof record.downloadUrl !== 'string' ||
20
+ (record.dependencies !== undefined && (!Array.isArray(record.dependencies) ||
21
+ record.dependencies.some((d) => typeof d !== 'string' || !validName(d))))) {
22
+ throw new Error('invalid NxMirror resolver response for ' + name);
23
+ }
24
+ if (version && record.version !== version) throw new Error('NxMirror returned the wrong version for ' + name);
25
+ return record;
26
+ }
27
+
28
+ async function download(record) {
29
+ const url = new URL(record.downloadUrl, baseUrl());
30
+ if (!['https:', 'http:'].includes(url.protocol)) throw new Error('invalid NxMirror download URL');
31
+ const res = await fetch(url, { signal: AbortSignal.timeout(30000) });
32
+ if (!res.ok) throw new Error('NxMirror download failed (HTTP ' + res.status + ')');
33
+ if (Number(res.headers.get('content-length')) > MAX_ARCHIVE) throw new Error('NxMirror archive too large');
34
+ const chunks = [];
35
+ let size = 0;
36
+ for await (const chunk of res.body) {
37
+ size += chunk.length;
38
+ if (size > MAX_ARCHIVE) throw new Error('NxMirror archive too large');
39
+ chunks.push(chunk);
40
+ }
41
+ return Buffer.concat(chunks);
42
+ }
43
+
44
+ module.exports = { resolve, download, baseUrl, DEFAULT_URL };
package/lib/pkgman.js CHANGED
@@ -21,10 +21,12 @@ const fs = require('fs');
21
21
  const path = require('path');
22
22
  const os = require('os');
23
23
  const crypto = require('crypto');
24
- const { readZip, writeZip } = require('./zip');
24
+ const { readZip, writeZip, safeEntryName } = require('./zip');
25
25
  const reg = require('./registry');
26
26
  const gh = require('./gh');
27
27
  const semver = require('./semver');
28
+ const nx = require('./nxmirror');
29
+ const { readTarGz } = require('./tar');
28
30
 
29
31
  /* mozhi.toml is the canonical manifest name; package.toml remains
30
32
  * accepted for compatibility with packages published before v3.6. */
@@ -122,6 +124,15 @@ function readManifestFrom(files, prefix) {
122
124
  return null;
123
125
  }
124
126
 
127
+ /* Shared by author-side build requests and archive validation. */
128
+ function validateBinaryPath(binary) {
129
+ const safe = safeEntryName(binary);
130
+ if (!safe || safe !== binary || safe === ORIGIN_FILE || /\.(mz|mozhi|toml)$/.test(safe)) {
131
+ throw new Error('package binary must be a canonical relative artifact path, not a source/manifest file');
132
+ }
133
+ return safe;
134
+ }
135
+
125
136
  /* Verify a zip's package structure. Returns {manifestFile, manifest, prefix, entry, files}. */
126
137
  function verifyZip(files, expectedName) {
127
138
  const prefix = findManifestPrefix(files);
@@ -130,6 +141,9 @@ function verifyZip(files, expectedName) {
130
141
  if (!manifest.name) {
131
142
  throw new Error('package structure invalid: ' + mf.name + ' has no "name" field');
132
143
  }
144
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(manifest.name)) {
145
+ throw new Error('invalid package name: ' + manifest.name);
146
+ }
133
147
  if (expectedName && manifest.name !== expectedName) {
134
148
  throw new Error(
135
149
  'package structure invalid: manifest name "' + manifest.name + '" does not match expected "' + expectedName + '"'
@@ -143,6 +157,12 @@ function verifyZip(files, expectedName) {
143
157
  .filter(Boolean).join(', ') + ')'
144
158
  );
145
159
  }
160
+ if (manifest.binary) {
161
+ const binary = validateBinaryPath(manifest.binary);
162
+ if (binary === entry || !files.has(prefix + binary)) {
163
+ throw new Error('package binary must be an existing, canonical relative artifact path, not a source/manifest file');
164
+ }
165
+ }
146
166
  return { manifestFile: mf.name, manifest, prefix, entry, files };
147
167
  }
148
168
 
@@ -171,6 +191,9 @@ function extractTo(pkg, root, origin) {
171
191
  fs.mkdirSync(path.dirname(target), { recursive: true });
172
192
  fs.writeFileSync(target, data);
173
193
  }
194
+ // Only the manifest-declared optional tool gets execute permission.
195
+ // Never run package binaries or build hooks during installation.
196
+ if (pkg.manifest.binary) fs.chmodSync(path.join(staging, pkg.manifest.binary), 0o755);
174
197
  writeOrigin(staging, origin);
175
198
  fs.rmSync(dest, { recursive: true, force: true });
176
199
  fs.mkdirSync(path.dirname(dest), { recursive: true });
@@ -353,6 +376,33 @@ async function installFromRegistry(entry, nameSpec, opts = {}) {
353
376
  };
354
377
  }
355
378
 
379
+ async function installFromNxMirror(name, version, opts) {
380
+ const record = await nx.resolve(name, version);
381
+ if (opts.constraint && !semver.satisfies(record.version, opts.constraint)) {
382
+ throw new Error('NxMirror version of "' + name + '" does not satisfy ' + opts.constraint);
383
+ }
384
+ const buf = await nx.download(record);
385
+ assertChecksum(buf, record.sha256, name + ' archive');
386
+ const pkg = verifyZip(readTarGz(buf), name);
387
+ if (pkg.manifest.version !== record.version) throw new Error('NxMirror manifest version mismatch');
388
+ if (record.modSha256) {
389
+ if (!/^[a-f0-9]{64}$/i.test(record.modSha256)) throw new Error('invalid NxMirror module checksum');
390
+ const mod = pkg.files.get(pkg.prefix + 'src/mod.mz');
391
+ if (!mod) throw new Error('NxMirror package has no src/mod.mz');
392
+ assertChecksum(mod, record.modSha256, name + ' module');
393
+ }
394
+ const deps = { ...pkg.manifest.dependencies };
395
+ for (const dep of record.dependencies || []) {
396
+ if (!Object.hasOwn(deps, dep)) deps[dep] = '*';
397
+ }
398
+ pkg.manifest.dependencies = deps;
399
+ const dest = extractTo(pkg, pkgRoot(opts.local !== true), {
400
+ kind: 'nxmirror', name, version: record.version, registry: nx.baseUrl(),
401
+ sha256: record.sha256, local: !!opts.local, installed_at: new Date().toISOString(),
402
+ });
403
+ return { manifest: pkg.manifest, dest, manifestFile: pkg.manifestFile };
404
+ }
405
+
356
406
  async function installFromLocalZip(file, opts = {}) {
357
407
  const buf = fs.readFileSync(file);
358
408
  const res = await installFromZipBuffer(buf, {
@@ -410,6 +460,15 @@ async function install(spec, opts = {}) {
410
460
  const res = await installFromGit(m[1] + '/' + m[2], m[3] || null, { local });
411
461
  return finishInstall(res, { local, noDeps: opts.noDeps, depth: opts.depth || 0, seen: opts.seen });
412
462
  }
463
+ // nx:name[@version] explicitly selects NxMirror; bare names fall back
464
+ // only when absent from the existing registry (never on integrity failures).
465
+ const nxSpec = spec.startsWith('nx:') ? spec.slice(3) : null;
466
+ if (nxSpec !== null || opts.nxmirror) {
467
+ const match = (nxSpec === null ? spec : nxSpec).match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:@([^@/]+))?$/);
468
+ if (!match) throw new Error('invalid NxMirror spec: ' + spec);
469
+ const res = await installFromNxMirror(match[1], match[2] || null, { ...opts, local });
470
+ return finishInstall(res, { ...opts, local, nxmirror: true, depth: opts.depth || 0 });
471
+ }
413
472
  // registry name[@tag]
414
473
  const nm = spec.match(/^([^@]+)(?:@(.+))?$/);
415
474
  if (!nm) throw new Error('invalid package spec: ' + spec);
@@ -418,11 +477,14 @@ async function install(spec, opts = {}) {
418
477
  const { registry, source } = await reg.fetchRegistry();
419
478
  const entry = reg.findPackage(registry, name);
420
479
  if (!entry) {
421
- throw new Error(
422
- 'package "' + name + '" is not in the Mozhi registry.\n' +
423
- ' install from any Git repo: mz install @username/repo\n' +
424
- ' search the registry: mz search ' + name
425
- );
480
+ let res;
481
+ try {
482
+ res = await installFromNxMirror(name, tag, { ...opts, local });
483
+ } catch (e) {
484
+ throw new Error(e.message + '\n install from any Git repo: mz install @username/repo\n' +
485
+ ' search the registry: mz search ' + name);
486
+ }
487
+ return finishInstall(res, { ...opts, local, nxmirror: true, depth: opts.depth || 0 });
426
488
  }
427
489
  const res = await installFromRegistry(entry, name, { local, tag, constraint: opts.constraint });
428
490
  return finishInstall(res, { local, noDeps: opts.noDeps, depth: opts.depth || 0, seen: opts.seen, registrySource: source });
@@ -443,13 +505,14 @@ async function finishInstall(res, ctx) {
443
505
  const installed = [];
444
506
  for (const depName of names) {
445
507
  const constraint = deps[depName];
446
- const have = listInstalled().find((p) => p.name === depName);
508
+ const depDir = path.join(pkgRoot(ctx.local !== true), depName);
509
+ const have = readManifestDir(depDir);
447
510
  if (have && have.version && semver.satisfies(have.version, constraint)) {
448
511
  installed.push({ name: depName, version: have.version, skipped: true });
449
512
  continue;
450
513
  }
451
514
  const sub = await install(depName, {
452
- local: ctx.local, constraint, noDeps: false,
515
+ local: ctx.local, constraint, noDeps: false, nxmirror: ctx.nxmirror,
453
516
  depth: ctx.depth + 1,
454
517
  seen: ctx.seen,
455
518
  });
@@ -499,9 +562,15 @@ function uninstall(name, opts = {}) {
499
562
  }
500
563
 
501
564
  function readManifestDir(dir) {
502
- const mp = path.join(dir, MANIFEST);
503
- if (!fs.existsSync(mp)) return null;
504
- return parseManifest(fs.readFileSync(mp, 'utf8'));
565
+ /* Try every supported manifest name — legacy packages ship
566
+ * package.toml, current scaffolds write mozhi.toml. Without the
567
+ * fallback, `mz list` silently hid legacy packages after the
568
+ * mozhi.toml migration. */
569
+ for (const m of MANIFESTS) {
570
+ const mp = path.join(dir, m);
571
+ if (fs.existsSync(mp)) return parseManifest(fs.readFileSync(mp, 'utf8'));
572
+ }
573
+ return null;
505
574
  }
506
575
 
507
576
  function listInstalled() {
@@ -518,6 +587,7 @@ function listInstalled() {
518
587
  name: m.name || e.name,
519
588
  version: m.version || null,
520
589
  source: origin.kind === 'git' ? (origin.repo + (origin.tag ? '@' + origin.tag : ''))
590
+ : origin.kind === 'nxmirror' ? 'nxmirror: ' + origin.registry
521
591
  : origin.kind === 'local-zip' ? 'zip: ' + (origin.file || '?')
522
592
  : origin.kind === 'local-dir' ? 'dir: ' + (origin.file || '?')
523
593
  : 'unknown',
@@ -559,7 +629,9 @@ async function update(name, opts = {}) {
559
629
  }
560
630
  const results = [];
561
631
  for (const t of targets) {
562
- const res = await install(t.name, { local: !!opts.local, noDeps: true, depth: MAX_DEP_DEPTH });
632
+ const origin = readOrigin(t.path);
633
+ const res = await install(t.name, { local: !!opts.local, noDeps: true, depth: MAX_DEP_DEPTH,
634
+ nxmirror: origin && origin.kind === 'nxmirror' });
563
635
  const newVer = res.manifest ? res.manifest.version : null;
564
636
  results.push({ name: t.name, from: t.version, to: newVer, changed: newVer !== t.version });
565
637
  }
@@ -606,7 +678,8 @@ function info(name, opts = {}) {
606
678
  /* Validate a package directory. Returns manifest + file map. Throws when invalid. */
607
679
  function checkDir(dir) {
608
680
  const abs = path.resolve(dir || '.');
609
- const manifest = parseManifest(fs.readFileSync(path.join(abs, MANIFEST), 'utf8'));
681
+ const mf = MANIFESTS.find((m) => fs.existsSync(path.join(abs, m)));
682
+ if (!mf) throw new Error('missing mozhi.toml or package.toml');
610
683
  const files = new Map();
611
684
  const walk = (d, rel) => {
612
685
  for (const e of fs.readdirSync(d, { withFileTypes: true })) {
@@ -634,6 +707,6 @@ function zipDir(dir, outPath) {
634
707
 
635
708
  module.exports = {
636
709
  install, uninstall, listInstalled, update, info, checkDir, zipDir,
637
- parseManifest, verifyZip, findManifestPrefix, resolveEntry,
710
+ parseManifest, verifyZip, findManifestPrefix, resolveEntry, validateBinaryPath,
638
711
  pkgRoot, libsRoot, MANIFEST, MANIFESTS, ORIGIN_FILE, sha256hex,
639
712
  };
package/lib/tar.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ // Restricted tar.gz reader: regular files/directories only, never filesystem links.
3
+ const { gunzipSync } = require('zlib');
4
+ const MAX_BYTES = 128 * 1024 * 1024;
5
+
6
+ function safeName(name) {
7
+ if (!name || name.includes('\0') || name.includes('\\') || name.startsWith('/') ||
8
+ /^[A-Za-z]:/.test(name) || name.split('/').includes('..')) {
9
+ throw new Error('unsafe tar entry: ' + name);
10
+ }
11
+ return name.split('/').filter((p) => p && p !== '.').join('/');
12
+ }
13
+
14
+ function readTarGz(buf) {
15
+ const tar = gunzipSync(buf, { maxOutputLength: MAX_BYTES });
16
+ const files = new Map();
17
+ const text = (b) => b.toString('utf8').replace(/\0.*$/s, '');
18
+ const octal = (b) => {
19
+ const s = text(b).trim();
20
+ if (!/^[0-7]+$/.test(s)) throw new Error('invalid tar numeric field');
21
+ return parseInt(s, 8);
22
+ };
23
+ let offset = 0;
24
+ let count = 0;
25
+ while (offset + 512 <= tar.length) {
26
+ const h = tar.subarray(offset, offset + 512);
27
+ if (h.every((b) => b === 0)) {
28
+ if (tar.length - offset < 1024 || !tar.subarray(offset).every((b) => b === 0)) {
29
+ throw new Error('invalid tar end marker');
30
+ }
31
+ return files;
32
+ }
33
+ if (++count > 4096) throw new Error('too many tar entries');
34
+ let sum = 0;
35
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i];
36
+ if (sum !== octal(h.subarray(148, 156))) throw new Error('tar header checksum mismatch');
37
+ const size = octal(h.subarray(124, 136));
38
+ const prefix = text(h.subarray(345, 500));
39
+ const name = safeName((prefix ? prefix + '/' : '') + text(h.subarray(0, 100)));
40
+ const type = h[156];
41
+ // Fail closed on symlinks, hardlinks, devices and extension headers.
42
+ if (![0, 48, 53].includes(type)) throw new Error('unsupported tar entry type: ' + name);
43
+ if (size > 64 * 1024 * 1024 || offset + 512 + Math.ceil(size / 512) * 512 > tar.length) {
44
+ throw new Error('truncated or oversized tar entry: ' + name);
45
+ }
46
+ if (type === 53 && size !== 0) throw new Error('invalid tar directory: ' + name);
47
+ if (type !== 53) {
48
+ if (!name || files.has(name)) throw new Error('duplicate or empty tar entry: ' + name);
49
+ files.set(name, tar.subarray(offset + 512, offset + 512 + size));
50
+ }
51
+ offset += 512 + Math.ceil(size / 512) * 512;
52
+ }
53
+ throw new Error('truncated tar archive');
54
+ }
55
+
56
+ module.exports = { readTarGz };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossberryweb/mozhi",
3
- "version": "3.7.0",
4
- "description": "Mozhi programming language interpreter \u2014 native web, JSON, fs, math, SQLite, templates \u2014 with the built-in package manager (`mz install`). Install once, get both commands: `mozhi` and the short alias `mz` (identical behavior).",
3
+ "version": "3.9.0",
4
+ "description": "Mozhi programming language: native web platform, mz package manager with NxMirror support, nx_modules imports, apps, and configurable numeric native builds.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",