@calimero-network/mero-js 33.0.0 → 33.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.
package/dist/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export { DEFAULT_RETRY, NodeTransport, directoryTransport, newIdempotencyKey, qu
4
4
  export type { DirectorySource, HttpMethod, NodeTransportOptions, QueryValue, RequestOptions, Transport, } from './runtime/transport.js';
5
5
  export * from './sealed/index.js';
6
6
  export * from './agent-gate/index.js';
7
+ export * from './recovery/backup-files.js';
package/dist/index.js CHANGED
@@ -22,3 +22,5 @@ export * from './sealed/index.js';
22
22
  // Private agents (mero-tee's agent gate): attest one, claim it with your key,
23
23
  // give it its secrets sealed to its TD.
24
24
  export * from './agent-gate/index.js';
25
+ // The recovery disk's files as their holder's device opens them.
26
+ export * from './recovery/backup-files.js';
package/dist/index.mjs CHANGED
@@ -1810,6 +1810,10 @@ var NodeTransport = class {
1810
1810
  };
1811
1811
  this.raw = raw;
1812
1812
  }
1813
+ /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */
1814
+ isNetworkFailure(error) {
1815
+ return error instanceof TypeError && this.networkFailures.has(error);
1816
+ }
1813
1817
  /** Re-read the node list from `source` when it is due, and after a failover. */
1814
1818
  useDirectory(source) {
1815
1819
  this.source = source;
@@ -4270,6 +4274,11 @@ function upgradeConsent(app, toVersion, returnTo) {
4270
4274
  }
4271
4275
 
4272
4276
  // src/client/calimero-client.ts
4277
+ var FILE_PART_BYTES = 16 * 1024 * 1024;
4278
+ var PART_RESENDS = 1;
4279
+ var MAX_FAILURES = 8;
4280
+ var MAX_JUMPS = 16;
4281
+ var CALL_RETRIES = 8;
4273
4282
  function deployerKey(deployer) {
4274
4283
  return "account" in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
4275
4284
  }
@@ -4300,6 +4309,15 @@ function toHex(bytes) {
4300
4309
  function presenceState(state) {
4301
4310
  return state === null ? null : toHex(state);
4302
4311
  }
4312
+ async function readSlice(data, start, end) {
4313
+ if (data instanceof Blob) return new Uint8Array(await data.slice(start, end).arrayBuffer());
4314
+ return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);
4315
+ }
4316
+ function nextPart(answer, parts) {
4317
+ const next = answer?.next;
4318
+ if (typeof next === "number" && Number.isInteger(next) && next >= 0 && next <= parts) return next;
4319
+ throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);
4320
+ }
4303
4321
  var CalimeroClient = class _CalimeroClient {
4304
4322
  /**
4305
4323
  * A client for the Calimero Cloud cluster named `cluster`: its node list read
@@ -4536,6 +4554,84 @@ var CalimeroClient = class _CalimeroClient {
4536
4554
  async downloadBlobGranted(app, id, grant) {
4537
4555
  return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());
4538
4556
  }
4557
+ /**
4558
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
4559
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
4560
+ * file for each, so one that may have reached it is never repeated); a larger file
4561
+ * is a session of parts, each sent again after a dropped connection or a `503`.
4562
+ * A session the node lost is begun again once; any other failure aborts it.
4563
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
4564
+ */
4565
+ async uploadFile(app, data) {
4566
+ const size = data instanceof Blob ? data.size : data.byteLength;
4567
+ if (size <= FILE_PART_BYTES) return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });
4568
+ try {
4569
+ return await this.uploadSession(app, data, size);
4570
+ } catch (error) {
4571
+ if (!(error instanceof CalimeroError) || error.code !== "UPLOAD_UNKNOWN") throw error;
4572
+ return this.uploadSession(app, data, size);
4573
+ }
4574
+ }
4575
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
4576
+ async uploadSession(app, data, size) {
4577
+ const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));
4578
+ const { uploadId: upload, partBytes, parts } = begin;
4579
+ if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {
4580
+ throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);
4581
+ }
4582
+ try {
4583
+ await this.sendParts(app, upload, data, size, partBytes, parts);
4584
+ return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));
4585
+ } catch (error) {
4586
+ if (!(error instanceof CalimeroError && error.code === "UPLOAD_UNKNOWN")) await this.apps.uploadAbort({ app, upload }).catch(() => void 0);
4587
+ throw error;
4588
+ }
4589
+ }
4590
+ /** Send every part, in order, from wherever the node says the session is. */
4591
+ async sendParts(app, upload, data, size, partBytes, parts) {
4592
+ let [next, failures, jumps] = [0, 0, 0];
4593
+ while (next < parts) {
4594
+ try {
4595
+ const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));
4596
+ next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);
4597
+ failures = 0;
4598
+ continue;
4599
+ } catch (error) {
4600
+ if (error instanceof CalimeroError && error.code === "PART_OUT_OF_ORDER") {
4601
+ jumps += 1;
4602
+ if (jumps > MAX_JUMPS) throw error;
4603
+ next = nextPart(error.details, parts);
4604
+ continue;
4605
+ }
4606
+ if (!this.isTransient(error) || ++failures > MAX_FAILURES) throw error;
4607
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));
4608
+ if (failures > PART_RESENDS) {
4609
+ try {
4610
+ const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);
4611
+ if (at > next) failures = 0;
4612
+ next = at;
4613
+ } catch (asked) {
4614
+ if (!this.isTransient(asked)) throw asked;
4615
+ }
4616
+ }
4617
+ }
4618
+ }
4619
+ }
4620
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
4621
+ async untilAvailable(send) {
4622
+ for (let retry = 0; ; retry++) {
4623
+ try {
4624
+ return await send();
4625
+ } catch (error) {
4626
+ if (!this.isTransient(error) || retry >= CALL_RETRIES) throw error;
4627
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));
4628
+ }
4629
+ }
4630
+ }
4631
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
4632
+ isTransient(error) {
4633
+ return error instanceof UnavailableError || this.transport.isNetworkFailure(error);
4634
+ }
4539
4635
  // ---------------------------------------------------------------- packages
