@calimero-network/mero-js 33.2.0 → 33.3.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.mjs CHANGED
@@ -1,17 +1,32 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
1
5
  // src/crypto/internal.ts
2
6
  function hex(bytes) {
3
7
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4
8
  }
5
9
  function fromHex(value, label, expectedBytes) {
6
- const clean = value.trim();
7
- if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length !== expectedBytes * 2) {
10
+ const clean2 = value.trim();
11
+ if (!/^[0-9a-fA-F]*$/.test(clean2) || clean2.length !== expectedBytes * 2) {
8
12
  throw new Error(
9
- `${label} must be ${expectedBytes * 2} hex characters, got ${clean.length}`
13
+ `${label} must be ${expectedBytes * 2} hex characters, got ${clean2.length}`
10
14
  );
11
15
  }
12
16
  const bytes = new Uint8Array(expectedBytes);
13
17
  for (let i = 0; i < expectedBytes; i += 1) {
14
- bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);
18
+ bytes[i] = Number.parseInt(clean2.slice(i * 2, i * 2 + 2), 16);
19
+ }
20
+ return bytes;
21
+ }
22
+ function fromHexUnsized(value, label) {
23
+ const clean2 = value.trim();
24
+ if (!/^[0-9a-fA-F]*$/.test(clean2) || clean2.length % 2 !== 0) {
25
+ throw new Error(`${label} must be an even number of hex characters`);
26
+ }
27
+ const bytes = new Uint8Array(clean2.length / 2);
28
+ for (let i = 0; i < bytes.length; i += 1) {
29
+ bytes[i] = Number.parseInt(clean2.slice(i * 2, i * 2 + 2), 16);
15
30
  }
16
31
  return bytes;
17
32
  }
@@ -674,11 +689,11 @@ async function verifyEcdsa(spki, curve, hash, signature, data) {
674
689
  return crypto.subtle.verify({ name: "ECDSA", hash }, key, p1363, data);
675
690
  }
676
691
  function fromBase64(value, what) {
677
- const clean = value.replace(/\s+/g, "");
678
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 !== 0) {
692
+ const clean2 = value.replace(/\s+/g, "");
693
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean2) || clean2.length % 4 !== 0) {
679
694
  throw new Error(`${what} is not base64`);
680
695
  }
681
- const binary = atob(clean);
696
+ const binary = atob(clean2);
682
697
  const bytes = new Uint8Array(binary.length);
683
698
  for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
684
699
  return bytes;
@@ -4085,6 +4100,600 @@ function refusalOf(response, error) {
4085
4100
  return errorFrom(response.status, body, response.headers.get("retry-after"));
4086
4101
  }
4087
4102
 
