@dakota-xyz/ts-sdk 1.0.15
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/LICENSE +21 -0
- package/README.md +607 -0
- package/dist/index.d.mts +5723 -0
- package/dist/index.d.ts +5723 -0
- package/dist/index.js +2074 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2044 -0
- package/dist/index.mjs.map +1 -0
- package/dist/webhook/index.d.mts +409 -0
- package/dist/webhook/index.d.ts +409 -0
- package/dist/webhook/index.js +936 -0
- package/dist/webhook/index.js.map +1 -0
- package/dist/webhook/index.mjs +921 -0
- package/dist/webhook/index.mjs.map +1 -0
- package/package.json +96 -0
|
@@ -0,0 +1,936 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// node_modules/@noble/ed25519/index.js
|
|
4
|
+
var ed25519_CURVE = {
|
|
5
|
+
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
|
|
6
|
+
n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
|
|
7
|
+
a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
|
|
8
|
+
d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
|
|
9
|
+
Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
|
|
10
|
+
Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
|
|
11
|
+
};
|
|
12
|
+
var { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;
|
|
13
|
+
var h = 8n;
|
|
14
|
+
var L = 32;
|
|
15
|
+
var L2 = 64;
|
|
16
|
+
var err = (m = "") => {
|
|
17
|
+
throw new Error(m);
|
|
18
|
+
};
|
|
19
|
+
var isBig = (n) => typeof n === "bigint";
|
|
20
|
+
var isStr = (s) => typeof s === "string";
|
|
21
|
+
var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
22
|
+
var abytes = (a, l) => !isBytes(a) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a;
|
|
23
|
+
var u8n = (len) => new Uint8Array(len);
|
|
24
|
+
var u8fr = (buf) => Uint8Array.from(buf);
|
|
25
|
+
var padh = (n, pad) => n.toString(16).padStart(pad, "0");
|
|
26
|
+
var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
|
|
27
|
+
var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
28
|
+
var _ch = (ch) => {
|
|
29
|
+
if (ch >= C._0 && ch <= C._9)
|
|
30
|
+
return ch - C._0;
|
|
31
|
+
if (ch >= C.A && ch <= C.F)
|
|
32
|
+
return ch - (C.A - 10);
|
|
33
|
+
if (ch >= C.a && ch <= C.f)
|
|
34
|
+
return ch - (C.a - 10);
|
|
35
|
+
return;
|
|
36
|
+
};
|
|
37
|
+
var hexToBytes = (hex) => {
|
|
38
|
+
const e = "hex invalid";
|
|
39
|
+
if (!isStr(hex))
|
|
40
|
+
return err(e);
|
|
41
|
+
const hl = hex.length;
|
|
42
|
+
const al = hl / 2;
|
|
43
|
+
if (hl % 2)
|
|
44
|
+
return err(e);
|
|
45
|
+
const array = u8n(al);
|
|
46
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
47
|
+
const n1 = _ch(hex.charCodeAt(hi));
|
|
48
|
+
const n2 = _ch(hex.charCodeAt(hi + 1));
|
|
49
|
+
if (n1 === void 0 || n2 === void 0)
|
|
50
|
+
return err(e);
|
|
51
|
+
array[ai] = n1 * 16 + n2;
|
|
52
|
+
}
|
|
53
|
+
return array;
|
|
54
|
+
};
|
|
55
|
+
var toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
|
|
56
|
+
var cr = () => globalThis?.crypto;
|
|
57
|
+
var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined");
|
|
58
|
+
var concatBytes = (...arrs) => {
|
|
59
|
+
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
|
|
60
|
+
let pad = 0;
|
|
61
|
+
arrs.forEach((a) => {
|
|
62
|
+
r.set(a, pad);
|
|
63
|
+
pad += a.length;
|
|
64
|
+
});
|
|
65
|
+
return r;
|
|
66
|
+
};
|
|
67
|
+
var randomBytes = (len = L) => {
|
|
68
|
+
const c = cr();
|
|
69
|
+
return c.getRandomValues(u8n(len));
|
|
70
|
+
};
|
|
71
|
+
var big = BigInt;
|
|
72
|
+
var arange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
|
|
73
|
+
var M = (a, b = P) => {
|
|
74
|
+
const r = a % b;
|
|
75
|
+
return r >= 0n ? r : b + r;
|
|
76
|
+
};
|
|
77
|
+
var modN = (a) => M(a, N);
|
|
78
|
+
var invert = (num, md) => {
|
|
79
|
+
if (num === 0n || md <= 0n)
|
|
80
|
+
err("no inverse n=" + num + " mod=" + md);
|
|
81
|
+
let a = M(num, md), b = md, x = 0n, u = 1n;
|
|
82
|
+
while (a !== 0n) {
|
|
83
|
+
const q = b / a, r = b % a;
|
|
84
|
+
const m = x - u * q;
|
|
85
|
+
b = a, a = r, x = u, u = m;
|
|
86
|
+
}
|
|
87
|
+
return b === 1n ? M(x, md) : err("no inverse");
|
|
88
|
+
};
|
|
89
|
+
var callHash = (name) => {
|
|
90
|
+
const fn = etc[name];
|
|
91
|
+
err("hashes." + name + " not set");
|
|
92
|
+
return fn;
|
|
93
|
+
};
|
|
94
|
+
var apoint = (p) => p instanceof Point ? p : err("Point expected");
|
|
95
|
+
var B256 = 2n ** 256n;
|
|
96
|
+
var Point = class _Point {
|
|
97
|
+
static BASE;
|
|
98
|
+
static ZERO;
|
|
99
|
+
ex;
|
|
100
|
+
ey;
|
|
101
|
+
ez;
|
|
102
|
+
et;
|
|
103
|
+
constructor(ex, ey, ez, et) {
|
|
104
|
+
const max = B256;
|
|
105
|
+
this.ex = arange(ex, 0n, max);
|
|
106
|
+
this.ey = arange(ey, 0n, max);
|
|
107
|
+
this.ez = arange(ez, 1n, max);
|
|
108
|
+
this.et = arange(et, 0n, max);
|
|
109
|
+
Object.freeze(this);
|
|
110
|
+
}
|
|
111
|
+
static fromAffine(p) {
|
|
112
|
+
return new _Point(p.x, p.y, 1n, M(p.x * p.y));
|
|
113
|
+
}
|
|
114
|
+
/** RFC8032 5.1.3: Uint8Array to Point. */
|
|
115
|
+
static fromBytes(hex, zip215 = false) {
|
|
116
|
+
const d = _d;
|
|
117
|
+
const normed = u8fr(abytes(hex, L));
|
|
118
|
+
const lastByte = hex[31];
|
|
119
|
+
normed[31] = lastByte & -129;
|
|
120
|
+
const y = bytesToNumLE(normed);
|
|
121
|
+
const max = zip215 ? B256 : P;
|
|
122
|
+
arange(y, 0n, max);
|
|
123
|
+
const y2 = M(y * y);
|
|
124
|
+
const u = M(y2 - 1n);
|
|
125
|
+
const v = M(d * y2 + 1n);
|
|
126
|
+
let { isValid, value: x } = uvRatio(u, v);
|
|
127
|
+
if (!isValid)
|
|
128
|
+
err("bad point: y not sqrt");
|
|
129
|
+
const isXOdd = (x & 1n) === 1n;
|
|
130
|
+
const isLastByteOdd = (lastByte & 128) !== 0;
|
|
131
|
+
if (!zip215 && x === 0n && isLastByteOdd)
|
|
132
|
+
err("bad point: x==0, isLastByteOdd");
|
|
133
|
+
if (isLastByteOdd !== isXOdd)
|
|
134
|
+
x = M(-x);
|
|
135
|
+
return new _Point(x, y, 1n, M(x * y));
|
|
136
|
+
}
|
|
137
|
+
/** Checks if the point is valid and on-curve. */
|
|
138
|
+
assertValidity() {
|
|
139
|
+
const a = _a;
|
|
140
|
+
const d = _d;
|
|
141
|
+
const p = this;
|
|
142
|
+
if (p.is0())
|
|
143
|
+
throw new Error("bad point: ZERO");
|
|
144
|
+
const { ex: X, ey: Y, ez: Z, et: T } = p;
|
|
145
|
+
const X2 = M(X * X);
|
|
146
|
+
const Y2 = M(Y * Y);
|
|
147
|
+
const Z2 = M(Z * Z);
|
|
148
|
+
const Z4 = M(Z2 * Z2);
|
|
149
|
+
const aX2 = M(X2 * a);
|
|
150
|
+
const left = M(Z2 * M(aX2 + Y2));
|
|
151
|
+
const right = M(Z4 + M(d * M(X2 * Y2)));
|
|
152
|
+
if (left !== right)
|
|
153
|
+
throw new Error("bad point: equation left != right (1)");
|
|
154
|
+
const XY = M(X * Y);
|
|
155
|
+
const ZT = M(Z * T);
|
|
156
|
+
if (XY !== ZT)
|
|
157
|
+
throw new Error("bad point: equation left != right (2)");
|
|
158
|
+
return this;
|
|
159
|
+
}
|
|
160
|
+
/** Equality check: compare points P&Q. */
|
|
161
|
+
equals(other) {
|
|
162
|
+
const { ex: X1, ey: Y1, ez: Z1 } = this;
|
|
163
|
+
const { ex: X2, ey: Y2, ez: Z2 } = apoint(other);
|
|
164
|
+
const X1Z2 = M(X1 * Z2);
|
|
165
|
+
const X2Z1 = M(X2 * Z1);
|
|
166
|
+
const Y1Z2 = M(Y1 * Z2);
|
|
167
|
+
const Y2Z1 = M(Y2 * Z1);
|
|
168
|
+
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
|
169
|
+
}
|
|
170
|
+
is0() {
|
|
171
|
+
return this.equals(I);
|
|
172
|
+
}
|
|
173
|
+
/** Flip point over y coordinate. */
|
|
174
|
+
negate() {
|
|
175
|
+
return new _Point(M(-this.ex), this.ey, this.ez, M(-this.et));
|
|
176
|
+
}
|
|
177
|
+
/** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
|
|
178
|
+
double() {
|
|
179
|
+
const { ex: X1, ey: Y1, ez: Z1 } = this;
|
|
180
|
+
const a = _a;
|
|
181
|
+
const A = M(X1 * X1);
|
|
182
|
+
const B = M(Y1 * Y1);
|
|
183
|
+
const C2 = M(2n * M(Z1 * Z1));
|
|
184
|
+
const D = M(a * A);
|
|
185
|
+
const x1y1 = X1 + Y1;
|
|
186
|
+
const E = M(M(x1y1 * x1y1) - A - B);
|
|
187
|
+
const G2 = D + B;
|
|
188
|
+
const F = G2 - C2;
|
|
189
|
+
const H = D - B;
|
|
190
|
+
const X3 = M(E * F);
|
|
191
|
+
const Y3 = M(G2 * H);
|
|
192
|
+
const T3 = M(E * H);
|
|
193
|
+
const Z3 = M(F * G2);
|
|
194
|
+
return new _Point(X3, Y3, Z3, T3);
|
|
195
|
+
}
|
|
196
|
+
/** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
|
|
197
|
+
add(other) {
|
|
198
|
+
const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
|
|
199
|
+
const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other);
|
|
200
|
+
const a = _a;
|
|
201
|
+
const d = _d;
|
|
202
|
+
const A = M(X1 * X2);
|
|
203
|
+
const B = M(Y1 * Y2);
|
|
204
|
+
const C2 = M(T1 * d * T2);
|
|
205
|
+
const D = M(Z1 * Z2);
|
|
206
|
+
const E = M((X1 + Y1) * (X2 + Y2) - A - B);
|
|
207
|
+
const F = M(D - C2);
|
|
208
|
+
const G2 = M(D + C2);
|
|
209
|
+
const H = M(B - a * A);
|
|
210
|
+
const X3 = M(E * F);
|
|
211
|
+
const Y3 = M(G2 * H);
|
|
212
|
+
const T3 = M(E * H);
|
|
213
|
+
const Z3 = M(F * G2);
|
|
214
|
+
return new _Point(X3, Y3, Z3, T3);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
|
|
218
|
+
* Uses {@link wNAF} for base point.
|
|
219
|
+
* Uses fake point to mitigate side-channel leakage.
|
|
220
|
+
* @param n scalar by which point is multiplied
|
|
221
|
+
* @param safe safe mode guards against timing attacks; unsafe mode is faster
|
|
222
|
+
*/
|
|
223
|
+
multiply(n, safe = true) {
|
|
224
|
+
if (!safe && (n === 0n || this.is0()))
|
|
225
|
+
return I;
|
|
226
|
+
arange(n, 1n, N);
|
|
227
|
+
if (n === 1n)
|
|
228
|
+
return this;
|
|
229
|
+
if (this.equals(G))
|
|
230
|
+
return wNAF(n).p;
|
|
231
|
+
let p = I;
|
|
232
|
+
let f = G;
|
|
233
|
+
for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
|
|
234
|
+
if (n & 1n)
|
|
235
|
+
p = p.add(d);
|
|
236
|
+
else if (safe)
|
|
237
|
+
f = f.add(d);
|
|
238
|
+
}
|
|
239
|
+
return p;
|
|
240
|
+
}
|
|
241
|
+
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
|
|
242
|
+
toAffine() {
|
|
243
|
+
const { ex: x, ey: y, ez: z } = this;
|
|
244
|
+
if (this.equals(I))
|
|
245
|
+
return { x: 0n, y: 1n };
|
|
246
|
+
const iz = invert(z, P);
|
|
247
|
+
if (M(z * iz) !== 1n)
|
|
248
|
+
err("invalid inverse");
|
|
249
|
+
return { x: M(x * iz), y: M(y * iz) };
|
|
250
|
+
}
|
|
251
|
+
toBytes() {
|
|
252
|
+
const { x, y } = this.assertValidity().toAffine();
|
|
253
|
+
const b = numTo32bLE(y);
|
|
254
|
+
b[31] |= x & 1n ? 128 : 0;
|
|
255
|
+
return b;
|
|
256
|
+
}
|
|
257
|
+
toHex() {
|
|
258
|
+
return bytesToHex(this.toBytes());
|
|
259
|
+
}
|
|
260
|
+
// encode to hex string
|
|
261
|
+
clearCofactor() {
|
|
262
|
+
return this.multiply(big(h), false);
|
|
263
|
+
}
|
|
264
|
+
isSmallOrder() {
|
|
265
|
+
return this.clearCofactor().is0();
|
|
266
|
+
}
|
|
267
|
+
isTorsionFree() {
|
|
268
|
+
let p = this.multiply(N / 2n, false).double();
|
|
269
|
+
if (N % 2n)
|
|
270
|
+
p = p.add(this);
|
|
271
|
+
return p.is0();
|
|
272
|
+
}
|
|
273
|
+
static fromHex(hex, zip215) {
|
|
274
|
+
return _Point.fromBytes(toU8(hex), zip215);
|
|
275
|
+
}
|
|
276
|
+
get x() {
|
|
277
|
+
return this.toAffine().x;
|
|
278
|
+
}
|
|
279
|
+
get y() {
|
|
280
|
+
return this.toAffine().y;
|
|
281
|
+
}
|
|
282
|
+
toRawBytes() {
|
|
283
|
+
return this.toBytes();
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
|
|
287
|
+
var I = new Point(0n, 1n, 1n, 0n);
|
|
288
|
+
Point.BASE = G;
|
|
289
|
+
Point.ZERO = I;
|
|
290
|
+
var numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();
|
|
291
|
+
var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
|
|
292
|
+
var pow2 = (x, power) => {
|
|
293
|
+
let r = x;
|
|
294
|
+
while (power-- > 0n) {
|
|
295
|
+
r *= r;
|
|
296
|
+
r %= P;
|
|
297
|
+
}
|
|
298
|
+
return r;
|
|
299
|
+
};
|
|
300
|
+
var pow_2_252_3 = (x) => {
|
|
301
|
+
const x2 = x * x % P;
|
|
302
|
+
const b2 = x2 * x % P;
|
|
303
|
+
const b4 = pow2(b2, 2n) * b2 % P;
|
|
304
|
+
const b5 = pow2(b4, 1n) * x % P;
|
|
305
|
+
const b10 = pow2(b5, 5n) * b5 % P;
|
|
306
|
+
const b20 = pow2(b10, 10n) * b10 % P;
|
|
307
|
+
const b40 = pow2(b20, 20n) * b20 % P;
|
|
308
|
+
const b80 = pow2(b40, 40n) * b40 % P;
|
|
309
|
+
const b160 = pow2(b80, 80n) * b80 % P;
|
|
310
|
+
const b240 = pow2(b160, 80n) * b80 % P;
|
|
311
|
+
const b250 = pow2(b240, 10n) * b10 % P;
|
|
312
|
+
const pow_p_5_8 = pow2(b250, 2n) * x % P;
|
|
313
|
+
return { pow_p_5_8, b2 };
|
|
314
|
+
};
|
|
315
|
+
var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
|
|
316
|
+
var uvRatio = (u, v) => {
|
|
317
|
+
const v3 = M(v * v * v);
|
|
318
|
+
const v7 = M(v3 * v3 * v);
|
|
319
|
+
const pow = pow_2_252_3(u * v7).pow_p_5_8;
|
|
320
|
+
let x = M(u * v3 * pow);
|
|
321
|
+
const vx2 = M(v * x * x);
|
|
322
|
+
const root1 = x;
|
|
323
|
+
const root2 = M(x * RM1);
|
|
324
|
+
const useRoot1 = vx2 === u;
|
|
325
|
+
const useRoot2 = vx2 === M(-u);
|
|
326
|
+
const noRoot = vx2 === M(-u * RM1);
|
|
327
|
+
if (useRoot1)
|
|
328
|
+
x = root1;
|
|
329
|
+
if (useRoot2 || noRoot)
|
|
330
|
+
x = root2;
|
|
331
|
+
if ((M(x) & 1n) === 1n)
|
|
332
|
+
x = M(-x);
|
|
333
|
+
return { isValid: useRoot1 || useRoot2, value: x };
|
|
334
|
+
};
|
|
335
|
+
var modL_LE = (hash) => modN(bytesToNumLE(hash));
|
|
336
|
+
var sha512a = (...m) => etc.sha512Async(...m);
|
|
337
|
+
var sha512s = (...m) => callHash("sha512Sync")(...m);
|
|
338
|
+
var hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
|
|
339
|
+
var hashFinishS = (res) => res.finish(sha512s(res.hashable));
|
|
340
|
+
var veriOpts = { zip215: true };
|
|
341
|
+
var _verify = (sig, msg, pub, opts = veriOpts) => {
|
|
342
|
+
sig = toU8(sig, L2);
|
|
343
|
+
msg = toU8(msg);
|
|
344
|
+
pub = toU8(pub, L);
|
|
345
|
+
const { zip215 } = opts;
|
|
346
|
+
let A;
|
|
347
|
+
let R;
|
|
348
|
+
let s;
|
|
349
|
+
let SB;
|
|
350
|
+
let hashable = Uint8Array.of();
|
|
351
|
+
try {
|
|
352
|
+
A = Point.fromHex(pub, zip215);
|
|
353
|
+
R = Point.fromHex(sig.slice(0, L), zip215);
|
|
354
|
+
s = bytesToNumLE(sig.slice(L, L2));
|
|
355
|
+
SB = G.multiply(s, false);
|
|
356
|
+
hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
}
|
|
359
|
+
const finish = (hashed) => {
|
|
360
|
+
if (SB == null)
|
|
361
|
+
return false;
|
|
362
|
+
if (!zip215 && A.isSmallOrder())
|
|
363
|
+
return false;
|
|
364
|
+
const k = modL_LE(hashed);
|
|
365
|
+
const RkA = R.add(A.multiply(k, false));
|
|
366
|
+
return RkA.add(SB.negate()).clearCofactor().is0();
|
|
367
|
+
};
|
|
368
|
+
return { hashable, finish };
|
|
369
|
+
};
|
|
370
|
+
var verifyAsync = async (s, m, p, opts = veriOpts) => hashFinishA(_verify(s, m, p, opts));
|
|
371
|
+
var verify = (s, m, p, opts = veriOpts) => hashFinishS(_verify(s, m, p, opts));
|
|
372
|
+
var etc = {
|
|
373
|
+
sha512Async: async (...messages) => {
|
|
374
|
+
const s = subtle();
|
|
375
|
+
const m = concatBytes(...messages);
|
|
376
|
+
return u8n(await s.digest("SHA-512", m.buffer));
|
|
377
|
+
},
|
|
378
|
+
sha512Sync: void 0,
|
|
379
|
+
bytesToHex,
|
|
380
|
+
hexToBytes,
|
|
381
|
+
concatBytes,
|
|
382
|
+
mod: M,
|
|
383
|
+
invert,
|
|
384
|
+
randomBytes
|
|
385
|
+
};
|
|
386
|
+
var W = 8;
|
|
387
|
+
var scalarBits = 256;
|
|
388
|
+
var pwindows = Math.ceil(scalarBits / W) + 1;
|
|
389
|
+
var pwindowSize = 2 ** (W - 1);
|
|
390
|
+
var precompute = () => {
|
|
391
|
+
const points = [];
|
|
392
|
+
let p = G;
|
|
393
|
+
let b = p;
|
|
394
|
+
for (let w = 0; w < pwindows; w++) {
|
|
395
|
+
b = p;
|
|
396
|
+
points.push(b);
|
|
397
|
+
for (let i = 1; i < pwindowSize; i++) {
|
|
398
|
+
b = b.add(p);
|
|
399
|
+
points.push(b);
|
|
400
|
+
}
|
|
401
|
+
p = b.double();
|
|
402
|
+
}
|
|
403
|
+
return points;
|
|
404
|
+
};
|
|
405
|
+
var Gpows = void 0;
|
|
406
|
+
var ctneg = (cnd, p) => {
|
|
407
|
+
const n = p.negate();
|
|
408
|
+
return cnd ? n : p;
|
|
409
|
+
};
|
|
410
|
+
var wNAF = (n) => {
|
|
411
|
+
const comp = Gpows || (Gpows = precompute());
|
|
412
|
+
let p = I;
|
|
413
|
+
let f = G;
|
|
414
|
+
const pow_2_w = 2 ** W;
|
|
415
|
+
const maxNum = pow_2_w;
|
|
416
|
+
const mask = big(pow_2_w - 1);
|
|
417
|
+
const shiftBy = big(W);
|
|
418
|
+
for (let w = 0; w < pwindows; w++) {
|
|
419
|
+
let wbits = Number(n & mask);
|
|
420
|
+
n >>= shiftBy;
|
|
421
|
+
if (wbits > pwindowSize) {
|
|
422
|
+
wbits -= maxNum;
|
|
423
|
+
n += 1n;
|
|
424
|
+
}
|
|
425
|
+
const off = w * pwindowSize;
|
|
426
|
+
const offF = off;
|
|
427
|
+
const offP = off + Math.abs(wbits) - 1;
|
|
428
|
+
const isEven = w % 2 !== 0;
|
|
429
|
+
const isNeg = wbits < 0;
|
|
430
|
+
if (wbits === 0) {
|
|
431
|
+
f = f.add(ctneg(isEven, comp[offF]));
|
|
432
|
+
} else {
|
|
433
|
+
p = p.add(ctneg(isNeg, comp[offP]));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return { p, f };
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
// src/webhook/signature.ts
|
|
440
|
+
var DEFAULT_TIMESTAMP_TOLERANCE = 300;
|
|
441
|
+
var SIGNATURE_HEADER = "x-webhook-signature";
|
|
442
|
+
var TIMESTAMP_HEADER = "x-webhook-timestamp";
|
|
443
|
+
var SignatureVerificationError = class _SignatureVerificationError extends Error {
|
|
444
|
+
constructor(message) {
|
|
445
|
+
super(message);
|
|
446
|
+
this.name = "SignatureVerificationError";
|
|
447
|
+
if (Error.captureStackTrace) {
|
|
448
|
+
Error.captureStackTrace(this, _SignatureVerificationError);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
function parsePublicKey(hexKey) {
|
|
453
|
+
if (!hexKey || typeof hexKey !== "string") {
|
|
454
|
+
throw new SignatureVerificationError("Public key is required");
|
|
455
|
+
}
|
|
456
|
+
const cleanKey = hexKey.trim().toLowerCase();
|
|
457
|
+
if (cleanKey.length !== 64) {
|
|
458
|
+
throw new SignatureVerificationError(
|
|
459
|
+
`Invalid public key length: expected 64 hex characters, got ${cleanKey.length}`
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
if (!/^[0-9a-f]+$/.test(cleanKey)) {
|
|
463
|
+
throw new SignatureVerificationError("Invalid public key: must be hex-encoded");
|
|
464
|
+
}
|
|
465
|
+
const bytes = new Uint8Array(32);
|
|
466
|
+
for (let i = 0; i < 32; i++) {
|
|
467
|
+
bytes[i] = parseInt(cleanKey.substring(i * 2, i * 2 + 2), 16);
|
|
468
|
+
}
|
|
469
|
+
return bytes;
|
|
470
|
+
}
|
|
471
|
+
function parseSignature(signatureB64) {
|
|
472
|
+
if (!signatureB64 || typeof signatureB64 !== "string") {
|
|
473
|
+
throw new SignatureVerificationError("Signature is required");
|
|
474
|
+
}
|
|
475
|
+
try {
|
|
476
|
+
const normalized = signatureB64.replace(/-/g, "+").replace(/_/g, "/");
|
|
477
|
+
const binaryString = atob(normalized);
|
|
478
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
479
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
480
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
481
|
+
}
|
|
482
|
+
if (bytes.length !== 64) {
|
|
483
|
+
throw new SignatureVerificationError(
|
|
484
|
+
`Invalid signature length: expected 64 bytes, got ${bytes.length}`
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
return bytes;
|
|
488
|
+
} catch (error) {
|
|
489
|
+
if (error instanceof SignatureVerificationError) {
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
throw new SignatureVerificationError("Invalid signature: must be base64-encoded");
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
function validateTimestamp(timestampStr, toleranceSeconds) {
|
|
496
|
+
if (!timestampStr || typeof timestampStr !== "string") {
|
|
497
|
+
throw new SignatureVerificationError("Timestamp is required");
|
|
498
|
+
}
|
|
499
|
+
const timestamp = parseInt(timestampStr, 10);
|
|
500
|
+
if (isNaN(timestamp)) {
|
|
501
|
+
throw new SignatureVerificationError("Invalid timestamp: must be a Unix timestamp");
|
|
502
|
+
}
|
|
503
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
504
|
+
const age = now - timestamp;
|
|
505
|
+
if (age > toleranceSeconds) {
|
|
506
|
+
throw new SignatureVerificationError(
|
|
507
|
+
`Timestamp expired: ${age} seconds old (tolerance: ${toleranceSeconds}s)`
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
if (age < -toleranceSeconds) {
|
|
511
|
+
throw new SignatureVerificationError(
|
|
512
|
+
`Timestamp is in the future: ${-age} seconds ahead (tolerance: ${toleranceSeconds}s)`
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function buildSignedMessage(payload, timestamp) {
|
|
517
|
+
const payloadBytes = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
|
|
518
|
+
const timestampBytes = new TextEncoder().encode(timestamp + ".");
|
|
519
|
+
const message = new Uint8Array(timestampBytes.length + payloadBytes.length);
|
|
520
|
+
message.set(timestampBytes);
|
|
521
|
+
message.set(payloadBytes, timestampBytes.length);
|
|
522
|
+
return message;
|
|
523
|
+
}
|
|
524
|
+
async function verifySignature(payload, signatureB64, timestampStr, publicKeyHex, toleranceSeconds = DEFAULT_TIMESTAMP_TOLERANCE) {
|
|
525
|
+
validateTimestamp(timestampStr, toleranceSeconds);
|
|
526
|
+
const publicKey = parsePublicKey(publicKeyHex);
|
|
527
|
+
const signature = parseSignature(signatureB64);
|
|
528
|
+
const message = buildSignedMessage(payload, timestampStr);
|
|
529
|
+
const isValid = await verifyAsync(signature, message, publicKey);
|
|
530
|
+
if (!isValid) {
|
|
531
|
+
throw new SignatureVerificationError("Signature verification failed");
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
function verifySignatureSync(payload, signatureB64, timestampStr, publicKeyHex, toleranceSeconds = DEFAULT_TIMESTAMP_TOLERANCE) {
|
|
535
|
+
validateTimestamp(timestampStr, toleranceSeconds);
|
|
536
|
+
const publicKey = parsePublicKey(publicKeyHex);
|
|
537
|
+
const signature = parseSignature(signatureB64);
|
|
538
|
+
const message = buildSignedMessage(payload, timestampStr);
|
|
539
|
+
const isValid = verify(signature, message, publicKey);
|
|
540
|
+
if (!isValid) {
|
|
541
|
+
throw new SignatureVerificationError("Signature verification failed");
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// src/webhook/events.ts
|
|
546
|
+
var WebhookEventType = /* @__PURE__ */ ((WebhookEventType2) => {
|
|
547
|
+
WebhookEventType2["UserCreated"] = "user.created";
|
|
548
|
+
WebhookEventType2["UserUpdated"] = "user.updated";
|
|
549
|
+
WebhookEventType2["UserDeleted"] = "user.deleted";
|
|
550
|
+
WebhookEventType2["ApiKeyCreated"] = "api_key.created";
|
|
551
|
+
WebhookEventType2["ApiKeyDeleted"] = "api_key.deleted";
|
|
552
|
+
WebhookEventType2["CustomerCreated"] = "customer.created";
|
|
553
|
+
WebhookEventType2["CustomerUpdated"] = "customer.updated";
|
|
554
|
+
WebhookEventType2["CustomerKybLinkCreated"] = "customer.kyb_link.created";
|
|
555
|
+
WebhookEventType2["CustomerKybLinkUpdated"] = "customer.kyb_link.updated";
|
|
556
|
+
WebhookEventType2["CustomerKybStatusCreated"] = "customer.kyb_status.created";
|
|
557
|
+
WebhookEventType2["CustomerKybStatusUpdated"] = "customer.kyb_status.updated";
|
|
558
|
+
WebhookEventType2["CustomerKybApplicationSubmitted"] = "customer.kyb_application.submitted";
|
|
559
|
+
WebhookEventType2["AutoAccountCreated"] = "auto_account.created";
|
|
560
|
+
WebhookEventType2["AutoAccountUpdated"] = "auto_account.updated";
|
|
561
|
+
WebhookEventType2["AutoAccountDeleted"] = "auto_account.deleted";
|
|
562
|
+
WebhookEventType2["TransactionAutoCreated"] = "transaction.auto.created";
|
|
563
|
+
WebhookEventType2["TransactionAutoUpdated"] = "transaction.auto.updated";
|
|
564
|
+
WebhookEventType2["TransactionOneOffCreated"] = "transaction.one_off.created";
|
|
565
|
+
WebhookEventType2["TransactionOneOffUpdated"] = "transaction.one_off.updated";
|
|
566
|
+
WebhookEventType2["RecipientCreated"] = "recipient.created";
|
|
567
|
+
WebhookEventType2["RecipientUpdated"] = "recipient.updated";
|
|
568
|
+
WebhookEventType2["RecipientDeleted"] = "recipient.deleted";
|
|
569
|
+
WebhookEventType2["DestinationCreated"] = "destination.created";
|
|
570
|
+
WebhookEventType2["DestinationDeleted"] = "destination.deleted";
|
|
571
|
+
WebhookEventType2["TargetCreated"] = "target.created";
|
|
572
|
+
WebhookEventType2["TargetUpdated"] = "target.updated";
|
|
573
|
+
WebhookEventType2["TargetDeleted"] = "target.deleted";
|
|
574
|
+
WebhookEventType2["ExceptionCreated"] = "exception.created";
|
|
575
|
+
WebhookEventType2["ExceptionCleared"] = "exception.cleared";
|
|
576
|
+
WebhookEventType2["BvnkOnboardingCreated"] = "bvnk.onboarding.created";
|
|
577
|
+
WebhookEventType2["BvnkOnboardingUpdated"] = "bvnk.onboarding.updated";
|
|
578
|
+
WebhookEventType2["WalletCreated"] = "wallet.created";
|
|
579
|
+
WebhookEventType2["WalletUpdated"] = "wallet.updated";
|
|
580
|
+
WebhookEventType2["WalletSignerGroupCreated"] = "wallet.signer_group.created";
|
|
581
|
+
WebhookEventType2["WalletSignerGroupUpdated"] = "wallet.signer_group.updated";
|
|
582
|
+
WebhookEventType2["WalletPolicyCreated"] = "wallet.policy.created";
|
|
583
|
+
WebhookEventType2["WalletPolicyUpdated"] = "wallet.policy.updated";
|
|
584
|
+
WebhookEventType2["WalletTransactionCreated"] = "wallet.transaction.created";
|
|
585
|
+
WebhookEventType2["WalletTransactionUpdated"] = "wallet.transaction.updated";
|
|
586
|
+
WebhookEventType2["WalletDeposit"] = "wallet.deposit";
|
|
587
|
+
WebhookEventType2["TransactionCreated"] = "transaction.created";
|
|
588
|
+
WebhookEventType2["TransactionUpdated"] = "transaction.updated";
|
|
589
|
+
WebhookEventType2["TransactionCompleted"] = "transaction.completed";
|
|
590
|
+
WebhookEventType2["TransactionFailed"] = "transaction.failed";
|
|
591
|
+
WebhookEventType2["TransactionCancelled"] = "transaction.cancelled";
|
|
592
|
+
WebhookEventType2["AccountCreated"] = "account.created";
|
|
593
|
+
WebhookEventType2["AccountUpdated"] = "account.updated";
|
|
594
|
+
return WebhookEventType2;
|
|
595
|
+
})(WebhookEventType || {});
|
|
596
|
+
function parseEvent(payload) {
|
|
597
|
+
const payloadStr = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
|
|
598
|
+
try {
|
|
599
|
+
const event = JSON.parse(payloadStr);
|
|
600
|
+
if (!event.id || typeof event.id !== "string") {
|
|
601
|
+
throw new Error("Invalid event: missing or invalid id");
|
|
602
|
+
}
|
|
603
|
+
if (!event.type || typeof event.type !== "string") {
|
|
604
|
+
throw new Error("Invalid event: missing or invalid type");
|
|
605
|
+
}
|
|
606
|
+
if (event.data === void 0) {
|
|
607
|
+
throw new Error("Invalid event: missing data");
|
|
608
|
+
}
|
|
609
|
+
return event;
|
|
610
|
+
} catch (error) {
|
|
611
|
+
if (error instanceof SyntaxError) {
|
|
612
|
+
throw new Error("Invalid event: malformed JSON");
|
|
613
|
+
}
|
|
614
|
+
throw error;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
function matchesEventType(eventType, pattern) {
|
|
618
|
+
if (pattern === "*") {
|
|
619
|
+
return true;
|
|
620
|
+
}
|
|
621
|
+
if (pattern.endsWith(".*")) {
|
|
622
|
+
const prefix = pattern.slice(0, -2);
|
|
623
|
+
return eventType.startsWith(prefix + ".");
|
|
624
|
+
}
|
|
625
|
+
return eventType === pattern;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/webhook/idempotency.ts
|
|
629
|
+
var MemoryIdempotencyStore = class {
|
|
630
|
+
seen = /* @__PURE__ */ new Set();
|
|
631
|
+
maxSize;
|
|
632
|
+
ttlMs;
|
|
633
|
+
timestamps = /* @__PURE__ */ new Map();
|
|
634
|
+
/**
|
|
635
|
+
* Create a new in-memory idempotency store.
|
|
636
|
+
*
|
|
637
|
+
* @param options - Store options
|
|
638
|
+
* @param options.maxSize - Maximum number of event IDs to store (default: 10000)
|
|
639
|
+
* @param options.ttlMs - Time-to-live in milliseconds (default: 24 hours)
|
|
640
|
+
*/
|
|
641
|
+
constructor(options) {
|
|
642
|
+
this.maxSize = options?.maxSize ?? 1e4;
|
|
643
|
+
this.ttlMs = options?.ttlMs ?? 24 * 60 * 60 * 1e3;
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Check if an event has been seen.
|
|
647
|
+
*/
|
|
648
|
+
has(eventId) {
|
|
649
|
+
this.cleanup();
|
|
650
|
+
if (!this.seen.has(eventId)) {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
const timestamp = this.timestamps.get(eventId);
|
|
654
|
+
if (timestamp && Date.now() - timestamp > this.ttlMs) {
|
|
655
|
+
this.seen.delete(eventId);
|
|
656
|
+
this.timestamps.delete(eventId);
|
|
657
|
+
return false;
|
|
658
|
+
}
|
|
659
|
+
return true;
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Mark an event as seen.
|
|
663
|
+
*/
|
|
664
|
+
add(eventId) {
|
|
665
|
+
this.cleanup();
|
|
666
|
+
if (this.seen.size >= this.maxSize) {
|
|
667
|
+
const oldest = this.findOldest();
|
|
668
|
+
if (oldest) {
|
|
669
|
+
this.seen.delete(oldest);
|
|
670
|
+
this.timestamps.delete(oldest);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
this.seen.add(eventId);
|
|
674
|
+
this.timestamps.set(eventId, Date.now());
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Get the number of stored event IDs.
|
|
678
|
+
*/
|
|
679
|
+
get size() {
|
|
680
|
+
return this.seen.size;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Clear all stored event IDs.
|
|
684
|
+
*/
|
|
685
|
+
clear() {
|
|
686
|
+
this.seen.clear();
|
|
687
|
+
this.timestamps.clear();
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Remove expired entries.
|
|
691
|
+
*/
|
|
692
|
+
cleanup() {
|
|
693
|
+
const now = Date.now();
|
|
694
|
+
const expired = [];
|
|
695
|
+
for (const [eventId, timestamp] of this.timestamps) {
|
|
696
|
+
if (now - timestamp > this.ttlMs) {
|
|
697
|
+
expired.push(eventId);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
for (const eventId of expired) {
|
|
701
|
+
this.seen.delete(eventId);
|
|
702
|
+
this.timestamps.delete(eventId);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Find the oldest entry.
|
|
707
|
+
*/
|
|
708
|
+
findOldest() {
|
|
709
|
+
let oldest;
|
|
710
|
+
let oldestTime = Infinity;
|
|
711
|
+
for (const [eventId, timestamp] of this.timestamps) {
|
|
712
|
+
if (timestamp < oldestTime) {
|
|
713
|
+
oldestTime = timestamp;
|
|
714
|
+
oldest = eventId;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
return oldest;
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
// src/webhook/handler.ts
|
|
722
|
+
var DEFAULT_MAX_PAYLOAD_SIZE = 64 * 1024;
|
|
723
|
+
var WebhookHandler = class {
|
|
724
|
+
publicKey;
|
|
725
|
+
timestampTolerance;
|
|
726
|
+
maxPayloadSize;
|
|
727
|
+
idempotencyStore;
|
|
728
|
+
handlers = /* @__PURE__ */ new Map();
|
|
729
|
+
defaultHandler = null;
|
|
730
|
+
/**
|
|
731
|
+
* Create a new webhook handler.
|
|
732
|
+
*
|
|
733
|
+
* @param config - Handler configuration
|
|
734
|
+
*/
|
|
735
|
+
constructor(config) {
|
|
736
|
+
if (!config.publicKey) {
|
|
737
|
+
throw new Error("Public key is required");
|
|
738
|
+
}
|
|
739
|
+
this.publicKey = config.publicKey;
|
|
740
|
+
this.timestampTolerance = config.timestampTolerance ?? DEFAULT_TIMESTAMP_TOLERANCE;
|
|
741
|
+
this.maxPayloadSize = config.maxPayloadSize ?? DEFAULT_MAX_PAYLOAD_SIZE;
|
|
742
|
+
if (config.idempotencyStore === false) {
|
|
743
|
+
this.idempotencyStore = null;
|
|
744
|
+
} else if (config.idempotencyStore) {
|
|
745
|
+
this.idempotencyStore = config.idempotencyStore;
|
|
746
|
+
} else {
|
|
747
|
+
this.idempotencyStore = new MemoryIdempotencyStore();
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Register a handler for specific event types.
|
|
752
|
+
*
|
|
753
|
+
* Supports wildcards: 'customer.*' matches all customer events.
|
|
754
|
+
*
|
|
755
|
+
* @param eventType - Event type or pattern to handle
|
|
756
|
+
* @param handler - Handler function
|
|
757
|
+
* @returns this for chaining
|
|
758
|
+
*
|
|
759
|
+
* @example
|
|
760
|
+
* ```typescript
|
|
761
|
+
* handler
|
|
762
|
+
* .on('customer.created', handleCustomerCreated)
|
|
763
|
+
* .on('transaction.*', handleTransactionEvents)
|
|
764
|
+
* .on('*', logAllEvents);
|
|
765
|
+
* ```
|
|
766
|
+
*/
|
|
767
|
+
on(eventType, handler) {
|
|
768
|
+
const handlers = this.handlers.get(eventType) ?? [];
|
|
769
|
+
handlers.push(handler);
|
|
770
|
+
this.handlers.set(eventType, handlers);
|
|
771
|
+
return this;
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Register a default handler for unmatched events.
|
|
775
|
+
*
|
|
776
|
+
* @param handler - Handler function
|
|
777
|
+
* @returns this for chaining
|
|
778
|
+
*/
|
|
779
|
+
onDefault(handler) {
|
|
780
|
+
this.defaultHandler = handler;
|
|
781
|
+
return this;
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Handle an incoming webhook request.
|
|
785
|
+
*
|
|
786
|
+
* @param body - Raw request body (string or Buffer)
|
|
787
|
+
* @param headers - Request headers
|
|
788
|
+
* @throws SignatureVerificationError if signature is invalid
|
|
789
|
+
* @throws Error if payload is invalid or too large
|
|
790
|
+
*
|
|
791
|
+
* @example
|
|
792
|
+
* ```typescript
|
|
793
|
+
* // Express with raw body parser
|
|
794
|
+
* app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
795
|
+
* try {
|
|
796
|
+
* await handler.handleRequest(req.body, req.headers);
|
|
797
|
+
* res.sendStatus(200);
|
|
798
|
+
* } catch (error) {
|
|
799
|
+
* res.status(400).send(error.message);
|
|
800
|
+
* }
|
|
801
|
+
* });
|
|
802
|
+
* ```
|
|
803
|
+
*/
|
|
804
|
+
async handleRequest(body, headers) {
|
|
805
|
+
let payload;
|
|
806
|
+
if (typeof body === "string") {
|
|
807
|
+
payload = new TextEncoder().encode(body);
|
|
808
|
+
} else if (body instanceof Uint8Array) {
|
|
809
|
+
payload = body;
|
|
810
|
+
} else if (Buffer.isBuffer(body)) {
|
|
811
|
+
payload = new Uint8Array(body);
|
|
812
|
+
} else {
|
|
813
|
+
throw new Error("Invalid body: must be string, Uint8Array, or Buffer");
|
|
814
|
+
}
|
|
815
|
+
if (payload.length > this.maxPayloadSize) {
|
|
816
|
+
throw new Error(`Payload too large: ${payload.length} bytes (max: ${this.maxPayloadSize})`);
|
|
817
|
+
}
|
|
818
|
+
const signature = this.getHeader(headers, SIGNATURE_HEADER);
|
|
819
|
+
const timestamp = this.getHeader(headers, TIMESTAMP_HEADER);
|
|
820
|
+
if (!signature) {
|
|
821
|
+
throw new SignatureVerificationError(`Missing ${SIGNATURE_HEADER} header`);
|
|
822
|
+
}
|
|
823
|
+
if (!timestamp) {
|
|
824
|
+
throw new SignatureVerificationError(`Missing ${TIMESTAMP_HEADER} header`);
|
|
825
|
+
}
|
|
826
|
+
await verifySignature(payload, signature, timestamp, this.publicKey, this.timestampTolerance);
|
|
827
|
+
const event = parseEvent(payload);
|
|
828
|
+
if (this.idempotencyStore) {
|
|
829
|
+
if (await this.idempotencyStore.has(event.id)) {
|
|
830
|
+
return event;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
await this.dispatch(event);
|
|
834
|
+
if (this.idempotencyStore) {
|
|
835
|
+
await this.idempotencyStore.add(event.id);
|
|
836
|
+
}
|
|
837
|
+
return event;
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Construct a webhook event from payload and verify signature.
|
|
841
|
+
*
|
|
842
|
+
* Use this when you need to verify and parse without dispatching.
|
|
843
|
+
*
|
|
844
|
+
* @param payload - Raw request body
|
|
845
|
+
* @param signature - X-Webhook-Signature header value
|
|
846
|
+
* @param timestamp - X-Webhook-Timestamp header value
|
|
847
|
+
* @returns Parsed and verified event
|
|
848
|
+
*/
|
|
849
|
+
async constructEvent(payload, signature, timestamp) {
|
|
850
|
+
await verifySignature(payload, signature, timestamp, this.publicKey, this.timestampTolerance);
|
|
851
|
+
return parseEvent(payload);
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Create Express-compatible middleware.
|
|
855
|
+
*
|
|
856
|
+
* @returns Express middleware function
|
|
857
|
+
*
|
|
858
|
+
* @example
|
|
859
|
+
* ```typescript
|
|
860
|
+
* import express from 'express';
|
|
861
|
+
*
|
|
862
|
+
* const app = express();
|
|
863
|
+
*
|
|
864
|
+
* app.post(
|
|
865
|
+
* '/webhooks/dakota',
|
|
866
|
+
* express.raw({ type: 'application/json' }),
|
|
867
|
+
* handler.expressMiddleware()
|
|
868
|
+
* );
|
|
869
|
+
* ```
|
|
870
|
+
*/
|
|
871
|
+
expressMiddleware() {
|
|
872
|
+
return async (req, res, next) => {
|
|
873
|
+
try {
|
|
874
|
+
await this.handleRequest(req.body, req.headers);
|
|
875
|
+
res.sendStatus(200);
|
|
876
|
+
} catch (error) {
|
|
877
|
+
if (error instanceof SignatureVerificationError) {
|
|
878
|
+
res.status(401).send(error.message);
|
|
879
|
+
} else if (error instanceof Error) {
|
|
880
|
+
res.status(400).send(error.message);
|
|
881
|
+
} else {
|
|
882
|
+
next(error);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Dispatch an event to registered handlers.
|
|
889
|
+
*/
|
|
890
|
+
async dispatch(event) {
|
|
891
|
+
let handled = false;
|
|
892
|
+
for (const [pattern, handlers] of this.handlers) {
|
|
893
|
+
if (matchesEventType(event.type, pattern)) {
|
|
894
|
+
for (const handler of handlers) {
|
|
895
|
+
await handler(event);
|
|
896
|
+
handled = true;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (!handled && this.defaultHandler) {
|
|
901
|
+
await this.defaultHandler(event);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Get a header value (case-insensitive).
|
|
906
|
+
*/
|
|
907
|
+
getHeader(headers, name) {
|
|
908
|
+
const value = headers[name] ?? headers[name.toLowerCase()];
|
|
909
|
+
if (Array.isArray(value)) {
|
|
910
|
+
return value[0];
|
|
911
|
+
}
|
|
912
|
+
return value;
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
/*! Bundled license information:
|
|
916
|
+
|
|
917
|
+
@noble/ed25519/index.js:
|
|
918
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
919
|
+
*/
|
|
920
|
+
|
|
921
|
+
exports.DEFAULT_TIMESTAMP_TOLERANCE = DEFAULT_TIMESTAMP_TOLERANCE;
|
|
922
|
+
exports.MemoryIdempotencyStore = MemoryIdempotencyStore;
|
|
923
|
+
exports.SIGNATURE_HEADER = SIGNATURE_HEADER;
|
|
924
|
+
exports.SignatureVerificationError = SignatureVerificationError;
|
|
925
|
+
exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER;
|
|
926
|
+
exports.WebhookEventType = WebhookEventType;
|
|
927
|
+
exports.WebhookHandler = WebhookHandler;
|
|
928
|
+
exports.matchesEventType = matchesEventType;
|
|
929
|
+
exports.parseEvent = parseEvent;
|
|
930
|
+
exports.parsePublicKey = parsePublicKey;
|
|
931
|
+
exports.parseSignature = parseSignature;
|
|
932
|
+
exports.validateTimestamp = validateTimestamp;
|
|
933
|
+
exports.verifySignature = verifySignature;
|
|
934
|
+
exports.verifySignatureSync = verifySignatureSync;
|
|
935
|
+
//# sourceMappingURL=index.js.map
|
|
936
|
+
//# sourceMappingURL=index.js.map
|