@knolo/cli 6.2.9 → 6.2.11

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.
@@ -56,12 +56,15 @@ export async function stageLockfileUpdate({ cwd = process.cwd(), registry, manif
56
56
  return { path: targetPath, tempPath, entry };
57
57
  }
58
58
 
59
- async function readLockfile(filePath) {
59
+ export async function readLockfile(filePath, { required = false } = {}) {
60
60
  let text;
61
61
  try {
62
62
  text = await readFile(filePath, 'utf8');
63
63
  } catch (error) {
64
- if (error?.code === 'ENOENT') return { packs: {} };
64
+ if (error?.code === 'ENOENT') {
65
+ if (required) throw new Error(`${LOCKFILE_NAME} is missing.`);
66
+ return { packs: {} };
67
+ }
65
68
  throw error;
66
69
  }
67
70
  let value;
@@ -0,0 +1,187 @@
1
+ import {
2
+ normalizeRegistryUrl,
3
+ registryApiUrl,
4
+ resolveRegistryUrl,
5
+ } from './config.mjs';
6
+ import { optionalHubHeaders } from './commands.mjs';
7
+ import { getJson } from './http.mjs';
8
+ import { LOCKFILE_NAME, lockfilePath, readLockfile } from './lockfile.mjs';
9
+ import { parsePackName } from './specs.mjs';
10
+
11
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
12
+ const VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
13
+
14
+ export async function runHubOutdated(
15
+ args,
16
+ {
17
+ env = process.env,
18
+ fetchImpl = globalThis.fetch,
19
+ cwd = process.cwd(),
20
+ homeDir,
21
+ print = console.log,
22
+ } = {}
23
+ ) {
24
+ const flags = parseOutdatedArgs(args);
25
+ const targetPath = lockfilePath(cwd);
26
+ const lockfile = await readLockfile(targetPath, { required: true });
27
+ const packs = lockfile.packs ?? {};
28
+ if (!packs || typeof packs !== 'object' || Array.isArray(packs)) {
29
+ throw new Error(`${LOCKFILE_NAME}.packs must be an object.`);
30
+ }
31
+
32
+ const registry = resolveOutdatedRegistry(
33
+ lockfile.registry,
34
+ flags.registry,
35
+ env
36
+ );
37
+ const headers = await optionalHubHeaders(registry, { env, homeDir });
38
+ const names = Object.keys(packs).sort();
39
+ const rows = [];
40
+ for (const name of names) {
41
+ const pinned = pinFromEntry(name, packs[name]);
42
+ const url = registryApiUrl(registry, [
43
+ 'packs',
44
+ pinned.publisher,
45
+ pinned.slug,
46
+ ]);
47
+ const body = await getJson(url, { fetchImpl, headers });
48
+ const latest = latestFromBody(name, body);
49
+ rows.push({
50
+ name,
51
+ pinned: { version: pinned.version, sha256: pinned.sha256 },
52
+ latest: { version: latest.version, sha256: latest.sha256 },
53
+ status: classifyPin(pinned, latest),
54
+ });
55
+ }
56
+
57
+ const report = { registry, packs: rows };
58
+ if (flags.json) print(JSON.stringify(report, null, 2));
59
+ else {
60
+ const visible = rows.filter((row) => row.status !== 'current');
61
+ if (visible.length > 0) print(renderTable(visible));
62
+ }
63
+ return {
64
+ exitCode: rows.every((row) => row.status === 'current') ? 0 : 1,
65
+ report,
66
+ };
67
+ }
68
+
69
+ function resolveOutdatedRegistry(lockRegistry, requested, env) {
70
+ const locked =
71
+ typeof lockRegistry === 'string'
72
+ ? normalizeRegistryUrl(lockRegistry)
73
+ : undefined;
74
+ const flag =
75
+ requested === undefined ? undefined : normalizeRegistryUrl(requested);
76
+ if (locked && flag && locked !== flag) {
77
+ throw new Error(`Lockfile registry is ${locked}; refusing to ask ${flag}.`);
78
+ }
79
+ if (locked) return locked;
80
+ return resolveRegistryUrl({ value: flag, env });
81
+ }
82
+
83
+ function pinFromEntry(name, entry) {
84
+ const parsed = parsePackName(name);
85
+ if (parsed.name !== name)
86
+ throw new Error(`Lockfile pack name is invalid: ${name}.`);
87
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
88
+ throw new Error(`Lockfile entry ${name} needs a version and sha256.`);
89
+ }
90
+ if (typeof entry.version !== 'string' || !SHA256_PATTERN.test(entry.sha256)) {
91
+ throw new Error(`Lockfile entry ${name} needs a version and sha256.`);
92
+ }
93
+ return {
94
+ publisher: parsed.publisher,
95
+ slug: parsed.slug,
96
+ version: entry.version,
97
+ sha256: entry.sha256,
98
+ };
99
+ }
100
+
101
+ function latestFromBody(name, body) {
102
+ const latest = body?.latest;
103
+ if (!latest || typeof latest !== 'object' || Array.isArray(latest)) {
104
+ throw new Error(`Registry returned an invalid latest version for ${name}.`);
105
+ }
106
+ if (
107
+ typeof latest.version !== 'string' ||
108
+ !SHA256_PATTERN.test(latest.sha256)
109
+ ) {
110
+ throw new Error(`Registry returned an invalid latest version for ${name}.`);
111
+ }
112
+ return {
113
+ version: latest.version,
114
+ sha256: latest.sha256,
115
+ yanked: latest.yanked === true,
116
+ };
117
+ }
118
+
119
+ export function classifyPin(pinned, latest) {
120
+ if (latest.yanked) return 'yanked';
121
+ if (pinned.version === latest.version && pinned.sha256 === latest.sha256)
122
+ return 'current';
123
+ if (pinned.version === latest.version) return 'pin-mismatch';
124
+ const pinVersion = parseDottedVersion(pinned.version);
125
+ const latestVersion = parseDottedVersion(latest.version);
126
+ if (!pinVersion || !latestVersion) return 'uncomparable';
127
+ const order = compareDottedVersion(pinVersion, latestVersion);
128
+ if (order < 0) return 'newer';
129
+ if (order > 0) return 'ahead';
130
+ return 'current';
131
+ }
132
+
133
+ function parseDottedVersion(value) {
134
+ const match = VERSION_PATTERN.exec(value);
135
+ if (!match) return null;
136
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
137
+ }
138
+
139
+ function compareDottedVersion(left, right) {
140
+ for (let index = 0; index < 3; index += 1) {
141
+ if (left[index] !== right[index])
142
+ return left[index] < right[index] ? -1 : 1;
143
+ }
144
+ return 0;
145
+ }
146
+
147
+ function renderTable(rows) {
148
+ const header = ['NAME', 'PINNED', 'LATEST', 'STATUS'];
149
+ const body = rows.map((row) => [
150
+ row.name,
151
+ row.pinned.version,
152
+ row.latest.version,
153
+ row.status,
154
+ ]);
155
+ const widths = header.map((label, index) =>
156
+ Math.max(label.length, ...body.map((cells) => cells[index].length))
157
+ );
158
+ const line = (cells) =>
159
+ cells
160
+ .map((cell, index) => cell.padEnd(widths[index]))
161
+ .join(' ')
162
+ .trimEnd();
163
+ return [line(header), ...body.map(line)].join('\n');
164
+ }
165
+
166
+ function parseOutdatedArgs(args) {
167
+ const flags = {};
168
+ for (let index = 0; index < args.length; index += 1) {
169
+ const arg = args[index];
170
+ if (arg === '--json') {
171
+ flags.json = true;
172
+ continue;
173
+ }
174
+ if (arg === '--registry') {
175
+ const value = args[index + 1];
176
+ if (value === undefined || value.startsWith('--'))
177
+ throw new Error(`Missing value for ${arg}`);
178
+ flags.registry = value;
179
+ index += 1;
180
+ continue;
181
+ }
182
+ if (arg.startsWith('--'))
183
+ throw new Error(`Unknown flag for outdated: ${arg}`);
184
+ throw new Error('Usage: knolo outdated [--json] [--registry <url>]');
185
+ }
186
+ return flags;
187
+ }
package/bin/research.mjs CHANGED
@@ -8,7 +8,8 @@
8
8
  import { createHash } from 'node:crypto';
9
9
  import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
10
10
  import path from 'node:path';
11
- import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { loadCoreModule } from './load-core.mjs';
12
13
  import {
13
14
  KAR_CLI_MAX_IMAGE_BYTES,
14
15
  KAR_CLI_MAX_TEXT_BYTES,
@@ -512,18 +513,12 @@ async function loadApis() {
512
513
  }
513
514
 
514
515
  async function importFirst(candidates, check) {
515
- for (const candidate of candidates) {
516
- try {
517
- const href = candidate.startsWith('@')
518
- ? candidate
519
- : pathToFileURL(candidate).href;
520
- const loaded = await import(href);
521
- if (check(loaded)) return loaded;
522
- } catch {
523
- // Try the next candidate.
524
- }
516
+ try {
517
+ return await loadCoreModule(candidates, check);
518
+ } catch (error) {
519
+ const detail = error instanceof Error ? error.message : String(error);
520
+ throw new Error(`Could not load @knolo/core. Build packages/core first. (${detail})`);
525
521
  }
526
- throw new Error('Could not load @knolo/core. Build packages/core first.');
527
522
  }
528
523
 
529
524
  function parseVerifyFlags(argv) {
package/bin/setup.mjs CHANGED
@@ -138,7 +138,8 @@ export async function findOnPath(name, pathEnv) {
138
138
  const candidate = path.join(dir, name);
139
139
  try {
140
140
  await access(candidate, constants.X_OK);
141
- return candidate;
141
+ // A directory passes X_OK, and spawning it fails with EACCES.
142
+ if ((await stat(candidate)).isFile()) return candidate;
142
143
  } catch {
143
144
  // Try the next directory.
144
145
  }
package/bin/skill.mjs CHANGED
@@ -21,7 +21,8 @@ import {
21
21
  } from 'node:fs/promises';
22
22
  import { homedir, tmpdir } from 'node:os';
23
23
  import path from 'node:path';
24
- import { fileURLToPath, pathToFileURL } from 'node:url';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { loadCoreModule } from './load-core.mjs';
25
26
  import { normalizeCategories } from './registry/categories.mjs';
26
27
  import {
27
28
  normalizeRegistryUrl,
@@ -904,32 +905,19 @@ function coreModuleReady(loaded) {
904
905
  );
905
906
  }
906
907
 
907
- async function loadCore() {
908
- const fileHref = pathToFileURL(
909
- path.resolve(__dirname, '../../core/dist/index.js')
910
- ).href;
911
- let lastError = null;
912
- // A failed ESM import stays cached for that exact URL. A later attempt uses
913
- // a new file URL so a transient open does not stick for the process.
914
- for (let attempt = 0; attempt < 3; attempt += 1) {
915
- const fileUrl =
916
- attempt === 0 ? fileHref : `${fileHref}?knolo-load=${attempt}`;
917
- for (const specifier of [fileUrl, '@knolo/core']) {
918
- try {
919
- const loaded = await import(specifier);
920
- if (coreModuleReady(loaded)) return loaded;
921
- lastError = new Error('module did not export the Knowledge Image API');
922
- } catch (error) {
923
- lastError = error;
924
- }
925
- }
926
- if (attempt < 2) {
927
- await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1)));
928
- }
929
- }
930
- throw new Error(
931
- `Could not load @knolo/core. Build packages/core first. (${coreLoadDetail(lastError)})`
932
- );
908
+ let corePromise;
909
+
910
+ function loadCore() {
911
+ corePromise ??= loadCoreModule(
912
+ [path.resolve(__dirname, '../../core/dist/index.js'), '@knolo/core'],
913
+ coreModuleReady
914
+ ).catch((error) => {
915
+ corePromise = undefined;
916
+ throw new Error(
917
+ `Could not load @knolo/core. Build packages/core first. (${coreLoadDetail(error)})`
918
+ );
919
+ });
920
+ return corePromise;
933
921
  }
934
922
 
935
923
  const SKILL_ARCHIVE_FORMAT = 'knolo-skill-archive-v1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knolo/cli",
3
- "version": "6.2.9",
3
+ "version": "6.2.11",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "knolo": "bin/knolo.mjs"
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "scripts": {
30
30
  "build": "node -e \"console.log('cli is executable via bin/knolo.mjs')\"",
31
- "test": "npm run build --prefix ../core && npm run build --prefix ../exchange && node --test test/cli.test.mjs test/ask.test.mjs test/kar.test.mjs test/kar-graph.test.mjs test/kar-produce.test.mjs test/hub.integration.test.mjs test/compose.test.mjs test/cortex.test.mjs test/flight.test.mjs test/skill.test.mjs test/setup.test.mjs test/exchange.test.mjs test/research.test.mjs test/kite.test.mjs",
31
+ "test": "npm run build --prefix ../core && npm run build --prefix ../exchange && node --test test/cli.test.mjs test/publish-preflight.test.mjs test/mount.test.mjs test/receipt.test.mjs test/outdated.test.mjs test/ask.test.mjs test/kar.test.mjs test/kar-graph.test.mjs test/kar-produce.test.mjs test/hub.integration.test.mjs test/compose.test.mjs test/cortex.test.mjs test/flight.test.mjs test/skill.test.mjs test/persona.test.mjs test/setup.test.mjs test/exchange.test.mjs test/research.test.mjs test/kite.test.mjs test/unknown-command.test.mjs",
32
32
  "test:hub": "node --test test/hub.integration.test.mjs"
33
33
  },
34
34
  "dependencies": {
@@ -494,7 +494,14 @@ fn read_u32(bytes: &[u8], cursor: &mut usize) -> Result<u32, KnoloError> {
494
494
  }
495
495
 
496
496
  fn read_u32_array(bytes: &[u8], cursor: &mut usize, len: usize) -> Result<Vec<u32>, KnoloError> {
497
- let mut out = Vec::with_capacity(len);
497
+ let remaining = bytes.len().saturating_sub(*cursor);
498
+ if len > remaining / 4 {
499
+ return Err(KnoloError::InvalidPack("unexpected end-of-buffer".into()));
500
+ }
501
+
502
+ let mut out = Vec::new();
503
+ out.try_reserve_exact(len)
504
+ .map_err(|_| KnoloError::InvalidPack("postings allocation failed".into()))?;
498
505
  for _ in 0..len {
499
506
  out.push(read_u32(bytes, cursor)?);
500
507
  }
@@ -2003,9 +2010,92 @@ fn map_strings(map: &[(String, CborValue)], key: &str) -> Result<Vec<String>, Kn
2003
2010
 
2004
2011
  fn decode_cbor_exact(bytes: &[u8]) -> Result<CborValue, KnoloError> { let mut cursor = 0; let value = decode_cbor(bytes, &mut cursor)?; if cursor != bytes.len() { return Err(KnoloError::InvalidPack("trailing V5 CBOR bytes".into())); } Ok(value) }
2005
2012
  fn decode_cbor(bytes: &[u8], cursor: &mut usize) -> Result<CborValue, KnoloError> {
2006
- let initial = *bytes.get(*cursor).ok_or_else(|| KnoloError::InvalidPack("truncated V5 CBOR".into()))?; *cursor += 1; let major = initial >> 5; let ai = initial & 31;
2013
+ let initial = *bytes.get(*cursor)
2014
+ .ok_or_else(|| KnoloError::InvalidPack("truncated V5 CBOR".into()))?;
2015
+ *cursor += 1;
2016
+
2017
+ let major = initial >> 5;
2018
+ let ai = initial & 31;
2007
2019
  let length = |cursor: &mut usize| read_cbor_length(bytes, cursor, ai);
2008
- match major { 0 => Ok(CborValue::UInt(length(cursor)?)), 1 => { let value = length(cursor)?; if value > i64::MAX as u64 { return Err(KnoloError::InvalidPack("V5 negative integer overflow".into())); } Ok(CborValue::NInt(-1 - value as i64)) }, 2 => { let len = usize::try_from(length(cursor)?).map_err(|_| KnoloError::InvalidPack("V5 bytes length overflow".into()))?; Ok(CborValue::Bytes(read_slice(bytes, cursor, len)?.to_vec())) }, 3 => { let len = usize::try_from(length(cursor)?).map_err(|_| KnoloError::InvalidPack("V5 text length overflow".into()))?; let value = std::str::from_utf8(read_slice(bytes, cursor, len)?).map_err(|_| KnoloError::InvalidPack("V5 text is not UTF-8".into()))?; Ok(CborValue::Text(value.to_string())) }, 4 => { let len = usize::try_from(length(cursor)?).map_err(|_| KnoloError::InvalidPack("V5 array length overflow".into()))?; let mut values = Vec::with_capacity(len); for _ in 0..len { values.push(decode_cbor(bytes, cursor)?); } Ok(CborValue::Array(values)) }, 5 => { let len = usize::try_from(length(cursor)?).map_err(|_| KnoloError::InvalidPack("V5 map length overflow".into()))?; let mut values = Vec::with_capacity(len); for _ in 0..len { let key = match decode_cbor(bytes, cursor)? { CborValue::Text(value) => value, _ => return Err(KnoloError::InvalidPack("V5 map key is not text".into())) }; if values.iter().any(|(name, _): &(String, CborValue)| name == &key) { return Err(KnoloError::InvalidPack("duplicate V5 map key".into())); } values.push((key, decode_cbor(bytes, cursor)?)); } Ok(CborValue::Map(values)) }, 7 if ai == 20 => Ok(CborValue::Bool(false)), 7 if ai == 21 => Ok(CborValue::Bool(true)), 7 if ai == 22 => Ok(CborValue::Null), _ => Err(KnoloError::InvalidPack("unsupported V5 CBOR type".into())) }
2020
+
2021
+ match major {
2022
+ 0 => Ok(CborValue::UInt(length(cursor)?)),
2023
+ 1 => {
2024
+ let value = length(cursor)?;
2025
+ if value > i64::MAX as u64 {
2026
+ return Err(KnoloError::InvalidPack("V5 negative integer overflow".into()));
2027
+ }
2028
+ Ok(CborValue::NInt(-1 - value as i64))
2029
+ }
2030
+ 2 => {
2031
+ let len = usize::try_from(length(cursor)?)
2032
+ .map_err(|_| KnoloError::InvalidPack("V5 bytes length overflow".into()))?;
2033
+ Ok(CborValue::Bytes(read_slice(bytes, cursor, len)?.to_vec()))
2034
+ }
2035
+ 3 => {
2036
+ let len = usize::try_from(length(cursor)?)
2037
+ .map_err(|_| KnoloError::InvalidPack("V5 text length overflow".into()))?;
2038
+ let value = std::str::from_utf8(read_slice(bytes, cursor, len)?)
2039
+ .map_err(|_| KnoloError::InvalidPack("V5 text is not UTF-8".into()))?;
2040
+ Ok(CborValue::Text(value.to_string()))
2041
+ }
2042
+ 4 => {
2043
+ let len = usize::try_from(length(cursor)?)
2044
+ .map_err(|_| KnoloError::InvalidPack("V5 array length overflow".into()))?;
2045
+
2046
+ let remaining = bytes.len().saturating_sub(*cursor);
2047
+ if len > remaining {
2048
+ return Err(KnoloError::InvalidPack(
2049
+ "V5 array count exceeds remaining input".into(),
2050
+ ));
2051
+ }
2052
+
2053
+ let mut values = Vec::new();
2054
+ for _ in 0..len {
2055
+ values.try_reserve(1).map_err(|_| {
2056
+ KnoloError::InvalidPack("V5 array allocation failed".into())
2057
+ })?;
2058
+ values.push(decode_cbor(bytes, cursor)?);
2059
+ }
2060
+ Ok(CborValue::Array(values))
2061
+ }
2062
+ 5 => {
2063
+ let len = usize::try_from(length(cursor)?)
2064
+ .map_err(|_| KnoloError::InvalidPack("V5 map length overflow".into()))?;
2065
+
2066
+ let remaining = bytes.len().saturating_sub(*cursor);
2067
+ if len > remaining / 2 {
2068
+ return Err(KnoloError::InvalidPack(
2069
+ "V5 map count exceeds remaining input".into(),
2070
+ ));
2071
+ }
2072
+
2073
+ let mut values: Vec<(String, CborValue)> = Vec::new();
2074
+ for _ in 0..len {
2075
+ let key = match decode_cbor(bytes, cursor)? {
2076
+ CborValue::Text(value) => value,
2077
+ _ => return Err(KnoloError::InvalidPack("V5 map key is not text".into())),
2078
+ };
2079
+
2080
+ if values.iter().any(|(name, _)| name == &key) {
2081
+ return Err(KnoloError::InvalidPack("duplicate V5 map key".into()));
2082
+ }
2083
+
2084
+ let value = decode_cbor(bytes, cursor)?;
2085
+
2086
+ values.try_reserve(1).map_err(|_| {
2087
+ KnoloError::InvalidPack("V5 map allocation failed".into())
2088
+ })?;
2089
+
2090
+ values.push((key, value));
2091
+ }
2092
+ Ok(CborValue::Map(values))
2093
+ }
2094
+ 7 if ai == 20 => Ok(CborValue::Bool(false)),
2095
+ 7 if ai == 21 => Ok(CborValue::Bool(true)),
2096
+ 7 if ai == 22 => Ok(CborValue::Null),
2097
+ _ => Err(KnoloError::InvalidPack("unsupported V5 CBOR type".into())),
2098
+ }
2009
2099
  }
2010
2100
  fn read_cbor_length(bytes: &[u8], cursor: &mut usize, ai: u8) -> Result<u64, KnoloError> { match ai { 0..=23 => Ok(ai as u64), 24 => Ok(read_slice(bytes, cursor, 1)?[0] as u64), 25 => Ok(u16::from_be_bytes(read_slice(bytes, cursor, 2)?.try_into().unwrap()) as u64), 26 => Ok(u32::from_be_bytes(read_slice(bytes, cursor, 4)?.try_into().unwrap()) as u64), 27 => Ok(u64::from_be_bytes(read_slice(bytes, cursor, 8)?.try_into().unwrap())), _ => Err(KnoloError::InvalidPack("indefinite V5 CBOR is not allowed".into())) } }
2011
2101
 
@@ -2036,3 +2126,80 @@ pub(crate) fn sha256(input: &[u8]) -> [u8; 32] {
2036
2126
  for chunk in data.chunks_exact(64) { let mut w = [0u32; 64]; for i in 0..16 { w[i] = u32::from_be_bytes(chunk[i*4..i*4+4].try_into().unwrap()); } for i in 16..64 { let s0 = w[i-15].rotate_right(7) ^ w[i-15].rotate_right(18) ^ (w[i-15] >> 3); let s1 = w[i-2].rotate_right(17) ^ w[i-2].rotate_right(19) ^ (w[i-2] >> 10); w[i] = w[i-16].wrapping_add(s0).wrapping_add(w[i-7]).wrapping_add(s1); } let mut a=h[0]; let mut b=h[1]; let mut c=h[2]; let mut d=h[3]; let mut e=h[4]; let mut f=h[5]; let mut g=h[6]; let mut hh=h[7]; for i in 0..64 { let s1=e.rotate_right(6)^e.rotate_right(11)^e.rotate_right(25); let ch=(e&f)^((!e)&g); let t1=hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); let s0=a.rotate_right(2)^a.rotate_right(13)^a.rotate_right(22); let maj=(a&b)^(a&c)^(b&c); let t2=s0.wrapping_add(maj); hh=g; g=f; f=e; e=d.wrapping_add(t1); d=c; c=b; b=a; a=t1.wrapping_add(t2); } h[0]=h[0].wrapping_add(a); h[1]=h[1].wrapping_add(b); h[2]=h[2].wrapping_add(c); h[3]=h[3].wrapping_add(d); h[4]=h[4].wrapping_add(e); h[5]=h[5].wrapping_add(f); h[6]=h[6].wrapping_add(g); h[7]=h[7].wrapping_add(hh); }
2037
2127
  let mut out = [0u8; 32]; for (i, value) in h.iter().enumerate() { out[i*4..i*4+4].copy_from_slice(&value.to_be_bytes()); } out
2038
2128
  }
2129
+
2130
+ #[cfg(test)]
2131
+ mod cbor_decoder_security_tests {
2132
+ use super::*;
2133
+
2134
+ fn image_with_commit_payload(commit_payload: &[u8]) -> Vec<u8> {
2135
+ let empty_payload = encode_cbor(&CborValue::Array(vec![]));
2136
+
2137
+ let object_segment = encode_v5_segment(1, &empty_payload);
2138
+ let event_segment = encode_v5_segment(2, &empty_payload);
2139
+ let commit_segment = encode_v5_segment(3, commit_payload);
2140
+
2141
+ let commit_offset =
2142
+ V5_DATA_START + object_segment.len() + event_segment.len();
2143
+
2144
+ let mut image = vec![0u8; commit_offset + commit_segment.len()];
2145
+
2146
+ image[0..8].copy_from_slice(KNOWLEDGE_IMAGE_V5_MAGIC);
2147
+ image[8..10].copy_from_slice(&5u16.to_le_bytes());
2148
+ image[12..14].copy_from_slice(&(V5_SUPERBLOCK_SIZE as u16).to_le_bytes());
2149
+
2150
+ let object_start = V5_DATA_START;
2151
+ let event_start = object_start + object_segment.len();
2152
+
2153
+ image[object_start..event_start].copy_from_slice(&object_segment);
2154
+ image[event_start..commit_offset].copy_from_slice(&event_segment);
2155
+ image[commit_offset..].copy_from_slice(&commit_segment);
2156
+
2157
+ let commit_digest = digest_domain("commit", commit_payload);
2158
+ let state = digest_domain("state", &digest_raw(&commit_digest));
2159
+
2160
+ let superblock = encode_v5_superblock(
2161
+ 1,
2162
+ commit_offset,
2163
+ commit_segment.len(),
2164
+ &commit_digest,
2165
+ &state,
2166
+ );
2167
+
2168
+ image[V5_HEADER_SIZE..V5_HEADER_SIZE + V5_SUPERBLOCK_SIZE]
2169
+ .copy_from_slice(&superblock);
2170
+
2171
+ image
2172
+ }
2173
+
2174
+ fn assert_rejected_without_panic(payload: &[u8], label: &str) {
2175
+ let image = image_with_commit_payload(payload);
2176
+
2177
+ let outcome = std::panic::catch_unwind(|| {
2178
+ mount_knowledge_image(&image)
2179
+ });
2180
+
2181
+ assert!(
2182
+ outcome.is_ok(),
2183
+ "{label}: mount_knowledge_image panicked"
2184
+ );
2185
+
2186
+ assert!(
2187
+ outcome.unwrap().is_err(),
2188
+ "{label}: malformed CBOR was unexpectedly accepted"
2189
+ );
2190
+ }
2191
+
2192
+ #[test]
2193
+ fn rejects_array_with_untrusted_maximum_length_without_panicking() {
2194
+ let mut payload = vec![0x9b];
2195
+ payload.extend_from_slice(&u64::MAX.to_be_bytes());
2196
+ assert_rejected_without_panic(&payload, "CBOR array");
2197
+ }
2198
+
2199
+ #[test]
2200
+ fn rejects_map_with_untrusted_maximum_length_without_panicking() {
2201
+ let mut payload = vec![0xbb];
2202
+ payload.extend_from_slice(&u64::MAX.to_be_bytes());
2203
+ assert_rejected_without_panic(&payload, "CBOR map");
2204
+ }
2205
+ }