@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.cjs CHANGED
@@ -48,9 +48,12 @@ __export(index_exports, {
48
48
  DEFAULT_RELEASE_MIRROR: () => DEFAULT_RELEASE_MIRROR,
49
49
  DEFAULT_RETRY: () => DEFAULT_RETRY,
50
50
  DirectoryError: () => DirectoryError,
51
+ FILE_PART_BYTES: () => FILE_PART_BYTES,
51
52
  FeatureNotActive: () => FeatureNotActive,
52
53
  GITHUB_RELEASES: () => GITHUB_RELEASES,
53
54
  HANDSHAKE_PATH: () => HANDSHAKE_PATH,
55
+ HPKE_AAD: () => HPKE_AAD,
56
+ HPKE_INFO: () => HPKE_INFO,
54
57
  IdempotencyMismatch: () => IdempotencyMismatch,
55
58
  KMS_RELEASE_SIGNER: () => KMS_RELEASE_SIGNER,
56
59
  LoginRequired: () => LoginRequired,
@@ -68,12 +71,14 @@ __export(index_exports, {
68
71
  PasskeyUnknownHere: () => PasskeyUnknownHere,
69
72
  QuotaExceeded: () => QuotaExceeded,
70
73
  RECOVERY_DOMAIN: () => RECOVERY_DOMAIN,
74
+ RECOVERY_FORMAT: () => RECOVERY_FORMAT,
71
75
  RELEASE_VERIFIER: () => RELEASE_VERIFIER,
72
76
  RecoveryNotReady: () => RecoveryNotReady,
73
77
  ReleaseDeadlineError: () => ReleaseDeadlineError,
74
78
  RuntimeTooOld: () => RuntimeTooOld,
75
79
  SEALED_CONTENT_TYPE: () => SEALED_CONTENT_TYPE,
76
80
  SEALED_PATH: () => SEALED_PATH,
81
+ SIGNING_LABEL: () => SIGNING_LABEL,
77
82
  SealedTransportError: () => SealedTransportError,
78
83
  SignUpRefused: () => SignUpRefused,
79
84
  StaleTransportKeyError: () => StaleTransportKeyError,
@@ -85,6 +90,7 @@ __export(index_exports, {
85
90
  agentQuoteVerifier: () => agentQuoteVerifier,
86
91
  attestAgent: () => attestAgent,
87
92
  b64url: () => b64url,
93
+ backupPublicKey: () => backupPublicKey,
88
94
  browserPasskey: () => browserPasskey,
89
95
  checkOwner: () => checkOwner,
90
96
  claimedRelease: () => claimedRelease,
@@ -107,8 +113,12 @@ __export(index_exports, {
107
113
  fromB64url: () => fromB64url,
108
114
  frontendManifest: () => frontendManifest,
109
115
  generateOwnerKey: () => generateOwnerKey,
116
+ holderKey: () => holderKey,
117
+ holderRecoveryBody: () => holderRecoveryBody,
118
+ newBackupKeyPair: () => newBackupKeyPair,
110
119
  newIdempotencyKey: () => newIdempotencyKey,
111
120
  newRecoverySeed: () => newRecoverySeed,
121
+ openDataKey: () => openDataKey,
112
122
  orgCapabilities: () => orgCapabilities,
113
123
  ownerPublicKey: () => ownerPublicKey,
114
124
  pageDeployment: () => pageDeployment,
@@ -122,6 +132,8 @@ __export(index_exports, {
122
132
  publisherBindingBytes: () => publisherBindingBytes,
123
133
  publisherBindingMessage: () => publisherBindingMessage,
124
134
  queryString: () => queryString,
135
+ receiptKeyBinding: () => receiptKeyBinding,
136
+ recoveryAttestationNonce: () => recoveryAttestationNonce,
125
137
  recoveryMessage: () => recoveryMessage,
126
138
  recoveryPublicKey: () => recoveryPublicKey,
127
139
  recoverySeedText: () => recoverySeedText,
@@ -139,6 +151,8 @@ __export(index_exports, {
139
151
  trustedMeasurementsFromReleases: () => trustedMeasurementsFromReleases,
140
152
  upgradeConsent: () => upgradeConsent,
141
153
  validateAgentId: () => validateAgentId,
154
+ verifyRecoveryAttestation: () => verifyRecoveryAttestation,
155
+ verifyRecoveryHeader: () => verifyRecoveryHeader,
142
156
  verifyReleaseUrl: () => verifyReleaseUrl,
143
157
  verifySignedAgentPolicy: () => verifySignedAgentPolicy,
144
158
  verifySignedNodeRelease: () => verifySignedNodeRelease,
@@ -1958,6 +1972,10 @@ var NodeTransport = class {
1958
1972
  };
1959
1973
  this.raw = raw;
1960
1974
  }
1975
+ /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */
1976
+ isNetworkFailure(error) {
1977
+ return error instanceof TypeError && this.networkFailures.has(error);
1978
+ }
1961
1979
  /** Re-read the node list from `source` when it is due, and after a failover. */
1962
1980
  useDirectory(source) {
1963
1981
  this.source = source;
@@ -4418,6 +4436,11 @@ function upgradeConsent(app, toVersion, returnTo) {
4418
4436
  }
4419
4437
 
4420
4438
  // src/client/calimero-client.ts
4439
+ var FILE_PART_BYTES = 16 * 1024 * 1024;
4440
+ var PART_RESENDS = 1;
4441
+ var MAX_FAILURES = 8;
4442
+ var MAX_JUMPS = 16;
4443
+ var CALL_RETRIES = 8;
4421
4444
  function deployerKey(deployer) {
4422
4445
  return "account" in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
4423
4446
  }
@@ -4448,6 +4471,15 @@ function toHex(bytes) {
4448
4471
  function presenceState(state) {
4449
4472
  return state === null ? null : toHex(state);
4450
4473
  }
4474
+ async function readSlice(data, start, end) {
4475
+ if (data instanceof Blob) return new Uint8Array(await data.slice(start, end).arrayBuffer());
4476
+ return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);
4477
+ }
4478
+ function nextPart(answer, parts) {
4479
+ const next = answer?.next;
4480
+ if (typeof next === "number" && Number.isInteger(next) && next >= 0 && next <= parts) return next;
4481
+ throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);
4482
+ }
4451
4483
  var CalimeroClient = class _CalimeroClient {
4452
4484
  /**
4453
4485
  * A client for the Calimero Cloud cluster named `cluster`: its node list read
@@ -4684,6 +4716,84 @@ var CalimeroClient = class _CalimeroClient {
4684
4716
  async downloadBlobGranted(app, id, grant) {
4685
4717
  return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());
4686
4718
  }
4719
+ /**
4720
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
4721
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
4722
+ * file for each, so one that may have reached it is never repeated); a larger file
4723
+ * is a session of parts, each sent again after a dropped connection or a `503`.
4724
+ * A session the node lost is begun again once; any other failure aborts it.
4725
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
4726
+ */
4727
+ async uploadFile(app, data) {
4728
+ const size = data instanceof Blob ? data.size : data.byteLength;
4729
+ if (size <= FILE_PART_BYTES) return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });
4730
+ try {
4731
+ return await this.uploadSession(app, data, size);
4732
+ } catch (error) {
4733
+ if (!(error instanceof CalimeroError) || error.code !== "UPLOAD_UNKNOWN") throw error;
4734
+ return this.uploadSession(app, data, size);
4735
+ }
4736
+ }
4737
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
4738
+ async uploadSession(app, data, size) {
4739
+ const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));
4740
+ const { uploadId: upload, partBytes, parts } = begin;
4741
+ if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {
4742
+ throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);
4743
+ }
4744
+ try {
4745
+ await this.sendParts(app, upload, data, size, partBytes, parts);
4746
+ return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));
4747
+ } catch (error) {
4748
+ if (!(error instanceof CalimeroError && error.code === "UPLOAD_UNKNOWN")) await this.apps.uploadAbort({ app, upload }).catch(() => void 0);
4749
+ throw error;
4750
+ }
4751
+ }
4752
+ /** Send every part, in order, from wherever the node says the session is. */
4753
+ async sendParts(app, upload, data, size, partBytes, parts) {
4754
+ let [next, failures, jumps] = [0, 0, 0];
4755
+ while (next < parts) {
4756
+ try {
4757
+ const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));
4758
+ next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);
4759
+ failures = 0;
4760
+ continue;
4761
+ } catch (error) {
4762
+ if (error instanceof CalimeroError && error.code === "PART_OUT_OF_ORDER") {
4763
+ jumps += 1;
4764
+ if (jumps > MAX_JUMPS) throw error;
4765
+ next = nextPart(error.details, parts);
4766
+ continue;
4767
+ }
4768
+ if (!this.isTransient(error) || ++failures > MAX_FAILURES) throw error;
4769
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));
4770
+ if (failures > PART_RESENDS) {
4771
+ try {
4772
+ const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);
4773
+ if (at > next) failures = 0;
4774
+ next = at;
4775
+ } catch (asked) {
4776
+ if (!this.isTransient(asked)) throw asked;
4777
+ }
4778
+ }
4779
+ }
4780
+ }
4781
+ }
4782
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
4783
+ async untilAvailable(send) {
4784
+ for (let retry = 0; ; retry++) {
4785
+ try {
4786
+ return await send();
4787
+ } catch (error) {
4788
+ if (!this.isTransient(error) || retry >= CALL_RETRIES) throw error;
4789
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));
4790
+ }
4791
+ }
4792
+ }
4793
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
4794
+ isTransient(error) {
4795
+ return error instanceof UnavailableError || this.transport.isNetworkFailure(error);
4796
+ }
4687
4797
  // ---------------------------------------------------------------- packages
