protect-mcp 0.7.4 → 0.7.6

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
@@ -5,9 +5,11 @@ import {
5
5
  import {
6
6
  createSelectiveDisclosurePackage,
7
7
  discloseField,
8
+ hmac,
9
+ sha256 as sha2562,
8
10
  signCommittedDecision,
9
11
  verifySelectiveDisclosurePackage
10
- } from "./chunk-F2FKQ4XN.mjs";
12
+ } from "./chunk-WV4DKYE4.mjs";
11
13
  import {
12
14
  formatReportMarkdown,
13
15
  generateReport
@@ -26,7 +28,7 @@ import {
26
28
  readInstalledConnectorPilots,
27
29
  simulate,
28
30
  writeConnectorPilots
29
- } from "./chunk-36UID5WY.mjs";
31
+ } from "./chunk-JCMDLN5I.mjs";
30
32
  import {
31
33
  ProtectGateway,
32
34
  buildDecisionContext,
@@ -38,10 +40,10 @@ import {
38
40
  resolveCredential,
39
41
  sendApprovalNotification,
40
42
  validateCredentials
41
- } from "./chunk-UBZJ3VI2.mjs";
43
+ } from "./chunk-VTPZ4G5I.mjs";
42
44
  import {
43
45
  createSandboxServer
44
- } from "./chunk-KPSICBAJ.mjs";
46
+ } from "./chunk-SETXVE2K.mjs";
45
47
  import {
46
48
  BUILTIN_PATTERNS,
47
49
  generateHookSettings,
@@ -53,7 +55,7 @@ import {
53
55
  forwardReceipt,
54
56
  getScopeBlindBridge,
55
57
  startHookServer
56
- } from "./chunk-NVJHGXXG.mjs";
58
+ } from "./chunk-6E2DHBAR.mjs";
57
59
  import {
58
60
  checkRateLimit,
59
61
  evaluateCedar,
@@ -68,9 +70,42 @@ import {
68
70
  policySetFromSource,
69
71
  runEvaluatorSelfTest,
70
72
  signDecision
71
- } from "./chunk-D2RDY2JR.mjs";
72
- import "./chunk-LYKNULYU.mjs";
73
- import "./chunk-D733KAPG.mjs";
73
+ } from "./chunk-WIPWNWMJ.mjs";
74
+ import {
75
+ Field,
76
+ _abool2,
77
+ _abytes2,
78
+ _createCurveFields,
79
+ _validateObject,
80
+ aInRange,
81
+ bitLen,
82
+ bitMask,
83
+ bytesToNumberBE,
84
+ createHmacDrbg,
85
+ ed25519,
86
+ ensureBytes,
87
+ getMinHashLength,
88
+ mapHashToField,
89
+ memoized,
90
+ mulEndoUnsafe,
91
+ nLength,
92
+ negateCt,
93
+ normalizeZ,
94
+ numberToHexUnpadded,
95
+ pippenger,
96
+ sha256,
97
+ sha384,
98
+ sha512,
99
+ wNAF
100
+ } from "./chunk-LJQOALYR.mjs";
101
+ import {
102
+ ahash,
103
+ bytesToHex,
104
+ concatBytes,
105
+ hexToBytes,
106
+ isBytes,
107
+ randomBytes
108
+ } from "./chunk-D733KAPG.mjs";
74
109
  import "./chunk-PQJP2ZCI.mjs";
75
110
 
76
111
  // src/manifest.ts
@@ -578,7 +613,7 @@ function createLogAnchorField(anchor) {
578
613
  }
579
614
 
580
615
  // src/selective-disclosure.ts
