@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.js CHANGED
@@ -37,13 +37,22 @@ var __decorateClass = (decorators, target, key, kind) => {
37
37
  // src/index.ts
38
38
  var index_exports = {};
39
39
  __export(index_exports, {
40
+ ATS1_HDR: () => ATS1_HDR,
41
+ ATS1_SCHEMA: () => ATS1_SCHEMA,
40
42
  AXIS_MAGIC: () => AXIS_MAGIC,
41
43
  AXIS_VERSION: () => AXIS_VERSION,
44
+ Ats1Codec: () => ats1_exports,
42
45
  AxisFrameZ: () => AxisFrameZ,
46
+ AxisPacketTags: () => T,
47
+ ContractViolationError: () => ContractViolationError,
48
+ DEFAULT_CONTRACTS: () => DEFAULT_CONTRACTS,
49
+ Decision: () => Decision,
43
50
  ERR_BAD_SIGNATURE: () => ERR_BAD_SIGNATURE,
44
51
  ERR_CONTRACT_VIOLATION: () => ERR_CONTRACT_VIOLATION,
45
52
  ERR_INVALID_PACKET: () => ERR_INVALID_PACKET,
46
53
  ERR_REPLAY_DETECTED: () => ERR_REPLAY_DETECTED,
54
+ ExecutionMeter: () => ExecutionMeter,
55
+ FALLBACK_CONTRACT: () => FALLBACK_CONTRACT,
47
56
  FLAG_BODY_TLV: () => FLAG_BODY_TLV,
48
57
  FLAG_CHAIN_REQ: () => FLAG_CHAIN_REQ,
49
58
  FLAG_HAS_WITNESS: () => FLAG_HAS_WITNESS,
@@ -60,6 +69,11 @@ __export(index_exports, {
60
69
  PROOF_JWT: () => PROOF_JWT,
61
70
  PROOF_LOOM: () => PROOF_LOOM,
62
71
  PROOF_MTLS: () => PROOF_MTLS,
72
+ Schema2002_PasskeyLoginOptionsRes: () => Schema2002_PasskeyLoginOptionsRes,
73
+ Schema2011_PasskeyLoginVerifyReq: () => Schema2011_PasskeyLoginVerifyReq,
74
+ Schema2012_PasskeyLoginVerifyRes: () => Schema2012_PasskeyLoginVerifyRes,
75
+ Schema2021_PasskeyRegisterOptionsReq: () => Schema2021_PasskeyRegisterOptionsReq,
76
+ SensorDecisions: () => SensorDecisions,
63
77
  TLV_ACTOR_ID: () => TLV_ACTOR_ID,
64
78
  TLV_AUD: () => TLV_AUD,
65
79
  TLV_EFFECT: () => TLV_EFFECT,
@@ -79,26 +93,55 @@ __export(index_exports, {
79
93
  TLV_PREV_HASH: () => TLV_PREV_HASH,
80
94
  TLV_PROOF_REF: () => TLV_PROOF_REF,
81
95
  TLV_PROOF_TYPE: () => TLV_PROOF_TYPE,
96
+ TLV_REALM: () => TLV_REALM,
82
97
  TLV_RECEIPT_HASH: () => TLV_RECEIPT_HASH,
83
98
  TLV_RID: () => TLV_RID,
84
99
  TLV_TRACE_ID: () => TLV_TRACE_ID,
85
100
  TLV_TS: () => TLV_TS,
101
+ axis1SigningBytes: () => axis1SigningBytes,
102
+ b64urlDecode: () => b64urlDecode,
103
+ b64urlDecodeString: () => b64urlDecodeString,
104
+ b64urlEncode: () => b64urlEncode,
105
+ b64urlEncodeString: () => b64urlEncodeString,
106
+ buildAts1Hdr: () => buildAts1Hdr,
107
+ buildPacket: () => buildPacket,
108
+ buildTLVs: () => buildTLVs,
109
+ bytes: () => bytes,
110
+ canonicalJson: () => canonicalJson,
111
+ canonicalJsonExcluding: () => canonicalJsonExcluding,
86
112
  computeReceiptHash: () => computeReceiptHash,
87
113
  computeSignaturePayload: () => computeSignaturePayload,
88
114
  decodeArray: () => decodeArray,
115
+ decodeAxis1Frame: () => decodeAxis1Frame,
89
116
  decodeFrame: () => decodeFrame,
90
117
  decodeObject: () => decodeObject,
91
118
  decodeTLVs: () => decodeTLVs,
92
119
  decodeTLVsList: () => decodeTLVsList,
93
120
  decodeVarint: () => decodeVarint,
121
+ encVarint: () => encVarint,
122
+ encodeAxis1Frame: () => encodeAxis1Frame,
94
123
  encodeFrame: () => encodeFrame,
95
124
  encodeTLVs: () => encodeTLVs,
96
125
  encodeVarint: () => encodeVarint,
97
126
  generateEd25519KeyPair: () => generateEd25519KeyPair,
98
127
  getSignTarget: () => getSignTarget,
128
+ nonce16: () => nonce16,
129
+ normalizeSensorDecision: () => normalizeSensorDecision,
130
+ packPasskeyLoginOptionsReq: () => packPasskeyLoginOptionsReq,
131
+ packPasskeyLoginOptionsRes: () => packPasskeyLoginOptionsRes,
132
+ packPasskeyLoginVerifyReq: () => packPasskeyLoginVerifyReq,
133
+ packPasskeyLoginVerifyRes: () => packPasskeyLoginVerifyRes,
134
+ packPasskeyRegisterOptionsReq: () => packPasskeyRegisterOptionsReq,
99
135
  sha256: () => sha256,
100
136
  signFrame: () => signFrame,
137
+ tlv: () => tlv,
138
+ u64be: () => u64be,
139
+ unpackPasskeyLoginOptionsReq: () => unpackPasskeyLoginOptionsReq,
140
+ unpackPasskeyLoginVerifyReq: () => unpackPasskeyLoginVerifyReq,
141
+ unpackPasskeyRegisterOptionsReq: () => unpackPasskeyRegisterOptionsReq,
142
+ utf8: () => utf8,
101
143
  varintLength: () => varintLength,
144
+ varintU: () => varintU,
102
145
  verifyFrameSignature: () => verifyFrameSignature
103
146
  });
104
147
  module.exports = __toCommonJS(index_exports);
@@ -309,6 +352,7 @@ var TLV_PROOF_TYPE = 5;
309
352
  var TLV_PROOF_REF = 6;
310
353
  var TLV_NONCE = 7;
311
354
  var TLV_AUD = 8;
355
+ var TLV_REALM = TLV_AUD;
312
356
  var TLV_NODE = 9;
313
357
  var TLV_TRACE_ID = 10;
314
358
  var TLV_KID = 11;
@@ -336,17 +380,17 @@ var ERR_CONTRACT_VIOLATION = "CONTRACT_VIOLATION";
336
380
  // src/core/varint.ts
337
381
  function encodeVarint(value) {
338
382
  if (value < 0) throw new Error("Varint must be unsigned");
339
- const bytes = [];
383
+ const bytes2 = [];
340
384
  while (true) {
341
385
  const byte = value & 127;
342
386
  value >>>= 7;
343
387
  if (value === 0) {
344
- bytes.push(byte);
388
+ bytes2.push(byte);
345
389
  break;
346
390
  }
347
- bytes.push(byte | 128);
391
+ bytes2.push(byte | 128);
348
392
  }
349
- return new Uint8Array(bytes);
393
+ return new Uint8Array(bytes2);
350
394
  }
351
395
  function decodeVarint(buf, offset = 0) {
352
396
  let value = 0;
@@ -447,25 +491,28 @@ function decodeTLVs(buf) {
447
491
  }
448
492
  return map2;
449
493
  }
450
- function decodeObject(bytes, depth = 0, limits = { maxDepth: 8, maxItems: 128 }) {
494
+ function decodeObject(bytes2, depth = 0, limits = { maxDepth: 8, maxItems: 128 }) {
451
495
  if (depth > limits.maxDepth) {
452
496
  throw new Error("OBJECT_DEPTH_EXCEEDED");
453
497
  }
454
- const map2 = decodeTLVs(bytes);
498
+ const map2 = decodeTLVs(bytes2);
455
499
  return map2;
456
500
  }
457
- function decodeArray(bytes, itemType, maxItems = 256) {
458
- const list = decodeTLVsList(bytes, maxItems);
501
+ function decodeArray(bytes2, itemType, maxItems = 256) {
502
+ const list = decodeTLVsList(bytes2, maxItems);
459
503
  const items = [];
460
- for (const tlv of list) {
461
- if (tlv.type !== itemType) {
462
- throw new Error(`INVALID_ARRAY_ITEM:${tlv.type}`);
504
+ for (const tlv2 of list) {
505
+ if (tlv2.type !== itemType) {
506
+ throw new Error(`INVALID_ARRAY_ITEM:${tlv2.type}`);
463
507
  }
464
- items.push(tlv.value);
508
+ items.push(tlv2.value);
465
509
  }
466
510
  return items;
467
511
  }
468
512
 
513
+ // src/core/signature.ts
514
+ var crypto = __toESM(require("crypto"));
515
+
469
516
  // src/core/axis-bin.ts
470
517
  var z = __toESM(require("zod"));
471
518
  var AxisFrameZ = z.object({
@@ -563,7 +610,6 @@ function getSignTarget(frame) {
563
610
  }
564
611
 
565
612
  // src/core/signature.ts
566
- var crypto = __toESM(require("crypto"));
567
613
  function computeSignaturePayload(frame) {
568
614
  const frameWithoutSig = {
569
615
  ...frame,
@@ -680,15 +726,1273 @@ function computeReceiptHash(receiptBytes, prevHash) {
680
726
  }
681
727
  return hasher.digest();
682
728
  }
729
+
730
+ // src/codec/ats1.constants.ts
731
+ var ATS1_HDR = {
732
+ INTENT_ID: 1,
733
+ // uvarint
734
+ ACTOR_KEY_ID: 2,
735
+ // bytes (key fingerprint / credentialId hash)
736
+ CAPSULE_ID: 3,
737
+ // bytes or varint
738
+ NONCE: 4,
739
+ // 16 bytes
740
+ TS_MS: 5,
741
+ // u64be (8)
742
+ SCHEMA_ID: 6,
743
+ // uvarint
744
+ BODY_HASH: 7,
745
+ // 32 bytes (sha256)
746
+ TRACE_ID: 8
747
+ // 16 bytes
748
+ };
749
+ var ATS1_SCHEMA = {
750
+ PASSKEY_LOGIN_OPTIONS_REQ: 2001,
751
+ PASSKEY_LOGIN_OPTIONS_RES: 2002,
752
+ PASSKEY_LOGIN_VERIFY_REQ: 2011,
753
+ PASSKEY_LOGIN_VERIFY_RES: 2012,
754
+ PASSKEY_REGISTER_OPTIONS_REQ: 2021,
755
+ PASSKEY_REGISTER_OPTIONS_RES: 2022,
756
+ PASSKEY_REGISTER_VERIFY_REQ: 2031,
757
+ PASSKEY_REGISTER_VERIFY_RES: 2032
758
+ };
759
+
760
+ // src/codec/ats1.ts
761
+ var ats1_exports = {};
762
+ __export(ats1_exports, {
763
+ DEFAULT_LIMITS: () => DEFAULT_LIMITS,
764
+ HDR_TAGS: () => HDR_TAGS,
765
+ Schema2001_PasskeyLoginOptionsReq: () => Schema2001_PasskeyLoginOptionsReq,
766
+ Schema3100_DeviceContext: () => Schema3100_DeviceContext,
767
+ Schema4001_LoginWithDeviceReq: () => Schema4001_LoginWithDeviceReq,
768
+ decodeAxisHeaderFromTLVs: () => decodeAxisHeaderFromTLVs,
769
+ decodeAxisRequestBinary: () => decodeAxisRequestBinary,
770
+ decodeTLVStream: () => decodeTLVStream,
771
+ decodeU64BE: () => decodeU64BE,
772
+ decodeUVarint: () => decodeUVarint,
773
+ encodeAxisHeaderToTLVs: () => encodeAxisHeaderToTLVs,
774
+ encodeAxisRequestBinary: () => encodeAxisRequestBinary,
775
+ encodeTLV: () => encodeTLV,
776
+ encodeTLVStreamCanonical: () => encodeTLVStreamCanonical,
777
+ encodeU64BE: () => encodeU64BE,
778
+ encodeUVarint: () => encodeUVarint,
779
+ logicalBodyToTLVs: () => logicalBodyToTLVs,
780
+ sha256: () => sha2562,
781
+ tlvsToLogicalBody: () => tlvsToLogicalBody,
782
+ tlvsToMap: () => tlvsToMap,
783
+ validateTLVsAgainstSchema: () => validateTLVsAgainstSchema
784
+ });
785
+ var import_crypto = require("crypto");
786
+ var DEFAULT_LIMITS = {
787
+ maxVarintBytes: 10,
788
+ maxTlvCount: 512,
789
+ maxValueBytes: 1048576,
790
+ // 1 MiB
791
+ maxNestingDepth: 4
792
+ };
793
+ function encodeUVarint(n) {
794
+ let x = typeof n === "bigint" ? n : BigInt(n);
795
+ if (x < 0n) throw new Error("encodeUVarint: negative not allowed");
796
+ const out = [];
797
+ while (x >= 0x80n) {
798
+ out.push(Number(x & 0x7fn | 0x80n));
799
+ x >>= 7n;
800
+ }
801
+ out.push(Number(x));
802
+ return Buffer.from(out);
803
+ }
804
+ function decodeUVarint(buf, offset, limits = DEFAULT_LIMITS) {
805
+ let x = 0n;
806
+ let shift = 0n;
807
+ const start = offset;
808
+ for (let i = 0; i < limits.maxVarintBytes; i++) {
809
+ if (offset >= buf.length) throw new Error("decodeUVarint: truncated");
810
+ const b = buf[offset++];
811
+ x |= BigInt(b & 127) << shift;
812
+ if ((b & 128) === 0) {
813
+ const bytesRead = offset - start;
814
+ const re = encodeUVarint(x);
815
+ const original = buf.subarray(start, offset);
816
+ if (!re.equals(original))
817
+ throw new Error("decodeUVarint: non-minimal varint");
818
+ return { value: x, offset, bytesRead };
819
+ }
820
+ shift += 7n;
821
+ }
822
+ throw new Error("decodeUVarint: too long");
823
+ }
824
+ function encodeU64BE(n) {
825
+ if (n < 0n) throw new Error("encodeU64BE: negative not allowed");
826
+ const b = Buffer.alloc(8);
827
+ b.writeBigUInt64BE(n, 0);
828
+ return b;
829
+ }
830
+ function decodeU64BE(buf) {
831
+ if (buf.length !== 8) throw new Error("decodeU64BE: length must be 8");
832
+ return buf.readBigUInt64BE(0);
833
+ }
834
+ function sha2562(data) {
835
+ return (0, import_crypto.createHash)("sha256").update(data).digest();
836
+ }
837
+ function encodeTLV(tag, value) {
838
+ if (!Number.isInteger(tag) || tag <= 0)
839
+ throw new Error("encodeTLV: tag must be positive int");
840
+ const t = encodeUVarint(tag);
841
+ const l = encodeUVarint(value.length);
842
+ return Buffer.concat([t, l, value]);
843
+ }
844
+ function encodeTLVStreamCanonical(entries) {
845
+ const sorted = [...entries].sort((a, b) => a.tag - b.tag);
846
+ const parts = [];
847
+ for (const e of sorted) parts.push(encodeTLV(e.tag, e.value));
848
+ return Buffer.concat(parts);
849
+ }
850
+ function decodeTLVStream(stream, limits = DEFAULT_LIMITS) {
851
+ const out = [];
852
+ let off = 0;
853
+ while (off < stream.length) {
854
+ if (out.length >= limits.maxTlvCount)
855
+ throw new Error("decodeTLVStream: too many TLVs");
856
+ const tagRes = decodeUVarint(stream, off, limits);
857
+ const tag = Number(tagRes.value);
858
+ off = tagRes.offset;
859
+ const lenRes = decodeUVarint(stream, off, limits);
860
+ const len = Number(lenRes.value);
861
+ off = lenRes.offset;
862
+ if (len < 0) throw new Error("decodeTLVStream: negative length");
863
+ if (len > limits.maxValueBytes)
864
+ throw new Error("decodeTLVStream: value too large");
865
+ if (off + len > stream.length)
866
+ throw new Error("decodeTLVStream: truncated value");
867
+ const value = stream.subarray(off, off + len);
868
+ off += len;
869
+ out.push({ tag, value: Buffer.from(value) });
870
+ }
871
+ for (let i = 1; i < out.length; i++) {
872
+ if (out[i].tag < out[i - 1].tag)
873
+ throw new Error("decodeTLVStream: non-canonical tag order");
874
+ }
875
+ return out;
876
+ }
877
+ function tlvsToMap(entries) {
878
+ const m = /* @__PURE__ */ new Map();
879
+ for (const e of entries) {
880
+ const arr = m.get(e.tag) ?? [];
881
+ arr.push(e.value);
882
+ m.set(e.tag, arr);
883
+ }
884
+ return m;
885
+ }
886
+ function validateTLVsAgainstSchema(schema, tlvs, depth = 0, limits = DEFAULT_LIMITS) {
887
+ if (depth > Math.min(schema.maxNestingDepth, limits.maxNestingDepth)) {
888
+ throw new Error("validateTLVsAgainstSchema: nesting depth exceeded");
889
+ }
890
+ if (schema.maxBodyBytes && tlvsBytes(tlvs) > schema.maxBodyBytes) {
891
+ throw new Error("validateTLVsAgainstSchema: body too large");
892
+ }
893
+ const byTag = /* @__PURE__ */ new Map();
894
+ for (const t of tlvs) {
895
+ if (!byTag.has(t.tag)) byTag.set(t.tag, []);
896
+ byTag.get(t.tag).push(t);
897
+ }
898
+ const fieldByTag = new Map(schema.fields.map((f) => [f.tag, f]));
899
+ if (schema.strict) {
900
+ for (const tag of byTag.keys()) {
901
+ if (!fieldByTag.has(tag))
902
+ throw new Error(`validateTLVsAgainstSchema: unknown tag ${tag}`);
903
+ }
904
+ }
905
+ for (const f of schema.fields) {
906
+ const vals = byTag.get(f.tag) ?? [];
907
+ if (f.required && vals.length === 0)
908
+ throw new Error(`validateTLVsAgainstSchema: missing ${f.name}`);
909
+ if (!f.repeated && vals.length > 1) {
910
+ throw new Error(
911
+ `validateTLVsAgainstSchema: duplicate tag not allowed for ${f.name}`
912
+ );
913
+ }
914
+ if (typeof f.maxLen === "number") {
915
+ for (const v of vals) {
916
+ if (v.value.length > f.maxLen)
917
+ throw new Error(`validateTLVsAgainstSchema: ${f.name} too long`);
918
+ }
919
+ }
920
+ for (const v of vals) {
921
+ switch (f.type) {
922
+ case "u64be":
923
+ if (v.value.length !== 8)
924
+ throw new Error(
925
+ `validateTLVsAgainstSchema: ${f.name} u64be must be 8 bytes`
926
+ );
927
+ break;
928
+ case "nested": {
929
+ if (!f.nestedSchema)
930
+ throw new Error(
931
+ `validateTLVsAgainstSchema: ${f.name} missing nestedSchema`
932
+ );
933
+ const nestedTlvs = decodeTLVStream(v.value, limits);
934
+ validateTLVsAgainstSchema(
935
+ f.nestedSchema,
936
+ nestedTlvs,
937
+ depth + 1,
938
+ limits
939
+ );
940
+ break;
941
+ }
942
+ default:
943
+ break;
944
+ }
945
+ }
946
+ }
947
+ }
948
+ function tlvsBytes(tlvs) {
949
+ let n = 0;
950
+ for (const t of tlvs) {
951
+ n += encodeUVarint(t.tag).length + encodeUVarint(t.value.length).length + t.value.length;
952
+ }
953
+ return n;
954
+ }
955
+ function logicalBodyToTLVs(schema, body, limits = DEFAULT_LIMITS) {
956
+ if (body.schemaId !== schema.schemaId)
957
+ throw new Error("logicalBodyToTLVs: schemaId mismatch");
958
+ const fieldsByName = new Map(schema.fields.map((f) => [f.name, f]));
959
+ const tlvs = [];
960
+ for (const [name, val] of Object.entries(body.fields ?? {})) {
961
+ const f = fieldsByName.get(name);
962
+ if (!f) {
963
+ if (schema.strict)
964
+ throw new Error(`logicalBodyToTLVs: unknown field ${name}`);
965
+ continue;
966
+ }
967
+ const pushOne = (v) => {
968
+ const valueBuf = encodeFieldValue(f, v, limits);
969
+ if (valueBuf.length > limits.maxValueBytes)
970
+ throw new Error("logicalBodyToTLVs: value too large");
971
+ tlvs.push({ tag: f.tag, value: valueBuf });
972
+ };
973
+ if (f.repeated) {
974
+ if (!Array.isArray(val))
975
+ throw new Error(
976
+ `logicalBodyToTLVs: repeated field ${name} must be array`
977
+ );
978
+ for (const item of val) pushOne(item);
979
+ } else {
980
+ pushOne(val);
981
+ }
982
+ }
983
+ validateTLVsAgainstSchema(schema, tlvs, 0, limits);
984
+ return tlvs;
985
+ }
986
+ function encodeFieldValue(f, val, limits) {
987
+ switch (f.type) {
988
+ case "bytes":
989
+ if (Buffer.isBuffer(val)) return Buffer.from(val);
990
+ if (val instanceof Uint8Array) return Buffer.from(val);
991
+ throw new Error(`encodeFieldValue: ${f.name} expects bytes`);
992
+ case "utf8":
993
+ if (typeof val !== "string")
994
+ throw new Error(`encodeFieldValue: ${f.name} expects string`);
995
+ return Buffer.from(val, "utf8");
996
+ case "uvarint":
997
+ if (typeof val !== "number" && typeof val !== "bigint")
998
+ throw new Error(`encodeFieldValue: ${f.name} expects number/bigint`);
999
+ return encodeUVarint(val);
1000
+ case "u64be":
1001
+ if (typeof val !== "bigint")
1002
+ throw new Error(`encodeFieldValue: ${f.name} expects bigint`);
1003
+ return encodeU64BE(val);
1004
+ case "nested": {
1005
+ if (!f.nestedSchema)
1006
+ throw new Error(`encodeFieldValue: ${f.name} missing nestedSchema`);
1007
+ const nestedFields = val && typeof val === "object" && "fields" in val ? val.fields : val;
1008
+ if (!nestedFields || typeof nestedFields !== "object")
1009
+ throw new Error(`encodeFieldValue: ${f.name} expects object`);
1010
+ const nestedBody = {
1011
+ schemaId: f.nestedSchema.schemaId,
1012
+ fields: nestedFields
1013
+ };
1014
+ const nestedTlvs = logicalBodyToTLVs(f.nestedSchema, nestedBody, limits);
1015
+ const nestedBytes = encodeTLVStreamCanonical(nestedTlvs);
1016
+ const re = decodeTLVStream(nestedBytes, limits);
1017
+ validateTLVsAgainstSchema(f.nestedSchema, re, 1, limits);
1018
+ return nestedBytes;
1019
+ }
1020
+ default:
1021
+ throw new Error(`encodeFieldValue: unsupported type ${f.type}`);
1022
+ }
1023
+ }
1024
+ function tlvsToLogicalBody(schema, tlvs, limits = DEFAULT_LIMITS) {
1025
+ validateTLVsAgainstSchema(schema, tlvs, 0, limits);
1026
+ const fields = {};
1027
+ const fieldByTag = new Map(schema.fields.map((f) => [f.tag, f]));
1028
+ for (const t of tlvs) {
1029
+ const f = fieldByTag.get(t.tag);
1030
+ if (!f) {
1031
+ if (schema.strict)
1032
+ throw new Error(`tlvsToLogicalBody: unknown tag ${t.tag}`);
1033
+ continue;
1034
+ }
1035
+ const decoded = decodeFieldValue(f, t.value, limits);
1036
+ if (f.repeated) {
1037
+ if (!Array.isArray(fields[f.name])) fields[f.name] = [];
1038
+ fields[f.name].push(decoded);
1039
+ } else {
1040
+ fields[f.name] = decoded;
1041
+ }
1042
+ }
1043
+ return { schemaId: schema.schemaId, fields };
1044
+ }
1045
+ function decodeFieldValue(f, value, limits) {
1046
+ switch (f.type) {
1047
+ case "bytes":
1048
+ return Buffer.from(value);
1049
+ case "utf8":
1050
+ return value.toString("utf8");
1051
+ case "uvarint": {
1052
+ const r = decodeUVarint(value, 0, limits);
1053
+ if (r.offset !== value.length)
1054
+ throw new Error(
1055
+ `decodeFieldValue: ${f.name} uvarint has trailing bytes`
1056
+ );
1057
+ const asNum = Number(r.value);
1058
+ return Number.isSafeInteger(asNum) ? asNum : r.value;
1059
+ }
1060
+ case "u64be":
1061
+ return decodeU64BE(value);
1062
+ case "nested": {
1063
+ if (!f.nestedSchema)
1064
+ throw new Error(`decodeFieldValue: ${f.name} missing nestedSchema`);
1065
+ const nestedTlvs = decodeTLVStream(value, limits);
1066
+ const nestedBody = tlvsToLogicalBody(f.nestedSchema, nestedTlvs, limits);
1067
+ return nestedBody.fields;
1068
+ }
1069
+ default:
1070
+ throw new Error(`decodeFieldValue: unsupported type ${f.type}`);
1071
+ }
1072
+ }
1073
+ var HDR_TAGS = {
1074
+ intent_id: 1,
1075
+ actor_key_id: 2,
1076
+ capsule_id: 3,
1077
+ nonce: 4,
1078
+ ts_ms: 5,
1079
+ schema_id: 6,
1080
+ body_hash: 7,
1081
+ trace_id: 8
1082
+ };
1083
+ function encodeAxisHeaderToTLVs(hdr) {
1084
+ if (hdr.nonce.byteLength !== 16)
1085
+ throw new Error("encodeAxisHeaderToTLVs: nonce must be 16 bytes");
1086
+ if (hdr.bodyHash.byteLength !== 32)
1087
+ throw new Error("encodeAxisHeaderToTLVs: bodyHash must be 32 bytes");
1088
+ if (hdr.traceId && hdr.traceId.byteLength !== 16)
1089
+ throw new Error("encodeAxisHeaderToTLVs: traceId must be 16 bytes");
1090
+ const tlvs = [
1091
+ { tag: HDR_TAGS.intent_id, value: encodeUVarint(hdr.intentId) },
1092
+ { tag: HDR_TAGS.actor_key_id, value: Buffer.from(hdr.actorKeyId) },
1093
+ { tag: HDR_TAGS.nonce, value: Buffer.from(hdr.nonce) },
1094
+ { tag: HDR_TAGS.ts_ms, value: encodeU64BE(hdr.tsMs) },
1095
+ { tag: HDR_TAGS.schema_id, value: encodeUVarint(hdr.schemaId) },
1096
+ { tag: HDR_TAGS.body_hash, value: Buffer.from(hdr.bodyHash) }
1097
+ ];
1098
+ if (hdr.capsuleId)
1099
+ tlvs.push({ tag: HDR_TAGS.capsule_id, value: Buffer.from(hdr.capsuleId) });
1100
+ if (hdr.traceId)
1101
+ tlvs.push({ tag: HDR_TAGS.trace_id, value: Buffer.from(hdr.traceId) });
1102
+ return tlvs;
1103
+ }
1104
+ function decodeAxisHeaderFromTLVs(hdrTlvs, limits = DEFAULT_LIMITS) {
1105
+ const m = tlvsToMap(hdrTlvs);
1106
+ const get1 = (tag) => {
1107
+ const arr = m.get(tag);
1108
+ if (!arr || arr.length !== 1)
1109
+ throw new Error(
1110
+ `decodeAxisHeaderFromTLVs: missing/dup header tag ${tag}`
1111
+ );
1112
+ return arr[0];
1113
+ };
1114
+ const getOpt1 = (tag) => {
1115
+ const arr = m.get(tag);
1116
+ if (!arr) return void 0;
1117
+ if (arr.length !== 1)
1118
+ throw new Error(`decodeAxisHeaderFromTLVs: dup header tag ${tag}`);
1119
+ return arr[0];
1120
+ };
1121
+ const intentIdVar = decodeUVarint(get1(HDR_TAGS.intent_id), 0, limits);
1122
+ if (intentIdVar.offset !== get1(HDR_TAGS.intent_id).length)
1123
+ throw new Error("decodeAxisHeaderFromTLVs: intent_id trailing bytes");
1124
+ const schemaIdVar = decodeUVarint(get1(HDR_TAGS.schema_id), 0, limits);
1125
+ if (schemaIdVar.offset !== get1(HDR_TAGS.schema_id).length)
1126
+ throw new Error("decodeAxisHeaderFromTLVs: schema_id trailing bytes");
1127
+ const ts = decodeU64BE(get1(HDR_TAGS.ts_ms));
1128
+ const nonce = get1(HDR_TAGS.nonce);
1129
+ if (nonce.length !== 16)
1130
+ throw new Error("decodeAxisHeaderFromTLVs: nonce must be 16 bytes");
1131
+ const bodyHash = get1(HDR_TAGS.body_hash);
1132
+ if (bodyHash.length !== 32)
1133
+ throw new Error("decodeAxisHeaderFromTLVs: body_hash must be 32 bytes");
1134
+ const trace = getOpt1(HDR_TAGS.trace_id);
1135
+ if (trace && trace.length !== 16)
1136
+ throw new Error("decodeAxisHeaderFromTLVs: trace_id must be 16 bytes");
1137
+ return {
1138
+ intentId: Number(intentIdVar.value),
1139
+ actorKeyId: Buffer.from(get1(HDR_TAGS.actor_key_id)),
1140
+ capsuleId: getOpt1(HDR_TAGS.capsule_id) ? Buffer.from(getOpt1(HDR_TAGS.capsule_id)) : void 0,
1141
+ nonce: Buffer.from(nonce),
1142
+ tsMs: ts,
1143
+ schemaId: Number(schemaIdVar.value),
1144
+ bodyHash: Buffer.from(bodyHash),
1145
+ traceId: trace ? Buffer.from(trace) : void 0
1146
+ };
1147
+ }
1148
+ function encodeAxisRequestBinary(schema, req, limits = DEFAULT_LIMITS) {
1149
+ const bodyTlvs = logicalBodyToTLVs(schema, req.body, limits);
1150
+ const bodyBytes = encodeTLVStreamCanonical(bodyTlvs);
1151
+ const bodyHash = sha2562(bodyBytes);
1152
+ const hdr = {
1153
+ ...req.hdr,
1154
+ schemaId: schema.schemaId,
1155
+ bodyHash
1156
+ };
1157
+ const hdrTlvs = encodeAxisHeaderToTLVs(hdr);
1158
+ const hdrBytes = encodeTLVStreamCanonical(hdrTlvs);
1159
+ return { hdrBytes, bodyBytes, bodyHash };
1160
+ }
1161
+ function decodeAxisRequestBinary(schema, hdrBytes, bodyBytes, limits = DEFAULT_LIMITS) {
1162
+ const hdrTlvs = decodeTLVStream(hdrBytes, limits);
1163
+ const bodyTlvs = decodeTLVStream(bodyBytes, limits);
1164
+ const hdr = decodeAxisHeaderFromTLVs(hdrTlvs, limits);
1165
+ if (hdr.schemaId !== schema.schemaId)
1166
+ throw new Error("decodeAxisRequestBinary: schemaId mismatch");
1167
+ const bh = sha2562(bodyBytes);
1168
+ if (!Buffer.from(hdr.bodyHash).equals(bh))
1169
+ throw new Error("decodeAxisRequestBinary: body_hash mismatch");
1170
+ const body = tlvsToLogicalBody(schema, bodyTlvs, limits);
1171
+ const sensorInput = {
1172
+ hdrTLVs: tlvsToMap(hdrTlvs),
1173
+ bodyTLVs: tlvsToMap(bodyTlvs),
1174
+ schemaId: hdr.schemaId,
1175
+ intentId: hdr.intentId
1176
+ };
1177
+ return { hdr, body, sensorInput };
1178
+ }
1179
+ var Schema3100_DeviceContext = {
1180
+ schemaId: 3100,
1181
+ name: "device.context",
1182
+ strict: true,
1183
+ maxNestingDepth: 4,
1184
+ fields: [
1185
+ { tag: 1, name: "deviceId", type: "bytes", required: true, maxLen: 128 },
1186
+ { tag: 2, name: "os", type: "utf8", required: true, maxLen: 64 },
1187
+ { tag: 3, name: "hw", type: "utf8", required: true, maxLen: 64 }
1188
+ ]
1189
+ };
1190
+ var Schema2001_PasskeyLoginOptionsReq = {
1191
+ schemaId: 2001,
1192
+ name: "axis.auth.passkey.login.options.req",
1193
+ strict: true,
1194
+ maxNestingDepth: 4,
1195
+ fields: [
1196
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 }
1197
+ ]
1198
+ };
1199
+ var Schema4001_LoginWithDeviceReq = {
1200
+ schemaId: 4001,
1201
+ name: "axis.auth.login.with_device.req",
1202
+ strict: true,
1203
+ maxNestingDepth: 4,
1204
+ fields: [
1205
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 },
1206
+ {
1207
+ tag: 2,
1208
+ name: "device",
1209
+ type: "nested",
1210
+ required: true,
1211
+ nestedSchema: Schema3100_DeviceContext
1212
+ }
1213
+ ]
1214
+ };
1215
+
1216
+ // src/codec/ats1.passkey.schemas.ts
1217
+ function buildAts1Hdr(params) {
1218
+ const hdr = {
1219
+ intentId: params.intentId,
1220
+ schemaId: params.schemaId,
1221
+ actorKeyId: params.actorKeyId ?? Buffer.alloc(0),
1222
+ capsuleId: params.capsuleId,
1223
+ nonce: params.nonce ?? require("crypto").randomBytes(16),
1224
+ tsMs: params.tsMs ?? BigInt(Date.now()),
1225
+ bodyHash: params.bodyHash ?? Buffer.alloc(32),
1226
+ traceId: params.traceId
1227
+ };
1228
+ const tlvs = encodeAxisHeaderToTLVs(hdr);
1229
+ return encodeTLVStreamCanonical(tlvs);
1230
+ }
1231
+ function packPasskeyLoginOptionsReq(params) {
1232
+ const bodyTlvs = logicalBodyToTLVs(
1233
+ Schema2001_PasskeyLoginOptionsReq,
1234
+ {
1235
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_REQ,
1236
+ fields: { username: params.username }
1237
+ }
1238
+ );
1239
+ const body = encodeTLVStreamCanonical(bodyTlvs);
1240
+ const bodyHash = sha2562(body);
1241
+ const hdr = buildAts1Hdr({
1242
+ intentId: params.intentId,
1243
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_REQ,
1244
+ actorKeyId: params.actorKeyId,
1245
+ capsuleId: params.capsuleId,
1246
+ traceId: params.traceId,
1247
+ bodyHash
1248
+ });
1249
+ return { hdr, body };
1250
+ }
1251
+ function unpackPasskeyLoginOptionsReq(body) {
1252
+ const tlvs = decodeTLVStream(body);
1253
+ const decoded = tlvsToLogicalBody(
1254
+ Schema2001_PasskeyLoginOptionsReq,
1255
+ tlvs
1256
+ );
1257
+ return { username: decoded.fields.username };
1258
+ }
1259
+ var Schema2021_PasskeyRegisterOptionsReq = {
1260
+ schemaId: ATS1_SCHEMA.PASSKEY_REGISTER_OPTIONS_REQ,
1261
+ name: "axis.auth.passkey.register.options.req",
1262
+ strict: true,
1263
+ maxNestingDepth: 4,
1264
+ fields: [
1265
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 }
1266
+ ]
1267
+ };
1268
+ var Schema2011_PasskeyLoginVerifyReq = {
1269
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_REQ,
1270
+ name: "axis.auth.passkey.login.verify.req",
1271
+ strict: true,
1272
+ maxNestingDepth: 4,
1273
+ fields: [
1274
+ { tag: 1, name: "username", type: "utf8", required: true, maxLen: 128 },
1275
+ {
1276
+ tag: 2,
1277
+ name: "credentialId",
1278
+ type: "bytes",
1279
+ required: true,
1280
+ maxLen: 1024
1281
+ },
1282
+ {
1283
+ tag: 3,
1284
+ name: "clientDataJSON",
1285
+ type: "bytes",
1286
+ required: true,
1287
+ maxLen: 4096
1288
+ },
1289
+ {
1290
+ tag: 4,
1291
+ name: "authenticatorData",
1292
+ type: "bytes",
1293
+ required: true,
1294
+ maxLen: 1024
1295
+ },
1296
+ { tag: 5, name: "signature", type: "bytes", required: true, maxLen: 1024 },
1297
+ { tag: 6, name: "userHandle", type: "bytes", required: false, maxLen: 128 }
1298
+ ]
1299
+ };
1300
+ function packPasskeyRegisterOptionsReq(params) {
1301
+ const bodyTlvs = logicalBodyToTLVs(
1302
+ Schema2021_PasskeyRegisterOptionsReq,
1303
+ {
1304
+ schemaId: ATS1_SCHEMA.PASSKEY_REGISTER_OPTIONS_REQ,
1305
+ fields: { username: params.username }
1306
+ }
1307
+ );
1308
+ const body = encodeTLVStreamCanonical(bodyTlvs);
1309
+ const bodyHash = sha2562(body);
1310
+ const hdr = buildAts1Hdr({
1311
+ intentId: params.intentId,
1312
+ schemaId: ATS1_SCHEMA.PASSKEY_REGISTER_OPTIONS_REQ,
1313
+ actorKeyId: params.actorKeyId,
1314
+ traceId: params.traceId,
1315
+ bodyHash
1316
+ });
1317
+ return { hdr, body };
1318
+ }
1319
+ function unpackPasskeyRegisterOptionsReq(body) {
1320
+ const tlvs = decodeTLVStream(body);
1321
+ const decoded = tlvsToLogicalBody(
1322
+ Schema2021_PasskeyRegisterOptionsReq,
1323
+ tlvs
1324
+ );
1325
+ return { username: decoded.fields.username };
1326
+ }
1327
+ function packPasskeyLoginVerifyReq(params) {
1328
+ const bodyTlvs = logicalBodyToTLVs(Schema2011_PasskeyLoginVerifyReq, {
1329
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_REQ,
1330
+ fields: {
1331
+ username: params.username,
1332
+ credentialId: params.credentialId,
1333
+ clientDataJSON: params.clientDataJSON,
1334
+ authenticatorData: params.authenticatorData,
1335
+ signature: params.signature,
1336
+ userHandle: params.userHandle
1337
+ }
1338
+ });
1339
+ const body = encodeTLVStreamCanonical(bodyTlvs);
1340
+ const bodyHash = sha2562(body);
1341
+ const hdr = buildAts1Hdr({
1342
+ intentId: params.intentId,
1343
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_REQ,
1344
+ actorKeyId: params.actorKeyId,
1345
+ traceId: params.traceId,
1346
+ bodyHash
1347
+ });
1348
+ return { hdr, body };
1349
+ }
1350
+ function unpackPasskeyLoginVerifyReq(body) {
1351
+ const tlvs = decodeTLVStream(body);
1352
+ const decoded = tlvsToLogicalBody(
1353
+ Schema2011_PasskeyLoginVerifyReq,
1354
+ tlvs
1355
+ );
1356
+ const f = decoded.fields;
1357
+ return {
1358
+ username: f.username,
1359
+ credentialId: f.credentialId,
1360
+ clientDataJSON: f.clientDataJSON,
1361
+ authenticatorData: f.authenticatorData,
1362
+ signature: f.signature,
1363
+ userHandle: f.userHandle
1364
+ };
1365
+ }
1366
+ var Schema2002_PasskeyLoginOptionsRes = {
1367
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_RES,
1368
+ name: "axis.auth.passkey.login.options.res",
1369
+ strict: false,
1370
+ // allow extra fields from WebAuthn library
1371
+ maxNestingDepth: 4,
1372
+ fields: [
1373
+ { tag: 1, name: "challenge", type: "utf8", required: true },
1374
+ // base64url string
1375
+ { tag: 2, name: "timeout", type: "uvarint", required: false },
1376
+ { tag: 3, name: "rpId", type: "utf8", required: false },
1377
+ { tag: 4, name: "userVerification", type: "utf8", required: false },
1378
+ { tag: 5, name: "allowCredentialsJson", type: "utf8", required: false }
1379
+ // JSON array for simplicity
1380
+ ]
1381
+ };
1382
+ function packPasskeyLoginOptionsRes(params) {
1383
+ const fields = {
1384
+ challenge: params.challenge
1385
+ };
1386
+ if (params.timeout !== void 0) fields.timeout = params.timeout;
1387
+ if (params.rpId) fields.rpId = params.rpId;
1388
+ if (params.userVerification)
1389
+ fields.userVerification = params.userVerification;
1390
+ if (params.allowCredentials)
1391
+ fields.allowCredentialsJson = JSON.stringify(params.allowCredentials);
1392
+ const bodyTlvs = logicalBodyToTLVs(Schema2002_PasskeyLoginOptionsRes, {
1393
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_OPTIONS_RES,
1394
+ fields
1395
+ });
1396
+ return encodeTLVStreamCanonical(bodyTlvs);
1397
+ }
1398
+ var Schema2012_PasskeyLoginVerifyRes = {
1399
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_RES,
1400
+ name: "axis.auth.passkey.login.verify.res",
1401
+ strict: true,
1402
+ maxNestingDepth: 4,
1403
+ fields: [
1404
+ { tag: 1, name: "actorId", type: "utf8", required: true, maxLen: 256 },
1405
+ { tag: 2, name: "keyId", type: "utf8", required: true, maxLen: 256 },
1406
+ { tag: 3, name: "capsule", type: "bytes", required: true, maxLen: 4096 },
1407
+ { tag: 4, name: "expiresAt", type: "u64be", required: true }
1408
+ ]
1409
+ };
1410
+ function packPasskeyLoginVerifyRes(params) {
1411
+ const bodyTlvs = logicalBodyToTLVs(Schema2012_PasskeyLoginVerifyRes, {
1412
+ schemaId: ATS1_SCHEMA.PASSKEY_LOGIN_VERIFY_RES,
1413
+ fields: {
1414
+ actorId: params.actorId,
1415
+ keyId: params.keyId,
1416
+ capsule: params.capsule,
1417
+ expiresAt: params.expiresAt
1418
+ }
1419
+ });
1420
+ return encodeTLVStreamCanonical(bodyTlvs);
1421
+ }
1422
+
1423
+ // src/codec/tlv.encode.ts
1424
+ var import_crypto2 = require("crypto");
1425
+ function encVarint(x) {
1426
+ if (x < 0n) throw new Error("VARINT_NEG");
1427
+ const out = [];
1428
+ while (x >= 0x80n) {
1429
+ out.push(Number(x & 0x7fn | 0x80n));
1430
+ x >>= 7n;
1431
+ }
1432
+ out.push(Number(x));
1433
+ return Buffer.from(out);
1434
+ }
1435
+ function varintU(x) {
1436
+ const v = typeof x === "number" ? BigInt(x) : x;
1437
+ return encVarint(v);
1438
+ }
1439
+ function u64be(x) {
1440
+ if (x < 0n) throw new Error("U64_NEG");
1441
+ const b = Buffer.alloc(8);
1442
+ b.writeBigUInt64BE(x, 0);
1443
+ return b;
1444
+ }
1445
+ function utf8(s) {
1446
+ return Buffer.from(s, "utf8");
1447
+ }
1448
+ function bytes(b) {
1449
+ return Buffer.isBuffer(b) ? b : Buffer.from(b);
1450
+ }
1451
+ function nonce16() {
1452
+ return (0, import_crypto2.randomBytes)(16);
1453
+ }
1454
+ function tlv(type, value) {
1455
+ if (!Number.isSafeInteger(type) || type < 0) throw new Error("TLV_BAD_TYPE");
1456
+ return Buffer.concat([
1457
+ encVarint(BigInt(type)),
1458
+ encVarint(BigInt(value.length)),
1459
+ value
1460
+ ]);
1461
+ }
1462
+ function buildTLVs(items, opts) {
1463
+ const allow = opts?.allowDupTypes ?? /* @__PURE__ */ new Set();
1464
+ const sorted = [...items].sort((a, b) => a.type - b.type);
1465
+ for (let i = 1; i < sorted.length; i++) {
1466
+ if (sorted[i].type === sorted[i - 1].type && !allow.has(sorted[i].type)) {
1467
+ throw new Error(`TLV_DUP_TYPE_${sorted[i].type}`);
1468
+ }
1469
+ }
1470
+ return Buffer.concat(sorted.map((it) => tlv(it.type, it.value)));
1471
+ }
1472
+
1473
+ // src/codec/axis1.encode.ts
1474
+ var MAGIC = Buffer.from("AXIS1", "ascii");
1475
+ function encodeAxis1Frame(f) {
1476
+ if (!Buffer.isBuffer(f.hdr) || !Buffer.isBuffer(f.body) || !Buffer.isBuffer(f.sig)) {
1477
+ throw new Error("AXIS1_BAD_BUFFERS");
1478
+ }
1479
+ if (f.ver !== 1) throw new Error("AXIS1_BAD_VER");
1480
+ const hdrLen = encVarint(BigInt(f.hdr.length));
1481
+ const bodyLen = encVarint(BigInt(f.body.length));
1482
+ const sigLen = encVarint(BigInt(f.sig.length));
1483
+ return Buffer.concat([
1484
+ MAGIC,
1485
+ Buffer.from([f.ver & 255]),
1486
+ Buffer.from([f.flags & 255]),
1487
+ hdrLen,
1488
+ bodyLen,
1489
+ sigLen,
1490
+ f.hdr,
1491
+ f.body,
1492
+ f.sig
1493
+ ]);
1494
+ }
1495
+
1496
+ // src/codec/axis1.signing.ts
1497
+ var MAGIC2 = Buffer.from("AXIS1", "ascii");
1498
+ function axis1SigningBytes(params) {
1499
+ if (params.ver !== 1) throw new Error("AXIS1_BAD_VER");
1500
+ const hdrLen = encVarint(BigInt(params.hdr.length));
1501
+ const bodyLen = encVarint(BigInt(params.body.length));
1502
+ const sigLenZero = encVarint(0n);
1503
+ return Buffer.concat([
1504
+ MAGIC2,
1505
+ Buffer.from([params.ver & 255]),
1506
+ Buffer.from([params.flags & 255]),
1507
+ hdrLen,
1508
+ bodyLen,
1509
+ sigLenZero,
1510
+ params.hdr,
1511
+ params.body
1512
+ ]);
1513
+ }
1514
+
1515
+ // src/crypto/b64url.ts
1516
+ function b64urlEncode(buf) {
1517
+ return buf.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
1518
+ }
1519
+ function b64urlDecode(str) {
1520
+ const pad = str.length % 4 ? "=".repeat(4 - str.length % 4) : "";
1521
+ const base64 = (str + pad).replace(/-/g, "+").replace(/_/g, "/");
1522
+ return Buffer.from(base64, "base64");
1523
+ }
1524
+ function b64urlEncodeString(str, encoding = "utf8") {
1525
+ return b64urlEncode(Buffer.from(str, encoding));
1526
+ }
1527
+ function b64urlDecodeString(str, encoding = "utf8") {
1528
+ return b64urlDecode(str).toString(encoding);
1529
+ }
1530
+
1531
+ // src/crypto/canonical-json.ts
1532
+ function sortRec(value) {
1533
+ if (value === null) {
1534
+ return null;
1535
+ }
1536
+ if (value === void 0) {
1537
+ return void 0;
1538
+ }
1539
+ if (Array.isArray(value)) {
1540
+ return value.map(sortRec);
1541
+ }
1542
+ if (typeof value === "object") {
1543
+ const sorted = {};
1544
+ const keys = Object.keys(value).sort();
1545
+ for (const key of keys) {
1546
+ const sortedValue = sortRec(value[key]);
1547
+ if (sortedValue !== void 0) {
1548
+ sorted[key] = sortedValue;
1549
+ }
1550
+ }
1551
+ return sorted;
1552
+ }
1553
+ return value;
1554
+ }
1555
+ function canonicalJson(value) {
1556
+ return JSON.stringify(sortRec(value));
1557
+ }
1558
+ function canonicalJsonExcluding(obj, exclude) {
1559
+ const filtered = {};
1560
+ for (const key in obj) {
1561
+ if (!exclude.includes(key) && obj[key] !== void 0) {
1562
+ filtered[key] = obj[key];
1563
+ }
1564
+ }
1565
+ return canonicalJson(filtered);
1566
+ }
1567
+
1568
+ // src/contract/execution-meter.ts
1569
+ var ContractViolationError = class extends Error {
1570
+ constructor(code, message) {
1571
+ super(message);
1572
+ this.code = code;
1573
+ this.name = "ContractViolationError";
1574
+ }
1575
+ };
1576
+ var ExecutionMeter = class {
1577
+ // ExecutionContract
1578
+ constructor(contract) {
1579
+ this.dbWrites = 0;
1580
+ this.dbReads = 0;
1581
+ this.externalCalls = 0;
1582
+ this.contract = contract;
1583
+ this.startTime = Date.now();
1584
+ }
1585
+ recordDbWrite() {
1586
+ this.dbWrites++;
1587
+ if (this.dbWrites > this.contract.maxDbWrites) {
1588
+ throw new ContractViolationError(
1589
+ "MAX_DB_WRITES_EXCEEDED",
1590
+ `DB writes exceeded: ${this.dbWrites}/${this.contract.maxDbWrites}`
1591
+ );
1592
+ }
1593
+ }
1594
+ recordDbRead() {
1595
+ this.dbReads++;
1596
+ if (this.contract.maxDbReads && this.dbReads > this.contract.maxDbReads) {
1597
+ throw new ContractViolationError(
1598
+ "MAX_DB_READS_EXCEEDED",
1599
+ `DB reads exceeded: ${this.dbReads}/${this.contract.maxDbReads}`
1600
+ );
1601
+ }
1602
+ }
1603
+ recordExternalCall() {
1604
+ this.externalCalls++;
1605
+ if (this.externalCalls > this.contract.maxExternalCalls) {
1606
+ throw new ContractViolationError(
1607
+ "MAX_EXTERNAL_CALLS_EXCEEDED",
1608
+ `External calls exceeded: ${this.externalCalls}/${this.contract.maxExternalCalls}`
1609
+ );
1610
+ }
1611
+ }
1612
+ checkTime() {
1613
+ const elapsed = Date.now() - this.startTime;
1614
+ if (elapsed > this.contract.maxTimeMs) {
1615
+ throw new ContractViolationError(
1616
+ "MAX_TIME_EXCEEDED",
1617
+ `Execution time exceeded: ${elapsed}ms/${this.contract.maxTimeMs}ms`
1618
+ );
1619
+ }
1620
+ }
1621
+ validateEffect(effect) {
1622
+ if (this.contract.allowedEffects.includes("*")) {
1623
+ return;
1624
+ }
1625
+ if (!this.contract.allowedEffects.includes(effect)) {
1626
+ throw new ContractViolationError(
1627
+ "INVALID_EFFECT",
1628
+ `Effect '${effect}' not allowed. Allowed: ${this.contract.allowedEffects.join(", ")}`
1629
+ );
1630
+ }
1631
+ }
1632
+ getMetrics() {
1633
+ return {
1634
+ dbWrites: this.dbWrites,
1635
+ dbReads: this.dbReads,
1636
+ externalCalls: this.externalCalls,
1637
+ elapsedMs: Date.now() - this.startTime
1638
+ };
1639
+ }
1640
+ getContract() {
1641
+ return this.contract;
1642
+ }
1643
+ };
1644
+
1645
+ // src/contract/contract.interface.ts
1646
+ var DEFAULT_CONTRACTS = {
1647
+ // System intents
1648
+ "system.ping": {
1649
+ maxDbWrites: 0,
1650
+ maxExternalCalls: 0,
1651
+ maxTimeMs: 100,
1652
+ allowedEffects: ["system.pong"]
1653
+ },
1654
+ // Catalog intents
1655
+ "catalog.list": {
1656
+ maxDbWrites: 0,
1657
+ maxExternalCalls: 0,
1658
+ maxTimeMs: 200,
1659
+ allowedEffects: ["catalog.listed"]
1660
+ },
1661
+ "catalog.search": {
1662
+ maxDbWrites: 0,
1663
+ maxExternalCalls: 0,
1664
+ maxTimeMs: 300,
1665
+ allowedEffects: ["catalog.searched"]
1666
+ },
1667
+ // Passport intents
1668
+ "passport.issue": {
1669
+ maxDbWrites: 10,
1670
+ maxExternalCalls: 0,
1671
+ maxTimeMs: 500,
1672
+ allowedEffects: ["passport.issued", "passport.rejected"]
1673
+ },
1674
+ "passport.revoke": {
1675
+ maxDbWrites: 5,
1676
+ maxExternalCalls: 0,
1677
+ maxTimeMs: 300,
1678
+ allowedEffects: ["passport.revoked", "passport.revoke_failed"]
1679
+ },
1680
+ // File intents
1681
+ "file.init": {
1682
+ maxDbWrites: 2,
1683
+ maxExternalCalls: 0,
1684
+ maxTimeMs: 200,
1685
+ allowedEffects: ["file.initialized"]
1686
+ },
1687
+ "file.chunk": {
1688
+ maxDbWrites: 2,
1689
+ maxExternalCalls: 0,
1690
+ maxTimeMs: 1e3,
1691
+ allowedEffects: ["file.chunk.stored"]
1692
+ },
1693
+ "file.finalize": {
1694
+ maxDbWrites: 2,
1695
+ maxExternalCalls: 0,
1696
+ maxTimeMs: 500,
1697
+ allowedEffects: ["file.finalized"]
1698
+ },
1699
+ // Stream intents
1700
+ "stream.publish": {
1701
+ maxDbWrites: 1,
1702
+ maxExternalCalls: 0,
1703
+ maxTimeMs: 200,
1704
+ allowedEffects: ["stream.published"]
1705
+ },
1706
+ "stream.read": {
1707
+ maxDbWrites: 0,
1708
+ maxExternalCalls: 0,
1709
+ maxTimeMs: 300,
1710
+ allowedEffects: ["stream.data"]
1711
+ },
1712
+ // Mail intents
1713
+ "mail.send": {
1714
+ maxDbWrites: 3,
1715
+ maxExternalCalls: 1,
1716
+ // Email service
1717
+ maxTimeMs: 2e3,
1718
+ allowedEffects: ["mail.sent", "mail.failed"]
1719
+ }
1720
+ };
1721
+ var FALLBACK_CONTRACT = {
1722
+ maxDbWrites: 10,
1723
+ maxExternalCalls: 0,
1724
+ maxTimeMs: 1e3,
1725
+ allowedEffects: ["*"]
1726
+ // Allow any effect
1727
+ };
1728
+
1729
+ // src/types/tlv.ts
1730
+ function decVarint(buf, off) {
1731
+ let shift = 0n;
1732
+ let x = 0n;
1733
+ while (true) {
1734
+ if (off >= buf.length) throw new Error("varint overflow");
1735
+ const b = BigInt(buf[off++]);
1736
+ x |= (b & 0x7fn) << shift;
1737
+ if ((b & 0x80n) === 0n) break;
1738
+ shift += 7n;
1739
+ if (shift > 63n) throw new Error("varint too large");
1740
+ }
1741
+ return { val: x, off };
1742
+ }
1743
+ function parseTLVs(buf, maxItems = 512) {
1744
+ const out = [];
1745
+ let off = 0;
1746
+ while (off < buf.length) {
1747
+ if (out.length >= maxItems) throw new Error("TLV_TOO_MANY_ITEMS");
1748
+ const t1 = decVarint(buf, off);
1749
+ off = t1.off;
1750
+ const t2 = decVarint(buf, off);
1751
+ off = t2.off;
1752
+ const type = Number(t1.val);
1753
+ const len = Number(t2.val);
1754
+ if (len < 0 || off + len > buf.length) {
1755
+ throw new Error("TLV_LEN_INVALID");
1756
+ }
1757
+ const value = buf.subarray(off, off + len);
1758
+ off += len;
1759
+ out.push({ type, value });
1760
+ }
1761
+ return out;
1762
+ }
1763
+ function tlvMap(buf) {
1764
+ const m = /* @__PURE__ */ new Map();
1765
+ for (const it of parseTLVs(buf)) {
1766
+ const arr = m.get(it.type) ?? [];
1767
+ arr.push(it.value);
1768
+ m.set(it.type, arr);
1769
+ }
1770
+ return m;
1771
+ }
1772
+ function asUtf8(b) {
1773
+ if (!b) return void 0;
1774
+ return b.toString("utf8");
1775
+ }
1776
+ function asBigintVarint(b) {
1777
+ if (!b) return void 0;
1778
+ const { val, off } = decVarint(b, 0);
1779
+ if (off !== b.length) throw new Error("VARINT_TRAILING_BYTES");
1780
+ return val;
1781
+ }
1782
+ function asBigint64BE(b) {
1783
+ if (!b) return void 0;
1784
+ if (b.length !== 8) throw new Error("Expected 8 bytes for u64");
1785
+ return b.readBigUInt64BE(0);
1786
+ }
1787
+
1788
+ // src/types/frame.ts
1789
+ var MAGIC3 = Buffer.from("AXIS1", "ascii");
1790
+ function decodeAxis1Frame(buf) {
1791
+ let off = 0;
1792
+ const magic = buf.subarray(off, off + 5);
1793
+ off += 5;
1794
+ if (magic.length !== 5 || !magic.equals(MAGIC3))
1795
+ throw new Error("AXIS1_BAD_MAGIC");
1796
+ if (off + 2 > buf.length) throw new Error("AXIS1_TRUNCATED");
1797
+ const ver = buf[off++];
1798
+ const flags = buf[off++];
1799
+ const h1 = decVarint(buf, off);
1800
+ off = h1.off;
1801
+ const b1 = decVarint(buf, off);
1802
+ off = b1.off;
1803
+ const s1 = decVarint(buf, off);
1804
+ off = s1.off;
1805
+ const hdrLen = Number(h1.val);
1806
+ const bodyLen = Number(b1.val);
1807
+ const sigLen = Number(s1.val);
1808
+ if (hdrLen < 0 || bodyLen < 0 || sigLen < 0) throw new Error("AXIS1_LEN_NEG");
1809
+ if (off + hdrLen + bodyLen + sigLen > buf.length)
1810
+ throw new Error("AXIS1_TRUNCATED_PAYLOAD");
1811
+ const hdr = buf.subarray(off, off + hdrLen);
1812
+ off += hdrLen;
1813
+ const body = buf.subarray(off, off + bodyLen);
1814
+ off += bodyLen;
1815
+ const sig = buf.subarray(off, off + sigLen);
1816
+ off += sigLen;
1817
+ if (off !== buf.length) throw new Error("AXIS1_TRAILING_BYTES");
1818
+ return { ver, flags, hdr, body, sig, frameSize: buf.length };
1819
+ }
1820
+
1821
+ // src/types/packet.ts
1822
+ var T = {
1823
+ /** The specific intent or action (e.g., 'vault.create') */
1824
+ INTENT: TLV_INTENT,
1825
+ /** Package identifier / ID */
1826
+ PID: TLV_PID,
1827
+ /** Versioning of the intent schema */
1828
+ INTENT_VERSION: 10,
1829
+ // Defaulting to TRACE_ID for now or a new tag if available
1830
+ /** Unique identifier for the requesting actor */
1831
+ ACTOR_ID: TLV_ACTOR_ID,
1832
+ /** Optional Capability Token identifier (16 bytes) */
1833
+ CAPSULE_ID: TLV_PROOF_REF,
1834
+ /** Unique session/request identifier (16 bytes) */
1835
+ NONCE: TLV_NONCE,
1836
+ /** High-precision Unix timestamp in milliseconds */
1837
+ TS_MS: TLV_TS,
1838
+ /** Proof type */
1839
+ PROOF_TYPE: TLV_PROOF_TYPE,
1840
+ /** Standard binary body tag */
1841
+ BODY: 100,
1842
+ /** Standard JSON-encoded body tag */
1843
+ JSON: 200
1844
+ };
1845
+ function buildPacket(hdr, body, sig, flags = 0) {
1846
+ const hm = tlvMap(hdr);
1847
+ const BODY_IS_TLV = 1;
1848
+ const bm = flags & BODY_IS_TLV ? tlvMap(body) : /* @__PURE__ */ new Map();
1849
+ const intent = asUtf8(hm.get(T.INTENT)?.[0]);
1850
+ const intentVerRaw = hm.get(T.INTENT_VERSION)?.[0];
1851
+ const intentVer = intentVerRaw ? Number(asBigintVarint(intentVerRaw)) : 1;
1852
+ const actorIdRaw = hm.get(T.ACTOR_ID)?.[0];
1853
+ const actorId = actorIdRaw ? actorIdRaw.toString("hex") : void 0;
1854
+ const capsuleId = hm.get(T.CAPSULE_ID)?.[0];
1855
+ const pid = hm.get(T.PID)?.[0] || hm.get(T.NONCE)?.[0];
1856
+ const nonce = hm.get(T.NONCE)?.[0];
1857
+ const tsMs = asBigint64BE(hm.get(T.TS_MS)?.[0]);
1858
+ if (!intent) throw new Error("PACKET_MISSING_INTENT");
1859
+ if (!actorId) throw new Error("PACKET_MISSING_ACTOR_ID");
1860
+ if (!nonce || nonce.length < 16 || nonce.length > 32)
1861
+ throw new Error("PACKET_BAD_NONCE");
1862
+ if (!pid) throw new Error("PACKET_MISSING_PID");
1863
+ if (!tsMs) throw new Error("PACKET_MISSING_TS");
1864
+ return {
1865
+ intent,
1866
+ intentVersion: intentVer,
1867
+ actorId,
1868
+ capsuleId,
1869
+ pid,
1870
+ nonce,
1871
+ tsMs,
1872
+ headersMap: hm,
1873
+ bodyMap: bm,
1874
+ hdrBytes: hdr,
1875
+ bodyBytes: body,
1876
+ sig
1877
+ };
1878
+ }
1879
+
1880
+ // src/sensor/axis-sensor.ts
1881
+ var Decision = /* @__PURE__ */ ((Decision2) => {
1882
+ Decision2["ALLOW"] = "ALLOW";
1883
+ Decision2["DENY"] = "DENY";
1884
+ Decision2["THROTTLE"] = "THROTTLE";
1885
+ Decision2["FLAG"] = "FLAG";
1886
+ return Decision2;
1887
+ })(Decision || {});
1888
+ function normalizeSensorDecision(sensorDecision) {
1889
+ if ("action" in sensorDecision) {
1890
+ switch (sensorDecision.action) {
1891
+ case "ALLOW":
1892
+ return {
1893
+ allow: true,
1894
+ riskScore: 0,
1895
+ reasons: [],
1896
+ meta: sensorDecision.meta
1897
+ };
1898
+ case "DENY":
1899
+ return {
1900
+ allow: false,
1901
+ riskScore: 100,
1902
+ reasons: [sensorDecision.code, sensorDecision.reason].filter(
1903
+ Boolean
1904
+ ),
1905
+ meta: sensorDecision.meta,
1906
+ retryAfterMs: sensorDecision.retryAfterMs
1907
+ };
1908
+ case "THROTTLE":
1909
+ return {
1910
+ allow: false,
1911
+ riskScore: 50,
1912
+ reasons: ["RATE_LIMIT"],
1913
+ retryAfterMs: sensorDecision.retryAfterMs,
1914
+ meta: sensorDecision.meta
1915
+ };
1916
+ case "FLAG":
1917
+ return {
1918
+ allow: true,
1919
+ riskScore: sensorDecision.scoreDelta,
1920
+ reasons: sensorDecision.reasons,
1921
+ meta: sensorDecision.meta
1922
+ };
1923
+ }
1924
+ }
1925
+ return {
1926
+ allow: sensorDecision.allow,
1927
+ riskScore: sensorDecision.riskScore,
1928
+ reasons: sensorDecision.reasons,
1929
+ tags: sensorDecision.tags,
1930
+ meta: sensorDecision.meta,
1931
+ tighten: sensorDecision.tighten,
1932
+ retryAfterMs: sensorDecision.retryAfterMs
1933
+ };
1934
+ }
1935
+ var SensorDecisions = {
1936
+ allow(meta, tags) {
1937
+ return {
1938
+ decision: "ALLOW" /* ALLOW */,
1939
+ allow: true,
1940
+ riskScore: 0,
1941
+ reasons: [],
1942
+ tags,
1943
+ meta
1944
+ };
1945
+ },
1946
+ deny(code, reason, meta) {
1947
+ return {
1948
+ decision: "DENY" /* DENY */,
1949
+ allow: false,
1950
+ riskScore: 100,
1951
+ code,
1952
+ reasons: [code, reason].filter(Boolean),
1953
+ meta
1954
+ };
1955
+ },
1956
+ throttle(retryAfterMs, meta) {
1957
+ return {
1958
+ decision: "THROTTLE" /* THROTTLE */,
1959
+ allow: false,
1960
+ riskScore: 50,
1961
+ retryAfterMs,
1962
+ code: "RATE_LIMIT",
1963
+ reasons: ["RATE_LIMIT"],
1964
+ meta
1965
+ };
1966
+ },
1967
+ flag(scoreDelta, reasons, meta) {
1968
+ return {
1969
+ decision: "FLAG" /* FLAG */,
1970
+ allow: true,
1971
+ riskScore: scoreDelta,
1972
+ scoreDelta,
1973
+ reasons,
1974
+ meta
1975
+ };
1976
+ }
1977
+ };
683
1978
  // Annotate the CommonJS export names for ESM import in node:
684
1979
  0 && (module.exports = {
1980
+ ATS1_HDR,
1981
+ ATS1_SCHEMA,
685
1982
  AXIS_MAGIC,
686
1983
  AXIS_VERSION,
1984
+ Ats1Codec,
687
1985
  AxisFrameZ,
1986
+ AxisPacketTags,
1987
+ ContractViolationError,
1988
+ DEFAULT_CONTRACTS,
1989
+ Decision,
688
1990
  ERR_BAD_SIGNATURE,
689
1991
  ERR_CONTRACT_VIOLATION,
690
1992
  ERR_INVALID_PACKET,
691
1993
  ERR_REPLAY_DETECTED,
1994
+ ExecutionMeter,
1995
+ FALLBACK_CONTRACT,
692
1996
  FLAG_BODY_TLV,
693
1997
  FLAG_CHAIN_REQ,
694
1998
  FLAG_HAS_WITNESS,
@@ -705,6 +2009,11 @@ function computeReceiptHash(receiptBytes, prevHash) {
705
2009
  PROOF_JWT,
706
2010
  PROOF_LOOM,
707
2011
  PROOF_MTLS,
2012
+ Schema2002_PasskeyLoginOptionsRes,
2013
+ Schema2011_PasskeyLoginVerifyReq,
2014
+ Schema2012_PasskeyLoginVerifyRes,
2015
+ Schema2021_PasskeyRegisterOptionsReq,
2016
+ SensorDecisions,
708
2017
  TLV_ACTOR_ID,
709
2018
  TLV_AUD,
710
2019
  TLV_EFFECT,
@@ -724,26 +2033,55 @@ function computeReceiptHash(receiptBytes, prevHash) {
724
2033
  TLV_PREV_HASH,
725
2034
  TLV_PROOF_REF,
726
2035
  TLV_PROOF_TYPE,
2036
+ TLV_REALM,
727
2037
  TLV_RECEIPT_HASH,
728
2038
  TLV_RID,
729
2039
  TLV_TRACE_ID,
730
2040
  TLV_TS,
2041
+ axis1SigningBytes,
2042
+ b64urlDecode,
2043
+ b64urlDecodeString,
2044
+ b64urlEncode,
2045
+ b64urlEncodeString,
2046
+ buildAts1Hdr,
2047
+ buildPacket,
2048
+ buildTLVs,
2049
+ bytes,
2050
+ canonicalJson,
2051
+ canonicalJsonExcluding,
731
2052
  computeReceiptHash,
732
2053
  computeSignaturePayload,
733
2054
  decodeArray,
2055
+ decodeAxis1Frame,
734
2056
  decodeFrame,
735
2057
  decodeObject,
736
2058
  decodeTLVs,
737
2059
  decodeTLVsList,
738
2060
  decodeVarint,
2061
+ encVarint,
2062
+ encodeAxis1Frame,
739
2063
  encodeFrame,
740
2064
  encodeTLVs,
741
2065
  encodeVarint,
742
2066
  generateEd25519KeyPair,
743
2067
  getSignTarget,
2068
+ nonce16,
2069
+ normalizeSensorDecision,
2070
+ packPasskeyLoginOptionsReq,
2071
+ packPasskeyLoginOptionsRes,
2072
+ packPasskeyLoginVerifyReq,
2073
+ packPasskeyLoginVerifyRes,
2074
+ packPasskeyRegisterOptionsReq,
744
2075
  sha256,
745
2076
  signFrame,
2077
+ tlv,
2078
+ u64be,
2079
+ unpackPasskeyLoginOptionsReq,
2080
+ unpackPasskeyLoginVerifyReq,
2081
+ unpackPasskeyRegisterOptionsReq,
2082
+ utf8,
746
2083
  varintLength,
2084
+ varintU,
747
2085
  verifyFrameSignature
748
2086
  });
749
2087
  //# sourceMappingURL=index.js.map