@aikdna/kdna-core 0.12.0 → 0.12.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025-2026 AIKDNA Contributors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ KDNA
2
+ Copyright 2026 KDNA contributors
3
+
4
+ This product includes software developed by the KDNA Team
5
+ (https://github.com/aikdna).
6
+
7
+ KDNA Documentation and examples are licensed under CC BY 4.0 unless
8
+ otherwise noted. Code, including validators and package metadata, is
9
+ licensed under Apache-2.0.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikdna/kdna-core",
3
- "version": "0.12.0",
3
+ "version": "0.12.1",
4
4
  "description": "KDNA core library — load, validate, lint, and render KDNA domain judgment assets. Supports KDNA Container format (payload.kdnab via CBOR).",
5
5
  "type": "commonjs",
6
6
  "main": "src/index.js",
@@ -21,12 +21,15 @@
21
21
  },
22
22
  "types": "src/types.d.ts",
23
23
  "scripts": {
24
- "test": "node --test test/*.test.js && node -e \"const m = require('./src/index.js'); console.log('kdna-core exports:', Object.keys(m).join(', '));\""
24
+ "test": "node ../../scripts/run-node-tests.js test/*.test.js && node -e \"const m = require('./src/index.js'); console.log('kdna-core exports:', Object.keys(m).join(', '));\"",
25
+ "prepublishOnly": "npm --prefix ../.. run ecosystem-gate"
25
26
  },
26
27
  "files": [
27
28
  "src/",
28
29
  "schema/",
29
- "README.md"
30
+ "README.md",
31
+ "LICENSE",
32
+ "NOTICE"
30
33
  ],
31
34
  "keywords": [
32
35
  "kdna",
@@ -54,7 +57,7 @@
54
57
  }
55
58
  },
56
59
  "dependencies": {
57
- "@noble/hashes": "^2.2.0",
60
+ "@noble/hashes": "^1.8.0",
58
61
  "cbor-x": "^1.6.4"
59
62
  }
60
63
  }
package/src/v1/index.js CHANGED
@@ -43,6 +43,29 @@ const MIMETYPE_V1 = 'application/vnd.kdna.asset';
43
43
  const MIMETYPE_V2 = 'application/vnd.aikdna.kdna+zip';
44
44
  const V1_REQUIRED_DIR_ENTRIES = ['mimetype', 'kdna.json', 'payload.kdnab'];
45
45
  const V1_OPTIONAL_DIR_ENTRIES = ['checksums.json', 'signatures', 'attachments'];
46
+ const V1_ALLOWED_TOP_LEVEL_ENTRIES = new Set([
47
+ ...V1_REQUIRED_DIR_ENTRIES,
48
+ ...V1_OPTIONAL_DIR_ENTRIES,
49
+ ]);
50
+ const V1_FORBIDDEN_LEGACY_TOP_LEVEL = new Set([
51
+ 'KDNA_Core.json',
52
+ 'KDNA_Patterns.json',
53
+ 'KDNA_Scenarios.json',
54
+ 'KDNA_Cases.json',
55
+ 'KDNA_Reasoning.json',
56
+ 'KDNA_Evolution.json',
57
+ ]);
58
+
59
+ const DEFAULT_CONTAINER_LIMITS = Object.freeze({
60
+ maxContainerBytes: 25 * 1024 * 1024,
61
+ maxEntries: 128,
62
+ maxEntryBytes: 5 * 1024 * 1024,
63
+ maxTotalUncompressedBytes: 12 * 1024 * 1024,
64
+ maxCompressionRatio: 100,
65
+ maxJsonDepth: 64,
66
+ maxJsonArrayLength: 10000,
67
+ maxJsonStringLength: 1024 * 1024,
68
+ });
46
69
 
47
70
  // Words that must never appear in v1 CLI output as positive claims.
48
71
  // Schema-valid, signature-valid, compatible — those are fine.
