@nextera.one/axis-server-sdk 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -0
- package/dist/core/index.d.mts +3 -1
- package/dist/core/index.d.ts +3 -1
- package/dist/core/index.js +3 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +2 -0
- package/dist/core/index.mjs.map +1 -1
- package/dist/index.d.mts +634 -2
- package/dist/index.d.ts +634 -2
- package/dist/index.js +1351 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1318 -13
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# @nextera.one/axis-server-sdk
|
|
2
|
+
|
|
3
|
+
Server-side SDK for the AXIS protocol.
|
|
4
|
+
|
|
5
|
+
This package contains the Nest-friendly server runtime pieces plus the shared AXIS binary protocol utilities used by both client and server implementations.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @nextera.one/axis-server-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Peer dependencies:
|
|
14
|
+
|
|
15
|
+
- `@nestjs/common`
|
|
16
|
+
- `reflect-metadata`
|
|
17
|
+
|
|
18
|
+
## What It Exposes
|
|
19
|
+
|
|
20
|
+
Root exports are split into two groups:
|
|
21
|
+
|
|
22
|
+
- Server runtime helpers: `@Handler`, `@Intent`, `IntentRouter`, handler interfaces, sensor interfaces.
|
|
23
|
+
- Shared protocol primitives: binary frame codecs, TLV/varint/constants, binary signature helpers, codec utilities, packet types.
|
|
24
|
+
|
|
25
|
+
## Shared Core API
|
|
26
|
+
|
|
27
|
+
The canonical cross-SDK protocol layer is the `./core` subpath:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import {
|
|
31
|
+
AXIS_MAGIC,
|
|
32
|
+
TLV_AUD,
|
|
33
|
+
TLV_REALM,
|
|
34
|
+
AxisBinaryFrame,
|
|
35
|
+
AxisFrameZ,
|
|
36
|
+
encodeFrame,
|
|
37
|
+
decodeFrame,
|
|
38
|
+
getSignTarget,
|
|
39
|
+
signFrame,
|
|
40
|
+
verifyFrameSignature,
|
|
41
|
+
} from '@nextera.one/axis-server-sdk/core';
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Notes:
|
|
45
|
+
|
|
46
|
+
- `TLV_AUD` is the canonical name for tag `8`.
|
|
47
|
+
- `TLV_REALM` remains available as a compatibility alias.
|
|
48
|
+
- `AxisBinaryFrame` is the explicit low-level binary frame type.
|
|
49
|
+
|
|
50
|
+
## Decorator Example
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import {
|
|
54
|
+
Handler,
|
|
55
|
+
Intent,
|
|
56
|
+
IntentRouter,
|
|
57
|
+
AxisEffect,
|
|
58
|
+
} from '@nextera.one/axis-server-sdk';
|
|
59
|
+
import type { AxisBinaryFrame } from '@nextera.one/axis-server-sdk/core';
|
|
60
|
+
|
|
61
|
+
@Handler('system')
|
|
62
|
+
export class SystemHandler {
|
|
63
|
+
constructor(private readonly router: IntentRouter) {}
|
|
64
|
+
|
|
65
|
+
onModuleInit() {
|
|
66
|
+
this.router.registerHandler(this);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
@Intent('ping', { frame: true })
|
|
70
|
+
async ping(frame: AxisBinaryFrame): Promise<AxisEffect> {
|
|
71
|
+
return {
|
|
72
|
+
ok: true,
|
|
73
|
+
effect: 'PONG',
|
|
74
|
+
body: frame.body,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Versioning
|
|
81
|
+
|
|
82
|
+
The server SDK may include additional server-only exports beyond the shared `./core` surface. For code intended to work across both client and server SDKs, prefer importing protocol primitives from `./core`.
|
package/dist/core/index.d.mts
CHANGED
|
@@ -7,6 +7,7 @@ declare const AxisFrameZ: z.ZodObject<{
|
|
|
7
7
|
sig: z.ZodCustom<Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>>;
|
|
8
8
|
}, z.z.core.$strip>;
|
|
9
9
|
type AxisFrame = z.infer<typeof AxisFrameZ>;
|
|
10
|
+
type AxisBinaryFrame = AxisFrame;
|
|
10
11
|
declare function encodeFrame(frame: AxisFrame): Uint8Array;
|
|
11
12
|
declare function decodeFrame(buf: Uint8Array): AxisFrame;
|
|
12
13
|
declare function getSignTarget(frame: AxisFrame): Uint8Array;
|
|
@@ -28,6 +29,7 @@ declare const TLV_PROOF_TYPE = 5;
|
|
|
28
29
|
declare const TLV_PROOF_REF = 6;
|
|
29
30
|
declare const TLV_NONCE = 7;
|
|
30
31
|
declare const TLV_AUD = 8;
|
|
32
|
+
declare const TLV_REALM = 8;
|
|
31
33
|
declare const TLV_NODE = 9;
|
|
32
34
|
declare const TLV_TRACE_ID = 10;
|
|
33
35
|
declare const TLV_KID = 11;
|
|
@@ -82,4 +84,4 @@ declare function generateEd25519KeyPair(): {
|
|
|
82
84
|
declare function sha256(data: Buffer | Uint8Array): Buffer;
|
|
83
85
|
declare function computeReceiptHash(receiptBytes: Buffer | Uint8Array, prevHash?: Buffer | Uint8Array): Buffer;
|
|
84
86
|
|
|
85
|
-
export { AXIS_MAGIC, AXIS_VERSION, 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, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, 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_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_RECEIPT_HASH, TLV_RID, TLV_TRACE_ID, TLV_TS, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
|
|
87
|
+
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, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, 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_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_TRACE_ID, TLV_TS, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
|
package/dist/core/index.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ declare const AxisFrameZ: z.ZodObject<{
|
|
|
7
7
|
sig: z.ZodCustom<Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>>;
|
|
8
8
|
}, z.z.core.$strip>;
|
|
9
9
|
type AxisFrame = z.infer<typeof AxisFrameZ>;
|
|
10
|
+
type AxisBinaryFrame = AxisFrame;
|
|
10
11
|
declare function encodeFrame(frame: AxisFrame): Uint8Array;
|
|
11
12
|
declare function decodeFrame(buf: Uint8Array): AxisFrame;
|
|
12
13
|
declare function getSignTarget(frame: AxisFrame): Uint8Array;
|
|
@@ -28,6 +29,7 @@ declare const TLV_PROOF_TYPE = 5;
|
|
|
28
29
|
declare const TLV_PROOF_REF = 6;
|
|
29
30
|
declare const TLV_NONCE = 7;
|
|
30
31
|
declare const TLV_AUD = 8;
|
|
32
|
+
declare const TLV_REALM = 8;
|
|
31
33
|
declare const TLV_NODE = 9;
|
|
32
34
|
declare const TLV_TRACE_ID = 10;
|
|
33
35
|
declare const TLV_KID = 11;
|
|
@@ -82,4 +84,4 @@ declare function generateEd25519KeyPair(): {
|
|
|
82
84
|
declare function sha256(data: Buffer | Uint8Array): Buffer;
|
|
83
85
|
declare function computeReceiptHash(receiptBytes: Buffer | Uint8Array, prevHash?: Buffer | Uint8Array): Buffer;
|
|
84
86
|
|
|
85
|
-
export { AXIS_MAGIC, AXIS_VERSION, 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, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, 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_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_RECEIPT_HASH, TLV_RID, TLV_TRACE_ID, TLV_TS, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
|
|
87
|
+
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, PROOF_CAPSULE, PROOF_JWT, PROOF_LOOM, PROOF_MTLS, type TLV, TLV_ACTOR_ID, TLV_AUD, TLV_EFFECT, TLV_ERROR_CODE, TLV_ERROR_MSG, 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_OK, TLV_PID, TLV_PREV_HASH, TLV_PROOF_REF, TLV_PROOF_TYPE, TLV_REALM, TLV_RECEIPT_HASH, TLV_RID, TLV_TRACE_ID, TLV_TS, computeReceiptHash, computeSignaturePayload, decodeArray, decodeFrame, decodeObject, decodeTLVs, decodeTLVsList, decodeVarint, encodeFrame, encodeTLVs, encodeVarint, generateEd25519KeyPair, getSignTarget, sha256, signFrame, varintLength, verifyFrameSignature };
|
package/dist/core/index.js
CHANGED
|
@@ -66,6 +66,7 @@ __export(core_exports, {
|
|
|
66
66
|
TLV_PREV_HASH: () => TLV_PREV_HASH,
|
|
67
67
|
TLV_PROOF_REF: () => TLV_PROOF_REF,
|
|
68
68
|
TLV_PROOF_TYPE: () => TLV_PROOF_TYPE,
|
|
69
|
+
TLV_REALM: () => TLV_REALM,
|
|
69
70
|
TLV_RECEIPT_HASH: () => TLV_RECEIPT_HASH,
|
|
70
71
|
TLV_RID: () => TLV_RID,
|
|
71
72
|
TLV_TRACE_ID: () => TLV_TRACE_ID,
|
|
@@ -108,6 +109,7 @@ var TLV_PROOF_TYPE = 5;
|
|
|
108
109
|
var TLV_PROOF_REF = 6;
|
|
109
110
|
var TLV_NONCE = 7;
|
|
110
111
|
var TLV_AUD = 8;
|
|
112
|
+
var TLV_REALM = TLV_AUD;
|
|
111
113
|
var TLV_NODE = 9;
|
|
112
114
|
var TLV_TRACE_ID = 10;
|
|
113
115
|
var TLV_KID = 11;
|
|
@@ -518,6 +520,7 @@ function computeReceiptHash(receiptBytes, prevHash) {
|
|
|
518
520
|
TLV_PREV_HASH,
|
|
519
521
|
TLV_PROOF_REF,
|
|
520
522
|
TLV_PROOF_TYPE,
|
|
523
|
+
TLV_REALM,
|
|
521
524
|
TLV_RECEIPT_HASH,
|
|
522
525
|
TLV_RID,
|
|
523
526
|
TLV_TRACE_ID,
|
package/dist/core/index.js.map
CHANGED
|
@@ -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_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 * Supported Authentication Proof Types\n */\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof */\nexport const PROOF_LOOM = 4;\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>;\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;;;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,IAAM,aAAa;AACnB,IAAM,eAAe;AACrB,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAClB,IAAM,UAAU;AAChB,IAAM,WAAW;AACjB,IAAM,eAAe;AAErB,IAAM,UAAU;AAKhB,IAAM,UAAU;AAChB,IAAM,SAAS;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S,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 * Supported Authentication Proof Types\n */\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof */\nexport const PROOF_LOOM = 4;\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;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V_NONCE = 7;
|
|
18
18
|
var TLV_AUD = 8;
|
|
19
|
+
var TLV_REALM = TLV_AUD;
|
|
19
20
|
var TLV_NODE = 9;
|
|
20
21
|
var TLV_TRACE_ID = 10;
|
|
21
22
|
var TLV_KID = 11;
|
|
@@ -425,6 +426,7 @@ export {
|
|
|
425
426
|
TLV_PREV_HASH,
|
|
426
427
|
TLV_PROOF_REF,
|
|
427
428
|
TLV_PROOF_TYPE,
|
|
429
|
+
TLV_REALM,
|
|
428
430
|
TLV_RECEIPT_HASH,
|
|
429
431
|
TLV_RID,
|
|
430
432
|
TLV_TRACE_ID,
|
package/dist/core/index.mjs.map
CHANGED
|
@@ -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_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 * Supported Authentication Proof Types\n */\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof */\nexport const PROOF_LOOM = 4;\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>;\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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ACR,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/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 * Supported Authentication Proof Types\n */\nexport const PROOF_CAPSULE = 1;\nexport const PROOF_JWT = 2;\nexport const PROOF_MTLS = 3;\n/** Loom Presence + Writ proof */\nexport const PROOF_LOOM = 4;\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;AAK7B,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAClB,IAAM,aAAa;AAEnB,IAAM,aAAa;AAKnB,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;;;ACnF/B,SAAS,aAAa,OAA2B;AACtD,MAAI,QAAQ,EAAG,OAAM,IAAI,MAAM,yBAAyB;AACxD,QAAM,QAAkB,CA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