@rbbtsn0w/adg 0.8.0-beta.4 → 0.8.0-beta.5

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.
@@ -75,17 +75,18 @@ export function multiselectSkills(opts) {
75
75
  return undefined;
76
76
  },
77
77
  render() {
78
+ const selected = this.value ?? [];
78
79
  const head = `${pc.gray(S_BAR)}\n${symbol(this.state)} ${opts.message}\n`;
79
80
  if (this.state === "submit" || this.state === "cancel") {
80
81
  const chosen = this.options
81
- .filter((o) => this.value.includes(o.value))
82
+ .filter((o) => selected.includes(o.value))
82
83
  .map((o) => pc.dim(o.label))
83
84
  .join(pc.dim(", "));
84
85
  return `${head}${pc.gray(S_BAR)} ${chosen || pc.dim("none")}`;
85
86
  }
86
87
  const rows = buildSkillRows(this.options, {
87
88
  cursor: this.cursor,
88
- selected: this.value,
89
+ selected,
89
90
  showDesc,
90
91
  loadDescription: opts.loadDescription,
91
92
  }).join(`\n${pc.cyan(S_BAR)} `);
@@ -27,7 +27,21 @@ export function getLockSource(parsedUrl, normalizedSource) {
27
27
  // When normalizedSource is used, parseSource() later resolves it to HTTPS,
28
28
  // breaking restore for private repos that require SSH authentication.
29
29
  const isSSH = parsedUrl.startsWith('git@') || parsedUrl.startsWith('ssh://');
30
- return isSSH ? parsedUrl : normalizedSource;
30
+ if (isSSH)
31
+ return parsedUrl;
32
+ if (parsedUrl.startsWith('http://') || parsedUrl.startsWith('https://')) {
33
+ try {
34
+ if (new URL(parsedUrl).hostname !== 'github.com')
35
+ return parsedUrl;
36
+ }
37
+ catch {
38
+ return normalizedSource;
39
+ }
40
+ }
41
+ return normalizedSource;
42
+ }
43
+ export function getProjectLockSourceUrl(sourceType, sourceUrl) {
44
+ return sourceType === 'git' || sourceType === 'gitlab' ? sourceUrl : undefined;
31
45
  }
32
46
  import { cloneRepo, cleanupTempDir, GitCloneError } from "./git.js";
33
47
  import { gitTreeShaForFolder } from "./git-tree.js";
@@ -36,7 +50,8 @@ import { installSkillForAgent, installBlobSkillForAgent, isSkillInstalled, getCa
36
50
  import { detectInstalledAgents, agents, getUniversalAgents, getVisibleUniversalAgents, getNonUniversalAgents, isUniversalAgent, getEveSubagents, } from "./agents.js";
37
51
  import { track, fetchAuditData, } from "./telemetry.js";
38
52
  import { detectAgent, getAgentType } from "./detect-agent.js";
39
- import { wellKnownProvider } from "./providers/index.js";
53
+ import { wellKnownProvider, computeWellKnownSkillDigest, WellKnownScopeNotFoundError, } from "./providers/index.js";
54
+ import { downloadSource } from "./download-source.js";
40
55
  import { addSkillToLock, fetchSkillFolderHash, getGitHubToken, isPromptDismissed, dismissPrompt, getLastSelectedAgents, saveSelectedAgents, } from "./skill-lock.js";
41
56
  import { addSkillToLocalLock, computeSkillFolderHash } from "./local-lock.js";
42
57
  import { tryBlobInstall, BLOB_ALLOWED_REPOS, getSkillFolderHashFromTree, fetchRepoTree, } from "./blob.js";
@@ -395,12 +410,24 @@ async function selectAgentsInteractive(options) {
395
410
  */
396
411
  async function handleWellKnownSkills(source, url, options, spinner) {
397
412
  spinner.start('Discovering skills from well-known endpoint...');
398
- // Fetch all skills from the well-known endpoint
399
- const skills = await wellKnownProvider.fetchAllSkills(url);
413
+ // Fetch all skills from the well-known endpoint. Explicit named selection
414
+ // is the documented escape hatch for internal skills; wildcard is not.
415
+ let skills = [];
416
+ try {
417
+ skills = await wellKnownProvider.fetchAllSkills(url, {
418
+ includeInternal: Boolean(options.skill && options.skill.length > 0 && !options.skill.includes('*')),
419
+ });
420
+ }
421
+ catch (error) {
422
+ if (error instanceof WellKnownScopeNotFoundError) {
423
+ spinner.stop(pc.red('No matching skills'));
424
+ p.log.error(error.message);
425
+ process.exit(1);
426
+ }
427
+ }
400
428
  if (skills.length === 0) {
401
- spinner.stop(pc.red('No skills found'));
402
- p.outro(pc.red('No skills found at this URL. Make sure the server has a /.well-known/agent-skills/index.json or /.well-known/skills/index.json file.'));
403
- process.exit(1);
429
+ spinner.stop(pc.dim('No well-known skills found; trying direct download...'));
430
+ return false;
404
431
  }
405
432
  spinner.stop(`Found ${pc.green(skills.length)} skill${skills.length > 1 ? 's' : ''}`);
406
433
  // Log discovered skills
@@ -666,6 +693,7 @@ async function handleWellKnownSkills(source, url, options, spinner) {
666
693
  agents: targetAgents.join(','),
667
694
  ...(installGlobally && { global: '1' }),
668
695
  skillFiles: JSON.stringify(skillFiles),
696
+ installUrl: url,
669
697
  sourceType: 'well-known',
670
698
  });
671
699
  }
@@ -680,6 +708,8 @@ async function handleWellKnownSkills(source, url, options, spinner) {
680
708
  sourceType: 'well-known',
681
709
  sourceUrl: skill.sourceUrl,
682
710
  skillFolderHash: '', // Well-known skills don't have a folder hash
711
+ sourceBaseUrl: url,
712
+ wellKnownDigest: computeWellKnownSkillDigest(skill),
683
713
  });
684
714
  }