@@ -141,15 +164,15 @@ function detectContainerFormat(absPath) {
141
164
  fs.closeSync(fd);
142
165
  if (head[0] !== 0x50 || head[1] !== 0x4b) return null;
143
166
 
144
- // Read the first entry's name + content. We re-use listZipEntries.
145
- let entries;
167
+ // Read only the first central-directory entry. Dangerous later entries
168
+ // must not make detection fall through to a less strict legacy route;
169
+ // readV1Layout/validate will reject them with the secure container reader.
170
+ let first;
146
171
  try {
147
- entries = listZipEntries(absPath);
172
+ first = readFirstZipEntry(absPath);
148
173
  } catch {
149
174
  return null;
150
175
  }
151
- if (entries.length === 0) return null;
152
- const first = entries[0];
153
176
  if (first.name !== 'mimetype') return null;
154
177
  // The mimetype entry must be STORED (method 0).
155
178
  if (first.method !== 0) return null;
@@ -167,8 +190,13 @@ function detectContainerFormat(absPath) {
167
190
  * `data` is already decompressed. Throws on unsupported methods or
168
191
  * truncated input.
169
192
  */
170
- function listZipEntries(absPath) {
193
+ function listZipEntries(absPath, opts = {}) {
194
+ const secure = opts.secure !== false;
195
+ const limits = { ...DEFAULT_CONTAINER_LIMITS, ...(opts.limits || {}) };
171
196
  const buf = fs.readFileSync(absPath);
197
+ if (secure && buf.length > limits.maxContainerBytes) {
198
+ throw new Error(`container exceeds maximum size (${limits.maxContainerBytes} bytes)`);
199
+ }
172
200
 
173
201
  // Locate EOCD — search backwards within the 64KiB comment window.
174
202
  let eocdOff = -1;
@@ -183,8 +211,13 @@ function listZipEntries(absPath) {
183
211
 
184
212
  const totalEntries = buf.readUInt16LE(eocdOff + 10);
185
213
  const cdOffset = buf.readUInt32LE(eocdOff + 16);
214
+ if (secure && totalEntries > limits.maxEntries) {
215
+ throw new Error(`container has too many entries (${totalEntries} > ${limits.maxEntries})`);
216
+ }
186
217
 
187
218
  const entries = [];
219
+ const seenNames = new Set();
220
+ let totalUncompressed = 0;
188
221
  let p = cdOffset;
189
222
  for (let i = 0; i < totalEntries; i++) {
190
223
  if (buf.readUInt32LE(p) !== 0x02014b50) {
@@ -196,8 +229,30 @@ function listZipEntries(absPath) {
196
229
  const nameLen = buf.readUInt16LE(p + 28);
197
230
  const extraLen = buf.readUInt16LE(p + 30);
198
231
  const commentLen = buf.readUInt16LE(p + 32);
232
+ const externalAttributes = buf.readUInt32LE(p + 38);
199
233
  const localOff = buf.readUInt32LE(p + 42);
200
234
  const name = buf.slice(p + 46, p + 46 + nameLen).toString('utf8');
235
+ const normalizedName = secure ? normalizeContainerEntryName(name) : name;
236
+
237
+ if (secure) {
238
+ validateContainerEntryMetadata({
239
+ name,
240
+ normalizedName,
241
+ method,
242
+ compressedSize: compSize,
243
+ uncompressedSize: uncompSize,
244
+ externalAttributes,
245
+ seenNames,
246
+ limits,
247
+ });
248
+ totalUncompressed += uncompSize;
249
+ if (totalUncompressed > limits.maxTotalUncompressedBytes) {
250
+ throw new Error(
251
+ `container uncompressed content exceeds maximum (${limits.maxTotalUncompressedBytes} bytes)`,
252
+ );
253
+ }
254
+ seenNames.add(normalizedName);
255
+ }
201
256
 
202
257
  if (buf.readUInt32LE(localOff) !== 0x04034b50) {
203
258
  throw new Error(`bad local-file-header for entry ${name}`);
@@ -211,13 +266,17 @@ function listZipEntries(absPath) {
211
266
  if (method === 0) data = comp;
212
267
  else if (method === 8) data = zlib.inflateRawSync(comp);
213
268
  else throw new Error(`unsupported compression method ${method} for ${name}`);
269
+ if (secure && data.length !== uncompSize) {
270
+ throw new Error(`entry size mismatch for ${normalizedName}`);
271
+ }
214
272
 
215
273
  entries.push({
216
- name,
274
+ name: secure ? normalizedName : name,
217
275
  method,
218
276
  compressedSize: compSize,
219
277
  uncompressedSize: uncompSize,
220
278
  localOffset: localOff,
279
+ externalAttributes,
221
280
  data,
222
281
  });
223
282
  p += 46 + nameLen + extraLen + commentLen;
@@ -225,6 +284,106 @@ function listZipEntries(absPath) {
225
284
  return entries;
226
285
  }
227
286
 
287
+ function readFirstZipEntry(absPath) {
288
+ const buf = fs.readFileSync(absPath);
289
+ let eocdOff = -1;
290
+ const minStart = Math.max(0, buf.length - 65557);
291
+ for (let i = buf.length - 22; i >= minStart; i--) {
292
+ if (buf.readUInt32LE(i) === 0x06054b50) {
293
+ eocdOff = i;
294
+ break;
295
+ }
296
+ }
297
+ if (eocdOff < 0) throw new Error('not a ZIP/.kdna container (no EOCD)');
298
+ const totalEntries = buf.readUInt16LE(eocdOff + 10);
299
+ if (totalEntries === 0) throw new Error('empty ZIP/.kdna container');
300
+ const cdOffset = buf.readUInt32LE(eocdOff + 16);
301
+ if (buf.readUInt32LE(cdOffset) !== 0x02014b50) {
302
+ throw new Error(`bad central-directory entry at offset ${cdOffset}`);
303
+ }
304
+ const method = buf.readUInt16LE(cdOffset + 10);
305
+ const compSize = buf.readUInt32LE(cdOffset + 20);
306
+ const uncompSize = buf.readUInt32LE(cdOffset + 24);
307
+ const nameLen = buf.readUInt16LE(cdOffset + 28);
308
+ const extraLen = buf.readUInt16LE(cdOffset + 30);
309
+ const localOff = buf.readUInt32LE(cdOffset + 42);
310
+ const name = buf.slice(cdOffset + 46, cdOffset + 46 + nameLen).toString('utf8');
311
+ if (buf.readUInt32LE(localOff) !== 0x04034b50) {
312
+ throw new Error(`bad local-file-header for entry ${name}`);
313
+ }
314
+ const lNameLen = buf.readUInt16LE(localOff + 26);
315
+ const lExtraLen = buf.readUInt16LE(localOff + 28);
316
+ const compStart = localOff + 30 + lNameLen + lExtraLen;
317
+ const comp = buf.slice(compStart, compStart + compSize);
318
+ const data = method === 0 ? comp : method === 8 ? zlib.inflateRawSync(comp) : Buffer.alloc(0);
319
+ return { name, method, compressedSize: compSize, uncompressedSize: uncompSize, localOffset: localOff, extraLen, data };
320
+ }
321
+
322
+ function normalizeContainerEntryName(name) {
323
+ if (typeof name !== 'string' || name.length === 0) {
324
+ throw new Error('container entry has an empty name');
325
+ }
326
+ const normalized = name.normalize('NFC');
327
+ if (normalized !== name) {
328
+ throw new Error(`container entry uses a non-canonical Unicode name: ${name}`);
329
+ }
330
+ if (normalized.includes('\\')) {
331
+ throw new Error(`container entry uses backslash path separators: ${name}`);
332
+ }
333
+ if (normalized.startsWith('/') || /^[A-Za-z]:\//.test(normalized)) {
334
+ throw new Error(`container entry uses an absolute path: ${name}`);
335
+ }
336
+ const parts = normalized.split('/');
337
+ if (parts.some((part) => part === '' || part === '.' || part === '..')) {
338
+ throw new Error(`container entry uses an unsafe relative path: ${name}`);
339
+ }
340
+ return normalized;
341
+ }
342
+
343
+ function validateContainerEntryMetadata(entry) {
344
+ const {
345
+ name,
346
+ normalizedName,
347
+ method,
348
+ compressedSize,
349
+ uncompressedSize,
350
+ externalAttributes,
351
+ seenNames,
352
+ limits,
353
+ } = entry;
354
+
355
+ if (seenNames.has(normalizedName)) {
356
+ throw new Error(`container has duplicate entry: ${normalizedName}`);
357
+ }
358
+ const topLevel = normalizedName.split('/')[0];
359
+ if (!V1_ALLOWED_TOP_LEVEL_ENTRIES.has(topLevel)) {
360
+ if (V1_FORBIDDEN_LEGACY_TOP_LEVEL.has(topLevel)) {
361
+ throw new Error(`container includes forbidden top-level source entry: ${topLevel}`);
362
+ }
363
+ throw new Error(`container includes unsupported top-level entry: ${topLevel}`);
364
+ }
365
+ if ((topLevel === 'signatures' || topLevel === 'attachments') && normalizedName === topLevel) {
366
+ throw new Error(`container directory entry is not supported: ${name}`);
367
+ }
368
+ if (method !== 0 && method !== 8) {
369
+ throw new Error(`unsupported compression method ${method} for ${normalizedName}`);
370
+ }
371
+ if (uncompressedSize > limits.maxEntryBytes) {
372
+ throw new Error(`container entry ${normalizedName} exceeds maximum size (${limits.maxEntryBytes} bytes)`);
373
+ }
374
+ if (compressedSize > 0 && uncompressedSize / compressedSize > limits.maxCompressionRatio) {
375
+ throw new Error(`container entry ${normalizedName} exceeds maximum compression ratio`);
376
+ }
377
+
378
+ const mode = externalAttributes >>> 16;
379
+ const type = mode & 0o170000;
380
+ const symlink = type === 0o120000;
381
+ const deviceOrSpecial = type === 0o020000 || type === 0o060000 || type === 0o010000 || type === 0o140000;
382
+ if (symlink || deviceOrSpecial) {
383
+ throw new Error(`container entry ${normalizedName} has unsupported file attributes`);
384
+ }
385
+ }
386
+
228
387
  /**
229
388
  * CRC-32 (IEEE 802.3) used by ZIP.
230
389
  */
@@ -330,11 +489,11 @@ function readV1Layout(absPath) {
330
489
  let stat;
331
490
  try {
332
491
  stat = fs.statSync(absPath);
333
- } catch (e) {
492
+ } catch {
334
493
  throw new Error(`path not found: ${absPath}`);
335
494
  }
336
495
 
337
- let map = {};
496
+ const map = {};
338
497
  let entries = null; // ZIP entries if container
339
498
  let kind = null; // 'dir' | 'file'
340
499
 
@@ -345,6 +504,9 @@ function readV1Layout(absPath) {
345
504
  if (!fs.existsSync(full)) {
346
505
  throw new Error(`not a KDNA v1 source dir: missing ${f}`);
347
506
  }
507
+ if (fs.lstatSync(full).isSymbolicLink()) {
508
+ throw new Error(`not a KDNA v1 source dir: ${f} must not be a symlink`);
509
+ }
348
510
  }
349
511
  for (const f of [...V1_REQUIRED_DIR_ENTRIES, ...V1_OPTIONAL_DIR_ENTRIES]) {
350
512
  const full = path.join(absPath, f);
@@ -399,7 +561,7 @@ function readV1Layout(absPath) {
399
561
  // docs/core/manifest.md / schema/manifest.schema.json.)
400
562
  let manifest;
401
563
  try {
402
- manifest = JSON.parse(map['kdna.json'].toString('utf8'));
564
+ manifest = parseJsonEntry('kdna.json', map['kdna.json']);
403
565
  } catch (e) {
404
566
  throw new Error(`kdna.json is not valid JSON: ${e.message}`);
405
567
  }
@@ -410,6 +572,43 @@ function readV1Layout(absPath) {
410
572
  return { kind, map, manifest, entries };
411
573
  }
412
574
 
575
+ function parseJsonEntry(name, bytes, opts = {}) {
576
+ if (!Buffer.isBuffer(bytes)) {
577
+ throw new Error(`${name} is not a file entry`);
578
+ }
579
+ const limits = { ...DEFAULT_CONTAINER_LIMITS, ...(opts.limits || {}) };
580
+ if (bytes.length > limits.maxEntryBytes) {
581
+ throw new Error(`${name} exceeds maximum size (${limits.maxEntryBytes} bytes)`);
582
+ }
583
+ const parsed = JSON.parse(bytes.toString('utf8'));
584
+ assertJsonWithinLimits(parsed, name, limits);
585
+ return parsed;
586
+ }
587
+
588
+ function assertJsonWithinLimits(value, name, limits) {
589
+ function walk(node, depth) {
590
+ if (depth > limits.maxJsonDepth) {
591
+ throw new Error(`${name} exceeds maximum JSON depth (${limits.maxJsonDepth})`);
592
+ }
593
+ if (typeof node === 'string') {
594
+ if (node.length > limits.maxJsonStringLength) {
595
+ throw new Error(`${name} contains a string exceeding ${limits.maxJsonStringLength} characters`);
596
+ }
597
+ return;
598
+ }
599
+ if (node === null || typeof node !== 'object') return;
600
+ if (Array.isArray(node)) {
601
+ if (node.length > limits.maxJsonArrayLength) {
602
+ throw new Error(`${name} contains an array exceeding ${limits.maxJsonArrayLength} items`);
603
+ }
604
+ for (const item of node) walk(item, depth + 1);
605
+ return;
606
+ }
607
+ for (const child of Object.values(node)) walk(child, depth + 1);
608
+ }
609
+ walk(value, 0);
610
+ }
611
+
413
612
  // ─── inspect ───────────────────────────────────────────────────────────
414
613
 
415
614
  /**
@@ -485,7 +684,7 @@ function runValidate(v1) {
485
684
  // payload gate — payload.kdnab against payload-profile-v1.schema.json
486
685
  let payload;
487
686
  try {
488
- payload = JSON.parse(v1.map['payload.kdnab'].toString('utf8'));
687
+ payload = parseJsonEntry('payload.kdnab', v1.map['payload.kdnab']);
489
688
  } catch (e) {
490
689
  result.payload_valid = false;
491
690
  problems.push(`payload: not valid JSON (${e.message})`);
@@ -502,7 +701,7 @@ function runValidate(v1) {
502
701
  if (v1.map['checksums.json']) {
503
702
  let checks;
504
703
  try {
505
- checks = JSON.parse(v1.map['checksums.json'].toString('utf8'));
704
+ checks = parseJsonEntry('checksums.json', v1.map['checksums.json']);
506
705
  } catch (e) {
507
706
  result.checksums_valid = false;
508
707
  problems.push(`checksums: not valid JSON (${e.message})`);
@@ -737,7 +936,7 @@ function unpack(inputPath, outputDir) {
737
936
 
738
937
  // ─── Public router entry points ────────────────────────────────────────
739
938
 
740
- function inspect(inputPath, opts = {}) {
939
+ function inspect(inputPath, _opts = {}) {
741
940
  const v1 = readV1Layout(path.resolve(inputPath));
742
941
  const out = buildInspectOutput(v1);
743
942
  // Guard against accidental forbidden wording in any future field additions.
@@ -745,7 +944,7 @@ function inspect(inputPath, opts = {}) {
745
944
  return out;
746
945
  }
747
946
 
748
- function validate(inputPath, opts = {}) {
947
+ function validate(inputPath, _opts = {}) {
749
948
  const v1 = readV1Layout(path.resolve(inputPath));
750
949
  return runValidate(v1);
751
950
  }
@@ -951,6 +1150,13 @@ function planLoad(inputPath, opts = {}) {
951
1150
 
952
1151
  if (plan.entitlement_profile === 'password') {
953
1152
  if (opts.password || opts.hasPassword === true) {
1153
+ if (opts.hasPassword === true && !opts.password) {
1154
+ plan.issues.push(buildLoadPlanIssue(
1155
+ 'KDNA_AUTH_PASSWORD_DIAGNOSTIC',
1156
+ 'info',
1157
+ 'hasPassword is a diagnostic credential-presence signal only; it does not verify the password.',
1158
+ ));
1159
+ }
954
1160
  plan.state = 'ready';
955
1161
  plan.required_action = 'load';
956
1162
  plan.can_load_now = true;
@@ -1106,6 +1312,7 @@ module.exports = {
1106
1312
  inspect,
1107
1313
  validate,
1108
1314
  planLoad,
1315
+ loadAuthorized,
1109
1316
  buildChecksumsV1,
1110
1317
  pack,
1111
1318
  unpack,
@@ -1122,6 +1329,9 @@ function renderPromptItem(item) {
1122
1329
 
1123
1330
  if (item.type === 'axiom_applicability' && item.one_sentence) {
1124
1331
  const parts = [item.one_sentence];
1332
+ if (Array.isArray(item.applies_when) && item.applies_when.length) {
1333
+ parts.push(`applies when: ${item.applies_when.slice(0, 2).join('; ')}`);
1334
+ }
1125
1335
  if (Array.isArray(item.does_not_apply_when) && item.does_not_apply_when.length) {
1126
1336
  parts.push(`does not apply when: ${item.does_not_apply_when.slice(0, 2).join('; ')}`);
1127
1337
  }
@@ -1144,7 +1354,52 @@ function renderPromptItem(item) {
1144
1354
  return JSON.stringify(item);
1145
1355
  }
1146
1356
 
1357
+ function loadAuthorized(inputPath, opts = {}) {
1358
+ const plan = planLoad(inputPath, opts);
1359
+ if (plan.can_load_now !== true) {
1360
+ const issueCodes = Array.isArray(plan.issues)
1361
+ ? plan.issues.map((issue) => issue.code).filter(Boolean)
1362
+ : [];
1363
+ const err = new Error(
1364
+ `LoadPlan denied loading: state=${plan.state || 'invalid'} required_action=${plan.required_action || 'block'}`,
1365
+ );
1366
+ err.code = issueCodes[0] || 'KDNA_LOAD_NOT_AUTHORIZED';
1367
+ err.plan = plan;
1368
+ throw err;
1369
+ }
1370
+ return loadV1Unsafe(inputPath, opts);
1371
+ }
1372
+
1147
1373
  function loadV1(inputPath, opts = {}) {
1374
+ return loadAuthorized(inputPath, opts);
1375
+ }
1376
+
1377
+ function normalizeCompactAxiom(axiom) {
1378
+ if (typeof axiom === 'string') {
1379
+ return {
1380
+ type: 'axiom_applicability',
1381
+ statement: axiom,
1382
+ one_sentence: axiom,
1383
+ applies_when: [],
1384
+ does_not_apply_when: [],
1385
+ failure_risk: null,
1386
+ };
1387
+ }
1388
+ if (!axiom || typeof axiom !== 'object') return null;
1389
+ const statement = axiom.statement || axiom.one_sentence || axiom.full_statement || axiom.id || null;
1390
+ if (!statement) return null;
1391
+ return {
1392
+ type: 'axiom_applicability',
1393
+ id: axiom.id || null,
1394
+ statement,
1395
+ one_sentence: axiom.one_sentence || statement,
1396
+ applies_when: Array.isArray(axiom.applies_when) ? axiom.applies_when : [],
1397
+ does_not_apply_when: Array.isArray(axiom.does_not_apply_when) ? axiom.does_not_apply_when : [],
1398
+ failure_risk: axiom.failure_risk || null,
1399
+ };
1400
+ }
1401
+
1402
+ function loadV1Unsafe(inputPath, opts = {}) {
1148
1403
  const v1 = readV1Layout(path.resolve(inputPath));
1149
1404
  const m = v1.manifest;
1150
1405
  const profile = opts.profile || (m.load_contract ? m.load_contract.default_profile : 'compact') || 'compact';
@@ -1152,7 +1407,7 @@ function loadV1(inputPath, opts = {}) {
1152
1407
 
1153
1408
  let payload;
1154
1409
  try {
1155
- payload = JSON.parse(v1.map['payload.kdnab'].toString('utf8'));
1410
+ payload = parseJsonEntry('payload.kdnab', v1.map['payload.kdnab']);
1156
1411
  } catch (e) {
1157
1412
  throw new Error(`payload.kdnab is not valid JSON: ${e.message}`);
1158
1413
  }
@@ -1166,7 +1421,7 @@ function loadV1(inputPath, opts = {}) {
1166
1421
  // Digest verification — refuse to load if checksums.json is present and digests mismatch.
1167
1422
  if (v1.map['checksums.json']) {
1168
1423
  try {
1169
- const checks = JSON.parse(v1.map['checksums.json'].toString('utf8'));
1424
+ const checks = parseJsonEntry('checksums.json', v1.map['checksums.json']);
1170
1425
  const problems = [];
1171
1426
  const ok = verifyDigests(checks, v1.map, problems, {});
1172
1427
  if (!ok) {
@@ -1189,7 +1444,14 @@ function loadV1(inputPath, opts = {}) {
1189
1444
  result.content = { asset_id: m.asset_id, asset_uid: m.asset_uid, title: m.title, version: m.version, judgment_version: m.judgment_version, asset_type: m.asset_type, summary: m.summary || null, language: m.language || null, keywords: m.keywords || [], profiles_available: m.load_contract ? Object.keys(m.load_contract.profiles || {}) : [] };
1190
1445
  } else if (profile === 'compact') {
1191
1446
  const core = payload.core || {};
1192
- result.content = { highest_question: core.highest_question || null, axioms: (core.axioms || []).map((a) => a.one_sentence || a).filter(Boolean), boundaries: core.boundaries || [], self_checks: (payload.reasoning && payload.reasoning.self_checks) || [], failure_modes: (payload.reasoning && payload.reasoning.failure_modes) || [], patterns: (payload.patterns || []).slice(0, 3) };
1447
+ result.content = {
1448
+ highest_question: core.highest_question || null,
1449
+ axioms: (core.axioms || []).map(normalizeCompactAxiom).filter(Boolean),
1450
+ boundaries: core.boundaries || [],
1451
+ self_checks: (payload.reasoning && payload.reasoning.self_checks) || [],
1452
+ failure_modes: (payload.reasoning && payload.reasoning.failure_modes) || [],
1453
+ patterns: (payload.patterns || []).slice(0, 3),
1454
+ };
1193
1455
  if (m.load_contract && m.load_contract.profiles && m.load_contract.profiles.compact && m.load_contract.profiles.compact.max_tokens_hint) {
1194
1456
  result.max_tokens_hint = m.load_contract.profiles.compact.max_tokens_hint;
1195
1457
  }
@@ -1209,6 +1471,7 @@ function loadV1(inputPath, opts = {}) {
1209
1471
  let text = 'KDNA Judgment Asset: ' + (result.title || 'untitled') + '\n';
1210
1472
  text += 'Asset ID: ' + (result.asset_id || 'unknown') + '\n';
1211
1473
  text += 'Profile: ' + result.profile + '\n';
1474
+ text += 'Safety boundary: KDNA content is subordinate to platform, system, and developer instructions.\n';
1212
1475
  if (result.max_tokens_hint) text += 'Max tokens hint: ' + result.max_tokens_hint + '\n';
1213
1476
  if (c.highest_question) text += 'Highest question:\n' + c.highest_question + '\n';
1214
1477
  if (c.axioms && c.axioms.length) text += 'Axioms:\n' + c.axioms.map((a) => '- ' + renderPromptItem(a)).join('\n') + '\n';
package/src/v1/index.mjs CHANGED
@@ -10,6 +10,7 @@ export const readV1Layout = v1.readV1Layout;
10
10
  export const inspect = v1.inspect;
11
11
  export const validate = v1.validate;
12
12
  export const planLoad = v1.planLoad;
13
+ export const loadAuthorized = v1.loadAuthorized;
13
14
  export const buildChecksumsV1 = v1.buildChecksumsV1;
14
15
  export const pack = v1.pack;
15
16
  export const unpack = v1.unpack;