@nextera.one/axis-server-sdk 0.6.0 → 0.7.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.
@@ -68,6 +68,20 @@ declare const PROOF_JWT = 2;
68
68
  declare const PROOF_MTLS = 3;
69
69
  declare const PROOF_LOOM = 4;
70
70
  declare const PROOF_WITNESS = 5;
71
+ declare enum ProofType {
72
+ NONE = 0,
73
+ CAPSULE = 1,
74
+ JWT = 2,
75
+ MTLS = 3,
76
+ LOOM = 4,
77
+ WITNESS = 5
78
+ }
79
+ declare enum BodyProfile {
80
+ RAW = 0,
81
+ TLV_MAP = 1,
82
+ OBJ = 2,
83
+ ARR = 3
84
+ }
71
85
  declare const ERR_INVALID_PACKET = "INVALID_PACKET";
72
86
  declare const ERR_BAD_SIGNATURE = "BAD_SIGNATURE";
73
87
  declare const ERR_REPLAY_DETECTED = "REPLAY_DETECTED";
@@ -103,4 +117,4 @@ declare function generateEd25519KeyPair(): {
103
117
  declare function sha256(data: Buffer | Uint8Array): Buffer;
104
118
  declare function computeReceiptHash(receiptBytes: Buffer | Uint8Array, prevHash?: Buffer | Uint8Array): Buffer;
105
119
 
106
- export { AXIS_MAGIC, AXIS_VERSION, type AxisBinaryFrame, type AxisFrame, AxisFrameZ, ERR_BAD_SIGNATURE, ERR_CONTRACT_VIOLATION, ERR_INVALID_PACKET, ERR_REPLAY_DETECTED, FLAG_BODY_TLV, FLAG_CHAIN_REQ, FLAG_HAS_WITNESS, MAX_BODY_LEN, MAX_FRAME_LEN, MAX_HDR_LEN, MAX_SIG_LEN, NCERT_ALG, NCERT_EXP, NCERT_ISSUER_KID, NCERT_KID, NCERT_NBF, NCERT_NODE_ID, NCERT_PAYLOAD, NCERT_PUB, NCERT_SCOPE, NCERT_SIG, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, PROOF_NONE, PROOF_WITNESS, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_BODY_ARR, TLV_BODY_OBJ, TLV_CAPSULE, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, TLV_INDEX, TLV_INTENT, TLV_KID, TLV_LOOM_PRESENCE_ID, TLV_LOOM_THREAD_HASH, TLV_LOOM_WRIT, TLV_NODE, TLV_NODE_CERT_HASH, TLV_NODE_KID, TLV_NONCE, TLV_OFFSET, TLV_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_SHA256_CHUNK, TLV_TRACE_ID, TLV_TS, TLV_UPLOAD_ID, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
120
+ export { AXIS_MAGIC, AXIS_VERSION, type AxisBinaryFrame, type AxisFrame, AxisFrameZ, BodyProfile, ERR_BAD_SIGNATURE, ERR_CONTRACT_VIOLATION, ERR_INVALID_PACKET, ERR_REPLAY_DETECTED, FLAG_BODY_TLV, FLAG_CHAIN_REQ, FLAG_HAS_WITNESS, MAX_BODY_LEN, MAX_FRAME_LEN, MAX_HDR_LEN, MAX_SIG_LEN, NCERT_ALG, NCERT_EXP, NCERT_ISSUER_KID, NCERT_KID, NCERT_NBF, NCERT_NODE_ID, NCERT_PAYLOAD, NCERT_PUB, NCERT_SCOPE, NCERT_SIG, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, PROOF_NONE, PROOF_WITNESS, ProofType, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_BODY_ARR, TLV_BODY_OBJ, TLV_CAPSULE, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, TLV_INDEX, TLV_INTENT, TLV_KID, TLV_LOOM_PRESENCE_ID, TLV_LOOM_THREAD_HASH, TLV_LOOM_WRIT, TLV_NODE, TLV_NODE_CERT_HASH, TLV_NODE_KID, TLV_NONCE, TLV_OFFSET, TLV_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_SHA256_CHUNK, TLV_TRACE_ID, TLV_TS, TLV_UPLOAD_ID, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
@@ -68,6 +68,20 @@ declare const PROOF_JWT = 2;
68
68
  declare const PROOF_MTLS = 3;
69
69
  declare const PROOF_LOOM = 4;
70
70
  declare const PROOF_WITNESS = 5;
71
+ declare enum ProofType {
72
+ NONE = 0,
73
+ CAPSULE = 1,
74
+ JWT = 2,
75
+ MTLS = 3,
76
+ LOOM = 4,
77
+ WITNESS = 5
78
+ }
79
+ declare enum BodyProfile {
80
+ RAW = 0,
81
+ TLV_MAP = 1,
82
+ OBJ = 2,
83
+ ARR = 3
84
+ }
71
85
  declare const ERR_INVALID_PACKET = "INVALID_PACKET";
72
86
  declare const ERR_BAD_SIGNATURE = "BAD_SIGNATURE";
73
87
  declare const ERR_REPLAY_DETECTED = "REPLAY_DETECTED";
@@ -103,4 +117,4 @@ declare function generateEd25519KeyPair(): {
103
117
  declare function sha256(data: Buffer | Uint8Array): Buffer;
104
118
  declare function computeReceiptHash(receiptBytes: Buffer | Uint8Array, prevHash?: Buffer | Uint8Array): Buffer;
105
119
 
106
- export { AXIS_MAGIC, AXIS_VERSION, type AxisBinaryFrame, type AxisFrame, AxisFrameZ, ERR_BAD_SIGNATURE, ERR_CONTRACT_VIOLATION, ERR_INVALID_PACKET, ERR_REPLAY_DETECTED, FLAG_BODY_TLV, FLAG_CHAIN_REQ, FLAG_HAS_WITNESS, MAX_BODY_LEN, MAX_FRAME_LEN, MAX_HDR_LEN, MAX_SIG_LEN, NCERT_ALG, NCERT_EXP, NCERT_ISSUER_KID, NCERT_KID, NCERT_NBF, NCERT_NODE_ID, NCERT_PAYLOAD, NCERT_PUB, NCERT_SCOPE, NCERT_SIG, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, PROOF_NONE, PROOF_WITNESS, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_BODY_ARR, TLV_BODY_OBJ, TLV_CAPSULE, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, TLV_INDEX, TLV_INTENT, TLV_KID, TLV_LOOM_PRESENCE_ID, TLV_LOOM_THREAD_HASH, TLV_LOOM_WRIT, TLV_NODE, TLV_NODE_CERT_HASH, TLV_NODE_KID, TLV_NONCE, TLV_OFFSET, TLV_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_SHA256_CHUNK, TLV_TRACE_ID, TLV_TS, TLV_UPLOAD_ID, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
120
+ export { AXIS_MAGIC, AXIS_VERSION, type AxisBinaryFrame, type AxisFrame, AxisFrameZ, BodyProfile, ERR_BAD_SIGNATURE, ERR_CONTRACT_VIOLATION, ERR_INVALID_PACKET, ERR_REPLAY_DETECTED, FLAG_BODY_TLV, FLAG_CHAIN_REQ, FLAG_HAS_WITNESS, MAX_BODY_LEN, MAX_FRAME_LEN, MAX_HDR_LEN, MAX_SIG_LEN, NCERT_ALG, NCERT_EXP, NCERT_ISSUER_KID, NCERT_KID, NCERT_NBF, NCERT_NODE_ID, NCERT_PAYLOAD, NCERT_PUB, NCERT_SCOPE, NCERT_SIG, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, PROOF_NONE, PROOF_WITNESS, ProofType, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_BODY_ARR, TLV_BODY_OBJ, TLV_CAPSULE, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, TLV_INDEX, TLV_INTENT, TLV_KID, TLV_LOOM_PRESENCE_ID, TLV_LOOM_THREAD_HASH, TLV_LOOM_WRIT, TLV_NODE, TLV_NODE_CERT_HASH, TLV_NODE_KID, TLV_NONCE, TLV_OFFSET, TLV_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_SHA256_CHUNK, TLV_TRACE_ID, TLV_TS, TLV_UPLOAD_ID, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
@@ -32,6 +32,7 @@ __export(core_exports, {
32
32
  AXIS_MAGIC: () => AXIS_MAGIC,
33
33
  AXIS_VERSION: () => AXIS_VERSION,
34
34
  AxisFrameZ: () => AxisFrameZ,
35
+ BodyProfile: () => BodyProfile,
35
36
  ERR_BAD_SIGNATURE: () => ERR_BAD_SIGNATURE,
36
37
  ERR_CONTRACT_VIOLATION: () => ERR_CONTRACT_VIOLATION,
37
38
  ERR_INVALID_PACKET: () => ERR_INVALID_PACKET,
@@ -59,6 +60,7 @@ __export(core_exports, {
59
60
  PROOF_MTLS: () => PROOF_MTLS,
60
61
  PROOF_NONE: () => PROOF_NONE,
61
62
  PROOF_WITNESS: () => PROOF_WITNESS,
63
+ ProofType: () => ProofType,
62
64
  TLV_ACTOR_ID: () => TLV_ACTOR_ID,
63
65
  TLV_AUD: () => TLV_AUD,
64
66
  TLV_BODY_ARR: () => TLV_BODY_ARR,
@@ -167,6 +169,22 @@ var PROOF_JWT = 2;
167
169
  var PROOF_MTLS = 3;
168
170
  var PROOF_LOOM = 4;
169
171
  var PROOF_WITNESS = 5;
172
+ var ProofType = /* @__PURE__ */ ((ProofType2) => {
173
+ ProofType2[ProofType2["NONE"] = 0] = "NONE";
174
+ ProofType2[ProofType2["CAPSULE"] = 1] = "CAPSULE";
175
+ ProofType2[ProofType2["JWT"] = 2] = "JWT";
176
+ ProofType2[ProofType2["MTLS"] = 3] = "MTLS";
177
+ ProofType2[ProofType2["LOOM"] = 4] = "LOOM";
178
+ ProofType2[ProofType2["WITNESS"] = 5] = "WITNESS";
179
+ return ProofType2;
180
+ })(ProofType || {});
181
+ var BodyProfile = /* @__PURE__ */ ((BodyProfile2) => {
182
+ BodyProfile2[BodyProfile2["RAW"] = 0] = "RAW";
183
+ BodyProfile2[BodyProfile2["TLV_MAP"] = 1] = "TLV_MAP";
184
+ BodyProfile2[BodyProfile2["OBJ"] = 2] = "OBJ";
185
+ BodyProfile2[BodyProfile2["ARR"] = 3] = "ARR";
186
+ return BodyProfile2;
187
+ })(BodyProfile || {});
170
188
  var ERR_INVALID_PACKET = "INVALID_PACKET";
171
189
  var ERR_BAD_SIGNATURE = "BAD_SIGNATURE";
172
190
  var ERR_REPLAY_DETECTED = "REPLAY_DETECTED";
@@ -524,6 +542,7 @@ function computeReceiptHash(receiptBytes, prevHash) {
524
542
  AXIS_MAGIC,
525
543
  AXIS_VERSION,
526
544
  AxisFrameZ,
545
+ BodyProfile,
527
546
  ERR_BAD_SIGNATURE,
528
547
  ERR_CONTRACT_VIOLATION,
529
548
  ERR_INVALID_PACKET,
@@ -551,6 +570,7 @@ function computeReceiptHash(receiptBytes, prevHash) {
551
570
  PROOF_MTLS,
552
571
  PROOF_NONE,
553
572
  PROOF_WITNESS,
573
+ ProofType,
554
574
  TLV_ACTOR_ID,
555
575
  TLV_AUD,
556
576
  TLV_BODY_ARR,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/index.ts","../../src/core/constants.ts","../../src/core/varint.ts","../../src/core/tlv.ts","../../src/core/axis-bin.ts","../../src/core/signature.ts"],"sourcesContent":["export * from './constants';\nexport * from './varint';\nexport * from './tlv';\nexport * from './axis-bin';\nexport * from './signature';\n","/**\n * AXIS Protocol Magic Bytes (e.g., 'AXIS1')\n */\nexport const AXIS_MAGIC = new Uint8Array([0x41, 0x58, 0x49, 0x53, 0x31]);\n\n/**\n * AXIS Protocol Version\n */\nexport const AXIS_VERSION = 0x01;\n\n/**\n * Maximum allowed size for the Header section in bytes.\n */\nexport const MAX_HDR_LEN = 2048;\n\n/**\n * Maximum allowed size for the Body section in bytes.\n */\nexport const MAX_BODY_LEN = 65536;\n\n/**\n * Maximum allowed size for the Signature section in bytes.\n */\nexport const MAX_SIG_LEN = 128;\n\n/**\n * Total maximum allowed size for a single AXIS frame.\n */\nexport const MAX_FRAME_LEN = 70 * 1024; // 70 KB\n\n/**\n * Frame Control Flags\n */\nexport const FLAG_BODY_TLV = 0x01;\nexport const FLAG_CHAIN_REQ = 0x02;\nexport const FLAG_HAS_WITNESS = 0x04;\n\n/**\n * TLV Tags for Header Section\n */\nexport const TLV_PID = 1;\nexport const TLV_TS = 2;\nexport const TLV_INTENT = 3;\nexport const TLV_ACTOR_ID = 4;\nexport const TLV_PROOF_TYPE = 5;\nexport const TLV_PROOF_REF = 6;\nexport const TLV_NONCE = 7;\nexport const TLV_AUD = 8;\nexport const TLV_REALM = TLV_AUD;\nexport const TLV_NODE = 9;\nexport const TLV_TRACE_ID = 10;\n/** Key ID for key rotation support */\nexport const TLV_KID = 11;\n\n/**\n * TLV Tags for Receipt Section\n */\nexport const TLV_RID = 15;\nexport const TLV_OK = 16;\nexport const TLV_EFFECT = 17;\nexport const TLV_ERROR_CODE = 18;\nexport const TLV_ERROR_MSG = 19;\nexport const TLV_PREV_HASH = 20;\nexport const TLV_RECEIPT_HASH = 21;\nexport const TLV_NODE_KID = 30;\nexport const TLV_NODE_CERT_HASH = 34;\n\n/**\n * TLV Tags for Loom Runtime (Lawful Execution)\n */\n/** Presence ID - liveness proof (UTF-8 string, e.g., \"pr_abc123\") */\nexport const TLV_LOOM_PRESENCE_ID = 91;\n/** Writ - executable intent (canonical JSON, UTF-8 encoded) */\nexport const TLV_LOOM_WRIT = 92;\n/** Thread Hash - causal continuity (32 bytes, raw binary) */\nexport const TLV_LOOM_THREAD_HASH = 93;\n\n/**\n * TLV Tags for Application Extensions (File Transfer / Capsule, range 70-99)\n */\n/** Upload session identifier (16 bytes, raw binary) */\nexport const TLV_UPLOAD_ID = 70;\n/** Chunk index within an upload session */\nexport const TLV_INDEX = 71;\n/** Byte offset of the chunk within the file */\nexport const TLV_OFFSET = 72;\n/** SHA-256 hash of a file chunk (32 bytes, raw binary) */\nexport const TLV_SHA256_CHUNK = 73;\n/** Capsule identifier stored as UTF-8 string */\nexport const TLV_CAPSULE = 90;\n\n/**\n * TLV Tags for Body Structure (used in body-profile validation)\n */\n/** Nested object TLV type */\nexport const TLV_BODY_OBJ = 254;\n/** Array TLV type */\nexport const TLV_BODY_ARR = 255;\n\n/**\n * TLV Tags for Node Certificate format (cert payload fields, not frame headers)\n *\n * These are used exclusively inside the node certificate binary format\n * and are NOT shared with the frame header TLV namespace.\n */\nexport const NCERT_NODE_ID = 1;\nexport const NCERT_KID = 2;\nexport const NCERT_ALG = 3;\nexport const NCERT_PUB = 4;\nexport const NCERT_NBF = 5;\nexport const NCERT_EXP = 6;\nexport const NCERT_SCOPE = 7;\nexport const NCERT_ISSUER_KID = 8;\n/** Cert envelope: signed payload bytes */\nexport const NCERT_PAYLOAD = 50;\n/** Cert envelope: root signature (64 bytes, Ed25519) */\nexport const NCERT_SIG = 51;\n\n/**\n * Supported Authentication Proof Types\n */\n/** No proof / unauthenticated request */\nexport const PROOF_NONE = 0;\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof (Lawful Execution) */\nexport const PROOF_LOOM = 4;\n/** Witnessed signature proof */\nexport const PROOF_WITNESS = 5;\n\n/**\n * Standard Protocol Error Codes\n */\nexport const ERR_INVALID_PACKET = 'INVALID_PACKET';\nexport const ERR_BAD_SIGNATURE = 'BAD_SIGNATURE';\nexport const ERR_REPLAY_DETECTED = 'REPLAY_DETECTED';\nexport const ERR_CONTRACT_VIOLATION = 'CONTRACT_VIOLATION';\n","/**\n * Encodes a number (up to 53 bits safe integer) into a Varint buffer.\n * Varints are a way of encoding integers using one or more bytes.\n * Smaller numbers take fewer bytes.\n *\n * @param {number} value - The unsigned integer to encode\n * @returns {Uint8Array} The encoded binary buffer\n * @throws {Error} If the value is negative\n */\nexport function encodeVarint(value: number): Uint8Array {\n if (value < 0) throw new Error('Varint must be unsigned');\n const bytes: number[] = [];\n while (true) {\n const byte = value & 0x7f;\n value >>>= 7;\n if (value === 0) {\n bytes.push(byte);\n break;\n }\n bytes.push(byte | 0x80);\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * Decodes a Varint from a buffer starting at a specific offset.\n *\n * @param {Uint8Array} buf - The buffer containing the encoded varint\n * @param {number} [offset=0] - The starting position in the buffer\n * @returns {Object} The decoded numeric value and the number of bytes consumed (length)\n * @throws {Error} If the buffer is too small or the varint exceeds 8 bytes (max 53-bit safe int)\n */\nexport function decodeVarint(\n buf: Uint8Array,\n offset = 0,\n): { value: number; length: number } {\n let value = 0;\n let shift = 0;\n let length = 0;\n\n while (true) {\n if (offset + length >= buf.length) {\n throw new Error('Varint decode out of bounds');\n }\n const byte = buf[offset + length];\n value += (byte & 0x7f) * Math.pow(2, shift);\n length++;\n shift += 7;\n if ((byte & 0x80) === 0) {\n break;\n }\n if (length > 8) throw new Error('Varint too large');\n }\n\n return { value, length };\n}\n\n/**\n * Calculates the number of bytes required to encode a value as a varint.\n * Useful for pre-allocating buffers.\n *\n * @param {number} value - The unsigned integer to check\n * @returns {number} The byte length\n * @throws {Error} If the value is negative\n */\nexport function varintLength(value: number): number {\n if (value < 0) throw new Error('Varint must be unsigned');\n let len = 0;\n do {\n value >>>= 7;\n len++;\n } while (value !== 0);\n return len;\n}\n","import { encodeVarint, decodeVarint, varintLength } from './varint';\n\n/**\n * Represents a basic Type-Length-Value structure.\n *\n * @interface TLV\n */\nexport interface TLV {\n /** The tag or type identifier */\n type: number;\n /** The raw binary value */\n value: Uint8Array;\n}\n\n/**\n * Encodes an array of TLVs into a canonical binary buffer.\n *\n * **Canonical Rules:**\n * 1. TLVs MUST be sorted by `type` in ascending order.\n * 2. Duplicate `type` entries are NOT allowed.\n * 3. Format: `[type_varint][len_varint][value_bytes]`\n *\n * @param {TLV[]} tlvs - The list of TLV entries to encode\n * @returns {Uint8Array} The sorted and encoded binary buffer\n * @throws {Error} If duplicate types are detected\n */\nexport function encodeTLVs(tlvs: TLV[]): Uint8Array {\n // 1. Sort by TYPE ascending\n // Create a copy to avoid mutating input\n const sorted = [...tlvs].sort((a, b) => a.type - b.type);\n\n // 2. Check for duplicates\n for (let i = 0; i < sorted.length - 1; i++) {\n if (sorted[i].type === sorted[i + 1].type) {\n throw new Error(`Duplicate TLV type: ${sorted[i].type}`);\n }\n }\n\n // 3. Calculate total size\n let totalSize = 0;\n for (const t of sorted) {\n totalSize += varintLength(t.type);\n totalSize += varintLength(t.value.length);\n totalSize += t.value.length;\n }\n\n // 4. Encode\n const buf = new Uint8Array(totalSize);\n let offset = 0;\n for (const t of sorted) {\n const typeBytes = encodeVarint(t.type);\n buf.set(typeBytes, offset);\n offset += typeBytes.length;\n\n const lenBytes = encodeVarint(t.value.length);\n buf.set(lenBytes, offset);\n offset += lenBytes.length;\n\n buf.set(t.value, offset);\n offset += t.value.length;\n }\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a flat list.\n * Preserves the original wire order and allows duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing TLV-encoded data\n * @param {number} [maxItems=1024] - Security limit for the number of parsed items\n * @returns {TLV[]} A list of decoded TLV entries\n * @throws {Error} If the buffer is truncated or malformed\n */\nexport function decodeTLVsList(buf: Uint8Array, maxItems = 1024): TLV[] {\n const list: TLV[] = [];\n let offset = 0;\n\n while (offset < buf.length) {\n if (list.length >= maxItems) throw new Error('TLV_LIMIT');\n\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n list.push({ type, value });\n offset += len;\n }\n\n return list;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a Map for efficient access.\n * Enforces strict canonical order (sorted tiles) and forbids duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing canonical TLV data\n * @returns {Map<number, Uint8Array>} Map of Tag -> Value\n * @throws {Error} If canonical order is violated or duplicates are found\n */\nexport function decodeTLVs(buf: Uint8Array): Map<number, Uint8Array> {\n const map = new Map<number, Uint8Array>();\n let offset = 0;\n let lastType = -1;\n\n while (offset < buf.length) {\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Check canonical order\n if (type <= lastType) {\n throw new Error(\n `TLV violation: Unsorted or duplicate type ${type} after ${lastType}`,\n );\n }\n lastType = type;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n map.set(type, value);\n offset += len;\n }\n\n return map;\n}\n\n/**\n * Recursive Object Decoder (safe nesting).\n * This follows the AXIS Option A: Nested TLV objects.\n */\nexport function decodeObject(\n bytes: Uint8Array,\n depth = 0,\n limits = { maxDepth: 8, maxItems: 128 },\n): Map<number, any> {\n if (depth > limits.maxDepth) {\n throw new Error('OBJECT_DEPTH_EXCEEDED');\n }\n\n const map = decodeTLVs(bytes);\n // In v1, we leave values as Uint8Array unless schema-driven.\n // The IntentSchemaValidator will handle deeper recursion.\n return map;\n}\n\n/**\n * Array Decoder (explicit container).\n * VALUE = repeated TLVs of one ITEM type.\n */\nexport function decodeArray(\n bytes: Uint8Array,\n itemType: number,\n maxItems = 256,\n): Uint8Array[] {\n const list = decodeTLVsList(bytes, maxItems);\n const items: Uint8Array[] = [];\n\n for (const tlv of list) {\n if (tlv.type !== itemType) {\n throw new Error(`INVALID_ARRAY_ITEM:${tlv.type}`);\n }\n items.push(tlv.value);\n }\n\n return items;\n}\n","import * as z from 'zod';\n\n/**\n * AxisFrame Schema\n *\n * Defines the logical structure of an AXIS frame using Zod for runtime validation.\n * This is used for internal processing after the low-level binary parsing is complete.\n */\nexport const AxisFrameZ = z.object({\n /** Flag bits for protocol control (e.g., encryption, compression) */\n flags: z.number().int().nonnegative(),\n /** A map of TLV headers where key=Tag and value=BinaryData */\n headers: z.map(\n z.number(),\n z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n ),\n /** The main payload of the frame */\n body: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n /** The cryptographic signature covering the frame (except the signature itself) */\n sig: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n});\n\n/**\n * Represents a structured AXIS frame.\n * @typedef {Object} AxisFrame\n */\nexport type AxisFrame = z.infer<typeof AxisFrameZ>;\nexport type AxisBinaryFrame = AxisFrame;\nimport {\n AXIS_MAGIC,\n AXIS_VERSION,\n MAX_BODY_LEN,\n MAX_FRAME_LEN,\n MAX_HDR_LEN,\n MAX_SIG_LEN,\n} from './constants';\nimport { decodeTLVs, encodeTLVs } from './tlv';\nimport { decodeVarint, encodeVarint } from './varint';\n\n/**\n * Encodes a structured AxisFrame into its binary wire representation.\n *\n * **Encoding Steps:**\n * 1. Encodes header TLV map into a single buffer.\n * 2. Validates lengths against MAX_* constants.\n * 3. Encodes lengths (HDR, BODY, SIG) as varints.\n * 4. Assembles the final byte array with magic, version, and flags.\n *\n * @param {AxisFrame} frame - The structured frame to encode\n * @returns {Uint8Array} The full binary frame\n * @throws {Error} If any section exceeds protocol limits\n */\nexport function encodeFrame(frame: AxisFrame): Uint8Array {\n const hdrBytes = encodeTLVs(\n Array.from(frame.headers.entries()).map(([t, v]) => ({\n type: t,\n value: v,\n })),\n );\n\n if (hdrBytes.length > MAX_HDR_LEN) throw new Error('Header too large');\n if (frame.body.length > MAX_BODY_LEN) throw new Error('Body too large');\n if (frame.sig.length > MAX_SIG_LEN) throw new Error('Signature too large');\n\n // Header Len, Body Len, Sig Len\n const hdrLenBytes = encodeVarint(hdrBytes.length);\n const bodyLenBytes = encodeVarint(frame.body.length);\n const sigLenBytes = encodeVarint(frame.sig.length);\n\n const totalLen =\n 5 + // Magic (AXIS1)\n 1 + // Version\n 1 + // Flags\n hdrLenBytes.length +\n bodyLenBytes.length +\n sigLenBytes.length +\n hdrBytes.length +\n frame.body.length +\n frame.sig.length;\n\n if (totalLen > MAX_FRAME_LEN) throw new Error('Total frame too large');\n\n const buf = new Uint8Array(totalLen);\n let offset = 0;\n\n // Magic (AXIS1 - 5 bytes)\n buf.set(AXIS_MAGIC, offset);\n offset += 5;\n\n // Version\n buf[offset++] = AXIS_VERSION;\n\n // Flags\n buf[offset++] = frame.flags;\n\n // Lengths\n buf.set(hdrLenBytes, offset);\n offset += hdrLenBytes.length;\n\n buf.set(bodyLenBytes, offset);\n offset += bodyLenBytes.length;\n\n buf.set(sigLenBytes, offset);\n offset += sigLenBytes.length;\n\n // Payloads\n buf.set(hdrBytes, offset);\n offset += hdrBytes.length;\n\n buf.set(frame.body, offset);\n offset += frame.body.length;\n\n buf.set(frame.sig, offset);\n offset += frame.sig.length;\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer into a structured AxisFrame with strict validation.\n *\n * @param {Uint8Array} buf - Raw bytes from the wire\n * @returns {AxisFrame} The parsed and validated frame\n * @throws {Error} If magic, version, or lengths are invalid\n */\nexport function decodeFrame(buf: Uint8Array): AxisFrame {\n let offset = 0;\n\n // 1. Magic (AXIS1 - 5 bytes)\n if (offset + 5 > buf.length) throw new Error('Packet too short');\n for (let i = 0; i < 5; i++) {\n if (buf[offset + i] !== AXIS_MAGIC[i]) throw new Error('Invalid Magic');\n }\n offset += 5;\n\n // 2. Version\n const ver = buf[offset++];\n if (ver !== AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);\n\n // 3. Flags\n const flags = buf[offset++];\n\n // 4. Lengths\n const { value: hdrLen, length: hlLen } = decodeVarint(buf, offset);\n offset += hlLen;\n if (hdrLen > MAX_HDR_LEN) throw new Error('Header limit exceeded');\n\n const { value: bodyLen, length: blLen } = decodeVarint(buf, offset);\n offset += blLen;\n if (bodyLen > MAX_BODY_LEN) throw new Error('Body limit exceeded');\n\n const { value: sigLen, length: slLen } = decodeVarint(buf, offset);\n offset += slLen;\n if (sigLen > MAX_SIG_LEN) throw new Error('Signature limit exceeded');\n\n // 5. Extract Bytes\n if (offset + hdrLen + bodyLen + sigLen > buf.length) {\n throw new Error('Frame truncated');\n }\n\n const hdrBytes = buf.slice(offset, offset + hdrLen);\n offset += hdrLen;\n\n const bodyBytes = buf.slice(offset, offset + bodyLen);\n offset += bodyLen;\n\n const sigBytes = buf.slice(offset, offset + sigLen);\n offset += sigLen;\n\n // 6. Decode Header TLVs\n const headers = decodeTLVs(hdrBytes);\n\n return {\n flags,\n headers,\n body: bodyBytes,\n sig: sigBytes,\n };\n}\n\n/**\n * Helper to get canonical bytes for signing.\n * SigTarget = All bytes up to SigLen, with SigLen=0, and no SigBytes.\n */\nexport function getSignTarget(frame: AxisFrame): Uint8Array {\n // Re-encode frame but with empty signature\n // Note: This is efficient enough for v1 (tens of KB).\n return encodeFrame({\n ...frame,\n sig: new Uint8Array(0),\n });\n}\n","import * as crypto from 'crypto';\n\nimport { AxisFrame, encodeFrame } from './axis-bin';\n\n/**\n * Signature utilities for AXIS binary frames\n * Supports Ed25519 signature generation and verification\n */\n\n/**\n * Computes the canonical payload for signing an AXIS frame.\n * The signature covers all bytes of the encoded frame EXCEPT the signature field itself.\n *\n * @param {AxisFrame} frame - The frame to prepare for signing\n * @returns {Buffer} The serialized canonical bytes for the signature algorithm\n */\nexport function computeSignaturePayload(frame: AxisFrame): Buffer {\n // Re-encode frame with empty signature\n const frameWithoutSig: AxisFrame = {\n ...frame,\n sig: new Uint8Array(0),\n };\n\n const encoded = encodeFrame(frameWithoutSig);\n return Buffer.from(encoded);\n}\n\n/**\n * Signs an AXIS frame using the Ed25519 algorithm.\n * Automatically handles both raw 32-byte seeds and pkcs8 DER-encoded private keys.\n *\n * @param {AxisFrame} frame - The frame to sign\n * @param {Buffer} privateKey - Ed25519 private key (32-byte raw OR pkcs8 DER)\n * @returns {Buffer} The 64-byte Ed25519 signature\n * @throws {Error} If key format is invalid or signing fail\n */\nexport function signFrame(frame: AxisFrame, privateKey: Buffer): Buffer {\n const payload = computeSignaturePayload(frame);\n\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte seed or DER-encoded\n if (privateKey.length === 32) {\n // Raw seed - wrap in pkcs8 DER format\n // pkcs8 prefix for Ed25519: 0x302e020100300506032b657004220420\n const pkcs8Prefix = Buffer.from([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,\n 0x04, 0x22, 0x04, 0x20,\n ]);\n const pkcs8Key = Buffer.concat([pkcs8Prefix, privateKey]);\n\n keyObject = crypto.createPrivateKey({\n key: pkcs8Key,\n format: 'der',\n type: 'pkcs8',\n });\n } else {\n // Assume already DER-encoded pkcs8\n keyObject = crypto.createPrivateKey({\n key: privateKey,\n format: 'der',\n type: 'pkcs8',\n });\n }\n\n const signature = crypto.sign(null, payload, keyObject);\n\n if (signature.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n return signature;\n}\n\n/**\n * Verifies an Ed25519 signature on an AXIS frame.\n * Automatically handles both raw 32-byte public keys and spki DER-encoded public keys.\n *\n * @param {AxisFrame} frame - The frame containing the signature to verify\n * @param {Buffer} publicKey - Ed25519 public key (32-byte raw OR spki DER)\n * @returns {boolean} True if the signature is cryptographically valid\n * @throws {Error} If signature length is invalid\n */\nexport function verifyFrameSignature(\n frame: AxisFrame,\n publicKey: Buffer,\n): boolean {\n if (frame.sig.length === 0) {\n return false; // No signature\n }\n\n if (frame.sig.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n const payload = computeSignaturePayload(frame);\n\n try {\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte or DER-encoded\n if (publicKey.length === 32) {\n // Raw key - wrap in spki DER format\n // spki prefix for Ed25519: 0x302a300506032b6570032100\n const spkiPrefix = Buffer.from([\n 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,\n ]);\n const spkiKey = Buffer.concat([spkiPrefix, publicKey]);\n\n keyObject = crypto.createPublicKey({\n key: spkiKey,\n format: 'der',\n type: 'spki',\n });\n } else {\n // Assume already DER-encoded spki\n keyObject = crypto.createPublicKey({\n key: publicKey,\n format: 'der',\n type: 'spki',\n });\n }\n\n const valid = crypto.verify(\n null,\n payload,\n keyObject,\n Buffer.from(frame.sig),\n );\n return valid;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Generates a new Ed25519 key pair for use with the AXIS protocol.\n * Returns keys in canonical DER format (pkcs8 for private, spki for public).\n *\n * @returns {Object} An object containing the privateKey and publicKey as Buffers\n */\nexport function generateEd25519KeyPair(): {\n privateKey: Buffer;\n publicKey: Buffer;\n} {\n const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');\n\n return {\n privateKey: privateKey.export({ type: 'pkcs8', format: 'der' }) as Buffer,\n publicKey: publicKey.export({ type: 'spki', format: 'der' }) as Buffer,\n };\n}\n\n/**\n * Computes a standard SHA-256 hash of the provided data.\n *\n * @param {Buffer | Uint8Array} data - The input data to hash\n * @returns {Buffer} The 32-byte SHA-256 digest\n */\nexport function sha256(data: Buffer | Uint8Array): Buffer {\n return crypto.createHash('sha256').update(data).digest();\n}\n\n/**\n * Computes a hash for an AXIS receipt, optionally chaining it to a previous hash.\n * This is used for generating an immutable transaction chain.\n *\n * @param {Buffer | Uint8Array} receiptBytes - The canonical binary representation of the receipt\n * @param {Buffer | Uint8Array} [prevHash] - The hash of the previous receipt in the chain\n * @returns {Buffer} The 32-byte SHA-256 hash of the receipt (and link)\n */\nexport function computeReceiptHash(\n receiptBytes: Buffer | Uint8Array,\n prevHash?: Buffer | Uint8Array,\n): Buffer {\n const hasher = crypto.createHash('sha256');\n hasher.update(receiptBytes);\n\n if (prevHash && prevHash.length > 0) {\n hasher.update(prevHash);\n }\n\n return hasher.digest();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAa,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,IAAM,EAAI,CAAC;AAKhE,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,gBAAgB,KAAK;AAK3B,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAKzB,IAAM,UAAU;AAChB,IAAM,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;AAAA,QACjC,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,MAAM;AAAA,MACR,CAAC;AAAA,IACH,OAAO;AAEL,kBAAmB,uBAAgB;AAAA,QACjC,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,MAAM;AAAA,MACR,CAAC;AAAA,IACH;AAEA,UAAM,QAAe;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO,KAAK,MAAM,GAAG;AAAA,IACvB;AACA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO;AAAA,EACT;AACF;AAQO,SAAS,yBAGd;AACA,QAAM,EAAE,YAAY,UAAU,IAAW,2BAAoB,SAAS;AAEtE,SAAO;AAAA,IACL,YAAY,WAAW,OAAO,EAAE,MAAM,SAAS,QAAQ,MAAM,CAAC;AAAA,IAC9D,WAAW,UAAU,OAAO,EAAE,MAAM,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC7D;AACF;AAQO,SAAS,OAAO,MAAmC;AACxD,SAAc,kBAAW,QAAQ,EAAE,OAAO,IAAI,EAAE,OAAO;AACzD;AAUO,SAAS,mBACd,cACA,UACQ;AACR,QAAM,SAAgB,kBAAW,QAAQ;AACzC,SAAO,OAAO,YAAY;AAE1B,MAAI,YAAY,SAAS,SAAS,GAAG;AACnC,WAAO,OAAO,QAAQ;AAAA,EACxB;AAEA,SAAO,OAAO,OAAO;AACvB;","names":["map"]}
1
+ {"version":3,"sources":["../../src/core/index.ts","../../src/core/constants.ts","../../src/core/varint.ts","../../src/core/tlv.ts","../../src/core/axis-bin.ts","../../src/core/signature.ts"],"sourcesContent":["export * from './constants';\nexport * from './varint';\nexport * from './tlv';\nexport * from './axis-bin';\nexport * from './signature';\n","/**\n * AXIS Protocol Magic Bytes (e.g., 'AXIS1')\n */\nexport const AXIS_MAGIC = new Uint8Array([0x41, 0x58, 0x49, 0x53, 0x31]);\n\n/**\n * AXIS Protocol Version\n */\nexport const AXIS_VERSION = 0x01;\n\n/**\n * Maximum allowed size for the Header section in bytes.\n */\nexport const MAX_HDR_LEN = 2048;\n\n/**\n * Maximum allowed size for the Body section in bytes.\n */\nexport const MAX_BODY_LEN = 65536;\n\n/**\n * Maximum allowed size for the Signature section in bytes.\n */\nexport const MAX_SIG_LEN = 128;\n\n/**\n * Total maximum allowed size for a single AXIS frame.\n */\nexport const MAX_FRAME_LEN = 70 * 1024; // 70 KB\n\n/**\n * Frame Control Flags\n */\nexport const FLAG_BODY_TLV = 0x01;\nexport const FLAG_CHAIN_REQ = 0x02;\nexport const FLAG_HAS_WITNESS = 0x04;\n\n/**\n * TLV Tags for Header Section\n */\nexport const TLV_PID = 1;\nexport const TLV_TS = 2;\nexport const TLV_INTENT = 3;\nexport const TLV_ACTOR_ID = 4;\nexport const TLV_PROOF_TYPE = 5;\nexport const TLV_PROOF_REF = 6;\nexport const TLV_NONCE = 7;\nexport const TLV_AUD = 8;\nexport const TLV_REALM = TLV_AUD;\nexport const TLV_NODE = 9;\nexport const TLV_TRACE_ID = 10;\n/** Key ID for key rotation support */\nexport const TLV_KID = 11;\n\n/**\n * TLV Tags for Receipt Section\n */\nexport const TLV_RID = 15;\nexport const TLV_OK = 16;\nexport const TLV_EFFECT = 17;\nexport const TLV_ERROR_CODE = 18;\nexport const TLV_ERROR_MSG = 19;\nexport const TLV_PREV_HASH = 20;\nexport const TLV_RECEIPT_HASH = 21;\nexport const TLV_NODE_KID = 30;\nexport const TLV_NODE_CERT_HASH = 34;\n\n/**\n * TLV Tags for Loom Runtime (Lawful Execution)\n */\n/** Presence ID - liveness proof (UTF-8 string, e.g., \"pr_abc123\") */\nexport const TLV_LOOM_PRESENCE_ID = 91;\n/** Writ - executable intent (canonical JSON, UTF-8 encoded) */\nexport const TLV_LOOM_WRIT = 92;\n/** Thread Hash - causal continuity (32 bytes, raw binary) */\nexport const TLV_LOOM_THREAD_HASH = 93;\n\n/**\n * TLV Tags for Application Extensions (File Transfer / Capsule, range 70-99)\n */\n/** Upload session identifier (16 bytes, raw binary) */\nexport const TLV_UPLOAD_ID = 70;\n/** Chunk index within an upload session */\nexport const TLV_INDEX = 71;\n/** Byte offset of the chunk within the file */\nexport const TLV_OFFSET = 72;\n/** SHA-256 hash of a file chunk (32 bytes, raw binary) */\nexport const TLV_SHA256_CHUNK = 73;\n/** Capsule identifier stored as UTF-8 string */\nexport const TLV_CAPSULE = 90;\n\n/**\n * TLV Tags for Body Structure (used in body-profile validation)\n */\n/** Nested object TLV type */\nexport const TLV_BODY_OBJ = 254;\n/** Array TLV type */\nexport const TLV_BODY_ARR = 255;\n\n/**\n * TLV Tags for Node Certificate format (cert payload fields, not frame headers)\n *\n * These are used exclusively inside the node certificate binary format\n * and are NOT shared with the frame header TLV namespace.\n */\nexport const NCERT_NODE_ID = 1;\nexport const NCERT_KID = 2;\nexport const NCERT_ALG = 3;\nexport const NCERT_PUB = 4;\nexport const NCERT_NBF = 5;\nexport const NCERT_EXP = 6;\nexport const NCERT_SCOPE = 7;\nexport const NCERT_ISSUER_KID = 8;\n/** Cert envelope: signed payload bytes */\nexport const NCERT_PAYLOAD = 50;\n/** Cert envelope: root signature (64 bytes, Ed25519) */\nexport const NCERT_SIG = 51;\n\n/**\n * Supported Authentication Proof Types\n */\n/** No proof / unauthenticated request */\nexport const PROOF_NONE = 0;\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof (Lawful Execution) */\nexport const PROOF_LOOM = 4;\n/** Witnessed signature proof */\nexport const PROOF_WITNESS = 5;\n\n/**\n * Canonical ProofType enum (mirrors PROOF_* constants).\n */\nexport enum ProofType {\n NONE = 0,\n CAPSULE = 1,\n JWT = 2,\n MTLS = 3,\n LOOM = 4,\n WITNESS = 5,\n}\n\n/**\n * Body Profile — declares the structural format of an AXIS frame body.\n */\nexport enum BodyProfile {\n RAW = 0,\n TLV_MAP = 1,\n OBJ = 2,\n ARR = 3,\n}\n\n/**\n * Standard Protocol Error Codes\n */\nexport const ERR_INVALID_PACKET = 'INVALID_PACKET';\nexport const ERR_BAD_SIGNATURE = 'BAD_SIGNATURE';\nexport const ERR_REPLAY_DETECTED = 'REPLAY_DETECTED';\nexport const ERR_CONTRACT_VIOLATION = 'CONTRACT_VIOLATION';\n","/**\n * Encodes a number (up to 53 bits safe integer) into a Varint buffer.\n * Varints are a way of encoding integers using one or more bytes.\n * Smaller numbers take fewer bytes.\n *\n * @param {number} value - The unsigned integer to encode\n * @returns {Uint8Array} The encoded binary buffer\n * @throws {Error} If the value is negative\n */\nexport function encodeVarint(value: number): Uint8Array {\n if (value < 0) throw new Error('Varint must be unsigned');\n const bytes: number[] = [];\n while (true) {\n const byte = value & 0x7f;\n value >>>= 7;\n if (value === 0) {\n bytes.push(byte);\n break;\n }\n bytes.push(byte | 0x80);\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * Decodes a Varint from a buffer starting at a specific offset.\n *\n * @param {Uint8Array} buf - The buffer containing the encoded varint\n * @param {number} [offset=0] - The starting position in the buffer\n * @returns {Object} The decoded numeric value and the number of bytes consumed (length)\n * @throws {Error} If the buffer is too small or the varint exceeds 8 bytes (max 53-bit safe int)\n */\nexport function decodeVarint(\n buf: Uint8Array,\n offset = 0,\n): { value: number; length: number } {\n let value = 0;\n let shift = 0;\n let length = 0;\n\n while (true) {\n if (offset + length >= buf.length) {\n throw new Error('Varint decode out of bounds');\n }\n const byte = buf[offset + length];\n value += (byte & 0x7f) * Math.pow(2, shift);\n length++;\n shift += 7;\n if ((byte & 0x80) === 0) {\n break;\n }\n if (length > 8) throw new Error('Varint too large');\n }\n\n return { value, length };\n}\n\n/**\n * Calculates the number of bytes required to encode a value as a varint.\n * Useful for pre-allocating buffers.\n *\n * @param {number} value - The unsigned integer to check\n * @returns {number} The byte length\n * @throws {Error} If the value is negative\n */\nexport function varintLength(value: number): number {\n if (value < 0) throw new Error('Varint must be unsigned');\n let len = 0;\n do {\n value >>>= 7;\n len++;\n } while (value !== 0);\n return len;\n}\n","import { encodeVarint, decodeVarint, varintLength } from './varint';\n\n/**\n * Represents a basic Type-Length-Value structure.\n *\n * @interface TLV\n */\nexport interface TLV {\n /** The tag or type identifier */\n type: number;\n /** The raw binary value */\n value: Uint8Array;\n}\n\n/**\n * Encodes an array of TLVs into a canonical binary buffer.\n *\n * **Canonical Rules:**\n * 1. TLVs MUST be sorted by `type` in ascending order.\n * 2. Duplicate `type` entries are NOT allowed.\n * 3. Format: `[type_varint][len_varint][value_bytes]`\n *\n * @param {TLV[]} tlvs - The list of TLV entries to encode\n * @returns {Uint8Array} The sorted and encoded binary buffer\n * @throws {Error} If duplicate types are detected\n */\nexport function encodeTLVs(tlvs: TLV[]): Uint8Array {\n // 1. Sort by TYPE ascending\n // Create a copy to avoid mutating input\n const sorted = [...tlvs].sort((a, b) => a.type - b.type);\n\n // 2. Check for duplicates\n for (let i = 0; i < sorted.length - 1; i++) {\n if (sorted[i].type === sorted[i + 1].type) {\n throw new Error(`Duplicate TLV type: ${sorted[i].type}`);\n }\n }\n\n // 3. Calculate total size\n let totalSize = 0;\n for (const t of sorted) {\n totalSize += varintLength(t.type);\n totalSize += varintLength(t.value.length);\n totalSize += t.value.length;\n }\n\n // 4. Encode\n const buf = new Uint8Array(totalSize);\n let offset = 0;\n for (const t of sorted) {\n const typeBytes = encodeVarint(t.type);\n buf.set(typeBytes, offset);\n offset += typeBytes.length;\n\n const lenBytes = encodeVarint(t.value.length);\n buf.set(lenBytes, offset);\n offset += lenBytes.length;\n\n buf.set(t.value, offset);\n offset += t.value.length;\n }\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a flat list.\n * Preserves the original wire order and allows duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing TLV-encoded data\n * @param {number} [maxItems=1024] - Security limit for the number of parsed items\n * @returns {TLV[]} A list of decoded TLV entries\n * @throws {Error} If the buffer is truncated or malformed\n */\nexport function decodeTLVsList(buf: Uint8Array, maxItems = 1024): TLV[] {\n const list: TLV[] = [];\n let offset = 0;\n\n while (offset < buf.length) {\n if (list.length >= maxItems) throw new Error('TLV_LIMIT');\n\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n list.push({ type, value });\n offset += len;\n }\n\n return list;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a Map for efficient access.\n * Enforces strict canonical order (sorted tiles) and forbids duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing canonical TLV data\n * @returns {Map<number, Uint8Array>} Map of Tag -> Value\n * @throws {Error} If canonical order is violated or duplicates are found\n */\nexport function decodeTLVs(buf: Uint8Array): Map<number, Uint8Array> {\n const map = new Map<number, Uint8Array>();\n let offset = 0;\n let lastType = -1;\n\n while (offset < buf.length) {\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Check canonical order\n if (type <= lastType) {\n throw new Error(\n `TLV violation: Unsorted or duplicate type ${type} after ${lastType}`,\n );\n }\n lastType = type;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n map.set(type, value);\n offset += len;\n }\n\n return map;\n}\n\n/**\n * Recursive Object Decoder (safe nesting).\n * This follows the AXIS Option A: Nested TLV objects.\n */\nexport function decodeObject(\n bytes: Uint8Array,\n depth = 0,\n limits = { maxDepth: 8, maxItems: 128 },\n): Map<number, any> {\n if (depth > limits.maxDepth) {\n throw new Error('OBJECT_DEPTH_EXCEEDED');\n }\n\n const map = decodeTLVs(bytes);\n // In v1, we leave values as Uint8Array unless schema-driven.\n // The IntentSchemaValidator will handle deeper recursion.\n return map;\n}\n\n/**\n * Array Decoder (explicit container).\n * VALUE = repeated TLVs of one ITEM type.\n */\nexport function decodeArray(\n bytes: Uint8Array,\n itemType: number,\n maxItems = 256,\n): Uint8Array[] {\n const list = decodeTLVsList(bytes, maxItems);\n const items: Uint8Array[] = [];\n\n for (const tlv of list) {\n if (tlv.type !== itemType) {\n throw new Error(`INVALID_ARRAY_ITEM:${tlv.type}`);\n }\n items.push(tlv.value);\n }\n\n return items;\n}\n","import * as z from 'zod';\n\n/**\n * AxisFrame Schema\n *\n * Defines the logical structure of an AXIS frame using Zod for runtime validation.\n * This is used for internal processing after the low-level binary parsing is complete.\n */\nexport const AxisFrameZ = z.object({\n /** Flag bits for protocol control (e.g., encryption, compression) */\n flags: z.number().int().nonnegative(),\n /** A map of TLV headers where key=Tag and value=BinaryData */\n headers: z.map(\n z.number(),\n z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n ),\n /** The main payload of the frame */\n body: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n /** The cryptographic signature covering the frame (except the signature itself) */\n sig: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n});\n\n/**\n * Represents a structured AXIS frame.\n * @typedef {Object} AxisFrame\n */\nexport type AxisFrame = z.infer<typeof AxisFrameZ>;\nexport type AxisBinaryFrame = AxisFrame;\nimport {\n AXIS_MAGIC,\n AXIS_VERSION,\n MAX_BODY_LEN,\n MAX_FRAME_LEN,\n MAX_HDR_LEN,\n MAX_SIG_LEN,\n} from './constants';\nimport { decodeTLVs, encodeTLVs } from './tlv';\nimport { decodeVarint, encodeVarint } from './varint';\n\n/**\n * Encodes a structured AxisFrame into its binary wire representation.\n *\n * **Encoding Steps:**\n * 1. Encodes header TLV map into a single buffer.\n * 2. Validates lengths against MAX_* constants.\n * 3. Encodes lengths (HDR, BODY, SIG) as varints.\n * 4. Assembles the final byte array with magic, version, and flags.\n *\n * @param {AxisFrame} frame - The structured frame to encode\n * @returns {Uint8Array} The full binary frame\n * @throws {Error} If any section exceeds protocol limits\n */\nexport function encodeFrame(frame: AxisFrame): Uint8Array {\n const hdrBytes = encodeTLVs(\n Array.from(frame.headers.entries()).map(([t, v]) => ({\n type: t,\n value: v,\n })),\n );\n\n if (hdrBytes.length > MAX_HDR_LEN) throw new Error('Header too large');\n if (frame.body.length > MAX_BODY_LEN) throw new Error('Body too large');\n if (frame.sig.length > MAX_SIG_LEN) throw new Error('Signature too large');\n\n // Header Len, Body Len, Sig Len\n const hdrLenBytes = encodeVarint(hdrBytes.length);\n const bodyLenBytes = encodeVarint(frame.body.length);\n const sigLenBytes = encodeVarint(frame.sig.length);\n\n const totalLen =\n 5 + // Magic (AXIS1)\n 1 + // Version\n 1 + // Flags\n hdrLenBytes.length +\n bodyLenBytes.length +\n sigLenBytes.length +\n hdrBytes.length +\n frame.body.length +\n frame.sig.length;\n\n if (totalLen > MAX_FRAME_LEN) throw new Error('Total frame too large');\n\n const buf = new Uint8Array(totalLen);\n let offset = 0;\n\n // Magic (AXIS1 - 5 bytes)\n buf.set(AXIS_MAGIC, offset);\n offset += 5;\n\n // Version\n buf[offset++] = AXIS_VERSION;\n\n // Flags\n buf[offset++] = frame.flags;\n\n // Lengths\n buf.set(hdrLenBytes, offset);\n offset += hdrLenBytes.length;\n\n buf.set(bodyLenBytes, offset);\n offset += bodyLenBytes.length;\n\n buf.set(sigLenBytes, offset);\n offset += sigLenBytes.length;\n\n // Payloads\n buf.set(hdrBytes, offset);\n offset += hdrBytes.length;\n\n buf.set(frame.body, offset);\n offset += frame.body.length;\n\n buf.set(frame.sig, offset);\n offset += frame.sig.length;\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer into a structured AxisFrame with strict validation.\n *\n * @param {Uint8Array} buf - Raw bytes from the wire\n * @returns {AxisFrame} The parsed and validated frame\n * @throws {Error} If magic, version, or lengths are invalid\n */\nexport function decodeFrame(buf: Uint8Array): AxisFrame {\n let offset = 0;\n\n // 1. Magic (AXIS1 - 5 bytes)\n if (offset + 5 > buf.length) throw new Error('Packet too short');\n for (let i = 0; i < 5; i++) {\n if (buf[offset + i] !== AXIS_MAGIC[i]) throw new Error('Invalid Magic');\n }\n offset += 5;\n\n // 2. Version\n const ver = buf[offset++];\n if (ver !== AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);\n\n // 3. Flags\n const flags = buf[offset++];\n\n // 4. Lengths\n const { value: hdrLen, length: hlLen } = decodeVarint(buf, offset);\n offset += hlLen;\n if (hdrLen > MAX_HDR_LEN) throw new Error('Header limit exceeded');\n\n const { value: bodyLen, length: blLen } = decodeVarint(buf, offset);\n offset += blLen;\n if (bodyLen > MAX_BODY_LEN) throw new Error('Body limit exceeded');\n\n const { value: sigLen, length: slLen } = decodeVarint(buf, offset);\n offset += slLen;\n if (sigLen > MAX_SIG_LEN) throw new Error('Signature limit exceeded');\n\n // 5. Extract Bytes\n if (offset + hdrLen + bodyLen + sigLen > buf.length) {\n throw new Error('Frame truncated');\n }\n\n const hdrBytes = buf.slice(offset, offset + hdrLen);\n offset += hdrLen;\n\n const bodyBytes = buf.slice(offset, offset + bodyLen);\n offset += bodyLen;\n\n const sigBytes = buf.slice(offset, offset + sigLen);\n offset += sigLen;\n\n // 6. Decode Header TLVs\n const headers = decodeTLVs(hdrBytes);\n\n return {\n flags,\n headers,\n body: bodyBytes,\n sig: sigBytes,\n };\n}\n\n/**\n * Helper to get canonical bytes for signing.\n * SigTarget = All bytes up to SigLen, with SigLen=0, and no SigBytes.\n */\nexport function getSignTarget(frame: AxisFrame): Uint8Array {\n // Re-encode frame but with empty signature\n // Note: This is efficient enough for v1 (tens of KB).\n return encodeFrame({\n ...frame,\n sig: new Uint8Array(0),\n });\n}\n","import * as crypto from 'crypto';\n\nimport { AxisFrame, encodeFrame } from './axis-bin';\n\n/**\n * Signature utilities for AXIS binary frames\n * Supports Ed25519 signature generation and verification\n */\n\n/**\n * Computes the canonical payload for signing an AXIS frame.\n * The signature covers all bytes of the encoded frame EXCEPT the signature field itself.\n *\n * @param {AxisFrame} frame - The frame to prepare for signing\n * @returns {Buffer} The serialized canonical bytes for the signature algorithm\n */\nexport function computeSignaturePayload(frame: AxisFrame): Buffer {\n // Re-encode frame with empty signature\n const frameWithoutSig: AxisFrame = {\n ...frame,\n sig: new Uint8Array(0),\n };\n\n const encoded = encodeFrame(frameWithoutSig);\n return Buffer.from(encoded);\n}\n\n/**\n * Signs an AXIS frame using the Ed25519 algorithm.\n * Automatically handles both raw 32-byte seeds and pkcs8 DER-encoded private keys.\n *\n * @param {AxisFrame} frame - The frame to sign\n * @param {Buffer} privateKey - Ed25519 private key (32-byte raw OR pkcs8 DER)\n * @returns {Buffer} The 64-byte Ed25519 signature\n * @throws {Error} If key format is invalid or signing fail\n */\nexport function signFrame(frame: AxisFrame, privateKey: Buffer): Buffer {\n const payload = computeSignaturePayload(frame);\n\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte seed or DER-encoded\n if (privateKey.length === 32) {\n // Raw seed - wrap in pkcs8 DER format\n // pkcs8 prefix for Ed25519: 0x302e020100300506032b657004220420\n const pkcs8Prefix = Buffer.from([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,\n 0x04, 0x22, 0x04, 0x20,\n ]);\n const pkcs8Key = Buffer.concat([pkcs8Prefix, privateKey]);\n\n keyObject = crypto.createPrivateKey({\n key: pkcs8Key,\n format: 'der',\n type: 'pkcs8',\n });\n } else {\n // Assume already DER-encoded pkcs8\n keyObject = crypto.createPrivateKey({\n key: privateKey,\n format: 'der',\n type: 'pkcs8',\n });\n }\n\n const signature = crypto.sign(null, payload, keyObject);\n\n if (signature.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n return signature;\n}\n\n/**\n * Verifies an Ed25519 signature on an AXIS frame.\n * Automatically handles both raw 32-byte public keys and spki DER-encoded public keys.\n *\n * @param {AxisFrame} frame - The frame containing the signature to verify\n * @param {Buffer} publicKey - Ed25519 public key (32-byte raw OR spki DER)\n * @returns {boolean} True if the signature is cryptographically valid\n * @throws {Error} If signature length is invalid\n */\nexport function verifyFrameSignature(\n frame: AxisFrame,\n publicKey: Buffer,\n): boolean {\n if (frame.sig.length === 0) {\n return false; // No signature\n }\n\n if (frame.sig.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n const payload = computeSignaturePayload(frame);\n\n try {\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte or DER-encoded\n if (publicKey.length === 32) {\n // Raw key - wrap in spki DER format\n // spki prefix for Ed25519: 0x302a300506032b6570032100\n const spkiPrefix = Buffer.from([\n 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,\n ]);\n const spkiKey = Buffer.concat([spkiPrefix, publicKey]);\n\n keyObject = crypto.createPublicKey({\n key: spkiKey,\n format: 'der',\n type: 'spki',\n });\n } else {\n // Assume already DER-encoded spki\n keyObject = crypto.createPublicKey({\n key: publicKey,\n format: 'der',\n type: 'spki',\n });\n }\n\n const valid = crypto.verify(\n null,\n payload,\n keyObject,\n Buffer.from(frame.sig),\n );\n return valid;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Generates a new Ed25519 key pair for use with the AXIS protocol.\n * Returns keys in canonical DER format (pkcs8 for private, spki for public).\n *\n * @returns {Object} An object containing the privateKey and publicKey as Buffers\n */\nexport function generateEd25519KeyPair(): {\n privateKey: Buffer;\n publicKey: Buffer;\n} {\n const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');\n\n return {\n privateKey: privateKey.export({ type: 'pkcs8', format: 'der' }) as Buffer,\n publicKey: publicKey.export({ type: 'spki', format: 'der' }) as Buffer,\n };\n}\n\n/**\n * Computes a standard SHA-256 hash of the provided data.\n *\n * @param {Buffer | Uint8Array} data - The input data to hash\n * @returns {Buffer} The 32-byte SHA-256 digest\n */\nexport function sha256(data: Buffer | Uint8Array): Buffer {\n return crypto.createHash('sha256').update(data).digest();\n}\n\n/**\n * Computes a hash for an AXIS receipt, optionally chaining it to a previous hash.\n * This is used for generating an immutable transaction chain.\n *\n * @param {Buffer | Uint8Array} receiptBytes - The canonical binary representation of the receipt\n * @param {Buffer | Uint8Array} [prevHash] - The hash of the previous receipt in the chain\n * @returns {Buffer} The 32-byte SHA-256 hash of the receipt (and link)\n */\nexport function computeReceiptHash(\n receiptBytes: Buffer | Uint8Array,\n prevHash?: Buffer | Uint8Array,\n): Buffer {\n const hasher = crypto.createHash('sha256');\n hasher.update(receiptBytes);\n\n if (prevHash && prevHash.length > 0) {\n hasher.update(prevHash);\n }\n\n return hasher.digest();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAa,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,IAAM,EAAI,CAAC;AAKhE,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,gBAAgB,KAAK;AAK3B,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAKzB,IAAM,UAAU;AAChB,IAAM,SAAS;AACf,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O,QAAQ;AAAA,EACxB;AAEA,SAAO,OAAO,OAAO;AACvB;","names":["ProofType","BodyProfile","map"]}
@@ -55,6 +55,22 @@ var PROOF_JWT = 2;
55
55
  var PROOF_MTLS = 3;
56
56
  var PROOF_LOOM = 4;
57
57
  var PROOF_WITNESS = 5;
58
+ var ProofType = /* @__PURE__ */ ((ProofType2) => {
59
+ ProofType2[ProofType2["NONE"] = 0] = "NONE";
60
+ ProofType2[ProofType2["CAPSULE"] = 1] = "CAPSULE";
61
+ ProofType2[ProofType2["JWT"] = 2] = "JWT";
62
+ ProofType2[ProofType2["MTLS"] = 3] = "MTLS";
63
+ ProofType2[ProofType2["LOOM"] = 4] = "LOOM";
64
+ ProofType2[ProofType2["WITNESS"] = 5] = "WITNESS";
65
+ return ProofType2;
66
+ })(ProofType || {});
67
+ var BodyProfile = /* @__PURE__ */ ((BodyProfile2) => {
68
+ BodyProfile2[BodyProfile2["RAW"] = 0] = "RAW";
69
+ BodyProfile2[BodyProfile2["TLV_MAP"] = 1] = "TLV_MAP";
70
+ BodyProfile2[BodyProfile2["OBJ"] = 2] = "OBJ";
71
+ BodyProfile2[BodyProfile2["ARR"] = 3] = "ARR";
72
+ return BodyProfile2;
73
+ })(BodyProfile || {});
58
74
  var ERR_INVALID_PACKET = "INVALID_PACKET";
59
75
  var ERR_BAD_SIGNATURE = "BAD_SIGNATURE";
60
76
  var ERR_REPLAY_DETECTED = "REPLAY_DETECTED";
@@ -411,6 +427,7 @@ export {
411
427
  AXIS_MAGIC,
412
428
  AXIS_VERSION,
413
429
  AxisFrameZ,
430
+ BodyProfile,
414
431
  ERR_BAD_SIGNATURE,
415
432
  ERR_CONTRACT_VIOLATION,
416
433
  ERR_INVALID_PACKET,
@@ -438,6 +455,7 @@ export {
438
455
  PROOF_MTLS,
439
456
  PROOF_NONE,
440
457
  PROOF_WITNESS,
458
+ ProofType,
441
459
  TLV_ACTOR_ID,
442
460
  TLV_AUD,
443
461
  TLV_BODY_ARR,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/constants.ts","../../src/core/varint.ts","../../src/core/tlv.ts","../../src/core/axis-bin.ts","../../src/core/signature.ts"],"sourcesContent":["/**\n * AXIS Protocol Magic Bytes (e.g., 'AXIS1')\n */\nexport const AXIS_MAGIC = new Uint8Array([0x41, 0x58, 0x49, 0x53, 0x31]);\n\n/**\n * AXIS Protocol Version\n */\nexport const AXIS_VERSION = 0x01;\n\n/**\n * Maximum allowed size for the Header section in bytes.\n */\nexport const MAX_HDR_LEN = 2048;\n\n/**\n * Maximum allowed size for the Body section in bytes.\n */\nexport const MAX_BODY_LEN = 65536;\n\n/**\n * Maximum allowed size for the Signature section in bytes.\n */\nexport const MAX_SIG_LEN = 128;\n\n/**\n * Total maximum allowed size for a single AXIS frame.\n */\nexport const MAX_FRAME_LEN = 70 * 1024; // 70 KB\n\n/**\n * Frame Control Flags\n */\nexport const FLAG_BODY_TLV = 0x01;\nexport const FLAG_CHAIN_REQ = 0x02;\nexport const FLAG_HAS_WITNESS = 0x04;\n\n/**\n * TLV Tags for Header Section\n */\nexport const TLV_PID = 1;\nexport const TLV_TS = 2;\nexport const TLV_INTENT = 3;\nexport const TLV_ACTOR_ID = 4;\nexport const TLV_PROOF_TYPE = 5;\nexport const TLV_PROOF_REF = 6;\nexport const TLV_NONCE = 7;\nexport const TLV_AUD = 8;\nexport const TLV_REALM = TLV_AUD;\nexport const TLV_NODE = 9;\nexport const TLV_TRACE_ID = 10;\n/** Key ID for key rotation support */\nexport const TLV_KID = 11;\n\n/**\n * TLV Tags for Receipt Section\n */\nexport const TLV_RID = 15;\nexport const TLV_OK = 16;\nexport const TLV_EFFECT = 17;\nexport const TLV_ERROR_CODE = 18;\nexport const TLV_ERROR_MSG = 19;\nexport const TLV_PREV_HASH = 20;\nexport const TLV_RECEIPT_HASH = 21;\nexport const TLV_NODE_KID = 30;\nexport const TLV_NODE_CERT_HASH = 34;\n\n/**\n * TLV Tags for Loom Runtime (Lawful Execution)\n */\n/** Presence ID - liveness proof (UTF-8 string, e.g., \"pr_abc123\") */\nexport const TLV_LOOM_PRESENCE_ID = 91;\n/** Writ - executable intent (canonical JSON, UTF-8 encoded) */\nexport const TLV_LOOM_WRIT = 92;\n/** Thread Hash - causal continuity (32 bytes, raw binary) */\nexport const TLV_LOOM_THREAD_HASH = 93;\n\n/**\n * TLV Tags for Application Extensions (File Transfer / Capsule, range 70-99)\n */\n/** Upload session identifier (16 bytes, raw binary) */\nexport const TLV_UPLOAD_ID = 70;\n/** Chunk index within an upload session */\nexport const TLV_INDEX = 71;\n/** Byte offset of the chunk within the file */\nexport const TLV_OFFSET = 72;\n/** SHA-256 hash of a file chunk (32 bytes, raw binary) */\nexport const TLV_SHA256_CHUNK = 73;\n/** Capsule identifier stored as UTF-8 string */\nexport const TLV_CAPSULE = 90;\n\n/**\n * TLV Tags for Body Structure (used in body-profile validation)\n */\n/** Nested object TLV type */\nexport const TLV_BODY_OBJ = 254;\n/** Array TLV type */\nexport const TLV_BODY_ARR = 255;\n\n/**\n * TLV Tags for Node Certificate format (cert payload fields, not frame headers)\n *\n * These are used exclusively inside the node certificate binary format\n * and are NOT shared with the frame header TLV namespace.\n */\nexport const NCERT_NODE_ID = 1;\nexport const NCERT_KID = 2;\nexport const NCERT_ALG = 3;\nexport const NCERT_PUB = 4;\nexport const NCERT_NBF = 5;\nexport const NCERT_EXP = 6;\nexport const NCERT_SCOPE = 7;\nexport const NCERT_ISSUER_KID = 8;\n/** Cert envelope: signed payload bytes */\nexport const NCERT_PAYLOAD = 50;\n/** Cert envelope: root signature (64 bytes, Ed25519) */\nexport const NCERT_SIG = 51;\n\n/**\n * Supported Authentication Proof Types\n */\n/** No proof / unauthenticated request */\nexport const PROOF_NONE = 0;\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof (Lawful Execution) */\nexport const PROOF_LOOM = 4;\n/** Witnessed signature proof */\nexport const PROOF_WITNESS = 5;\n\n/**\n * Standard Protocol Error Codes\n */\nexport const ERR_INVALID_PACKET = 'INVALID_PACKET';\nexport const ERR_BAD_SIGNATURE = 'BAD_SIGNATURE';\nexport const ERR_REPLAY_DETECTED = 'REPLAY_DETECTED';\nexport const ERR_CONTRACT_VIOLATION = 'CONTRACT_VIOLATION';\n","/**\n * Encodes a number (up to 53 bits safe integer) into a Varint buffer.\n * Varints are a way of encoding integers using one or more bytes.\n * Smaller numbers take fewer bytes.\n *\n * @param {number} value - The unsigned integer to encode\n * @returns {Uint8Array} The encoded binary buffer\n * @throws {Error} If the value is negative\n */\nexport function encodeVarint(value: number): Uint8Array {\n if (value < 0) throw new Error('Varint must be unsigned');\n const bytes: number[] = [];\n while (true) {\n const byte = value & 0x7f;\n value >>>= 7;\n if (value === 0) {\n bytes.push(byte);\n break;\n }\n bytes.push(byte | 0x80);\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * Decodes a Varint from a buffer starting at a specific offset.\n *\n * @param {Uint8Array} buf - The buffer containing the encoded varint\n * @param {number} [offset=0] - The starting position in the buffer\n * @returns {Object} The decoded numeric value and the number of bytes consumed (length)\n * @throws {Error} If the buffer is too small or the varint exceeds 8 bytes (max 53-bit safe int)\n */\nexport function decodeVarint(\n buf: Uint8Array,\n offset = 0,\n): { value: number; length: number } {\n let value = 0;\n let shift = 0;\n let length = 0;\n\n while (true) {\n if (offset + length >= buf.length) {\n throw new Error('Varint decode out of bounds');\n }\n const byte = buf[offset + length];\n value += (byte & 0x7f) * Math.pow(2, shift);\n length++;\n shift += 7;\n if ((byte & 0x80) === 0) {\n break;\n }\n if (length > 8) throw new Error('Varint too large');\n }\n\n return { value, length };\n}\n\n/**\n * Calculates the number of bytes required to encode a value as a varint.\n * Useful for pre-allocating buffers.\n *\n * @param {number} value - The unsigned integer to check\n * @returns {number} The byte length\n * @throws {Error} If the value is negative\n */\nexport function varintLength(value: number): number {\n if (value < 0) throw new Error('Varint must be unsigned');\n let len = 0;\n do {\n value >>>= 7;\n len++;\n } while (value !== 0);\n return len;\n}\n","import { encodeVarint, decodeVarint, varintLength } from './varint';\n\n/**\n * Represents a basic Type-Length-Value structure.\n *\n * @interface TLV\n */\nexport interface TLV {\n /** The tag or type identifier */\n type: number;\n /** The raw binary value */\n value: Uint8Array;\n}\n\n/**\n * Encodes an array of TLVs into a canonical binary buffer.\n *\n * **Canonical Rules:**\n * 1. TLVs MUST be sorted by `type` in ascending order.\n * 2. Duplicate `type` entries are NOT allowed.\n * 3. Format: `[type_varint][len_varint][value_bytes]`\n *\n * @param {TLV[]} tlvs - The list of TLV entries to encode\n * @returns {Uint8Array} The sorted and encoded binary buffer\n * @throws {Error} If duplicate types are detected\n */\nexport function encodeTLVs(tlvs: TLV[]): Uint8Array {\n // 1. Sort by TYPE ascending\n // Create a copy to avoid mutating input\n const sorted = [...tlvs].sort((a, b) => a.type - b.type);\n\n // 2. Check for duplicates\n for (let i = 0; i < sorted.length - 1; i++) {\n if (sorted[i].type === sorted[i + 1].type) {\n throw new Error(`Duplicate TLV type: ${sorted[i].type}`);\n }\n }\n\n // 3. Calculate total size\n let totalSize = 0;\n for (const t of sorted) {\n totalSize += varintLength(t.type);\n totalSize += varintLength(t.value.length);\n totalSize += t.value.length;\n }\n\n // 4. Encode\n const buf = new Uint8Array(totalSize);\n let offset = 0;\n for (const t of sorted) {\n const typeBytes = encodeVarint(t.type);\n buf.set(typeBytes, offset);\n offset += typeBytes.length;\n\n const lenBytes = encodeVarint(t.value.length);\n buf.set(lenBytes, offset);\n offset += lenBytes.length;\n\n buf.set(t.value, offset);\n offset += t.value.length;\n }\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a flat list.\n * Preserves the original wire order and allows duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing TLV-encoded data\n * @param {number} [maxItems=1024] - Security limit for the number of parsed items\n * @returns {TLV[]} A list of decoded TLV entries\n * @throws {Error} If the buffer is truncated or malformed\n */\nexport function decodeTLVsList(buf: Uint8Array, maxItems = 1024): TLV[] {\n const list: TLV[] = [];\n let offset = 0;\n\n while (offset < buf.length) {\n if (list.length >= maxItems) throw new Error('TLV_LIMIT');\n\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n list.push({ type, value });\n offset += len;\n }\n\n return list;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a Map for efficient access.\n * Enforces strict canonical order (sorted tiles) and forbids duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing canonical TLV data\n * @returns {Map<number, Uint8Array>} Map of Tag -> Value\n * @throws {Error} If canonical order is violated or duplicates are found\n */\nexport function decodeTLVs(buf: Uint8Array): Map<number, Uint8Array> {\n const map = new Map<number, Uint8Array>();\n let offset = 0;\n let lastType = -1;\n\n while (offset < buf.length) {\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Check canonical order\n if (type <= lastType) {\n throw new Error(\n `TLV violation: Unsorted or duplicate type ${type} after ${lastType}`,\n );\n }\n lastType = type;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n map.set(type, value);\n offset += len;\n }\n\n return map;\n}\n\n/**\n * Recursive Object Decoder (safe nesting).\n * This follows the AXIS Option A: Nested TLV objects.\n */\nexport function decodeObject(\n bytes: Uint8Array,\n depth = 0,\n limits = { maxDepth: 8, maxItems: 128 },\n): Map<number, any> {\n if (depth > limits.maxDepth) {\n throw new Error('OBJECT_DEPTH_EXCEEDED');\n }\n\n const map = decodeTLVs(bytes);\n // In v1, we leave values as Uint8Array unless schema-driven.\n // The IntentSchemaValidator will handle deeper recursion.\n return map;\n}\n\n/**\n * Array Decoder (explicit container).\n * VALUE = repeated TLVs of one ITEM type.\n */\nexport function decodeArray(\n bytes: Uint8Array,\n itemType: number,\n maxItems = 256,\n): Uint8Array[] {\n const list = decodeTLVsList(bytes, maxItems);\n const items: Uint8Array[] = [];\n\n for (const tlv of list) {\n if (tlv.type !== itemType) {\n throw new Error(`INVALID_ARRAY_ITEM:${tlv.type}`);\n }\n items.push(tlv.value);\n }\n\n return items;\n}\n","import * as z from 'zod';\n\n/**\n * AxisFrame Schema\n *\n * Defines the logical structure of an AXIS frame using Zod for runtime validation.\n * This is used for internal processing after the low-level binary parsing is complete.\n */\nexport const AxisFrameZ = z.object({\n /** Flag bits for protocol control (e.g., encryption, compression) */\n flags: z.number().int().nonnegative(),\n /** A map of TLV headers where key=Tag and value=BinaryData */\n headers: z.map(\n z.number(),\n z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n ),\n /** The main payload of the frame */\n body: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n /** The cryptographic signature covering the frame (except the signature itself) */\n sig: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n});\n\n/**\n * Represents a structured AXIS frame.\n * @typedef {Object} AxisFrame\n */\nexport type AxisFrame = z.infer<typeof AxisFrameZ>;\nexport type AxisBinaryFrame = AxisFrame;\nimport {\n AXIS_MAGIC,\n AXIS_VERSION,\n MAX_BODY_LEN,\n MAX_FRAME_LEN,\n MAX_HDR_LEN,\n MAX_SIG_LEN,\n} from './constants';\nimport { decodeTLVs, encodeTLVs } from './tlv';\nimport { decodeVarint, encodeVarint } from './varint';\n\n/**\n * Encodes a structured AxisFrame into its binary wire representation.\n *\n * **Encoding Steps:**\n * 1. Encodes header TLV map into a single buffer.\n * 2. Validates lengths against MAX_* constants.\n * 3. Encodes lengths (HDR, BODY, SIG) as varints.\n * 4. Assembles the final byte array with magic, version, and flags.\n *\n * @param {AxisFrame} frame - The structured frame to encode\n * @returns {Uint8Array} The full binary frame\n * @throws {Error} If any section exceeds protocol limits\n */\nexport function encodeFrame(frame: AxisFrame): Uint8Array {\n const hdrBytes = encodeTLVs(\n Array.from(frame.headers.entries()).map(([t, v]) => ({\n type: t,\n value: v,\n })),\n );\n\n if (hdrBytes.length > MAX_HDR_LEN) throw new Error('Header too large');\n if (frame.body.length > MAX_BODY_LEN) throw new Error('Body too large');\n if (frame.sig.length > MAX_SIG_LEN) throw new Error('Signature too large');\n\n // Header Len, Body Len, Sig Len\n const hdrLenBytes = encodeVarint(hdrBytes.length);\n const bodyLenBytes = encodeVarint(frame.body.length);\n const sigLenBytes = encodeVarint(frame.sig.length);\n\n const totalLen =\n 5 + // Magic (AXIS1)\n 1 + // Version\n 1 + // Flags\n hdrLenBytes.length +\n bodyLenBytes.length +\n sigLenBytes.length +\n hdrBytes.length +\n frame.body.length +\n frame.sig.length;\n\n if (totalLen > MAX_FRAME_LEN) throw new Error('Total frame too large');\n\n const buf = new Uint8Array(totalLen);\n let offset = 0;\n\n // Magic (AXIS1 - 5 bytes)\n buf.set(AXIS_MAGIC, offset);\n offset += 5;\n\n // Version\n buf[offset++] = AXIS_VERSION;\n\n // Flags\n buf[offset++] = frame.flags;\n\n // Lengths\n buf.set(hdrLenBytes, offset);\n offset += hdrLenBytes.length;\n\n buf.set(bodyLenBytes, offset);\n offset += bodyLenBytes.length;\n\n buf.set(sigLenBytes, offset);\n offset += sigLenBytes.length;\n\n // Payloads\n buf.set(hdrBytes, offset);\n offset += hdrBytes.length;\n\n buf.set(frame.body, offset);\n offset += frame.body.length;\n\n buf.set(frame.sig, offset);\n offset += frame.sig.length;\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer into a structured AxisFrame with strict validation.\n *\n * @param {Uint8Array} buf - Raw bytes from the wire\n * @returns {AxisFrame} The parsed and validated frame\n * @throws {Error} If magic, version, or lengths are invalid\n */\nexport function decodeFrame(buf: Uint8Array): AxisFrame {\n let offset = 0;\n\n // 1. Magic (AXIS1 - 5 bytes)\n if (offset + 5 > buf.length) throw new Error('Packet too short');\n for (let i = 0; i < 5; i++) {\n if (buf[offset + i] !== AXIS_MAGIC[i]) throw new Error('Invalid Magic');\n }\n offset += 5;\n\n // 2. Version\n const ver = buf[offset++];\n if (ver !== AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);\n\n // 3. Flags\n const flags = buf[offset++];\n\n // 4. Lengths\n const { value: hdrLen, length: hlLen } = decodeVarint(buf, offset);\n offset += hlLen;\n if (hdrLen > MAX_HDR_LEN) throw new Error('Header limit exceeded');\n\n const { value: bodyLen, length: blLen } = decodeVarint(buf, offset);\n offset += blLen;\n if (bodyLen > MAX_BODY_LEN) throw new Error('Body limit exceeded');\n\n const { value: sigLen, length: slLen } = decodeVarint(buf, offset);\n offset += slLen;\n if (sigLen > MAX_SIG_LEN) throw new Error('Signature limit exceeded');\n\n // 5. Extract Bytes\n if (offset + hdrLen + bodyLen + sigLen > buf.length) {\n throw new Error('Frame truncated');\n }\n\n const hdrBytes = buf.slice(offset, offset + hdrLen);\n offset += hdrLen;\n\n const bodyBytes = buf.slice(offset, offset + bodyLen);\n offset += bodyLen;\n\n const sigBytes = buf.slice(offset, offset + sigLen);\n offset += sigLen;\n\n // 6. Decode Header TLVs\n const headers = decodeTLVs(hdrBytes);\n\n return {\n flags,\n headers,\n body: bodyBytes,\n sig: sigBytes,\n };\n}\n\n/**\n * Helper to get canonical bytes for signing.\n * SigTarget = All bytes up to SigLen, with SigLen=0, and no SigBytes.\n */\nexport function getSignTarget(frame: AxisFrame): Uint8Array {\n // Re-encode frame but with empty signature\n // Note: This is efficient enough for v1 (tens of KB).\n return encodeFrame({\n ...frame,\n sig: new Uint8Array(0),\n });\n}\n","import * as crypto from 'crypto';\n\nimport { AxisFrame, encodeFrame } from './axis-bin';\n\n/**\n * Signature utilities for AXIS binary frames\n * Supports Ed25519 signature generation and verification\n */\n\n/**\n * Computes the canonical payload for signing an AXIS frame.\n * The signature covers all bytes of the encoded frame EXCEPT the signature field itself.\n *\n * @param {AxisFrame} frame - The frame to prepare for signing\n * @returns {Buffer} The serialized canonical bytes for the signature algorithm\n */\nexport function computeSignaturePayload(frame: AxisFrame): Buffer {\n // Re-encode frame with empty signature\n const frameWithoutSig: AxisFrame = {\n ...frame,\n sig: new Uint8Array(0),\n };\n\n const encoded = encodeFrame(frameWithoutSig);\n return Buffer.from(encoded);\n}\n\n/**\n * Signs an AXIS frame using the Ed25519 algorithm.\n * Automatically handles both raw 32-byte seeds and pkcs8 DER-encoded private keys.\n *\n * @param {AxisFrame} frame - The frame to sign\n * @param {Buffer} privateKey - Ed25519 private key (32-byte raw OR pkcs8 DER)\n * @returns {Buffer} The 64-byte Ed25519 signature\n * @throws {Error} If key format is invalid or signing fail\n */\nexport function signFrame(frame: AxisFrame, privateKey: Buffer): Buffer {\n const payload = computeSignaturePayload(frame);\n\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte seed or DER-encoded\n if (privateKey.length === 32) {\n // Raw seed - wrap in pkcs8 DER format\n // pkcs8 prefix for Ed25519: 0x302e020100300506032b657004220420\n const pkcs8Prefix = Buffer.from([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,\n 0x04, 0x22, 0x04, 0x20,\n ]);\n const pkcs8Key = Buffer.concat([pkcs8Prefix, privateKey]);\n\n keyObject = crypto.createPrivateKey({\n key: pkcs8Key,\n format: 'der',\n type: 'pkcs8',\n });\n } else {\n // Assume already DER-encoded pkcs8\n keyObject = crypto.createPrivateKey({\n key: privateKey,\n format: 'der',\n type: 'pkcs8',\n });\n }\n\n const signature = crypto.sign(null, payload, keyObject);\n\n if (signature.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n return signature;\n}\n\n/**\n * Verifies an Ed25519 signature on an AXIS frame.\n * Automatically handles both raw 32-byte public keys and spki DER-encoded public keys.\n *\n * @param {AxisFrame} frame - The frame containing the signature to verify\n * @param {Buffer} publicKey - Ed25519 public key (32-byte raw OR spki DER)\n * @returns {boolean} True if the signature is cryptographically valid\n * @throws {Error} If signature length is invalid\n */\nexport function verifyFrameSignature(\n frame: AxisFrame,\n publicKey: Buffer,\n): boolean {\n if (frame.sig.length === 0) {\n return false; // No signature\n }\n\n if (frame.sig.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n const payload = computeSignaturePayload(frame);\n\n try {\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte or DER-encoded\n if (publicKey.length === 32) {\n // Raw key - wrap in spki DER format\n // spki prefix for Ed25519: 0x302a300506032b6570032100\n const spkiPrefix = Buffer.from([\n 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,\n ]);\n const spkiKey = Buffer.concat([spkiPrefix, publicKey]);\n\n keyObject = crypto.createPublicKey({\n key: spkiKey,\n format: 'der',\n type: 'spki',\n });\n } else {\n // Assume already DER-encoded spki\n keyObject = crypto.createPublicKey({\n key: publicKey,\n format: 'der',\n type: 'spki',\n });\n }\n\n const valid = crypto.verify(\n null,\n payload,\n keyObject,\n Buffer.from(frame.sig),\n );\n return valid;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Generates a new Ed25519 key pair for use with the AXIS protocol.\n * Returns keys in canonical DER format (pkcs8 for private, spki for public).\n *\n * @returns {Object} An object containing the privateKey and publicKey as Buffers\n */\nexport function generateEd25519KeyPair(): {\n privateKey: Buffer;\n publicKey: Buffer;\n} {\n const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');\n\n return {\n privateKey: privateKey.export({ type: 'pkcs8', format: 'der' }) as Buffer,\n publicKey: publicKey.export({ type: 'spki', format: 'der' }) as Buffer,\n };\n}\n\n/**\n * Computes a standard SHA-256 hash of the provided data.\n *\n * @param {Buffer | Uint8Array} data - The input data to hash\n * @returns {Buffer} The 32-byte SHA-256 digest\n */\nexport function sha256(data: Buffer | Uint8Array): Buffer {\n return crypto.createHash('sha256').update(data).digest();\n}\n\n/**\n * Computes a hash for an AXIS receipt, optionally chaining it to a previous hash.\n * This is used for generating an immutable transaction chain.\n *\n * @param {Buffer | Uint8Array} receiptBytes - The canonical binary representation of the receipt\n * @param {Buffer | Uint8Array} [prevHash] - The hash of the previous receipt in the chain\n * @returns {Buffer} The 32-byte SHA-256 hash of the receipt (and link)\n */\nexport function computeReceiptHash(\n receiptBytes: Buffer | Uint8Array,\n prevHash?: Buffer | Uint8Array,\n): Buffer {\n const hasher = crypto.createHash('sha256');\n hasher.update(receiptBytes);\n\n if (prevHash && prevHash.length > 0) {\n hasher.update(prevHash);\n }\n\n return hasher.digest();\n}\n"],"mappings":";AAGO,IAAM,aAAa,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,IAAM,EAAI,CAAC;AAKhE,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,gBAAgB,KAAK;AAK3B,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAKzB,IAAM,UAAU;AAChB,IAAM,SAAS;AACf,IAAM,aAAa;AACnB,IAAM,eAAe;AACrB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAClB,IAAM,UAAU;AAChB,IAAM,YAAY;AAClB,IAAM,WAAW;AACjB,IAAM,eAAe;AAErB,IAAM,UAAU;AAKhB,IAAM,UAAU;AAChB,IAAM,SAAS;AACf,IAAM,aAAa;AACnB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AACzB,IAAM,eAAe;AACrB,IAAM,qBAAqB;AAM3B,IAAM,uBAAuB;AAE7B,IAAM,gBAAgB;AAEtB,IAAM,uBAAuB;AAM7B,IAAM,gBAAgB;AAEtB,IAAM,YAAY;AAElB,IAAM,aAAa;AAEnB,IAAM,mBAAmB;AA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,IAC9D,WAAW,UAAU,OAAO,EAAE,MAAM,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC7D;AACF;AAQO,SAAS,OAAO,MAAmC;AACxD,SAAc,kBAAW,QAAQ,EAAE,OAAO,IAAI,EAAE,OAAO;AACzD;AAUO,SAAS,mBACd,cACA,UACQ;AACR,QAAM,SAAgB,kBAAW,QAAQ;AACzC,SAAO,OAAO,YAAY;AAE1B,MAAI,YAAY,SAAS,SAAS,GAAG;AACnC,WAAO,OAAO,QAAQ;AAAA,EACxB;AAEA,SAAO,OAAO,OAAO;AACvB;","names":["map"]}
1
+ {"version":3,"sources":["../../src/core/constants.ts","../../src/core/varint.ts","../../src/core/tlv.ts","../../src/core/axis-bin.ts","../../src/core/signature.ts"],"sourcesContent":["/**\n * AXIS Protocol Magic Bytes (e.g., 'AXIS1')\n */\nexport const AXIS_MAGIC = new Uint8Array([0x41, 0x58, 0x49, 0x53, 0x31]);\n\n/**\n * AXIS Protocol Version\n */\nexport const AXIS_VERSION = 0x01;\n\n/**\n * Maximum allowed size for the Header section in bytes.\n */\nexport const MAX_HDR_LEN = 2048;\n\n/**\n * Maximum allowed size for the Body section in bytes.\n */\nexport const MAX_BODY_LEN = 65536;\n\n/**\n * Maximum allowed size for the Signature section in bytes.\n */\nexport const MAX_SIG_LEN = 128;\n\n/**\n * Total maximum allowed size for a single AXIS frame.\n */\nexport const MAX_FRAME_LEN = 70 * 1024; // 70 KB\n\n/**\n * Frame Control Flags\n */\nexport const FLAG_BODY_TLV = 0x01;\nexport const FLAG_CHAIN_REQ = 0x02;\nexport const FLAG_HAS_WITNESS = 0x04;\n\n/**\n * TLV Tags for Header Section\n */\nexport const TLV_PID = 1;\nexport const TLV_TS = 2;\nexport const TLV_INTENT = 3;\nexport const TLV_ACTOR_ID = 4;\nexport const TLV_PROOF_TYPE = 5;\nexport const TLV_PROOF_REF = 6;\nexport const TLV_NONCE = 7;\nexport const TLV_AUD = 8;\nexport const TLV_REALM = TLV_AUD;\nexport const TLV_NODE = 9;\nexport const TLV_TRACE_ID = 10;\n/** Key ID for key rotation support */\nexport const TLV_KID = 11;\n\n/**\n * TLV Tags for Receipt Section\n */\nexport const TLV_RID = 15;\nexport const TLV_OK = 16;\nexport const TLV_EFFECT = 17;\nexport const TLV_ERROR_CODE = 18;\nexport const TLV_ERROR_MSG = 19;\nexport const TLV_PREV_HASH = 20;\nexport const TLV_RECEIPT_HASH = 21;\nexport const TLV_NODE_KID = 30;\nexport const TLV_NODE_CERT_HASH = 34;\n\n/**\n * TLV Tags for Loom Runtime (Lawful Execution)\n */\n/** Presence ID - liveness proof (UTF-8 string, e.g., \"pr_abc123\") */\nexport const TLV_LOOM_PRESENCE_ID = 91;\n/** Writ - executable intent (canonical JSON, UTF-8 encoded) */\nexport const TLV_LOOM_WRIT = 92;\n/** Thread Hash - causal continuity (32 bytes, raw binary) */\nexport const TLV_LOOM_THREAD_HASH = 93;\n\n/**\n * TLV Tags for Application Extensions (File Transfer / Capsule, range 70-99)\n */\n/** Upload session identifier (16 bytes, raw binary) */\nexport const TLV_UPLOAD_ID = 70;\n/** Chunk index within an upload session */\nexport const TLV_INDEX = 71;\n/** Byte offset of the chunk within the file */\nexport const TLV_OFFSET = 72;\n/** SHA-256 hash of a file chunk (32 bytes, raw binary) */\nexport const TLV_SHA256_CHUNK = 73;\n/** Capsule identifier stored as UTF-8 string */\nexport const TLV_CAPSULE = 90;\n\n/**\n * TLV Tags for Body Structure (used in body-profile validation)\n */\n/** Nested object TLV type */\nexport const TLV_BODY_OBJ = 254;\n/** Array TLV type */\nexport const TLV_BODY_ARR = 255;\n\n/**\n * TLV Tags for Node Certificate format (cert payload fields, not frame headers)\n *\n * These are used exclusively inside the node certificate binary format\n * and are NOT shared with the frame header TLV namespace.\n */\nexport const NCERT_NODE_ID = 1;\nexport const NCERT_KID = 2;\nexport const NCERT_ALG = 3;\nexport const NCERT_PUB = 4;\nexport const NCERT_NBF = 5;\nexport const NCERT_EXP = 6;\nexport const NCERT_SCOPE = 7;\nexport const NCERT_ISSUER_KID = 8;\n/** Cert envelope: signed payload bytes */\nexport const NCERT_PAYLOAD = 50;\n/** Cert envelope: root signature (64 bytes, Ed25519) */\nexport const NCERT_SIG = 51;\n\n/**\n * Supported Authentication Proof Types\n */\n/** No proof / unauthenticated request */\nexport const PROOF_NONE = 0;\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof (Lawful Execution) */\nexport const PROOF_LOOM = 4;\n/** Witnessed signature proof */\nexport const PROOF_WITNESS = 5;\n\n/**\n * Canonical ProofType enum (mirrors PROOF_* constants).\n */\nexport enum ProofType {\n NONE = 0,\n CAPSULE = 1,\n JWT = 2,\n MTLS = 3,\n LOOM = 4,\n WITNESS = 5,\n}\n\n/**\n * Body Profile — declares the structural format of an AXIS frame body.\n */\nexport enum BodyProfile {\n RAW = 0,\n TLV_MAP = 1,\n OBJ = 2,\n ARR = 3,\n}\n\n/**\n * Standard Protocol Error Codes\n */\nexport const ERR_INVALID_PACKET = 'INVALID_PACKET';\nexport const ERR_BAD_SIGNATURE = 'BAD_SIGNATURE';\nexport const ERR_REPLAY_DETECTED = 'REPLAY_DETECTED';\nexport const ERR_CONTRACT_VIOLATION = 'CONTRACT_VIOLATION';\n","/**\n * Encodes a number (up to 53 bits safe integer) into a Varint buffer.\n * Varints are a way of encoding integers using one or more bytes.\n * Smaller numbers take fewer bytes.\n *\n * @param {number} value - The unsigned integer to encode\n * @returns {Uint8Array} The encoded binary buffer\n * @throws {Error} If the value is negative\n */\nexport function encodeVarint(value: number): Uint8Array {\n if (value < 0) throw new Error('Varint must be unsigned');\n const bytes: number[] = [];\n while (true) {\n const byte = value & 0x7f;\n value >>>= 7;\n if (value === 0) {\n bytes.push(byte);\n break;\n }\n bytes.push(byte | 0x80);\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * Decodes a Varint from a buffer starting at a specific offset.\n *\n * @param {Uint8Array} buf - The buffer containing the encoded varint\n * @param {number} [offset=0] - The starting position in the buffer\n * @returns {Object} The decoded numeric value and the number of bytes consumed (length)\n * @throws {Error} If the buffer is too small or the varint exceeds 8 bytes (max 53-bit safe int)\n */\nexport function decodeVarint(\n buf: Uint8Array,\n offset = 0,\n): { value: number; length: number } {\n let value = 0;\n let shift = 0;\n let length = 0;\n\n while (true) {\n if (offset + length >= buf.length) {\n throw new Error('Varint decode out of bounds');\n }\n const byte = buf[offset + length];\n value += (byte & 0x7f) * Math.pow(2, shift);\n length++;\n shift += 7;\n if ((byte & 0x80) === 0) {\n break;\n }\n if (length > 8) throw new Error('Varint too large');\n }\n\n return { value, length };\n}\n\n/**\n * Calculates the number of bytes required to encode a value as a varint.\n * Useful for pre-allocating buffers.\n *\n * @param {number} value - The unsigned integer to check\n * @returns {number} The byte length\n * @throws {Error} If the value is negative\n */\nexport function varintLength(value: number): number {\n if (value < 0) throw new Error('Varint must be unsigned');\n let len = 0;\n do {\n value >>>= 7;\n len++;\n } while (value !== 0);\n return len;\n}\n","import { encodeVarint, decodeVarint, varintLength } from './varint';\n\n/**\n * Represents a basic Type-Length-Value structure.\n *\n * @interface TLV\n */\nexport interface TLV {\n /** The tag or type identifier */\n type: number;\n /** The raw binary value */\n value: Uint8Array;\n}\n\n/**\n * Encodes an array of TLVs into a canonical binary buffer.\n *\n * **Canonical Rules:**\n * 1. TLVs MUST be sorted by `type` in ascending order.\n * 2. Duplicate `type` entries are NOT allowed.\n * 3. Format: `[type_varint][len_varint][value_bytes]`\n *\n * @param {TLV[]} tlvs - The list of TLV entries to encode\n * @returns {Uint8Array} The sorted and encoded binary buffer\n * @throws {Error} If duplicate types are detected\n */\nexport function encodeTLVs(tlvs: TLV[]): Uint8Array {\n // 1. Sort by TYPE ascending\n // Create a copy to avoid mutating input\n const sorted = [...tlvs].sort((a, b) => a.type - b.type);\n\n // 2. Check for duplicates\n for (let i = 0; i < sorted.length - 1; i++) {\n if (sorted[i].type === sorted[i + 1].type) {\n throw new Error(`Duplicate TLV type: ${sorted[i].type}`);\n }\n }\n\n // 3. Calculate total size\n let totalSize = 0;\n for (const t of sorted) {\n totalSize += varintLength(t.type);\n totalSize += varintLength(t.value.length);\n totalSize += t.value.length;\n }\n\n // 4. Encode\n const buf = new Uint8Array(totalSize);\n let offset = 0;\n for (const t of sorted) {\n const typeBytes = encodeVarint(t.type);\n buf.set(typeBytes, offset);\n offset += typeBytes.length;\n\n const lenBytes = encodeVarint(t.value.length);\n buf.set(lenBytes, offset);\n offset += lenBytes.length;\n\n buf.set(t.value, offset);\n offset += t.value.length;\n }\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a flat list.\n * Preserves the original wire order and allows duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing TLV-encoded data\n * @param {number} [maxItems=1024] - Security limit for the number of parsed items\n * @returns {TLV[]} A list of decoded TLV entries\n * @throws {Error} If the buffer is truncated or malformed\n */\nexport function decodeTLVsList(buf: Uint8Array, maxItems = 1024): TLV[] {\n const list: TLV[] = [];\n let offset = 0;\n\n while (offset < buf.length) {\n if (list.length >= maxItems) throw new Error('TLV_LIMIT');\n\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n list.push({ type, value });\n offset += len;\n }\n\n return list;\n}\n\n/**\n * Decodes a binary buffer of TLVs into a Map for efficient access.\n * Enforces strict canonical order (sorted tiles) and forbids duplicate types.\n *\n * @param {Uint8Array} buf - The buffer containing canonical TLV data\n * @returns {Map<number, Uint8Array>} Map of Tag -> Value\n * @throws {Error} If canonical order is violated or duplicates are found\n */\nexport function decodeTLVs(buf: Uint8Array): Map<number, Uint8Array> {\n const map = new Map<number, Uint8Array>();\n let offset = 0;\n let lastType = -1;\n\n while (offset < buf.length) {\n // Decode TYPE\n const { value: type, length: typeLen } = decodeVarint(buf, offset);\n offset += typeLen;\n\n // Check canonical order\n if (type <= lastType) {\n throw new Error(\n `TLV violation: Unsorted or duplicate type ${type} after ${lastType}`,\n );\n }\n lastType = type;\n\n // Decode LEN\n const { value: len, length: lenLen } = decodeVarint(buf, offset);\n offset += lenLen;\n\n // Check bounds\n if (offset + len > buf.length) {\n throw new Error(`TLV violation: Length ${len} exceeds buffer`);\n }\n\n // Extract VALUE\n const value = buf.slice(offset, offset + len);\n map.set(type, value);\n offset += len;\n }\n\n return map;\n}\n\n/**\n * Recursive Object Decoder (safe nesting).\n * This follows the AXIS Option A: Nested TLV objects.\n */\nexport function decodeObject(\n bytes: Uint8Array,\n depth = 0,\n limits = { maxDepth: 8, maxItems: 128 },\n): Map<number, any> {\n if (depth > limits.maxDepth) {\n throw new Error('OBJECT_DEPTH_EXCEEDED');\n }\n\n const map = decodeTLVs(bytes);\n // In v1, we leave values as Uint8Array unless schema-driven.\n // The IntentSchemaValidator will handle deeper recursion.\n return map;\n}\n\n/**\n * Array Decoder (explicit container).\n * VALUE = repeated TLVs of one ITEM type.\n */\nexport function decodeArray(\n bytes: Uint8Array,\n itemType: number,\n maxItems = 256,\n): Uint8Array[] {\n const list = decodeTLVsList(bytes, maxItems);\n const items: Uint8Array[] = [];\n\n for (const tlv of list) {\n if (tlv.type !== itemType) {\n throw new Error(`INVALID_ARRAY_ITEM:${tlv.type}`);\n }\n items.push(tlv.value);\n }\n\n return items;\n}\n","import * as z from 'zod';\n\n/**\n * AxisFrame Schema\n *\n * Defines the logical structure of an AXIS frame using Zod for runtime validation.\n * This is used for internal processing after the low-level binary parsing is complete.\n */\nexport const AxisFrameZ = z.object({\n /** Flag bits for protocol control (e.g., encryption, compression) */\n flags: z.number().int().nonnegative(),\n /** A map of TLV headers where key=Tag and value=BinaryData */\n headers: z.map(\n z.number(),\n z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n ),\n /** The main payload of the frame */\n body: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n /** The cryptographic signature covering the frame (except the signature itself) */\n sig: z.custom<Uint8Array>((v) => v instanceof Uint8Array),\n});\n\n/**\n * Represents a structured AXIS frame.\n * @typedef {Object} AxisFrame\n */\nexport type AxisFrame = z.infer<typeof AxisFrameZ>;\nexport type AxisBinaryFrame = AxisFrame;\nimport {\n AXIS_MAGIC,\n AXIS_VERSION,\n MAX_BODY_LEN,\n MAX_FRAME_LEN,\n MAX_HDR_LEN,\n MAX_SIG_LEN,\n} from './constants';\nimport { decodeTLVs, encodeTLVs } from './tlv';\nimport { decodeVarint, encodeVarint } from './varint';\n\n/**\n * Encodes a structured AxisFrame into its binary wire representation.\n *\n * **Encoding Steps:**\n * 1. Encodes header TLV map into a single buffer.\n * 2. Validates lengths against MAX_* constants.\n * 3. Encodes lengths (HDR, BODY, SIG) as varints.\n * 4. Assembles the final byte array with magic, version, and flags.\n *\n * @param {AxisFrame} frame - The structured frame to encode\n * @returns {Uint8Array} The full binary frame\n * @throws {Error} If any section exceeds protocol limits\n */\nexport function encodeFrame(frame: AxisFrame): Uint8Array {\n const hdrBytes = encodeTLVs(\n Array.from(frame.headers.entries()).map(([t, v]) => ({\n type: t,\n value: v,\n })),\n );\n\n if (hdrBytes.length > MAX_HDR_LEN) throw new Error('Header too large');\n if (frame.body.length > MAX_BODY_LEN) throw new Error('Body too large');\n if (frame.sig.length > MAX_SIG_LEN) throw new Error('Signature too large');\n\n // Header Len, Body Len, Sig Len\n const hdrLenBytes = encodeVarint(hdrBytes.length);\n const bodyLenBytes = encodeVarint(frame.body.length);\n const sigLenBytes = encodeVarint(frame.sig.length);\n\n const totalLen =\n 5 + // Magic (AXIS1)\n 1 + // Version\n 1 + // Flags\n hdrLenBytes.length +\n bodyLenBytes.length +\n sigLenBytes.length +\n hdrBytes.length +\n frame.body.length +\n frame.sig.length;\n\n if (totalLen > MAX_FRAME_LEN) throw new Error('Total frame too large');\n\n const buf = new Uint8Array(totalLen);\n let offset = 0;\n\n // Magic (AXIS1 - 5 bytes)\n buf.set(AXIS_MAGIC, offset);\n offset += 5;\n\n // Version\n buf[offset++] = AXIS_VERSION;\n\n // Flags\n buf[offset++] = frame.flags;\n\n // Lengths\n buf.set(hdrLenBytes, offset);\n offset += hdrLenBytes.length;\n\n buf.set(bodyLenBytes, offset);\n offset += bodyLenBytes.length;\n\n buf.set(sigLenBytes, offset);\n offset += sigLenBytes.length;\n\n // Payloads\n buf.set(hdrBytes, offset);\n offset += hdrBytes.length;\n\n buf.set(frame.body, offset);\n offset += frame.body.length;\n\n buf.set(frame.sig, offset);\n offset += frame.sig.length;\n\n return buf;\n}\n\n/**\n * Decodes a binary buffer into a structured AxisFrame with strict validation.\n *\n * @param {Uint8Array} buf - Raw bytes from the wire\n * @returns {AxisFrame} The parsed and validated frame\n * @throws {Error} If magic, version, or lengths are invalid\n */\nexport function decodeFrame(buf: Uint8Array): AxisFrame {\n let offset = 0;\n\n // 1. Magic (AXIS1 - 5 bytes)\n if (offset + 5 > buf.length) throw new Error('Packet too short');\n for (let i = 0; i < 5; i++) {\n if (buf[offset + i] !== AXIS_MAGIC[i]) throw new Error('Invalid Magic');\n }\n offset += 5;\n\n // 2. Version\n const ver = buf[offset++];\n if (ver !== AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);\n\n // 3. Flags\n const flags = buf[offset++];\n\n // 4. Lengths\n const { value: hdrLen, length: hlLen } = decodeVarint(buf, offset);\n offset += hlLen;\n if (hdrLen > MAX_HDR_LEN) throw new Error('Header limit exceeded');\n\n const { value: bodyLen, length: blLen } = decodeVarint(buf, offset);\n offset += blLen;\n if (bodyLen > MAX_BODY_LEN) throw new Error('Body limit exceeded');\n\n const { value: sigLen, length: slLen } = decodeVarint(buf, offset);\n offset += slLen;\n if (sigLen > MAX_SIG_LEN) throw new Error('Signature limit exceeded');\n\n // 5. Extract Bytes\n if (offset + hdrLen + bodyLen + sigLen > buf.length) {\n throw new Error('Frame truncated');\n }\n\n const hdrBytes = buf.slice(offset, offset + hdrLen);\n offset += hdrLen;\n\n const bodyBytes = buf.slice(offset, offset + bodyLen);\n offset += bodyLen;\n\n const sigBytes = buf.slice(offset, offset + sigLen);\n offset += sigLen;\n\n // 6. Decode Header TLVs\n const headers = decodeTLVs(hdrBytes);\n\n return {\n flags,\n headers,\n body: bodyBytes,\n sig: sigBytes,\n };\n}\n\n/**\n * Helper to get canonical bytes for signing.\n * SigTarget = All bytes up to SigLen, with SigLen=0, and no SigBytes.\n */\nexport function getSignTarget(frame: AxisFrame): Uint8Array {\n // Re-encode frame but with empty signature\n // Note: This is efficient enough for v1 (tens of KB).\n return encodeFrame({\n ...frame,\n sig: new Uint8Array(0),\n });\n}\n","import * as crypto from 'crypto';\n\nimport { AxisFrame, encodeFrame } from './axis-bin';\n\n/**\n * Signature utilities for AXIS binary frames\n * Supports Ed25519 signature generation and verification\n */\n\n/**\n * Computes the canonical payload for signing an AXIS frame.\n * The signature covers all bytes of the encoded frame EXCEPT the signature field itself.\n *\n * @param {AxisFrame} frame - The frame to prepare for signing\n * @returns {Buffer} The serialized canonical bytes for the signature algorithm\n */\nexport function computeSignaturePayload(frame: AxisFrame): Buffer {\n // Re-encode frame with empty signature\n const frameWithoutSig: AxisFrame = {\n ...frame,\n sig: new Uint8Array(0),\n };\n\n const encoded = encodeFrame(frameWithoutSig);\n return Buffer.from(encoded);\n}\n\n/**\n * Signs an AXIS frame using the Ed25519 algorithm.\n * Automatically handles both raw 32-byte seeds and pkcs8 DER-encoded private keys.\n *\n * @param {AxisFrame} frame - The frame to sign\n * @param {Buffer} privateKey - Ed25519 private key (32-byte raw OR pkcs8 DER)\n * @returns {Buffer} The 64-byte Ed25519 signature\n * @throws {Error} If key format is invalid or signing fail\n */\nexport function signFrame(frame: AxisFrame, privateKey: Buffer): Buffer {\n const payload = computeSignaturePayload(frame);\n\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte seed or DER-encoded\n if (privateKey.length === 32) {\n // Raw seed - wrap in pkcs8 DER format\n // pkcs8 prefix for Ed25519: 0x302e020100300506032b657004220420\n const pkcs8Prefix = Buffer.from([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,\n 0x04, 0x22, 0x04, 0x20,\n ]);\n const pkcs8Key = Buffer.concat([pkcs8Prefix, privateKey]);\n\n keyObject = crypto.createPrivateKey({\n key: pkcs8Key,\n format: 'der',\n type: 'pkcs8',\n });\n } else {\n // Assume already DER-encoded pkcs8\n keyObject = crypto.createPrivateKey({\n key: privateKey,\n format: 'der',\n type: 'pkcs8',\n });\n }\n\n const signature = crypto.sign(null, payload, keyObject);\n\n if (signature.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n return signature;\n}\n\n/**\n * Verifies an Ed25519 signature on an AXIS frame.\n * Automatically handles both raw 32-byte public keys and spki DER-encoded public keys.\n *\n * @param {AxisFrame} frame - The frame containing the signature to verify\n * @param {Buffer} publicKey - Ed25519 public key (32-byte raw OR spki DER)\n * @returns {boolean} True if the signature is cryptographically valid\n * @throws {Error} If signature length is invalid\n */\nexport function verifyFrameSignature(\n frame: AxisFrame,\n publicKey: Buffer,\n): boolean {\n if (frame.sig.length === 0) {\n return false; // No signature\n }\n\n if (frame.sig.length !== 64) {\n throw new Error('Ed25519 signature must be 64 bytes');\n }\n\n const payload = computeSignaturePayload(frame);\n\n try {\n let keyObject: crypto.KeyObject;\n\n // Check if key is raw 32-byte or DER-encoded\n if (publicKey.length === 32) {\n // Raw key - wrap in spki DER format\n // spki prefix for Ed25519: 0x302a300506032b6570032100\n const spkiPrefix = Buffer.from([\n 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,\n ]);\n const spkiKey = Buffer.concat([spkiPrefix, publicKey]);\n\n keyObject = crypto.createPublicKey({\n key: spkiKey,\n format: 'der',\n type: 'spki',\n });\n } else {\n // Assume already DER-encoded spki\n keyObject = crypto.createPublicKey({\n key: publicKey,\n format: 'der',\n type: 'spki',\n });\n }\n\n const valid = crypto.verify(\n null,\n payload,\n keyObject,\n Buffer.from(frame.sig),\n );\n return valid;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Generates a new Ed25519 key pair for use with the AXIS protocol.\n * Returns keys in canonical DER format (pkcs8 for private, spki for public).\n *\n * @returns {Object} An object containing the privateKey and publicKey as Buffers\n */\nexport function generateEd25519KeyPair(): {\n privateKey: Buffer;\n publicKey: Buffer;\n} {\n const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');\n\n return {\n privateKey: privateKey.export({ type: 'pkcs8', format: 'der' }) as Buffer,\n publicKey: publicKey.export({ type: 'spki', format: 'der' }) as Buffer,\n };\n}\n\n/**\n * Computes a standard SHA-256 hash of the provided data.\n *\n * @param {Buffer | Uint8Array} data - The input data to hash\n * @returns {Buffer} The 32-byte SHA-256 digest\n */\nexport function sha256(data: Buffer | Uint8Array): Buffer {\n return crypto.createHash('sha256').update(data).digest();\n}\n\n/**\n * Computes a hash for an AXIS receipt, optionally chaining it to a previous hash.\n * This is used for generating an immutable transaction chain.\n *\n * @param {Buffer | Uint8Array} receiptBytes - The canonical binary representation of the receipt\n * @param {Buffer | Uint8Array} [prevHash] - The hash of the previous receipt in the chain\n * @returns {Buffer} The 32-byte SHA-256 hash of the receipt (and link)\n */\nexport function computeReceiptHash(\n receiptBytes: Buffer | Uint8Array,\n prevHash?: Buffer | Uint8Array,\n): Buffer {\n const hasher = crypto.createHash('sha256');\n hasher.update(receiptBytes);\n\n if (prevHash && prevHash.length > 0) {\n hasher.update(prevHash);\n }\n\n return hasher.digest();\n}\n"],"mappings":";AAGO,IAAM,aAAa,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,IAAM,EAAI,CAAC;AAKhE,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,eAAe;AAKrB,IAAM,cAAc;AAKpB,IAAM,gBAAgB,K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ACA,UACQ;AACR,QAAM,SAAgB,kBAAW,QAAQ;AACzC,SAAO,OAAO,YAAY;AAE1B,MAAI,YAAY,SAAS,SAAS,GAAG;AACnC,WAAO,OAAO,QAAQ;AAAA,EACxB;AAEA,SAAO,OAAO,OAAO;AACvB;","names":["ProofType","BodyProfile","map"]}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AxisFrame } from './core/index.mjs';
2
- export { AXIS_MAGIC, AXIS_VERSION, AxisBinaryFrame, AxisFrameZ, TLV as AxisTlvType, ERR_BAD_SIGNATURE, ERR_CONTRACT_VIOLATION, ERR_INVALID_PACKET, ERR_REPLAY_DETECTED, FLAG_BODY_TLV, FLAG_CHAIN_REQ, FLAG_HAS_WITNESS, MAX_BODY_LEN, MAX_FRAME_LEN, MAX_HDR_LEN, MAX_SIG_LEN, NCERT_ALG, NCERT_EXP, NCERT_ISSUER_KID, NCERT_KID, NCERT_NBF, NCERT_NODE_ID, NCERT_PAYLOAD, NCERT_PUB, NCERT_SCOPE, NCERT_SIG, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, PROOF_NONE, PROOF_WITNESS, TLV, TLV_ACTOR_ID, TLV_AUD, TLV_BODY_ARR, TLV_BODY_OBJ, TLV_CAPSULE, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, TLV_INDEX, TLV_INTENT, TLV_KID, TLV_LOOM_PRESENCE_ID, TLV_LOOM_THREAD_HASH, TLV_LOOM_WRIT, TLV_NODE, TLV_NODE_CERT_HASH, TLV_NODE_KID, TLV_NONCE, TLV_OFFSET, TLV_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_SHA256_CHUNK, TLV_TRACE_ID, TLV_TS, TLV_UPLOAD_ID, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature } from './core/index.mjs';
2
+ export { AXIS_MAGIC, AXIS_VERSION, AxisBinaryFrame, AxisFrameZ, TLV as AxisTlvType, BodyProfile, ERR_BAD_SIGNATURE, ERR_CONTRACT_VIOLATION, ERR_INVALID_PACKET, ERR_REPLAY_DETECTED, FLAG_BODY_TLV, FLAG_CHAIN_REQ, FLAG_HAS_WITNESS, MAX_BODY_LEN, MAX_FRAME_LEN, MAX_HDR_LEN, MAX_SIG_LEN, NCERT_ALG, NCERT_EXP, NCERT_ISSUER_KID, NCERT_KID, NCERT_NBF, NCERT_NODE_ID, NCERT_PAYLOAD, NCERT_PUB, NCERT_SCOPE, NCERT_SIG, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, PROOF_NONE, PROOF_WITNESS, ProofType, TLV, TLV_ACTOR_ID, TLV_AUD, TLV_BODY_ARR, TLV_BODY_OBJ, TLV_CAPSULE, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, TLV_INDEX, TLV_INTENT, TLV_KID, TLV_LOOM_PRESENCE_ID, TLV_LOOM_THREAD_HASH, TLV_LOOM_WRIT, TLV_NODE, TLV_NODE_CERT_HASH, TLV_NODE_KID, TLV_NONCE, TLV_OFFSET, TLV_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_SHA256_CHUNK, TLV_TRACE_ID, TLV_TS, TLV_UPLOAD_ID, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature } from './core/index.mjs';
3
3
  import { OnModuleInit } from '@nestjs/common';
4
4
  import 'zod';
5
5
 
@@ -683,4 +683,60 @@ interface AxisCrudHandler extends AxisHandlerInit {
683
683
  remove(body: Uint8Array, headers?: Map<number, Uint8Array>): Promise<Uint8Array>;
684
684
  }
685
685
 
686
- export { ATS1_HDR, ATS1_SCHEMA, type ActorKeyRecord, ats1 as Ats1Codec, type Axis1DecodedFrame, type Axis1FrameToEncode, type AxisAlg, type AxisPacket as AxisBinaryPacket, type AxisCapsule, type AxisCapsuleConstraints, type AxisCapsulePayload, type AxisCrudHandler, type AxisEffect, type AxisHandler, type AxisHandlerInit, type AxisObservedContext, type AxisPacket$1 as AxisPacket, T as AxisPacketTags, type AxisPostSensor, type AxisPreSensor, type AxisRequestContext, type AxisResponse, type AxisSensor, type AxisSensorInit, type AxisSig, type CapsuleBatchBody, type CapsuleBatchResult, type CapsuleIssueBody, type CapsuleIssueResult, type CapsuleMode, type CapsuleRecord, type CapsuleRevokeBody, type CapsuleStatus, ContractViolationError, DEFAULT_CONTRACTS, Decision, type ExecutionContract, ExecutionMeter, type ExecutionMetrics, FALLBACK_CONTRACT, HANDLER_METADATA_KEY, Handler, INTENT_ROUTES_KEY, Intent, type IntentExecBody, type IntentOptions, type IntentRoute, IntentRouter, type IssuerKeyRecord, type KeyStatus, Schema2002_PasskeyLoginOptionsRes, Schema2011_PasskeyLoginVerifyReq, Schema2012_PasskeyLoginVerifyRes, Schema2021_PasskeyRegisterOptionsReq, type SensorDecision, SensorDecisions, type SensorInput, type SensorMinifiedDecision, type SensorPhaseMetadata, type TickWindow, axis1SigningBytes, b64urlDecode, b64urlDecodeString, b64urlEncode, b64urlEncodeString, buildAts1Hdr, buildPacket, buildTLVs, bytes, canonicalJson, canonicalJsonExcluding, decodeAxis1Frame, encVarint, encodeAxis1Frame, nonce16, normalizeSensorDecision, packPasskeyLoginOptionsReq, packPasskeyLoginOptionsRes, packPasskeyLoginVerifyReq, packPasskeyLoginVerifyRes, packPasskeyRegisterOptionsReq, tlv, u64be, unpackPasskeyLoginOptionsReq, unpackPasskeyLoginVerifyReq, unpackPasskeyRegisterOptionsReq, utf8, varintU };
686
+ declare function hasScope(scopes: string[], required: string): boolean;
687
+ declare function parseScope(scope: string): {
688
+ resource: string;
689
+ id: string;
690
+ } | null;
691
+ declare function canAccessResource(scopes: string[], resourceType: string, resourceId: string): boolean;
692
+
693
+ declare const CAPABILITIES: {
694
+ readonly read: "read";
695
+ readonly write: "write";
696
+ readonly execute: "execute";
697
+ readonly admin: "admin";
698
+ readonly sign: "sign";
699
+ readonly witness: "witness";
700
+ };
701
+ type Capability = keyof typeof CAPABILITIES;
702
+ declare const PROOF_CAPABILITIES: Record<number, Capability[]>;
703
+ declare const INTENT_REQUIREMENTS: Record<string, Capability[]>;
704
+
705
+ declare function validateFrameShape(frame: any): boolean;
706
+ declare function isTimestampValid(ts: number, skewSeconds?: number): boolean;
707
+
708
+ declare const AXIS_OPCODES: Set<string>;
709
+ declare function isKnownOpcode(op: string): boolean;
710
+ declare function isAdminOpcode(op: string): boolean;
711
+
712
+ type ReceiptEffect = 'ALLOW' | 'DENY' | 'ERROR';
713
+ declare function buildReceiptHash(prevHash: Buffer | null, pid: Buffer, actorId: string, intent: string, effect: ReceiptEffect, ts: bigint): Buffer;
714
+
715
+ declare enum IntentSensitivity {
716
+ LOW = 1,
717
+ MEDIUM = 2,
718
+ HIGH = 3,
719
+ CRITICAL = 4
720
+ }
721
+ declare const INTENT_SENSITIVITY_MAP: Record<string, IntentSensitivity>;
722
+ declare function classifyIntent(intent: string): IntentSensitivity;
723
+ declare function sensitivityName(level: IntentSensitivity): string;
724
+
725
+ declare const INTENT_TIMEOUTS: Record<string, number>;
726
+ declare const DEFAULT_TIMEOUT = 10000;
727
+ declare function resolveTimeout(intent: string): number;
728
+
729
+ interface IntentDefinition {
730
+ intent: string;
731
+ description: string;
732
+ sensitivity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
733
+ requiredProof: string[];
734
+ contract: {
735
+ maxDbWrites: number;
736
+ maxTimeMs: number;
737
+ };
738
+ examples?: string[];
739
+ deprecated?: boolean;
740
+ }
741
+
742
+ export { ATS1_HDR, ATS1_SCHEMA, AXIS_OPCODES, type ActorKeyRecord, ats1 as Ats1Codec, type Axis1DecodedFrame, type Axis1FrameToEncode, type AxisAlg, type AxisPacket as AxisBinaryPacket, type AxisCapsule, type AxisCapsuleConstraints, type AxisCapsulePayload, type AxisCrudHandler, type AxisEffect, type AxisHandler, type AxisHandlerInit, type AxisObservedContext, type AxisPacket$1 as AxisPacket, T as AxisPacketTags, type AxisPostSensor, type AxisPreSensor, type AxisRequestContext, type AxisResponse, type AxisSensor, type AxisSensorInit, type AxisSig, CAPABILITIES, type Capability, type CapsuleBatchBody, type CapsuleBatchResult, type CapsuleIssueBody, type CapsuleIssueResult, type CapsuleMode, type CapsuleRecord, type CapsuleRevokeBody, type CapsuleStatus, ContractViolationError, DEFAULT_CONTRACTS, DEFAULT_TIMEOUT, Decision, type ExecutionContract, ExecutionMeter, type ExecutionMetrics, FALLBACK_CONTRACT, HANDLER_METADATA_KEY, Handler, INTENT_REQUIREMENTS, INTENT_ROUTES_KEY, INTENT_SENSITIVITY_MAP, INTENT_TIMEOUTS, Intent, type IntentDefinition, type IntentExecBody, type IntentOptions, type IntentRoute, IntentRouter, IntentSensitivity, type IssuerKeyRecord, type KeyStatus, PROOF_CAPABILITIES, type ReceiptEffect, Schema2002_PasskeyLoginOptionsRes, Schema2011_PasskeyLoginVerifyReq, Schema2012_PasskeyLoginVerifyRes, Schema2021_PasskeyRegisterOptionsReq, type SensorDecision, SensorDecisions, type SensorInput, type SensorMinifiedDecision, type SensorPhaseMetadata, type TickWindow, axis1SigningBytes, b64urlDecode, b64urlDecodeString, b64urlEncode, b64urlEncodeString, buildAts1Hdr, buildPacket, buildReceiptHash, buildTLVs, bytes, canAccessResource, canonicalJson, canonicalJsonExcluding, classifyIntent, decodeAxis1Frame, encVarint, encodeAxis1Frame, hasScope, isAdminOpcode, isKnownOpcode, isTimestampValid, nonce16, normalizeSensorDecision, packPasskeyLoginOptionsReq, packPasskeyLoginOptionsRes, packPasskeyLoginVerifyReq, packPasskeyLoginVerifyRes, packPasskeyRegisterOptionsReq, parseScope, resolveTimeout, sensitivityName, tlv, u64be, unpackPasskeyLoginOptionsReq, unpackPasskeyLoginVerifyReq, unpackPasskeyRegisterOptionsReq, utf8, validateFrameShape, varintU };