@certivu/cli 1.1.3 → 1.2.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.
Files changed (2) hide show
  1. package/dist/index.js +23 -1272
  2. package/package.json +23 -20
package/dist/index.js CHANGED
@@ -1,26 +1,4 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
22
- mod2
23
- ));
24
2
 
25
3
  // src/config.ts
26
4
  var import_node_fs = require("fs");
@@ -134,9 +112,9 @@ Usage: certivu config [get|set <key> <value>]`);
134
112
 
135
113
  // src/commands/sign.ts
136
114
  var import_node_fs2 = require("fs");
115
+ var import_node_path2 = require("path");
137
116
 
138
117
  // ../../packages/sdk/dist/index.js
139
- var nc = __toESM(require("crypto"));
140
118
  async function getAuditLog(baseUrl, apiKey, options = {}) {
141
119
  const page = options.page ?? 1;
142
120
  const limit = options.limit ?? 20;
@@ -149,1215 +127,6 @@ async function getAuditLog(baseUrl, apiKey, options = {}) {
149
127
  }
150
128
  return res.json();
151
129
  }
152
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
153
- var _32n = /* @__PURE__ */ BigInt(32);
154
- function fromBig(n, le = false) {
155
- if (le)
156
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
157
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
158
- }
159
- function split(lst, le = false) {
160
- const len = lst.length;
161
- let Ah = new Uint32Array(len);
162
- let Al = new Uint32Array(len);
163
- for (let i = 0; i < len; i++) {
164
- const { h, l } = fromBig(lst[i], le);
165
- [Ah[i], Al[i]] = [h, l];
166
- }
167
- return [Ah, Al];
168
- }
169
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
170
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
171
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
172
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
173
- function isBytes(a) {
174
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
175
- }
176
- function anumber(n) {
177
- if (!Number.isSafeInteger(n) || n < 0)
178
- throw new Error("positive integer expected, got " + n);
179
- }
180
- function abytes(b, ...lengths) {
181
- if (!isBytes(b))
182
- throw new Error("Uint8Array expected");
183
- if (lengths.length > 0 && !lengths.includes(b.length))
184
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
185
- }
186
- function aexists(instance, checkFinished = true) {
187
- if (instance.destroyed)
188
- throw new Error("Hash instance has been destroyed");
189
- if (checkFinished && instance.finished)
190
- throw new Error("Hash#digest() has already been called");
191
- }
192
- function aoutput(out, instance) {
193
- abytes(out);
194
- const min = instance.outputLen;
195
- if (out.length < min) {
196
- throw new Error("digestInto() expects output buffer of length at least " + min);
197
- }
198
- }
199
- function u32(arr) {
200
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
201
- }
202
- function clean(...arrays) {
203
- for (let i = 0; i < arrays.length; i++) {
204
- arrays[i].fill(0);
205
- }
206
- }
207
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
208
- function byteSwap(word) {
209
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
210
- }
211
- function byteSwap32(arr) {
212
- for (let i = 0; i < arr.length; i++) {
213
- arr[i] = byteSwap(arr[i]);
214
- }
215
- return arr;
216
- }
217
- var swap32IfBE = isLE ? (u) => u : byteSwap32;
218
- var hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
219
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
220
- function bytesToHex(bytes) {
221
- abytes(bytes);
222
- if (hasHexBuiltin)
223
- return bytes.toHex();
224
- let hex = "";
225
- for (let i = 0; i < bytes.length; i++) {
226
- hex += hexes[bytes[i]];
227
- }
228
- return hex;
229
- }
230
- function utf8ToBytes(str) {
231
- if (typeof str !== "string")
232
- throw new Error("string expected");
233
- return new Uint8Array(new TextEncoder().encode(str));
234
- }
235
- function toBytes(data) {
236
- if (typeof data === "string")
237
- data = utf8ToBytes(data);
238
- abytes(data);
239
- return data;
240
- }
241
- var Hash = class {
242
- };
243
- function createHasher(hashCons) {
244
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
245
- const tmp = hashCons();
246
- hashC.outputLen = tmp.outputLen;
247
- hashC.blockLen = tmp.blockLen;
248
- hashC.create = () => hashCons();
249
- return hashC;
250
- }
251
- var _0n = BigInt(0);
252
- var _1n = BigInt(1);
253
- var _2n = BigInt(2);
254
- var _7n = BigInt(7);
255
- var _256n = BigInt(256);
256
- var _0x71n = BigInt(113);
257
- var SHA3_PI = [];
258
- var SHA3_ROTL = [];
259
- var _SHA3_IOTA = [];
260
- for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
261
- [x, y] = [y, (2 * x + 3 * y) % 5];
262
- SHA3_PI.push(2 * (5 * y + x));
263
- SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
264
- let t = _0n;
265
- for (let j = 0; j < 7; j++) {
266
- R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
267
- if (R & _2n)
268
- t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
269
- }
270
- _SHA3_IOTA.push(t);
271
- }
272
- var IOTAS = split(_SHA3_IOTA, true);
273
- var SHA3_IOTA_H = IOTAS[0];
274
- var SHA3_IOTA_L = IOTAS[1];
275
- var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
276
- var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
277
- function keccakP(s, rounds = 24) {
278
- const B = new Uint32Array(5 * 2);
279
- for (let round = 24 - rounds; round < 24; round++) {
280
- for (let x = 0; x < 10; x++)
281
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
282
- for (let x = 0; x < 10; x += 2) {
283
- const idx1 = (x + 8) % 10;
284
- const idx0 = (x + 2) % 10;
285
- const B0 = B[idx0];
286
- const B1 = B[idx0 + 1];
287
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
288
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
289
- for (let y = 0; y < 50; y += 10) {
290
- s[x + y] ^= Th;
291
- s[x + y + 1] ^= Tl;
292
- }
293
- }
294
- let curH = s[2];
295
- let curL = s[3];
296
- for (let t = 0; t < 24; t++) {
297
- const shift = SHA3_ROTL[t];
298
- const Th = rotlH(curH, curL, shift);
299
- const Tl = rotlL(curH, curL, shift);
300
- const PI = SHA3_PI[t];
301
- curH = s[PI];
302
- curL = s[PI + 1];
303
- s[PI] = Th;
304
- s[PI + 1] = Tl;
305
- }
306
- for (let y = 0; y < 50; y += 10) {
307
- for (let x = 0; x < 10; x++)
308
- B[x] = s[y + x];
309
- for (let x = 0; x < 10; x++)
310
- s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
311
- }
312
- s[0] ^= SHA3_IOTA_H[round];
313
- s[1] ^= SHA3_IOTA_L[round];
314
- }
315
- clean(B);
316
- }
317
- var Keccak = class _Keccak extends Hash {
318
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
319
- super();
320
- this.pos = 0;
321
- this.posOut = 0;
322
- this.finished = false;
323
- this.destroyed = false;
324
- this.enableXOF = false;
325
- this.blockLen = blockLen;
326
- this.suffix = suffix;
327
- this.outputLen = outputLen;
328
- this.enableXOF = enableXOF;
329
- this.rounds = rounds;
330
- anumber(outputLen);
331
- if (!(0 < blockLen && blockLen < 200))
332
- throw new Error("only keccak-f1600 function is supported");
333
- this.state = new Uint8Array(200);
334
- this.state32 = u32(this.state);
335
- }
336
- clone() {
337
- return this._cloneInto();
338
- }
339
- keccak() {
340
- swap32IfBE(this.state32);
341
- keccakP(this.state32, this.rounds);
342
- swap32IfBE(this.state32);
343
- this.posOut = 0;
344
- this.pos = 0;
345
- }
346
- update(data) {
347
- aexists(this);
348
- data = toBytes(data);
349
- abytes(data);
350
- const { blockLen, state } = this;
351
- const len = data.length;
352
- for (let pos = 0; pos < len; ) {
353
- const take = Math.min(blockLen - this.pos, len - pos);
354
- for (let i = 0; i < take; i++)
355
- state[this.pos++] ^= data[pos++];
356
- if (this.pos === blockLen)
357
- this.keccak();
358
- }
359
- return this;
360
- }
361
- finish() {
362
- if (this.finished)
363
- return;
364
- this.finished = true;
365
- const { state, suffix, pos, blockLen } = this;
366
- state[pos] ^= suffix;
367
- if ((suffix & 128) !== 0 && pos === blockLen - 1)
368
- this.keccak();
369
- state[blockLen - 1] ^= 128;
370
- this.keccak();
371
- }
372
- writeInto(out) {
373
- aexists(this, false);
374
- abytes(out);
375
- this.finish();
376
- const bufferOut = this.state;
377
- const { blockLen } = this;
378
- for (let pos = 0, len = out.length; pos < len; ) {
379
- if (this.posOut >= blockLen)
380
- this.keccak();
381
- const take = Math.min(blockLen - this.posOut, len - pos);
382
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
383
- this.posOut += take;
384
- pos += take;
385
- }
386
- return out;
387
- }
388
- xofInto(out) {
389
- if (!this.enableXOF)
390
- throw new Error("XOF is not possible for this instance");
391
- return this.writeInto(out);
392
- }
393
- xof(bytes) {
394
- anumber(bytes);
395
- return this.xofInto(new Uint8Array(bytes));
396
- }
397
- digestInto(out) {
398
- aoutput(out, this);
399
- if (this.finished)
400
- throw new Error("digest() was already called");
401
- this.writeInto(out);
402
- this.destroy();
403
- return out;
404
- }
405
- digest() {
406
- return this.digestInto(new Uint8Array(this.outputLen));
407
- }
408
- destroy() {
409
- this.destroyed = true;
410
- clean(this.state);
411
- }
412
- _cloneInto(to) {
413
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
414
- to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
415
- to.state32.set(this.state32);
416
- to.pos = this.pos;
417
- to.posOut = this.posOut;
418
- to.finished = this.finished;
419
- to.rounds = rounds;
420
- to.suffix = suffix;
421
- to.outputLen = outputLen;
422
- to.enableXOF = enableXOF;
423
- to.destroyed = this.destroyed;
424
- return to;
425
- }
426
- };
427
- var gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
428
- var sha3_256 = /* @__PURE__ */ (() => gen(6, 136, 256 / 8))();
429
- function hash(content) {
430
- const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
431
- return `sha3-256:${bytesToHex(sha3_256(bytes))}`;
432
- }
433
- function canonicalJson(obj) {
434
- return JSON.stringify(obj, Object.keys(obj).sort());
435
- }
436
- function anumber2(n) {
437
- if (!Number.isSafeInteger(n) || n < 0)
438
- throw new Error("positive integer expected, got " + n);
439
- }
440
- function isBytes2(a) {
441
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
442
- }
443
- function abytes2(b, ...lengths) {
444
- if (!isBytes2(b))
445
- throw new Error("Uint8Array expected");
446
- if (lengths.length > 0 && !lengths.includes(b.length))
447
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
448
- }
449
- function aexists2(instance, checkFinished = true) {
450
- if (instance.destroyed)
451
- throw new Error("Hash instance has been destroyed");
452
- if (checkFinished && instance.finished)
453
- throw new Error("Hash#digest() has already been called");
454
- }
455
- function aoutput2(out, instance) {
456
- abytes2(out);
457
- const min = instance.outputLen;
458
- if (out.length < min) {
459
- throw new Error("digestInto() expects output buffer of length at least " + min);
460
- }
461
- }
462
- var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
463
- var _32n2 = /* @__PURE__ */ BigInt(32);
464
- function fromBig2(n, le = false) {
465
- if (le)
466
- return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) };
467
- return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 };
468
- }
469
- function split2(lst, le = false) {
470
- let Ah = new Uint32Array(lst.length);
471
- let Al = new Uint32Array(lst.length);
472
- for (let i = 0; i < lst.length; i++) {
473
- const { h, l } = fromBig2(lst[i], le);
474
- [Ah[i], Al[i]] = [h, l];
475
- }
476
- return [Ah, Al];
477
- }
478
- var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s;
479
- var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s;
480
- var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s;
481
- var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s;
482
- var crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
483
- var u322 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
484
- var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
485
- var byteSwap2 = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
486
- function byteSwap322(arr) {
487
- for (let i = 0; i < arr.length; i++) {
488
- arr[i] = byteSwap2(arr[i]);
489
- }
490
- }
491
- function utf8ToBytes2(str) {
492
- if (typeof str !== "string")
493
- throw new Error("utf8ToBytes expected string, got " + typeof str);
494
- return new Uint8Array(new TextEncoder().encode(str));
495
- }
496
- function toBytes2(data) {
497
- if (typeof data === "string")
498
- data = utf8ToBytes2(data);
499
- abytes2(data);
500
- return data;
501
- }
502
- function concatBytes(...arrays) {
503
- let sum = 0;
504
- for (let i = 0; i < arrays.length; i++) {
505
- const a = arrays[i];
506
- abytes2(a);
507
- sum += a.length;
508
- }
509
- const res = new Uint8Array(sum);
510
- for (let i = 0, pad = 0; i < arrays.length; i++) {
511
- const a = arrays[i];
512
- res.set(a, pad);
513
- pad += a.length;
514
- }
515
- return res;
516
- }
517
- var Hash2 = class {
518
- clone() {
519
- return this._cloneInto();
520
- }
521
- };
522
- function wrapConstructor(hashCons) {
523
- const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
524
- const tmp = hashCons();
525
- hashC.outputLen = tmp.outputLen;
526
- hashC.blockLen = tmp.blockLen;
527
- hashC.create = () => hashCons();
528
- return hashC;
529
- }
530
- function wrapXOFConstructorWithOpts(hashCons) {
531
- const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest();
532
- const tmp = hashCons({});
533
- hashC.outputLen = tmp.outputLen;
534
- hashC.blockLen = tmp.blockLen;
535
- hashC.create = (opts) => hashCons(opts);
536
- return hashC;
537
- }
538
- function randomBytes(bytesLength = 32) {
539
- if (crypto2 && typeof crypto2.getRandomValues === "function") {
540
- return crypto2.getRandomValues(new Uint8Array(bytesLength));
541
- }
542
- if (crypto2 && typeof crypto2.randomBytes === "function") {
543
- return crypto2.randomBytes(bytesLength);
544
- }
545
- throw new Error("crypto.getRandomValues must be defined");
546
- }
547
- var SHA3_PI2 = [];
548
- var SHA3_ROTL2 = [];
549
- var _SHA3_IOTA2 = [];
550
- var _0n2 = /* @__PURE__ */ BigInt(0);
551
- var _1n2 = /* @__PURE__ */ BigInt(1);
552
- var _2n2 = /* @__PURE__ */ BigInt(2);
553
- var _7n2 = /* @__PURE__ */ BigInt(7);
554
- var _256n2 = /* @__PURE__ */ BigInt(256);
555
- var _0x71n2 = /* @__PURE__ */ BigInt(113);
556
- for (let round = 0, R = _1n2, x = 1, y = 0; round < 24; round++) {
557
- [x, y] = [y, (2 * x + 3 * y) % 5];
558
- SHA3_PI2.push(2 * (5 * y + x));
559
- SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64);
560
- let t = _0n2;
561
- for (let j = 0; j < 7; j++) {
562
- R = (R << _1n2 ^ (R >> _7n2) * _0x71n2) % _256n2;
563
- if (R & _2n2)
564
- t ^= _1n2 << (_1n2 << /* @__PURE__ */ BigInt(j)) - _1n2;
565
- }
566
- _SHA3_IOTA2.push(t);
567
- }
568
- var [SHA3_IOTA_H2, SHA3_IOTA_L2] = /* @__PURE__ */ split2(_SHA3_IOTA2, true);
569
- var rotlH2 = (h, l, s) => s > 32 ? rotlBH2(h, l, s) : rotlSH2(h, l, s);
570
- var rotlL2 = (h, l, s) => s > 32 ? rotlBL2(h, l, s) : rotlSL2(h, l, s);
571
- function keccakP2(s, rounds = 24) {
572
- const B = new Uint32Array(5 * 2);
573
- for (let round = 24 - rounds; round < 24; round++) {
574
- for (let x = 0; x < 10; x++)
575
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
576
- for (let x = 0; x < 10; x += 2) {
577
- const idx1 = (x + 8) % 10;
578
- const idx0 = (x + 2) % 10;
579
- const B0 = B[idx0];
580
- const B1 = B[idx0 + 1];
581
- const Th = rotlH2(B0, B1, 1) ^ B[idx1];
582
- const Tl = rotlL2(B0, B1, 1) ^ B[idx1 + 1];
583
- for (let y = 0; y < 50; y += 10) {
584
- s[x + y] ^= Th;
585
- s[x + y + 1] ^= Tl;
586
- }
587
- }
588
- let curH = s[2];
589
- let curL = s[3];
590
- for (let t = 0; t < 24; t++) {
591
- const shift = SHA3_ROTL2[t];
592
- const Th = rotlH2(curH, curL, shift);
593
- const Tl = rotlL2(curH, curL, shift);
594
- const PI = SHA3_PI2[t];
595
- curH = s[PI];
596
- curL = s[PI + 1];
597
- s[PI] = Th;
598
- s[PI + 1] = Tl;
599
- }
600
- for (let y = 0; y < 50; y += 10) {
601
- for (let x = 0; x < 10; x++)
602
- B[x] = s[y + x];
603
- for (let x = 0; x < 10; x++)
604
- s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
605
- }
606
- s[0] ^= SHA3_IOTA_H2[round];
607
- s[1] ^= SHA3_IOTA_L2[round];
608
- }
609
- B.fill(0);
610
- }
611
- var Keccak2 = class _Keccak2 extends Hash2 {
612
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
613
- super();
614
- this.blockLen = blockLen;
615
- this.suffix = suffix;
616
- this.outputLen = outputLen;
617
- this.enableXOF = enableXOF;
618
- this.rounds = rounds;
619
- this.pos = 0;
620
- this.posOut = 0;
621
- this.finished = false;
622
- this.destroyed = false;
623
- anumber2(outputLen);
624
- if (0 >= this.blockLen || this.blockLen >= 200)
625
- throw new Error("Sha3 supports only keccak-f1600 function");
626
- this.state = new Uint8Array(200);
627
- this.state32 = u322(this.state);
628
- }
629
- keccak() {
630
- if (!isLE2)
631
- byteSwap322(this.state32);
632
- keccakP2(this.state32, this.rounds);
633
- if (!isLE2)
634
- byteSwap322(this.state32);
635
- this.posOut = 0;
636
- this.pos = 0;
637
- }
638
- update(data) {
639
- aexists2(this);
640
- const { blockLen, state } = this;
641
- data = toBytes2(data);
642
- const len = data.length;
643
- for (let pos = 0; pos < len; ) {
644
- const take = Math.min(blockLen - this.pos, len - pos);
645
- for (let i = 0; i < take; i++)
646
- state[this.pos++] ^= data[pos++];
647
- if (this.pos === blockLen)
648
- this.keccak();
649
- }
650
- return this;
651
- }
652
- finish() {
653
- if (this.finished)
654
- return;
655
- this.finished = true;
656
- const { state, suffix, pos, blockLen } = this;
657
- state[pos] ^= suffix;
658
- if ((suffix & 128) !== 0 && pos === blockLen - 1)
659
- this.keccak();
660
- state[blockLen - 1] ^= 128;
661
- this.keccak();
662
- }
663
- writeInto(out) {
664
- aexists2(this, false);
665
- abytes2(out);
666
- this.finish();
667
- const bufferOut = this.state;
668
- const { blockLen } = this;
669
- for (let pos = 0, len = out.length; pos < len; ) {
670
- if (this.posOut >= blockLen)
671
- this.keccak();
672
- const take = Math.min(blockLen - this.posOut, len - pos);
673
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
674
- this.posOut += take;
675
- pos += take;
676
- }
677
- return out;
678
- }
679
- xofInto(out) {
680
- if (!this.enableXOF)
681
- throw new Error("XOF is not possible for this instance");
682
- return this.writeInto(out);
683
- }
684
- xof(bytes) {
685
- anumber2(bytes);
686
- return this.xofInto(new Uint8Array(bytes));
687
- }
688
- digestInto(out) {
689
- aoutput2(out, this);
690
- if (this.finished)
691
- throw new Error("digest() was already called");
692
- this.writeInto(out);
693
- this.destroy();
694
- return out;
695
- }
696
- digest() {
697
- return this.digestInto(new Uint8Array(this.outputLen));
698
- }
699
- destroy() {
700
- this.destroyed = true;
701
- this.state.fill(0);
702
- }
703
- _cloneInto(to) {
704
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
705
- to || (to = new _Keccak2(blockLen, suffix, outputLen, enableXOF, rounds));
706
- to.state32.set(this.state32);
707
- to.pos = this.pos;
708
- to.posOut = this.posOut;
709
- to.finished = this.finished;
710
- to.rounds = rounds;
711
- to.suffix = suffix;
712
- to.outputLen = outputLen;
713
- to.enableXOF = enableXOF;
714
- to.destroyed = this.destroyed;
715
- return to;
716
- }
717
- };
718
- var gen2 = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak2(blockLen, suffix, outputLen));
719
- var sha3_224 = /* @__PURE__ */ gen2(6, 144, 224 / 8);
720
- var sha3_2562 = /* @__PURE__ */ gen2(6, 136, 256 / 8);
721
- var sha3_384 = /* @__PURE__ */ gen2(6, 104, 384 / 8);
722
- var sha3_512 = /* @__PURE__ */ gen2(6, 72, 512 / 8);
723
- var keccak_224 = /* @__PURE__ */ gen2(1, 144, 224 / 8);
724
- var keccak_256 = /* @__PURE__ */ gen2(1, 136, 256 / 8);
725
- var keccak_384 = /* @__PURE__ */ gen2(1, 104, 384 / 8);
726
- var keccak_512 = /* @__PURE__ */ gen2(1, 72, 512 / 8);
727
- var genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak2(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true));
728
- var shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8);
729
- var shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8);
730
- var ensureBytes = abytes2;
731
- var randomBytes2 = randomBytes;
732
- function equalBytes(a, b) {
733
- if (a.length !== b.length)
734
- return false;
735
- let diff = 0;
736
- for (let i = 0; i < a.length; i++)
737
- diff |= a[i] ^ b[i];
738
- return diff === 0;
739
- }
740
- function splitCoder(...lengths) {
741
- const getLength = (c2) => typeof c2 === "number" ? c2 : c2.bytesLen;
742
- const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
743
- return {
744
- bytesLen,
745
- encode: (bufs) => {
746
- const res = new Uint8Array(bytesLen);
747
- for (let i = 0, pos = 0; i < lengths.length; i++) {
748
- const c2 = lengths[i];
749
- const l = getLength(c2);
750
- const b = typeof c2 === "number" ? bufs[i] : c2.encode(bufs[i]);
751
- ensureBytes(b, l);
752
- res.set(b, pos);
753
- if (typeof c2 !== "number")
754
- b.fill(0);
755
- pos += l;
756
- }
757
- return res;
758
- },
759
- decode: (buf) => {
760
- ensureBytes(buf, bytesLen);
761
- const res = [];
762
- for (const c2 of lengths) {
763
- const l = getLength(c2);
764
- const b = buf.subarray(0, l);
765
- res.push(typeof c2 === "number" ? b : c2.decode(b));
766
- buf = buf.subarray(l);
767
- }
768
- return res;
769
- }
770
- };
771
- }
772
- function vecCoder(c2, vecLen) {
773
- const bytesLen = vecLen * c2.bytesLen;
774
- return {
775
- bytesLen,
776
- encode: (u) => {
777
- if (u.length !== vecLen)
778
- throw new Error(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
779
- const res = new Uint8Array(bytesLen);
780
- for (let i = 0, pos = 0; i < u.length; i++) {
781
- const b = c2.encode(u[i]);
782
- res.set(b, pos);
783
- b.fill(0);
784
- pos += b.length;
785
- }
786
- return res;
787
- },
788
- decode: (a) => {
789
- ensureBytes(a, bytesLen);
790
- const r = [];
791
- for (let i = 0; i < a.length; i += c2.bytesLen)
792
- r.push(c2.decode(a.subarray(i, i + c2.bytesLen)));
793
- return r;
794
- }
795
- };
796
- }
797
- function cleanBytes(...list) {
798
- for (const t of list) {
799
- if (Array.isArray(t))
800
- for (const b of t)
801
- b.fill(0);
802
- else
803
- t.fill(0);
804
- }
805
- }
806
- function getMask(bits) {
807
- return (1 << bits) - 1;
808
- }
809
- function bitReversal(n, bits = 8) {
810
- const padded = n.toString(2).padStart(8, "0");
811
- const sliced = padded.slice(-bits).padStart(7, "0");
812
- const revrsd = sliced.split("").reverse().join("");
813
- return Number.parseInt(revrsd, 2);
814
- }
815
- var genCrystals = (opts) => {
816
- const { newPoly: newPoly2, N: N2, Q: Q2, F: F2, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits, isKyber } = opts;
817
- const mod2 = (a, modulo = Q2) => {
818
- const result = a % modulo | 0;
819
- return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
820
- };
821
- const smod2 = (a, modulo = Q2) => {
822
- const r = mod2(a, modulo) | 0;
823
- return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
824
- };
825
- function getZettas() {
826
- const out = newPoly2(N2);
827
- for (let i = 0; i < N2; i++) {
828
- const b = bitReversal(i, brvBits);
829
- const p = BigInt(ROOT_OF_UNITY2) ** BigInt(b) % BigInt(Q2);
830
- out[i] = Number(p) | 0;
831
- }
832
- return out;
833
- }
834
- const nttZetas = getZettas();
835
- const LEN1 = isKyber ? 128 : N2;
836
- const LEN2 = isKyber ? 1 : 0;
837
- const NTT2 = {
838
- encode: (r) => {
839
- for (let k = 1, len = 128; len > LEN2; len >>= 1) {
840
- for (let start = 0; start < N2; start += 2 * len) {
841
- const zeta = nttZetas[k++];
842
- for (let j = start; j < start + len; j++) {
843
- const t = mod2(zeta * r[j + len]);
844
- r[j + len] = mod2(r[j] - t) | 0;
845
- r[j] = mod2(r[j] + t) | 0;
846
- }
847
- }
848
- }
849
- return r;
850
- },
851
- decode: (r) => {
852
- for (let k = LEN1 - 1, len = 1 + LEN2; len < LEN1 + LEN2; len <<= 1) {
853
- for (let start = 0; start < N2; start += 2 * len) {
854
- const zeta = nttZetas[k--];
855
- for (let j = start; j < start + len; j++) {
856
- const t = r[j];
857
- r[j] = mod2(t + r[j + len]);
858
- r[j + len] = mod2(zeta * (r[j + len] - t));
859
- }
860
- }
861
- }
862
- for (let i = 0; i < r.length; i++)
863
- r[i] = mod2(F2 * r[i]);
864
- return r;
865
- }
866
- };
867
- const bitsCoder2 = (d, c2) => {
868
- const mask = getMask(d);
869
- const bytesLen = d * (N2 / 8);
870
- return {
871
- bytesLen,
872
- encode: (poly) => {
873
- const r = new Uint8Array(bytesLen);
874
- for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
875
- buf |= (c2.encode(poly[i]) & mask) << bufLen;
876
- bufLen += d;
877
- for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
878
- r[pos++] = buf & getMask(bufLen);
879
- }
880
- return r;
881
- },
882
- decode: (bytes) => {
883
- const r = newPoly2(N2);
884
- for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
885
- buf |= bytes[i] << bufLen;
886
- bufLen += 8;
887
- for (; bufLen >= d; bufLen -= d, buf >>= d)
888
- r[pos++] = c2.decode(buf & mask);
889
- }
890
- return r;
891
- }
892
- };
893
- };
894
- return { mod: mod2, smod: smod2, nttZetas, NTT: NTT2, bitsCoder: bitsCoder2 };
895
- };
896
- var createXofShake = (shake) => (seed, blockLen) => {
897
- if (!blockLen)
898
- blockLen = shake.blockLen;
899
- const _seed = new Uint8Array(seed.length + 2);
900
- _seed.set(seed);
901
- const seedLen = seed.length;
902
- const buf = new Uint8Array(blockLen);
903
- let h = shake.create({});
904
- let calls = 0;
905
- let xofs = 0;
906
- return {
907
- stats: () => ({ calls, xofs }),
908
- get: (x, y) => {
909
- _seed[seedLen + 0] = x;
910
- _seed[seedLen + 1] = y;
911
- h.destroy();
912
- h = shake.create({}).update(_seed);
913
- calls++;
914
- return () => {
915
- xofs++;
916
- return h.xofInto(buf);
917
- };
918
- },
919
- clean: () => {
920
- h.destroy();
921
- buf.fill(0);
922
- _seed.fill(0);
923
- }
924
- };
925
- };
926
- var XOF128 = /* @__PURE__ */ createXofShake(shake128);
927
- var XOF256 = /* @__PURE__ */ createXofShake(shake256);
928
- var N = 256;
929
- var Q = 8380417;
930
- var ROOT_OF_UNITY = 1753;
931
- var F = 8347681;
932
- var D = 13;
933
- var GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;
934
- var GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;
935
- var PARAMS = {
936
- 2: { K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80 },
937
- 3: { K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55 },
938
- 5: { K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75 }
939
- };
940
- var newPoly = (n) => new Int32Array(n);
941
- var { mod, smod, NTT, bitsCoder } = genCrystals({
942
- N,
943
- Q,
944
- F,
945
- ROOT_OF_UNITY,
946
- newPoly,
947
- isKyber: false,
948
- brvBits: 8
949
- });
950
- var id = (n) => n;
951
- var polyCoder = (d, compress = id, verify = id) => bitsCoder(d, {
952
- encode: (i) => compress(verify(i)),
953
- decode: (i) => verify(compress(i))
954
- });
955
- var polyAdd = (a, b) => {
956
- for (let i = 0; i < a.length; i++)
957
- a[i] = mod(a[i] + b[i]);
958
- return a;
959
- };
960
- var polySub = (a, b) => {
961
- for (let i = 0; i < a.length; i++)
962
- a[i] = mod(a[i] - b[i]);
963
- return a;
964
- };
965
- var polyShiftl = (p) => {
966
- for (let i = 0; i < N; i++)
967
- p[i] <<= D;
968
- return p;
969
- };
970
- var polyChknorm = (p, B) => {
971
- for (let i = 0; i < N; i++)
972
- if (Math.abs(smod(p[i])) >= B)
973
- return true;
974
- return false;
975
- };
976
- var MultiplyNTTs = (a, b) => {
977
- const c2 = newPoly(N);
978
- for (let i = 0; i < a.length; i++)
979
- c2[i] = mod(a[i] * b[i]);
980
- return c2;
981
- };
982
- function RejNTTPoly(xof) {
983
- const r = newPoly(N);
984
- for (let j = 0; j < N; ) {
985
- const b = xof();
986
- if (b.length % 3)
987
- throw new Error("RejNTTPoly: unaligned block");
988
- for (let i = 0; j < N && i <= b.length - 3; i += 3) {
989
- const t = (b[i + 0] | b[i + 1] << 8 | b[i + 2] << 16) & 8388607;
990
- if (t < Q)
991
- r[j++] = t;
992
- }
993
- }
994
- return r;
995
- }
996
- var EMPTY = new Uint8Array(0);
997
- function getDilithium(opts) {
998
- const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;
999
- const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128: XOF1282, XOF256: XOF2562 } = opts;
1000
- if (![2, 4].includes(ETA))
1001
- throw new Error("Wrong ETA");
1002
- if (![1 << 17, 1 << 19].includes(GAMMA1))
1003
- throw new Error("Wrong GAMMA1");
1004
- if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))
1005
- throw new Error("Wrong GAMMA2");
1006
- const BETA = TAU * ETA;
1007
- const decompose = (r) => {
1008
- const rPlus = mod(r);
1009
- const r0 = smod(rPlus, 2 * GAMMA2) | 0;
1010
- if (rPlus - r0 === Q - 1)
1011
- return { r1: 0 | 0, r0: r0 - 1 | 0 };
1012
- const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;
1013
- return { r1, r0 };
1014
- };
1015
- const HighBits = (r) => decompose(r).r1;
1016
- const LowBits = (r) => decompose(r).r0;
1017
- const MakeHint = (z, r) => {
1018
- const res0 = z <= GAMMA2 || z > Q - GAMMA2 || z === Q - GAMMA2 && r === 0 ? 0 : 1;
1019
- return res0;
1020
- };
1021
- const UseHint = (h, r) => {
1022
- const m = Math.floor((Q - 1) / (2 * GAMMA2));
1023
- const { r1, r0 } = decompose(r);
1024
- if (h === 1)
1025
- return r0 > 0 ? mod(r1 + 1, m) | 0 : mod(r1 - 1, m) | 0;
1026
- return r1 | 0;
1027
- };
1028
- const Power2Round = (r) => {
1029
- const rPlus = mod(r);
1030
- const r0 = smod(rPlus, 2 ** D) | 0;
1031
- return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };
1032
- };
1033
- const hintCoder = {
1034
- bytesLen: OMEGA + K,
1035
- encode: (h) => {
1036
- if (h === false)
1037
- throw new Error("hint.encode: hint is false");
1038
- const res = new Uint8Array(OMEGA + K);
1039
- for (let i = 0, k = 0; i < K; i++) {
1040
- for (let j = 0; j < N; j++)
1041
- if (h[i][j] !== 0)
1042
- res[k++] = j;
1043
- res[OMEGA + i] = k;
1044
- }
1045
- return res;
1046
- },
1047
- decode: (buf) => {
1048
- const h = [];
1049
- let k = 0;
1050
- for (let i = 0; i < K; i++) {
1051
- const hi = newPoly(N);
1052
- if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)
1053
- return false;
1054
- for (let j = k; j < buf[OMEGA + i]; j++) {
1055
- if (j > k && buf[j] <= buf[j - 1])
1056
- return false;
1057
- hi[buf[j]] = 1;
1058
- }
1059
- k = buf[OMEGA + i];
1060
- h.push(hi);
1061
- }
1062
- for (let j = k; j < OMEGA; j++)
1063
- if (buf[j] !== 0)
1064
- return false;
1065
- return h;
1066
- }
1067
- };
1068
- const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {
1069
- if (!(-ETA <= i && i <= ETA))
1070
- throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);
1071
- return i;
1072
- });
1073
- const T0Coder = polyCoder(13, (i) => (1 << D - 1) - i);
1074
- const T1Coder = polyCoder(10);
1075
- const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => smod(GAMMA1 - i));
1076
- const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);
1077
- const W1Vec = vecCoder(W1Coder, K);
1078
- const publicCoder = splitCoder(32, vecCoder(T1Coder, K));
1079
- const secretCoder = splitCoder(32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));
1080
- const sigCoder = splitCoder(C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);
1081
- const CoefFromHalfByte = ETA === 2 ? (n) => n < 15 ? 2 - n % 5 : false : (n) => n < 9 ? 4 - n : false;
1082
- function RejBoundedPoly(xof) {
1083
- const r = newPoly(N);
1084
- for (let j = 0; j < N; ) {
1085
- const b = xof();
1086
- for (let i = 0; j < N && i < b.length; i += 1) {
1087
- const d1 = CoefFromHalfByte(b[i] & 15);
1088
- const d2 = CoefFromHalfByte(b[i] >> 4 & 15);
1089
- if (d1 !== false)
1090
- r[j++] = d1;
1091
- if (j < N && d2 !== false)
1092
- r[j++] = d2;
1093
- }
1094
- }
1095
- return r;
1096
- }
1097
- const SampleInBall = (seed) => {
1098
- const pre = newPoly(N);
1099
- const s = shake256.create({}).update(seed);
1100
- const buf = new Uint8Array(shake256.blockLen);
1101
- s.xofInto(buf);
1102
- const masks = buf.slice(0, 8);
1103
- for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {
1104
- let b = i + 1;
1105
- for (; b > i; ) {
1106
- b = buf[pos++];
1107
- if (pos < shake256.blockLen)
1108
- continue;
1109
- s.xofInto(buf);
1110
- pos = 0;
1111
- }
1112
- pre[i] = pre[b];
1113
- pre[b] = 1 - ((masks[maskPos] >> maskBit++ & 1) << 1);
1114
- if (maskBit >= 8) {
1115
- maskPos++;
1116
- maskBit = 0;
1117
- }
1118
- }
1119
- return pre;
1120
- };
1121
- const polyPowerRound = (p) => {
1122
- const res0 = newPoly(N);
1123
- const res1 = newPoly(N);
1124
- for (let i = 0; i < p.length; i++) {
1125
- const { r0, r1 } = Power2Round(p[i]);
1126
- res0[i] = r0;
1127
- res1[i] = r1;
1128
- }
1129
- return { r0: res0, r1: res1 };
1130
- };
1131
- const polyUseHint = (u, h) => {
1132
- for (let i = 0; i < N; i++)
1133
- u[i] = UseHint(h[i], u[i]);
1134
- return u;
1135
- };
1136
- const polyMakeHint = (a, b) => {
1137
- const v = newPoly(N);
1138
- let cnt = 0;
1139
- for (let i = 0; i < N; i++) {
1140
- const h = MakeHint(a[i], b[i]);
1141
- v[i] = h;
1142
- cnt += h;
1143
- }
1144
- return { v, cnt };
1145
- };
1146
- const signRandBytes = 32;
1147
- const seedCoder = splitCoder(32, 64, 32);
1148
- const internal = {
1149
- signRandBytes,
1150
- keygen: (seed = randomBytes2(32)) => {
1151
- const seedDst = new Uint8Array(32 + 2);
1152
- seedDst.set(seed);
1153
- seedDst[32] = K;
1154
- seedDst[33] = L;
1155
- const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));
1156
- const xofPrime = XOF2562(rhoPrime);
1157
- const s1 = [];
1158
- for (let i = 0; i < L; i++)
1159
- s1.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255)));
1160
- const s2 = [];
1161
- for (let i = L; i < L + K; i++)
1162
- s2.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255)));
1163
- const s1Hat = s1.map((i) => NTT.encode(i.slice()));
1164
- const t0 = [];
1165
- const t1 = [];
1166
- const xof = XOF1282(rho);
1167
- const t = newPoly(N);
1168
- for (let i = 0; i < K; i++) {
1169
- t.fill(0);
1170
- for (let j = 0; j < L; j++) {
1171
- const aij = RejNTTPoly(xof.get(j, i));
1172
- polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));
1173
- }
1174
- NTT.decode(t);
1175
- const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i]));
1176
- t0.push(r0);
1177
- t1.push(r1);
1178
- }
1179
- const publicKey = publicCoder.encode([rho, t1]);
1180
- const tr = shake256(publicKey, { dkLen: TR_BYTES });
1181
- const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);
1182
- xof.clean();
1183
- xofPrime.clean();
1184
- cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);
1185
- return { publicKey, secretKey };
1186
- },
1187
- sign: (secretKey, msg, random) => {
1188
- const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey);
1189
- const A = [];
1190
- const xof = XOF1282(rho);
1191
- for (let i = 0; i < K; i++) {
1192
- const pv = [];
1193
- for (let j = 0; j < L; j++)
1194
- pv.push(RejNTTPoly(xof.get(j, i)));
1195
- A.push(pv);
1196
- }
1197
- xof.clean();
1198
- for (let i = 0; i < L; i++)
1199
- NTT.encode(s1[i]);
1200
- for (let i = 0; i < K; i++) {
1201
- NTT.encode(s2[i]);
1202
- NTT.encode(t0[i]);
1203
- }
1204
- const mu = shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();
1205
- const rnd = random ? random : new Uint8Array(32);
1206
- ensureBytes(rnd);
1207
- const rhoprime = shake256.create({ dkLen: CRH_BYTES }).update(_K).update(rnd).update(mu).digest();
1208
- ensureBytes(rhoprime, CRH_BYTES);
1209
- const x256 = XOF2562(rhoprime, ZCoder.bytesLen);
1210
- main_loop:
1211
- for (let kappa = 0; ; ) {
1212
- const y = [];
1213
- for (let i = 0; i < L; i++, kappa++)
1214
- y.push(ZCoder.decode(x256.get(kappa & 255, kappa >> 8)()));
1215
- const z = y.map((i) => NTT.encode(i.slice()));
1216
- const w = [];
1217
- for (let i = 0; i < K; i++) {
1218
- const wi = newPoly(N);
1219
- for (let j = 0; j < L; j++)
1220
- polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));
1221
- NTT.decode(wi);
1222
- w.push(wi);
1223
- }
1224
- const w1 = w.map((j) => j.map(HighBits));
1225
- const cTilde = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(w1)).digest();
1226
- const cHat = NTT.encode(SampleInBall(cTilde));
1227
- const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));
1228
- for (let i = 0; i < L; i++) {
1229
- polyAdd(NTT.decode(cs1[i]), y[i]);
1230
- if (polyChknorm(cs1[i], GAMMA1 - BETA))
1231
- continue main_loop;
1232
- }
1233
- let cnt = 0;
1234
- const h = [];
1235
- for (let i = 0; i < K; i++) {
1236
- const cs2 = NTT.decode(MultiplyNTTs(s2[i], cHat));
1237
- const r0 = polySub(w[i], cs2).map(LowBits);
1238
- if (polyChknorm(r0, GAMMA2 - BETA))
1239
- continue main_loop;
1240
- const ct0 = NTT.decode(MultiplyNTTs(t0[i], cHat));
1241
- if (polyChknorm(ct0, GAMMA2))
1242
- continue main_loop;
1243
- polyAdd(r0, ct0);
1244
- const hint = polyMakeHint(r0, w1[i]);
1245
- h.push(hint.v);
1246
- cnt += hint.cnt;
1247
- }
1248
- if (cnt > OMEGA)
1249
- continue;
1250
- x256.clean();
1251
- const res = sigCoder.encode([cTilde, cs1, h]);
1252
- cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, mu, s1, s2, t0, ...A);
1253
- return res;
1254
- }
1255
- throw new Error("Unreachable code path reached, report this error");
1256
- },
1257
- verify: (publicKey, msg, sig) => {
1258
- const [rho, t1] = publicCoder.decode(publicKey);
1259
- const tr = shake256(publicKey, { dkLen: TR_BYTES });
1260
- if (sig.length !== sigCoder.bytesLen)
1261
- return false;
1262
- const [cTilde, z, h] = sigCoder.decode(sig);
1263
- if (h === false)
1264
- return false;
1265
- for (let i = 0; i < L; i++)
1266
- if (polyChknorm(z[i], GAMMA1 - BETA))
1267
- return false;
1268
- const mu = shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();
1269
- const c2 = NTT.encode(SampleInBall(cTilde));
1270
- const zNtt = z.map((i) => i.slice());
1271
- for (let i = 0; i < L; i++)
1272
- NTT.encode(zNtt[i]);
1273
- const wTick1 = [];
1274
- const xof = XOF1282(rho);
1275
- for (let i = 0; i < K; i++) {
1276
- const ct12d = MultiplyNTTs(NTT.encode(polyShiftl(t1[i])), c2);
1277
- const Az = newPoly(N);
1278
- for (let j = 0; j < L; j++) {
1279
- const aij = RejNTTPoly(xof.get(j, i));
1280
- polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));
1281
- }
1282
- const wApprox = NTT.decode(polySub(Az, ct12d));
1283
- wTick1.push(polyUseHint(wApprox, h[i]));
1284
- }
1285
- xof.clean();
1286
- const c22 = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(wTick1)).digest();
1287
- for (const t of h) {
1288
- const sum = t.reduce((acc, i) => acc + i, 0);
1289
- if (!(sum <= OMEGA))
1290
- return false;
1291
- }
1292
- for (const t of z)
1293
- if (polyChknorm(t, GAMMA1 - BETA))
1294
- return false;
1295
- return equalBytes(cTilde, c22);
1296
- }
1297
- };
1298
- const getMessage = (msg, ctx = EMPTY) => {
1299
- ensureBytes(msg);
1300
- ensureBytes(ctx);
1301
- if (ctx.length > 255)
1302
- throw new Error("context should be less than 255 bytes");
1303
- return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);
1304
- };
1305
- return {
1306
- internal,
1307
- keygen: internal.keygen,
1308
- signRandBytes: internal.signRandBytes,
1309
- sign: (secretKey, msg, ctx = EMPTY, random) => {
1310
- const M = getMessage(msg, ctx);
1311
- const res = internal.sign(secretKey, M, random);
1312
- M.fill(0);
1313
- return res;
1314
- },
1315
- verify: (publicKey, msg, sig, ctx = EMPTY) => {
1316
- return internal.verify(publicKey, getMessage(msg, ctx), sig);
1317
- }
1318
- };
1319
- }
1320
- var ml_dsa44 = /* @__PURE__ */ getDilithium({
1321
- ...PARAMS[2],
1322
- CRH_BYTES: 64,
1323
- TR_BYTES: 64,
1324
- C_TILDE_BYTES: 32,
1325
- XOF128,
1326
- XOF256
1327
- });
1328
- var ml_dsa65 = /* @__PURE__ */ getDilithium({
1329
- ...PARAMS[3],
1330
- CRH_BYTES: 64,
1331
- TR_BYTES: 64,
1332
- C_TILDE_BYTES: 48,
1333
- XOF128,
1334
- XOF256
1335
- });
1336
- var ml_dsa87 = /* @__PURE__ */ getDilithium({
1337
- ...PARAMS[5],
1338
- CRH_BYTES: 64,
1339
- TR_BYTES: 64,
1340
- C_TILDE_BYTES: 64,
1341
- XOF128,
1342
- XOF256
1343
- });
1344
- function toBase64(bytes) {
1345
- let binary = "";
1346
- for (const byte of bytes)
1347
- binary += String.fromCharCode(byte);
1348
- return btoa(binary);
1349
- }
1350
- function fromBase64(b64) {
1351
- return Uint8Array.from(atob(b64), (c2) => c2.charCodeAt(0));
1352
- }
1353
- function sign(privateKey, message) {
1354
- const secretKey = fromBase64(privateKey);
1355
- const msg = new TextEncoder().encode(message);
1356
- const signature = ml_dsa65.sign(secretKey, msg);
1357
- return toBase64(signature);
1358
- }
1359
- var XMP_NS = "http://ns.adobe.com/xap/1.0/\0";
1360
- var XMP_NS_BYTES = new TextEncoder().encode(XMP_NS);
1361
130
  function toUint8Array(content) {
1362
131
  if (typeof content === "string")
1363
132
  return new TextEncoder().encode(content);
@@ -1365,38 +134,23 @@ function toUint8Array(content) {
1365
134
  }
1366
135
  async function signContent(baseUrl, apiKey, input) {
1367
136
  const bytes = toUint8Array(input.content);
1368
- const contentHash = hash(bytes);
1369
- const watermarkId = input.watermarkId ?? crypto.randomUUID();
1370
- const signedAt = (/* @__PURE__ */ new Date()).toISOString();
1371
- const signedPayload = {
1372
- generator_id: input.generatorId,
1373
- model: input.model,
1374
- content_hash: contentHash,
1375
- watermark_id: watermarkId,
1376
- signed_at: signedAt
1377
- };
1378
- const message = canonicalJson(signedPayload);
1379
- const signature = sign(input.privateKey, message);
1380
- const res = await fetch(`${baseUrl}/v1/records`, {
137
+ const form = new FormData();
138
+ form.append("image", new Blob([bytes]), "image");
139
+ form.append("model", input.model);
140
+ form.append("generator_id", input.generatorId);
141
+ const res = await fetch(`${baseUrl}/v1/sign`, {
1381
142
  method: "POST",
1382
- headers: {
1383
- "Content-Type": "application/json",
1384
- Authorization: `Bearer ${apiKey}`
1385
- },
1386
- body: JSON.stringify({
1387
- watermark_id: watermarkId,
1388
- generator_id: input.generatorId,
1389
- model: input.model,
1390
- content_hash: contentHash,
1391
- signature,
1392
- signed_payload: signedPayload
1393
- })
143
+ headers: { Authorization: `Bearer ${apiKey}` },
144
+ body: form
1394
145
  });
1395
146
  if (!res.ok) {
1396
147
  const err2 = await res.json().catch(() => ({}));
1397
148
  throw new Error(err2.error ?? `HTTP ${res.status}`);
1398
149
  }
1399
- return res.json();
150
+ const token = res.headers.get("X-Certivu-Token") ?? "";
151
+ const record_id = res.headers.get("X-Certivu-Record-Id") ?? "";
152
+ const watermarkedContent = new Uint8Array(await res.arrayBuffer());
153
+ return { token, record_id, watermarkedContent };
1400
154
  }
1401
155
  function toUint8Array2(content) {
1402
156
  if (typeof content === "string")
@@ -1452,21 +206,16 @@ var CertivuClient = class {
1452
206
  apiKey;
1453
207
  baseUrl;
1454
208
  generatorId;
1455
- privateKey;
1456
209
  constructor(config) {
1457
210
  this.apiKey = config.apiKey;
1458
211
  this.baseUrl = (config.baseUrl ?? "https://api.certivu.ai").replace(/\/$/, "");
1459
212
  this.generatorId = config.generatorId;
1460
- this.privateKey = config.privateKey;
1461
213
  }
1462
214
  async sign(input) {
1463
215
  const generatorId = input.generatorId ?? this.generatorId;
1464
- const privateKey = input.privateKey ?? this.privateKey;
1465
216
  if (!generatorId)
1466
217
  throw new Error("generatorId is required for sign (provide in config or input)");
1467
- if (!privateKey)
1468
- throw new Error("privateKey is required for sign (provide in config or input)");
1469
- return signContent(this.baseUrl, this.apiKey, { ...input, generatorId, privateKey });
218
+ return signContent(this.baseUrl, this.apiKey, { ...input, generatorId });
1470
219
  }
1471
220
  async verify(input) {
1472
221
  return verifyContent(this.baseUrl, this.apiKey, input);
@@ -1477,8 +226,8 @@ var CertivuClient = class {
1477
226
  async getAuditLog(options) {
1478
227
  return getAuditLog(this.baseUrl, this.apiKey, options);
1479
228
  }
1480
- async getTokenStatus(token2) {
1481
- const res = await fetch(`${this.baseUrl}/v1/verify/status/${encodeURIComponent(token2)}`);
229
+ async getTokenStatus(token) {
230
+ const res = await fetch(`${this.baseUrl}/v1/verify/status/${encodeURIComponent(token)}`);
1482
231
  if (!res.ok) {
1483
232
  const err2 = await res.json().catch(() => ({}));
1484
233
  throw new Error(err2.error ?? `HTTP ${res.status}`);
@@ -1493,10 +242,8 @@ async function signCommand(filePath, flags) {
1493
242
  const config = await loadConfig();
1494
243
  const apiKey = flags.apiKey ?? config.apiKey;
1495
244
  const generatorId = flags.generatorId ?? config.generatorId;
1496
- const privateKey = flags.privateKey ?? config.privateKey;
1497
245
  if (!apiKey) die("API key required. Set CERTIVU_API_KEY or run: certivu config set api-key <key>");
1498
246
  if (!generatorId) die("Generator ID required. Set CERTIVU_GENERATOR_ID or run: certivu config set generator-id <id>");
1499
- if (!privateKey) die("Private key required. Set CERTIVU_PRIVATE_KEY or run: certivu config set private-key <key>");
1500
247
  let content;
1501
248
  try {
1502
249
  content = new Uint8Array((0, import_node_fs2.readFileSync)(filePath));
@@ -1506,20 +253,26 @@ async function signCommand(filePath, flags) {
1506
253
  const clientConfig = {
1507
254
  apiKey,
1508
255
  generatorId,
1509
- privateKey,
1510
256
  ...flags.baseUrl || config.baseUrl ? { baseUrl: flags.baseUrl ?? config.baseUrl } : {}
1511
257
  };
1512
258
  const client = new CertivuClient(clientConfig);
1513
259
  let result;
1514
260
  try {
1515
- result = await client.sign({ content, model: flags.model, generatorId, privateKey });
261
+ result = await client.sign({ content, model: flags.model, generatorId });
1516
262
  } catch (e) {
1517
263
  const msg = e instanceof Error ? e.message : String(e);
1518
264
  die(`Sign failed: ${msg}`);
1519
265
  }
266
+ const outPath = flags.output ?? (filePath.replace(/(\.[^.]+)$/, `.signed$1`) || `${filePath}.signed${(0, import_node_path2.extname)(filePath)}`);
267
+ try {
268
+ (0, import_node_fs2.writeFileSync)(outPath, result.watermarkedContent);
269
+ } catch {
270
+ die(`Could not write output file: ${outPath}`);
271
+ }
1520
272
  console.log(ok("Signed"));
1521
273
  row("Token", result.token);
1522
274
  row("Record ID", result.record_id);
275
+ row("Output", outPath);
1523
276
  if (result.deduplicated) {
1524
277
  console.log(" (content already signed \u2014 existing token returned, no quota consumed)");
1525
278
  }
@@ -1702,5 +455,3 @@ Run 'certivu --help' for usage.`);
1702
455
  }
1703
456
  }
1704
457
  main();
1705
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1706
- /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */