@motebit/crypto 0.8.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 ADDED
@@ -0,0 +1,2513 @@
1
+ // ../../node_modules/.pnpm/@noble+ed25519@3.0.1/node_modules/@noble/ed25519/index.js
2
+ var ed25519_CURVE = {
3
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
4
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
5
+ h: 8n,
6
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
7
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
8
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
9
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
10
+ };
11
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
12
+ var L = 32;
13
+ var captureTrace = (...args) => {
14
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
15
+ Error.captureStackTrace(...args);
16
+ }
17
+ };
18
+ var err = (message = "") => {
19
+ const e = new Error(message);
20
+ captureTrace(e, err);
21
+ throw e;
22
+ };
23
+ var isBig = (n) => typeof n === "bigint";
24
+ var isStr = (s) => typeof s === "string";
25
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
26
+ var abytes = (value, length, title = "") => {
27
+ const bytes = isBytes(value);
28
+ const len = value?.length;
29
+ const needsLen = length !== void 0;
30
+ if (!bytes || needsLen && len !== length) {
31
+ const prefix = title && `"${title}" `;
32
+ const ofLen = needsLen ? ` of length ${length}` : "";
33
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
34
+ err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
35
+ }
36
+ return value;
37
+ };
38
+ var u8n = (len) => new Uint8Array(len);
39
+ var u8fr = (buf) => Uint8Array.from(buf);
40
+ var padh = (n, pad) => n.toString(16).padStart(pad, "0");
41
+ var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
42
+ var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
43
+ var _ch = (ch) => {
44
+ if (ch >= C._0 && ch <= C._9)
45
+ return ch - C._0;
46
+ if (ch >= C.A && ch <= C.F)
47
+ return ch - (C.A - 10);
48
+ if (ch >= C.a && ch <= C.f)
49
+ return ch - (C.a - 10);
50
+ return;
51
+ };
52
+ var hexToBytes = (hex) => {
53
+ const e = "hex invalid";
54
+ if (!isStr(hex))
55
+ return err(e);
56
+ const hl = hex.length;
57
+ const al = hl / 2;
58
+ if (hl % 2)
59
+ return err(e);
60
+ const array = u8n(al);
61
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
62
+ const n1 = _ch(hex.charCodeAt(hi));
63
+ const n2 = _ch(hex.charCodeAt(hi + 1));
64
+ if (n1 === void 0 || n2 === void 0)
65
+ return err(e);
66
+ array[ai] = n1 * 16 + n2;
67
+ }
68
+ return array;
69
+ };
70
+ var cr = () => globalThis?.crypto;
71
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
72
+ var concatBytes = (...arrs) => {
73
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
74
+ let pad = 0;
75
+ arrs.forEach((a) => {
76
+ r.set(a, pad);
77
+ pad += a.length;
78
+ });
79
+ return r;
80
+ };
81
+ var randomBytes = (len = L) => {
82
+ const c = cr();
83
+ return c.getRandomValues(u8n(len));
84
+ };
85
+ var big = BigInt;
86
+ var assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
87
+ var M = (a, b = P) => {
88
+ const r = a % b;
89
+ return r >= 0n ? r : b + r;
90
+ };
91
+ var P_MASK = (1n << 255n) - 1n;
92
+ var modP = (num) => {
93
+ if (num < 0n)
94
+ err("negative coordinate");
95
+ let r = (num >> 255n) * 19n + (num & P_MASK);
96
+ r = (r >> 255n) * 19n + (r & P_MASK);
97
+ return r % P;
98
+ };
99
+ var modN = (a) => M(a, N);
100
+ var invert = (num, md) => {
101
+ if (num === 0n || md <= 0n)
102
+ err("no inverse n=" + num + " mod=" + md);
103
+ let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
104
+ while (a !== 0n) {
105
+ const q = b / a, r = b % a;
106
+ const m = x - u * q, n = y - v * q;
107
+ b = a, a = r, x = u, y = v, u = m, v = n;
108
+ }
109
+ return b === 1n ? M(x, md) : err("no inverse");
110
+ };
111
+ var apoint = (p) => p instanceof Point ? p : err("Point expected");
112
+ var B256 = 2n ** 256n;
113
+ var Point = class _Point {
114
+ static BASE;
115
+ static ZERO;
116
+ X;
117
+ Y;
118
+ Z;
119
+ T;
120
+ constructor(X, Y, Z, T) {
121
+ const max = B256;
122
+ this.X = assertRange(X, 0n, max);
123
+ this.Y = assertRange(Y, 0n, max);
124
+ this.Z = assertRange(Z, 1n, max);
125
+ this.T = assertRange(T, 0n, max);
126
+ Object.freeze(this);
127
+ }
128
+ static CURVE() {
129
+ return ed25519_CURVE;
130
+ }
131
+ static fromAffine(p) {
132
+ return new _Point(p.x, p.y, 1n, modP(p.x * p.y));
133
+ }
134
+ /** RFC8032 5.1.3: Uint8Array to Point. */
135
+ static fromBytes(hex, zip215 = false) {
136
+ const d = _d;
137
+ const normed = u8fr(abytes(hex, L));
138
+ const lastByte = hex[31];
139
+ normed[31] = lastByte & ~128;
140
+ const y = bytesToNumberLE(normed);
141
+ const max = zip215 ? B256 : P;
142
+ assertRange(y, 0n, max);
143
+ const y2 = modP(y * y);
144
+ const u = M(y2 - 1n);
145
+ const v = modP(d * y2 + 1n);
146
+ let { isValid, value: x } = uvRatio(u, v);
147
+ if (!isValid)
148
+ err("bad point: y not sqrt");
149
+ const isXOdd = (x & 1n) === 1n;
150
+ const isLastByteOdd = (lastByte & 128) !== 0;
151
+ if (!zip215 && x === 0n && isLastByteOdd)
152
+ err("bad point: x==0, isLastByteOdd");
153
+ if (isLastByteOdd !== isXOdd)
154
+ x = M(-x);
155
+ return new _Point(x, y, 1n, modP(x * y));
156
+ }
157
+ static fromHex(hex, zip215) {
158
+ return _Point.fromBytes(hexToBytes(hex), zip215);
159
+ }
160
+ get x() {
161
+ return this.toAffine().x;
162
+ }
163
+ get y() {
164
+ return this.toAffine().y;
165
+ }
166
+ /** Checks if the point is valid and on-curve. */
167
+ assertValidity() {
168
+ const a = _a;
169
+ const d = _d;
170
+ const p = this;
171
+ if (p.is0())
172
+ return err("bad point: ZERO");
173
+ const { X, Y, Z, T } = p;
174
+ const X2 = modP(X * X);
175
+ const Y2 = modP(Y * Y);
176
+ const Z2 = modP(Z * Z);
177
+ const Z4 = modP(Z2 * Z2);
178
+ const aX2 = modP(X2 * a);
179
+ const left = modP(Z2 * (aX2 + Y2));
180
+ const right = M(Z4 + modP(d * modP(X2 * Y2)));
181
+ if (left !== right)
182
+ return err("bad point: equation left != right (1)");
183
+ const XY = modP(X * Y);
184
+ const ZT = modP(Z * T);
185
+ if (XY !== ZT)
186
+ return err("bad point: equation left != right (2)");
187
+ return this;
188
+ }
189
+ /** Equality check: compare points P&Q. */
190
+ equals(other) {
191
+ const { X: X1, Y: Y1, Z: Z1 } = this;
192
+ const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
193
+ const X1Z2 = modP(X1 * Z2);
194
+ const X2Z1 = modP(X2 * Z1);
195
+ const Y1Z2 = modP(Y1 * Z2);
196
+ const Y2Z1 = modP(Y2 * Z1);
197
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
198
+ }
199
+ is0() {
200
+ return this.equals(I);
201
+ }
202
+ /** Flip point over y coordinate. */
203
+ negate() {
204
+ return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
205
+ }
206
+ /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
207
+ double() {
208
+ const { X: X1, Y: Y1, Z: Z1 } = this;
209
+ const a = _a;
210
+ const A = modP(X1 * X1);
211
+ const B = modP(Y1 * Y1);
212
+ const C2 = modP(2n * Z1 * Z1);
213
+ const D = modP(a * A);
214
+ const x1y1 = M(X1 + Y1);
215
+ const E = M(modP(x1y1 * x1y1) - A - B);
216
+ const G2 = M(D + B);
217
+ const F = M(G2 - C2);
218
+ const H = M(D - B);
219
+ const X3 = modP(E * F);
220
+ const Y3 = modP(G2 * H);
221
+ const T3 = modP(E * H);
222
+ const Z3 = modP(F * G2);
223
+ return new _Point(X3, Y3, Z3, T3);
224
+ }
225
+ /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
226
+ add(other) {
227
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
228
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
229
+ const a = _a;
230
+ const d = _d;
231
+ const A = modP(X1 * X2);
232
+ const B = modP(Y1 * Y2);
233
+ const C2 = modP(modP(T1 * d) * T2);
234
+ const D = modP(Z1 * Z2);
235
+ const E = M(modP(M(X1 + Y1) * M(X2 + Y2)) - A - B);
236
+ const F = M(D - C2);
237
+ const G2 = M(D + C2);
238
+ const H = M(B - modP(a * A));
239
+ const X3 = modP(E * F);
240
+ const Y3 = modP(G2 * H);
241
+ const T3 = modP(E * H);
242
+ const Z3 = modP(F * G2);
243
+ return new _Point(X3, Y3, Z3, T3);
244
+ }
245
+ subtract(other) {
246
+ return this.add(apoint(other).negate());
247
+ }
248
+ /**
249
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
250
+ * Uses {@link wNAF} for base point.
251
+ * Uses fake point to mitigate side-channel leakage.
252
+ * @param n scalar by which point is multiplied
253
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
254
+ */
255
+ multiply(n, safe = true) {
256
+ if (!safe && (n === 0n || this.is0()))
257
+ return I;
258
+ assertRange(n, 1n, N);
259
+ if (n === 1n)
260
+ return this;
261
+ if (this.equals(G))
262
+ return wNAF(n).p;
263
+ let p = I;
264
+ let f = G;
265
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
266
+ if (n & 1n)
267
+ p = p.add(d);
268
+ else if (safe)
269
+ f = f.add(d);
270
+ }
271
+ return p;
272
+ }
273
+ multiplyUnsafe(scalar) {
274
+ return this.multiply(scalar, false);
275
+ }
276
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
277
+ toAffine() {
278
+ const { X, Y, Z } = this;
279
+ if (this.equals(I))
280
+ return { x: 0n, y: 1n };
281
+ const iz = invert(Z, P);
282
+ if (modP(Z * iz) !== 1n)
283
+ err("invalid inverse");
284
+ const x = modP(X * iz);
285
+ const y = modP(Y * iz);
286
+ return { x, y };
287
+ }
288
+ toBytes() {
289
+ const { x, y } = this.toAffine();
290
+ const b = numTo32bLE(y);
291
+ b[31] |= x & 1n ? 128 : 0;
292
+ return b;
293
+ }
294
+ toHex() {
295
+ return bytesToHex(this.toBytes());
296
+ }
297
+ clearCofactor() {
298
+ return this.multiply(big(h), false);
299
+ }
300
+ isSmallOrder() {
301
+ return this.clearCofactor().is0();
302
+ }
303
+ isTorsionFree() {
304
+ let p = this.multiply(N / 2n, false).double();
305
+ if (N % 2n)
306
+ p = p.add(this);
307
+ return p.is0();
308
+ }
309
+ };
310
+ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
311
+ var I = new Point(0n, 1n, 1n, 0n);
312
+ Point.BASE = G;
313
+ Point.ZERO = I;
314
+ var numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), 64)).reverse();
315
+ var bytesToNumberLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
316
+ var pow2 = (x, power) => {
317
+ let r = x;
318
+ while (power-- > 0n) {
319
+ r = modP(r * r);
320
+ }
321
+ return r;
322
+ };
323
+ var pow_2_252_3 = (x) => {
324
+ const x2 = modP(x * x);
325
+ const b2 = modP(x2 * x);
326
+ const b4 = modP(pow2(b2, 2n) * b2);
327
+ const b5 = modP(pow2(b4, 1n) * x);
328
+ const b10 = modP(pow2(b5, 5n) * b5);
329
+ const b20 = modP(pow2(b10, 10n) * b10);
330
+ const b40 = modP(pow2(b20, 20n) * b20);
331
+ const b80 = modP(pow2(b40, 40n) * b40);
332
+ const b160 = modP(pow2(b80, 80n) * b80);
333
+ const b240 = modP(pow2(b160, 80n) * b80);
334
+ const b250 = modP(pow2(b240, 10n) * b10);
335
+ const pow_p_5_8 = modP(pow2(b250, 2n) * x);
336
+ return { pow_p_5_8, b2 };
337
+ };
338
+ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
339
+ var uvRatio = (u, v) => {
340
+ const v3 = modP(v * modP(v * v));
341
+ const v7 = modP(modP(v3 * v3) * v);
342
+ const pow = pow_2_252_3(modP(u * v7)).pow_p_5_8;
343
+ let x = modP(u * modP(v3 * pow));
344
+ const vx2 = modP(v * modP(x * x));
345
+ const root1 = x;
346
+ const root2 = modP(x * RM1);
347
+ const useRoot1 = vx2 === u;
348
+ const useRoot2 = vx2 === M(-u);
349
+ const noRoot = vx2 === M(-u * RM1);
350
+ if (useRoot1)
351
+ x = root1;
352
+ if (useRoot2 || noRoot)
353
+ x = root2;
354
+ if ((M(x) & 1n) === 1n)
355
+ x = M(-x);
356
+ return { isValid: useRoot1 || useRoot2, value: x };
357
+ };
358
+ var modL_LE = (hash2) => modN(bytesToNumberLE(hash2));
359
+ var sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
360
+ var hash2extK = (hashed) => {
361
+ const head = hashed.slice(0, 32);
362
+ head[0] &= 248;
363
+ head[31] &= 127;
364
+ head[31] |= 64;
365
+ const prefix = hashed.slice(32, 64);
366
+ const scalar = modL_LE(head);
367
+ const point = G.multiply(scalar);
368
+ const pointBytes = point.toBytes();
369
+ return { head, prefix, scalar, point, pointBytes };
370
+ };
371
+ var getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
372
+ var getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
373
+ var hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
374
+ var _sign = (e, rBytes, msg) => {
375
+ const { pointBytes: P2, scalar: s } = e;
376
+ const r = modL_LE(rBytes);
377
+ const R = G.multiply(r).toBytes();
378
+ const hashable = concatBytes(R, P2, msg);
379
+ const finish = (hashed) => {
380
+ const S = modN(r + modL_LE(hashed) * s);
381
+ return abytes(concatBytes(R, numTo32bLE(S)), 64);
382
+ };
383
+ return { hashable, finish };
384
+ };
385
+ var signAsync = async (message, secretKey) => {
386
+ const m = abytes(message);
387
+ const e = await getExtendedPublicKeyAsync(secretKey);
388
+ const rBytes = await sha512a(e.prefix, m);
389
+ return hashFinishA(_sign(e, rBytes, m));
390
+ };
391
+ var defaultVerifyOpts = { zip215: true };
392
+ var _verify = (sig, msg, publicKey, options = defaultVerifyOpts) => {
393
+ sig = abytes(sig, 64);
394
+ msg = abytes(msg);
395
+ publicKey = abytes(publicKey, L);
396
+ const { zip215 } = options;
397
+ const r = sig.subarray(0, L);
398
+ const s = bytesToNumberLE(sig.subarray(L, L * 2));
399
+ let A, R, SB;
400
+ let hashable = Uint8Array.of();
401
+ let finished = false;
402
+ try {
403
+ A = Point.fromBytes(publicKey, zip215);
404
+ R = Point.fromBytes(r, zip215);
405
+ SB = G.multiply(s, false);
406
+ hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
407
+ finished = true;
408
+ } catch (error) {
409
+ }
410
+ const finish = (hashed) => {
411
+ if (!finished)
412
+ return false;
413
+ if (!zip215 && A.isSmallOrder())
414
+ return false;
415
+ const k = modL_LE(hashed);
416
+ const RkA = R.add(A.multiply(k, false));
417
+ return RkA.subtract(SB).clearCofactor().is0();
418
+ };
419
+ return { hashable, finish };
420
+ };
421
+ var verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
422
+ var hashes = {
423
+ sha512Async: async (message) => {
424
+ const s = subtle();
425
+ const m = concatBytes(message);
426
+ return u8n(await s.digest("SHA-512", m.buffer));
427
+ },
428
+ sha512: void 0
429
+ };
430
+ var randomSecretKey = (seed = randomBytes(L)) => seed;
431
+ var keygenAsync = async (seed) => {
432
+ const secretKey = randomSecretKey(seed);
433
+ const publicKey = await getPublicKeyAsync(secretKey);
434
+ return { secretKey, publicKey };
435
+ };
436
+ var W = 8;
437
+ var scalarBits = 256;
438
+ var pwindows = Math.ceil(scalarBits / W) + 1;
439
+ var pwindowSize = 2 ** (W - 1);
440
+ var precompute = () => {
441
+ const points = [];
442
+ let p = G;
443
+ let b = p;
444
+ for (let w = 0; w < pwindows; w++) {
445
+ b = p;
446
+ points.push(b);
447
+ for (let i = 1; i < pwindowSize; i++) {
448
+ b = b.add(p);
449
+ points.push(b);
450
+ }
451
+ p = b.double();
452
+ }
453
+ return points;
454
+ };
455
+ var Gpows = void 0;
456
+ var ctneg = (cnd, p) => {
457
+ const n = p.negate();
458
+ return cnd ? n : p;
459
+ };
460
+ var wNAF = (n) => {
461
+ const comp = Gpows || (Gpows = precompute());
462
+ let p = I;
463
+ let f = G;
464
+ const pow_2_w = 2 ** W;
465
+ const maxNum = pow_2_w;
466
+ const mask = big(pow_2_w - 1);
467
+ const shiftBy = big(W);
468
+ for (let w = 0; w < pwindows; w++) {
469
+ let wbits = Number(n & mask);
470
+ n >>= shiftBy;
471
+ if (wbits > pwindowSize) {
472
+ wbits -= maxNum;
473
+ n += 1n;
474
+ }
475
+ const off = w * pwindowSize;
476
+ const offF = off;
477
+ const offP = off + Math.abs(wbits) - 1;
478
+ const isEven = w % 2 !== 0;
479
+ const isNeg = wbits < 0;
480
+ if (wbits === 0) {
481
+ f = f.add(ctneg(isEven, comp[offF]));
482
+ } else {
483
+ p = p.add(ctneg(isNeg, comp[offP]));
484
+ }
485
+ }
486
+ if (n !== 0n)
487
+ err("invalid wnaf");
488
+ return { p, f };
489
+ };
490
+
491
+ // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/_assert.js
492
+ function isBytes2(a) {
493
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
494
+ }
495
+ function abytes2(b, ...lengths) {
496
+ if (!isBytes2(b))
497
+ throw new Error("Uint8Array expected");
498
+ if (lengths.length > 0 && !lengths.includes(b.length))
499
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
500
+ }
501
+ function aexists(instance, checkFinished = true) {
502
+ if (instance.destroyed)
503
+ throw new Error("Hash instance has been destroyed");
504
+ if (checkFinished && instance.finished)
505
+ throw new Error("Hash#digest() has already been called");
506
+ }
507
+ function aoutput(out, instance) {
508
+ abytes2(out);
509
+ const min = instance.outputLen;
510
+ if (out.length < min) {
511
+ throw new Error("digestInto() expects output buffer of length at least " + min);
512
+ }
513
+ }
514
+
515
+ // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/utils.js
516
+ var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
517
+ function utf8ToBytes(str) {
518
+ if (typeof str !== "string")
519
+ throw new Error("utf8ToBytes expected string, got " + typeof str);
520
+ return new Uint8Array(new TextEncoder().encode(str));
521
+ }
522
+ function toBytes(data) {
523
+ if (typeof data === "string")
524
+ data = utf8ToBytes(data);
525
+ abytes2(data);
526
+ return data;
527
+ }
528
+ var Hash = class {
529
+ // Safe version that clones internal state
530
+ clone() {
531
+ return this._cloneInto();
532
+ }
533
+ };
534
+ function wrapConstructor(hashCons) {
535
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
536
+ const tmp = hashCons();
537
+ hashC.outputLen = tmp.outputLen;
538
+ hashC.blockLen = tmp.blockLen;
539
+ hashC.create = () => hashCons();
540
+ return hashC;
541
+ }
542
+
543
+ // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/_md.js
544
+ function setBigUint64(view, byteOffset, value, isLE) {
545
+ if (typeof view.setBigUint64 === "function")
546
+ return view.setBigUint64(byteOffset, value, isLE);
547
+ const _32n2 = BigInt(32);
548
+ const _u32_max = BigInt(4294967295);
549
+ const wh = Number(value >> _32n2 & _u32_max);
550
+ const wl = Number(value & _u32_max);
551
+ const h2 = isLE ? 4 : 0;
552
+ const l = isLE ? 0 : 4;
553
+ view.setUint32(byteOffset + h2, wh, isLE);
554
+ view.setUint32(byteOffset + l, wl, isLE);
555
+ }
556
+ var HashMD = class extends Hash {
557
+ constructor(blockLen, outputLen, padOffset, isLE) {
558
+ super();
559
+ this.blockLen = blockLen;
560
+ this.outputLen = outputLen;
561
+ this.padOffset = padOffset;
562
+ this.isLE = isLE;
563
+ this.finished = false;
564
+ this.length = 0;
565
+ this.pos = 0;
566
+ this.destroyed = false;
567
+ this.buffer = new Uint8Array(blockLen);
568
+ this.view = createView(this.buffer);
569
+ }
570
+ update(data) {
571
+ aexists(this);
572
+ const { view, buffer, blockLen } = this;
573
+ data = toBytes(data);
574
+ const len = data.length;
575
+ for (let pos = 0; pos < len; ) {
576
+ const take = Math.min(blockLen - this.pos, len - pos);
577
+ if (take === blockLen) {
578
+ const dataView = createView(data);
579
+ for (; blockLen <= len - pos; pos += blockLen)
580
+ this.process(dataView, pos);
581
+ continue;
582
+ }
583
+ buffer.set(data.subarray(pos, pos + take), this.pos);
584
+ this.pos += take;
585
+ pos += take;
586
+ if (this.pos === blockLen) {
587
+ this.process(view, 0);
588
+ this.pos = 0;
589
+ }
590
+ }
591
+ this.length += data.length;
592
+ this.roundClean();
593
+ return this;
594
+ }
595
+ digestInto(out) {
596
+ aexists(this);
597
+ aoutput(out, this);
598
+ this.finished = true;
599
+ const { buffer, view, blockLen, isLE } = this;
600
+ let { pos } = this;
601
+ buffer[pos++] = 128;
602
+ this.buffer.subarray(pos).fill(0);
603
+ if (this.padOffset > blockLen - pos) {
604
+ this.process(view, 0);
605
+ pos = 0;
606
+ }
607
+ for (let i = pos; i < blockLen; i++)
608
+ buffer[i] = 0;
609
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
610
+ this.process(view, 0);
611
+ const oview = createView(out);
612
+ const len = this.outputLen;
613
+ if (len % 4)
614
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
615
+ const outLen = len / 4;
616
+ const state = this.get();
617
+ if (outLen > state.length)
618
+ throw new Error("_sha2: outputLen bigger than state");
619
+ for (let i = 0; i < outLen; i++)
620
+ oview.setUint32(4 * i, state[i], isLE);
621
+ }
622
+ digest() {
623
+ const { buffer, outputLen } = this;
624
+ this.digestInto(buffer);
625
+ const res = buffer.slice(0, outputLen);
626
+ this.destroy();
627
+ return res;
628
+ }
629
+ _cloneInto(to) {
630
+ to || (to = new this.constructor());
631
+ to.set(...this.get());
632
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
633
+ to.length = length;
634
+ to.pos = pos;
635
+ to.finished = finished;
636
+ to.destroyed = destroyed;
637
+ if (length % blockLen)
638
+ to.buffer.set(buffer);
639
+ return to;
640
+ }
641
+ };
642
+
643
+ // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/_u64.js
644
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
645
+ var _32n = /* @__PURE__ */ BigInt(32);
646
+ function fromBig(n, le = false) {
647
+ if (le)
648
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
649
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
650
+ }
651
+ function split(lst, le = false) {
652
+ let Ah = new Uint32Array(lst.length);
653
+ let Al = new Uint32Array(lst.length);
654
+ for (let i = 0; i < lst.length; i++) {
655
+ const { h: h2, l } = fromBig(lst[i], le);
656
+ [Ah[i], Al[i]] = [h2, l];
657
+ }
658
+ return [Ah, Al];
659
+ }
660
+ var toBig = (h2, l) => BigInt(h2 >>> 0) << _32n | BigInt(l >>> 0);
661
+ var shrSH = (h2, _l, s) => h2 >>> s;
662
+ var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
663
+ var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
664
+ var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
665
+ var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
666
+ var rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
667
+ var rotr32H = (_h, l) => l;
668
+ var rotr32L = (h2, _l) => h2;
669
+ var rotlSH = (h2, l, s) => h2 << s | l >>> 32 - s;
670
+ var rotlSL = (h2, l, s) => l << s | h2 >>> 32 - s;
671
+ var rotlBH = (h2, l, s) => l << s - 32 | h2 >>> 64 - s;
672
+ var rotlBL = (h2, l, s) => h2 << s - 32 | l >>> 64 - s;
673
+ function add(Ah, Al, Bh, Bl) {
674
+ const l = (Al >>> 0) + (Bl >>> 0);
675
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
676
+ }
677
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
678
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
679
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
680
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
681
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
682
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
683
+ var u64 = {
684
+ fromBig,
685
+ split,
686
+ toBig,
687
+ shrSH,
688
+ shrSL,
689
+ rotrSH,
690
+ rotrSL,
691
+ rotrBH,
692
+ rotrBL,
693
+ rotr32H,
694
+ rotr32L,
695
+ rotlSH,
696
+ rotlSL,
697
+ rotlBH,
698
+ rotlBL,
699
+ add,
700
+ add3L,
701
+ add3H,
702
+ add4L,
703
+ add4H,
704
+ add5H,
705
+ add5L
706
+ };
707
+ var u64_default = u64;
708
+
709
+ // ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/sha512.js
710
+ var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([
711
+ "0x428a2f98d728ae22",
712
+ "0x7137449123ef65cd",
713
+ "0xb5c0fbcfec4d3b2f",
714
+ "0xe9b5dba58189dbbc",
715
+ "0x3956c25bf348b538",
716
+ "0x59f111f1b605d019",
717
+ "0x923f82a4af194f9b",
718
+ "0xab1c5ed5da6d8118",
719
+ "0xd807aa98a3030242",
720
+ "0x12835b0145706fbe",
721
+ "0x243185be4ee4b28c",
722
+ "0x550c7dc3d5ffb4e2",
723
+ "0x72be5d74f27b896f",
724
+ "0x80deb1fe3b1696b1",
725
+ "0x9bdc06a725c71235",
726
+ "0xc19bf174cf692694",
727
+ "0xe49b69c19ef14ad2",
728
+ "0xefbe4786384f25e3",
729
+ "0x0fc19dc68b8cd5b5",
730
+ "0x240ca1cc77ac9c65",
731
+ "0x2de92c6f592b0275",
732
+ "0x4a7484aa6ea6e483",
733
+ "0x5cb0a9dcbd41fbd4",
734
+ "0x76f988da831153b5",
735
+ "0x983e5152ee66dfab",
736
+ "0xa831c66d2db43210",
737
+ "0xb00327c898fb213f",
738
+ "0xbf597fc7beef0ee4",
739
+ "0xc6e00bf33da88fc2",
740
+ "0xd5a79147930aa725",
741
+ "0x06ca6351e003826f",
742
+ "0x142929670a0e6e70",
743
+ "0x27b70a8546d22ffc",
744
+ "0x2e1b21385c26c926",
745
+ "0x4d2c6dfc5ac42aed",
746
+ "0x53380d139d95b3df",
747
+ "0x650a73548baf63de",
748
+ "0x766a0abb3c77b2a8",
749
+ "0x81c2c92e47edaee6",
750
+ "0x92722c851482353b",
751
+ "0xa2bfe8a14cf10364",
752
+ "0xa81a664bbc423001",
753
+ "0xc24b8b70d0f89791",
754
+ "0xc76c51a30654be30",
755
+ "0xd192e819d6ef5218",
756
+ "0xd69906245565a910",
757
+ "0xf40e35855771202a",
758
+ "0x106aa07032bbd1b8",
759
+ "0x19a4c116b8d2d0c8",
760
+ "0x1e376c085141ab53",
761
+ "0x2748774cdf8eeb99",
762
+ "0x34b0bcb5e19b48a8",
763
+ "0x391c0cb3c5c95a63",
764
+ "0x4ed8aa4ae3418acb",
765
+ "0x5b9cca4f7763e373",
766
+ "0x682e6ff3d6b2b8a3",
767
+ "0x748f82ee5defb2fc",
768
+ "0x78a5636f43172f60",
769
+ "0x84c87814a1f0ab72",
770
+ "0x8cc702081a6439ec",
771
+ "0x90befffa23631e28",
772
+ "0xa4506cebde82bde9",
773
+ "0xbef9a3f7b2c67915",
774
+ "0xc67178f2e372532b",
775
+ "0xca273eceea26619c",
776
+ "0xd186b8c721c0c207",
777
+ "0xeada7dd6cde0eb1e",
778
+ "0xf57d4f7fee6ed178",
779
+ "0x06f067aa72176fba",
780
+ "0x0a637dc5a2c898a6",
781
+ "0x113f9804bef90dae",
782
+ "0x1b710b35131c471b",
783
+ "0x28db77f523047d84",
784
+ "0x32caab7b40c72493",
785
+ "0x3c9ebe0a15c9bebc",
786
+ "0x431d67c49c100d4c",
787
+ "0x4cc5d4becb3e42b6",
788
+ "0x597f299cfc657e2a",
789
+ "0x5fcb6fab3ad6faec",
790
+ "0x6c44198c4a475817"
791
+ ].map((n) => BigInt(n))))();
792
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
793
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
794
+ var SHA512 = class extends HashMD {
795
+ constructor() {
796
+ super(128, 64, 16, false);
797
+ this.Ah = 1779033703 | 0;
798
+ this.Al = 4089235720 | 0;
799
+ this.Bh = 3144134277 | 0;
800
+ this.Bl = 2227873595 | 0;
801
+ this.Ch = 1013904242 | 0;
802
+ this.Cl = 4271175723 | 0;
803
+ this.Dh = 2773480762 | 0;
804
+ this.Dl = 1595750129 | 0;
805
+ this.Eh = 1359893119 | 0;
806
+ this.El = 2917565137 | 0;
807
+ this.Fh = 2600822924 | 0;
808
+ this.Fl = 725511199 | 0;
809
+ this.Gh = 528734635 | 0;
810
+ this.Gl = 4215389547 | 0;
811
+ this.Hh = 1541459225 | 0;
812
+ this.Hl = 327033209 | 0;
813
+ }
814
+ // prettier-ignore
815
+ get() {
816
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
817
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
818
+ }
819
+ // prettier-ignore
820
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
821
+ this.Ah = Ah | 0;
822
+ this.Al = Al | 0;
823
+ this.Bh = Bh | 0;
824
+ this.Bl = Bl | 0;
825
+ this.Ch = Ch | 0;
826
+ this.Cl = Cl | 0;
827
+ this.Dh = Dh | 0;
828
+ this.Dl = Dl | 0;
829
+ this.Eh = Eh | 0;
830
+ this.El = El | 0;
831
+ this.Fh = Fh | 0;
832
+ this.Fl = Fl | 0;
833
+ this.Gh = Gh | 0;
834
+ this.Gl = Gl | 0;
835
+ this.Hh = Hh | 0;
836
+ this.Hl = Hl | 0;
837
+ }
838
+ process(view, offset) {
839
+ for (let i = 0; i < 16; i++, offset += 4) {
840
+ SHA512_W_H[i] = view.getUint32(offset);
841
+ SHA512_W_L[i] = view.getUint32(offset += 4);
842
+ }
843
+ for (let i = 16; i < 80; i++) {
844
+ const W15h = SHA512_W_H[i - 15] | 0;
845
+ const W15l = SHA512_W_L[i - 15] | 0;
846
+ const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7);
847
+ const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7);
848
+ const W2h = SHA512_W_H[i - 2] | 0;
849
+ const W2l = SHA512_W_L[i - 2] | 0;
850
+ const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6);
851
+ const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6);
852
+ const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
853
+ const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
854
+ SHA512_W_H[i] = SUMh | 0;
855
+ SHA512_W_L[i] = SUMl | 0;
856
+ }
857
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
858
+ for (let i = 0; i < 80; i++) {
859
+ const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41);
860
+ const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41);
861
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
862
+ const CHIl = El & Fl ^ ~El & Gl;
863
+ const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
864
+ const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
865
+ const T1l = T1ll | 0;
866
+ const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39);
867
+ const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39);
868
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
869
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
870
+ Hh = Gh | 0;
871
+ Hl = Gl | 0;
872
+ Gh = Fh | 0;
873
+ Gl = Fl | 0;
874
+ Fh = Eh | 0;
875
+ Fl = El | 0;
876
+ ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
877
+ Dh = Ch | 0;
878
+ Dl = Cl | 0;
879
+ Ch = Bh | 0;
880
+ Cl = Bl | 0;
881
+ Bh = Ah | 0;
882
+ Bl = Al | 0;
883
+ const All = u64_default.add3L(T1l, sigma0l, MAJl);
884
+ Ah = u64_default.add3H(All, T1h, sigma0h, MAJh);
885
+ Al = All | 0;
886
+ }
887
+ ({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
888
+ ({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
889
+ ({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
890
+ ({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
891
+ ({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
892
+ ({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
893
+ ({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
894
+ ({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
895
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
896
+ }
897
+ roundClean() {
898
+ SHA512_W_H.fill(0);
899
+ SHA512_W_L.fill(0);
900
+ }
901
+ destroy() {
902
+ this.buffer.fill(0);
903
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
904
+ }
905
+ };
906
+ var sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
907
+
908
+ // src/signing.ts
909
+ if (!hashes.sha512) {
910
+ hashes.sha512 = (msg) => sha512(msg);
911
+ }
912
+ function canonicalJson(obj) {
913
+ if (obj === null || obj === void 0) return JSON.stringify(obj);
914
+ if (typeof obj !== "object") return JSON.stringify(obj);
915
+ if (Array.isArray(obj)) {
916
+ return "[" + obj.map((item) => canonicalJson(item)).join(",") + "]";
917
+ }
918
+ const sorted = Object.keys(obj).sort();
919
+ const entries = [];
920
+ for (const key of sorted) {
921
+ const val = obj[key];
922
+ if (val === void 0) continue;
923
+ entries.push(JSON.stringify(key) + ":" + canonicalJson(val));
924
+ }
925
+ return "{" + entries.join(",") + "}";
926
+ }
927
+ function bytesToHex2(bytes) {
928
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
929
+ }
930
+ function hexToBytes2(hex) {
931
+ const bytes = new Uint8Array(hex.length / 2);
932
+ for (let i = 0; i < hex.length; i += 2) {
933
+ bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
934
+ }
935
+ return bytes;
936
+ }
937
+ function toBase64Url(data) {
938
+ let binary = "";
939
+ for (let i = 0; i < data.length; i++) {
940
+ binary += String.fromCharCode(data[i]);
941
+ }
942
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
943
+ }
944
+ function fromBase64Url(str) {
945
+ const padded = str.replace(/-/g, "+").replace(/_/g, "/");
946
+ const binary = atob(padded);
947
+ const bytes = new Uint8Array(binary.length);
948
+ for (let i = 0; i < binary.length; i++) {
949
+ bytes[i] = binary.charCodeAt(i);
950
+ }
951
+ return bytes;
952
+ }
953
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
954
+ function base58btcEncode(bytes) {
955
+ let zeros = 0;
956
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
957
+ let value = 0n;
958
+ for (let i = 0; i < bytes.length; i++) {
959
+ value = value * 256n + BigInt(bytes[i]);
960
+ }
961
+ let result = "";
962
+ while (value > 0n) {
963
+ const remainder = Number(value % 58n);
964
+ value = value / 58n;
965
+ result = BASE58_ALPHABET[remainder] + result;
966
+ }
967
+ return BASE58_ALPHABET[0].repeat(zeros) + result;
968
+ }
969
+ function base58btcDecode(str) {
970
+ let zeros = 0;
971
+ while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;
972
+ let value = 0n;
973
+ for (let i = 0; i < str.length; i++) {
974
+ const idx = BASE58_ALPHABET.indexOf(str[i]);
975
+ if (idx === -1) throw new Error(`Invalid base58 character: ${str[i]}`);
976
+ value = value * 58n + BigInt(idx);
977
+ }
978
+ const hex = [];
979
+ while (value > 0n) {
980
+ const byte = Number(value & 0xffn);
981
+ hex.unshift(byte.toString(16).padStart(2, "0"));
982
+ value >>= 8n;
983
+ }
984
+ const dataBytes = hex.length > 0 ? new Uint8Array(hex.map((h2) => parseInt(h2, 16))) : new Uint8Array(0);
985
+ const result = new Uint8Array(zeros + dataBytes.length);
986
+ result.set(dataBytes, zeros);
987
+ return result;
988
+ }
989
+ function didKeyToPublicKey(did) {
990
+ if (!did.startsWith("did:key:z")) {
991
+ throw new Error("Invalid did:key URI: must start with did:key:z");
992
+ }
993
+ const encoded = did.slice("did:key:z".length);
994
+ const decoded = base58btcDecode(encoded);
995
+ if (decoded.length !== 34) {
996
+ throw new Error(
997
+ `Invalid did:key: expected 34 bytes (2 prefix + 32 key), got ${decoded.length}`
998
+ );
999
+ }
1000
+ if (decoded[0] !== 237 || decoded[1] !== 1) {
1001
+ throw new Error("Invalid did:key: multicodec prefix is not ed25519-pub (0xed01)");
1002
+ }
1003
+ return decoded.slice(2);
1004
+ }
1005
+ function publicKeyToDidKey(publicKey) {
1006
+ if (publicKey.length !== 32) {
1007
+ throw new Error("Ed25519 public key must be 32 bytes");
1008
+ }
1009
+ const prefixed = new Uint8Array(34);
1010
+ prefixed[0] = 237;
1011
+ prefixed[1] = 1;
1012
+ prefixed.set(publicKey, 2);
1013
+ return `did:key:z${base58btcEncode(prefixed)}`;
1014
+ }
1015
+ function hexPublicKeyToDidKey(hexPublicKey) {
1016
+ return publicKeyToDidKey(hexToBytes2(hexPublicKey));
1017
+ }
1018
+ async function hash(data) {
1019
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1020
+ const hashArray = new Uint8Array(hashBuffer);
1021
+ return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
1022
+ }
1023
+ async function sha256(data) {
1024
+ const buf = await crypto.subtle.digest("SHA-256", data);
1025
+ return new Uint8Array(buf);
1026
+ }
1027
+ async function generateKeypair() {
1028
+ const { secretKey, publicKey } = await keygenAsync();
1029
+ return { publicKey, privateKey: secretKey };
1030
+ }
1031
+ async function ed25519Sign(message, privateKey) {
1032
+ return signAsync(message, privateKey);
1033
+ }
1034
+ async function ed25519Verify(signature, message, publicKey) {
1035
+ try {
1036
+ return await verifyAsync(signature, message, publicKey);
1037
+ } catch {
1038
+ return false;
1039
+ }
1040
+ }
1041
+ async function createSignedToken(payload, privateKey) {
1042
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
1043
+ const payloadB64 = toBase64Url(payloadBytes);
1044
+ const signature = await ed25519Sign(payloadBytes, privateKey);
1045
+ const sigB64 = toBase64Url(signature);
1046
+ return `${payloadB64}.${sigB64}`;
1047
+ }
1048
+ async function verifySignedToken(token, publicKey) {
1049
+ const dotIdx = token.indexOf(".");
1050
+ if (dotIdx === -1) return null;
1051
+ const payloadB64 = token.slice(0, dotIdx);
1052
+ const sigB64 = token.slice(dotIdx + 1);
1053
+ let payloadBytes;
1054
+ let signature;
1055
+ try {
1056
+ payloadBytes = fromBase64Url(payloadB64);
1057
+ signature = fromBase64Url(sigB64);
1058
+ } catch {
1059
+ return null;
1060
+ }
1061
+ const valid = await ed25519Verify(signature, payloadBytes, publicKey);
1062
+ if (!valid) return null;
1063
+ let payload;
1064
+ try {
1065
+ payload = JSON.parse(new TextDecoder().decode(payloadBytes));
1066
+ } catch {
1067
+ return null;
1068
+ }
1069
+ if (payload.exp <= Date.now()) return null;
1070
+ if (!payload.jti) return null;
1071
+ if (!payload.aud) return null;
1072
+ return payload;
1073
+ }
1074
+ function parseScopeSet(scope) {
1075
+ if (scope === "*") return /* @__PURE__ */ new Set(["*"]);
1076
+ return new Set(
1077
+ scope.split(",").map((s) => s.trim()).filter((s) => s.length > 0)
1078
+ );
1079
+ }
1080
+ function isScopeNarrowed(parentScope, childScope) {
1081
+ const parent = parseScopeSet(parentScope);
1082
+ const child = parseScopeSet(childScope);
1083
+ if (parent.has("*")) return true;
1084
+ if (child.has("*")) return false;
1085
+ for (const cap of child) {
1086
+ if (!parent.has(cap)) return false;
1087
+ }
1088
+ return true;
1089
+ }
1090
+
1091
+ // src/artifacts.ts
1092
+ async function signExecutionReceipt(receipt, privateKey, publicKey) {
1093
+ const body = publicKey ? { ...receipt, public_key: bytesToHex2(publicKey) } : receipt;
1094
+ const canonical = canonicalJson(body);
1095
+ const message = new TextEncoder().encode(canonical);
1096
+ const sig = await ed25519Sign(message, privateKey);
1097
+ return { ...body, signature: toBase64Url(sig) };
1098
+ }
1099
+ async function verifyExecutionReceipt(receipt, publicKey) {
1100
+ const { signature, ...body } = receipt;
1101
+ const canonical = canonicalJson(body);
1102
+ const message = new TextEncoder().encode(canonical);
1103
+ try {
1104
+ const sig = fromBase64Url(signature);
1105
+ return await ed25519Verify(sig, message, publicKey);
1106
+ } catch {
1107
+ return false;
1108
+ }
1109
+ }
1110
+ async function signSovereignPaymentReceipt(input, privateKey, publicKey) {
1111
+ const receipt = {
1112
+ task_id: `${input.rail}:tx:${input.tx_hash}`,
1113
+ motebit_id: input.payee_motebit_id,
1114
+ device_id: input.payee_device_id,
1115
+ submitted_at: input.submitted_at,
1116
+ completed_at: input.completed_at,
1117
+ status: "completed",
1118
+ result: `${input.service_description} | paid by ${input.payer_motebit_id}: ${input.amount_micro.toString()} micro-${input.asset} via ${input.rail}`,
1119
+ tools_used: input.tools_used ?? [],
1120
+ memories_formed: 0,
1121
+ prompt_hash: input.prompt_hash,
1122
+ result_hash: input.result_hash
1123
+ // relay_task_id intentionally omitted — sovereign rail, no relay binding
1124
+ };
1125
+ return signExecutionReceipt(receipt, privateKey, publicKey);
1126
+ }
1127
+ async function verifyReceiptChain(receipt, knownKeys) {
1128
+ const { task_id, motebit_id } = receipt;
1129
+ let publicKey = knownKeys.get(motebit_id);
1130
+ if (!publicKey && receipt.public_key) {
1131
+ publicKey = hexToBytes2(receipt.public_key);
1132
+ }
1133
+ if (!publicKey) {
1134
+ const delegations2 = await verifyDelegations(receipt, knownKeys);
1135
+ return { task_id, motebit_id, verified: false, error: "unknown motebit_id", delegations: delegations2 };
1136
+ }
1137
+ let verified;
1138
+ let error;
1139
+ try {
1140
+ verified = await verifyExecutionReceipt(receipt, publicKey);
1141
+ } catch (err2) {
1142
+ verified = false;
1143
+ error = err2 instanceof Error ? err2.message : String(err2);
1144
+ }
1145
+ const delegations = await verifyDelegations(receipt, knownKeys);
1146
+ const result = { task_id, motebit_id, verified, delegations };
1147
+ if (error) {
1148
+ result.error = error;
1149
+ }
1150
+ return result;
1151
+ }
1152
+ async function verifyDelegations(receipt, knownKeys) {
1153
+ if (!receipt.delegation_receipts || receipt.delegation_receipts.length === 0) {
1154
+ return [];
1155
+ }
1156
+ return Promise.all(receipt.delegation_receipts.map((dr) => verifyReceiptChain(dr, knownKeys)));
1157
+ }
1158
+ async function verifyReceiptSequence(chain) {
1159
+ if (chain.length === 0) return { valid: true };
1160
+ for (let i = 0; i < chain.length; i++) {
1161
+ const entry = chain[i];
1162
+ const sigValid = await verifyExecutionReceipt(entry.receipt, entry.signer_public_key);
1163
+ if (!sigValid) {
1164
+ return { valid: false, error: `Receipt ${i} has invalid signature`, index: i };
1165
+ }
1166
+ }
1167
+ for (let i = 1; i < chain.length; i++) {
1168
+ const prev = chain[i - 1];
1169
+ const curr = chain[i];
1170
+ if (prev.receipt.completed_at > curr.receipt.submitted_at) {
1171
+ return {
1172
+ valid: false,
1173
+ error: `Receipt ${i} submitted_at (${curr.receipt.submitted_at}) is before receipt ${i - 1} completed_at (${prev.receipt.completed_at})`,
1174
+ index: i
1175
+ };
1176
+ }
1177
+ }
1178
+ return { valid: true };
1179
+ }
1180
+ async function signDelegation(delegation, delegatorPrivateKey) {
1181
+ const canonical = canonicalJson(delegation);
1182
+ const message = new TextEncoder().encode(canonical);
1183
+ const sig = await ed25519Sign(message, delegatorPrivateKey);
1184
+ return { ...delegation, signature: toBase64Url(sig) };
1185
+ }
1186
+ async function verifyDelegation(delegation, options) {
1187
+ const checkExpiry = options?.checkExpiry ?? true;
1188
+ if (checkExpiry) {
1189
+ const now = options?.now ?? Date.now();
1190
+ if (delegation.expires_at < now) return false;
1191
+ }
1192
+ const { signature, ...body } = delegation;
1193
+ const canonical = canonicalJson(body);
1194
+ const message = new TextEncoder().encode(canonical);
1195
+ try {
1196
+ const pubKey = fromBase64Url(delegation.delegator_public_key);
1197
+ const sig = fromBase64Url(signature);
1198
+ return await ed25519Verify(sig, message, pubKey);
1199
+ } catch {
1200
+ return false;
1201
+ }
1202
+ }
1203
+ async function verifyDelegationChain(chain) {
1204
+ if (chain.length === 0) return { valid: true };
1205
+ for (let i = 0; i < chain.length; i++) {
1206
+ const delegation = chain[i];
1207
+ const sigValid = await verifyDelegation(delegation, { checkExpiry: false });
1208
+ if (!sigValid) {
1209
+ return { valid: false, error: `Delegation ${i} has invalid signature` };
1210
+ }
1211
+ if (i > 0) {
1212
+ const prev = chain[i - 1];
1213
+ if (prev.delegate_id !== delegation.delegator_id) {
1214
+ return {
1215
+ valid: false,
1216
+ error: `Chain break at ${i}: delegate_id "${prev.delegate_id}" !== delegator_id "${delegation.delegator_id}"`
1217
+ };
1218
+ }
1219
+ if (prev.delegate_public_key !== delegation.delegator_public_key) {
1220
+ return {
1221
+ valid: false,
1222
+ error: `Chain break at ${i}: delegate_public_key mismatch`
1223
+ };
1224
+ }
1225
+ if (!isScopeNarrowed(prev.scope, delegation.scope)) {
1226
+ return {
1227
+ valid: false,
1228
+ error: `Delegation ${i} widens scope: parent="${prev.scope}", child="${delegation.scope}"`
1229
+ };
1230
+ }
1231
+ }
1232
+ }
1233
+ return { valid: true };
1234
+ }
1235
+ function keySuccessionPayload(oldPublicKeyHex, newPublicKeyHex, timestamp, reason, recovery) {
1236
+ const obj = {
1237
+ old_public_key: oldPublicKeyHex,
1238
+ new_public_key: newPublicKeyHex,
1239
+ timestamp
1240
+ };
1241
+ if (reason !== void 0) {
1242
+ obj.reason = reason;
1243
+ }
1244
+ if (recovery) {
1245
+ obj.recovery = true;
1246
+ }
1247
+ return canonicalJson(obj);
1248
+ }
1249
+ async function signKeySuccession(oldPrivateKey, newPrivateKey, newPublicKey, oldPublicKey, reason) {
1250
+ const timestamp = Date.now();
1251
+ const oldPublicKeyHex = bytesToHex2(oldPublicKey);
1252
+ const newPublicKeyHex = bytesToHex2(newPublicKey);
1253
+ const payload = keySuccessionPayload(oldPublicKeyHex, newPublicKeyHex, timestamp, reason);
1254
+ const message = new TextEncoder().encode(payload);
1255
+ const oldSig = await ed25519Sign(message, oldPrivateKey);
1256
+ const newSig = await ed25519Sign(message, newPrivateKey);
1257
+ return {
1258
+ old_public_key: oldPublicKeyHex,
1259
+ new_public_key: newPublicKeyHex,
1260
+ timestamp,
1261
+ ...reason !== void 0 ? { reason } : {},
1262
+ old_key_signature: bytesToHex2(oldSig),
1263
+ new_key_signature: bytesToHex2(newSig)
1264
+ };
1265
+ }
1266
+ async function signGuardianRecoverySuccession(guardianPrivateKey, newPrivateKey, oldPublicKey, newPublicKey, reason) {
1267
+ const timestamp = Date.now();
1268
+ const oldPublicKeyHex = bytesToHex2(oldPublicKey);
1269
+ const newPublicKeyHex = bytesToHex2(newPublicKey);
1270
+ const effectiveReason = reason ?? "guardian_recovery";
1271
+ const payload = keySuccessionPayload(
1272
+ oldPublicKeyHex,
1273
+ newPublicKeyHex,
1274
+ timestamp,
1275
+ effectiveReason,
1276
+ true
1277
+ );
1278
+ const message = new TextEncoder().encode(payload);
1279
+ const guardianSig = await ed25519Sign(message, guardianPrivateKey);
1280
+ const newSig = await ed25519Sign(message, newPrivateKey);
1281
+ return {
1282
+ old_public_key: oldPublicKeyHex,
1283
+ new_public_key: newPublicKeyHex,
1284
+ timestamp,
1285
+ reason: effectiveReason,
1286
+ new_key_signature: bytesToHex2(newSig),
1287
+ recovery: true,
1288
+ guardian_signature: bytesToHex2(guardianSig)
1289
+ };
1290
+ }
1291
+ async function verifyKeySuccession(record, guardianPublicKeyHex) {
1292
+ const payload = keySuccessionPayload(
1293
+ record.old_public_key,
1294
+ record.new_public_key,
1295
+ record.timestamp,
1296
+ record.reason,
1297
+ record.recovery
1298
+ );
1299
+ const message = new TextEncoder().encode(payload);
1300
+ try {
1301
+ const newPubKey = hexToBytes2(record.new_public_key);
1302
+ const newSig = hexToBytes2(record.new_key_signature);
1303
+ const newValid = await ed25519Verify(newSig, message, newPubKey);
1304
+ if (!newValid) return false;
1305
+ if (record.recovery) {
1306
+ if (!record.guardian_signature || !guardianPublicKeyHex) return false;
1307
+ const guardianPubKey = hexToBytes2(guardianPublicKeyHex);
1308
+ const guardianSig = hexToBytes2(record.guardian_signature);
1309
+ return await ed25519Verify(guardianSig, message, guardianPubKey);
1310
+ } else {
1311
+ if (!record.old_key_signature) return false;
1312
+ const oldPubKey = hexToBytes2(record.old_public_key);
1313
+ const oldSig = hexToBytes2(record.old_key_signature);
1314
+ return await ed25519Verify(oldSig, message, oldPubKey);
1315
+ }
1316
+ } catch {
1317
+ return false;
1318
+ }
1319
+ }
1320
+ async function verifySuccessionChain(chain, guardianPublicKeyHex) {
1321
+ if (chain.length === 0) {
1322
+ return {
1323
+ valid: false,
1324
+ genesis_public_key: "",
1325
+ current_public_key: "",
1326
+ length: 0,
1327
+ error: { index: 0, message: "Empty succession chain" }
1328
+ };
1329
+ }
1330
+ const genesisKey = chain[0].old_public_key;
1331
+ const currentKey = chain[chain.length - 1].new_public_key;
1332
+ for (let i = 0; i < chain.length; i++) {
1333
+ const record = chain[i];
1334
+ if (record.recovery && !guardianPublicKeyHex) {
1335
+ return {
1336
+ valid: false,
1337
+ genesis_public_key: genesisKey,
1338
+ current_public_key: currentKey,
1339
+ length: chain.length,
1340
+ error: {
1341
+ index: i,
1342
+ message: `Record ${i} is a guardian recovery but no guardian public key provided`
1343
+ }
1344
+ };
1345
+ }
1346
+ const sigValid = await verifyKeySuccession(record, guardianPublicKeyHex);
1347
+ if (!sigValid) {
1348
+ return {
1349
+ valid: false,
1350
+ genesis_public_key: genesisKey,
1351
+ current_public_key: currentKey,
1352
+ length: chain.length,
1353
+ error: { index: i, message: `Record ${i} has invalid signature` }
1354
+ };
1355
+ }
1356
+ if (i < chain.length - 1) {
1357
+ const next = chain[i + 1];
1358
+ if (record.new_public_key !== next.old_public_key) {
1359
+ return {
1360
+ valid: false,
1361
+ genesis_public_key: genesisKey,
1362
+ current_public_key: currentKey,
1363
+ length: chain.length,
1364
+ error: {
1365
+ index: i + 1,
1366
+ message: `Chain break at ${i + 1}: expected old_public_key "${record.new_public_key}", got "${next.old_public_key}"`
1367
+ }
1368
+ };
1369
+ }
1370
+ }
1371
+ if (i < chain.length - 1) {
1372
+ const next = chain[i + 1];
1373
+ if (record.timestamp >= next.timestamp) {
1374
+ return {
1375
+ valid: false,
1376
+ genesis_public_key: genesisKey,
1377
+ current_public_key: currentKey,
1378
+ length: chain.length,
1379
+ error: {
1380
+ index: i + 1,
1381
+ message: `Temporal ordering violation at ${i + 1}: timestamp ${next.timestamp} is not after ${record.timestamp}`
1382
+ }
1383
+ };
1384
+ }
1385
+ }
1386
+ }
1387
+ return {
1388
+ valid: true,
1389
+ genesis_public_key: genesisKey,
1390
+ current_public_key: currentKey,
1391
+ length: chain.length
1392
+ };
1393
+ }
1394
+ async function signGuardianRevocation(identityPrivateKey, guardianPrivateKey, timestamp) {
1395
+ const ts = timestamp ?? Date.now();
1396
+ const payload = canonicalJson({ action: "guardian_revoked", timestamp: ts });
1397
+ const message = new TextEncoder().encode(payload);
1398
+ const identitySig = await ed25519Sign(message, identityPrivateKey);
1399
+ const guardianSig = await ed25519Sign(message, guardianPrivateKey);
1400
+ return {
1401
+ payload,
1402
+ identity_signature: bytesToHex2(identitySig),
1403
+ guardian_signature: bytesToHex2(guardianSig),
1404
+ timestamp: ts
1405
+ };
1406
+ }
1407
+ async function verifyGuardianRevocation(revocation, identityPublicKeyHex, guardianPublicKeyHex) {
1408
+ const payload = canonicalJson({ action: "guardian_revoked", timestamp: revocation.timestamp });
1409
+ const message = new TextEncoder().encode(payload);
1410
+ try {
1411
+ const identityPub = hexToBytes2(identityPublicKeyHex);
1412
+ const guardianPub = hexToBytes2(guardianPublicKeyHex);
1413
+ const identitySig = hexToBytes2(revocation.identity_signature);
1414
+ const guardianSig = hexToBytes2(revocation.guardian_signature);
1415
+ const identityValid = await ed25519Verify(identitySig, message, identityPub);
1416
+ const guardianValid = await ed25519Verify(guardianSig, message, guardianPub);
1417
+ return identityValid && guardianValid;
1418
+ } catch {
1419
+ return false;
1420
+ }
1421
+ }
1422
+ async function signCollaborativeReceipt(receipt, initiatorPrivateKey) {
1423
+ const receiptsCanonical = canonicalJson(receipt.participant_receipts);
1424
+ const receiptsBytes = new TextEncoder().encode(receiptsCanonical);
1425
+ const contentHash = await hash(receiptsBytes);
1426
+ const sigPayload = canonicalJson({
1427
+ proposal_id: receipt.proposal_id,
1428
+ plan_id: receipt.plan_id,
1429
+ content_hash: contentHash
1430
+ });
1431
+ const sigMessage = new TextEncoder().encode(sigPayload);
1432
+ const sig = await ed25519Sign(sigMessage, initiatorPrivateKey);
1433
+ return {
1434
+ ...receipt,
1435
+ content_hash: contentHash,
1436
+ initiator_signature: toBase64Url(sig)
1437
+ };
1438
+ }
1439
+ async function verifyCollaborativeReceipt(receipt, initiatorPublicKey, participantKeys) {
1440
+ const receiptsCanonical = canonicalJson(receipt.participant_receipts);
1441
+ const receiptsBytes = new TextEncoder().encode(receiptsCanonical);
1442
+ const expectedHash = await hash(receiptsBytes);
1443
+ if (expectedHash !== receipt.content_hash) {
1444
+ return { valid: false, error: "Content hash mismatch" };
1445
+ }
1446
+ const sigPayload = canonicalJson({
1447
+ proposal_id: receipt.proposal_id,
1448
+ plan_id: receipt.plan_id,
1449
+ content_hash: receipt.content_hash
1450
+ });
1451
+ const sigMessage = new TextEncoder().encode(sigPayload);
1452
+ try {
1453
+ const sig = fromBase64Url(receipt.initiator_signature);
1454
+ const sigValid = await ed25519Verify(sig, sigMessage, initiatorPublicKey);
1455
+ if (!sigValid) {
1456
+ return { valid: false, error: "Initiator signature invalid" };
1457
+ }
1458
+ } catch {
1459
+ return { valid: false, error: "Initiator signature decode failed" };
1460
+ }
1461
+ if (participantKeys) {
1462
+ for (let i = 0; i < receipt.participant_receipts.length; i++) {
1463
+ const pr = receipt.participant_receipts[i];
1464
+ const pubKey = participantKeys.get(pr.motebit_id);
1465
+ if (!pubKey) {
1466
+ return {
1467
+ valid: false,
1468
+ error: `Unknown participant key for receipt ${i} (${pr.motebit_id})`
1469
+ };
1470
+ }
1471
+ const prValid = await verifyExecutionReceipt(pr, pubKey);
1472
+ if (!prValid) {
1473
+ return {
1474
+ valid: false,
1475
+ error: `Participant receipt ${i} (${pr.motebit_id}) signature invalid`
1476
+ };
1477
+ }
1478
+ }
1479
+ }
1480
+ return { valid: true };
1481
+ }
1482
+
1483
+ // src/credentials.ts
1484
+ function buildVerificationMethod(publicKey) {
1485
+ const did = publicKeyToDidKey(publicKey);
1486
+ const fragment = did.slice("did:key:".length);
1487
+ return `${did}#${fragment}`;
1488
+ }
1489
+ async function signDataIntegrity(document, privateKey, publicKey, proofPurpose) {
1490
+ const verificationMethod = buildVerificationMethod(publicKey);
1491
+ const created = (/* @__PURE__ */ new Date()).toISOString();
1492
+ const proofOptions = {
1493
+ type: "DataIntegrityProof",
1494
+ cryptosuite: "eddsa-jcs-2022",
1495
+ created,
1496
+ verificationMethod,
1497
+ proofPurpose
1498
+ };
1499
+ const encoder = new TextEncoder();
1500
+ const proofHash = await sha256(encoder.encode(canonicalJson(proofOptions)));
1501
+ const { proof: _proof, ...docWithoutProof } = document;
1502
+ const docHash = await sha256(encoder.encode(canonicalJson(docWithoutProof)));
1503
+ const combined = new Uint8Array(proofHash.length + docHash.length);
1504
+ combined.set(proofHash);
1505
+ combined.set(docHash, proofHash.length);
1506
+ const signature = await ed25519Sign(combined, privateKey);
1507
+ const proofValue = "z" + base58btcEncode(signature);
1508
+ return { ...proofOptions, proofValue };
1509
+ }
1510
+ async function verifyDataIntegritySigning(document, proof) {
1511
+ if (proof.type !== "DataIntegrityProof" || proof.cryptosuite !== "eddsa-jcs-2022") {
1512
+ return false;
1513
+ }
1514
+ const did = proof.verificationMethod.split("#")[0];
1515
+ let publicKey;
1516
+ try {
1517
+ publicKey = didKeyToPublicKey(did);
1518
+ } catch {
1519
+ return false;
1520
+ }
1521
+ const { proofValue, ...proofOptions } = proof;
1522
+ const encoder = new TextEncoder();
1523
+ const proofHash = await sha256(encoder.encode(canonicalJson(proofOptions)));
1524
+ const { proof: _proof, ...docWithoutProof } = document;
1525
+ const docHash = await sha256(encoder.encode(canonicalJson(docWithoutProof)));
1526
+ const combined = new Uint8Array(proofHash.length + docHash.length);
1527
+ combined.set(proofHash);
1528
+ combined.set(docHash, proofHash.length);
1529
+ if (!proofValue.startsWith("z")) return false;
1530
+ let signature;
1531
+ try {
1532
+ signature = base58btcDecode(proofValue.slice(1));
1533
+ } catch {
1534
+ return false;
1535
+ }
1536
+ return ed25519Verify(signature, combined, publicKey);
1537
+ }
1538
+ async function signVerifiableCredential(unsignedVC, privateKey, publicKey) {
1539
+ const proof = await signDataIntegrity(
1540
+ unsignedVC,
1541
+ privateKey,
1542
+ publicKey,
1543
+ "assertionMethod"
1544
+ );
1545
+ return { ...unsignedVC, proof };
1546
+ }
1547
+ async function verifyVerifiableCredential(vc) {
1548
+ if (vc.validUntil) {
1549
+ const expiresAt = new Date(vc.validUntil).getTime();
1550
+ if (Date.now() > expiresAt) return false;
1551
+ }
1552
+ return verifyDataIntegritySigning(vc, vc.proof);
1553
+ }
1554
+ async function signVerifiablePresentation(unsignedVP, privateKey, publicKey) {
1555
+ const proof = await signDataIntegrity(
1556
+ unsignedVP,
1557
+ privateKey,
1558
+ publicKey,
1559
+ "authentication"
1560
+ );
1561
+ return { ...unsignedVP, proof };
1562
+ }
1563
+ async function verifyVerifiablePresentation(vp) {
1564
+ const errors = [];
1565
+ const vpValid = await verifyDataIntegritySigning(
1566
+ vp,
1567
+ vp.proof
1568
+ );
1569
+ if (!vpValid) {
1570
+ errors.push("Presentation proof is invalid");
1571
+ }
1572
+ for (let i = 0; i < vp.verifiableCredential.length; i++) {
1573
+ const vc = vp.verifiableCredential[i];
1574
+ const vcValid = await verifyVerifiableCredential(vc);
1575
+ if (!vcValid) {
1576
+ errors.push(`Credential ${i} proof is invalid`);
1577
+ }
1578
+ }
1579
+ return { valid: errors.length === 0, errors };
1580
+ }
1581
+ var VC_TYPE_GRADIENT = "AgentGradientCredential";
1582
+ var VC_TYPE_REPUTATION = "AgentReputationCredential";
1583
+ var VC_TYPE_TRUST = "AgentTrustCredential";
1584
+ var ONE_HOUR_MS = 60 * 60 * 1e3;
1585
+ async function issueGradientCredential(snapshot, privateKey, publicKey, subjectDid, validForMs = ONE_HOUR_MS, statusEndpoint) {
1586
+ const issuerDid = publicKeyToDidKey(publicKey);
1587
+ const subject = {
1588
+ id: subjectDid ?? issuerDid,
1589
+ gradient: snapshot.gradient,
1590
+ knowledge_density: snapshot.knowledge_density,
1591
+ knowledge_quality: snapshot.knowledge_quality,
1592
+ graph_connectivity: snapshot.graph_connectivity,
1593
+ temporal_stability: snapshot.temporal_stability,
1594
+ retrieval_quality: snapshot.retrieval_quality,
1595
+ interaction_efficiency: snapshot.interaction_efficiency,
1596
+ tool_efficiency: snapshot.tool_efficiency,
1597
+ curiosity_pressure: snapshot.curiosity_pressure,
1598
+ measured_at: snapshot.timestamp
1599
+ };
1600
+ const now = /* @__PURE__ */ new Date();
1601
+ const unsignedVC = {
1602
+ "@context": ["https://www.w3.org/ns/credentials/v2"],
1603
+ type: ["VerifiableCredential", VC_TYPE_GRADIENT],
1604
+ issuer: issuerDid,
1605
+ credentialSubject: subject,
1606
+ validFrom: now.toISOString(),
1607
+ validUntil: new Date(now.getTime() + validForMs).toISOString(),
1608
+ ...statusEndpoint ? { credentialStatus: { id: statusEndpoint, type: "RevocationList2024" } } : {}
1609
+ };
1610
+ return signVerifiableCredential(unsignedVC, privateKey, publicKey);
1611
+ }
1612
+ async function issueReputationCredential(snapshot, privateKey, publicKey, subjectDid, validForMs = ONE_HOUR_MS, statusEndpoint) {
1613
+ const issuerDid = publicKeyToDidKey(publicKey);
1614
+ const subject = {
1615
+ id: subjectDid,
1616
+ success_rate: snapshot.success_rate,
1617
+ avg_latency_ms: snapshot.avg_latency_ms,
1618
+ task_count: snapshot.task_count,
1619
+ trust_score: snapshot.trust_score,
1620
+ availability: snapshot.availability,
1621
+ sample_size: snapshot.task_count,
1622
+ measured_at: snapshot.measured_at
1623
+ };
1624
+ const now = /* @__PURE__ */ new Date();
1625
+ const unsignedVC = {
1626
+ "@context": ["https://www.w3.org/ns/credentials/v2"],
1627
+ type: ["VerifiableCredential", VC_TYPE_REPUTATION],
1628
+ issuer: issuerDid,
1629
+ credentialSubject: subject,
1630
+ validFrom: now.toISOString(),
1631
+ validUntil: new Date(now.getTime() + validForMs).toISOString(),
1632
+ ...statusEndpoint ? { credentialStatus: { id: statusEndpoint, type: "RevocationList2024" } } : {}
1633
+ };
1634
+ return signVerifiableCredential(unsignedVC, privateKey, publicKey);
1635
+ }
1636
+ async function issueTrustCredential(trustRecord, privateKey, publicKey, subjectDid, validForMs = ONE_HOUR_MS, statusEndpoint) {
1637
+ const issuerDid = publicKeyToDidKey(publicKey);
1638
+ const subject = {
1639
+ id: subjectDid,
1640
+ trust_level: trustRecord.trust_level,
1641
+ interaction_count: trustRecord.interaction_count,
1642
+ successful_tasks: trustRecord.successful_tasks ?? 0,
1643
+ failed_tasks: trustRecord.failed_tasks ?? 0,
1644
+ first_seen_at: trustRecord.first_seen_at,
1645
+ last_seen_at: trustRecord.last_seen_at
1646
+ };
1647
+ const now = /* @__PURE__ */ new Date();
1648
+ const unsignedVC = {
1649
+ "@context": ["https://www.w3.org/ns/credentials/v2"],
1650
+ type: ["VerifiableCredential", VC_TYPE_TRUST],
1651
+ issuer: issuerDid,
1652
+ credentialSubject: subject,
1653
+ validFrom: now.toISOString(),
1654
+ validUntil: new Date(now.getTime() + validForMs).toISOString(),
1655
+ ...statusEndpoint ? { credentialStatus: { id: statusEndpoint, type: "RevocationList2024" } } : {}
1656
+ };
1657
+ return signVerifiableCredential(unsignedVC, privateKey, publicKey);
1658
+ }
1659
+ async function createPresentation(credentials, privateKey, publicKey) {
1660
+ const holderDid = publicKeyToDidKey(publicKey);
1661
+ const unsignedVP = {
1662
+ "@context": ["https://www.w3.org/ns/credentials/v2"],
1663
+ type: ["VerifiablePresentation"],
1664
+ holder: holderDid,
1665
+ verifiableCredential: credentials
1666
+ };
1667
+ return signVerifiablePresentation(unsignedVP, privateKey, publicKey);
1668
+ }
1669
+
1670
+ // src/credential-anchor.ts
1671
+ function toHex(bytes) {
1672
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1673
+ }
1674
+ function fromHex(hex) {
1675
+ const bytes = new Uint8Array(hex.length / 2);
1676
+ for (let i = 0; i < hex.length; i += 2) {
1677
+ bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
1678
+ }
1679
+ return bytes;
1680
+ }
1681
+ function concat(a, b) {
1682
+ const out = new Uint8Array(a.length + b.length);
1683
+ out.set(a);
1684
+ out.set(b, a.length);
1685
+ return out;
1686
+ }
1687
+ async function computeCredentialLeaf(credential) {
1688
+ const canonical = canonicalJson(credential);
1689
+ const hash2 = await sha256(new TextEncoder().encode(canonical));
1690
+ return toHex(hash2);
1691
+ }
1692
+ async function verifyMerkleInclusion(leaf, index, siblings, layerSizes, expectedRoot) {
1693
+ let current = fromHex(leaf);
1694
+ let idx = index;
1695
+ let sibIdx = 0;
1696
+ for (const layerSize of layerSizes) {
1697
+ const siblingPos = idx % 2 === 0 ? idx + 1 : idx - 1;
1698
+ const hasSibling = siblingPos >= 0 && siblingPos < layerSize;
1699
+ if (hasSibling) {
1700
+ if (sibIdx >= siblings.length) return false;
1701
+ const siblingBytes = fromHex(siblings[sibIdx]);
1702
+ const combined = idx % 2 === 0 ? concat(current, siblingBytes) : concat(siblingBytes, current);
1703
+ current = await sha256(combined);
1704
+ sibIdx++;
1705
+ }
1706
+ idx = Math.floor(idx / 2);
1707
+ }
1708
+ return toHex(current) === expectedRoot;
1709
+ }
1710
+ async function verifyCredentialAnchor(credential, anchorProof, chainVerifier) {
1711
+ const errors = [];
1712
+ const computedHash = await computeCredentialLeaf(credential);
1713
+ const hashValid = computedHash === anchorProof.credential_hash;
1714
+ if (!hashValid) {
1715
+ errors.push(
1716
+ `Hash mismatch: computed ${computedHash.slice(0, 16)}\u2026, proof claims ${anchorProof.credential_hash.slice(0, 16)}\u2026`
1717
+ );
1718
+ }
1719
+ const merkleValid = await verifyMerkleInclusion(
1720
+ anchorProof.credential_hash,
1721
+ anchorProof.leaf_index,
1722
+ anchorProof.siblings,
1723
+ anchorProof.layer_sizes,
1724
+ anchorProof.merkle_root
1725
+ );
1726
+ if (!merkleValid) {
1727
+ errors.push("Merkle proof does not reconstruct to the claimed root");
1728
+ }
1729
+ const batchPayload = canonicalJson({
1730
+ batch_id: anchorProof.batch_id,
1731
+ merkle_root: anchorProof.merkle_root,
1732
+ leaf_count: anchorProof.leaf_count,
1733
+ first_issued_at: anchorProof.first_issued_at,
1734
+ last_issued_at: anchorProof.last_issued_at,
1735
+ relay_id: anchorProof.relay_id
1736
+ });
1737
+ const payloadBytes = new TextEncoder().encode(batchPayload);
1738
+ const signatureBytes = hexToBytes2(anchorProof.batch_signature);
1739
+ const publicKeyBytes = hexToBytes2(anchorProof.relay_public_key);
1740
+ let relaySignatureValid = false;
1741
+ try {
1742
+ relaySignatureValid = await ed25519Verify(signatureBytes, payloadBytes, publicKeyBytes);
1743
+ } catch {
1744
+ relaySignatureValid = false;
1745
+ }
1746
+ if (!relaySignatureValid) {
1747
+ errors.push("Relay batch signature verification failed");
1748
+ }
1749
+ let chainVerified = null;
1750
+ if (anchorProof.anchor && chainVerifier) {
1751
+ try {
1752
+ chainVerified = await chainVerifier({
1753
+ ...anchorProof.anchor,
1754
+ expected_root: anchorProof.merkle_root
1755
+ });
1756
+ if (!chainVerified) {
1757
+ errors.push("Onchain anchor verification failed");
1758
+ }
1759
+ } catch (err2) {
1760
+ chainVerified = false;
1761
+ errors.push(
1762
+ `Onchain verification error: ${err2 instanceof Error ? err2.message : String(err2)}`
1763
+ );
1764
+ }
1765
+ }
1766
+ const valid = hashValid && merkleValid && relaySignatureValid && (chainVerified === null || chainVerified);
1767
+ return {
1768
+ valid,
1769
+ steps: {
1770
+ hash_valid: hashValid,
1771
+ merkle_valid: merkleValid,
1772
+ relay_signature_valid: relaySignatureValid,
1773
+ chain_verified: chainVerified
1774
+ },
1775
+ errors
1776
+ };
1777
+ }
1778
+
1779
+ // src/index.ts
1780
+ if (!hashes.sha512) {
1781
+ hashes.sha512 = (msg) => sha512(msg);
1782
+ }
1783
+ function parseYamlValue(raw) {
1784
+ const trimmed = raw.trim();
1785
+ if (trimmed === "null") return null;
1786
+ if (trimmed === "true") return true;
1787
+ if (trimmed === "false") return false;
1788
+ if (trimmed === "[]") return [];
1789
+ if (trimmed === "{}") return {};
1790
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
1791
+ return JSON.parse(trimmed);
1792
+ }
1793
+ const num = Number(trimmed);
1794
+ if (trimmed !== "" && !isNaN(num) && isFinite(num)) return num;
1795
+ return trimmed;
1796
+ }
1797
+ function parseYaml(text) {
1798
+ const lines = text.split("\n");
1799
+ const root = {};
1800
+ const stack = [
1801
+ { obj: root, indent: -1 }
1802
+ ];
1803
+ let currentArray = null;
1804
+ let currentArrayIndent = -1;
1805
+ for (let i = 0; i < lines.length; i++) {
1806
+ const line = lines[i];
1807
+ if (line.trim() === "" || line.trim().startsWith("#")) continue;
1808
+ const lineIndent = line.length - line.trimStart().length;
1809
+ const trimmed = line.trimStart();
1810
+ if (trimmed.startsWith("- ")) {
1811
+ const itemContent = trimmed.slice(2);
1812
+ const colonIdx2 = itemContent.indexOf(": ");
1813
+ if (colonIdx2 !== -1) {
1814
+ const obj = {};
1815
+ const key = itemContent.slice(0, colonIdx2);
1816
+ const val = itemContent.slice(colonIdx2 + 2);
1817
+ obj[key] = parseYamlValue(val);
1818
+ for (let j = i + 1; j < lines.length; j++) {
1819
+ const nextLine = lines[j];
1820
+ if (nextLine.trim() === "") continue;
1821
+ const nextIndent = nextLine.length - nextLine.trimStart().length;
1822
+ const nextTrimmed = nextLine.trimStart();
1823
+ if (nextIndent > lineIndent && !nextTrimmed.startsWith("- ")) {
1824
+ const nextColonIdx = nextTrimmed.indexOf(": ");
1825
+ if (nextColonIdx !== -1) {
1826
+ const nk = nextTrimmed.slice(0, nextColonIdx);
1827
+ const nv = nextTrimmed.slice(nextColonIdx + 2);
1828
+ obj[nk] = parseYamlValue(nv);
1829
+ i = j;
1830
+ }
1831
+ } else {
1832
+ break;
1833
+ }
1834
+ }
1835
+ if (currentArray) currentArray.push(obj);
1836
+ } else {
1837
+ if (currentArray) currentArray.push(parseYamlValue(itemContent));
1838
+ }
1839
+ continue;
1840
+ }
1841
+ const colonIdx = trimmed.indexOf(": ");
1842
+ const endsWithColon = trimmed.endsWith(":") && colonIdx === -1;
1843
+ if (endsWithColon) {
1844
+ const key = trimmed.slice(0, -1);
1845
+ if (currentArray && lineIndent <= currentArrayIndent) {
1846
+ currentArray = null;
1847
+ currentArrayIndent = -1;
1848
+ }
1849
+ while (stack.length > 1 && stack[stack.length - 1].indent >= lineIndent) {
1850
+ stack.pop();
1851
+ }
1852
+ const parent = stack[stack.length - 1].obj;
1853
+ let nextIdx = i + 1;
1854
+ while (nextIdx < lines.length && lines[nextIdx].trim() === "") nextIdx++;
1855
+ if (nextIdx < lines.length && lines[nextIdx].trimStart().startsWith("- ")) {
1856
+ const arr = [];
1857
+ parent[key] = arr;
1858
+ currentArray = arr;
1859
+ currentArrayIndent = lineIndent;
1860
+ } else {
1861
+ const nested = {};
1862
+ parent[key] = nested;
1863
+ stack.push({ obj: nested, indent: lineIndent });
1864
+ }
1865
+ continue;
1866
+ }
1867
+ if (colonIdx !== -1) {
1868
+ if (currentArray && lineIndent <= currentArrayIndent) {
1869
+ currentArray = null;
1870
+ currentArrayIndent = -1;
1871
+ }
1872
+ while (stack.length > 1 && stack[stack.length - 1].indent >= lineIndent) {
1873
+ stack.pop();
1874
+ }
1875
+ const key = trimmed.slice(0, colonIdx);
1876
+ const val = trimmed.slice(colonIdx + 2);
1877
+ const parent = stack[stack.length - 1].obj;
1878
+ parent[key] = parseYamlValue(val);
1879
+ }
1880
+ }
1881
+ return root;
1882
+ }
1883
+ function hexToBytes3(hex) {
1884
+ const bytes = new Uint8Array(hex.length / 2);
1885
+ for (let i = 0; i < hex.length; i += 2) {
1886
+ bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
1887
+ }
1888
+ return bytes;
1889
+ }
1890
+ function fromBase64Url2(str) {
1891
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
1892
+ const pad = base64.length % 4;
1893
+ if (pad === 2) base64 += "==";
1894
+ else if (pad === 3) base64 += "=";
1895
+ const binary = atob(base64);
1896
+ const bytes = new Uint8Array(binary.length);
1897
+ for (let i = 0; i < binary.length; i++) {
1898
+ bytes[i] = binary.charCodeAt(i);
1899
+ }
1900
+ return bytes;
1901
+ }
1902
+ function canonicalJson2(obj) {
1903
+ if (obj === null || obj === void 0) return JSON.stringify(obj);
1904
+ if (typeof obj !== "object") return JSON.stringify(obj);
1905
+ if (Array.isArray(obj)) {
1906
+ return "[" + obj.map((item) => canonicalJson2(item)).join(",") + "]";
1907
+ }
1908
+ const sorted = Object.keys(obj).sort();
1909
+ const entries = [];
1910
+ for (const key of sorted) {
1911
+ const val = obj[key];
1912
+ if (val === void 0) continue;
1913
+ entries.push(JSON.stringify(key) + ":" + canonicalJson2(val));
1914
+ }
1915
+ return "{" + entries.join(",") + "}";
1916
+ }
1917
+ var BASE58_ALPHABET2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1918
+ function base58btcEncode2(bytes) {
1919
+ let zeros = 0;
1920
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
1921
+ let value = 0n;
1922
+ for (let i = 0; i < bytes.length; i++) {
1923
+ value = value * 256n + BigInt(bytes[i]);
1924
+ }
1925
+ let result = "";
1926
+ while (value > 0n) {
1927
+ const remainder = Number(value % 58n);
1928
+ value = value / 58n;
1929
+ result = BASE58_ALPHABET2[remainder] + result;
1930
+ }
1931
+ return BASE58_ALPHABET2[0].repeat(zeros) + result;
1932
+ }
1933
+ function base58btcDecode2(str) {
1934
+ let zeros = 0;
1935
+ while (zeros < str.length && str[zeros] === BASE58_ALPHABET2[0]) zeros++;
1936
+ let value = 0n;
1937
+ for (let i = 0; i < str.length; i++) {
1938
+ const idx = BASE58_ALPHABET2.indexOf(str[i]);
1939
+ if (idx === -1) throw new Error(`Invalid base58 character: ${str[i]}`);
1940
+ value = value * 58n + BigInt(idx);
1941
+ }
1942
+ const hex = [];
1943
+ while (value > 0n) {
1944
+ const byte = Number(value & 0xffn);
1945
+ hex.unshift(byte.toString(16).padStart(2, "0"));
1946
+ value >>= 8n;
1947
+ }
1948
+ const dataBytes = hex.length > 0 ? new Uint8Array(hex.map((h2) => parseInt(h2, 16))) : new Uint8Array(0);
1949
+ const result = new Uint8Array(zeros + dataBytes.length);
1950
+ result.set(dataBytes, zeros);
1951
+ return result;
1952
+ }
1953
+ function publicKeyToDidKey2(pubKey) {
1954
+ const prefixed = new Uint8Array(34);
1955
+ prefixed[0] = 237;
1956
+ prefixed[1] = 1;
1957
+ prefixed.set(pubKey, 2);
1958
+ return `did:key:z${base58btcEncode2(prefixed)}`;
1959
+ }
1960
+ function didKeyToPublicKey2(did) {
1961
+ if (!did.startsWith("did:key:z")) {
1962
+ throw new Error("Invalid did:key URI: must start with did:key:z");
1963
+ }
1964
+ const encoded = did.slice("did:key:z".length);
1965
+ const decoded = base58btcDecode2(encoded);
1966
+ if (decoded.length !== 34) {
1967
+ throw new Error(
1968
+ `Invalid did:key: expected 34 bytes (2 prefix + 32 key), got ${decoded.length}`
1969
+ );
1970
+ }
1971
+ if (decoded[0] !== 237 || decoded[1] !== 1) {
1972
+ throw new Error("Invalid did:key: multicodec prefix is not ed25519-pub (0xed01)");
1973
+ }
1974
+ return decoded.slice(2);
1975
+ }
1976
+ async function sha2562(data) {
1977
+ const buf = await crypto.subtle.digest("SHA-256", data);
1978
+ return new Uint8Array(buf);
1979
+ }
1980
+ var SIG_PREFIX = "<!-- motebit:sig:Ed25519:";
1981
+ var SIG_SUFFIX = " -->";
1982
+ function detectArtifactType(artifact) {
1983
+ if (typeof artifact === "string") {
1984
+ if (artifact.includes("---")) {
1985
+ return "identity";
1986
+ }
1987
+ try {
1988
+ const parsed = JSON.parse(artifact);
1989
+ return detectArtifactType(parsed);
1990
+ } catch {
1991
+ return null;
1992
+ }
1993
+ }
1994
+ if (typeof artifact !== "object" || artifact === null) return null;
1995
+ const obj = artifact;
1996
+ if ("holder" in obj && "verifiableCredential" in obj && "proof" in obj) {
1997
+ return "presentation";
1998
+ }
1999
+ if ("credentialSubject" in obj && "issuer" in obj && "proof" in obj) {
2000
+ return "credential";
2001
+ }
2002
+ if ("task_id" in obj && "motebit_id" in obj && "signature" in obj && "prompt_hash" in obj) {
2003
+ return "receipt";
2004
+ }
2005
+ return null;
2006
+ }
2007
+ function parse(content) {
2008
+ const firstDash = content.indexOf("---\n");
2009
+ if (firstDash === -1) throw new Error("Missing frontmatter opening ---");
2010
+ const bodyStart = firstDash + 4;
2011
+ const secondDash = content.indexOf("\n---", bodyStart);
2012
+ if (secondDash === -1) throw new Error("Missing frontmatter closing ---");
2013
+ const rawFrontmatter = content.slice(bodyStart, secondDash);
2014
+ const frontmatter = parseYaml(rawFrontmatter);
2015
+ const sigStart = content.indexOf(SIG_PREFIX);
2016
+ if (sigStart === -1) throw new Error("Missing signature");
2017
+ const sigValueStart = sigStart + SIG_PREFIX.length;
2018
+ const sigEnd = content.indexOf(SIG_SUFFIX, sigValueStart);
2019
+ if (sigEnd === -1) throw new Error("Malformed signature");
2020
+ const signature = content.slice(sigValueStart, sigEnd);
2021
+ return { frontmatter, signature, rawFrontmatter };
2022
+ }
2023
+ function identityError(msg) {
2024
+ return { type: "identity", valid: false, identity: null, error: msg, errors: [{ message: msg }] };
2025
+ }
2026
+ async function verifyIdentity(content) {
2027
+ let parsed;
2028
+ try {
2029
+ parsed = parse(content);
2030
+ } catch (err2) {
2031
+ const msg = err2 instanceof Error ? err2.message : String(err2);
2032
+ return identityError(msg);
2033
+ }
2034
+ const pubKeyHex = parsed.frontmatter.identity?.public_key;
2035
+ if (!pubKeyHex) {
2036
+ return identityError("No public key in frontmatter");
2037
+ }
2038
+ let pubKey;
2039
+ try {
2040
+ pubKey = hexToBytes3(pubKeyHex);
2041
+ } catch {
2042
+ return identityError("Invalid public key hex");
2043
+ }
2044
+ if (pubKey.length !== 32) {
2045
+ return identityError("Public key must be 32 bytes");
2046
+ }
2047
+ let sigBytes;
2048
+ try {
2049
+ sigBytes = fromBase64Url2(parsed.signature);
2050
+ } catch {
2051
+ return identityError("Invalid signature encoding");
2052
+ }
2053
+ if (sigBytes.length !== 64) {
2054
+ return identityError("Signature must be 64 bytes");
2055
+ }
2056
+ const frontmatterBytes = new TextEncoder().encode(parsed.rawFrontmatter);
2057
+ let valid;
2058
+ try {
2059
+ valid = await verifyAsync(sigBytes, frontmatterBytes, pubKey);
2060
+ } catch {
2061
+ valid = false;
2062
+ }
2063
+ if (!valid) {
2064
+ return identityError("Signature verification failed");
2065
+ }
2066
+ const guardian = parsed.frontmatter.guardian;
2067
+ if (guardian?.attestation && guardian.public_key) {
2068
+ const motebitId = parsed.frontmatter.motebit_id;
2069
+ const attestPayload = canonicalJson2({
2070
+ action: "guardian_attestation",
2071
+ guardian_public_key: guardian.public_key,
2072
+ motebit_id: motebitId
2073
+ });
2074
+ const attestMessage = new TextEncoder().encode(attestPayload);
2075
+ let guardianPubKey;
2076
+ try {
2077
+ guardianPubKey = hexToBytes3(guardian.public_key);
2078
+ } catch {
2079
+ return identityError("Invalid guardian public key hex");
2080
+ }
2081
+ if (guardianPubKey.length !== 32) {
2082
+ return identityError("Guardian public key must be 32 bytes");
2083
+ }
2084
+ let attestSig;
2085
+ try {
2086
+ attestSig = hexToBytes3(guardian.attestation);
2087
+ } catch {
2088
+ return identityError("Invalid guardian attestation encoding");
2089
+ }
2090
+ let attestValid;
2091
+ try {
2092
+ attestValid = await verifyAsync(attestSig, attestMessage, guardianPubKey);
2093
+ } catch {
2094
+ attestValid = false;
2095
+ }
2096
+ if (!attestValid) {
2097
+ return identityError("Guardian attestation signature verification failed");
2098
+ }
2099
+ }
2100
+ const chain = parsed.frontmatter.succession;
2101
+ let successionResult;
2102
+ if (chain && chain.length > 0) {
2103
+ const guardianPubKeyHex = parsed.frontmatter.guardian?.public_key;
2104
+ successionResult = await verifySuccessionChain2(chain, pubKeyHex, guardianPubKeyHex);
2105
+ }
2106
+ return {
2107
+ type: "identity",
2108
+ valid: true,
2109
+ identity: parsed.frontmatter,
2110
+ did: publicKeyToDidKey2(pubKey),
2111
+ ...successionResult ? { succession: successionResult } : {}
2112
+ };
2113
+ }
2114
+ async function verifySuccessionChain2(chain, currentPublicKeyHex, guardianPublicKeyHex) {
2115
+ try {
2116
+ for (let i = 0; i < chain.length; i++) {
2117
+ const record = chain[i];
2118
+ const payloadObj = {
2119
+ old_public_key: record.old_public_key,
2120
+ new_public_key: record.new_public_key,
2121
+ timestamp: record.timestamp
2122
+ };
2123
+ if (record.reason !== void 0) {
2124
+ payloadObj.reason = record.reason;
2125
+ }
2126
+ if (record.recovery) {
2127
+ payloadObj.recovery = true;
2128
+ }
2129
+ const payload = canonicalJson2(payloadObj);
2130
+ const message = new TextEncoder().encode(payload);
2131
+ const newPubKey = hexToBytes3(record.new_public_key);
2132
+ const newSig = hexToBytes3(record.new_key_signature);
2133
+ const newValid = await verifyAsync(newSig, message, newPubKey);
2134
+ if (!newValid) {
2135
+ return {
2136
+ valid: false,
2137
+ rotations: chain.length,
2138
+ error: `Succession record ${i}: new_key_signature verification failed`
2139
+ };
2140
+ }
2141
+ if (record.recovery) {
2142
+ if (!guardianPublicKeyHex) {
2143
+ return {
2144
+ valid: false,
2145
+ rotations: chain.length,
2146
+ error: `Succession record ${i}: guardian recovery but no guardian public key in identity`
2147
+ };
2148
+ }
2149
+ if (!record.guardian_signature) {
2150
+ return {
2151
+ valid: false,
2152
+ rotations: chain.length,
2153
+ error: `Succession record ${i}: guardian recovery but no guardian_signature`
2154
+ };
2155
+ }
2156
+ const guardianPubKey = hexToBytes3(guardianPublicKeyHex);
2157
+ const guardianSig = hexToBytes3(record.guardian_signature);
2158
+ const guardianValid = await verifyAsync(guardianSig, message, guardianPubKey);
2159
+ if (!guardianValid) {
2160
+ return {
2161
+ valid: false,
2162
+ rotations: chain.length,
2163
+ error: `Succession record ${i}: guardian_signature verification failed`
2164
+ };
2165
+ }
2166
+ } else {
2167
+ if (!record.old_key_signature) {
2168
+ return {
2169
+ valid: false,
2170
+ rotations: chain.length,
2171
+ error: `Succession record ${i}: normal rotation but no old_key_signature`
2172
+ };
2173
+ }
2174
+ const oldPubKey = hexToBytes3(record.old_public_key);
2175
+ const oldSig = hexToBytes3(record.old_key_signature);
2176
+ const oldValid = await verifyAsync(oldSig, message, oldPubKey);
2177
+ if (!oldValid) {
2178
+ return {
2179
+ valid: false,
2180
+ rotations: chain.length,
2181
+ error: `Succession record ${i}: old_key_signature verification failed`
2182
+ };
2183
+ }
2184
+ }
2185
+ if (i < chain.length - 1) {
2186
+ const next = chain[i + 1];
2187
+ if (record.new_public_key !== next.old_public_key) {
2188
+ return {
2189
+ valid: false,
2190
+ rotations: chain.length,
2191
+ error: `Succession chain broken at record ${i}: new_public_key does not match next record's old_public_key`
2192
+ };
2193
+ }
2194
+ }
2195
+ if (i < chain.length - 1) {
2196
+ const next = chain[i + 1];
2197
+ if (record.timestamp >= next.timestamp) {
2198
+ return {
2199
+ valid: false,
2200
+ rotations: chain.length,
2201
+ error: `Succession chain temporal ordering violated at record ${i}`
2202
+ };
2203
+ }
2204
+ }
2205
+ }
2206
+ const lastRecord = chain[chain.length - 1];
2207
+ if (lastRecord.new_public_key !== currentPublicKeyHex) {
2208
+ return {
2209
+ valid: false,
2210
+ rotations: chain.length,
2211
+ error: "Succession chain terminal: last new_public_key does not match identity public_key"
2212
+ };
2213
+ }
2214
+ return {
2215
+ valid: true,
2216
+ genesis_public_key: chain[0].old_public_key,
2217
+ rotations: chain.length
2218
+ };
2219
+ } catch (err2) {
2220
+ const msg = err2 instanceof Error ? err2.message : String(err2);
2221
+ return {
2222
+ valid: false,
2223
+ rotations: 0,
2224
+ error: `Succession verification error: ${msg}`
2225
+ };
2226
+ }
2227
+ }
2228
+ async function verifyReceiptSignature(receipt, publicKey) {
2229
+ const { signature, ...body } = receipt;
2230
+ if (!signature || signature.trim() === "") {
2231
+ return { valid: false, error: "Receipt signature is empty" };
2232
+ }
2233
+ let sig;
2234
+ try {
2235
+ sig = fromBase64Url2(signature);
2236
+ } catch {
2237
+ return { valid: false, error: "Receipt signature is not valid base64url" };
2238
+ }
2239
+ if (sig.length !== 64) {
2240
+ return { valid: false, error: `Receipt signature must be 64 bytes, got ${sig.length}` };
2241
+ }
2242
+ const canonical = canonicalJson2(body);
2243
+ const message = new TextEncoder().encode(canonical);
2244
+ try {
2245
+ const valid = await verifyAsync(sig, message, publicKey);
2246
+ return { valid };
2247
+ } catch {
2248
+ return { valid: false, error: "Ed25519 verification threw" };
2249
+ }
2250
+ }
2251
+ async function verifyReceipt(receipt) {
2252
+ let publicKey = null;
2253
+ let signerDid;
2254
+ if (receipt.public_key) {
2255
+ try {
2256
+ publicKey = hexToBytes3(receipt.public_key);
2257
+ if (publicKey.length === 32) {
2258
+ signerDid = publicKeyToDidKey2(publicKey);
2259
+ } else {
2260
+ publicKey = null;
2261
+ }
2262
+ } catch {
2263
+ publicKey = null;
2264
+ }
2265
+ }
2266
+ if (!publicKey) {
2267
+ const delegations2 = await verifyReceiptDelegations(receipt);
2268
+ return {
2269
+ type: "receipt",
2270
+ valid: false,
2271
+ receipt,
2272
+ errors: [{ message: "No embedded public_key \u2014 cannot verify without known keys" }],
2273
+ ...delegations2.length > 0 ? { delegations: delegations2 } : {}
2274
+ };
2275
+ }
2276
+ const sigResult = await verifyReceiptSignature(receipt, publicKey);
2277
+ const errors = [];
2278
+ if (!sigResult.valid) {
2279
+ errors.push({ message: sigResult.error ?? "Receipt signature verification failed" });
2280
+ }
2281
+ const delegations = await verifyReceiptDelegations(receipt);
2282
+ const delegationErrors = delegations.filter((d) => !d.valid);
2283
+ for (const d of delegationErrors) {
2284
+ errors.push({
2285
+ message: `Delegation ${d.receipt?.task_id ?? "unknown"}: verification failed`,
2286
+ path: `delegation_receipts`
2287
+ });
2288
+ }
2289
+ return {
2290
+ type: "receipt",
2291
+ valid: sigResult.valid && delegationErrors.length === 0,
2292
+ receipt,
2293
+ signer: signerDid,
2294
+ ...delegations.length > 0 ? { delegations } : {},
2295
+ ...errors.length > 0 ? { errors } : {}
2296
+ };
2297
+ }
2298
+ async function verifyReceiptDelegations(receipt) {
2299
+ if (!receipt.delegation_receipts || receipt.delegation_receipts.length === 0) {
2300
+ return [];
2301
+ }
2302
+ return Promise.all(receipt.delegation_receipts.map((dr) => verifyReceipt(dr)));
2303
+ }
2304
+ async function verifyDataIntegrity(document, proof) {
2305
+ if (proof.type !== "DataIntegrityProof" || proof.cryptosuite !== "eddsa-jcs-2022") {
2306
+ return false;
2307
+ }
2308
+ const did = proof.verificationMethod.split("#")[0];
2309
+ let publicKey;
2310
+ try {
2311
+ publicKey = didKeyToPublicKey2(did);
2312
+ } catch {
2313
+ return false;
2314
+ }
2315
+ const { proofValue, ...proofOptions } = proof;
2316
+ const encoder = new TextEncoder();
2317
+ const proofHash = await sha2562(encoder.encode(canonicalJson2(proofOptions)));
2318
+ const { proof: _proof, ...docWithoutProof } = document;
2319
+ const docHash = await sha2562(encoder.encode(canonicalJson2(docWithoutProof)));
2320
+ const combined = new Uint8Array(proofHash.length + docHash.length);
2321
+ combined.set(proofHash);
2322
+ combined.set(docHash, proofHash.length);
2323
+ if (!proofValue.startsWith("z")) return false;
2324
+ let signature;
2325
+ try {
2326
+ signature = base58btcDecode2(proofValue.slice(1));
2327
+ } catch {
2328
+ return false;
2329
+ }
2330
+ try {
2331
+ return await verifyAsync(signature, combined, publicKey);
2332
+ } catch {
2333
+ return false;
2334
+ }
2335
+ }
2336
+ var DEFAULT_CLOCK_SKEW_SECONDS = 60;
2337
+ async function verifyCredential(vc, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS) {
2338
+ const errors = [];
2339
+ let expired = false;
2340
+ if (vc.validUntil) {
2341
+ const expiresAt = new Date(vc.validUntil).getTime();
2342
+ const skewMs = clockSkewSeconds * 1e3;
2343
+ if (Date.now() > expiresAt + skewMs) {
2344
+ expired = true;
2345
+ errors.push({ message: "Credential has expired", path: "validUntil" });
2346
+ }
2347
+ }
2348
+ const proofValid = await verifyDataIntegrity(vc, vc.proof);
2349
+ if (!proofValid) {
2350
+ errors.push({ message: "Credential proof verification failed", path: "proof" });
2351
+ }
2352
+ const issuerDid = typeof vc.issuer === "string" ? vc.issuer : void 0;
2353
+ const subjectId = vc.credentialSubject?.id;
2354
+ return {
2355
+ type: "credential",
2356
+ valid: proofValid && !expired,
2357
+ credential: vc,
2358
+ issuer: issuerDid,
2359
+ subject: subjectId,
2360
+ expired,
2361
+ ...errors.length > 0 ? { errors } : {}
2362
+ };
2363
+ }
2364
+ async function verifyPresentation(vp, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS) {
2365
+ const errors = [];
2366
+ const envelopeValid = await verifyDataIntegrity(
2367
+ vp,
2368
+ vp.proof
2369
+ );
2370
+ if (!envelopeValid) {
2371
+ errors.push({ message: "Presentation proof verification failed", path: "proof" });
2372
+ }
2373
+ const credentialResults = [];
2374
+ for (let i = 0; i < vp.verifiableCredential.length; i++) {
2375
+ const vc = vp.verifiableCredential[i];
2376
+ const vcResult = await verifyCredential(vc, clockSkewSeconds);
2377
+ credentialResults.push(vcResult);
2378
+ if (!vcResult.valid) {
2379
+ errors.push({
2380
+ message: `Credential ${i} verification failed`,
2381
+ path: `verifiableCredential[${i}]`
2382
+ });
2383
+ }
2384
+ }
2385
+ const allValid = envelopeValid && credentialResults.every((c) => c.valid);
2386
+ return {
2387
+ type: "presentation",
2388
+ valid: allValid,
2389
+ presentation: vp,
2390
+ holder: vp.holder,
2391
+ credentials: credentialResults,
2392
+ ...errors.length > 0 ? { errors } : {}
2393
+ };
2394
+ }
2395
+ async function verify(artifact, options) {
2396
+ const detected = detectArtifactType(artifact);
2397
+ if (detected === null) {
2398
+ const fallbackType = options?.expectedType ?? "identity";
2399
+ return {
2400
+ type: fallbackType,
2401
+ valid: false,
2402
+ ...fallbackType === "identity" ? { identity: null } : {},
2403
+ ...fallbackType === "receipt" ? { receipt: null } : {},
2404
+ ...fallbackType === "credential" ? { credential: null } : {},
2405
+ ...fallbackType === "presentation" ? { presentation: null } : {},
2406
+ errors: [{ message: "Unrecognized artifact format" }]
2407
+ };
2408
+ }
2409
+ if (options?.expectedType && options.expectedType !== detected) {
2410
+ return {
2411
+ type: detected,
2412
+ valid: false,
2413
+ ...detected === "identity" ? { identity: null } : {},
2414
+ ...detected === "receipt" ? { receipt: null } : {},
2415
+ ...detected === "credential" ? { credential: null } : {},
2416
+ ...detected === "presentation" ? { presentation: null } : {},
2417
+ errors: [{ message: `Expected type "${options.expectedType}" but detected "${detected}"` }]
2418
+ };
2419
+ }
2420
+ let resolved = artifact;
2421
+ if (typeof artifact === "string" && detected !== "identity") {
2422
+ try {
2423
+ resolved = JSON.parse(artifact);
2424
+ } catch {
2425
+ return {
2426
+ type: detected,
2427
+ valid: false,
2428
+ ...detected === "receipt" ? { receipt: null } : {},
2429
+ ...detected === "credential" ? { credential: null } : {},
2430
+ ...detected === "presentation" ? { presentation: null } : {},
2431
+ errors: [{ message: "Failed to parse JSON" }]
2432
+ };
2433
+ }
2434
+ }
2435
+ switch (detected) {
2436
+ case "identity":
2437
+ return verifyIdentity(resolved);
2438
+ case "receipt":
2439
+ return verifyReceipt(resolved);
2440
+ case "credential":
2441
+ return verifyCredential(resolved, options?.clockSkewSeconds);
2442
+ case "presentation":
2443
+ return verifyPresentation(resolved, options?.clockSkewSeconds);
2444
+ }
2445
+ }
2446
+ async function verifyIdentityFile(content) {
2447
+ const result = await verifyIdentity(content);
2448
+ return {
2449
+ valid: result.valid,
2450
+ identity: result.identity,
2451
+ did: result.did,
2452
+ error: result.errors?.[0]?.message,
2453
+ succession: result.succession
2454
+ };
2455
+ }
2456
+ export {
2457
+ base58btcDecode,
2458
+ base58btcEncode,
2459
+ bytesToHex2 as bytesToHex,
2460
+ canonicalJson,
2461
+ computeCredentialLeaf,
2462
+ createPresentation,
2463
+ createSignedToken,
2464
+ didKeyToPublicKey,
2465
+ ed25519Sign,
2466
+ ed25519Verify,
2467
+ fromBase64Url,
2468
+ generateKeypair,
2469
+ hash,
2470
+ hexPublicKeyToDidKey,
2471
+ hexToBytes2 as hexToBytes,
2472
+ isScopeNarrowed,
2473
+ issueGradientCredential,
2474
+ issueReputationCredential,
2475
+ issueTrustCredential,
2476
+ parse,
2477
+ parseScopeSet,
2478
+ publicKeyToDidKey,
2479
+ sha256,
2480
+ signCollaborativeReceipt,
2481
+ signDelegation,
2482
+ signExecutionReceipt,
2483
+ signGuardianRecoverySuccession,
2484
+ signGuardianRevocation,
2485
+ signKeySuccession,
2486
+ signSovereignPaymentReceipt,
2487
+ signVerifiableCredential,
2488
+ signVerifiablePresentation,
2489
+ toBase64Url,
2490
+ verify,
2491
+ verifyCollaborativeReceipt,
2492
+ verifyCredentialAnchor,
2493
+ verifyDelegation,
2494
+ verifyDelegationChain,
2495
+ verifyExecutionReceipt,
2496
+ verifyGuardianRevocation,
2497
+ verifyIdentityFile,
2498
+ verifyKeySuccession,
2499
+ verifyReceiptChain,
2500
+ verifyReceiptSequence,
2501
+ verifySignedToken,
2502
+ verifySuccessionChain,
2503
+ verifyVerifiableCredential,
2504
+ verifyVerifiablePresentation
2505
+ };
2506
+ /*! Bundled license information:
2507
+
2508
+ @noble/ed25519/index.js:
2509
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
2510
+
2511
+ @noble/hashes/esm/utils.js:
2512
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2513
+ */