4103
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js
4104
+ var fromNumH = (n) => n / 2 ** 32 | 0;
4105
+ var fromNumL = (n) => n >>> 0;
4106
+ function setU64FromNum(view, byteOffset, n, isLE) {
4107
+ const h = fromNumH(n);
4108
+ const l = fromNumL(n);
4109
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
4110
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
4111
+ }
4112
+
4113
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js
4114
+ function isBytes(a) {
4115
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
4116
+ }
4117
+ var atitle = (title) => title ? `"${title}" ` : "";
4118
+ function anumber(n, title = "") {
4119
+ if (typeof n !== "number")
4120
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
4121
+ if (!Number.isSafeInteger(n) || n < 0)
4122
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
4123
+ return n;
4124
+ }
4125
+ function abytes(value, length, title = "") {
4126
+ if (isBytes(value) && (length === void 0 || value.length === length))
4127
+ return value;
4128
+ if (length !== void 0)
4129
+ anumber(length, "length");
4130
+ const bytes = isBytes(value);
4131
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
4132
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
4133
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
4134
+ if (!bytes)
4135
+ throw new TypeError(message);
4136
+ throw new RangeError(message);
4137
+ }
4138
+ var aobject = (value, label) => {
4139
+ if (value === null || typeof value !== "object" || Array.isArray(value))
4140
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
4141
+ };
4142
+ var aopts = (value, label) => {
4143
+ aobject(value, label);
4144
+ const proto = Object.getPrototypeOf(value);
4145
+ if (proto !== Object.prototype && proto !== null)
4146
+ throw new TypeError(`"${label}" expected plain object`);
4147
+ if (Object.hasOwn(value, "__proto__"))
4148
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
4149
+ };
4150
+ function aexists(instance, checkFinished = true) {
4151
+ if (instance.destroyed)
4152
+ throw new Error("hash was destroyed");
4153
+ if (checkFinished && instance.finished)
4154
+ throw new Error("digest() was already called");
4155
+ }
4156
+ function aoutput(out, instance) {
4157
+ abytes(out, void 0, "output");
4158
+ const min = instance.outputLen;
4159
+ if (!(out.length >= min)) {
4160
+ throw new RangeError('"output" expected length >= ' + min);
4161
+ }
4162
+ }
4163
+ function clean(...arrays) {
4164
+ for (let i = 0; i < arrays.length; i++) {
4165
+ arrays[i].fill(0);
4166
+ }
4167
+ }
4168
+ function createView(arr) {
4169
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
4170
+ }
4171
+ function rotr(word, shift) {
4172
+ return word << 32 - shift | word >>> shift;
4173
+ }
4174
+ function checkOpts(defaults, opts, title = "opts") {
4175
+ aopts(defaults, "defaults");
4176
+ if (opts !== void 0)
4177
+ aopts(opts, title);
4178
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
4179
+ return merged;
4180
+ }
4181
+ function createHasher(hashCons, info = {}) {
4182
+ if (typeof hashCons !== "function")
4183
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
4184
+ info = checkOpts({}, info, "info");
4185
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
4186
+ const tmp = hashCons(void 0);
4187
+ hashC.outputLen = tmp.outputLen;
4188
+ hashC.blockLen = tmp.blockLen;
4189
+ hashC.canXOF = tmp.canXOF;
4190
+ hashC.create = (opts) => hashCons(opts);
4191
+ Object.assign(hashC, info);
4192
+ return Object.freeze(hashC);
4193
+ }
4194
+ var oidNist = (suffix) => ({
4195
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
4196
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
4197
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
4198
+ });
4199
+
4200
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
4201
+ function Chi(a, b, c) {
4202
+ return a & b ^ ~a & c;
4203
+ }
4204
+ function Maj(a, b, c) {
4205
+ return a & b ^ a & c ^ b & c;
4206
+ }
4207
+ var HashMD = class {
4208
+ constructor(blockLen, outputLen, padOffset, isLE) {
4209
+ __publicField(this, "blockLen");
4210
+ __publicField(this, "outputLen");
4211
+ __publicField(this, "canXOF", false);
4212
+ __publicField(this, "padOffset");
4213
+ __publicField(this, "isLE");
4214
+ // For partial updates less than block size
4215
+ __publicField(this, "buffer");
4216
+ __publicField(this, "view");
4217
+ __publicField(this, "finished", false);
4218
+ __publicField(this, "length", 0);
4219
+ __publicField(this, "pos", 0);
4220
+ __publicField(this, "destroyed", false);
4221
+ this.blockLen = blockLen;
4222
+ this.outputLen = outputLen;
4223
+ this.padOffset = padOffset;
4224
+ this.isLE = isLE;
4225
+ this.buffer = new Uint8Array(blockLen);
4226
+ this.view = createView(this.buffer);
4227
+ }
4228
+ update(data) {
4229
+ aexists(this);
4230
+ abytes(data);
4231
+ const { view, buffer, blockLen } = this;
4232
+ const len = data.length;
4233
+ let processed = false;
4234
+ for (let pos = 0; pos < len; ) {
4235
+ const take = Math.min(blockLen - this.pos, len - pos);
4236
+ if (take === blockLen) {
4237
+ const dataView = createView(data);
4238
+ for (; blockLen <= len - pos; pos += blockLen)
4239
+ this.process(dataView, pos);
4240
+ processed = true;
4241
+ continue;
4242
+ }
4243
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
4244
+ this.pos += take;
4245
+ pos += take;
4246
+ if (this.pos === blockLen) {
4247
+ this.process(view, 0);
4248
+ this.pos = 0;
4249
+ processed = true;
4250
+ }
4251
+ }
4252
+ this.length += data.length;
4253
+ if (processed)
4254
+ this.roundClean();
4255
+ return this;
4256
+ }
4257
+ digestInto(out) {
4258
+ aexists(this);
4259
+ aoutput(out, this);
4260
+ this.finished = true;
4261
+ const { buffer, view, blockLen, isLE } = this;
4262
+ let { pos } = this;
4263
+ buffer[pos++] = 128;
4264
+ buffer.fill(0, pos);
4265
+ if (this.padOffset > blockLen - pos) {
4266
+ this.process(view, 0);
4267
+ buffer.fill(0);
4268
+ }
4269
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
4270
+ this.process(view, 0);
4271
+ this.roundClean();
4272
+ const oview = out === buffer ? view : createView(out);
4273
+ const len = this.outputLen;
4274
+ const outLen = len / 4;
4275
+ const state = this.get();
4276
+ if (len % 4 || outLen > state.length)
4277
+ throw new Error("invalid outputLen");
4278
+ for (let i = 0; i < outLen; i++)
4279
+ oview.setUint32(4 * i, state[i], isLE);
4280
+ }
4281
+ digest() {
4282
+ const { buffer, outputLen } = this;
4283
+ this.digestInto(buffer);
4284
+ const res = buffer.slice(0, outputLen);
4285
+ this.destroy();
4286
+ return res;
4287
+ }
4288
+ _cloneIntoMeta(to) {
4289
+ const { buffer, length, finished, destroyed, pos } = this;
4290
+ to.destroyed = destroyed;
4291
+ to.finished = finished;
4292
+ to.length = length;
4293
+ to.pos = pos;
4294
+ if (pos)
4295
+ to.buffer.set(buffer);
4296
+ return to;
4297
+ }
4298
+ clone() {
4299
+ return this._cloneInto();
4300
+ }
4301
+ };
4302
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
4303
+ 1779033703,
4304
+ 3144134277,
4305
+ 1013904242,
4306
+ 2773480762,
4307
+ 1359893119,
4308
+ 2600822924,
4309
+ 528734635,
4310
+ 1541459225
4311
+ ]);
4312
+
4313
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js
4314
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
4315
+ 1116352408,
4316
+ 1899447441,
4317
+ 3049323471,
4318
+ 3921009573,
4319
+ 961987163,
4320
+ 1508970993,
4321
+ 2453635748,
4322
+ 2870763221,
4323
+ 3624381080,
4324
+ 310598401,
4325
+ 607225278,
4326
+ 1426881987,
4327
+ 1925078388,
4328
+ 2162078206,
4329
+ 2614888103,
4330
+ 3248222580,
4331
+ 3835390401,
4332
+ 4022224774,
4333
+ 264347078,
4334
+ 604807628,
4335
+ 770255983,
4336
+ 1249150122,
4337
+ 1555081692,
4338
+ 1996064986,
4339
+ 2554220882,
4340
+ 2821834349,
4341
+ 2952996808,
4342
+ 3210313671,
4343
+ 3336571891,
4344
+ 3584528711,
4345
+ 113926993,
4346
+ 338241895,
4347
+ 666307205,
4348
+ 773529912,
4349
+ 1294757372,
4350
+ 1396182291,
4351
+ 1695183700,
4352
+ 1986661051,
4353
+ 2177026350,
4354
+ 2456956037,
4355
+ 2730485921,
4356
+ 2820302411,
4357
+ 3259730800,
4358
+ 3345764771,
4359
+ 3516065817,
4360
+ 3600352804,
4361
+ 4094571909,
4362
+ 275423344,
4363
+ 430227734,
4364
+ 506948616,
4365
+ 659060556,
4366
+ 883997877,
4367
+ 958139571,
4368
+ 1322822218,
4369
+ 1537002063,
4370
+ 1747873779,
4371
+ 1955562222,
4372
+ 2024104815,
4373
+ 2227730452,
4374
+ 2361852424,
4375
+ 2428436474,
4376
+ 2756734187,
4377
+ 3204031479,
4378
+ 3329325298
4379
+ ]);
4380
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
4381
+ var SHA2_32B = class extends HashMD {
4382
+ constructor(outputLen, IV) {
4383
+ super(64, outputLen, 8, false);
4384
+ // We cannot use array here since array allows indexing by variable
4385
+ // which means optimizer/compiler cannot use registers.
4386
+ // Numeric initializers matter: starting the fields as `undefined` changes
4387
+ // V8's field representation and makes sha256 3x slower (measured).
4388
+ __publicField(this, "A", 0);
4389
+ __publicField(this, "B", 0);
4390
+ __publicField(this, "C", 0);
4391
+ __publicField(this, "D", 0);
4392
+ __publicField(this, "E", 0);
4393
+ __publicField(this, "F", 0);
4394
+ __publicField(this, "G", 0);
4395
+ __publicField(this, "H", 0);
4396
+ this.A = IV[0] | 0;
4397
+ this.B = IV[1] | 0;
4398
+ this.C = IV[2] | 0;
4399
+ this.D = IV[3] | 0;
4400
+ this.E = IV[4] | 0;
4401
+ this.F = IV[5] | 0;
4402
+ this.G = IV[6] | 0;
4403
+ this.H = IV[7] | 0;
4404
+ }
4405
+ get() {
4406
+ const { A, B, C, D, E, F, G, H } = this;
4407
+ return [A, B, C, D, E, F, G, H];
4408
+ }
4409
+ // prettier-ignore
4410
+ set(A, B, C, D, E, F, G, H) {
4411
+ this.A = A | 0;
4412
+ this.B = B | 0;
4413
+ this.C = C | 0;
4414
+ this.D = D | 0;
4415
+ this.E = E | 0;
4416
+ this.F = F | 0;
4417
+ this.G = G | 0;
4418
+ this.H = H | 0;
4419
+ }
4420
+ _cloneInto(to) {
4421
+ (to || (to = new this.constructor())).set(...this.get());
4422
+ return this._cloneIntoMeta(to);
4423
+ }
4424
+ process(view, offset) {
4425
+ for (let i = 0; i < 16; i++, offset += 4)
4426
+ SHA256_W[i] = view.getUint32(offset, false);
4427
+ for (let i = 16; i < 64; i++) {
4428
+ const W15 = SHA256_W[i - 15];
4429
+ const W2 = SHA256_W[i - 2];
4430
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
4431
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
4432
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
4433
+ }
4434
+ let { A, B, C, D, E, F, G, H } = this;
4435
+ for (let i = 0; i < 64; i++) {
4436
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
4437
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
4438
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
4439
+ const T2 = sigma0 + Maj(A, B, C) | 0;
4440
+ H = G;
4441
+ G = F;
4442
+ F = E;
4443
+ E = D + T1 | 0;
4444
+ D = C;
4445
+ C = B;
4446
+ B = A;
4447
+ A = T1 + T2 | 0;
4448
+ }
4449
+ A = A + this.A | 0;
4450
+ B = B + this.B | 0;
4451
+ C = C + this.C | 0;
4452
+ D = D + this.D | 0;
4453
+ E = E + this.E | 0;
4454
+ F = F + this.F | 0;
4455
+ G = G + this.G | 0;
4456
+ H = H + this.H | 0;
4457
+ this.set(A, B, C, D, E, F, G, H);
4458
+ }
4459
+ roundClean() {
4460
+ clean(SHA256_W);
4461
+ }
4462
+ destroy() {
4463
+ this.destroyed = true;
4464
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
4465
+ clean(this.buffer);
4466
+ }
4467
+ };
4468
+ var _SHA256 = class extends SHA2_32B {
4469
+ constructor() {
4470
+ super(32, SHA256_IV);
4471
+ }
4472
+ };
4473
+ var sha2562 = /* @__PURE__ */ createHasher(
4474
+ () => new _SHA256(),
4475
+ /* @__PURE__ */ oidNist(1)
4476
+ );
4477
+
4478
+ // src/sealed/file.ts
4479
+ var CHUNK_BYTES = 64 * 1024;
4480
+ var TAG_BYTES = 16;
4481
+ var SEALED_CHUNK_BYTES = CHUNK_BYTES + TAG_BYTES;
4482
+ var SEGMENT_BYTES = 256 * SEALED_CHUNK_BYTES;
4483
+ var NONCE_BYTES = 12;
4484
+ var enc = new TextEncoder();
4485
+ var AAD_PREFIX = enc.encode("calimero.file.v1");
4486
+ var SEGMENT_DOMAIN = enc.encode("calimero.file.segments.v1\0");
4487
+ var EXPORT_WRAP_SALT = enc.encode("calimero.export-wrap.v1");
4488
+ var DERIVE_LABEL = enc.encode("calimero.sealed.derive.v1\0");
4489
+ var ExportError = class extends Error {
4490
+ constructor(code, message) {
4491
+ super(message);
4492
+ this.code = code;
4493
+ this.name = "ExportError";
4494
+ }
4495
+ };
4496
+ var sha2563 = async (data) => new Uint8Array(await crypto.subtle.digest("SHA-256", data));
4497
+ function fileId(segments) {
4498
+ const count = new Uint8Array(4);
4499
+ new DataView(count.buffer).setUint32(0, segments.length, false);
4500
+ return sha2563(concat(SEGMENT_DOMAIN, count, ...segments));
4501
+ }
4502
+ function prefixed(field) {
4503
+ const bytes = enc.encode(field);
4504
+ const length = new Uint8Array(4);
4505
+ new DataView(length.buffer).setUint32(0, bytes.length, false);
4506
+ return concat(length, bytes);
4507
+ }
4508
+ async function unwrapExport(recipient, ephemeral, wrap, wrapped) {
4509
+ if (wrapped.length < NONCE_BYTES) throw new ExportError("TAMPERED", "the wrapped key is truncated");
4510
+ const shared = await dh(recipient.privateKey, ephemeral);
4511
+ if (shared.every((b) => b === 0)) throw new ExportError("BAD_ANSWER", "the ephemeral key is of low order");
4512
+ const info = concat(ephemeral, recipient.publicKey, prefixed(wrap.appId), prefixed(wrap.fileId));
4513
+ const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);
4514
+ const keyBytes = await crypto.subtle.deriveBits(
4515
+ { name: "HKDF", hash: "SHA-256", salt: EXPORT_WRAP_SALT, info: concat(DERIVE_LABEL, info) },
4516
+ ikm,
4517
+ 256
4518
+ );
4519
+ const key = await crypto.subtle.importKey("raw", keyBytes, "AES-GCM", false, ["decrypt"]);
4520
+ let secret;
4521
+ try {
4522
+ secret = await crypto.subtle.decrypt(
4523
+ { name: "AES-GCM", iv: wrapped.subarray(0, NONCE_BYTES) },
4524
+ key,
4525
+ wrapped.subarray(NONCE_BYTES)
4526
+ );
4527
+ } catch {
4528
+ throw new ExportError("TAMPERED", "the wrapped key does not open");
4529
+ }
4530
+ if (secret.byteLength !== 32) throw new ExportError("TAMPERED", "the wrapped key has the wrong length");
4531
+ return new Uint8Array(secret);
4532
+ }
4533
+ var SegmentReader = class _SegmentReader {
4534
+ constructor(key, segments) {
4535
+ this.key = key;
4536
+ this.segments = segments;
4537
+ this.pending = new Uint8Array();
4538
+ this.index = 0;
4539
+ this.next = 0;
4540
+ this.size = 0;
4541
+ this.hash = sha2562.create();
4542
+ }
4543
+ static async create(dataKey, segments) {
4544
+ const key = await crypto.subtle.importKey("raw", dataKey, "AES-GCM", false, ["decrypt"]);
4545
+ return new _SegmentReader(key, segments.map(hex));
4546
+ }
4547
+ /** Take the next segment; `emit` gets the plaintext of every chunk it completes. */
4548
+ async push(segment, emit) {
4549
+ const want = this.segments[this.next];
4550
+ if (want === void 0) throw new ExportError("TAMPERED", `the file has no segment ${this.next}`);
4551
+ if (this.next + 1 < this.segments.length && segment.length !== SEGMENT_BYTES) {
4552
+ throw new ExportError("TAMPERED", `segment ${this.next} is not a whole segment`);
4553
+ }
4554
+ if (hex(await sha2563(segment)) !== want) {
4555
+ throw new ExportError("TAMPERED", `segment ${this.next} is not the one the file lists`);
4556
+ }
4557
+ this.next += 1;
4558
+ const data = concat(this.pending, segment);
4559
+ let at = 0;
4560
+ while (data.length - at > SEALED_CHUNK_BYTES) {
4561
+ await emit(await this.open(data.subarray(at, at + SEALED_CHUNK_BYTES), false));
4562
+ at += SEALED_CHUNK_BYTES;
4563
+ }
4564
+ this.pending = data.slice(at);
4565
+ }
4566
+ /** Open the last chunk and check the whole plaintext's size and SHA-256: GCM does not commit to its key. */
4567
+ async finishExpecting(size, sha256Hex) {
4568
+ if (this.next !== this.segments.length) throw new ExportError("TAMPERED", "the file is missing segments");
4569
+ if (this.pending.length < TAG_BYTES) throw new ExportError("TAMPERED", "the file is truncated");
4570
+ const last = await this.open(this.pending, true);
4571
+ if (this.size !== size || hex(this.hash.digest()) !== sha256Hex) {
4572
+ throw new ExportError("TAMPERED", "the file is not the one that was sealed");
4573
+ }
4574
+ return last;
4575
+ }
4576
+ async open(chunk, last) {
4577
+ const iv = new Uint8Array(NONCE_BYTES);
4578
+ new DataView(iv.buffer).setBigUint64(4, BigInt(this.index), false);
4579
+ let plain;
4580
+ try {
4581
+ plain = new Uint8Array(
4582
+ await crypto.subtle.decrypt(
4583
+ { name: "AES-GCM", iv, additionalData: concat(AAD_PREFIX, new Uint8Array([last ? 1 : 0])) },
4584
+ this.key,
4585
+ chunk
4586
+ )
4587
+ );
4588
+ } catch {
4589
+ throw new ExportError(
4590
+ "TAMPERED",
4591
+ `chunk ${this.index} does not open: the file is altered, truncated or under another key`
4592
+ );
4593
+ }
4594
+ this.hash.update(plain);
4595
+ this.size += plain.length;
4596
+ this.index += 1;
4597
+ return plain;
4598
+ }
4599
+ };
4600
+
4601
+ // src/client/files.ts
4602
+ function hexField(value, label, bytes) {
4603
+ if (typeof value !== "string") throw new ExportError("BAD_ANSWER", `the node answered a bad ${label}`);
4604
+ try {
4605
+ return bytes === void 0 ? fromHexUnsized(value, label) : fromHex(value, label, bytes);
4606
+ } catch {
4607
+ throw new ExportError("BAD_ANSWER", `the node answered a bad ${label}`);
4608
+ }
4609
+ }
4610
+ function checked(answer) {
4611
+ const a = answer;
4612
+ if (typeof a !== "object" || a === null) throw new ExportError("BAD_ANSWER", "the node answered a bad export");
4613
+ if (typeof a.app !== "string") throw new ExportError("BAD_ANSWER", "the node answered a bad app");
4614
+ if (typeof a.size !== "number" || !Number.isSafeInteger(a.size) || a.size < 0) {
4615
+ throw new ExportError("BAD_ANSWER", "the node answered a bad size");
4616
+ }
4617
+ if (!Array.isArray(a.segments)) throw new ExportError("BAD_ANSWER", "the node answered a bad segment list");
4618
+ return {
4619
+ app: a.app,
4620
+ size: a.size,
4621
+ named: hexField(a.id, "file id", 32),
4622
+ segments: a.segments.map((h) => hexField(h, "segment hash", 32)),
4623
+ sha256: hex(hexField(a.sha256, "sha256", 32)),
4624
+ ephemeral: hexField(a.ephemeral, "ephemeral key", 32),
4625
+ wrapped: hexField(a.wrapped, "wrapped key")
4626
+ };
4627
+ }
4628
+ var aborted = () => new ExportError("ABORTED", "the export was aborted");
4629
+ async function readSegment(response, signal) {
4630
+ const declared = Number(response.headers.get("content-length"));
4631
+ if (Number.isFinite(declared) && declared > SEGMENT_BYTES) {
4632
+ await response.body?.cancel();
4633
+ throw new ExportError("TOO_LARGE", "a segment is longer than a whole segment");
4634
+ }
4635
+ if (!response.body) return new Uint8Array();
4636
+ const reader = response.body.getReader();
4637
+ const stop = () => void reader.cancel();
4638
+ signal?.addEventListener("abort", stop);
4639
+ const parts = [];
4640
+ let total = 0;
4641
+ try {
4642
+ for (; ; ) {
4643
+ const { done, value } = await reader.read();
4644
+ if (done) break;
4645
+ total += value.length;
4646
+ if (total > SEGMENT_BYTES) {
4647
+ await reader.cancel();
4648
+ throw new ExportError("TOO_LARGE", "a segment is longer than a whole segment");
4649
+ }
4650
+ parts.push(value);
4651
+ }
4652
+ } finally {
4653
+ signal?.removeEventListener("abort", stop);
4654
+ }
4655
+ if (signal?.aborted) throw aborted();
4656
+ return concat(...parts);
4657
+ }
4658
+ async function exportFileTo(transport, app, id, sink, signal, recipientSecret) {
4659
+ try {
4660
+ return await exportChecked(transport, app, id, sink, signal, recipientSecret);
4661
+ } catch (error) {
4662
+ if (signal?.aborted && !(error instanceof ExportError)) throw aborted();
4663
+ throw error;
4664
+ }
4665
+ }
4666
+ async function exportChecked(transport, app, id, sink, signal, recipientSecret) {
4667
+ const recipient = await x25519KeyPair(recipientSecret);
4668
+ const answer = checked(
4669
+ await transport.json("POST", routePath("apps/{app}/files/{id}/export", { app, id }), {
4670
+ body: { recipient: hex(recipient.publicKey) },
4671
+ signal
4672
+ })
4673
+ );
4674
+ const { segments, named } = answer;
4675
+ if (segments.length === 0 || hex(await fileId(segments)) !== hex(named) || hex(named) !== id) {
4676
+ throw new ExportError("NOT_THE_FILE", `the node answered segments that are not the file ${id}`);
4677
+ }
4678
+ const dataKey = await unwrapExport(recipient, answer.ephemeral, { appId: answer.app, fileId: id }, answer.wrapped);
4679
+ const reader = await SegmentReader.create(dataKey, segments);
4680
+ for (let k = 0; k < segments.length; k += 1) {
4681
+ if (signal?.aborted) throw aborted();
4682
+ const response = await transport.request("GET", routePath("apps/{app}/files/{id}/segments/{k}", { app, id, k }), {
4683
+ signal
4684
+ });
4685
+ await reader.push(await readSegment(response, signal), (chunk) => sink.write(chunk));
4686
+ }
4687
+ const last = await reader.finishExpecting(answer.size, answer.sha256);
4688
+ if (last.length > 0) await sink.write(last);
4689
+ return { size: answer.size, sha256: answer.sha256 };
4690
+ }
4691
+ async function exportFile(transport, app, id, signal) {
4692
+ const chunks = [];
4693
+ await exportFileTo(transport, app, id, { write: (chunk) => void chunks.push(chunk) }, signal);
4694
+ return concat(...chunks);
4695
+ }
4696
+
4088
4697
  // src/client/recovery-key.ts