685
715
  catch {
@@ -700,8 +730,10 @@ async function handleWellKnownSkills(source, url, options, spinner) {
700
730
  const computedHash = await computeSkillFolderHash(installDir);
701
731
  await addSkillToLocalLock(skill.installName, {
702
732
  source: sourceIdentifier,
733
+ sourceUrl: url,
703
734
  sourceType: 'well-known',
704
735
  computedHash,
736
+ wellKnownDigest: computeWellKnownSkillDigest(skill),
705
737
  }, cwd);
706
738
  }
707
739
  }
@@ -763,6 +795,7 @@ async function handleWellKnownSkills(source, url, options, spinner) {
763
795
  p.outro(pc.green('Done!') + pc.dim(' Review skills before use; they run with full agent permissions.'));
764
796
  // Prompt for find-skills after successful install
765
797
  await promptForFindSkills(options, targetAgents);
798
+ return true;
766
799
  }
767
800
  export async function runAdd(args, options = {}) {
768
801
  const source = args[0];
@@ -833,10 +866,14 @@ export async function runAdd(args, options = {}) {
833
866
  return Promise.resolve(null);
834
867
  return isRepoPrivate(ownerRepo.owner, ownerRepo.repo).catch(() => null);
835
868
  })();
836
- // Handle well-known skills from arbitrary URLs
869
+ let directDownload = parsed.type === 'download';
870
+ // Handle well-known skills from arbitrary URLs. If discovery does not
871
+ // yield skills, the same URL may still be a raw SKILL.md or archive.
837
872
  if (parsed.type === 'well-known') {
838
- await handleWellKnownSkills(source, parsed.url, options, spinner);
839
- return;
873
+ const handled = await handleWellKnownSkills(source, parsed.url, options, spinner);
874
+ if (handled)
875
+ return;
876
+ directDownload = true;
840
877
  }
841
878
  // If skillFilter is present from @skill syntax (e.g., owner/repo@skill-name),
842
879
  // merge it into options.skill
@@ -848,7 +885,7 @@ export async function runAdd(args, options = {}) {
848
885
  }
849
886
  // Include internal skills when a specific skill is explicitly requested
850
887
  // (via --skill or @skill syntax)
851
- const includeInternal = !!(options.skill && options.skill.length > 0);
888
+ const includeInternal = Boolean(options.skill && options.skill.length > 0 && !options.skill.includes('*'));
852
889
  let skills;
853
890
  let blobResult = null;
854
891
  if (parsed.type === 'local') {
@@ -866,6 +903,17 @@ export async function runAdd(args, options = {}) {
866
903
  fullDepth: options.fullDepth,
867
904
  });
868
905
  }
906
+ else if (parsed.type === 'well-known' || parsed.type === 'download') {
907
+ spinner.start('Downloading source...');
908
+ const downloaded = await downloadSource(parsed.url);
909
+ tempDir = downloaded.tempDir;
910
+ spinner.stop(`Downloaded ${downloaded.kind === 'skill-md' ? 'SKILL.md file' : 'archive'}`);
911
+ spinner.start('Discovering skills...');
912
+ skills = await discoverSkills(downloaded.rootDir, parsed.subpath, {
913
+ includeInternal,
914
+ fullDepth: options.fullDepth,
915
+ });
916
+ }
869
917
  else if (parsed.type === 'github' && !options.fullDepth) {
870
918
  // Try the blob-based fast install for GitHub sources; skip for --full-depth.
871
919
  // Eligible per repo (a BLOB_ALLOWED_REPOS entry = self-hosted download URL) or
@@ -1435,8 +1483,11 @@ export async function runAdd(args, options = {}) {
1435
1483
  }
1436
1484
  }