581
- import { createHash as createHash2, randomBytes } from "crypto";
616
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
582
617
  function redactFields(receipt, fieldsToRedact) {
583
618
  const redacted = JSON.parse(JSON.stringify(receipt));
584
619
  const salts = [];
@@ -594,7 +629,7 @@ function redactFields(receipt, fieldsToRedact) {
594
629
  if (i === parts.length - 1) {
595
630
  if (key in current) {
596
631
  const originalValue = current[key];
597
- const salt = randomBytes(16).toString("hex");
632
+ const salt = randomBytes2(16).toString("hex");
598
633
  const commitment = computeCommitment(salt, originalValue);
599
634
  salts.push({ field: fieldPath, salt, originalValue });
600
635
  current[key] = `sha256(salt + ${typeof originalValue === "string" ? "..." : JSON.stringify(originalValue).slice(0, 20) + "..."})`;
@@ -811,9 +846,1069 @@ MIT
811
846
  }
812
847
 
813
848
  // src/webauthn-approval.ts
814
- import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
849
+ import { createHash as createHash3, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
850
+
851
+ // node_modules/@noble/curves/esm/abstract/weierstrass.js
852
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
853
+ function _splitEndoScalar(k, basis, n) {
854
+ const [[a1, b1], [a2, b2]] = basis;
855
+ const c1 = divNearest(b2 * k, n);
856
+ const c2 = divNearest(-b1 * k, n);
857
+ let k1 = k - c1 * a1 - c2 * a2;
858
+ let k2 = -c1 * b1 - c2 * b2;
859
+ const k1neg = k1 < _0n;
860
+ const k2neg = k2 < _0n;
861
+ if (k1neg)
862
+ k1 = -k1;
863
+ if (k2neg)
864
+ k2 = -k2;
865
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n;
866
+ if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
867
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
868
+ }
869
+ return { k1neg, k1, k2neg, k2 };
870
+ }
871
+ function validateSigFormat(format) {
872
+ if (!["compact", "recovered", "der"].includes(format))
873
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
874
+ return format;
875
+ }
876
+ function validateSigOpts(opts, def) {
877
+ const optsn = {};
878
+ for (let optName of Object.keys(def)) {
879
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
880
+ }
881
+ _abool2(optsn.lowS, "lowS");
882
+ _abool2(optsn.prehash, "prehash");
883
+ if (optsn.format !== void 0)
884
+ validateSigFormat(optsn.format);
885
+ return optsn;
886
+ }
887
+ var DERErr = class extends Error {
888
+ constructor(m = "") {
889
+ super(m);
890
+ }
891
+ };
892
+ var DER = {
893
+ // asn.1 DER encoding utils
894
+ Err: DERErr,
895
+ // Basic building block is TLV (Tag-Length-Value)
896
+ _tlv: {
897
+ encode: (tag, data) => {
898
+ const { Err: E } = DER;
899
+ if (tag < 0 || tag > 256)
900
+ throw new E("tlv.encode: wrong tag");
901
+ if (data.length & 1)
902
+ throw new E("tlv.encode: unpadded data");
903
+ const dataLen = data.length / 2;
904
+ const len = numberToHexUnpadded(dataLen);
905
+ if (len.length / 2 & 128)
906
+ throw new E("tlv.encode: long form length too big");
907
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
908
+ const t = numberToHexUnpadded(tag);
909
+ return t + lenLen + len + data;
910
+ },
911
+ // v - value, l - left bytes (unparsed)
912
+ decode(tag, data) {
913
+ const { Err: E } = DER;
914
+ let pos = 0;
915
+ if (tag < 0 || tag > 256)
916
+ throw new E("tlv.encode: wrong tag");
917
+ if (data.length < 2 || data[pos++] !== tag)
918
+ throw new E("tlv.decode: wrong tlv");
919
+ const first = data[pos++];
920
+ const isLong = !!(first & 128);
921
+ let length = 0;
922
+ if (!isLong)
923
+ length = first;
924
+ else {
925
+ const lenLen = first & 127;
926
+ if (!lenLen)
927
+ throw new E("tlv.decode(long): indefinite length not supported");
928
+ if (lenLen > 4)
929
+ throw new E("tlv.decode(long): byte length is too big");
930
+ const lengthBytes = data.subarray(pos, pos + lenLen);
931
+ if (lengthBytes.length !== lenLen)
932
+ throw new E("tlv.decode: length bytes not complete");
933
+ if (lengthBytes[0] === 0)
934
+ throw new E("tlv.decode(long): zero leftmost byte");
935
+ for (const b of lengthBytes)
936
+ length = length << 8 | b;
937
+ pos += lenLen;
938
+ if (length < 128)
939
+ throw new E("tlv.decode(long): not minimal encoding");
940
+ }
941
+ const v = data.subarray(pos, pos + length);
942
+ if (v.length !== length)
943
+ throw new E("tlv.decode: wrong value length");
944
+ return { v, l: data.subarray(pos + length) };
945
+ }
946
+ },
947
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
948
+ // since we always use positive integers here. It must always be empty:
949
+ // - add zero byte if exists
950
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
951
+ _int: {
952
+ encode(num) {
953
+ const { Err: E } = DER;
954
+ if (num < _0n)
955
+ throw new E("integer: negative integers are not allowed");
956
+ let hex = numberToHexUnpadded(num);
957
+ if (Number.parseInt(hex[0], 16) & 8)
958
+ hex = "00" + hex;
959
+ if (hex.length & 1)
960
+ throw new E("unexpected DER parsing assertion: unpadded hex");
961
+ return hex;
962
+ },
963
+ decode(data) {
964
+ const { Err: E } = DER;
965
+ if (data[0] & 128)
966
+ throw new E("invalid signature integer: negative");
967
+ if (data[0] === 0 && !(data[1] & 128))
968
+ throw new E("invalid signature integer: unnecessary leading zero");
969
+ return bytesToNumberBE(data);
970
+ }
971
+ },
972
+ toSig(hex) {
973
+ const { Err: E, _int: int, _tlv: tlv } = DER;
974
+ const data = ensureBytes("signature", hex);
975
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
976
+ if (seqLeftBytes.length)
977
+ throw new E("invalid signature: left bytes after parsing");
978
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
979
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
980
+ if (sLeftBytes.length)
981
+ throw new E("invalid signature: left bytes after parsing");
982
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
983
+ },
984
+ hexFromSig(sig) {
985
+ const { _tlv: tlv, _int: int } = DER;
986
+ const rs = tlv.encode(2, int.encode(sig.r));
987
+ const ss = tlv.encode(2, int.encode(sig.s));
988
+ const seq = rs + ss;
989
+ return tlv.encode(48, seq);
990
+ }
991
+ };
992
+ var _0n = BigInt(0);
993
+ var _1n = BigInt(1);
994
+ var _2n = BigInt(2);
995
+ var _3n = BigInt(3);
996
+ var _4n = BigInt(4);
997
+ function _normFnElement(Fn, key) {
998
+ const { BYTES: expected } = Fn;
999
+ let num;
1000
+ if (typeof key === "bigint") {
1001
+ num = key;
1002
+ } else {
1003
+ let bytes = ensureBytes("private key", key);
1004
+ try {
1005
+ num = Fn.fromBytes(bytes);
1006
+ } catch (error) {
1007
+ throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
1008
+ }
1009
+ }
1010
+ if (!Fn.isValidNot0(num))
1011
+ throw new Error("invalid private key: out of range [1..N-1]");
1012
+ return num;
1013
+ }
1014
+ function weierstrassN(params, extraOpts = {}) {
1015
+ const validated = _createCurveFields("weierstrass", params, extraOpts);
1016
+ const { Fp, Fn } = validated;
1017
+ let CURVE = validated.CURVE;
1018
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
1019
+ _validateObject(extraOpts, {}, {
1020
+ allowInfinityPoint: "boolean",
1021
+ clearCofactor: "function",
1022
+ isTorsionFree: "function",
1023
+ fromBytes: "function",
1024
+ toBytes: "function",
1025
+ endo: "object",
1026
+ wrapPrivateKey: "boolean"
1027
+ });
1028
+ const { endo } = extraOpts;
1029
+ if (endo) {
1030
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
1031
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
1032
+ }
1033
+ }
1034
+ const lengths = getWLengths(Fp, Fn);
1035
+ function assertCompressionIsSupported() {
1036
+ if (!Fp.isOdd)
1037
+ throw new Error("compression is not supported: Field does not have .isOdd()");
1038
+ }
1039
+ function pointToBytes(_c, point, isCompressed) {
1040
+ const { x, y } = point.toAffine();
1041
+ const bx = Fp.toBytes(x);
1042
+ _abool2(isCompressed, "isCompressed");
1043
+ if (isCompressed) {
1044
+ assertCompressionIsSupported();
1045
+ const hasEvenY = !Fp.isOdd(y);
1046
+ return concatBytes(pprefix(hasEvenY), bx);
1047
+ } else {
1048
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
1049
+ }
1050
+ }
1051
+ function pointFromBytes(bytes) {
1052
+ _abytes2(bytes, void 0, "Point");
1053
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
1054
+ const length = bytes.length;
1055
+ const head = bytes[0];
1056
+ const tail = bytes.subarray(1);
1057
+ if (length === comp && (head === 2 || head === 3)) {
1058
+ const x = Fp.fromBytes(tail);
1059
+ if (!Fp.isValid(x))
1060
+ throw new Error("bad point: is not on curve, wrong x");
1061
+ const y2 = weierstrassEquation(x);
1062
+ let y;
1063
+ try {
1064
+ y = Fp.sqrt(y2);
1065
+ } catch (sqrtError) {
1066
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1067
+ throw new Error("bad point: is not on curve, sqrt error" + err);
1068
+ }
1069
+ assertCompressionIsSupported();
1070
+ const isYOdd = Fp.isOdd(y);
1071
+ const isHeadOdd = (head & 1) === 1;
1072
+ if (isHeadOdd !== isYOdd)
1073
+ y = Fp.neg(y);
1074
+ return { x, y };
1075
+ } else if (length === uncomp && head === 4) {
1076
+ const L = Fp.BYTES;
1077
+ const x = Fp.fromBytes(tail.subarray(0, L));
1078
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
1079
+ if (!isValidXY(x, y))
1080
+ throw new Error("bad point: is not on curve");
1081
+ return { x, y };
1082
+ } else {
1083
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
1084
+ }
1085
+ }
1086
+ const encodePoint = extraOpts.toBytes || pointToBytes;
1087
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
1088
+ function weierstrassEquation(x) {
1089
+ const x2 = Fp.sqr(x);
1090
+ const x3 = Fp.mul(x2, x);
1091
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
1092
+ }
1093
+ function isValidXY(x, y) {
1094
+ const left = Fp.sqr(y);
1095
+ const right = weierstrassEquation(x);
1096
+ return Fp.eql(left, right);
1097
+ }
1098
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
1099
+ throw new Error("bad curve params: generator point");
1100
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
1101
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1102
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
1103
+ throw new Error("bad curve params: a or b");
1104
+ function acoord(title, n, banZero = false) {
1105
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
1106
+ throw new Error(`bad point coordinate ${title}`);
1107
+ return n;
1108
+ }
1109
+ function aprjpoint(other) {
1110
+ if (!(other instanceof Point))
1111
+ throw new Error("ProjectivePoint expected");
1112
+ }
1113
+ function splitEndoScalarN(k) {
1114
+ if (!endo || !endo.basises)
1115
+ throw new Error("no endo");
1116
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
1117
+ }
1118
+ const toAffineMemo = memoized((p, iz) => {
1119
+ const { X, Y, Z } = p;
1120
+ if (Fp.eql(Z, Fp.ONE))
1121
+ return { x: X, y: Y };
1122
+ const is0 = p.is0();
1123
+ if (iz == null)
1124
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
1125
+ const x = Fp.mul(X, iz);
1126
+ const y = Fp.mul(Y, iz);
1127
+ const zz = Fp.mul(Z, iz);
1128
+ if (is0)
1129
+ return { x: Fp.ZERO, y: Fp.ZERO };
1130
+ if (!Fp.eql(zz, Fp.ONE))
1131
+ throw new Error("invZ was invalid");
1132
+ return { x, y };
1133
+ });
1134
+ const assertValidMemo = memoized((p) => {
1135
+ if (p.is0()) {
1136
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
1137
+ return;
1138
+ throw new Error("bad point: ZERO");
1139
+ }
1140
+ const { x, y } = p.toAffine();
1141
+ if (!Fp.isValid(x) || !Fp.isValid(y))
1142
+ throw new Error("bad point: x or y not field elements");
1143
+ if (!isValidXY(x, y))
1144
+ throw new Error("bad point: equation left != right");
1145
+ if (!p.isTorsionFree())
1146
+ throw new Error("bad point: not in prime-order subgroup");
1147
+ return true;
1148
+ });
1149
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
1150
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
1151
+ k1p = negateCt(k1neg, k1p);
1152
+ k2p = negateCt(k2neg, k2p);
1153
+ return k1p.add(k2p);
1154
+ }
1155
+ class Point {
1156
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1157
+ constructor(X, Y, Z) {
1158
+ this.X = acoord("x", X);
1159
+ this.Y = acoord("y", Y, true);
1160
+ this.Z = acoord("z", Z);
1161
+ Object.freeze(this);
1162
+ }
1163
+ static CURVE() {
1164
+ return CURVE;
1165
+ }
1166
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
1167
+ static fromAffine(p) {
1168
+ const { x, y } = p || {};
1169
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
1170
+ throw new Error("invalid affine point");
1171
+ if (p instanceof Point)
1172
+ throw new Error("projective point not allowed");
1173
+ if (Fp.is0(x) && Fp.is0(y))
1174
+ return Point.ZERO;
1175
+ return new Point(x, y, Fp.ONE);
1176
+ }
1177
+ static fromBytes(bytes) {
1178
+ const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
1179
+ P.assertValidity();
1180
+ return P;
1181
+ }
1182
+ static fromHex(hex) {
1183
+ return Point.fromBytes(ensureBytes("pointHex", hex));
1184
+ }
1185
+ get x() {
1186
+ return this.toAffine().x;
1187
+ }
1188
+ get y() {
1189
+ return this.toAffine().y;
1190
+ }
1191
+ /**
1192
+ *
1193
+ * @param windowSize
1194
+ * @param isLazy true will defer table computation until the first multiplication
1195
+ * @returns
1196
+ */
1197
+ precompute(windowSize = 8, isLazy = true) {
1198
+ wnaf.createCache(this, windowSize);
1199
+ if (!isLazy)
1200
+ this.multiply(_3n);
1201
+ return this;
1202
+ }
1203
+ // TODO: return `this`
1204
+ /** A point on curve is valid if it conforms to equation. */
1205
+ assertValidity() {
1206
+ assertValidMemo(this);
1207
+ }
1208
+ hasEvenY() {
1209
+ const { y } = this.toAffine();
1210
+ if (!Fp.isOdd)
1211
+ throw new Error("Field doesn't support isOdd");
1212
+ return !Fp.isOdd(y);
1213
+ }
1214
+ /** Compare one point to another. */
1215
+ equals(other) {
1216
+ aprjpoint(other);
1217
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1218
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1219
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1220
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1221
+ return U1 && U2;
1222
+ }
1223
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
1224
+ negate() {
1225
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
1226
+ }
1227
+ // Renes-Costello-Batina exception-free doubling formula.
1228
+ // There is 30% faster Jacobian formula, but it is not complete.
1229
+ // https://eprint.iacr.org/2015/1060, algorithm 3
1230
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1231
+ double() {
1232
+ const { a, b } = CURVE;
1233
+ const b3 = Fp.mul(b, _3n);
1234
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1235
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1236
+ let t0 = Fp.mul(X1, X1);
1237
+ let t1 = Fp.mul(Y1, Y1);
1238
+ let t2 = Fp.mul(Z1, Z1);
1239
+ let t3 = Fp.mul(X1, Y1);
1240
+ t3 = Fp.add(t3, t3);
1241
+ Z3 = Fp.mul(X1, Z1);
1242
+ Z3 = Fp.add(Z3, Z3);
1243
+ X3 = Fp.mul(a, Z3);
1244
+ Y3 = Fp.mul(b3, t2);
1245
+ Y3 = Fp.add(X3, Y3);
1246
+ X3 = Fp.sub(t1, Y3);
1247
+ Y3 = Fp.add(t1, Y3);
1248
+ Y3 = Fp.mul(X3, Y3);
1249
+ X3 = Fp.mul(t3, X3);
1250
+ Z3 = Fp.mul(b3, Z3);
1251
+ t2 = Fp.mul(a, t2);
1252
+ t3 = Fp.sub(t0, t2);
1253
+ t3 = Fp.mul(a, t3);
1254
+ t3 = Fp.add(t3, Z3);
1255
+ Z3 = Fp.add(t0, t0);
1256
+ t0 = Fp.add(Z3, t0);
1257
+ t0 = Fp.add(t0, t2);
1258
+ t0 = Fp.mul(t0, t3);
1259
+ Y3 = Fp.add(Y3, t0);
1260
+ t2 = Fp.mul(Y1, Z1);
1261
+ t2 = Fp.add(t2, t2);
1262
+ t0 = Fp.mul(t2, t3);
1263
+ X3 = Fp.sub(X3, t0);
1264
+ Z3 = Fp.mul(t2, t1);
1265
+ Z3 = Fp.add(Z3, Z3);
1266
+ Z3 = Fp.add(Z3, Z3);
1267
+ return new Point(X3, Y3, Z3);
1268
+ }
1269
+ // Renes-Costello-Batina exception-free addition formula.
1270
+ // There is 30% faster Jacobian formula, but it is not complete.
1271
+ // https://eprint.iacr.org/2015/1060, algorithm 1
1272
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1273
+ add(other) {
1274
+ aprjpoint(other);
1275
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1276
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1277
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1278
+ const a = CURVE.a;
1279
+ const b3 = Fp.mul(CURVE.b, _3n);
1280
+ let t0 = Fp.mul(X1, X2);
1281
+ let t1 = Fp.mul(Y1, Y2);
1282
+ let t2 = Fp.mul(Z1, Z2);
1283
+ let t3 = Fp.add(X1, Y1);
1284
+ let t4 = Fp.add(X2, Y2);
1285
+ t3 = Fp.mul(t3, t4);
1286
+ t4 = Fp.add(t0, t1);
1287
+ t3 = Fp.sub(t3, t4);
1288
+ t4 = Fp.add(X1, Z1);
1289
+ let t5 = Fp.add(X2, Z2);
1290
+ t4 = Fp.mul(t4, t5);
1291
+ t5 = Fp.add(t0, t2);
1292
+ t4 = Fp.sub(t4, t5);
1293
+ t5 = Fp.add(Y1, Z1);
1294
+ X3 = Fp.add(Y2, Z2);
1295
+ t5 = Fp.mul(t5, X3);
1296
+ X3 = Fp.add(t1, t2);
1297
+ t5 = Fp.sub(t5, X3);
1298
+ Z3 = Fp.mul(a, t4);
1299
+ X3 = Fp.mul(b3, t2);
1300
+ Z3 = Fp.add(X3, Z3);
1301
+ X3 = Fp.sub(t1, Z3);
1302
+ Z3 = Fp.add(t1, Z3);
1303
+ Y3 = Fp.mul(X3, Z3);
1304
+ t1 = Fp.add(t0, t0);
1305
+ t1 = Fp.add(t1, t0);
1306
+ t2 = Fp.mul(a, t2);
1307
+ t4 = Fp.mul(b3, t4);
1308
+ t1 = Fp.add(t1, t2);
1309
+ t2 = Fp.sub(t0, t2);
1310
+ t2 = Fp.mul(a, t2);
1311
+ t4 = Fp.add(t4, t2);
1312
+ t0 = Fp.mul(t1, t4);
1313
+ Y3 = Fp.add(Y3, t0);
1314
+ t0 = Fp.mul(t5, t4);
1315
+ X3 = Fp.mul(t3, X3);
1316
+ X3 = Fp.sub(X3, t0);
1317
+ t0 = Fp.mul(t3, t1);
1318
+ Z3 = Fp.mul(t5, Z3);
1319
+ Z3 = Fp.add(Z3, t0);
1320
+ return new Point(X3, Y3, Z3);
1321
+ }
1322
+ subtract(other) {
1323
+ return this.add(other.negate());
1324
+ }
1325
+ is0() {
1326
+ return this.equals(Point.ZERO);
1327
+ }
1328
+ /**
1329
+ * Constant time multiplication.
1330
+ * Uses wNAF method. Windowed method may be 10% faster,
1331
+ * but takes 2x longer to generate and consumes 2x memory.
1332
+ * Uses precomputes when available.
1333
+ * Uses endomorphism for Koblitz curves.
1334
+ * @param scalar by which the point would be multiplied
1335
+ * @returns New point
1336
+ */
1337
+ multiply(scalar) {
1338
+ const { endo: endo2 } = extraOpts;
1339
+ if (!Fn.isValidNot0(scalar))
1340
+ throw new Error("invalid scalar: out of range");
1341
+ let point, fake;
1342
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
1343
+ if (endo2) {
1344
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
1345
+ const { p: k1p, f: k1f } = mul(k1);
1346
+ const { p: k2p, f: k2f } = mul(k2);
1347
+ fake = k1f.add(k2f);
1348
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
1349
+ } else {
1350
+ const { p, f } = mul(scalar);
1351
+ point = p;
1352
+ fake = f;
1353
+ }
1354
+ return normalizeZ(Point, [point, fake])[0];
1355
+ }
1356
+ /**
1357
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1358
+ * It's faster, but should only be used when you don't care about
1359
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
1360
+ */
1361
+ multiplyUnsafe(sc) {
1362
+ const { endo: endo2 } = extraOpts;
1363
+ const p = this;
1364
+ if (!Fn.isValid(sc))
1365
+ throw new Error("invalid scalar: out of range");
1366
+ if (sc === _0n || p.is0())
1367
+ return Point.ZERO;
1368
+ if (sc === _1n)
1369
+ return p;
1370
+ if (wnaf.hasCache(this))
1371
+ return this.multiply(sc);
1372
+ if (endo2) {
1373
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
1374
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
1375
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
1376
+ } else {
1377
+ return wnaf.unsafe(p, sc);
1378
+ }
1379
+ }
1380
+ multiplyAndAddUnsafe(Q, a, b) {
1381
+ const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
1382
+ return sum.is0() ? void 0 : sum;
1383
+ }
1384
+ /**
1385
+ * Converts Projective point to affine (x, y) coordinates.
1386
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
1387
+ */
1388
+ toAffine(invertedZ) {
1389
+ return toAffineMemo(this, invertedZ);
1390
+ }
1391
+ /**
1392
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
1393
+ * Always torsion-free for cofactor=1 curves.
1394
+ */
1395
+ isTorsionFree() {
1396
+ const { isTorsionFree } = extraOpts;
1397
+ if (cofactor === _1n)
1398
+ return true;
1399
+ if (isTorsionFree)
1400
+ return isTorsionFree(Point, this);
1401
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
1402
+ }
1403
+ clearCofactor() {
1404
+ const { clearCofactor } = extraOpts;
1405
+ if (cofactor === _1n)
1406
+ return this;
1407
+ if (clearCofactor)
1408
+ return clearCofactor(Point, this);
1409
+ return this.multiplyUnsafe(cofactor);
1410
+ }
1411
+ isSmallOrder() {
1412
+ return this.multiplyUnsafe(cofactor).is0();
1413
+ }
1414
+ toBytes(isCompressed = true) {
1415
+ _abool2(isCompressed, "isCompressed");
1416
+ this.assertValidity();
1417
+ return encodePoint(Point, this, isCompressed);
1418
+ }
1419
+ toHex(isCompressed = true) {
1420
+ return bytesToHex(this.toBytes(isCompressed));
1421
+ }
1422
+ toString() {
1423
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1424
+ }
1425
+ // TODO: remove
1426
+ get px() {
1427
+ return this.X;
1428
+ }
1429
+ get py() {
1430
+ return this.X;
1431
+ }
1432
+ get pz() {
1433
+ return this.Z;
1434
+ }
1435
+ toRawBytes(isCompressed = true) {
1436
+ return this.toBytes(isCompressed);
1437
+ }
1438
+ _setWindowSize(windowSize) {
1439
+ this.precompute(windowSize);
1440
+ }
1441
+ static normalizeZ(points) {
1442
+ return normalizeZ(Point, points);
1443
+ }
1444
+ static msm(points, scalars) {
1445
+ return pippenger(Point, Fn, points, scalars);
1446
+ }
1447
+ static fromPrivateKey(privateKey) {
1448
+ return Point.BASE.multiply(_normFnElement(Fn, privateKey));
1449
+ }
1450
+ }
1451
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1452
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1453
+ Point.Fp = Fp;
1454
+ Point.Fn = Fn;
1455
+ const bits = Fn.BITS;
1456
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
1457
+ Point.BASE.precompute(8);
1458
+ return Point;
1459
+ }
1460
+ function pprefix(hasEvenY) {
1461
+ return Uint8Array.of(hasEvenY ? 2 : 3);
1462
+ }
1463
+ function getWLengths(Fp, Fn) {
1464
+ return {
1465
+ secretKey: Fn.BYTES,
1466
+ publicKey: 1 + Fp.BYTES,
1467
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
1468
+ publicKeyHasPrefix: true,
1469
+ signature: 2 * Fn.BYTES
1470
+ };
1471
+ }
1472
+ function ecdh(Point, ecdhOpts = {}) {
1473
+ const { Fn } = Point;
1474
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
1475
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
1476
+ function isValidSecretKey(secretKey) {
1477
+ try {
1478
+ return !!_normFnElement(Fn, secretKey);
1479
+ } catch (error) {
1480
+ return false;
1481
+ }
1482
+ }
1483
+ function isValidPublicKey(publicKey, isCompressed) {
1484
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
1485
+ try {
1486
+ const l = publicKey.length;
1487
+ if (isCompressed === true && l !== comp)
1488
+ return false;
1489
+ if (isCompressed === false && l !== publicKeyUncompressed)
1490
+ return false;
1491
+ return !!Point.fromBytes(publicKey);
1492
+ } catch (error) {
1493
+ return false;
1494
+ }
1495
+ }
1496
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
1497
+ return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
1498
+ }
1499
+ function getPublicKey(secretKey, isCompressed = true) {
1500
+ return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
1501
+ }
1502
+ function keygen(seed) {
1503
+ const secretKey = randomSecretKey(seed);
1504
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1505
+ }
1506
+ function isProbPub(item) {
1507
+ if (typeof item === "bigint")
1508
+ return false;
1509
+ if (item instanceof Point)
1510
+ return true;
1511
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
1512
+ if (Fn.allowedLengths || secretKey === publicKey)
1513
+ return void 0;
1514
+ const l = ensureBytes("key", item).length;
1515
+ return l === publicKey || l === publicKeyUncompressed;
1516
+ }
1517
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
1518
+ if (isProbPub(secretKeyA) === true)
1519
+ throw new Error("first arg must be private key");
1520
+ if (isProbPub(publicKeyB) === false)
1521
+ throw new Error("second arg must be public key");
1522
+ const s = _normFnElement(Fn, secretKeyA);
1523
+ const b = Point.fromHex(publicKeyB);
1524
+ return b.multiply(s).toBytes(isCompressed);
1525
+ }
1526
+ const utils = {
1527
+ isValidSecretKey,
1528
+ isValidPublicKey,
1529
+ randomSecretKey,
1530
+ // TODO: remove
1531
+ isValidPrivateKey: isValidSecretKey,
1532
+ randomPrivateKey: randomSecretKey,
1533
+ normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
1534
+ precompute(windowSize = 8, point = Point.BASE) {
1535
+ return point.precompute(windowSize, false);
1536
+ }
1537
+ };
1538
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
1539
+ }
1540
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
1541
+ ahash(hash);
1542
+ _validateObject(ecdsaOpts, {}, {
1543
+ hmac: "function",
1544
+ lowS: "boolean",
1545
+ randomBytes: "function",
1546
+ bits2int: "function",
1547
+ bits2int_modN: "function"
1548
+ });
1549
+ const randomBytes4 = ecdsaOpts.randomBytes || randomBytes;
1550
+ const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
1551
+ const { Fp, Fn } = Point;
1552
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
1553
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
1554
+ const defaultSigOpts = {
1555
+ prehash: false,
1556
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
1557
+ format: void 0,
1558
+ //'compact' as ECDSASigFormat,
1559
+ extraEntropy: false
1560
+ };
1561
+ const defaultSigOpts_format = "compact";
1562
+ function isBiggerThanHalfOrder(number) {
1563
+ const HALF = CURVE_ORDER >> _1n;
1564
+ return number > HALF;
1565
+ }
1566
+ function validateRS(title, num) {
1567
+ if (!Fn.isValidNot0(num))
1568
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
1569
+ return num;
1570
+ }
1571
+ function validateSigLength(bytes, format) {
1572
+ validateSigFormat(format);
1573
+ const size = lengths.signature;
1574
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
1575
+ return _abytes2(bytes, sizer, `${format} signature`);
1576
+ }
1577
+ class Signature {
1578
+ constructor(r, s, recovery) {
1579
+ this.r = validateRS("r", r);
1580
+ this.s = validateRS("s", s);
1581
+ if (recovery != null)
1582
+ this.recovery = recovery;
1583
+ Object.freeze(this);
1584
+ }
1585
+ static fromBytes(bytes, format = defaultSigOpts_format) {
1586
+ validateSigLength(bytes, format);
1587
+ let recid;
1588
+ if (format === "der") {
1589
+ const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes));
1590
+ return new Signature(r2, s2);
1591
+ }
1592
+ if (format === "recovered") {
1593
+ recid = bytes[0];
1594
+ format = "compact";
1595
+ bytes = bytes.subarray(1);
1596
+ }
1597
+ const L = Fn.BYTES;
1598
+ const r = bytes.subarray(0, L);
1599
+ const s = bytes.subarray(L, L * 2);
1600
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
1601
+ }
1602
+ static fromHex(hex, format) {
1603
+ return this.fromBytes(hexToBytes(hex), format);
1604
+ }
1605
+ addRecoveryBit(recovery) {
1606
+ return new Signature(this.r, this.s, recovery);
1607
+ }
1608
+ recoverPublicKey(messageHash) {
1609
+ const FIELD_ORDER = Fp.ORDER;
1610
+ const { r, s, recovery: rec } = this;
1611
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
1612
+ throw new Error("recovery id invalid");
1613
+ const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
1614
+ if (hasCofactor && rec > 1)
1615
+ throw new Error("recovery id is ambiguous for h>1 curve");
1616
+ const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
1617
+ if (!Fp.isValid(radj))
1618
+ throw new Error("recovery id 2 or 3 invalid");
1619
+ const x = Fp.toBytes(radj);
1620
+ const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
1621
+ const ir = Fn.inv(radj);
1622
+ const h = bits2int_modN(ensureBytes("msgHash", messageHash));
1623
+ const u1 = Fn.create(-h * ir);
1624
+ const u2 = Fn.create(s * ir);
1625
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
1626
+ if (Q.is0())
1627
+ throw new Error("point at infinify");
1628
+ Q.assertValidity();
1629
+ return Q;
1630
+ }
1631
+ // Signatures should be low-s, to prevent malleability.
1632
+ hasHighS() {
1633
+ return isBiggerThanHalfOrder(this.s);
1634
+ }
1635
+ toBytes(format = defaultSigOpts_format) {
1636
+ validateSigFormat(format);
1637
+ if (format === "der")
1638
+ return hexToBytes(DER.hexFromSig(this));
1639
+ const r = Fn.toBytes(this.r);
1640
+ const s = Fn.toBytes(this.s);
1641
+ if (format === "recovered") {
1642
+ if (this.recovery == null)
1643
+ throw new Error("recovery bit must be present");
1644
+ return concatBytes(Uint8Array.of(this.recovery), r, s);
1645
+ }
1646
+ return concatBytes(r, s);
1647
+ }
1648
+ toHex(format) {
1649
+ return bytesToHex(this.toBytes(format));
1650
+ }
1651
+ // TODO: remove
1652
+ assertValidity() {
1653
+ }
1654
+ static fromCompact(hex) {
1655
+ return Signature.fromBytes(ensureBytes("sig", hex), "compact");
1656
+ }
1657
+ static fromDER(hex) {
1658
+ return Signature.fromBytes(ensureBytes("sig", hex), "der");
1659
+ }
1660
+ normalizeS() {
1661
+ return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
1662
+ }
1663
+ toDERRawBytes() {
1664
+ return this.toBytes("der");
1665
+ }
1666
+ toDERHex() {
1667
+ return bytesToHex(this.toBytes("der"));
1668
+ }
1669
+ toCompactRawBytes() {
1670
+ return this.toBytes("compact");
1671
+ }
1672
+ toCompactHex() {
1673
+ return bytesToHex(this.toBytes("compact"));
1674
+ }
1675
+ }
1676
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
1677
+ if (bytes.length > 8192)
1678
+ throw new Error("input is too large");
1679
+ const num = bytesToNumberBE(bytes);
1680
+ const delta = bytes.length * 8 - fnBits;
1681
+ return delta > 0 ? num >> BigInt(delta) : num;
1682
+ };
1683
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
1684
+ return Fn.create(bits2int(bytes));
1685
+ };
1686
+ const ORDER_MASK = bitMask(fnBits);
1687
+ function int2octets(num) {
1688
+ aInRange("num < 2^" + fnBits, num, _0n, ORDER_MASK);
1689
+ return Fn.toBytes(num);
1690
+ }
1691
+ function validateMsgAndHash(message, prehash) {
1692
+ _abytes2(message, void 0, "message");
1693
+ return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
1694
+ }
1695
+ function prepSig(message, privateKey, opts) {
1696
+ if (["recovered", "canonical"].some((k) => k in opts))
1697
+ throw new Error("sign() legacy options not supported");
1698
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
1699
+ message = validateMsgAndHash(message, prehash);
1700
+ const h1int = bits2int_modN(message);
1701
+ const d = _normFnElement(Fn, privateKey);
1702
+ const seedArgs = [int2octets(d), int2octets(h1int)];
1703
+ if (extraEntropy != null && extraEntropy !== false) {
1704
+ const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy;
1705
+ seedArgs.push(ensureBytes("extraEntropy", e));
1706
+ }
1707
+ const seed = concatBytes(...seedArgs);
1708
+ const m = h1int;
1709
+ function k2sig(kBytes) {
1710
+ const k = bits2int(kBytes);
1711
+ if (!Fn.isValidNot0(k))
1712
+ return;
1713
+ const ik = Fn.inv(k);
1714
+ const q = Point.BASE.multiply(k).toAffine();
1715
+ const r = Fn.create(q.x);
1716
+ if (r === _0n)
1717
+ return;
1718
+ const s = Fn.create(ik * Fn.create(m + r * d));
1719
+ if (s === _0n)
1720
+ return;
1721
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n);
1722
+ let normS = s;
1723
+ if (lowS && isBiggerThanHalfOrder(s)) {
1724
+ normS = Fn.neg(s);
1725
+ recovery ^= 1;
1726
+ }
1727
+ return new Signature(r, normS, recovery);
1728
+ }
1729
+ return { seed, k2sig };
1730
+ }
1731
+ function sign(message, secretKey, opts = {}) {
1732
+ message = ensureBytes("message", message);
1733
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
1734
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
1735
+ const sig = drbg(seed, k2sig);
1736
+ return sig;
1737
+ }
1738
+ function tryParsingSig(sg) {
1739
+ let sig = void 0;
1740
+ const isHex = typeof sg === "string" || isBytes(sg);
1741
+ const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
1742
+ if (!isHex && !isObj)
1743
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
1744
+ if (isObj) {
1745
+ sig = new Signature(sg.r, sg.s);
1746
+ } else if (isHex) {
1747
+ try {
1748
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
1749
+ } catch (derError) {
1750
+ if (!(derError instanceof DER.Err))
1751
+ throw derError;
1752
+ }
1753
+ if (!sig) {
1754
+ try {
1755
+ sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
1756
+ } catch (error) {
1757
+ return false;
1758
+ }
1759
+ }
1760
+ }
1761
+ if (!sig)
1762
+ return false;
1763
+ return sig;
1764
+ }
1765
+ function verify(signature, message, publicKey, opts = {}) {
1766
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
1767
+ publicKey = ensureBytes("publicKey", publicKey);
1768
+ message = validateMsgAndHash(ensureBytes("message", message), prehash);
1769
+ if ("strict" in opts)
1770
+ throw new Error("options.strict was renamed to lowS");
1771
+ const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
1772
+ if (sig === false)
1773
+ return false;
1774
+ try {
1775
+ const P = Point.fromBytes(publicKey);
1776
+ if (lowS && sig.hasHighS())
1777
+ return false;
1778
+ const { r, s } = sig;
1779
+ const h = bits2int_modN(message);
1780
+ const is = Fn.inv(s);
1781
+ const u1 = Fn.create(h * is);
1782
+ const u2 = Fn.create(r * is);
1783
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
1784
+ if (R.is0())
1785
+ return false;
1786
+ const v = Fn.create(R.x);
1787
+ return v === r;
1788
+ } catch (e) {
1789
+ return false;
1790
+ }
1791
+ }
1792
+ function recoverPublicKey(signature, message, opts = {}) {
1793
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
1794
+ message = validateMsgAndHash(message, prehash);
1795
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
1796
+ }
1797
+ return Object.freeze({
1798
+ keygen,
1799
+ getPublicKey,
1800
+ getSharedSecret,
1801
+ utils,
1802
+ lengths,
1803
+ Point,
1804
+ sign,
1805
+ verify,
1806
+ recoverPublicKey,
1807
+ Signature,
1808
+ hash
1809
+ });
1810
+ }
1811
+ function _weierstrass_legacy_opts_to_new(c) {
1812
+ const CURVE = {
1813
+ a: c.a,
1814
+ b: c.b,
1815
+ p: c.Fp.ORDER,
1816
+ n: c.n,
1817
+ h: c.h,
1818
+ Gx: c.Gx,
1819
+ Gy: c.Gy
1820
+ };
1821
+ const Fp = c.Fp;
1822
+ let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
1823
+ const Fn = Field(CURVE.n, {
1824
+ BITS: c.nBitLength,
1825
+ allowedLengths,
1826
+ modFromBytes: c.wrapPrivateKey
1827
+ });
1828
+ const curveOpts = {
1829
+ Fp,
1830
+ Fn,
1831
+ allowInfinityPoint: c.allowInfinityPoint,
1832
+ endo: c.endo,
1833
+ isTorsionFree: c.isTorsionFree,
1834
+ clearCofactor: c.clearCofactor,
1835
+ fromBytes: c.fromBytes,
1836
+ toBytes: c.toBytes
1837
+ };
1838
+ return { CURVE, curveOpts };
1839
+ }
1840
+ function _ecdsa_legacy_opts_to_new(c) {
1841
+ const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
1842
+ const ecdsaOpts = {
1843
+ hmac: c.hmac,
1844
+ randomBytes: c.randomBytes,
1845
+ lowS: c.lowS,
1846
+ bits2int: c.bits2int,
1847
+ bits2int_modN: c.bits2int_modN
1848
+ };
1849
+ return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
1850
+ }
1851
+ function _ecdsa_new_output_to_legacy(c, _ecdsa) {
1852
+ const Point = _ecdsa.Point;
1853
+ return Object.assign({}, _ecdsa, {
1854
+ ProjectivePoint: Point,
1855
+ CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
1856
+ });
1857
+ }
1858
+ function weierstrass(c) {
1859
+ const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
1860
+ const Point = weierstrassN(CURVE, curveOpts);
1861
+ const signs = ecdsa(Point, hash, ecdsaOpts);
1862
+ return _ecdsa_new_output_to_legacy(c, signs);
1863
+ }
1864
+
1865
+ // node_modules/@noble/curves/esm/_shortw_utils.js
1866
+ function createCurve(curveDef, defHash) {
1867
+ const create = (hash) => weierstrass({ ...curveDef, hash });
1868
+ return { ...create(defHash), create };
1869
+ }
1870
+
1871
+ // node_modules/@noble/curves/esm/nist.js
1872
+ var p256_CURVE = {
1873
+ p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),
1874
+ n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
1875
+ h: BigInt(1),
1876
+ a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),
1877
+ b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),
1878
+ Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
1879
+ Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")
1880
+ };
1881
+ var p384_CURVE = {
1882
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),
1883
+ n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),
1884
+ h: BigInt(1),
1885
+ a: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),
1886
+ b: BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),
1887
+ Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),
1888
+ Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")
1889
+ };
1890
+ var p521_CURVE = {
1891
+ p: BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1892
+ n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),
1893
+ h: BigInt(1),
1894
+ a: BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),
1895
+ b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),
1896
+ Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),
1897
+ Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")
1898
+ };
1899
+ var Fp256 = Field(p256_CURVE.p);
1900
+ var Fp384 = Field(p384_CURVE.p);
1901
+ var Fp521 = Field(p521_CURVE.p);
1902
+ var p256 = createCurve({ ...p256_CURVE, Fp: Fp256, lowS: false }, sha256);
1903
+ var p384 = createCurve({ ...p384_CURVE, Fp: Fp384, lowS: false }, sha384);
1904
+ var p521 = createCurve({ ...p521_CURVE, Fp: Fp521, lowS: false, allowedPrivateKeyLengths: [130, 131, 132] }, sha512);
1905
+
1906
+ // node_modules/@noble/curves/esm/p256.js
1907
+ var p2562 = p256;
1908
+
1909
+ // src/webauthn-approval.ts
815
1910
  function createApprovalChallenge(requestId, toolName, agentId, rpId = "scopeblind.com", timeoutSeconds = 300) {
816
- const challengeBytes = randomBytes2(32);
1911
+ const challengeBytes = randomBytes3(32);
817
1912
  const contextHash = createHash3("sha256").update(JSON.stringify({ requestId, toolName, agentId, timestamp: Date.now() })).digest("hex");
818
1913
  return {
819
1914
  challenge: base64urlEncode(challengeBytes),
@@ -843,43 +1938,72 @@ function toCredentialRequestOptions(challenge, allowCredentials) {
843
1938
  }
844
1939
  };
845
1940
  }