4688
4798
  // ---------------------------------------------------------------- app instances
4689
4799
  /** Committed events from index `from`, then live, until `signal` aborts. */
@@ -5260,4 +5370,158 @@ function agentQuoteVerifier(policy, options) {
5260
5370
  allowedRtmr3: policy.allowed_rtmr3.map(register)
5261
5371
  });
5262
5372
  }
5373
+
5374
+ // src/recovery/backup-files.ts
5375
+ var RECOVERY_FORMAT = 1;
5376
+ var SIGNING_LABEL = new TextEncoder().encode("calimero.recovery-backup.v1\0");
5377
+ var HPKE_INFO = new TextEncoder().encode("calimero.recovery-backup.v1");
5378
+ var HPKE_AAD = new TextEncoder().encode("calimero.recovery-backup.key.v1");
5379
+ var KEM_ID2 = 32;
5380
+ var KDF_ID2 = 1;
5381
+ var AEAD_ID2 = 2;
5382
+ var MODE_BASE = 0;
5383
+ var utf85 = (s) => new TextEncoder().encode(s);
5384
+ var i2osp22 = (n) => new Uint8Array([n >> 8 & 255, n & 255]);
5385
+ var KEM_SUITE2 = concat(utf85("KEM"), i2osp22(KEM_ID2));
5386
+ var HPKE_SUITE2 = concat(utf85("HPKE"), i2osp22(KEM_ID2), i2osp22(KDF_ID2), i2osp22(AEAD_ID2));
5387
+ function holderKey(holder) {
5388
+ return holder.kind === "operator" ? "operator" : `${holder.kind}:${holder.id}`;
5389
+ }
5390
+ async function newBackupKeyPair() {
5391
+ const secret = crypto.getRandomValues(new Uint8Array(32));
5392
+ return { secret, publicKey: await backupPublicKey(secret) };
5393
+ }
5394
+ async function backupPublicKey(secret) {
5395
+ return hex((await x25519KeyPair(secret)).publicKey);
5396
+ }
5397
+ async function verifyRecoveryHeader(file) {
5398
+ const bytes = utf85(file.header);
5399
+ const header = JSON.parse(file.header);
5400
+ if (typeof header.format !== "number" || header.format > RECOVERY_FORMAT) {
5401
+ throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);
5402
+ }
5403
+ const key = await crypto.subtle.importKey(
5404
+ "raw",
5405
+ fromHex(header.signingKey, "signing key", 32),
5406
+ { name: "Ed25519" },
5407
+ false,
5408
+ ["verify"]
5409
+ );
5410
+ const ok = await crypto.subtle.verify(
5411
+ "Ed25519",
5412
+ key,
5413
+ fromHex(file.signature, "signature", 64),
5414
+ concat(SIGNING_LABEL, bytes)
5415
+ );
5416
+ if (!ok) throw new Error("the node's signature over the header does not hold");
5417
+ return header;
5418
+ }
5419
+ async function hmac2(key, data) {
5420
+ const raw = key.length === 0 ? new Uint8Array(32) : key;
5421
+ const k = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
5422
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
5423
+ }
5424
+ async function expand2(prk, info, length) {
5425
+ const out = new Uint8Array(length);
5426
+ let previous = new Uint8Array(0);
5427
+ for (let i = 1, offset = 0; offset < length; i += 1) {
5428
+ previous = await hmac2(prk, concat(previous, info, new Uint8Array([i])));
5429
+ out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
5430
+ offset += previous.length;
5431
+ }
5432
+ return out;
5433
+ }
5434
+ var labeledExtract2 = (suite, salt, label, ikm) => hmac2(salt, concat(utf85("HPKE-v1"), suite, utf85(label), ikm));
5435
+ var labeledExpand2 = (suite, prk, label, info, length) => expand2(prk, concat(i2osp22(length), utf85("HPKE-v1"), suite, utf85(label), info), length);
5436
+ async function openDataKey(header, secret) {
5437
+ const recipient = await x25519KeyPair(secret);
5438
+ if (hex(recipient.publicKey) !== header.recipient) {
5439
+ throw new Error("this key is not the one the file was sealed to");
5440
+ }
5441
+ const enc = fromHex(header.enc, "encapsulated key", 32);
5442
+ const dhValue = await dh(recipient.privateKey, enc);
5443
+ const empty = new Uint8Array(0);
5444
+ const prk = await labeledExtract2(KEM_SUITE2, empty, "eae_prk", dhValue);
5445
+ const shared = await labeledExpand2(KEM_SUITE2, prk, "shared_secret", concat(enc, recipient.publicKey), 32);
5446
+ const pskIdHash = await labeledExtract2(HPKE_SUITE2, empty, "psk_id_hash", empty);
5447
+ const infoHash = await labeledExtract2(HPKE_SUITE2, empty, "info_hash", HPKE_INFO);
5448
+ const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);
5449
+ const schedule = await labeledExtract2(HPKE_SUITE2, shared, "secret", empty);
5450
+ const key = await labeledExpand2(HPKE_SUITE2, schedule, "key", context, 32);
5451
+ const nonce2 = await labeledExpand2(HPKE_SUITE2, schedule, "base_nonce", context, 12);
5452
+ const aes = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
5453
+ let plain;
5454
+ try {
5455
+ plain = new Uint8Array(
5456
+ await crypto.subtle.decrypt(
5457
+ { name: "AES-GCM", iv: nonce2, additionalData: HPKE_AAD },
5458
+ aes,
5459
+ fromHex(header.wrappedKey, "wrapped key", 48)
5460
+ )
5461
+ );
5462
+ } catch {
5463
+ throw new Error("this key does not open the file");
5464
+ }
5465
+ if (plain.length !== 32) throw new Error("the data key is not 32 bytes");
5466
+ return plain;
5467
+ }
5468
+ async function holderRecoveryBody(holder, files, secret, options = {}) {
5469
+ const checked = [];
5470
+ for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
5471
+ const header = await verifyRecoveryHeader(f);
5472
+ if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);
5473
+ if (holderKey(header.holder) !== holderKey(holder)) {
5474
+ throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);
5475
+ }
5476
+ checked.push({ name: f.name, header });
5477
+ }
5478
+ const open = async (c) => ({
5479
+ file: c.name,
5480
+ key: hex(await openDataKey(c.header, secret))
5481
+ });
5482
+ const slice = checked.filter((c) => c.header.kind === "holder").pop();
5483
+ if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);
5484
+ const newestByApp = /* @__PURE__ */ new Map();
5485
+ for (const c of checked) {
5486
+ if (c.header.kind === "app" && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {
5487
+ newestByApp.set(c.header.app, c);
5488
+ }
5489
+ }
5490
+ return {
5491
+ holder: holderKey(holder),
5492
+ slice: await open(slice),
5493
+ apps: await Promise.all([...newestByApp.values()].map(open)),
5494
+ code: await Promise.all(checked.filter((c) => c.header.kind === "code").map(open))
5495
+ };
5496
+ }
5497
+ async function sha2562(data) {
5498
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
5499
+ }
5500
+ async function recoveryAttestationNonce(cluster, node) {
5501
+ const name = utf85(cluster);
5502
+ const len = new Uint8Array(4);
5503
+ new DataView(len.buffer).setUint32(0, name.length, false);
5504
+ const id = new Uint8Array(8);
5505
+ new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
5506
+ return hex(await sha2562(concat(utf85("calimero.recovery-backup.attest.v1\0"), len, name, id)));
5507
+ }
5508
+ async function receiptKeyBinding(receiptKey, governance) {
5509
+ const g = await sha2562(utf85(JSON.stringify(governance)));
5510
+ return hex(await sha2562(concat(utf85("calimero.tee-attest.receipt-key.v2"), receiptKey, g)));
5511
+ }
5512
+ async function verifyRecoveryAttestation(header, verifyQuote) {
5513
+ const doc = header.attestation;
5514
+ if (!doc || typeof doc.quote !== "string") throw new Error("the file carries no attestation");
5515
+ if (doc.cluster !== header.cluster || doc.node !== header.node) {
5516
+ throw new Error("the attestation is another node's");
5517
+ }
5518
+ if (doc.receiptKey !== header.signingKey) {
5519
+ throw new Error("the attested key is not the one that signed the file");
5520
+ }
5521
+ const nonce2 = await recoveryAttestationNonce(header.cluster, header.node);
5522
+ if (doc.nonce !== nonce2) throw new Error("the attestation is not over the recovery nonce");
5523
+ const reportDataSuffix = await receiptKeyBinding(fromHex(header.signingKey, "signing key", 32), doc.governance);
5524
+ const ok = await verifyQuote({ quoteB64: doc.quote, nonce: nonce2, reportDataSuffix });
5525
+ if (!ok) throw new Error("the quote was not accepted");
5526
+ }
5263
5527
  //# sourceMappingURL=index.cjs.map