1437
1485
  // Normalize source to owner/repo format for telemetry
1438
- const normalizedSource = getOwnerRepo(parsed);
1439
- const lockSource = getLockSource(parsed.url, normalizedSource);
1486
+ const normalizedSource = directDownload ? null : getOwnerRepo(parsed);
1487
+ const lockSource = directDownload ? null : getLockSource(parsed.url, normalizedSource);
1488
+ const projectLockSourceUrl = directDownload
1489
+ ? undefined
1490
+ : getProjectLockSourceUrl(parsed.type, parsed.url);
1440
1491
  // Only track if we have a valid remote source and it's not a private repo.
1441
1492
  // repoPrivacyPromise was started early (right after parsing) so it has
1442
1493
  // already been running in parallel with the entire install — no stall here.
@@ -1530,7 +1581,7 @@ export async function runAdd(args, options = {}) {
1530
1581
  }
1531
1582
  }
1532
1583
  // Add to local lock file for project-scoped installs
1533
- if (successful.length > 0 && !installGlobally) {
1584
+ if (successful.length > 0 && !installGlobally && !directDownload) {
1534
1585
  const successfulSkillNames = new Set(successful.map((r) => r.skill));
1535
1586
  // Record Eve subagent placement (root = '') so `update` can restore it.
1536
1587
  // Only meaningful when Eve is among the targets and a non-root subagent
@@ -1552,6 +1603,7 @@ export async function runAdd(args, options = {}) {
1552
1603
  const skillPathValue = skillFiles[skill.name];
1553
1604
  await addSkillToLocalLock(skill.name, {
1554
1605
  source: lockSource || parsed.url,
1606
+ ...(projectLockSourceUrl && { sourceUrl: projectLockSourceUrl }),
1555
1607
  ref: parsed.ref,
1556
1608
  sourceType: parsed.type,
1557
1609
  ...(skillPathValue && { skillPath: skillPathValue }),
@@ -1756,6 +1808,7 @@ async function promptForFindSkills(options, targetAgents) {
1756
1808
  export function parseAddOptions(args) {
1757
1809
  const options = {};
1758
1810
  const source = [];
1811
+ const errors = [];
1759
1812
  for (let i = 0; i < args.length; i++) {
1760
1813
  const arg = args[i];
1761
1814
  if (arg === '-g' || arg === '--global') {
@@ -1773,6 +1826,8 @@ export function parseAddOptions(args) {
1773
1826
  else if (arg === '-a' || arg === '--agent') {
1774
1827
  options.agent = options.agent || [];
1775
1828
  i++;
1829
+ if (!args[i] || args[i].startsWith('-'))
1830
+ errors.push(`${arg} requires an agent name`);
1776
1831
  let nextArg = args[i];
1777
1832
  while (i < args.length && nextArg && !nextArg.startsWith('-')) {
1778
1833
  options.agent.push(nextArg);
@@ -1784,6 +1839,8 @@ export function parseAddOptions(args) {
1784
1839
  else if (arg === '-s' || arg === '--skill') {
1785
1840
  options.skill = options.skill || [];
1786
1841
  i++;
1842
+ if (!args[i] || args[i].startsWith('-'))
1843
+ errors.push(`${arg} requires a skill name`);
1787
1844
  let nextArg = args[i];
1788
1845
  while (i < args.length && nextArg && !nextArg.startsWith('-')) {
1789
1846
  options.skill.push(nextArg);
@@ -1792,6 +1849,21 @@ export function parseAddOptions(args) {
1792
1849
  }
1793
1850
  i--; // Back up one since the loop will increment
1794
1851
  }
1852
+ else if (arg === '--metadata') {
1853
+ const metadata = args[++i];
1854
+ if (metadata === undefined) {
1855
+ errors.push('--metadata requires a JSON value');
1856
+ }
1857
+ else {
1858
+ try {
1859
+ JSON.parse(metadata);
1860
+ options.metadata = metadata;
1861
+ }
1862
+ catch {
1863
+ errors.push('--metadata must be valid JSON');
1864
+ }
1865
+ }
1866
+ }
1795
1867
  else if (arg === '--full-depth') {
1796
1868
  options.fullDepth = true;
1797
1869
  }
@@ -1801,6 +1873,8 @@ export function parseAddOptions(args) {
1801
1873
  else if (arg === '--subagent') {
1802
1874
  options.subagent = options.subagent || [];
1803
1875
  i++;
1876
+ if (!args[i] || args[i].startsWith('-'))
1877
+ errors.push('--subagent requires a name');
1804
1878
  let nextArg = args[i];
1805
1879
  while (i < args.length && nextArg && !nextArg.startsWith('-')) {
1806
1880
  options.subagent.push(nextArg);
@@ -1812,6 +1886,9 @@ export function parseAddOptions(args) {
1812
1886
  else if (arg && !arg.startsWith('-')) {
1813
1887
  source.push(arg);
1814
1888
  }
1889
+ else if (arg) {
1890
+ errors.push(`Unknown option: ${arg}`);
1891
+ }
1815
1892
  }
1816
- return { source, options };
1893
+ return { source, options, errors };
1817
1894
  }
@@ -16,6 +16,7 @@ const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, '.claude'
16
16
  const vibeHome = process.env.VIBE_HOME?.trim() || join(home, '.vibe');
17
17
  const hermesHome = process.env.HERMES_HOME?.trim() || join(home, '.hermes');
18
18
  const autohandHome = process.env.AUTOHAND_HOME?.trim() || join(home, '.autohand');
19
+ const grokHome = process.env.GROK_HOME?.trim() || join(home, '.grok');
19
20
  const zedAppDataHome = process.env.APPDATA?.trim();
20
21
  const zedFlatpakConfigHome = process.env.FLATPAK_XDG_CONFIG_HOME?.trim();
21
22
  function packageJsonHasDependency(packageJsonPath, dependencyName) {
@@ -39,6 +40,20 @@ export function getOpenClawGlobalSkillsDir(homeDir = home, pathExists = existsSy
39
40
  }
40
41
  return join(homeDir, '.openclaw/skills');
41
42
  }
43
+ export function isZCodeInstalled(homeDir = home, pathExists = existsSync) {
44
+ return pathExists(join(homeDir, '.zcode')) || pathExists('/Applications/ZCode.app');
45
+ }
46
+ export function isKimchiInstalled(homeDir = home, pathExists = existsSync) {
47
+ return pathExists(join(homeDir, '.config', 'kimchi'));
48
+ }
49
+ export function isMiniMaxCodeInstalled(homeDir = home, pathExists = existsSync) {
50
+ return pathExists(join(homeDir, '.minimax')) || pathExists('/Applications/MiniMax Code.app');
51
+ }
52
+ export function isPositAssistantInstalled(homeDir = home, pathExists = existsSync) {
53
+ // ~/.positai is the pre-rename config dir, still present on installs
54
+ // that haven't launched a current version yet.
55
+ return pathExists(join(homeDir, '.posit/assistant')) || pathExists(join(homeDir, '.positai'));
56
+ }
42
57
  export const agents = {
43
58
  'aider-desk': {
44
59
  name: 'aider-desk',
@@ -324,6 +339,15 @@ export const agents = {
324
339
  return existsSync(join(configHome, 'goose'));
325
340
  },
326
341
  },
342
+ grok: {
343
+ name: 'grok',
344
+ displayName: 'Grok Build',
345
+ skillsDir: '.grok/skills',
346
+ globalSkillsDir: join(grokHome, 'skills'),
347
+ detectInstalled: async () => {
348
+ return existsSync(grokHome);
349
+ },
350
+ },
327
351
  'hermes-agent': {
328
352
  name: 'hermes-agent',
329
353
  displayName: 'Hermes Agent',
@@ -378,6 +402,15 @@ export const agents = {
378
402
  return existsSync(join(home, '.kilocode'));
379
403
  },
380
404
  },
405
+ kimchi: {
406
+ name: 'kimchi',
407
+ displayName: 'Kimchi',
408
+ skillsDir: '.kimchi/skills',
409
+ globalSkillsDir: join(home, '.config', 'kimchi', 'harness', 'skills'),
410
+ detectInstalled: async () => {
411
+ return isKimchiInstalled();
412
+ },
413
+ },
381
414
  'kimi-code-cli': {
382
415
  name: 'kimi-code-cli',
383
416
  displayName: 'Kimi Code CLI',
@@ -433,6 +466,15 @@ export const agents = {
433
466
  return existsSync(join(home, '.mcpjam'));
434
467
  },
435
468
  },
469
+ 'minimax-code': {
470
+ name: 'minimax-code',
471
+ displayName: 'MiniMax Code',
472
+ skillsDir: '.minimax/skills',
473
+ globalSkillsDir: join(home, '.minimax/skills'),
474
+ detectInstalled: async () => {
475
+ return isMiniMaxCodeInstalled();
476
+ },
477
+ },
436
478
  'mistral-vibe': {
437
479
  name: 'mistral-vibe',
438
480
  displayName: 'Mistral Vibe',
@@ -496,6 +538,15 @@ export const agents = {
496
538
  return existsSync(join(home, '.pi/agent'));
497
539
  },
498
540
  },
541
+ 'posit-assistant': {
542
+ name: 'posit-assistant',
543
+ displayName: 'Posit Assistant',
544
+ skillsDir: '.posit/assistant/skills',
545
+ globalSkillsDir: join(home, '.posit/assistant/skills'),
546
+ detectInstalled: async () => {
547
+ return isPositAssistantInstalled();
548
+ },
549
+ },
499
550
  qoder: {
500
551
  name: 'qoder',
501
552
  displayName: 'Qoder',
@@ -635,6 +686,15 @@ export const agents = {
635
686
  (!!zedFlatpakConfigHome && existsSync(join(zedFlatpakConfigHome, 'zed'))));
636
687
  },
637
688
  },
689
+ zcode: {
690
+ name: 'zcode',
691
+ displayName: 'ZCode',
692
+ skillsDir: '.zcode/skills',
693
+ globalSkillsDir: join(home, '.zcode/skills'),
694
+ detectInstalled: async () => {
695
+ return isZCodeInstalled();
696
+ },
697
+ },
638
698
  zencoder: {
639
699
  name: 'zencoder',
640
700
  displayName: 'Zencoder',
@@ -0,0 +1,311 @@
1
+ import { crc32, inflateRawSync } from 'node:zlib';
2
+ const ZIP_LOCAL_FILE_HEADER = 0x04034b50;
3
+ const ZIP_CENTRAL_DIRECTORY_HEADER = 0x02014b50;
4
+ const ZIP_END_OF_CENTRAL_DIRECTORY = 0x06054b50;
5
+ const ZIP64_END_OF_CENTRAL_DIRECTORY = 0x06064b50;
6
+ const ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR = 0x07064b50;
7
+ const ZIP_END_MIN_SIZE = 22;
8
+ const ZIP_MAX_COMMENT_SIZE = 0xffff;
9
+ const CP437_HIGH_BYTES = [
10
+ 'ÇüéâäàåçêëèïîìÄÅ',
11
+ 'ÉæÆôöòûùÿÖÜ¢£¥₧ƒ',
12
+ 'áíóúñѪº¿⌐¬½¼¡«»',
13
+ '░▒▓│┤╡╢╖╕╣║╗╝╜╛┐',
14
+ '└┴┬├─┼╞╟╚╔╩╦╠═╬╧',
15
+ '╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀',
16
+ 'αßΓπΣσµτΦΘΩδ∞φε∩',
17
+ '≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00a0',
18
+ ].join('');
19
+ export class ArchiveValidationError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'ArchiveValidationError';
23
+ }
24
+ }
25
+ function ensureRange(buffer, offset, length, label) {
26
+ if (!Number.isSafeInteger(offset) ||
27
+ !Number.isSafeInteger(length) ||
28
+ offset < 0 ||
29
+ length < 0 ||
30
+ offset + length > buffer.length) {
31
+ throw new Error(`Invalid zip archive: ${label} is out of bounds`);
32
+ }
33
+ }
34
+ function findEndOfCentralDirectory(buffer) {
35
+ const minOffset = Math.max(0, buffer.length - ZIP_MAX_COMMENT_SIZE - ZIP_END_MIN_SIZE);
36
+ for (let offset = buffer.length - ZIP_END_MIN_SIZE; offset >= minOffset; offset--) {
37
+ if (buffer.readUInt32LE(offset) !== ZIP_END_OF_CENTRAL_DIRECTORY)
38
+ continue;
39
+ const commentLength = buffer.readUInt16LE(offset + 20);
40
+ if (offset + ZIP_END_MIN_SIZE + commentLength === buffer.length) {
41
+ return offset;
42
+ }
43
+ }
44
+ return -1;
45
+ }
46
+ function readUInt64AsNumber(buffer, offset, label) {
47
+ ensureRange(buffer, offset, 8, label);
48
+ const value = buffer.readBigUInt64LE(offset);
49
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
50
+ throw new Error(`Invalid zip archive: ${label} exceeds the safe integer range`);
51
+ }
52
+ return Number(value);
53
+ }
54
+ function readCentralDirectory(buffer, endOffset) {
55
+ const diskNumber = buffer.readUInt16LE(endOffset + 4);
56
+ const centralDirectoryDisk = buffer.readUInt16LE(endOffset + 6);
57
+ const entriesOnDisk = buffer.readUInt16LE(endOffset + 8);
58
+ const totalEntries = buffer.readUInt16LE(endOffset + 10);
59
+ const size = buffer.readUInt32LE(endOffset + 12);
60
+ const offset = buffer.readUInt32LE(endOffset + 16);
61
+ const usesZip64 = entriesOnDisk === 0xffff ||
62
+ totalEntries === 0xffff ||
63
+ size === 0xffffffff ||
64
+ offset === 0xffffffff;
65
+ if (!usesZip64) {
66
+ if (diskNumber !== 0 || centralDirectoryDisk !== 0 || entriesOnDisk !== totalEntries) {
67
+ throw new Error('Multi-disk zip archives are not supported');
68
+ }
69
+ return { entries: totalEntries, offset, size, trailerOffset: endOffset };
70
+ }
71
+ if (diskNumber !== 0 || centralDirectoryDisk !== 0) {
72
+ throw new Error('Multi-disk zip archives are not supported');
73
+ }
74
+ const locatorOffset = endOffset - 20;
75
+ ensureRange(buffer, locatorOffset, 20, 'zip64 locator');
76
+ if (buffer.readUInt32LE(locatorOffset) !== ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR) {
77
+ throw new Error('Invalid zip64 locator');
78
+ }
79
+ if (buffer.readUInt32LE(locatorOffset + 4) !== 0 ||
80
+ buffer.readUInt32LE(locatorOffset + 16) !== 1) {
81
+ throw new Error('Multi-disk zip archives are not supported');
82
+ }
83
+ const zip64EndOffset = readUInt64AsNumber(buffer, locatorOffset + 8, 'zip64 end offset');
84
+ ensureRange(buffer, zip64EndOffset, 56, 'zip64 end of central directory');
85
+ if (buffer.readUInt32LE(zip64EndOffset) !== ZIP64_END_OF_CENTRAL_DIRECTORY) {
86
+ throw new Error('Invalid zip64 end of central directory');
87
+ }
88
+ const recordSize = readUInt64AsNumber(buffer, zip64EndOffset + 4, 'zip64 end size');
89
+ if (recordSize < 44) {
90
+ throw new Error('Invalid zip64 end of central directory');
91
+ }
92
+ ensureRange(buffer, zip64EndOffset, recordSize + 12, 'zip64 end of central directory');
93
+ if (zip64EndOffset + recordSize + 12 !== locatorOffset) {
94
+ throw new Error('Invalid zip64 end of central directory');
95
+ }
96
+ if (buffer.readUInt32LE(zip64EndOffset + 16) !== 0 ||
97
+ buffer.readUInt32LE(zip64EndOffset + 20) !== 0) {
98
+ throw new Error('Multi-disk zip archives are not supported');
99
+ }
100
+ const zip64EntriesOnDisk = readUInt64AsNumber(buffer, zip64EndOffset + 24, 'zip64 entries on disk');
101
+ const zip64TotalEntries = readUInt64AsNumber(buffer, zip64EndOffset + 32, 'zip64 total entries');
102
+ if (zip64EntriesOnDisk !== zip64TotalEntries) {
103
+ throw new Error('Multi-disk zip archives are not supported');
104
+ }
105
+ return {
106
+ entries: zip64TotalEntries,
107
+ size: readUInt64AsNumber(buffer, zip64EndOffset + 40, 'zip64 central directory size'),
108
+ offset: readUInt64AsNumber(buffer, zip64EndOffset + 48, 'zip64 central directory offset'),
109
+ trailerOffset: zip64EndOffset,
110
+ };
111
+ }
112
+ function normalizeArchivePath(rawPath) {
113
+ if (!rawPath || rawPath.includes('\0'))
114
+ return null;
115
+ const path = rawPath.replace(/\\/g, '/');
116
+ if (path.startsWith('/') || /^[A-Za-z]:/.test(path))
117
+ return null;
118
+ const parts = path.split('/');
119
+ if (parts.some((part) => part === '..'))
120
+ return null;
121
+ const normalized = parts.filter((part) => part && part !== '.').join('/');
122
+ if (!normalized && !path.endsWith('/'))
123
+ return null;
124
+ return path.endsWith('/') && normalized ? `${normalized}/` : normalized;
125
+ }
126
+ function findExtraField(buffer, extraOffset, extraLength, targetId) {
127
+ const extraEnd = extraOffset + extraLength;
128
+ let offset = extraOffset;
129
+ while (offset < extraEnd) {
130
+ if (offset + 4 > extraEnd)
131
+ throw new Error('Invalid zip extra field');
132
+ const id = buffer.readUInt16LE(offset);
133
+ const size = buffer.readUInt16LE(offset + 2);
134
+ const dataOffset = offset + 4;
135
+ ensureRange(buffer, dataOffset, size, 'zip extra field');
136
+ if (dataOffset + size > extraEnd)
137
+ throw new Error('Invalid zip extra field');
138
+ if (id === targetId)
139
+ return buffer.subarray(dataOffset, dataOffset + size);
140
+ offset = dataOffset + size;
141
+ }
142
+ return null;
143
+ }
144
+ function decodeFileName(bytes, isUtf8, unicodePathExtra) {
145
+ if (isUtf8) {
146
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
147
+ }
148
+ if (unicodePathExtra &&
149
+ unicodePathExtra.length >= 5 &&
150
+ unicodePathExtra[0] === 1 &&
151
+ unicodePathExtra.readUInt32LE(1) === crc32(bytes)) {
152
+ return new TextDecoder('utf-8', { fatal: true }).decode(unicodePathExtra.subarray(5));
153
+ }
154
+ let result = '';
155
+ for (const byte of bytes) {
156
+ result += byte < 0x80 ? String.fromCharCode(byte) : CP437_HIGH_BYTES[byte - 0x80];
157
+ }
158
+ return result;
159
+ }
160
+ function readZip64EntryValues(buffer, extraOffset, extraLength, values) {
161
+ const needsZip64 = values.uncompressedSize === 0xffffffff ||
162
+ values.compressedSize === 0xffffffff ||
163
+ values.localHeaderOffset === 0xffffffff ||
164
+ values.diskStart === 0xffff;
165
+ if (!needsZip64) {
166
+ if (values.diskStart !== 0)
167
+ throw new Error('Multi-disk zip archives are not supported');
168
+ return values;
169
+ }
170
+ const zip64Extra = findExtraField(buffer, extraOffset, extraLength, 0x0001);
171
+ if (!zip64Extra)
172
+ throw new Error('Invalid zip64 extra field');
173
+ let valueOffset = 0;
174
+ const readNextUInt64 = (label) => {
175
+ if (valueOffset + 8 > zip64Extra.length) {
176
+ throw new Error(`Invalid zip64 extra field: missing ${label}`);
177
+ }
178
+ const value = readUInt64AsNumber(zip64Extra, valueOffset, `zip64 ${label}`);
179
+ valueOffset += 8;
180
+ return value;
181
+ };
182
+ const resolved = { ...values };
183
+ if (resolved.uncompressedSize === 0xffffffff) {
184
+ resolved.uncompressedSize = readNextUInt64('uncompressed size');
185
+ }
186
+ if (resolved.compressedSize === 0xffffffff) {
187
+ resolved.compressedSize = readNextUInt64('compressed size');
188
+ }
189
+ if (resolved.localHeaderOffset === 0xffffffff) {
190
+ resolved.localHeaderOffset = readNextUInt64('local header offset');
191
+ }
192
+ if (resolved.diskStart === 0xffff) {
193
+ if (valueOffset + 4 > zip64Extra.length) {
194
+ throw new Error('Invalid zip64 extra field: missing disk start');
195
+ }
196
+ resolved.diskStart = zip64Extra.readUInt32LE(valueOffset);
197
+ }
198
+ if (resolved.diskStart !== 0) {
199
+ throw new Error('Multi-disk zip archives are not supported');
200
+ }
201
+ return resolved;
202
+ }
203
+ export function readZipArchive(bytes, limits) {
204
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
205
+ const endOffset = findEndOfCentralDirectory(buffer);
206
+ if (endOffset < 0)
207
+ throw new Error('Invalid zip archive');
208
+ const centralDirectory = readCentralDirectory(buffer, endOffset);
209
+ const totalEntries = centralDirectory.entries;
210
+ if (totalEntries > limits.maxEntries) {
211
+ throw new ArchiveValidationError(`Archive contains too many files (${totalEntries}). Maximum is ${limits.maxEntries}.`);
212
+ }
213
+ ensureRange(buffer, centralDirectory.offset, centralDirectory.size, 'central directory');
214
+ if (centralDirectory.offset + centralDirectory.size > centralDirectory.trailerOffset) {
215
+ throw new Error('Invalid zip archive: central directory overlaps archive trailer');
216
+ }
217
+ const files = new Map();
218
+ let extractedBytes = 0;
219
+ let offset = centralDirectory.offset;
220
+ for (let index = 0; index < totalEntries; index++) {
221
+ ensureRange(buffer, offset, 46, 'central directory entry');
222
+ if (buffer.readUInt32LE(offset) !== ZIP_CENTRAL_DIRECTORY_HEADER) {
223
+ throw new Error('Invalid zip central directory entry');
224
+ }
225
+ const flags = buffer.readUInt16LE(offset + 8);
226
+ const method = buffer.readUInt16LE(offset + 10);
227
+ const expectedChecksum = buffer.readUInt32LE(offset + 16);
228
+ let compressedSize = buffer.readUInt32LE(offset + 20);
229
+ let uncompressedSize = buffer.readUInt32LE(offset + 24);
230
+ const fileNameLength = buffer.readUInt16LE(offset + 28);
231
+ const extraLength = buffer.readUInt16LE(offset + 30);
232
+ const commentLength = buffer.readUInt16LE(offset + 32);
233
+ let diskStart = buffer.readUInt16LE(offset + 34);
234
+ const externalAttributes = buffer.readUInt32LE(offset + 38);
235
+ let localHeaderOffset = buffer.readUInt32LE(offset + 42);
236
+ const variableSize = fileNameLength + extraLength + commentLength;
237
+ ensureRange(buffer, offset + 46, variableSize, 'central directory entry data');
238
+ const nameStart = offset + 46;
239
+ const extraOffset = nameStart + fileNameLength;
240
+ ({ compressedSize, diskStart, localHeaderOffset, uncompressedSize } = readZip64EntryValues(buffer, extraOffset, extraLength, {
241
+ compressedSize,
242
+ diskStart,
243
+ localHeaderOffset,
244
+ uncompressedSize,
245
+ }));
246
+ const centralFileName = buffer.subarray(nameStart, nameStart + fileNameLength);
247
+ const rawFileName = decodeFileName(centralFileName, Boolean(flags & 0x800), findExtraField(buffer, extraOffset, extraLength, 0x7075));
248
+ const fileName = normalizeArchivePath(rawFileName);
249
+ if (fileName === null) {
250
+ throw new ArchiveValidationError(`Archive contains unsafe path: ${rawFileName}`);
251
+ }
252
+ if (flags & 0x1) {
253
+ throw new ArchiveValidationError('Encrypted zip entries are not supported');
254
+ }
255
+ const fileType = (externalAttributes >>> 16) & 0o170000;
256
+ if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000) {
257
+ throw new ArchiveValidationError('Archive links are not supported');
258
+ }
259
+ const isDirectory = rawFileName.replace(/\\/g, '/').endsWith('/') || fileType === 0o040000;
260
+ offset += 46 + variableSize;
261
+ extractedBytes += uncompressedSize;
262
+ if (extractedBytes > limits.maxExtractedBytes) {
263
+ throw new ArchiveValidationError(`Archive extracts to more than ${limits.maxExtractedBytes} bytes.`);
264
+ }
265
+ if (isDirectory)
266
+ continue;
267
+ ensureRange(buffer, localHeaderOffset, 30, 'local file header');
268
+ if (buffer.readUInt32LE(localHeaderOffset) !== ZIP_LOCAL_FILE_HEADER) {
269
+ throw new Error('Invalid zip local file header');
270
+ }
271
+ const localFlags = buffer.readUInt16LE(localHeaderOffset + 6);
272
+ const localMethod = buffer.readUInt16LE(localHeaderOffset + 8);
273
+ const localFileNameLength = buffer.readUInt16LE(localHeaderOffset + 26);
274
+ const localExtraLength = buffer.readUInt16LE(localHeaderOffset + 28);
275
+ const localNameOffset = localHeaderOffset + 30;
276
+ ensureRange(buffer, localNameOffset, localFileNameLength + localExtraLength, 'local file header data');
277
+ const localFileName = buffer.subarray(localNameOffset, localNameOffset + localFileNameLength);
278
+ if (localFlags !== flags || localMethod !== method || !localFileName.equals(centralFileName)) {
279
+ throw new Error('Zip local header does not match central directory');
280
+ }
281
+ const dataOffset = localHeaderOffset + 30 + localFileNameLength + localExtraLength;
282
+ ensureRange(buffer, dataOffset, compressedSize, 'file data');
283
+ if (dataOffset + compressedSize > centralDirectory.offset) {
284
+ throw new Error('Invalid zip archive: file data overlaps central directory');
285
+ }
286
+ const compressed = buffer.subarray(dataOffset, dataOffset + compressedSize);
287
+ let contents;
288
+ if (method === 0) {
289
+ contents = compressed;
290
+ }
291
+ else if (method === 8) {
292
+ contents = inflateRawSync(compressed, {
293
+ maxOutputLength: uncompressedSize + 1,
294
+ });
295
+ }
296
+ else {
297
+ throw new Error(`Unsupported zip compression method: ${method}`);
298
+ }
299
+ if (contents.byteLength !== uncompressedSize) {
300
+ throw new Error('Zip entry size mismatch');
301
+ }
302
+ if (crc32(contents) !== expectedChecksum) {
303
+ throw new Error('Zip entry checksum mismatch');
304
+ }
305
+ files.set(fileName, new Uint8Array(contents));
306
+ }
307
+ if (offset !== centralDirectory.offset + centralDirectory.size) {
308
+ throw new Error('Invalid zip central directory size');
309
+ }
310
+ return files;
311
+ }