@nextera.one/axis-server-sdk 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -33,69 +33,80 @@ var __decorateClass = (decorators, target, key, kind) => {
33
33
  if (kind && result) __defProp(target, key, result);
34
34
  return result;
35
35
  };
36
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
36
37
 
37
38
  // src/index.ts
38
39
  var index_exports = {};
39
40
  __export(index_exports, {
40
41
  ATS1_HDR: () => ATS1_HDR,
41
42
  ATS1_SCHEMA: () => ATS1_SCHEMA,
42
- AXIS_MAGIC: () => AXIS_MAGIC,
43
+ AXIS_MAGIC: () => import_axis_protocol2.AXIS_MAGIC,
43
44
  AXIS_OPCODES: () => AXIS_OPCODES,
44
- AXIS_VERSION: () => AXIS_VERSION,
45
+ AXIS_UPLOAD_FILE_STORE: () => AXIS_UPLOAD_FILE_STORE,
46
+ AXIS_UPLOAD_RECEIPT_SIGNER: () => AXIS_UPLOAD_RECEIPT_SIGNER,
47
+ AXIS_UPLOAD_SESSION_STORE: () => AXIS_UPLOAD_SESSION_STORE,
48
+ AXIS_VERSION: () => import_axis_protocol2.AXIS_VERSION,
45
49
  Ats1Codec: () => ats1_exports,
50
+ AxisFilesDownloadHandler: () => AxisFilesDownloadHandler,
51
+ AxisFilesFinalizeHandler: () => AxisFilesFinalizeHandler,
46
52
  AxisFrameZ: () => AxisFrameZ,
47
53
  AxisIdDto: () => AxisIdDto,
48
54
  AxisPacketTags: () => T,
49
55
  AxisPartialType: () => AxisPartialType,
50
56
  AxisResponseDto: () => AxisResponseDto,
51
57
  AxisTlvDto: () => AxisTlvDto,
52
- BodyProfile: () => BodyProfile,
58
+ BodyProfile: () => import_axis_protocol2.BodyProfile,
53
59
  CAPABILITIES: () => CAPABILITIES,
54
60
  ContractViolationError: () => ContractViolationError,
55
61
  DEFAULT_CONTRACTS: () => DEFAULT_CONTRACTS,
56
62
  DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
57
63
  Decision: () => Decision,
58
- ERR_BAD_SIGNATURE: () => ERR_BAD_SIGNATURE,
59
- ERR_CONTRACT_VIOLATION: () => ERR_CONTRACT_VIOLATION,
60
- ERR_INVALID_PACKET: () => ERR_INVALID_PACKET,
61
- ERR_REPLAY_DETECTED: () => ERR_REPLAY_DETECTED,
64
+ DiskUploadFileStore: () => DiskUploadFileStore,
65
+ ERR_BAD_SIGNATURE: () => import_axis_protocol2.ERR_BAD_SIGNATURE,
66
+ ERR_CONTRACT_VIOLATION: () => import_axis_protocol2.ERR_CONTRACT_VIOLATION,
67
+ ERR_INVALID_PACKET: () => import_axis_protocol2.ERR_INVALID_PACKET,
68
+ ERR_REPLAY_DETECTED: () => import_axis_protocol2.ERR_REPLAY_DETECTED,
62
69
  ExecutionMeter: () => ExecutionMeter,
63
70
  FALLBACK_CONTRACT: () => FALLBACK_CONTRACT,
64
- FLAG_BODY_TLV: () => FLAG_BODY_TLV,
65
- FLAG_CHAIN_REQ: () => FLAG_CHAIN_REQ,
66
- FLAG_HAS_WITNESS: () => FLAG_HAS_WITNESS,
71
+ FLAG_BODY_TLV: () => import_axis_protocol2.FLAG_BODY_TLV,
72
+ FLAG_CHAIN_REQ: () => import_axis_protocol2.FLAG_CHAIN_REQ,
73
+ FLAG_HAS_WITNESS: () => import_axis_protocol2.FLAG_HAS_WITNESS,
67
74
  HANDLER_METADATA_KEY: () => HANDLER_METADATA_KEY,
68
75
  Handler: () => Handler,
76
+ INTENT_BODY_KEY: () => INTENT_BODY_KEY,
69
77
  INTENT_METADATA_KEY: () => INTENT_METADATA_KEY,
70
78
  INTENT_REQUIREMENTS: () => INTENT_REQUIREMENTS,
71
79
  INTENT_ROUTES_KEY: () => INTENT_ROUTES_KEY,
72
80
  INTENT_SENSITIVITY_MAP: () => INTENT_SENSITIVITY_MAP,
81
+ INTENT_SENSORS_KEY: () => INTENT_SENSORS_KEY,
73
82
  INTENT_TIMEOUTS: () => INTENT_TIMEOUTS,
74
83
  Intent: () => Intent,
84
+ IntentBody: () => IntentBody,
75
85
  IntentRouter: () => IntentRouter,
76
86
  IntentSensitivity: () => IntentSensitivity,
77
- MAX_BODY_LEN: () => MAX_BODY_LEN,
78
- MAX_FRAME_LEN: () => MAX_FRAME_LEN,
79
- MAX_HDR_LEN: () => MAX_HDR_LEN,
80
- MAX_SIG_LEN: () => MAX_SIG_LEN,
81
- NCERT_ALG: () => NCERT_ALG,
82
- NCERT_EXP: () => NCERT_EXP,
83
- NCERT_ISSUER_KID: () => NCERT_ISSUER_KID,
84
- NCERT_KID: () => NCERT_KID,
85
- NCERT_NBF: () => NCERT_NBF,
86
- NCERT_NODE_ID: () => NCERT_NODE_ID,
87
- NCERT_PAYLOAD: () => NCERT_PAYLOAD,
88
- NCERT_PUB: () => NCERT_PUB,
89
- NCERT_SCOPE: () => NCERT_SCOPE,
90
- NCERT_SIG: () => NCERT_SIG,
87
+ IntentSensors: () => IntentSensors,
88
+ MAX_BODY_LEN: () => import_axis_protocol2.MAX_BODY_LEN,
89
+ MAX_FRAME_LEN: () => import_axis_protocol2.MAX_FRAME_LEN,
90
+ MAX_HDR_LEN: () => import_axis_protocol2.MAX_HDR_LEN,
91
+ MAX_SIG_LEN: () => import_axis_protocol2.MAX_SIG_LEN,
92
+ NCERT_ALG: () => import_axis_protocol2.NCERT_ALG,
93
+ NCERT_EXP: () => import_axis_protocol2.NCERT_EXP,
94
+ NCERT_ISSUER_KID: () => import_axis_protocol2.NCERT_ISSUER_KID,
95
+ NCERT_KID: () => import_axis_protocol2.NCERT_KID,
96
+ NCERT_NBF: () => import_axis_protocol2.NCERT_NBF,
97
+ NCERT_NODE_ID: () => import_axis_protocol2.NCERT_NODE_ID,
98
+ NCERT_PAYLOAD: () => import_axis_protocol2.NCERT_PAYLOAD,
99
+ NCERT_PUB: () => import_axis_protocol2.NCERT_PUB,
100
+ NCERT_SCOPE: () => import_axis_protocol2.NCERT_SCOPE,
101
+ NCERT_SIG: () => import_axis_protocol2.NCERT_SIG,
91
102
  PROOF_CAPABILITIES: () => PROOF_CAPABILITIES,
92
- PROOF_CAPSULE: () => PROOF_CAPSULE,
93
- PROOF_JWT: () => PROOF_JWT,
94
- PROOF_LOOM: () => PROOF_LOOM,
95
- PROOF_MTLS: () => PROOF_MTLS,
96
- PROOF_NONE: () => PROOF_NONE,
97
- PROOF_WITNESS: () => PROOF_WITNESS,
98
- ProofType: () => ProofType,
103
+ PROOF_CAPSULE: () => import_axis_protocol2.PROOF_CAPSULE,
104
+ PROOF_JWT: () => import_axis_protocol2.PROOF_JWT,
105
+ PROOF_LOOM: () => import_axis_protocol2.PROOF_LOOM,
106
+ PROOF_MTLS: () => import_axis_protocol2.PROOF_MTLS,
107
+ PROOF_NONE: () => import_axis_protocol2.PROOF_NONE,
108
+ PROOF_WITNESS: () => import_axis_protocol2.PROOF_WITNESS,
109
+ ProofType: () => import_axis_protocol2.ProofType,
99
110
  RESPONSE_TAG_CREATED_AT: () => RESPONSE_TAG_CREATED_AT,
100
111
  RESPONSE_TAG_CREATED_BY: () => RESPONSE_TAG_CREATED_BY,
101
112
  RESPONSE_TAG_ID: () => RESPONSE_TAG_ID,
@@ -107,38 +118,39 @@ __export(index_exports, {
107
118
  Schema2012_PasskeyLoginVerifyRes: () => Schema2012_PasskeyLoginVerifyRes,
108
119
  Schema2021_PasskeyRegisterOptionsReq: () => Schema2021_PasskeyRegisterOptionsReq,
109
120
  SensorDecisions: () => SensorDecisions,
110
- TLV_ACTOR_ID: () => TLV_ACTOR_ID,
111
- TLV_AUD: () => TLV_AUD,
112
- TLV_BODY_ARR: () => TLV_BODY_ARR,
113
- TLV_BODY_OBJ: () => TLV_BODY_OBJ,
114
- TLV_CAPSULE: () => TLV_CAPSULE,
115
- TLV_EFFECT: () => TLV_EFFECT,
116
- TLV_ERROR_CODE: () => TLV_ERROR_CODE,
117
- TLV_ERROR_MSG: () => TLV_ERROR_MSG,
121
+ TLV: () => import_axis_protocol.TLV,
122
+ TLV_ACTOR_ID: () => import_axis_protocol2.TLV_ACTOR_ID,
123
+ TLV_AUD: () => import_axis_protocol2.TLV_AUD,
124
+ TLV_BODY_ARR: () => import_axis_protocol2.TLV_BODY_ARR,
125
+ TLV_BODY_OBJ: () => import_axis_protocol2.TLV_BODY_OBJ,
126
+ TLV_CAPSULE: () => import_axis_protocol2.TLV_CAPSULE,
127
+ TLV_EFFECT: () => import_axis_protocol2.TLV_EFFECT,
128
+ TLV_ERROR_CODE: () => import_axis_protocol2.TLV_ERROR_CODE,
129
+ TLV_ERROR_MSG: () => import_axis_protocol2.TLV_ERROR_MSG,
118
130
  TLV_FIELDS_KEY: () => TLV_FIELDS_KEY,
119
- TLV_INDEX: () => TLV_INDEX,
120
- TLV_INTENT: () => TLV_INTENT,
121
- TLV_KID: () => TLV_KID,
122
- TLV_LOOM_PRESENCE_ID: () => TLV_LOOM_PRESENCE_ID,
123
- TLV_LOOM_THREAD_HASH: () => TLV_LOOM_THREAD_HASH,
124
- TLV_LOOM_WRIT: () => TLV_LOOM_WRIT,
125
- TLV_NODE: () => TLV_NODE,
126
- TLV_NODE_CERT_HASH: () => TLV_NODE_CERT_HASH,
127
- TLV_NODE_KID: () => TLV_NODE_KID,
128
- TLV_NONCE: () => TLV_NONCE,
129
- TLV_OFFSET: () => TLV_OFFSET,
130
- TLV_OK: () => TLV_OK,
131
- TLV_PID: () => TLV_PID,
132
- TLV_PREV_HASH: () => TLV_PREV_HASH,
133
- TLV_PROOF_REF: () => TLV_PROOF_REF,
134
- TLV_PROOF_TYPE: () => TLV_PROOF_TYPE,
135
- TLV_REALM: () => TLV_REALM,
136
- TLV_RECEIPT_HASH: () => TLV_RECEIPT_HASH,
137
- TLV_RID: () => TLV_RID,
138
- TLV_SHA256_CHUNK: () => TLV_SHA256_CHUNK,
139
- TLV_TRACE_ID: () => TLV_TRACE_ID,
140
- TLV_TS: () => TLV_TS,
141
- TLV_UPLOAD_ID: () => TLV_UPLOAD_ID,
131
+ TLV_INDEX: () => import_axis_protocol2.TLV_INDEX,
132
+ TLV_INTENT: () => import_axis_protocol2.TLV_INTENT,
133
+ TLV_KID: () => import_axis_protocol2.TLV_KID,
134
+ TLV_LOOM_PRESENCE_ID: () => import_axis_protocol2.TLV_LOOM_PRESENCE_ID,
135
+ TLV_LOOM_THREAD_HASH: () => import_axis_protocol2.TLV_LOOM_THREAD_HASH,
136
+ TLV_LOOM_WRIT: () => import_axis_protocol2.TLV_LOOM_WRIT,
137
+ TLV_NODE: () => import_axis_protocol2.TLV_NODE,
138
+ TLV_NODE_CERT_HASH: () => import_axis_protocol2.TLV_NODE_CERT_HASH,
139
+ TLV_NODE_KID: () => import_axis_protocol2.TLV_NODE_KID,
140
+ TLV_NONCE: () => import_axis_protocol2.TLV_NONCE,
141
+ TLV_OFFSET: () => import_axis_protocol2.TLV_OFFSET,
142
+ TLV_OK: () => import_axis_protocol2.TLV_OK,
143
+ TLV_PID: () => import_axis_protocol2.TLV_PID,
144
+ TLV_PREV_HASH: () => import_axis_protocol2.TLV_PREV_HASH,
145
+ TLV_PROOF_REF: () => import_axis_protocol2.TLV_PROOF_REF,
146
+ TLV_PROOF_TYPE: () => import_axis_protocol2.TLV_PROOF_TYPE,
147
+ TLV_REALM: () => import_axis_protocol2.TLV_REALM,
148
+ TLV_RECEIPT_HASH: () => import_axis_protocol2.TLV_RECEIPT_HASH,
149
+ TLV_RID: () => import_axis_protocol2.TLV_RID,
150
+ TLV_SHA256_CHUNK: () => import_axis_protocol2.TLV_SHA256_CHUNK,
151
+ TLV_TRACE_ID: () => import_axis_protocol2.TLV_TRACE_ID,
152
+ TLV_TS: () => import_axis_protocol2.TLV_TS,
153
+ TLV_UPLOAD_ID: () => import_axis_protocol2.TLV_UPLOAD_ID,
142
154
  TLV_VALIDATORS_KEY: () => TLV_VALIDATORS_KEY,
143
155
  TlvEnum: () => TlvEnum,
144
156
  TlvField: () => TlvField,
@@ -163,18 +175,18 @@ __export(index_exports, {
163
175
  classifyIntent: () => classifyIntent,
164
176
  computeReceiptHash: () => computeReceiptHash,
165
177
  computeSignaturePayload: () => computeSignaturePayload,
166
- decodeArray: () => decodeArray,
178
+ decodeArray: () => import_axis_protocol.decodeArray,
167
179
  decodeAxis1Frame: () => decodeAxis1Frame,
168
180
  decodeFrame: () => decodeFrame,
169
- decodeObject: () => decodeObject,
170
- decodeTLVs: () => decodeTLVs,
171
- decodeTLVsList: () => decodeTLVsList,
172
- decodeVarint: () => decodeVarint,
181
+ decodeObject: () => import_axis_protocol.decodeObject,
182
+ decodeTLVs: () => import_axis_protocol.decodeTLVs,
183
+ decodeTLVsList: () => import_axis_protocol.decodeTLVsList,
184
+ decodeVarint: () => import_axis_protocol3.decodeVarint,
173
185
  encVarint: () => encVarint,
174
186
  encodeAxis1Frame: () => encodeAxis1Frame,
175
187
  encodeFrame: () => encodeFrame,
176
- encodeTLVs: () => encodeTLVs,
177
- encodeVarint: () => encodeVarint,
188
+ encodeTLVs: () => import_axis_protocol.encodeTLVs,
189
+ encodeVarint: () => import_axis_protocol3.encodeVarint,
178
190
  extractDtoSchema: () => extractDtoSchema,
179
191
  generateEd25519KeyPair: () => generateEd25519KeyPair,
180
192
  getSignTarget: () => getSignTarget,
@@ -201,7 +213,7 @@ __export(index_exports, {
201
213
  unpackPasskeyRegisterOptionsReq: () => unpackPasskeyRegisterOptionsReq,
202
214
  utf8: () => utf8,
203
215
  validateFrameShape: () => validateFrameShape,
204
- varintLength: () => varintLength,
216
+ varintLength: () => import_axis_protocol3.varintLength,
205
217
  varintU: () => varintU,
206
218
  verifyFrameSignature: () => verifyFrameSignature
207
219
  });
@@ -244,8 +256,26 @@ function Intent(action, options) {
244
256
  };
245
257
  }
246
258
 
247
- // src/decorators/tlv-field.decorator.ts
259
+ // src/decorators/intent-body.decorator.ts
248
260
  var import_reflect_metadata2 = require("reflect-metadata");
261
+ var INTENT_BODY_KEY = "axis:intent:body";
262
+ function IntentBody(decoder) {
263
+ return (target, propertyKey) => {
264
+ Reflect.defineMetadata(INTENT_BODY_KEY, decoder, target, propertyKey);
265
+ };
266
+ }
267
+
268
+ // src/decorators/intent-sensors.decorator.ts
269
+ var import_reflect_metadata3 = require("reflect-metadata");
270
+ var INTENT_SENSORS_KEY = "axis:intent:sensors";
271
+ function IntentSensors(sensors) {
272
+ return (target, propertyKey) => {
273
+ Reflect.defineMetadata(INTENT_SENSORS_KEY, sensors, target, propertyKey);
274
+ };
275
+ }
276
+
277
+ // src/decorators/tlv-field.decorator.ts
278
+ var import_reflect_metadata4 = require("reflect-metadata");
249
279
  var TLV_FIELDS_KEY = "axis:tlv:fields";
250
280
  var TLV_VALIDATORS_KEY = "axis:tlv:validators";
251
281
  function TlvField(tag, options) {
@@ -303,144 +333,14 @@ function TlvRange(min, max, message) {
303
333
  }
304
334
 
305
335
  // src/decorators/dto-schema.util.ts
306
- var import_reflect_metadata3 = require("reflect-metadata");
307
-
308
- // src/core/varint.ts
309
- function encodeVarint(value) {
310
- if (value < 0) throw new Error("Varint must be unsigned");
311
- const bytes2 = [];
312
- while (true) {
313
- const byte = value & 127;
314
- value >>>= 7;
315
- if (value === 0) {
316
- bytes2.push(byte);
317
- break;
318
- }
319
- bytes2.push(byte | 128);
320
- }
321
- return new Uint8Array(bytes2);
322
- }
323
- function decodeVarint(buf, offset = 0) {
324
- let value = 0;
325
- let shift = 0;
326
- let length = 0;
327
- while (true) {
328
- if (offset + length >= buf.length) {
329
- throw new Error("Varint decode out of bounds");
330
- }
331
- const byte = buf[offset + length];
332
- value += (byte & 127) * Math.pow(2, shift);
333
- length++;
334
- shift += 7;
335
- if ((byte & 128) === 0) {
336
- break;
337
- }
338
- if (length > 8) throw new Error("Varint too large");
339
- }
340
- return { value, length };
341
- }
342
- function varintLength(value) {
343
- if (value < 0) throw new Error("Varint must be unsigned");
344
- let len = 0;
345
- do {
346
- value >>>= 7;
347
- len++;
348
- } while (value !== 0);
349
- return len;
350
- }
336
+ var import_reflect_metadata5 = require("reflect-metadata");
351
337
 
352
338
  // src/core/tlv.ts
353
- function encodeTLVs(tlvs) {
354
- const sorted = [...tlvs].sort((a, b) => a.type - b.type);
355
- for (let i = 0; i < sorted.length - 1; i++) {
356
- if (sorted[i].type === sorted[i + 1].type) {
357
- throw new Error(`Duplicate TLV type: ${sorted[i].type}`);
358
- }
359
- }
360
- let totalSize = 0;
361
- for (const t of sorted) {
362
- totalSize += varintLength(t.type);
363
- totalSize += varintLength(t.value.length);
364
- totalSize += t.value.length;
365
- }
366
- const buf = new Uint8Array(totalSize);
367
- let offset = 0;
368
- for (const t of sorted) {
369
- const typeBytes = encodeVarint(t.type);
370
- buf.set(typeBytes, offset);
371
- offset += typeBytes.length;
372
- const lenBytes = encodeVarint(t.value.length);
373
- buf.set(lenBytes, offset);
374
- offset += lenBytes.length;
375
- buf.set(t.value, offset);
376
- offset += t.value.length;
377
- }
378
- return buf;
379
- }
380
- function decodeTLVsList(buf, maxItems = 1024) {
381
- const list = [];
382
- let offset = 0;
383
- while (offset < buf.length) {
384
- if (list.length >= maxItems) throw new Error("TLV_LIMIT");
385
- const { value: type, length: typeLen } = decodeVarint(buf, offset);
386
- offset += typeLen;
387
- const { value: len, length: lenLen } = decodeVarint(buf, offset);
388
- offset += lenLen;
389
- if (offset + len > buf.length) {
390
- throw new Error(`TLV violation: Length ${len} exceeds buffer`);
391
- }
392
- const value = buf.slice(offset, offset + len);
393
- list.push({ type, value });
394
- offset += len;
395
- }
396
- return list;
397
- }
398
- function decodeTLVs(buf) {
399
- const map2 = /* @__PURE__ */ new Map();
400
- let offset = 0;
401
- let lastType = -1;
402
- while (offset < buf.length) {
403
- const { value: type, length: typeLen } = decodeVarint(buf, offset);
404
- offset += typeLen;
405
- if (type <= lastType) {
406
- throw new Error(
407
- `TLV violation: Unsorted or duplicate type ${type} after ${lastType}`
408
- );
409
- }
410
- lastType = type;
411
- const { value: len, length: lenLen } = decodeVarint(buf, offset);
412
- offset += lenLen;
413
- if (offset + len > buf.length) {
414
- throw new Error(`TLV violation: Length ${len} exceeds buffer`);
415
- }
416
- const value = buf.slice(offset, offset + len);
417
- map2.set(type, value);
418
- offset += len;
419
- }
420
- return map2;
421
- }
422
- function decodeObject(bytes2, depth = 0, limits = { maxDepth: 8, maxItems: 128 }) {
423
- if (depth > limits.maxDepth) {
424
- throw new Error("OBJECT_DEPTH_EXCEEDED");
425
- }
426
- const map2 = decodeTLVs(bytes2);
427
- return map2;
428
- }
429
- function decodeArray(bytes2, itemType, maxItems = 256) {
430
- const list = decodeTLVsList(bytes2, maxItems);
431
- const items = [];
432
- for (const tlv2 of list) {
433
- if (tlv2.type !== itemType) {
434
- throw new Error(`INVALID_ARRAY_ITEM:${tlv2.type}`);
435
- }
436
- items.push(tlv2.value);
437
- }
438
- return items;
439
- }
339
+ var import_axis_protocol = require("@nextera.one/axis-protocol");
440
340
 
441
341
  // src/decorators/dto-schema.util.ts
442
342
  function extractDtoSchema(dto) {
443
- const fieldMetas = Reflect.getOwnMetadata(TLV_FIELDS_KEY, dto) || [];
343
+ const fieldMetas = Reflect.getMetadata(TLV_FIELDS_KEY, dto) || [];
444
344
  if (fieldMetas.length === 0) {
445
345
  throw new Error(
446
346
  `DTO class ${dto.name} has no @TlvField decorators \u2014 nothing to validate`
@@ -459,7 +359,7 @@ function extractDtoSchema(dto) {
459
359
  scope: m.options.scope
460
360
  };
461
361
  });
462
- const validatorMetas = Reflect.getOwnMetadata(TLV_VALIDATORS_KEY, dto) || [];
362
+ const validatorMetas = Reflect.getMetadata(TLV_VALIDATORS_KEY, dto) || [];
463
363
  const validators = /* @__PURE__ */ new Map();
464
364
  for (const vm of validatorMetas) {
465
365
  const tag = tagByProp.get(vm.property);
@@ -474,7 +374,7 @@ function extractDtoSchema(dto) {
474
374
  return { fields, validators };
475
375
  }
476
376
  function buildDtoDecoder(dto) {
477
- const fieldMetas = Reflect.getOwnMetadata(TLV_FIELDS_KEY, dto) || [];
377
+ const fieldMetas = Reflect.getMetadata(TLV_FIELDS_KEY, dto) || [];
478
378
  if (fieldMetas.length === 0) {
479
379
  throw new Error(
480
380
  `DTO class ${dto.name} has no @TlvField decorators \u2014 cannot build decoder`
@@ -485,7 +385,7 @@ function buildDtoDecoder(dto) {
485
385
  tagMap.set(m.tag, { property: m.property, kind: m.options.kind });
486
386
  }
487
387
  return (bodyBytes) => {
488
- const tlvMap2 = decodeTLVs(new Uint8Array(bodyBytes));
388
+ const tlvMap2 = (0, import_axis_protocol.decodeTLVs)(new Uint8Array(bodyBytes));
489
389
  const result = {};
490
390
  for (const [tag, raw] of tlvMap2) {
491
391
  const meta = tagMap.get(tag);
@@ -534,7 +434,7 @@ __decorateClass([
534
434
  ], AxisIdDto.prototype, "id", 2);
535
435
 
536
436
  // src/base/axis-partial-type.ts
537
- var import_reflect_metadata4 = require("reflect-metadata");
437
+ var import_reflect_metadata6 = require("reflect-metadata");
538
438
  function AxisPartialType(BaseDto) {
539
439
  class PartialDto extends BaseDto {
540
440
  }
@@ -581,10 +481,145 @@ __decorateClass([
581
481
 
582
482
  // src/engine/intent.router.ts
583
483
  var import_common2 = require("@nestjs/common");
484
+
485
+ // src/sensor/axis-sensor.ts
486
+ var Decision = /* @__PURE__ */ ((Decision2) => {
487
+ Decision2["ALLOW"] = "ALLOW";
488
+ Decision2["DENY"] = "DENY";
489
+ Decision2["THROTTLE"] = "THROTTLE";
490
+ Decision2["FLAG"] = "FLAG";
491
+ return Decision2;
492
+ })(Decision || {});
493
+ function normalizeSensorDecision(sensorDecision) {
494
+ if ("action" in sensorDecision) {
495
+ switch (sensorDecision.action) {
496
+ case "ALLOW":
497
+ return {
498
+ allow: true,
499
+ riskScore: 0,
500
+ reasons: [],
501
+ meta: sensorDecision.meta
502
+ };
503
+ case "DENY":
504
+ return {
505
+ allow: false,
506
+ riskScore: 100,
507
+ reasons: [sensorDecision.code, sensorDecision.reason].filter(
508
+ Boolean
509
+ ),
510
+ meta: sensorDecision.meta,
511
+ retryAfterMs: sensorDecision.retryAfterMs
512
+ };
513
+ case "THROTTLE":
514
+ return {
515
+ allow: false,
516
+ riskScore: 50,
517
+ reasons: ["RATE_LIMIT"],
518
+ retryAfterMs: sensorDecision.retryAfterMs,
519
+ meta: sensorDecision.meta
520
+ };
521
+ case "FLAG":
522
+ return {
523
+ allow: true,
524
+ riskScore: sensorDecision.scoreDelta,
525
+ reasons: sensorDecision.reasons,
526
+ meta: sensorDecision.meta
527
+ };
528
+ }
529
+ }
530
+ return {
531
+ allow: sensorDecision.allow,
532
+ riskScore: sensorDecision.riskScore,
533
+ reasons: sensorDecision.reasons,
534
+ tags: sensorDecision.tags,
535
+ meta: sensorDecision.meta,
536
+ tighten: sensorDecision.tighten,
537
+ retryAfterMs: sensorDecision.retryAfterMs
538
+ };
539
+ }
540
+ var SensorDecisions = {
541
+ allow(meta, tags) {
542
+ return {
543
+ decision: "ALLOW" /* ALLOW */,
544
+ allow: true,
545
+ riskScore: 0,
546
+ reasons: [],
547
+ tags,
548
+ meta
549
+ };
550
+ },
551
+ deny(code, reason, meta) {
552
+ return {
553
+ decision: "DENY" /* DENY */,
554
+ allow: false,
555
+ riskScore: 100,
556
+ code,
557
+ reasons: [code, reason].filter(Boolean),
558
+ meta
559
+ };
560
+ },
561
+ throttle(retryAfterMs, meta) {
562
+ return {
563
+ decision: "THROTTLE" /* THROTTLE */,
564
+ allow: false,
565
+ riskScore: 50,
566
+ retryAfterMs,
567
+ code: "RATE_LIMIT",
568
+ reasons: ["RATE_LIMIT"],
569
+ meta
570
+ };
571
+ },
572
+ flag(scoreDelta, reasons, meta) {
573
+ return {
574
+ decision: "FLAG" /* FLAG */,
575
+ allow: true,
576
+ riskScore: scoreDelta,
577
+ scoreDelta,
578
+ reasons,
579
+ meta
580
+ };
581
+ }
582
+ };
583
+
584
+ // src/engine/intent.router.ts
584
585
  var IntentRouter = class {
585
- constructor() {
586
+ constructor(moduleRef) {
587
+ this.moduleRef = moduleRef;
588
+ this.logger = new import_common2.Logger(IntentRouter.name);
586
589
  /** Internal registry of dynamic intent handlers */
587
590
  this.handlers = /* @__PURE__ */ new Map();
591
+ /** Per-intent sensor classes (resolved at call time) */
592
+ this.intentSensors = /* @__PURE__ */ new Map();
593
+ /** Per-intent body decoders */
594
+ this.intentDecoders = /* @__PURE__ */ new Map();
595
+ /** Per-intent TLV schemas */
596
+ this.intentSchemas = /* @__PURE__ */ new Map();
597
+ /** Per-intent custom validators */
598
+ this.intentValidators = /* @__PURE__ */ new Map();
599
+ /** Per-intent operation kind */
600
+ this.intentKinds = /* @__PURE__ */ new Map();
601
+ }
602
+ getSchema(intent) {
603
+ return this.intentSchemas.get(intent);
604
+ }
605
+ getValidators(intent) {
606
+ return this.intentValidators.get(intent);
607
+ }
608
+ has(intent) {
609
+ return this.handlers.has(intent) || IntentRouter.BUILTIN_INTENTS.has(intent);
610
+ }
611
+ getRegisteredIntents() {
612
+ return [...IntentRouter.BUILTIN_INTENTS, ...this.handlers.keys()];
613
+ }
614
+ getIntentEntry(intent) {
615
+ if (!this.has(intent)) return null;
616
+ return {
617
+ schema: this.intentSchemas.get(intent),
618
+ validators: this.intentValidators.get(intent),
619
+ hasSensors: this.intentSensors.has(intent),
620
+ builtin: IntentRouter.BUILTIN_INTENTS.has(intent),
621
+ kind: this.intentKinds.get(intent)
622
+ };
588
623
  }
589
624
  /**
590
625
  * Registers a handler for a specific intent.
@@ -620,6 +655,16 @@ var IntentRouter = class {
620
655
  } else {
621
656
  this.register(intentName, fn);
622
657
  }
658
+ this.registerIntentMeta(intentName, Object.getPrototypeOf(instance), String(route.methodName));
659
+ }
660
+ const proto = Object.getPrototypeOf(instance);
661
+ for (const key of Object.getOwnPropertyNames(proto)) {
662
+ const meta = Reflect.getMetadata(INTENT_METADATA_KEY, proto, key);
663
+ if (!meta?.intent) continue;
664
+ if (!this.handlers.has(meta.intent)) {
665
+ this.register(meta.intent, instance[key].bind(instance));
666
+ }
667
+ this.registerIntentMeta(meta.intent, proto, key);
623
668
  }
624
669
  }
625
670
  /**
@@ -643,6 +688,7 @@ var IntentRouter = class {
643
688
  intent = new TextDecoder().decode(intentBytes);
644
689
  let effect;
645
690
  if (intent === "system.ping" || intent === "public.ping") {
691
+ this.logger.debug("PING received");
646
692
  effect = {
647
693
  ok: true,
648
694
  effect: "pong",
@@ -683,6 +729,7 @@ var IntentRouter = class {
683
729
  if (!innerIntent) {
684
730
  throw new Error("INTENT.EXEC missing inner intent");
685
731
  }
732
+ this.logger.debug(`EXEC: routing to inner intent '${innerIntent}'`);
686
733
  const innerFrame = {
687
734
  ...frame,
688
735
  headers: new Map(frame.headers),
@@ -698,8 +745,23 @@ var IntentRouter = class {
698
745
  if (!handler) {
699
746
  throw new Error(`Intent not found: ${intent}`);
700
747
  }
748
+ const sensorClasses = this.intentSensors.get(intent);
749
+ if (sensorClasses && sensorClasses.length > 0) {
750
+ await this.runIntentSensors(sensorClasses, intent, frame);
751
+ }
752
+ const decoder = this.intentDecoders.get(intent);
753
+ let decodedBody = frame.body;
754
+ if (decoder) {
755
+ try {
756
+ decodedBody = decoder(Buffer.from(frame.body));
757
+ } catch (decodeErr) {
758
+ throw new Error(
759
+ `IntentBody decode failed for ${intent}: ${decodeErr.message}`
760
+ );
761
+ }
762
+ }
701
763
  if (typeof handler === "function") {
702
- const resultBody = await handler(frame.body, frame.headers);
764
+ const resultBody = decoder ? await handler(decodedBody, frame.headers) : await handler(frame.body, frame.headers);
703
765
  effect = {
704
766
  ok: true,
705
767
  effect: "complete",
@@ -709,10 +771,7 @@ var IntentRouter = class {
709
771
  if (typeof handler.handle === "function") {
710
772
  effect = await handler.handle(frame);
711
773
  } else if (typeof handler.execute === "function") {
712
- const bodyRes = await handler.execute(
713
- frame.body,
714
- frame.headers
715
- );
774
+ const bodyRes = decoder ? await handler.execute(decodedBody, frame.headers) : await handler.execute(frame.body, frame.headers);
716
775
  effect = {
717
776
  ok: true,
718
777
  effect: "complete",
@@ -725,99 +784,137 @@ var IntentRouter = class {
725
784
  }
726
785
  }
727
786
  }
728
- this.recordLatency(intent, start);
787
+ this.logIntent(intent, start, true);
729
788
  return effect;
730
789
  } catch (e) {
731
- console.error(`Error routing intent ${intent}:`, e.message);
790
+ this.logIntent(intent, start, false, e.message);
732
791
  throw e;
733
792
  }
734
793
  }
735
- recordLatency(intent, start) {
794
+ logIntent(intent, start, ok, error) {
736
795
  const diff = process.hrtime(start);
737
- void diff;
796
+ const ms = (diff[0] * 1e3 + diff[1] / 1e6).toFixed(2);
797
+ if (ok) {
798
+ this.logger.debug(`${intent} completed in ${ms}ms`);
799
+ } else {
800
+ this.logger.warn(`${intent} failed in ${ms}ms - ${error}`);
801
+ }
802
+ }
803
+ registerIntentMeta(intent, proto, methodName) {
804
+ const decoder = Reflect.getMetadata(INTENT_BODY_KEY, proto, methodName);
805
+ if (decoder) {
806
+ this.intentDecoders.set(intent, decoder);
807
+ }
808
+ const sensors = Reflect.getMetadata(INTENT_SENSORS_KEY, proto, methodName);
809
+ if (sensors && Array.isArray(sensors) && sensors.length > 0) {
810
+ this.intentSensors.set(intent, sensors);
811
+ }
812
+ const meta = Reflect.getMetadata(INTENT_METADATA_KEY, proto, methodName);
813
+ if (meta) {
814
+ this.storeSchema(meta);
815
+ if (meta.kind) {
816
+ this.intentKinds.set(intent, meta.kind);
817
+ }
818
+ }
819
+ }
820
+ async runIntentSensors(sensorClasses, intent, frame) {
821
+ if (!this.moduleRef) return;
822
+ for (const SensorClass of sensorClasses) {
823
+ let sensor;
824
+ try {
825
+ sensor = this.moduleRef.get(SensorClass, { strict: false });
826
+ } catch {
827
+ this.logger.warn(
828
+ `@IntentSensors: could not resolve ${SensorClass.name} for ${intent}`
829
+ );
830
+ continue;
831
+ }
832
+ const sensorInput = {
833
+ rawBytes: frame.body,
834
+ intent,
835
+ body: frame.body,
836
+ headerTLVs: frame.headers,
837
+ metadata: { phase: "intent", intent }
838
+ };
839
+ if (sensor.supports && !sensor.supports(sensorInput)) continue;
840
+ const decision = normalizeSensorDecision(await sensor.run(sensorInput));
841
+ if (!decision.allow) {
842
+ const reason = decision.reasons[0] || `${sensor.name}:DENIED`;
843
+ this.logger.warn(
844
+ `Intent sensor ${sensor.name} denied ${intent}: ${reason}`
845
+ );
846
+ throw new Error(`SENSOR_DENY:${reason}`);
847
+ }
848
+ }
849
+ }
850
+ storeSchema(meta) {
851
+ if (meta.dto) {
852
+ if (meta.tlv && meta.tlv.length > 0) {
853
+ this.logger.warn(
854
+ `${meta.intent}: both 'dto' and 'tlv' specified - using dto, ignoring tlv`
855
+ );
856
+ }
857
+ const extracted = extractDtoSchema(meta.dto);
858
+ const schema2 = {
859
+ intent: meta.intent,
860
+ version: 1,
861
+ bodyProfile: meta.bodyProfile || "TLV_MAP",
862
+ fields: extracted.fields.map((f) => ({
863
+ name: f.name,
864
+ tlv: f.tag,
865
+ kind: f.kind,
866
+ required: f.required,
867
+ maxLen: f.maxLen,
868
+ max: f.max,
869
+ scope: f.scope
870
+ }))
871
+ };
872
+ this.intentSchemas.set(meta.intent, schema2);
873
+ if (extracted.validators.size > 0) {
874
+ this.intentValidators.set(meta.intent, extracted.validators);
875
+ }
876
+ if (!this.intentDecoders.has(meta.intent)) {
877
+ this.intentDecoders.set(meta.intent, buildDtoDecoder(meta.dto));
878
+ }
879
+ return;
880
+ }
881
+ if (!meta.tlv || meta.tlv.length === 0) return;
882
+ const schema = {
883
+ intent: meta.intent,
884
+ version: 1,
885
+ bodyProfile: meta.bodyProfile || "TLV_MAP",
886
+ fields: meta.tlv.map((f) => ({
887
+ name: f.name,
888
+ tlv: f.tag,
889
+ kind: f.kind,
890
+ required: f.required,
891
+ maxLen: f.maxLen,
892
+ max: f.max,
893
+ scope: f.scope
894
+ }))
895
+ };
896
+ this.intentSchemas.set(meta.intent, schema);
738
897
  }
739
898
  };
899
+ /** Intents handled inline in route() — not in `handlers` map */
900
+ IntentRouter.BUILTIN_INTENTS = /* @__PURE__ */ new Set([
901
+ "system.ping",
902
+ "public.ping",
903
+ "system.time",
904
+ "system.echo",
905
+ "INTENT.EXEC",
906
+ "axis.intent.exec"
907
+ ]);
740
908
  IntentRouter = __decorateClass([
741
- (0, import_common2.Injectable)()
909
+ (0, import_common2.Injectable)(),
910
+ __decorateParam(0, (0, import_common2.Optional)())
742
911
  ], IntentRouter);
743
912
 
744
913
  // src/core/constants.ts
745
- var AXIS_MAGIC = new Uint8Array([65, 88, 73, 83, 49]);
746
- var AXIS_VERSION = 1;
747
- var MAX_HDR_LEN = 2048;
748
- var MAX_BODY_LEN = 65536;
749
- var MAX_SIG_LEN = 128;
750
- var MAX_FRAME_LEN = 70 * 1024;
751
- var FLAG_BODY_TLV = 1;
752
- var FLAG_CHAIN_REQ = 2;
753
- var FLAG_HAS_WITNESS = 4;
754
- var TLV_PID = 1;
755
- var TLV_TS = 2;
756
- var TLV_INTENT = 3;
757
- var TLV_ACTOR_ID = 4;
758
- var TLV_PROOF_TYPE = 5;
759
- var TLV_PROOF_REF = 6;
760
- var TLV_NONCE = 7;
761
- var TLV_AUD = 8;
762
- var TLV_REALM = TLV_AUD;
763
- var TLV_NODE = 9;
764
- var TLV_TRACE_ID = 10;
765
- var TLV_KID = 11;
766
- var TLV_RID = 15;
767
- var TLV_OK = 16;
768
- var TLV_EFFECT = 17;
769
- var TLV_ERROR_CODE = 18;
770
- var TLV_ERROR_MSG = 19;
771
- var TLV_PREV_HASH = 20;
772
- var TLV_RECEIPT_HASH = 21;
773
- var TLV_NODE_KID = 30;
774
- var TLV_NODE_CERT_HASH = 34;
775
- var TLV_LOOM_PRESENCE_ID = 91;
776
- var TLV_LOOM_WRIT = 92;
777
- var TLV_LOOM_THREAD_HASH = 93;
778
- var TLV_UPLOAD_ID = 70;
779
- var TLV_INDEX = 71;
780
- var TLV_OFFSET = 72;
781
- var TLV_SHA256_CHUNK = 73;
782
- var TLV_CAPSULE = 90;
783
- var TLV_BODY_OBJ = 254;
784
- var TLV_BODY_ARR = 255;
785
- var NCERT_NODE_ID = 1;
786
- var NCERT_KID = 2;
787
- var NCERT_ALG = 3;
788
- var NCERT_PUB = 4;
789
- var NCERT_NBF = 5;
790
- var NCERT_EXP = 6;
791
- var NCERT_SCOPE = 7;
792
- var NCERT_ISSUER_KID = 8;
793
- var NCERT_PAYLOAD = 50;
794
- var NCERT_SIG = 51;
795
- var PROOF_NONE = 0;
796
- var PROOF_CAPSULE = 1;
797
- var PROOF_JWT = 2;
798
- var PROOF_MTLS = 3;
799
- var PROOF_LOOM = 4;
800
- var PROOF_WITNESS = 5;
801
- var ProofType = /* @__PURE__ */ ((ProofType2) => {
802
- ProofType2[ProofType2["NONE"] = 0] = "NONE";
803
- ProofType2[ProofType2["CAPSULE"] = 1] = "CAPSULE";
804
- ProofType2[ProofType2["JWT"] = 2] = "JWT";
805
- ProofType2[ProofType2["MTLS"] = 3] = "MTLS";
806
- ProofType2[ProofType2["LOOM"] = 4] = "LOOM";
807
- ProofType2[ProofType2["WITNESS"] = 5] = "WITNESS";
808
- return ProofType2;
809
- })(ProofType || {});
810
- var BodyProfile = /* @__PURE__ */ ((BodyProfile2) => {
811
- BodyProfile2[BodyProfile2["RAW"] = 0] = "RAW";
812
- BodyProfile2[BodyProfile2["TLV_MAP"] = 1] = "TLV_MAP";
813
- BodyProfile2[BodyProfile2["OBJ"] = 2] = "OBJ";
814
- BodyProfile2[BodyProfile2["ARR"] = 3] = "ARR";
815
- return BodyProfile2;
816
- })(BodyProfile || {});
817
- var ERR_INVALID_PACKET = "INVALID_PACKET";
818
- var ERR_BAD_SIGNATURE = "BAD_SIGNATURE";
819
- var ERR_REPLAY_DETECTED = "REPLAY_DETECTED";
820
- var ERR_CONTRACT_VIOLATION = "CONTRACT_VIOLATION";
914
+ var import_axis_protocol2 = require("@nextera.one/axis-protocol");
915
+
916
+ // src/core/varint.ts
917
+ var import_axis_protocol3 = require("@nextera.one/axis-protocol");
821
918
 
822
919
  // src/core/signature.ts
823
920
  var crypto = __toESM(require("crypto"));
@@ -838,28 +935,28 @@ var AxisFrameZ = z.object({
838
935
  sig: z.custom((v) => v instanceof Uint8Array)
839
936
  });
840
937
  function encodeFrame(frame) {
841
- const hdrBytes = encodeTLVs(
938
+ const hdrBytes = (0, import_axis_protocol.encodeTLVs)(
842
939
  Array.from(frame.headers.entries()).map(([t, v]) => ({
843
940
  type: t,
844
941
  value: v
845
942
  }))
846
943
  );
847
- if (hdrBytes.length > MAX_HDR_LEN) throw new Error("Header too large");
848
- if (frame.body.length > MAX_BODY_LEN) throw new Error("Body too large");
849
- if (frame.sig.length > MAX_SIG_LEN) throw new Error("Signature too large");
850
- const hdrLenBytes = encodeVarint(hdrBytes.length);
851
- const bodyLenBytes = encodeVarint(frame.body.length);
852
- const sigLenBytes = encodeVarint(frame.sig.length);
944
+ if (hdrBytes.length > import_axis_protocol2.MAX_HDR_LEN) throw new Error("Header too large");
945
+ if (frame.body.length > import_axis_protocol2.MAX_BODY_LEN) throw new Error("Body too large");
946
+ if (frame.sig.length > import_axis_protocol2.MAX_SIG_LEN) throw new Error("Signature too large");
947
+ const hdrLenBytes = (0, import_axis_protocol3.encodeVarint)(hdrBytes.length);
948
+ const bodyLenBytes = (0, import_axis_protocol3.encodeVarint)(frame.body.length);
949
+ const sigLenBytes = (0, import_axis_protocol3.encodeVarint)(frame.sig.length);
853
950
  const totalLen = 5 + // Magic (AXIS1)
854
951
  1 + // Version
855
952
  1 + // Flags
856
953
  hdrLenBytes.length + bodyLenBytes.length + sigLenBytes.length + hdrBytes.length + frame.body.length + frame.sig.length;
857
- if (totalLen > MAX_FRAME_LEN) throw new Error("Total frame too large");
954
+ if (totalLen > import_axis_protocol2.MAX_FRAME_LEN) throw new Error("Total frame too large");
858
955
  const buf = new Uint8Array(totalLen);
859
956
  let offset = 0;
860
- buf.set(AXIS_MAGIC, offset);
957
+ buf.set(import_axis_protocol2.AXIS_MAGIC, offset);
861
958
  offset += 5;
862
- buf[offset++] = AXIS_VERSION;
959
+ buf[offset++] = import_axis_protocol2.AXIS_VERSION;
863
960
  buf[offset++] = frame.flags;
864
961
  buf.set(hdrLenBytes, offset);
865
962
  offset += hdrLenBytes.length;
@@ -879,21 +976,21 @@ function decodeFrame(buf) {
879
976
  let offset = 0;
880
977
  if (offset + 5 > buf.length) throw new Error("Packet too short");
881
978
  for (let i = 0; i < 5; i++) {
882
- if (buf[offset + i] !== AXIS_MAGIC[i]) throw new Error("Invalid Magic");
979
+ if (buf[offset + i] !== import_axis_protocol2.AXIS_MAGIC[i]) throw new Error("Invalid Magic");
883
980
  }
884
981
  offset += 5;
885
982
  const ver = buf[offset++];
886
- if (ver !== AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);
983
+ if (ver !== import_axis_protocol2.AXIS_VERSION) throw new Error(`Unsupported version: ${ver}`);
887
984
  const flags = buf[offset++];
888
- const { value: hdrLen, length: hlLen } = decodeVarint(buf, offset);
985
+ const { value: hdrLen, length: hlLen } = (0, import_axis_protocol3.decodeVarint)(buf, offset);
889
986
  offset += hlLen;
890
- if (hdrLen > MAX_HDR_LEN) throw new Error("Header limit exceeded");
891
- const { value: bodyLen, length: blLen } = decodeVarint(buf, offset);
987
+ if (hdrLen > import_axis_protocol2.MAX_HDR_LEN) throw new Error("Header limit exceeded");
988
+ const { value: bodyLen, length: blLen } = (0, import_axis_protocol3.decodeVarint)(buf, offset);
892
989
  offset += blLen;
893
- if (bodyLen > MAX_BODY_LEN) throw new Error("Body limit exceeded");
894
- const { value: sigLen, length: slLen } = decodeVarint(buf, offset);
990
+ if (bodyLen > import_axis_protocol2.MAX_BODY_LEN) throw new Error("Body limit exceeded");
991
+ const { value: sigLen, length: slLen } = (0, import_axis_protocol3.decodeVarint)(buf, offset);
895
992
  offset += slLen;
896
- if (sigLen > MAX_SIG_LEN) throw new Error("Signature limit exceeded");
993
+ if (sigLen > import_axis_protocol2.MAX_SIG_LEN) throw new Error("Signature limit exceeded");
897
994
  if (offset + hdrLen + bodyLen + sigLen > buf.length) {
898
995
  throw new Error("Frame truncated");
899
996
  }
@@ -903,7 +1000,7 @@ function decodeFrame(buf) {
903
1000
  offset += bodyLen;
904
1001
  const sigBytes = buf.slice(offset, offset + sigLen);
905
1002
  offset += sigLen;
906
- const headers = decodeTLVs(hdrBytes);
1003
+ const headers = (0, import_axis_protocol.decodeTLVs)(hdrBytes);
907
1004
  return {
908
1005
  flags,
909
1006
  headers,
@@ -2130,22 +2227,22 @@ function decodeAxis1Frame(buf) {
2130
2227
  // src/types/packet.ts
2131
2228
  var T = {
2132
2229
  /** The specific intent or action (e.g., 'vault.create') */
2133
- INTENT: TLV_INTENT,
2230
+ INTENT: import_axis_protocol2.TLV_INTENT,
2134
2231
  /** Package identifier / ID */
2135
- PID: TLV_PID,
2232
+ PID: import_axis_protocol2.TLV_PID,
2136
2233
  /** Versioning of the intent schema */
2137
2234
  INTENT_VERSION: 10,
2138
2235
  // Defaulting to TRACE_ID for now or a new tag if available
2139
2236
  /** Unique identifier for the requesting actor */
2140
- ACTOR_ID: TLV_ACTOR_ID,
2237
+ ACTOR_ID: import_axis_protocol2.TLV_ACTOR_ID,
2141
2238
  /** Optional Capability Token identifier (16 bytes) */
2142
- CAPSULE_ID: TLV_PROOF_REF,
2239
+ CAPSULE_ID: import_axis_protocol2.TLV_PROOF_REF,
2143
2240
  /** Unique session/request identifier (16 bytes) */
2144
- NONCE: TLV_NONCE,
2241
+ NONCE: import_axis_protocol2.TLV_NONCE,
2145
2242
  /** High-precision Unix timestamp in milliseconds */
2146
- TS_MS: TLV_TS,
2243
+ TS_MS: import_axis_protocol2.TLV_TS,
2147
2244
  /** Proof type */
2148
- PROOF_TYPE: TLV_PROOF_TYPE,
2245
+ PROOF_TYPE: import_axis_protocol2.TLV_PROOF_TYPE,
2149
2246
  /** Standard binary body tag */
2150
2247
  BODY: 100,
2151
2248
  /** Standard JSON-encoded body tag */
@@ -2186,105 +2283,6 @@ function buildPacket(hdr, body, sig, flags = 0) {
2186
2283
  };
2187
2284
  }
2188
2285
 
2189
- // src/sensor/axis-sensor.ts
2190
- var Decision = /* @__PURE__ */ ((Decision2) => {
2191
- Decision2["ALLOW"] = "ALLOW";
2192
- Decision2["DENY"] = "DENY";
2193
- Decision2["THROTTLE"] = "THROTTLE";
2194
- Decision2["FLAG"] = "FLAG";
2195
- return Decision2;
2196
- })(Decision || {});
2197
- function normalizeSensorDecision(sensorDecision) {
2198
- if ("action" in sensorDecision) {
2199
- switch (sensorDecision.action) {
2200
- case "ALLOW":
2201
- return {
2202
- allow: true,
2203
- riskScore: 0,
2204
- reasons: [],
2205
- meta: sensorDecision.meta
2206
- };
2207
- case "DENY":
2208
- return {
2209
- allow: false,
2210
- riskScore: 100,
2211
- reasons: [sensorDecision.code, sensorDecision.reason].filter(
2212
- Boolean
2213
- ),
2214
- meta: sensorDecision.meta,
2215
- retryAfterMs: sensorDecision.retryAfterMs
2216
- };
2217
- case "THROTTLE":
2218
- return {
2219
- allow: false,
2220
- riskScore: 50,
2221
- reasons: ["RATE_LIMIT"],
2222
- retryAfterMs: sensorDecision.retryAfterMs,
2223
- meta: sensorDecision.meta
2224
- };
2225
- case "FLAG":
2226
- return {
2227
- allow: true,
2228
- riskScore: sensorDecision.scoreDelta,
2229
- reasons: sensorDecision.reasons,
2230
- meta: sensorDecision.meta
2231
- };
2232
- }
2233
- }
2234
- return {
2235
- allow: sensorDecision.allow,
2236
- riskScore: sensorDecision.riskScore,
2237
- reasons: sensorDecision.reasons,
2238
- tags: sensorDecision.tags,
2239
- meta: sensorDecision.meta,
2240
- tighten: sensorDecision.tighten,
2241
- retryAfterMs: sensorDecision.retryAfterMs
2242
- };
2243
- }
2244
- var SensorDecisions = {
2245
- allow(meta, tags) {
2246
- return {
2247
- decision: "ALLOW" /* ALLOW */,
2248
- allow: true,
2249
- riskScore: 0,
2250
- reasons: [],
2251
- tags,
2252
- meta
2253
- };
2254
- },
2255
- deny(code, reason, meta) {
2256
- return {
2257
- decision: "DENY" /* DENY */,
2258
- allow: false,
2259
- riskScore: 100,
2260
- code,
2261
- reasons: [code, reason].filter(Boolean),
2262
- meta
2263
- };
2264
- },
2265
- throttle(retryAfterMs, meta) {
2266
- return {
2267
- decision: "THROTTLE" /* THROTTLE */,
2268
- allow: false,
2269
- riskScore: 50,
2270
- retryAfterMs,
2271
- code: "RATE_LIMIT",
2272
- reasons: ["RATE_LIMIT"],
2273
- meta
2274
- };
2275
- },
2276
- flag(scoreDelta, reasons, meta) {
2277
- return {
2278
- decision: "FLAG" /* FLAG */,
2279
- allow: true,
2280
- riskScore: scoreDelta,
2281
- scoreDelta,
2282
- reasons,
2283
- meta
2284
- };
2285
- }
2286
- };
2287
-
2288
2286
  // src/security/scopes.ts
2289
2287
  function hasScope(scopes, required) {
2290
2288
  if (!Array.isArray(scopes) || scopes.length === 0) {
@@ -2322,12 +2320,12 @@ var CAPABILITIES = {
2322
2320
  witness: "witness"
2323
2321
  };
2324
2322
  var PROOF_CAPABILITIES = {
2325
- [PROOF_NONE]: [],
2326
- [PROOF_CAPSULE]: ["read", "write", "execute"],
2327
- [PROOF_JWT]: ["read"],
2328
- [PROOF_MTLS]: ["read", "write", "admin"],
2329
- [PROOF_LOOM]: ["read", "write", "execute"],
2330
- [PROOF_WITNESS]: ["read", "write", "execute", "witness"]
2323
+ [import_axis_protocol2.PROOF_NONE]: [],
2324
+ [import_axis_protocol2.PROOF_CAPSULE]: ["read", "write", "execute"],
2325
+ [import_axis_protocol2.PROOF_JWT]: ["read"],
2326
+ [import_axis_protocol2.PROOF_MTLS]: ["read", "write", "admin"],
2327
+ [import_axis_protocol2.PROOF_LOOM]: ["read", "write", "execute"],
2328
+ [import_axis_protocol2.PROOF_WITNESS]: ["read", "write", "execute", "witness"]
2331
2329
  };
2332
2330
  var INTENT_REQUIREMENTS = {
2333
2331
  "public.*": [],
@@ -2582,14 +2580,246 @@ function isTimestampValid(ts, skewSeconds = 120) {
2582
2580
  const diff = Math.abs(now - ts);
2583
2581
  return diff <= skewSeconds;
2584
2582
  }
2583
+
2584
+ // src/upload/axis-files.handlers.ts
2585
+ var import_common3 = require("@nestjs/common");
2586
+ var crypto2 = __toESM(require("crypto"));
2587
+
2588
+ // src/upload/upload.tokens.ts
2589
+ var AXIS_UPLOAD_SESSION_STORE = "AXIS_UPLOAD_SESSION_STORE";
2590
+ var AXIS_UPLOAD_FILE_STORE = "AXIS_UPLOAD_FILE_STORE";
2591
+ var AXIS_UPLOAD_RECEIPT_SIGNER = "AXIS_UPLOAD_RECEIPT_SIGNER";
2592
+
2593
+ // src/upload/axis-files.handlers.ts
2594
+ var AxisFilesDownloadHandler = class {
2595
+ constructor(sessions, files) {
2596
+ this.sessions = sessions;
2597
+ this.files = files;
2598
+ this.logger = new import_common3.Logger(AxisFilesDownloadHandler.name);
2599
+ this.name = "axis.files.download";
2600
+ this.open = true;
2601
+ this.description = "File download handler";
2602
+ }
2603
+ async execute(body, headers) {
2604
+ const h = headers;
2605
+ if (!h) throw new Error("MISSING_HEADERS");
2606
+ const uploadIdBytes = h.get(20);
2607
+ if (!uploadIdBytes) throw new Error("MISSING_UPLOAD_ID");
2608
+ const uploadId = new TextDecoder().decode(uploadIdBytes);
2609
+ let rangeStart = 0;
2610
+ let rangeLen = -1;
2611
+ const startBytes = h.get(21);
2612
+ if (startBytes) {
2613
+ const { value } = (0, import_axis_protocol3.decodeVarint)(startBytes);
2614
+ rangeStart = value;
2615
+ }
2616
+ const lenBytes = h.get(22);
2617
+ if (lenBytes) {
2618
+ const { value } = (0, import_axis_protocol3.decodeVarint)(lenBytes);
2619
+ rangeLen = value;
2620
+ }
2621
+ const session = await this.sessions.findByFileId(uploadId);
2622
+ if (!session) {
2623
+ throw new Error(`SESSION_NOT_FOUND: ${uploadId}`);
2624
+ }
2625
+ if (session.status !== "COMPLETE") {
2626
+ throw new Error(`FILE_NOT_READY: Status is ${session.status}`);
2627
+ }
2628
+ const stat = await this.files.statFinal(
2629
+ uploadId,
2630
+ session.filename
2631
+ );
2632
+ const fileSize = stat.size;
2633
+ if (rangeStart < 0) rangeStart = 0;
2634
+ if (rangeStart >= fileSize) throw new Error("RANGE_OUT_OF_BOUNDS");
2635
+ let end = fileSize;
2636
+ if (rangeLen >= 0) {
2637
+ end = Math.min(rangeStart + rangeLen, fileSize);
2638
+ }
2639
+ const actualLen = end - rangeStart;
2640
+ const buffer = await this.files.readFinalRange(
2641
+ uploadId,
2642
+ session.filename,
2643
+ rangeStart,
2644
+ actualLen
2645
+ );
2646
+ const responseHeaders = /* @__PURE__ */ new Map();
2647
+ responseHeaders.set(30, (0, import_axis_protocol3.encodeVarint)(fileSize));
2648
+ responseHeaders.set(31, (0, import_axis_protocol3.encodeVarint)(rangeStart));
2649
+ responseHeaders.set(32, (0, import_axis_protocol3.encodeVarint)(actualLen));
2650
+ return {
2651
+ ok: true,
2652
+ effect: "FILE_PART",
2653
+ body: buffer,
2654
+ headers: responseHeaders
2655
+ };
2656
+ }
2657
+ };
2658
+ __decorateClass([
2659
+ Intent("file.download", { absolute: true, kind: "read" })
2660
+ ], AxisFilesDownloadHandler.prototype, "execute", 1);
2661
+ AxisFilesDownloadHandler = __decorateClass([
2662
+ Handler("axis.files.download"),
2663
+ (0, import_common3.Injectable)(),
2664
+ __decorateParam(0, (0, import_common3.Inject)(AXIS_UPLOAD_SESSION_STORE)),
2665
+ __decorateParam(1, (0, import_common3.Inject)(AXIS_UPLOAD_FILE_STORE))
2666
+ ], AxisFilesDownloadHandler);
2667
+ var AxisFilesFinalizeHandler = class {
2668
+ constructor(sessions, files, keyring) {
2669
+ this.sessions = sessions;
2670
+ this.files = files;
2671
+ this.keyring = keyring;
2672
+ this.logger = new import_common3.Logger(AxisFilesFinalizeHandler.name);
2673
+ this.name = "axis.files.finalize";
2674
+ this.open = false;
2675
+ this.description = "File upload finalization handler";
2676
+ }
2677
+ async execute(body, headers) {
2678
+ const bodyStr = new TextDecoder().decode(body);
2679
+ const req = JSON.parse(bodyStr);
2680
+ const { fileId, expectedHash } = req;
2681
+ if (!fileId) throw new Error("MISSING_FILE_ID");
2682
+ const session = await this.sessions.findByFileId(fileId);
2683
+ if (!session) throw new Error("SESSION_NOT_FOUND");
2684
+ if (!await this.files.hasTemp(fileId)) {
2685
+ throw new Error("CHUNKS_NOT_FOUND");
2686
+ }
2687
+ const hash = crypto2.createHash("sha256");
2688
+ const rs = this.files.createTempReadStream(fileId);
2689
+ for await (const chunk of rs) {
2690
+ hash.update(chunk);
2691
+ }
2692
+ const finalHash = hash.digest("hex");
2693
+ if (expectedHash && finalHash !== expectedHash) {
2694
+ throw new Error("HASH_MISMATCH");
2695
+ }
2696
+ const finalPath = await this.files.moveTempToFinal(
2697
+ fileId,
2698
+ session.filename
2699
+ );
2700
+ await this.sessions.updateStatus(fileId, "COMPLETE", null);
2701
+ if (!this.keyring) {
2702
+ this.logger.warn("Receipt signer not configured; returning unsigned receipt");
2703
+ return {
2704
+ ok: true,
2705
+ effect: "FILE_FINALIZED",
2706
+ body: new TextEncoder().encode(
2707
+ JSON.stringify({
2708
+ uploadId: fileId,
2709
+ sha256_final: finalHash,
2710
+ totalSize: session.totalSize,
2711
+ tsMs: Date.now(),
2712
+ path: finalPath
2713
+ })
2714
+ )
2715
+ };
2716
+ }
2717
+ const receiptData = {
2718
+ uploadId: fileId,
2719
+ sha256_final: finalHash,
2720
+ totalSize: session.totalSize,
2721
+ tsMs: Date.now()
2722
+ };
2723
+ const receiptJson = JSON.stringify(receiptData);
2724
+ const receiptBody = new TextEncoder().encode(receiptJson);
2725
+ const SIG_PRESENT = 1;
2726
+ const responseFrame = {
2727
+ flags: SIG_PRESENT,
2728
+ headers: /* @__PURE__ */ new Map(),
2729
+ body: receiptBody,
2730
+ sig: new Uint8Array(0)
2731
+ };
2732
+ const signTarget = getSignTarget(responseFrame);
2733
+ const { sig, kid } = this.keyring.signActive(signTarget);
2734
+ responseFrame.sig = sig;
2735
+ return {
2736
+ ok: true,
2737
+ effect: "FILE_FINALIZED",
2738
+ data: encodeFrame(responseFrame),
2739
+ headers: /* @__PURE__ */ new Map([[1, new TextEncoder().encode(kid)]])
2740
+ };
2741
+ }
2742
+ };
2743
+ __decorateClass([
2744
+ Intent("file.finalize", { absolute: true, kind: "action" })
2745
+ ], AxisFilesFinalizeHandler.prototype, "execute", 1);
2746
+ AxisFilesFinalizeHandler = __decorateClass([
2747
+ Handler("axis.files.finalize"),
2748
+ (0, import_common3.Injectable)(),
2749
+ __decorateParam(0, (0, import_common3.Inject)(AXIS_UPLOAD_SESSION_STORE)),
2750
+ __decorateParam(1, (0, import_common3.Inject)(AXIS_UPLOAD_FILE_STORE)),
2751
+ __decorateParam(2, (0, import_common3.Optional)()),
2752
+ __decorateParam(2, (0, import_common3.Inject)(AXIS_UPLOAD_RECEIPT_SIGNER))
2753
+ ], AxisFilesFinalizeHandler);
2754
+
2755
+ // src/upload/disk-upload-file.store.ts
2756
+ var fs = __toESM(require("fs"));
2757
+ var path = __toESM(require("path"));
2758
+ var DiskUploadFileStore = class {
2759
+ constructor(options) {
2760
+ this.uploadDir = options.uploadDir;
2761
+ this.chunkDir = options.chunkDir;
2762
+ }
2763
+ getFinalPath(fileId, filename) {
2764
+ const safeFilename = filename ? path.basename(filename) : fileId;
2765
+ return path.join(this.uploadDir, safeFilename);
2766
+ }
2767
+ getTempPath(fileId) {
2768
+ const safeId = path.basename(fileId);
2769
+ return path.join(this.chunkDir, safeId);
2770
+ }
2771
+ async statFinal(fileId, filename) {
2772
+ const finalPath = this.getFinalPath(fileId, filename);
2773
+ if (!fs.existsSync(finalPath)) {
2774
+ throw new Error("FILE_MISSING_ON_DISK");
2775
+ }
2776
+ const stat = fs.statSync(finalPath);
2777
+ return { path: finalPath, size: stat.size };
2778
+ }
2779
+ async readFinalRange(fileId, filename, start, length) {
2780
+ const finalPath = this.getFinalPath(fileId, filename);
2781
+ const buffer = Buffer.alloc(length);
2782
+ const fd = fs.openSync(finalPath, "r");
2783
+ try {
2784
+ fs.readSync(fd, buffer, 0, length, start);
2785
+ } finally {
2786
+ fs.closeSync(fd);
2787
+ }
2788
+ return buffer;
2789
+ }
2790
+ async hasTemp(fileId) {
2791
+ const tempPath = this.getTempPath(fileId);
2792
+ return fs.existsSync(tempPath);
2793
+ }
2794
+ async moveTempToFinal(fileId, filename) {
2795
+ const tempPath = this.getTempPath(fileId);
2796
+ const finalPath = this.getFinalPath(fileId, filename);
2797
+ try {
2798
+ await fs.promises.rename(tempPath, finalPath);
2799
+ } catch {
2800
+ await fs.promises.copyFile(tempPath, finalPath);
2801
+ await fs.promises.unlink(tempPath);
2802
+ }
2803
+ return finalPath;
2804
+ }
2805
+ createTempReadStream(fileId) {
2806
+ const tempPath = this.getTempPath(fileId);
2807
+ return fs.createReadStream(tempPath);
2808
+ }
2809
+ };
2585
2810
  // Annotate the CommonJS export names for ESM import in node:
2586
2811
  0 && (module.exports = {
2587
2812
  ATS1_HDR,
2588
2813
  ATS1_SCHEMA,
2589
2814
  AXIS_MAGIC,
2590
2815
  AXIS_OPCODES,
2816
+ AXIS_UPLOAD_FILE_STORE,
2817
+ AXIS_UPLOAD_RECEIPT_SIGNER,
2818
+ AXIS_UPLOAD_SESSION_STORE,
2591
2819
  AXIS_VERSION,
2592
2820
  Ats1Codec,
2821
+ AxisFilesDownloadHandler,
2822
+ AxisFilesFinalizeHandler,
2593
2823
  AxisFrameZ,
2594
2824
  AxisIdDto,
2595
2825
  AxisPacketTags,
@@ -2602,6 +2832,7 @@ function isTimestampValid(ts, skewSeconds = 120) {
2602
2832
  DEFAULT_CONTRACTS,
2603
2833
  DEFAULT_TIMEOUT,
2604
2834
  Decision,
2835
+ DiskUploadFileStore,
2605
2836
  ERR_BAD_SIGNATURE,
2606
2837
  ERR_CONTRACT_VIOLATION,
2607
2838
  ERR_INVALID_PACKET,
@@ -2613,14 +2844,18 @@ function isTimestampValid(ts, skewSeconds = 120) {
2613
2844
  FLAG_HAS_WITNESS,
2614
2845
  HANDLER_METADATA_KEY,
2615
2846
  Handler,
2847
+ INTENT_BODY_KEY,
2616
2848
  INTENT_METADATA_KEY,
2617
2849
  INTENT_REQUIREMENTS,
2618
2850
  INTENT_ROUTES_KEY,
2619
2851
  INTENT_SENSITIVITY_MAP,
2852
+ INTENT_SENSORS_KEY,
2620
2853
  INTENT_TIMEOUTS,
2621
2854
  Intent,
2855
+ IntentBody,
2622
2856
  IntentRouter,
2623
2857
  IntentSensitivity,
2858
+ IntentSensors,
2624
2859
  MAX_BODY_LEN,
2625
2860
  MAX_FRAME_LEN,
2626
2861
  MAX_HDR_LEN,
@@ -2654,6 +2889,7 @@ function isTimestampValid(ts, skewSeconds = 120) {
2654
2889
  Schema2012_PasskeyLoginVerifyRes,
2655
2890
  Schema2021_PasskeyRegisterOptionsReq,
2656
2891
  SensorDecisions,
2892
+ TLV,
2657
2893
  TLV_ACTOR_ID,
2658
2894
  TLV_AUD,
2659
2895
  TLV_BODY_ARR,