4540
4636
  // ---------------------------------------------------------------- app instances
4541
4637
  /** Committed events from index `from`, then live, until `signal` aborts. */
@@ -5112,6 +5208,160 @@ function agentQuoteVerifier(policy, options) {
5112
5208
  allowedRtmr3: policy.allowed_rtmr3.map(register)
5113
5209
  });
5114
5210
  }
5211
+
5212
+ // src/recovery/backup-files.ts
5213
+ var RECOVERY_FORMAT = 1;
5214
+ var SIGNING_LABEL = new TextEncoder().encode("calimero.recovery-backup.v1\0");
5215
+ var HPKE_INFO = new TextEncoder().encode("calimero.recovery-backup.v1");
5216
+ var HPKE_AAD = new TextEncoder().encode("calimero.recovery-backup.key.v1");
5217
+ var KEM_ID2 = 32;
5218
+ var KDF_ID2 = 1;
5219
+ var AEAD_ID2 = 2;
5220
+ var MODE_BASE = 0;
5221
+ var utf85 = (s) => new TextEncoder().encode(s);
5222
+ var i2osp22 = (n) => new Uint8Array([n >> 8 & 255, n & 255]);
5223
+ var KEM_SUITE2 = concat(utf85("KEM"), i2osp22(KEM_ID2));
5224
+ var HPKE_SUITE2 = concat(utf85("HPKE"), i2osp22(KEM_ID2), i2osp22(KDF_ID2), i2osp22(AEAD_ID2));
5225
+ function holderKey(holder) {
5226
+ return holder.kind === "operator" ? "operator" : `${holder.kind}:${holder.id}`;
5227
+ }
5228
+ async function newBackupKeyPair() {
5229
+ const secret = crypto.getRandomValues(new Uint8Array(32));
5230
+ return { secret, publicKey: await backupPublicKey(secret) };
5231
+ }
5232
+ async function backupPublicKey(secret) {
5233
+ return hex((await x25519KeyPair(secret)).publicKey);
5234
+ }
5235
+ async function verifyRecoveryHeader(file) {
5236
+ const bytes = utf85(file.header);
5237
+ const header = JSON.parse(file.header);
5238
+ if (typeof header.format !== "number" || header.format > RECOVERY_FORMAT) {
5239
+ throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);
5240
+ }
5241
+ const key = await crypto.subtle.importKey(
5242
+ "raw",
5243
+ fromHex(header.signingKey, "signing key", 32),
5244
+ { name: "Ed25519" },
5245
+ false,
5246
+ ["verify"]
5247
+ );
5248
+ const ok = await crypto.subtle.verify(
5249
+ "Ed25519",
5250
+ key,
5251
+ fromHex(file.signature, "signature", 64),
5252
+ concat(SIGNING_LABEL, bytes)
5253
+ );
5254
+ if (!ok) throw new Error("the node's signature over the header does not hold");
5255
+ return header;
5256
+ }
5257
+ async function hmac2(key, data) {
5258
+ const raw = key.length === 0 ? new Uint8Array(32) : key;
5259
+ const k = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
5260
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
5261
+ }
5262
+ async function expand2(prk, info, length) {
5263
+ const out = new Uint8Array(length);
5264
+ let previous = new Uint8Array(0);
5265
+ for (let i = 1, offset = 0; offset < length; i += 1) {
5266
+ previous = await hmac2(prk, concat(previous, info, new Uint8Array([i])));
5267
+ out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
5268
+ offset += previous.length;
5269
+ }
5270
+ return out;
5271
+ }
5272
+ var labeledExtract2 = (suite, salt, label, ikm) => hmac2(salt, concat(utf85("HPKE-v1"), suite, utf85(label), ikm));
5273
+ var labeledExpand2 = (suite, prk, label, info, length) => expand2(prk, concat(i2osp22(length), utf85("HPKE-v1"), suite, utf85(label), info), length);
5274
+ async function openDataKey(header, secret) {
5275
+ const recipient = await x25519KeyPair(secret);
5276
+ if (hex(recipient.publicKey) !== header.recipient) {
5277
+ throw new Error("this key is not the one the file was sealed to");
5278
+ }
5279
+ const enc = fromHex(header.enc, "encapsulated key", 32);
5280
+ const dhValue = await dh(recipient.privateKey, enc);
5281
+ const empty = new Uint8Array(0);
5282
+ 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);
5284
+ const pskIdHash = await labeledExtract2(HPKE_SUITE2, empty, "psk_id_hash", empty);
5285
+ const infoHash = await labeledExtract2(HPKE_SUITE2, empty, "info_hash", HPKE_INFO);
5286
+ const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);
5287
+ const schedule = await labeledExtract2(HPKE_SUITE2, shared, "secret", empty);
5288
+ const key = await labeledExpand2(HPKE_SUITE2, schedule, "key", context, 32);
5289
+ const nonce2 = await labeledExpand2(HPKE_SUITE2, schedule, "base_nonce", context, 12);
5290
+ const aes = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
5291
+ let plain;
5292
+ try {
5293
+ plain = new Uint8Array(
5294
+ await crypto.subtle.decrypt(
5295
+ { name: "AES-GCM", iv: nonce2, additionalData: HPKE_AAD },
5296
+ aes,
5297
+ fromHex(header.wrappedKey, "wrapped key", 48)
5298
+ )
5299
+ );
5300
+ } catch {
5301
+ throw new Error("this key does not open the file");
5302
+ }
5303
+ if (plain.length !== 32) throw new Error("the data key is not 32 bytes");
5304
+ return plain;
5305
+ }
5306
+ async function holderRecoveryBody(holder, files, secret, options = {}) {
5307
+ const checked = [];
5308
+ for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
5309
+ const header = await verifyRecoveryHeader(f);
5310
+ if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);
5311
+ if (holderKey(header.holder) !== holderKey(holder)) {
5312
+ throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);
5313
+ }
5314
+ checked.push({ name: f.name, header });
5315
+ }
5316
+ const open = async (c) => ({
5317
+ file: c.name,
5318
+ key: hex(await openDataKey(c.header, secret))
5319
+ });
5320
+ const slice = checked.filter((c) => c.header.kind === "holder").pop();
5321
+ if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);
5322
+ const newestByApp = /* @__PURE__ */ new Map();
5323
+ for (const c of checked) {
5324
+ if (c.header.kind === "app" && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {
5325
+ newestByApp.set(c.header.app, c);
5326
+ }
5327
+ }
5328
+ return {
5329
+ holder: holderKey(holder),
5330
+ slice: await open(slice),
5331
+ apps: await Promise.all([...newestByApp.values()].map(open)),
5332
+ code: await Promise.all(checked.filter((c) => c.header.kind === "code").map(open))
5333
+ };
5334
+ }
5335
+ async function sha2562(data) {
5336
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
5337
+ }
5338
+ async function recoveryAttestationNonce(cluster, node) {
5339
+ const name = utf85(cluster);
5340
+ const len = new Uint8Array(4);
5341
+ new DataView(len.buffer).setUint32(0, name.length, false);
5342
+ const id = new Uint8Array(8);
5343
+ 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)));
5345
+ }
5346
+ 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)));
5349
+ }
5350
+ async function verifyRecoveryAttestation(header, verifyQuote) {
5351
+ const doc = header.attestation;
5352
+ if (!doc || typeof doc.quote !== "string") throw new Error("the file carries no attestation");
5353
+ if (doc.cluster !== header.cluster || doc.node !== header.node) {
5354
+ throw new Error("the attestation is another node's");
5355
+ }
5356
+ if (doc.receiptKey !== header.signingKey) {
5357
+ throw new Error("the attested key is not the one that signed the file");
5358
+ }
5359
+ const nonce2 = await recoveryAttestationNonce(header.cluster, header.node);
5360
+ if (doc.nonce !== nonce2) throw new Error("the attestation is not over the recovery nonce");
5361
+ const reportDataSuffix = await receiptKeyBinding(fromHex(header.signingKey, "signing key", 32), doc.governance);
5362
+ const ok = await verifyQuote({ quoteB64: doc.quote, nonce: nonce2, reportDataSuffix });
5363
+ if (!ok) throw new Error("the quote was not accepted");
5364
+ }
5115
5365
  export {
5116
5366
  AGENT_ATTEST_DOMAIN,
5117
5367
  AGENT_PROVISION_INFO_DOMAIN,
@@ -5132,9 +5382,12 @@ export {
5132
5382
  DEFAULT_RELEASE_MIRROR,
5133
5383
  DEFAULT_RETRY,
5134
5384
  DirectoryError,
5385
+ FILE_PART_BYTES,
5135
5386
  FeatureNotActive,
5136
5387
  GITHUB_RELEASES,
5137
5388
  HANDSHAKE_PATH,
5389
+ HPKE_AAD,
5390
+ HPKE_INFO,
5138
5391
  IdempotencyMismatch,
5139
5392
  KMS_RELEASE_SIGNER,
5140
5393
  LoginRequired,
@@ -5152,12 +5405,14 @@ export {
5152
5405
  PasskeyUnknownHere,
5153
5406
  QuotaExceeded,
5154
5407
  RECOVERY_DOMAIN,
5408
+ RECOVERY_FORMAT,
5155
5409
  RELEASE_VERIFIER,
5156
5410
  RecoveryNotReady,
5157
5411
  ReleaseDeadlineError,
5158
5412
  RuntimeTooOld,
5159
5413
  SEALED_CONTENT_TYPE,
5160
5414
  SEALED_PATH,
5415
+ SIGNING_LABEL,
5161
5416
  SealedTransportError,
5162
5417
  SignUpRefused,
5163
5418
  StaleTransportKeyError,
@@ -5169,6 +5424,7 @@ export {
5169
5424
  agentQuoteVerifier,
5170
5425
  attestAgent,
5171
5426
  b64url,
5427
+ backupPublicKey,
5172
5428
  browserPasskey,
5173
5429
  checkOwner,
5174
5430
  claimedRelease,
@@ -5191,8 +5447,12 @@ export {
5191
5447
  fromB64url,
5192
5448
  frontendManifest,
5193
5449
  generateOwnerKey,
5450
+ holderKey,
5451
+ holderRecoveryBody,
5452
+ newBackupKeyPair,
5194
5453
  newIdempotencyKey,
5195
5454
  newRecoverySeed,
5455
+ openDataKey,
5196
5456
  orgCapabilities,
5197
5457
  ownerPublicKey,
5198
5458
  pageDeployment,
@@ -5206,6 +5466,8 @@ export {
5206
5466
  publisherBindingBytes,
5207
5467
  publisherBindingMessage,
5208
5468
  queryString,
5469
+ receiptKeyBinding,
5470
+ recoveryAttestationNonce,
5209
5471
  recoveryMessage,
5210
5472
  recoveryPublicKey,
5211
5473
  recoverySeedText,
@@ -5223,6 +5485,8 @@ export {
5223
5485
  trustedMeasurementsFromReleases,
5224
5486
  upgradeConsent,
5225
5487
  validateAgentId,
5488
+ verifyRecoveryAttestation,
5489
+ verifyRecoveryHeader,
5226
5490
  verifyReleaseUrl,
5227
5491
  verifySignedAgentPolicy,
5228
5492
  verifySignedNodeRelease,