846
- function verifyApprovalAssertion(challenge, assertion) {
1941
+ function verifyApprovalAssertion(challenge, assertion, credentialPublicKey, opts = {}) {
1942
+ const now = opts.now ?? Date.now();
1943
+ const fail = (reason, partial = {}) => ({
1944
+ valid: false,
1945
+ reason,
1946
+ credentialId: assertion.credentialId,
1947
+ authenticatorType: "unknown",
1948
+ userVerified: false,
1949
+ signCount: 0,
1950
+ contextHash: challenge.contextHash,
1951
+ approvedAt: new Date(now).toISOString(),
1952
+ ...partial
1953
+ });
847
1954
  const createdAt = new Date(challenge.createdAt).getTime();
848
- const now = Date.now();
849
- if (now - createdAt > challenge.timeoutSeconds * 1e3) {
850
- return {
851
- valid: false,
852
- credentialId: assertion.credentialId,
853
- authenticatorType: "unknown",
854
- userVerified: false,
855
- signCount: 0,
856
- contextHash: challenge.contextHash,
857
- approvedAt: (/* @__PURE__ */ new Date()).toISOString()
858
- };
1955
+ if (now - createdAt > challenge.timeoutSeconds * 1e3) return fail("challenge_expired");
1956
+ if (!credentialPublicKey?.publicKeyHex) return fail("missing_credential_public_key");
1957
+ const clientDataBytes = base64urlDecode(assertion.clientDataJSON);
1958
+ let clientData;
1959
+ try {
1960
+ clientData = JSON.parse(Buffer.from(clientDataBytes).toString("utf8"));
1961
+ } catch {
1962
+ return fail("client_data_parse_error");
859
1963
  }
1964
+ if (clientData.type !== "webauthn.get") return fail("wrong_client_data_type");
1965
+ if (!constantTimeStrEqual(clientData.challenge ?? "", challenge.challenge)) return fail("challenge_mismatch");
1966
+ const allowedOrigins = opts.expectedOrigin ? Array.isArray(opts.expectedOrigin) ? opts.expectedOrigin : [opts.expectedOrigin] : [`https://${challenge.rpId}`];
1967
+ if (!clientData.origin || !allowedOrigins.includes(clientData.origin)) return fail("origin_mismatch");
860
1968
  const authData = base64urlDecode(assertion.authenticatorData);
1969
+ if (authData.length < 37) return fail("authenticator_data_too_short");
1970
+ const rpIdHash = authData.slice(0, 32);
1971
+ const expectedRpIdHash = sha2562(new TextEncoder().encode(challenge.rpId));
1972
+ if (!bytesEqual(rpIdHash, expectedRpIdHash)) return fail("rp_id_hash_mismatch");
861
1973
  const flags = authData[32];
862
1974
  const userPresent = !!(flags & 1);
863
1975
  const userVerified = !!(flags & 4);
864
- const attestedCredData = !!(flags & 64);
865
- const signCount = authData.length >= 37 ? authData[33] << 24 | authData[34] << 16 | authData[35] << 8 | authData[36] : 0;
866
- let authenticatorType = "unknown";
1976
+ if (!userPresent) return fail("user_not_present");
1977
+ if ((opts.requireUserVerification ?? true) && !userVerified) return fail("user_verification_required", { userVerified });
1978
+ const signCount = authData[33] << 24 | authData[34] << 16 | authData[35] << 8 | authData[36];
1979
+ if (typeof opts.prevSignCount === "number" && signCount !== 0 && signCount <= opts.prevSignCount) {
1980
+ return fail("sign_count_regression", { userVerified, signCount });
1981
+ }
1982
+ const signedData = concatBytes2(authData, sha2562(clientDataBytes));
1983
+ const sigBytes = base64urlDecode(assertion.signature);
1984
+ let sigOk = false;
867
1985
  try {
868
- const clientData = JSON.parse(Buffer.from(base64urlDecode(assertion.clientDataJSON)).toString());
869
- if (clientData.type === "webauthn.get") {
870
- authenticatorType = "platform";
1986
+ if (credentialPublicKey.alg === -7) {
1987
+ sigOk = p2562.verify(sigBytes, sha2562(signedData), hexToBytes(credentialPublicKey.publicKeyHex), { format: "der" });
1988
+ } else if (credentialPublicKey.alg === -8) {
1989
+ sigOk = ed25519.verify(sigBytes, signedData, hexToBytes(credentialPublicKey.publicKeyHex));
1990
+ } else {
1991
+ return fail("unsupported_algorithm", { userVerified, signCount });
871
1992
  }
872
1993
  } catch {
1994
+ sigOk = false;
873
1995
  }
1996
+ if (!sigOk) return fail("invalid_signature", { userVerified, signCount });
874
1997
  return {
875
- valid: userPresent,
876
- // At minimum, user must be present
1998
+ valid: true,
877
1999
  credentialId: assertion.credentialId,
878
- authenticatorType,
2000
+ // Heuristic: platform authenticators (TouchID/FaceID/Hello) report UV; roaming
2001
+ // keys without a PIN are UP-only. Attachment is authoritative only at registration.
2002
+ authenticatorType: userVerified ? "platform" : "cross-platform",
879
2003
  userVerified,
880
2004
  signCount,
881
2005
  contextHash: challenge.contextHash,
882
- approvedAt: (/* @__PURE__ */ new Date()).toISOString()
2006
+ approvedAt: new Date(now).toISOString()
883
2007
  };
884
2008
  }
885
2009
  function createApprovalReceiptPayload(challenge, result) {
@@ -905,6 +2029,22 @@ function base64urlDecode(str) {
905
2029
  const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
906
2030
  return new Uint8Array(Buffer.from(padded, "base64"));
907
2031
  }
2032
+ function concatBytes2(a, b) {
2033
+ const out = new Uint8Array(a.length + b.length);
2034
+ out.set(a, 0);
2035
+ out.set(b, a.length);
2036
+ return out;
2037
+ }
2038
+ function bytesEqual(a, b) {
2039
+ if (a.length !== b.length) return false;
2040
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
2041
+ }
2042
+ function constantTimeStrEqual(a, b) {
2043
+ const ab = Buffer.from(a, "utf8");
2044
+ const bb = Buffer.from(b, "utf8");
2045
+ if (ab.length !== bb.length) return false;
2046
+ return timingSafeEqual(ab, bb);
2047
+ }
908
2048
 
909
2049
  // src/did-vc.ts
910
2050
  function ed25519ToDIDKey(publicKeyHex) {
@@ -1823,3 +2963,11 @@ export {
1823
2963
  verifySelectiveDisclosurePackage,
1824
2964
  writeConnectorPilots
1825
2965
  };
2966
+ /*! Bundled license information:
2967
+
2968
+ @noble/curves/esm/abstract/weierstrass.js:
2969
+ @noble/curves/esm/_shortw_utils.js:
2970
+ @noble/curves/esm/nist.js:
2971
+ @noble/curves/esm/p256.js:
2972
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2973
+ */