@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/dist/index.mjs CHANGED
@@ -1,5 +1,15 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
3
13
  var __decorateClass = (decorators, target, key, kind) => {
4
14
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
15
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -215,6 +225,7 @@ var TLV_PROOF_TYPE = 5;
215
225
  var TLV_PROOF_REF = 6;
216
226
  var TLV_NONCE = 7;
217
227
  var TLV_AUD = 8;
228
+ var TLV_REALM = TLV_AUD;
218
229
  var TLV_NODE = 9;
219
230
  var TLV_TRACE_ID = 10;
220
231
  var TLV_KID = 11;
@@ -242,17 +253,17 @@ var ERR_CONTRACT_VIOLATION = "CONTRACT_VIOLATION";
242
253
  // src/core/varint.ts
243
254
  function encodeVarint(value) {
244
255
  if (value < 0) throw new Error("Varint must be unsigned");
245
- const bytes = [];
256
+ const bytes2 = [];
246
257
  while (true) {
247
258
  const byte = value & 127;
248
259
  value >>>= 7;
249
260
  if (value === 0) {
250
- bytes.push(byte);
261
+ bytes2.push(byte);
251
262
  break;
252
263
  }
253
- bytes.push(byte | 128);
264
+ bytes2.push(byte | 128);
254
265
  }
255
- return new Uint8Array(bytes);
266
+ return new Uint8Array(bytes2);
256
267
  }
257
268
  function decodeVarint(buf, offset = 0) {
258
269
  let value = 0;
@@ -353,25 +364,28 @@ function decodeTLVs(buf) {
353
364
  }
354
365
  return map2;
355
366
  }
356
- function decodeObject(bytes, depth = 0, limits = { maxDepth: 8, maxItems: 128 }) {
367
+ function decodeObject(bytes2, depth = 0, limits = { maxDepth: 8, maxItems: 128 }) {
357
368
  if (depth > limits.maxDepth) {
358
369
  throw new Error("OBJECT_DEPTH_EXCEEDED");
359
370
  }
360
- const map2 = decodeTLVs(bytes);
371
+ const map2 = decodeTLVs(bytes2);
361
372
  return map2;
362
373
  }
363
- function decodeArray(bytes, itemType, maxItems = 256) {
364
- const list = decodeTLVsList(bytes, maxItems);
374
+ function decodeArray(bytes2, itemType, maxItems = 256) {
375
+ const list = decodeTLVsList(bytes2, maxItems);
365
376
  const items = [];
366
- for (const tlv of list) {
367
- if (tlv.type !== itemType) {
368
- throw new Error(`INVALID_ARRAY_ITEM:${tlv.type}`);
377
+ for (const tlv2 of list) {
378
+ if (tlv2.type !== itemType) {
379
+ throw new Error(`INVALID_ARRAY_ITEM:${tlv2.type}`);
369
380
  }
370
- items.push(tlv.value);
381
+ items.push(tlv2.value);
371
382
  }
372
383
  return items;
373
384
  }
374
385
 
386
+ // src/core/signature.ts
387
+ import * as crypto from "crypto";
388
+
375
389
  // src/core/axis-bin.ts
376
390
  import * as z from "zod";
377
391
  var AxisFrameZ = z.object({
@@ -469,7 +483,6 @@ function getSignTarget(frame) {
469
483
  }
470
484
 
471
485
  // src/core/signature.ts
472
- import * as crypto from "crypto";
473
486
  function computeSignaturePayload(frame) {
474
487
  const frameWithoutSig = {
475
488
  ...frame,
@@ -586,14 +599,1272 @@ function computeReceiptHash(receiptBytes, prevHash) {
586
599
  }
587
600
  return hasher.digest();
588
601
  }
602
+
603
+ // src/codec/ats1.constants.ts
604
+ var ATS1_HDR = {
605
+ INTENT_ID: 1,
606
+ // uvarint
607
+ ACTOR_KEY_ID: 2,
608
+ // bytes (key fingerprint / credentialId hash)
609
+ CAPSULE_ID: 3,
610
+ // bytes or varint
611
+ NONCE: 4,
612
+ // 16 bytes
613
+ TS_MS: 5,
614
+ // u64be (8)
615
+ SCHEMA_ID: 6,
616
+ // uvarint
617
+ BODY_HASH: 7,
618
+ // 32 bytes (sha256)
619
+ TRACE_ID: 8
620
+ // 16 bytes
621
+ };
622
+ var ATS1_SCHEMA = {
623
+ PASSKEY_LOGIN_OPTIONS_REQ: 2001,
624
+ PASSKEY_LOGIN_OPTIONS_RES: 2002,
625
+ PASSKEY_LOGIN_VERIFY_REQ: 2011,
626
+ PASSKEY_LOGIN_VERIFY_RES: 2012,
627
+ PASSKEY_REGISTER_OPTIONS_REQ: 2021,
628
+ PASSKEY_REGISTER_OPTIONS_RES: 2022,
629
+ PASSKEY_REGISTER_VERIFY_REQ: 2031,
630
+ PASSKEY_REGISTER_VERIFY_RES: 2032
631
+ };
632
+
633
+ // src/codec/ats1.ts
634
+ var ats1_exports = {};
635
+ __export(ats1_exports, {
636
+ DEFAULT_LIMITS: () => DEFAULT_LIMITS,
637
+ HDR_TAGS: () => HDR_TAGS,
638
+ Schema2001_PasskeyLoginOptionsReq: () => Schema2001_PasskeyLoginOptionsReq,
639
+ Schema3100_DeviceContext: () => Schema3100_DeviceContext,
640
+ Schema4001_LoginWithDeviceReq: () => Schema4001_LoginWithDeviceReq,
641
+ decodeAxisHeaderFromTLVs: () => decodeAxisHeaderFromTLVs,
642
+ decodeAxisRequestBinary: () => decodeAxisRequestBinary,
643
+ decodeTLVStream: () => decodeTLVStream,
644
+ decodeU64BE: () => decodeU64BE,
645
+ decodeUVarint: () => decodeUVarint,
646
+ encodeAxisHeaderToTLVs: () => encodeAxisHeaderToTLVs,
647
+ encodeAxisRequestBinary: () => encodeAxisRequestBinary,
648
+ encodeTLV: () => encodeTLV,
649
+ encodeTLVStreamCanonical: () => encodeTLVStreamCanonical,
650
+ encodeU64BE: () => encodeU64BE,
651
+ encodeUVarint: () => encodeUVarint,
652
+ logicalBodyToTLVs: () => logicalBodyToTLVs,
653
+ sha256: () => sha2562,
654
+ tlvsToLogicalBody: () => tlvsToLogicalBody,
655
+ tlvsToMap: () => tlvsToMap,
656
+ validateTLVsAgainstSchema: () => validateTLVsAgainstSchema
657
+ });
658
+ import { createHash as createHash2 } from "crypto";
659
+ var DEFAULT_LIMITS = {
660
+ maxVarintBytes: 10,
661
+ maxTlvCount: 512,
662
+ maxValueBytes: 1048576,
663
+ // 1 MiB
664
+ maxNestingDepth: 4
665
+ };
666
+ function encodeUVarint(n) {
667
+ let x = typeof n === "bigint" ? n : BigInt(n);
668
+ if (x < 0n) throw new Error("encodeUVarint: negative not allowed");
669
+ const out = [];
670
+ while (x >= 0x80n) {
671
+ out.push(Number(x & 0x7fn | 0x80n));
672
+ x >>= 7n;
673
+ }
674
+ out.push(Number(x));
675
+ return Buffer.from(out);
676
+ }
677
+ function decodeUVarint(buf, offset, limits = DEFAULT_LIMITS) {
678
+ let x = 0n;
679
+ let shift = 0n;
680
+ const start = offset;
681
+ for (let i = 0; i < limits.maxVarintBytes; i++) {
682
+ if (offset >= buf.length) throw new Error("decodeUVarint: truncated");
683
+ const b = buf[offset++];
684
+ x |= BigInt(b & 127) << shift;
685
+ if ((b & 128) === 0) {
686
+ const bytesRead = offset - start;
687
+ const re = encodeUVarint(x);
688
+ const original = buf.subarray(start, offset);
689
+ if (!re.equals(original))
690
+ throw new Error("decodeUVarint: non-minimal varint");
691
+ return { value: x, offset, bytesRead };
692
+ }
693
+ shift += 7n;
694
+ }
695
+ throw new Error("decodeUVarint: too long");
696
+ }
697
+ function encodeU64BE(n) {
698
+ if (n < 0n) throw new Error("encodeU64BE: negative not allowed");
699
+ const b = Buffer.alloc(8);
700
+ b.writeBigUInt64BE(n, 0);
701
+ return b;
702
+ }
703
+ function decodeU64BE(buf) {
704
+ if (buf.length !== 8) throw new Error("decodeU64BE: length must be 8");
705
+ return buf.readBigUInt64BE(0);
706
+ }
707
+ function sha2562(data) {
708
+ return createHash2("sha256").update(data).digest();
709
+ }
710
+ function encodeTLV(tag, value) {
711
+ if (!Number.isInteger(tag) || tag <= 0)
712
+ throw new Error("encodeTLV: tag must be positive int");
713
+ const t = encodeUVarint(tag);
714
+ const l = encodeUVarint(value.length);
715
+ return Buffer.concat([t, l, value]);
716
+ }
717
+ function encodeTLVStreamCanonical(entries) {
718
+ const sorted = [...entries].sort((a, b) => a.tag - b.tag);
719
+ const parts = [];
720
+ for (const e of sorted) parts.push(encodeTLV(e.tag, e.value));
721
+ return Buffer.concat(parts);
722
+ }
723
+ function decodeTLVStream(stream, limits = DEFAULT_LIMITS) {
724
+ const out = [];
725
+ let off = 0;
726
+ while (off < stream.length) {
727
+ if (out.length >= limits.maxTlvCount)
728
+ throw new Error("decodeTLVStream: too many TLVs");
729
+ const tagRes = decodeUVarint(stream, off, limits);
730
+ const tag = Number(tagRes.value);
731
+ off = tagRes.offset;
732
+ const lenRes = decodeUVarint(stream, off, limits);
733
+ const len = Number(lenRes.value);
734
+ off = lenRes.offset;
735
+ if (len < 0) throw new Error("decodeTLVStream: negative length");
736
+ if (len > limits.maxValueBytes)
737
+ throw new Error("decodeTLVStream: value too large");
738
+ if (off + len > stream.length)
739
+ throw new Error("decodeTLVStream: truncated value");
740
+ const value = stream.subarray(off, off + len);
741
+ off += len;
742
+ out.push({ tag, value: Buffer.from(value) });
743
+ }
744
+ for (let i = 1; i < out.length; i++) {
745
+ if (out[i].tag < out[i - 1].tag)
746
+ throw new Error("decodeTLVStream: non-canonical tag order");
747
+ }
748
+ return out;
749
+ }
750
+ function tlvsToMap(entries) {
751
+ const m = /* @__PURE__ */ new Map();
752
+ for (const e of entries) {
753
+ const arr = m.get(e.tag) ?? [];
754
+ arr.push(e.value);
755
+ m.set(e.tag, arr);
756
+ }
757
+ return m;
758
+ }
759
+ function validateTLVsAgainstSchema(schema, tlvs, depth = 0, limits = DEFAULT_LIMITS) {
760
+ if (depth > Math.min(schema.maxNestingDepth, limits.maxNestingDepth)) {
761
+ throw new Error("validateTLVsAgainstSchema: nesting depth exceeded");
762
+ }
763
+ if (schema.maxBodyBytes && tlvsBytes(tlvs) > schema.maxBodyBytes) {
764
+ throw new Error("validateTLVsAgainstSchema: body too large");
765
+ }
766
+ const byTag = /* @__PURE__ */ new Map();
767
+ for (const t of tlvs) {
768
+ if (!byTag.has(t.tag)) byTag.set(t.tag, []);
769
+ byTag.get(t.tag).push(t);
770
+ }
771
+ const fieldByTag = new Map(schema.fields.map((f) => [f.tag, f]));
772
+ if (schema.strict) {
773
+ for (const tag of byTag.keys()) {
774
+ if (!fieldByTag.has(tag))
775
+ throw new Error(`validateTLVsAgainstSchema: unknown tag ${tag}`);
776
+ }
777
+ }
778
+ for (const f of schema.fields) {
779
+ const vals = byTag.get(f.tag) ?? [];
780
+ if (f.required && vals.length === 0)
781
+ throw new Error(`validateTLVsAgainstSchema: missing ${f.name}`);
782
+ if (!f.repeated && vals.length > 1) {
783
+ throw new Error(
784
+ `validateTLVsAgainstSchema: duplicate tag not allowed for ${f.name}`
785
+ );
786
+ }
787
+ if (typeof f.maxLen === "number") {
788
+ for (const v of vals) {
789
+ if (v.value.length > f.maxLen)
790
+ throw new Error(`validateTLVsAgainstSchema: ${f.name} too long`);
791
+ }
792
+ }
793
+ for (const v of vals) {
794
+ switch (f.type) {
795
+ case "u64be":
796
+ if (v.value.length !== 8)
797
+ throw new Error(
798
+ `validateTLVsAgainstSchema: ${f.name} u64be must be 8 bytes`
799
+ );
800
+ break;
801
+ case "nested": {
802
+ if (!f.nestedSchema)
803
+ throw new Error(
804
+ `validateTLVsAgainstSchema: ${f.name} missing nestedSchema`
805
+ );
806
+ const nestedTlvs = decodeTLVStream(v.value, limits);
807
+ validateTLVsAgainstSchema(
808
+ f.nestedSchema,
809
+ nestedTlvs,
810
+ depth + 1,
811
+ limits
812
+ );
813
+ break;
814
+ }
815
+ default:
816
+ break;
817
+ }
818
+ }
819
+ }
820
+ }
821
+ function tlvsBytes(tlvs) {
822
+ let n = 0;
823
+ for (const t of tlvs) {
824
+ n += encodeUVarint(t.tag).length + encodeUVarint(t.value.length).length + t.value.length;
825
+ }
826
+ return n;
827
+ }
828
+ function logicalBodyToTLVs(schema, body, limits = DEFAULT_LIMITS) {
829
+ if (body.schemaId !== schema.schemaId)
830
+ throw new Error("logicalBodyToTLVs: schemaId mismatch");
831
+ const fieldsByName = new Map(schema.fields.map((f) => [f.name, f]));
832
+ const tlvs = [];
833
+ for (const [name, val] of Object.entries(body.fields ?? {})) {
834
+ const f = fieldsByName.get(name);
835
+ if (!f) {
836
+ if (schema.strict)
837
+ throw new Error(`logicalBodyToTLVs: unknown field ${name}`);
838
+ continue;
839
+ }
840
+ const pushOne = (v) => {
841
+ const valueBuf = encodeFieldValue(f, v, limits);
842
+ if (valueBuf.length > limits.maxValueBytes)
843
+ throw new Error("logicalBodyToTLVs: value too large");
844
+ tlvs.push({ tag: f.tag, value: valueBuf });
845
+ };
846
+ if (f.repeated) {
847
+ if (!Array.isArray(val))
848
+ throw new Error(
849
+ `logicalBodyToTLVs: repeated field ${name} must be array`
850
+ );
851
+ for (const item of val) pushOne(item);
852
+ } else {
853
+ pushOne(val);
854
+ }
855
+ }
856
+ validateTLVsAgainstSchema(schema, tlvs, 0, limits);
857
+ return tlvs;
858
+ }
859
+ function encodeFieldValue(f, val, limits) {
860
+ switch (f.type) {
861
+ case "bytes":
862
+ if (Buffer.isBuffer(val)) return Buffer.from(val);
863
+ if (val instanceof Uint8Array) return Buffer.from(val);
864
+ throw new Error(`encodeFieldValue: ${f.name} expects bytes`);
865
+ case "utf8":
866
+ if (typeof val !== "string")
867
+ throw new Error(`encodeFieldValue: ${f.name} expects string`);
868
+ return Buffer.from(val, "utf8");
869
+ case "uvarint":
870
+ if (typeof val !== "number" && typeof val !== "bigint")
871
+ throw new Error(`encodeFieldValue: ${f.name} expects number/bigint`);
872
+ return encodeUVarint(val);
873
+ case "u64be":
874
+ if (typeof val !== "bigint")
875
+ throw new Error(`encodeFieldValue: ${f.name} expects bigint`);
876
+ return encodeU64BE(val);
877
+ case "nested": {
878
+ if (!f.nestedSchema)
879
+ throw new Error(`encodeFieldValue: ${f.name} missing nestedSchema`);
880
+ const nestedFields = val && typeof val === "object" && "fields" in val ? val.fields : val;
881
+ if (!nestedFields || typeof nestedFields !== "object")
882
+ throw new Error(`encodeFieldValue: ${f.name} expects object`);
883
+ const nestedBody = {
884
+ schemaId: f.nestedSchema.schemaId,
885
+ fields: nestedFields
886
+ };
887
+ const nestedTlvs = logicalBodyToTLVs(f.nestedSchema, nestedBody, limits);
888
+ const nestedBytes = encodeTLVStreamCanonical(nestedTlvs);
889
+ const re = decodeTLVStream(nestedBytes, limits);
890
+ validateTLVsAgainstSchema(f.nestedSchema, re, 1, limits);
891
+ return nestedBytes;
892
+ }
893
+ default:
894
+ throw new Error(`encodeFieldValue: unsupported type ${f.type}`);
895
+ }
896
+ }
897
+ function tlvsToLogicalBody(schema, tlvs, limits = DEFAULT_LIMITS) {
898
+ validateTLVsAgainstSchema(schema, tlvs, 0, limits);
899
+ const fields = {};
900
+ const fieldByTag = new Map(schema.fields.map((f) => [f.tag, f]));
901
+ for (const t of tlvs) {
902
+ const f = fieldByTag.get(t.tag);
903
+ if (!f) {
904
+ if (schema.strict)
905
+ throw new Error(`tlvsToLogicalBody: unknown tag ${t.tag}`);
906
+ continue;
907
+ }
908
+ const decoded = decodeFieldValue(f, t.value, limits);
909
+ if (f.repeated) {
910
+ if (!Array.isArray(fields[f.name])) fields[f.name] = [];
911
+ fields[f.name].push(decoded);
912
+ } else {
913
+ fields[f.name] = decoded;
914
+ }
915
+ }
916
+ return { schemaId: schema.schemaId, fields };
917
+ }
918
+ function decodeFieldValue(f, value, limits) {
919
+ switch (f.type) {
920
+ case "bytes":
921
+ return Buffer.from(value);
922
+ case "utf8":
923
+ return value.toString("utf8");
924
+ case "uvarint": {
925
+ const r = decodeUVarint(value, 0, limits);
926
+ if (r.offset !== value.length)
927
+ throw new Error(
928
+ `decodeFieldValue: ${f.name} uvarint has trailing bytes`
929
+ );
930
+ const asNum = Number(r.value);
931
+ return Number.isSafeInteger(asNum) ? asNum : r.value;
932
+ }
933
+ case "u64be":
934
+ return decodeU64BE(value);
935
+ case "nested": {
936
+ if (!f.nestedSchema)
937
+ throw new Error(`decodeFieldValue: ${f.name} missing nestedSchema`);
938
+ const nestedTlvs = decodeTLVStream(value, limits);
939
+ const nestedBody = tlvsToLogicalBody(f.nestedSchema, nestedTlvs, limits);
940
+ return nestedBody.fields;
941
+ }
942
+ default:
943
+ throw new Error(`decodeFieldValue: unsupported type ${f.type}`);
944
+ }
945
+ }
946
+ var HDR_TAGS = {
947
+ intent_id: 1,
948
+ actor_key_id: 2,
949
+ capsule_id: 3,
950
+ nonce: 4,
951
+ ts_ms: 5,
952
+ schema_id: 6,
953
+ body_hash: 7,
954
+ trace_id: 8
955
+ };
956
+ function encodeAxisHeaderToTLVs(hdr) {
957
+ if (hdr.nonce.byteLength !== 16)
958
+ throw new Error("encodeAxisHeaderToTLVs: nonce must be 16 bytes");
959
+ if (hdr.bodyHash.byteLength !== 32)
960
+ throw new Error("encodeAxisHeaderToTLVs: bodyHash must be 32 bytes");
961
+ if (hdr.traceId && hdr.traceId.byteLength !== 16)
962
+ throw new Error("encodeAxisHeaderToTLVs: traceId must be 16 bytes");
963
+ const tlvs = [
964
+ { tag: HDR_TAGS.intent_id, value: encodeUVarint(hdr.intentId) },
965
+ { tag: HDR_TAGS.actor_key_id, value: Buffer.from(hdr.actorKeyId) },
966
+ { tag: HDR_TAGS.nonce, value: Buffer.from(hdr.nonce) },
967
+ { tag: HDR_TAGS.ts_ms, value: encodeU64BE(hdr.tsMs) },
968
+ { tag: HDR_TAGS.schema_id, value: encodeUVarint(hdr.schemaId) },
969
+ { tag: HDR_TAGS.body_hash, value: Buffer.from(hdr.bodyHash) }
970
+ ];
971
+ if (hdr.capsuleId)
972
+ tlvs.push({ tag: HDR_TAGS.capsule_id, value: Buffer.from(hdr.capsuleId) });
973
+ if (hdr.traceId)
974
+ tlvs.push({ tag: HDR_TAGS.trace_id, value: Buffer.from(hdr.traceId) });
975
+ return tlvs;
976
+ }
977
+ function decodeAxisHeaderFromTLVs(hdrTlvs, limits = DEFAULT_LIMITS) {
978
+ const m = tlvsToMap(hdrTlvs);
979
+ const get1 = (tag) => {
980
+ const arr = m.get(tag);
981
+ if (!arr || arr.length !== 1)
982
+ throw new Error(
983
+ `decodeAxisHeaderFromTLVs: missing/dup header tag ${tag}`
984
+ );
985
+ return arr[0];
986
+ };
987
+ const getOpt1 = (tag) => {
988
+ const arr = m.get(tag);
989
+ if (!arr) return void 0;
990
+ if (arr.length !== 1)
991
+ throw new Error(`decodeAxisHeaderFromTLVs: dup header tag ${tag}`);
992
+ return arr[0];
993
+ };
994
+ const intentIdVar = decodeUVarint(get1(HDR_TAGS.intent_id), 0, limits);
995
+ if (intentIdVar.offset !== get1(HDR_TAGS.intent_id).length)
996
+ throw new Error("decodeAxisHeaderFromTLVs: intent_id trailing bytes");
997
+ const schemaIdVar = decodeUVarint(get1(HDR_TAGS.schema_id), 0, limits);
998
+ if (schemaIdVar.offset !== get1(HDR_TAGS.schema_id).length)
999
+ throw new Error("decodeAxisHeaderFromTLVs: schema_id trailing bytes");
1000
+ const ts = decodeU64BE(get1(HDR_TAGS.ts_ms));
1001
+ const nonce = get1(HDR_TAGS.nonce);
1002
+ if (nonce.length !== 16)
1003
+ throw new Error("decodeAxisHeaderFromTLVs: nonce must be 16 bytes");
1004
+ const bodyHash = get1(HDR_TAGS.body_hash);
1005
+ if (bodyHash.length !== 32)
1006
+ throw new Error("decodeAxisHeaderFromTLVs: body_hash must be 32 bytes");
1007
+ const trace = getOpt1(HDR_TAGS.trace_id);
1008
+ if (trace && trace.length !== 16)
1009
+ throw new Error("decodeAxisHeaderFromTLVs: trace_id must be 16 bytes");
1010
+ return {
1011
+ intentId: Number(intentIdVar.value),
1012
+ actorKeyId: Buffer.from(get1(HDR_TAGS.actor_key_id)),
1013
+ capsuleId: getOpt1(HDR_TAGS.capsule_id) ? Buffer.from(getOpt1(HDR_TAGS.capsule_id)) : void 0,
1014
+ nonce: Buffer.from(nonce),
1015
+ tsMs: ts,
1016
+ schemaId: Number(schemaIdVar.value),
1017
+ bodyHash: Buffer.from(bodyHash),
1018
+ traceId: trace ? Buffer.from(trace) : void 0
1019
+ };
1020
+ }
1021
+ function encodeAxisRequestBinary(schema, req, limits = DEFAULT_LIMITS) {
1022
+ const bodyTlvs = logicalBodyToTLVs(schema, req.body, limits);
1023
+ const bodyBytes = encodeTLVStreamCanonical(bodyTlvs);
1024
+ const bodyHash = sha2562(bodyBytes);
1025
+ const hdr = {
1026
+ ...req.hdr,
1027
+ schemaId: schema.schemaId,
1028
+ bodyHash
1029
+ };
1030
+ const hdrTlvs = encodeAxisHeaderToTLVs(hdr);
1031
+ const hdrBytes = encodeTLVStreamCanonical(hdrTlvs);
1032
+ return { hdrBytes, bodyBytes, bodyHash };
1033
+ }
1034
+ function decodeAxisRequestBinary(schema, hdrBytes, bodyBytes, limits = DEFAULT_LIMITS) {
1035
+ const hdrTlvs = decodeTLVStream(hdrBytes, limits);
1036
+ const bodyTlvs = decodeTLVStream(bodyBytes, limits);
1037
+ const hdr = decodeAxisHeaderFromTLVs(hdrTlvs, limits);
1038
+ if (hdr.schemaId !== schema.schemaId)
1039
+ throw new Error("decodeAxisRequestBinary: schemaId mismatch");
1040
+ const bh = sha2562(bodyBytes);
1041
+ if (!Buffer.from(hdr.bodyHash).equals(bh))
1042
+ throw new Error("decodeAxisRequestBinary: body_hash mismatch");
1043
+ const body = tlvsToLogicalBody(schema, bodyTlvs, limits);
1044
+ const sensorInput = {
1045
+ hdrTLVs: tlvsToMap(hdrTlvs),
1046
+ bodyTLVs: tlvsToMap(bodyTlvs),
1047
+ schemaId: hdr.schemaId,
1048
+ intentId: hdr.intentId
1049
+ };
1050
+ return { hdr, body, sensorInput };
1051
+ }
1052
+ var Schema3100_DeviceContext = {
1053
+ schemaId: 3100,
1054
+ name: "device.context",
1055
+ strict: true,
1056
+ maxNestingDepth: 4,
1057
+ fields: [
1058
+ { tag: 1, name: "deviceId", type: "bytes", required: true, maxLen: 128 },
1059
+ { tag: 2, name: "os", type: "utf8", required: true, maxLen: 64 },
1060
+ { tag: 3, name: "hw", type: "utf8", required: true, maxLen: 64 }
1061
+ ]
1062
+ };
1063
+ var Schema2001_PasskeyLoginOptionsReq = {
1064
+ schemaId: 2001,
1065
+ name: "axis.auth.passkey.login.options.req",
1066
+ strict: true,
1067
+ maxNestingDepth: 4,
1068
+ fields: [
1069
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 }
1070
+ ]
1071
+ };
1072
+ var Schema4001_LoginWithDeviceReq = {
1073
+ schemaId: 4001,
1074
+ name: "axis.auth.login.with_device.req",
1075
+ strict: true,
1076
+ maxNestingDepth: 4,
1077
+ fields: [
1078
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 },
1079
+ {
1080
+ tag: 2,
1081
+ name: "device",
1082
+ type: "nested",
1083
+ required: true,
1084
+ nestedSchema: Schema3100_DeviceContext
1085
+ }
1086
+ ]
1087
+ };
1088
+
1089
+ // src/codec/ats1.passkey.schemas.ts
1090
+ function buildAts1Hdr(params) {
1091
+ const hdr = {
1092
+ intentId: params.intentId,
1093
+ schemaId: params.schemaId,
1094
+ actorKeyId: params.actorKeyId ?? Buffer.alloc(0),
1095
+ capsuleId: params.capsuleId,
1096
+ nonce: params.nonce ?? __require("crypto").randomBytes(16),
1097
+ tsMs: params.tsMs ?? BigInt(Date.now()),
1098
+ bodyHash: params.bodyHash ?? Buffer.alloc(32),
1099
+ traceId: params.traceId
1100
+ };
1101
+ const tlvs = encodeAxisHeaderToTLVs(hdr);
1102
+ return encodeTLVStreamCanonical(tlvs);
1103
+ }
1104
+ function packPasskeyLoginOptionsReq(params) {
1105
+ const bodyTlvs = logicalBodyToTLVs(
1106
+ Schema2001_PasskeyLoginOptionsReq,
1107
+ {
1108
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_REQ,
1109
+ fields: { username: params.username }
1110
+ }
1111
+ );
1112
+ const body = encodeTLVStreamCanonical(bodyTlvs);
1113
+ const bodyHash = sha2562(body);
1114
+ const hdr = buildAts1Hdr({
1115
+ intentId: params.intentId,
1116
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_REQ,
1117
+ actorKeyId: params.actorKeyId,
1118
+ capsuleId: params.capsuleId,
1119
+ traceId: params.traceId,
1120
+ bodyHash
1121
+ });
1122
+ return { hdr, body };
1123
+ }
1124
+ function unpackPasskeyLoginOptionsReq(body) {
1125
+ const tlvs = decodeTLVStream(body);
1126
+ const decoded = tlvsToLogicalBody(
1127
+ Schema2001_PasskeyLoginOptionsReq,
1128
+ tlvs
1129
+ );
1130
+ return { username: decoded.fields.username };
1131
+ }
1132
+ var Schema2021_PasskeyRegisterOptionsReq = {
1133
+ schemaId: ATS1_SCHEMA.PASSKEY_REGISTER_OPTIONS_REQ,
1134
+ name: "axis.auth.passkey.register.options.req",
1135
+ strict: true,
1136
+ maxNestingDepth: 4,
1137
+ fields: [
1138
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 }
1139
+ ]
1140
+ };
1141
+ var Schema2011_PasskeyLoginVerifyReq = {
1142
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_REQ,
1143
+ name: "axis.auth.passkey.login.verify.req",
1144
+ strict: true,
1145
+ maxNestingDepth: 4,
1146
+ fields: [
1147
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 },
1148
+ {
1149
+ tag: 2,
1150
+ name: "credentialId",
1151
+ type: "bytes",
1152
+ required: true,
1153
+ maxLen: 1024
1154
+ },
1155
+ {
1156
+ tag: 3,
1157
+ name: "clientDataJSON",
1158
+ type: "bytes",
1159
+ required: true,
1160
+ maxLen: 4096
1161
+ },
1162
+ {
1163
+ tag: 4,
1164
+ name: "authenticatorData",
1165
+ type: "bytes",
1166
+ required: true,
1167
+ maxLen: 1024
1168
+ },
1169
+ { tag: 5, name: "signature", type: "bytes", required: true, maxLen: 1024 },
1170
+ { tag: 6, name: "userHandle", type: "bytes", required: false, maxLen: 128 }
1171
+ ]
1172
+ };
1173
+ function packPasskeyRegisterOptionsReq(params) {
1174
+ const bodyTlvs = logicalBodyToTLVs(
1175
+ Schema2021_PasskeyRegisterOptionsReq,
1176
+ {
1177
+ schemaId: ATS1_SCHEMA.PASSKEY_REGISTER_OPTIONS_REQ,
1178
+ fields: { username: params.username }
1179
+ }
1180
+ );
1181
+ const body = encodeTLVStreamCanonical(bodyTlvs);
1182
+ const bodyHash = sha2562(body);
1183
+ const hdr = buildAts1Hdr({
1184
+ intentId: params.intentId,
1185
+ schemaId: ATS1_SCHEMA.PASSKEY_REGISTER_OPTIONS_REQ,
1186
+ actorKeyId: params.actorKeyId,
1187
+ traceId: params.traceId,
1188
+ bodyHash
1189
+ });
1190
+ return { hdr, body };
1191
+ }
1192
+ function unpackPasskeyRegisterOptionsReq(body) {
1193
+ const tlvs = decodeTLVStream(body);
1194
+ const decoded = tlvsToLogicalBody(
1195
+ Schema2021_PasskeyRegisterOptionsReq,
1196
+ tlvs
1197
+ );
1198
+ return { username: decoded.fields.username };
1199
+ }
1200
+ function packPasskeyLoginVerifyReq(params) {
1201
+ const bodyTlvs = logicalBodyToTLVs(Schema2011_PasskeyLoginVerifyReq, {
1202
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_REQ,
1203
+ fields: {
1204
+ username: params.username,
1205
+ credentialId: params.credentialId,
1206
+ clientDataJSON: params.clientDataJSON,
1207
+ authenticatorData: params.authenticatorData,
1208
+ signature: params.signature,
1209
+ userHandle: params.userHandle
1210
+ }
1211
+ });
1212
+ const body = encodeTLVStreamCanonical(bodyTlvs);
1213
+ const bodyHash = sha2562(body);
1214
+ const hdr = buildAts1Hdr({
1215
+ intentId: params.intentId,
1216
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_REQ,
1217
+ actorKeyId: params.actorKeyId,
1218
+ traceId: params.traceId,
1219
+ bodyHash
1220
+ });
1221
+ return { hdr, body };
1222
+ }
1223
+ function unpackPasskeyLoginVerifyReq(body) {
1224
+ const tlvs = decodeTLVStream(body);
1225
+ const decoded = tlvsToLogicalBody(
1226
+ Schema2011_PasskeyLoginVerifyReq,
1227
+ tlvs
1228
+ );
1229
+ const f = decoded.fields;
1230
+ return {
1231
+ username: f.username,
1232
+ credentialId: f.credentialId,
1233
+ clientDataJSON: f.clientDataJSON,
1234
+ authenticatorData: f.authenticatorData,
1235
+ signature: f.signature,
1236
+ userHandle: f.userHandle
1237
+ };
1238
+ }
1239
+ var Schema2002_PasskeyLoginOptionsRes = {
1240
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_RES,
1241
+ name: "axis.auth.passkey.login.options.res",
1242
+ strict: false,
1243
+ // allow extra fields from WebAuthn library
1244
+ maxNestingDepth: 4,
1245
+ fields: [
1246
+ { tag: 1, name: "challenge", type: "utf8", required: true },
1247
+ // base64url string
1248
+ { tag: 2, name: "timeout", type: "uvarint", required: false },
1249
+ { tag: 3, name: "rpId", type: "utf8", required: false },
1250
+ { tag: 4, name: "userVerification", type: "utf8", required: false },
1251
+ { tag: 5, name: "allowCredentialsJson", type: "utf8", required: false }
1252
+ // JSON array for simplicity
1253
+ ]
1254
+ };
1255
+ function packPasskeyLoginOptionsRes(params) {
1256
+ const fields = {
1257
+ challenge: params.challenge
1258
+ };
1259
+ if (params.timeout !== void 0) fields.timeout = params.timeout;
1260
+ if (params.rpId) fields.rpId = params.rpId;
1261
+ if (params.userVerification)
1262
+ fields.userVerification = params.userVerification;
1263
+ if (params.allowCredentials)
1264
+ fields.allowCredentialsJson = JSON.stringify(params.allowCredentials);
1265
+ const bodyTlvs = logicalBodyToTLVs(Schema2002_PasskeyLoginOptionsRes, {
1266
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_RES,
1267
+ fields
1268
+ });
1269
+ return encodeTLVStreamCanonical(bodyTlvs);
1270
+ }
1271
+ var Schema2012_PasskeyLoginVerifyRes = {
1272
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_RES,
1273
+ name: "axis.auth.passkey.login.verify.res",
1274
+ strict: true,
1275
+ maxNestingDepth: 4,
1276
+ fields: [
1277
+ { tag: 1, name: "actorId", type: "utf8", required: true, maxLen: 256 },
1278
+ { tag: 2, name: "keyId", type: "utf8", required: true, maxLen: 256 },
1279
+ { tag: 3, name: "capsule", type: "bytes", required: true, maxLen: 4096 },
1280
+ { tag: 4, name: "expiresAt", type: "u64be", required: true }
1281
+ ]
1282
+ };
1283
+ function packPasskeyLoginVerifyRes(params) {
1284
+ const bodyTlvs = logicalBodyToTLVs(Schema2012_PasskeyLoginVerifyRes, {
1285
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_RES,
1286
+ fields: {
1287
+ actorId: params.actorId,
1288
+ keyId: params.keyId,
1289
+ capsule: params.capsule,
1290
+ expiresAt: params.expiresAt
1291
+ }
1292
+ });
1293
+ return encodeTLVStreamCanonical(bodyTlvs);
1294
+ }
1295
+
1296
+ // src/codec/tlv.encode.ts
1297
+ import { randomBytes as randomBytes2 } from "crypto";
1298
+ function encVarint(x) {
1299
+ if (x < 0n) throw new Error("VARINT_NEG");
1300
+ const out = [];
1301
+ while (x >= 0x80n) {
1302
+ out.push(Number(x & 0x7fn | 0x80n));
1303
+ x >>= 7n;
1304
+ }
1305
+ out.push(Number(x));
1306
+ return Buffer.from(out);
1307
+ }
1308
+ function varintU(x) {
1309
+ const v = typeof x === "number" ? BigInt(x) : x;
1310
+ return encVarint(v);
1311
+ }
1312
+ function u64be(x) {
1313
+ if (x < 0n) throw new Error("U64_NEG");
1314
+ const b = Buffer.alloc(8);
1315
+ b.writeBigUInt64BE(x, 0);
1316
+ return b;
1317
+ }
1318
+ function utf8(s) {
1319
+ return Buffer.from(s, "utf8");
1320
+ }
1321
+ function bytes(b) {
1322
+ return Buffer.isBuffer(b) ? b : Buffer.from(b);
1323
+ }
1324
+ function nonce16() {
1325
+ return randomBytes2(16);
1326
+ }
1327
+ function tlv(type, value) {
1328
+ if (!Number.isSafeInteger(type) || type < 0) throw new Error("TLV_BAD_TYPE");
1329
+ return Buffer.concat([
1330
+ encVarint(BigInt(type)),
1331
+ encVarint(BigInt(value.length)),
1332
+ value
1333
+ ]);
1334
+ }
1335
+ function buildTLVs(items, opts) {
1336
+ const allow = opts?.allowDupTypes ?? /* @__PURE__ */ new Set();
1337
+ const sorted = [...items].sort((a, b) => a.type - b.type);
1338
+ for (let i = 1; i < sorted.length; i++) {
1339
+ if (sorted[i].type === sorted[i - 1].type && !allow.has(sorted[i].type)) {
1340
+ throw new Error(`TLV_DUP_TYPE_${sorted[i].type}`);
1341
+ }
1342
+ }
1343
+ return Buffer.concat(sorted.map((it) => tlv(it.type, it.value)));
1344
+ }
1345
+
1346
+ // src/codec/axis1.encode.ts
1347
+ var MAGIC = Buffer.from("AXIS1", "ascii");
1348
+ function encodeAxis1Frame(f) {
1349
+ if (!Buffer.isBuffer(f.hdr) || !Buffer.isBuffer(f.body) || !Buffer.isBuffer(f.sig)) {
1350
+ throw new Error("AXIS1_BAD_BUFFERS");
1351
+ }
1352
+ if (f.ver !== 1) throw new Error("AXIS1_BAD_VER");
1353
+ const hdrLen = encVarint(BigInt(f.hdr.length));
1354
+ const bodyLen = encVarint(BigInt(f.body.length));
1355
+ const sigLen = encVarint(BigInt(f.sig.length));
1356
+ return Buffer.concat([
1357
+ MAGIC,
1358
+ Buffer.from([f.ver & 255]),
1359
+ Buffer.from([f.flags & 255]),
1360
+ hdrLen,
1361
+ bodyLen,
1362
+ sigLen,
1363
+ f.hdr,
1364
+ f.body,
1365
+ f.sig
1366
+ ]);
1367
+ }
1368
+
1369
+ // src/codec/axis1.signing.ts
1370
+ var MAGIC2 = Buffer.from("AXIS1", "ascii");
1371
+ function axis1SigningBytes(params) {
1372
+ if (params.ver !== 1) throw new Error("AXIS1_BAD_VER");
1373
+ const hdrLen = encVarint(BigInt(params.hdr.length));
1374
+ const bodyLen = encVarint(BigInt(params.body.length));
1375
+ const sigLenZero = encVarint(0n);
1376
+ return Buffer.concat([
1377
+ MAGIC2,
1378
+ Buffer.from([params.ver & 255]),
1379
+ Buffer.from([params.flags & 255]),
1380
+ hdrLen,
1381
+ bodyLen,
1382
+ sigLenZero,
1383
+ params.hdr,
1384
+ params.body
1385
+ ]);
1386
+ }
1387
+
1388
+ // src/crypto/b64url.ts
1389
+ function b64urlEncode(buf) {
1390
+ return buf.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
1391
+ }
1392
+ function b64urlDecode(str) {
1393
+ const pad = str.length % 4 ? "=".repeat(4 - str.length % 4) : "";
1394
+ const base64 = (str + pad).replace(/-/g, "+").replace(/_/g, "/");
1395
+ return Buffer.from(base64, "base64");
1396
+ }
1397
+ function b64urlEncodeString(str, encoding = "utf8") {
1398
+ return b64urlEncode(Buffer.from(str, encoding));
1399
+ }
1400
+ function b64urlDecodeString(str, encoding = "utf8") {
1401
+ return b64urlDecode(str).toString(encoding);
1402
+ }
1403
+
1404
+ // src/crypto/canonical-json.ts
1405
+ function sortRec(value) {
1406
+ if (value === null) {
1407
+ return null;
1408
+ }
1409
+ if (value === void 0) {
1410
+ return void 0;
1411
+ }
1412
+ if (Array.isArray(value)) {
1413
+ return value.map(sortRec);
1414
+ }
1415
+ if (typeof value === "object") {
1416
+ const sorted = {};
1417
+ const keys = Object.keys(value).sort();
1418
+ for (const key of keys) {
1419
+ const sortedValue = sortRec(value[key]);
1420
+ if (sortedValue !== void 0) {
1421
+ sorted[key] = sortedValue;
1422
+ }
1423
+ }
1424
+ return sorted;
1425
+ }
1426
+ return value;
1427
+ }
1428
+ function canonicalJson(value) {
1429
+ return JSON.stringify(sortRec(value));
1430
+ }
1431
+ function canonicalJsonExcluding(obj, exclude) {
1432
+ const filtered = {};
1433
+ for (const key in obj) {
1434
+ if (!exclude.includes(key) && obj[key] !== void 0) {
1435
+ filtered[key] = obj[key];
1436
+ }
1437
+ }
1438
+ return canonicalJson(filtered);
1439
+ }
1440
+
1441
+ // src/contract/execution-meter.ts
1442
+ var ContractViolationError = class extends Error {
1443
+ constructor(code, message) {
1444
+ super(message);
1445
+ this.code = code;
1446
+ this.name = "ContractViolationError";
1447
+ }
1448
+ };
1449
+ var ExecutionMeter = class {
1450
+ // ExecutionContract
1451
+ constructor(contract) {
1452
+ this.dbWrites = 0;
1453
+ this.dbReads = 0;
1454
+ this.externalCalls = 0;
1455
+ this.contract = contract;
1456
+ this.startTime = Date.now();
1457
+ }
1458
+ recordDbWrite() {
1459
+ this.dbWrites++;
1460
+ if (this.dbWrites > this.contract.maxDbWrites) {
1461
+ throw new ContractViolationError(
1462
+ "MAX_DB_WRITES_EXCEEDED",
1463
+ `DB writes exceeded: ${this.dbWrites}/${this.contract.maxDbWrites}`
1464
+ );
1465
+ }
1466
+ }
1467
+ recordDbRead() {
1468
+ this.dbReads++;
1469
+ if (this.contract.maxDbReads && this.dbReads > this.contract.maxDbReads) {
1470
+ throw new ContractViolationError(
1471
+ "MAX_DB_READS_EXCEEDED",
1472
+ `DB reads exceeded: ${this.dbReads}/${this.contract.maxDbReads}`
1473
+ );
1474
+ }
1475
+ }
1476
+ recordExternalCall() {
1477
+ this.externalCalls++;
1478
+ if (this.externalCalls > this.contract.maxExternalCalls) {
1479
+ throw new ContractViolationError(
1480
+ "MAX_EXTERNAL_CALLS_EXCEEDED",
1481
+ `External calls exceeded: ${this.externalCalls}/${this.contract.maxExternalCalls}`
1482
+ );
1483
+ }
1484
+ }
1485
+ checkTime() {
1486
+ const elapsed = Date.now() - this.startTime;
1487
+ if (elapsed > this.contract.maxTimeMs) {
1488
+ throw new ContractViolationError(
1489
+ "MAX_TIME_EXCEEDED",
1490
+ `Execution time exceeded: ${elapsed}ms/${this.contract.maxTimeMs}ms`
1491
+ );
1492
+ }
1493
+ }
1494
+ validateEffect(effect) {
1495
+ if (this.contract.allowedEffects.includes("*")) {
1496
+ return;
1497
+ }
1498
+ if (!this.contract.allowedEffects.includes(effect)) {
1499
+ throw new ContractViolationError(
1500
+ "INVALID_EFFECT",
1501
+ `Effect '${effect}' not allowed. Allowed: ${this.contract.allowedEffects.join(", ")}`
1502
+ );
1503
+ }
1504
+ }
1505
+ getMetrics() {
1506
+ return {
1507
+ dbWrites: this.dbWrites,
1508
+ dbReads: this.dbReads,
1509
+ externalCalls: this.externalCalls,
1510
+ elapsedMs: Date.now() - this.startTime
1511
+ };
1512
+ }
1513
+ getContract() {
1514
+ return this.contract;
1515
+ }
1516
+ };
1517
+
1518
+ // src/contract/contract.interface.ts
1519
+ var DEFAULT_CONTRACTS = {
1520
+ // System intents
1521
+ "system.ping": {
1522
+ maxDbWrites: 0,
1523
+ maxExternalCalls: 0,
1524
+ maxTimeMs: 100,
1525
+ allowedEffects: ["system.pong"]
1526
+ },
1527
+ // Catalog intents
1528
+ "catalog.list": {
1529
+ maxDbWrites: 0,
1530
+ maxExternalCalls: 0,
1531
+ maxTimeMs: 200,
1532
+ allowedEffects: ["catalog.listed"]
1533
+ },
1534
+ "catalog.search": {
1535
+ maxDbWrites: 0,
1536
+ maxExternalCalls: 0,
1537
+ maxTimeMs: 300,
1538
+ allowedEffects: ["catalog.searched"]
1539
+ },
1540
+ // Passport intents
1541
+ "passport.issue": {
1542
+ maxDbWrites: 10,
1543
+ maxExternalCalls: 0,
1544
+ maxTimeMs: 500,
1545
+ allowedEffects: ["passport.issued", "passport.rejected"]
1546
+ },
1547
+ "passport.revoke": {
1548
+ maxDbWrites: 5,
1549
+ maxExternalCalls: 0,
1550
+ maxTimeMs: 300,
1551
+ allowedEffects: ["passport.revoked", "passport.revoke_failed"]
1552
+ },
1553
+ // File intents
1554
+ "file.init": {
1555
+ maxDbWrites: 2,
1556
+ maxExternalCalls: 0,
1557
+ maxTimeMs: 200,
1558
+ allowedEffects: ["file.initialized"]
1559
+ },
1560
+ "file.chunk": {
1561
+ maxDbWrites: 2,
1562
+ maxExternalCalls: 0,
1563
+ maxTimeMs: 1e3,
1564
+ allowedEffects: ["file.chunk.stored"]
1565
+ },
1566
+ "file.finalize": {
1567
+ maxDbWrites: 2,
1568
+ maxExternalCalls: 0,
1569
+ maxTimeMs: 500,
1570
+ allowedEffects: ["file.finalized"]
1571
+ },
1572
+ // Stream intents
1573
+ "stream.publish": {
1574
+ maxDbWrites: 1,
1575
+ maxExternalCalls: 0,
1576
+ maxTimeMs: 200,
1577
+ allowedEffects: ["stream.published"]
1578
+ },
1579
+ "stream.read": {
1580
+ maxDbWrites: 0,
1581
+ maxExternalCalls: 0,
1582
+ maxTimeMs: 300,
1583
+ allowedEffects: ["stream.data"]
1584
+ },
1585
+ // Mail intents
1586
+ "mail.send": {
1587
+ maxDbWrites: 3,
1588
+ maxExternalCalls: 1,
1589
+ // Email service
1590
+ maxTimeMs: 2e3,
1591
+ allowedEffects: ["mail.sent", "mail.failed"]
1592
+ }
1593
+ };
1594
+ var FALLBACK_CONTRACT = {
1595
+ maxDbWrites: 10,
1596
+ maxExternalCalls: 0,
1597
+ maxTimeMs: 1e3,
1598
+ allowedEffects: ["*"]
1599
+ // Allow any effect
1600
+ };
1601
+
1602
+ // src/types/tlv.ts
1603
+ function decVarint(buf, off) {
1604
+ let shift = 0n;
1605
+ let x = 0n;
1606
+ while (true) {
1607
+ if (off >= buf.length) throw new Error("varint overflow");
1608
+ const b = BigInt(buf[off++]);
1609
+ x |= (b & 0x7fn) << shift;
1610
+ if ((b & 0x80n) === 0n) break;
1611
+ shift += 7n;
1612
+ if (shift > 63n) throw new Error("varint too large");
1613
+ }
1614
+ return { val: x, off };
1615
+ }
1616
+ function parseTLVs(buf, maxItems = 512) {
1617
+ const out = [];
1618
+ let off = 0;
1619
+ while (off < buf.length) {
1620
+ if (out.length >= maxItems) throw new Error("TLV_TOO_MANY_ITEMS");
1621
+ const t1 = decVarint(buf, off);
1622
+ off = t1.off;
1623
+ const t2 = decVarint(buf, off);
1624
+ off = t2.off;
1625
+ const type = Number(t1.val);
1626
+ const len = Number(t2.val);
1627
+ if (len < 0 || off + len > buf.length) {
1628
+ throw new Error("TLV_LEN_INVALID");
1629
+ }
1630
+ const value = buf.subarray(off, off + len);
1631
+ off += len;
1632
+ out.push({ type, value });
1633
+ }
1634
+ return out;
1635
+ }
1636
+ function tlvMap(buf) {
1637
+ const m = /* @__PURE__ */ new Map();
1638
+ for (const it of parseTLVs(buf)) {
1639
+ const arr = m.get(it.type) ?? [];
1640
+ arr.push(it.value);
1641
+ m.set(it.type, arr);
1642
+ }
1643
+ return m;
1644
+ }
1645
+ function asUtf8(b) {
1646
+ if (!b) return void 0;
1647
+ return b.toString("utf8");
1648
+ }
1649
+ function asBigintVarint(b) {
1650
+ if (!b) return void 0;
1651
+ const { val, off } = decVarint(b, 0);
1652
+ if (off !== b.length) throw new Error("VARINT_TRAILING_BYTES");
1653
+ return val;
1654
+ }
1655
+ function asBigint64BE(b) {
1656
+ if (!b) return void 0;
1657
+ if (b.length !== 8) throw new Error("Expected 8 bytes for u64");
1658
+ return b.readBigUInt64BE(0);
1659
+ }
1660
+
1661
+ // src/types/frame.ts
1662
+ var MAGIC3 = Buffer.from("AXIS1", "ascii");
1663
+ function decodeAxis1Frame(buf) {
1664
+ let off = 0;
1665
+ const magic = buf.subarray(off, off + 5);
1666
+ off += 5;
1667
+ if (magic.length !== 5 || !magic.equals(MAGIC3))
1668
+ throw new Error("AXIS1_BAD_MAGIC");
1669
+ if (off + 2 > buf.length) throw new Error("AXIS1_TRUNCATED");
1670
+ const ver = buf[off++];
1671
+ const flags = buf[off++];
1672
+ const h1 = decVarint(buf, off);
1673
+ off = h1.off;
1674
+ const b1 = decVarint(buf, off);
1675
+ off = b1.off;
1676
+ const s1 = decVarint(buf, off);
1677
+ off = s1.off;
1678
+ const hdrLen = Number(h1.val);
1679
+ const bodyLen = Number(b1.val);
1680
+ const sigLen = Number(s1.val);
1681
+ if (hdrLen < 0 || bodyLen < 0 || sigLen < 0) throw new Error("AXIS1_LEN_NEG");
1682
+ if (off + hdrLen + bodyLen + sigLen > buf.length)
1683
+ throw new Error("AXIS1_TRUNCATED_PAYLOAD");
1684
+ const hdr = buf.subarray(off, off + hdrLen);
1685
+ off += hdrLen;
1686
+ const body = buf.subarray(off, off + bodyLen);
1687
+ off += bodyLen;
1688
+ const sig = buf.subarray(off, off + sigLen);
1689
+ off += sigLen;
1690
+ if (off !== buf.length) throw new Error("AXIS1_TRAILING_BYTES");
1691
+ return { ver, flags, hdr, body, sig, frameSize: buf.length };
1692
+ }
1693
+
1694
+ // src/types/packet.ts
1695
+ var T = {
1696
+ /** The specific intent or action (e.g., 'vault.create') */
1697
+ INTENT: TLV_INTENT,
1698
+ /** Package identifier / ID */
1699
+ PID: TLV_PID,
1700
+ /** Versioning of the intent schema */
1701
+ INTENT_VERSION: 10,
1702
+ // Defaulting to TRACE_ID for now or a new tag if available
1703
+ /** Unique identifier for the requesting actor */
1704
+ ACTOR_ID: TLV_ACTOR_ID,
1705
+ /** Optional Capability Token identifier (16 bytes) */
1706
+ CAPSULE_ID: TLV_PROOF_REF,
1707
+ /** Unique session/request identifier (16 bytes) */
1708
+ NONCE: TLV_NONCE,
1709
+ /** High-precision Unix timestamp in milliseconds */
1710
+ TS_MS: TLV_TS,
1711
+ /** Proof type */
1712
+ PROOF_TYPE: TLV_PROOF_TYPE,
1713
+ /** Standard binary body tag */
1714
+ BODY: 100,
1715
+ /** Standard JSON-encoded body tag */
1716
+ JSON: 200
1717
+ };
1718
+ function buildPacket(hdr, body, sig, flags = 0) {
1719
+ const hm = tlvMap(hdr);
1720
+ const BODY_IS_TLV = 1;
1721
+ const bm = flags & BODY_IS_TLV ? tlvMap(body) : /* @__PURE__ */ new Map();
1722
+ const intent = asUtf8(hm.get(T.INTENT)?.[0]);
1723
+ const intentVerRaw = hm.get(T.INTENT_VERSION)?.[0];
1724
+ const intentVer = intentVerRaw ? Number(asBigintVarint(intentVerRaw)) : 1;
1725
+ const actorIdRaw = hm.get(T.ACTOR_ID)?.[0];
1726
+ const actorId = actorIdRaw ? actorIdRaw.toString("hex") : void 0;
1727
+ const capsuleId = hm.get(T.CAPSULE_ID)?.[0];
1728
+ const pid = hm.get(T.PID)?.[0] || hm.get(T.NONCE)?.[0];
1729
+ const nonce = hm.get(T.NONCE)?.[0];
1730
+ const tsMs = asBigint64BE(hm.get(T.TS_MS)?.[0]);
1731
+ if (!intent) throw new Error("PACKET_MISSING_INTENT");
1732
+ if (!actorId) throw new Error("PACKET_MISSING_ACTOR_ID");
1733
+ if (!nonce || nonce.length < 16 || nonce.length > 32)
1734
+ throw new Error("PACKET_BAD_NONCE");
1735
+ if (!pid) throw new Error("PACKET_MISSING_PID");
1736
+ if (!tsMs) throw new Error("PACKET_MISSING_TS");
1737
+ return {
1738
+ intent,
1739
+ intentVersion: intentVer,
1740
+ actorId,
1741
+ capsuleId,
1742
+ pid,
1743
+ nonce,
1744
+ tsMs,
1745
+ headersMap: hm,
1746
+ bodyMap: bm,
1747
+ hdrBytes: hdr,
1748
+ bodyBytes: body,
1749
+ sig
1750
+ };
1751
+ }
1752
+
1753
+ // src/sensor/axis-sensor.ts
1754
+ var Decision = /* @__PURE__ */ ((Decision2) => {
1755
+ Decision2["ALLOW"] = "ALLOW";
1756
+ Decision2["DENY"] = "DENY";
1757
+ Decision2["THROTTLE"] = "THROTTLE";
1758
+ Decision2["FLAG"] = "FLAG";
1759
+ return Decision2;
1760
+ })(Decision || {});
1761
+ function normalizeSensorDecision(sensorDecision) {
1762
+ if ("action" in sensorDecision) {
1763
+ switch (sensorDecision.action) {
1764
+ case "ALLOW":
1765
+ return {
1766
+ allow: true,
1767
+ riskScore: 0,
1768
+ reasons: [],
1769
+ meta: sensorDecision.meta
1770
+ };
1771
+ case "DENY":
1772
+ return {
1773
+ allow: false,
1774
+ riskScore: 100,
1775
+ reasons: [sensorDecision.code, sensorDecision.reason].filter(
1776
+ Boolean
1777
+ ),
1778
+ meta: sensorDecision.meta,
1779
+ retryAfterMs: sensorDecision.retryAfterMs
1780
+ };
1781
+ case "THROTTLE":
1782
+ return {
1783
+ allow: false,
1784
+ riskScore: 50,
1785
+ reasons: ["RATE_LIMIT"],
1786
+ retryAfterMs: sensorDecision.retryAfterMs,
1787
+ meta: sensorDecision.meta
1788
+ };
1789
+ case "FLAG":
1790
+ return {
1791
+ allow: true,
1792
+ riskScore: sensorDecision.scoreDelta,
1793
+ reasons: sensorDecision.reasons,
1794
+ meta: sensorDecision.meta
1795
+ };
1796
+ }
1797
+ }
1798
+ return {
1799
+ allow: sensorDecision.allow,
1800
+ riskScore: sensorDecision.riskScore,
1801
+ reasons: sensorDecision.reasons,
1802
+ tags: sensorDecision.tags,
1803
+ meta: sensorDecision.meta,
1804
+ tighten: sensorDecision.tighten,
1805
+ retryAfterMs: sensorDecision.retryAfterMs
1806
+ };
1807
+ }
1808
+ var SensorDecisions = {
1809
+ allow(meta, tags) {
1810
+ return {
1811
+ decision: "ALLOW" /* ALLOW */,
1812
+ allow: true,
1813
+ riskScore: 0,
1814
+ reasons: [],
1815
+ tags,
1816
+ meta
1817
+ };
1818
+ },
1819
+ deny(code, reason, meta) {
1820
+ return {
1821
+ decision: "DENY" /* DENY */,
1822
+ allow: false,
1823
+ riskScore: 100,
1824
+ code,
1825
+ reasons: [code, reason].filter(Boolean),
1826
+ meta
1827
+ };
1828
+ },
1829
+ throttle(retryAfterMs, meta) {
1830
+ return {
1831
+ decision: "THROTTLE" /* THROTTLE */,
1832
+ allow: false,
1833
+ riskScore: 50,
1834
+ retryAfterMs,
1835
+ code: "RATE_LIMIT",
1836
+ reasons: ["RATE_LIMIT"],
1837
+ meta
1838
+ };
1839
+ },
1840
+ flag(scoreDelta, reasons, meta) {
1841
+ return {
1842
+ decision: "FLAG" /* FLAG */,
1843
+ allow: true,
1844
+ riskScore: scoreDelta,
1845
+ scoreDelta,
1846
+ reasons,
1847
+ meta
1848
+ };
1849
+ }
1850
+ };
589
1851
  export {
1852
+ ATS1_HDR,
1853
+ ATS1_SCHEMA,
590
1854
  AXIS_MAGIC,
591
1855
  AXIS_VERSION,
1856
+ ats1_exports as Ats1Codec,
592
1857
  AxisFrameZ,
1858
+ T as AxisPacketTags,
1859
+ ContractViolationError,
1860
+ DEFAULT_CONTRACTS,
1861
+ Decision,
593
1862
  ERR_BAD_SIGNATURE,
594
1863
  ERR_CONTRACT_VIOLATION,
595
1864
  ERR_INVALID_PACKET,
596
1865
  ERR_REPLAY_DETECTED,
1866
+ ExecutionMeter,
1867
+ FALLBACK_CONTRACT,
597
1868
  FLAG_BODY_TLV,
598
1869
  FLAG_CHAIN_REQ,
599
1870
  FLAG_HAS_WITNESS,
@@ -610,6 +1881,11 @@ export {
610
1881
  PROOF_JWT,
611
1882
  PROOF_LOOM,
612
1883
  PROOF_MTLS,
1884
+ Schema2002_PasskeyLoginOptionsRes,
1885
+ Schema2011_PasskeyLoginVerifyReq,
1886
+ Schema2012_PasskeyLoginVerifyRes,
1887
+ Schema2021_PasskeyRegisterOptionsReq,
1888
+ SensorDecisions,
613
1889
  TLV_ACTOR_ID,
614
1890
  TLV_AUD,
615
1891
  TLV_EFFECT,
@@ -629,26 +1905,55 @@ export {
629
1905
  TLV_PREV_HASH,
630
1906
  TLV_PROOF_REF,
631
1907
  TLV_PROOF_TYPE,
1908
+ TLV_REALM,
632
1909
  TLV_RECEIPT_HASH,
633
1910
  TLV_RID,
634
1911
  TLV_TRACE_ID,
635
1912
  TLV_TS,
1913
+ axis1SigningBytes,
1914
+ b64urlDecode,
1915
+ b64urlDecodeString,
1916
+ b64urlEncode,
1917
+ b64urlEncodeString,
1918
+ buildAts1Hdr,
1919
+ buildPacket,
1920
+ buildTLVs,
1921
+ bytes,
1922
+ canonicalJson,
1923
+ canonicalJsonExcluding,
636
1924
  computeReceiptHash,
637
1925
  computeSignaturePayload,
638
1926
  decodeArray,
1927
+ decodeAxis1Frame,
639
1928
  decodeFrame,
640
1929
  decodeObject,
641
1930
  decodeTLVs,
642
1931
  decodeTLVsList,
643
1932
  decodeVarint,
1933
+ encVarint,
1934
+ encodeAxis1Frame,
644
1935
  encodeFrame,
645
1936
  encodeTLVs,
646
1937
  encodeVarint,
647
1938
  generateEd25519KeyPair,
648
1939
  getSignTarget,
1940
+ nonce16,
1941
+ normalizeSensorDecision,
1942
+ packPasskeyLoginOptionsReq,
1943
+ packPasskeyLoginOptionsRes,
1944
+ packPasskeyLoginVerifyReq,
1945
+ packPasskeyLoginVerifyRes,
1946
+ packPasskeyRegisterOptionsReq,
649
1947
  sha256,
650
1948
  signFrame,
1949
+ tlv,
1950
+ u64be,
1951
+ unpackPasskeyLoginOptionsReq,
1952
+ unpackPasskeyLoginVerifyReq,
1953
+ unpackPasskeyRegisterOptionsReq,
1954
+ utf8,
651
1955
  varintLength,
1956
+ varintU,
652
1957
  verifyFrameSignature
653
1958
  };
654
1959
  //# sourceMappingURL=index.mjs.map