4089
4698
  var RECOVERY_DOMAIN = "calimero.org-recovery.v1\0";
4090
4699
  var MAX_RECOVERY_NONCE_BYTES = 64;
@@ -4211,6 +4820,13 @@ function consentReturn(href) {
4211
4820
  if (!requestId || result !== "approved" && result !== "declined") return null;
4212
4821
  return { requestId, result };
4213
4822
  }
4823
+ function withoutConsentReturn(href) {
4824
+ const url2 = new URL(String(href));
4825
+ url2.searchParams.delete("request_id");
4826
+ url2.searchParams.delete("result");
4827
+ return url2.toString();
4828
+ }
4829
+ var CONSENT_STORAGE_KEY = "calimero.consent";
4214
4830
  var RELEASE_VERIFIER = "https://mero-tee.vercel.app";
4215
4831
  function releaseNotesUrl(version) {
4216
4832
  return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;
@@ -4272,6 +4888,15 @@ function withdrawConsent(scope, version, returnTo) {
4272
4888
  function upgradeConsent(app, toVersion, returnTo) {
4273
4889
  return { kind: "upgrade", subject: { app, toVersion }, returnTo };
4274
4890
  }
4891
+ function createOrgConsent(name, returnTo) {
4892
+ return { kind: "createOrg", subject: { name }, returnTo };
4893
+ }
4894
+ function createInviteConsent(subject, returnTo) {
4895
+ return { kind: "createInvite", subject, returnTo };
4896
+ }
4897
+ function acceptInviteConsent(token, returnTo) {
4898
+ return { kind: "acceptInvite", subject: { token }, returnTo };
4899
+ }
4275
4900
 
4276
4901
  // src/client/calimero-client.ts
4277
4902
  var FILE_PART_BYTES = 16 * 1024 * 1024;
@@ -4546,6 +5171,18 @@ var CalimeroClient = class _CalimeroClient {
4546
5171
  async downloadBlob(app, id) {
4547
5172
  return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());
4548
5173
  }
5174
+ /**
5175
+ * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,
5176
+ * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of
5177
+ * the file. A failed check is an `ExportError`; `signal` aborts the download.
5178
+ */
5179
+ exportFileTo(app, id, sink, signal) {
5180
+ return exportFileTo(this.transport, app, id, sink, signal);
5181
+ }
5182
+ /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */
5183
+ exportFile(app, id, signal) {
5184
+ return exportFile(this.transport, app, id, signal);
5185
+ }
4549
5186
  /**
4550
5187
  * Download a component app's blob with a grant one of its runs handed out
4551
5188
  * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
@@ -4696,6 +5333,8 @@ var CalimeroClient = class _CalimeroClient {
4696
5333
  * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
4697
5334
  * once `navigate` returns (or `confirm` declines): with a popup
4698
5335
  * (`url => window.open(url)`), poll it with {@link waitForConsent}.
5336
+ * Before navigating it keeps `requestId` in `sessionStorage` (where there
5337
+ * is one), for {@link resumeConsent} when the page sends the person back.
4699
5338
  */
4700
5339
  async openConsentPage(request, navigateOrOptions = {}) {
4701
5340
  const options = typeof navigateOrOptions === "function" ? { navigate: navigateOrOptions } : navigateOrOptions;
@@ -4716,9 +5355,84 @@ var CalimeroClient = class _CalimeroClient {
4716
5355
  }
4717
5356
  }
4718
5357
  if (options.confirm && !await options.confirm(started)) return started;
5358
+ try {
5359
+ consentStorage()?.setItem(CONSENT_STORAGE_KEY, started.requestId);
5360
+ } catch {
5361
+ }
4719
5362
  navigate(started.url);
4720
5363
  return started;
4721
5364
  }
5365
+ /**
5366
+ * On the page the consent page sent the person back to
5367
+ * (`returnTo?request_id=…&result=…`): the decision on the request this page
5368
+ * started, read from the node (`GET /consent/{id}/result`), never from the
5369
+ * URL. `null` when the URL carries no `request_id`. The request is
5370
+ * `options.requestId`, or the one {@link openConsentPage} stored in this
5371
+ * tab; with the default `href` (`location.href`) the parameters are then
5372
+ * removed with `history.replaceState`, and the stored id once decided.
5373
+ *
5374
+ * Throws `CalimeroError`:
5375
+ * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;
5376
+ * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;
5377
+ * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the
5378
+ * page sent the person back, a sign that another request was approved on a
5379
+ * page that was not the node's. Do not act on it;
5380
+ * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):
5381
+ * an account has one undecided request per node, and a newer one replaced
5382
+ * it, possibly on a page that was not the node's. Do not act on it either.
5383
+ *
5384
+ * The URL's `result` is never trusted: the answer's `status` is the node's.
5385
+ * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is
5386
+ * in the answer, typed by `kind`.
5387
+ */
5388
+ async resumeConsent(options = {}) {
5389
+ const g = globalThis;
5390
+ const href = options.href ?? g.location?.href;
5391
+ if (href === void 0) throw new Error("no page to read the consent return from; pass `href`");
5392
+ const url2 = new URL(href);
5393
+ const returned = url2.searchParams.get("request_id");
5394
+ if (!returned) return null;
5395
+ if (options.href === void 0 && g.history) g.history.replaceState(g.history.state, "", withoutConsentReturn(url2));
5396
+ let ownId = options.requestId;
5397
+ if (ownId === void 0) {
5398
+ try {
5399
+ ownId = consentStorage()?.getItem(CONSENT_STORAGE_KEY) ?? void 0;
5400
+ } catch {
5401
+ ownId = void 0;
5402
+ }
5403
+ }
5404
+ if (!ownId) {
5405
+ throw new CalimeroError(200, "CONSENT_NOT_STARTED", "this page started no consent request", { returned });
5406
+ }
5407
+ if (returned !== ownId) {
5408
+ throw new CalimeroError(200, "CONSENT_REQUEST_MISMATCH", "the consent page returned another request than this page started", {
5409
+ requestId: ownId,
5410
+ returned
5411
+ });
5412
+ }
5413
+ let result;
5414
+ try {
5415
+ result = await this.consent.pageResult({ request: ownId });
5416
+ } catch (e) {
5417
+ if (e instanceof NotFound) {
5418
+ forgetConsent(ownId);
5419
+ throw new CalimeroError(404, "CONSENT_REPLACED", "this page's consent request was replaced by a newer one", {
5420
+ requestId: ownId
5421
+ });
5422
+ }
5423
+ throw e;
5424
+ }
5425
+ if (result.requestId !== ownId) {
5426
+ throw new CalimeroError(200, "CONSENT_REQUEST_MISMATCH", "the node answered another request", { requestId: ownId, returned: result.requestId });
5427
+ }
5428
+ if (result.status === "pending") {
5429
+ throw new CalimeroError(200, "CONSENT_NOT_DECIDED", "the consent page returned, but this request is still pending", {
5430
+ requestId: ownId
5431
+ });
5432
+ }
5433
+ forgetConsent(ownId);
5434
+ return result;
5435
+ }
4722
5436
  /**
4723
5437
  * Poll `client.consent.pageResult` until the request is decided, every
4724
5438
  * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
@@ -4740,6 +5454,20 @@ var CalimeroClient = class _CalimeroClient {
4740
5454
  // ---------------------------------------------------------------- deployers
4741
5455
  // ---------------------------------------------------------------- deployments
4742
5456
  };
5457
+ function consentStorage() {
5458
+ try {
5459
+ return globalThis.sessionStorage;
5460
+ } catch {
5461
+ return void 0;
5462
+ }
5463
+ }
5464
+ function forgetConsent(requestId) {
5465
+ try {
5466
+ const store = consentStorage();
5467
+ if (store?.getItem(CONSENT_STORAGE_KEY) === requestId) store.removeItem(CONSENT_STORAGE_KEY);
5468
+ } catch {
5469
+ }
5470
+ }
4743
5471
 
4744
5472
  // src/client/capabilities.ts
4745
5473
  var ORG_CAPABILITIES = {
@@ -5276,11 +6004,11 @@ async function openDataKey(header, secret) {
5276
6004
  if (hex(recipient.publicKey) !== header.recipient) {
5277
6005
  throw new Error("this key is not the one the file was sealed to");
5278
6006
  }
5279
- const enc = fromHex(header.enc, "encapsulated key", 32);
5280
- const dhValue = await dh(recipient.privateKey, enc);
6007
+ const enc2 = fromHex(header.enc, "encapsulated key", 32);
6008
+ const dhValue = await dh(recipient.privateKey, enc2);
5281
6009
  const empty = new Uint8Array(0);
5282
6010
  const prk = await labeledExtract2(KEM_SUITE2, empty, "eae_prk", dhValue);
5283
- const shared = await labeledExpand2(KEM_SUITE2, prk, "shared_secret", concat(enc, recipient.publicKey), 32);
6011
+ const shared = await labeledExpand2(KEM_SUITE2, prk, "shared_secret", concat(enc2, recipient.publicKey), 32);
5284
6012
  const pskIdHash = await labeledExtract2(HPKE_SUITE2, empty, "psk_id_hash", empty);
5285
6013
  const infoHash = await labeledExtract2(HPKE_SUITE2, empty, "info_hash", HPKE_INFO);
5286
6014
  const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);
@@ -5304,23 +6032,23 @@ async function openDataKey(header, secret) {
5304
6032
  return plain;
5305
6033
  }
5306
6034
  async function holderRecoveryBody(holder, files, secret, options = {}) {
5307
- const checked = [];
6035
+ const checked2 = [];
5308
6036
  for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
5309
6037
  const header = await verifyRecoveryHeader(f);
5310
6038
  if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);
5311
6039
  if (holderKey(header.holder) !== holderKey(holder)) {
5312
6040
  throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);
5313
6041
  }
5314
- checked.push({ name: f.name, header });
6042
+ checked2.push({ name: f.name, header });
5315
6043
  }
5316
6044
  const open = async (c) => ({
5317
6045
  file: c.name,
5318
6046
  key: hex(await openDataKey(c.header, secret))
5319
6047
  });
5320
- const slice = checked.filter((c) => c.header.kind === "holder").pop();
6048
+ const slice = checked2.filter((c) => c.header.kind === "holder").pop();
5321
6049
  if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);
5322
6050
  const newestByApp = /* @__PURE__ */ new Map();
5323
- for (const c of checked) {
6051
+ for (const c of checked2) {
5324
6052
  if (c.header.kind === "app" && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {
5325
6053
  newestByApp.set(c.header.app, c);
5326
6054
  }
@@ -5329,10 +6057,10 @@ async function holderRecoveryBody(holder, files, secret, options = {}) {
5329
6057
  holder: holderKey(holder),
5330
6058
  slice: await open(slice),
5331
6059
  apps: await Promise.all([...newestByApp.values()].map(open)),
5332
- code: await Promise.all(checked.filter((c) => c.header.kind === "code").map(open))
6060
+ code: await Promise.all(checked2.filter((c) => c.header.kind === "code").map(open))
5333
6061
  };
5334
6062
  }
5335
- async function sha2562(data) {
6063
+ async function sha2564(data) {
5336
6064
  return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
5337
6065
  }
5338
6066
  async function recoveryAttestationNonce(cluster, node) {
@@ -5341,11 +6069,11 @@ async function recoveryAttestationNonce(cluster, node) {
5341
6069
  new DataView(len.buffer).setUint32(0, name.length, false);
5342
6070
  const id = new Uint8Array(8);
5343
6071
  new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
5344
- return hex(await sha2562(concat(utf85("calimero.recovery-backup.attest.v1\0"), len, name, id)));
6072
+ return hex(await sha2564(concat(utf85("calimero.recovery-backup.attest.v1\0"), len, name, id)));
5345
6073
  }
5346
6074
  async function receiptKeyBinding(receiptKey, governance) {
5347
- const g = await sha2562(utf85(JSON.stringify(governance)));
5348
- return hex(await sha2562(concat(utf85("calimero.tee-attest.receipt-key.v2"), receiptKey, g)));
6075
+ const g = await sha2564(utf85(JSON.stringify(governance)));
6076
+ return hex(await sha2564(concat(utf85("calimero.tee-attest.receipt-key.v2"), receiptKey, g)));
5349
6077
  }
5350
6078
  async function verifyRecoveryAttestation(header, verifyQuote) {
5351
6079
  const doc = header.attestation;
@@ -5369,6 +6097,7 @@ export {
5369
6097
  AppError,
5370
6098
  ArgsTooLarge,
5371
6099
  BadOrigin,
6100
+ CONSENT_STORAGE_KEY,
5372
6101
  CalimeroClient,
5373
6102
  CalimeroError,
5374
6103
  ClusterNotUpgraded,
@@ -5382,6 +6111,7 @@ export {
5382
6111
  DEFAULT_RELEASE_MIRROR,
5383
6112
  DEFAULT_RETRY,
5384
6113
  DirectoryError,
6114
+ ExportError,
5385
6115
  FILE_PART_BYTES,
5386
6116
  FeatureNotActive,
5387
6117
  GITHUB_RELEASES,
@@ -5420,6 +6150,7 @@ export {
5420
6150
  UnavailableError,
5421
6151
  WrongNode,
5422
6152
  WrongRecoveryCode,
6153
+ acceptInviteConsent,
5423
6154
  agentKeyBinding,
5424
6155
  agentQuoteVerifier,
5425
6156
  attestAgent,
@@ -5432,6 +6163,8 @@ export {
5432
6163
  compareVersions,
5433
6164
  confirmationCode,
5434
6165
  consentReturn,
6166
+ createInviteConsent,
6167
+ createOrgConsent,
5435
6168
  createQuoteVerifier,
5436
6169
  createRouteClient,
5437
6170
  createRoutes,
@@ -5490,6 +6223,7 @@ export {
5490
6223
  verifyReleaseUrl,
5491
6224
  verifySignedAgentPolicy,
5492
6225
  verifySignedNodeRelease,
5493
- withdrawConsent
6226
+ withdrawConsent,
6227
+ withoutConsentReturn
5494
6228
  };
5495
6229
  //# sourceMappingURL=index.mjs.map