@calimero-network/mero-js 35.2.0 → 35.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.cjs CHANGED
@@ -181,6 +181,8 @@ __export(index_exports, {
181
181
  trustedMeasurementsFromReleases: () => trustedMeasurementsFromReleases,
182
182
  upgradeConsent: () => upgradeConsent,
183
183
  validateAgentId: () => validateAgentId,
184
+ verifyNode: () => verifyNode,
185
+ verifyNodeUrl: () => verifyNodeUrl,
184
186
  verifyRecoveryAttestation: () => verifyRecoveryAttestation,
185
187
  verifyRecoveryHeader: () => verifyRecoveryHeader,
186
188
  verifyReleaseUrl: () => verifyReleaseUrl,
@@ -1364,18 +1366,54 @@ function claimedRelease(doc, minReleaseVersion) {
1364
1366
  }
1365
1367
  return version;
1366
1368
  }
1369
+ var Unanswered = class extends Error {
1370
+ constructor(host, status, cause) {
1371
+ super(status ? `${host} answered HTTP ${status}` : `${host} could not be reached: ${cause?.message}`);
1372
+ this.host = host;
1373
+ this.status = status;
1374
+ this.cause = cause;
1375
+ }
1376
+ };
1377
+ function unanswered(host, error) {
1378
+ return error instanceof TypeError ? new Unanswered(host, void 0, error) : error;
1379
+ }
1380
+ var unansweredStatus = (status) => status === 429 || status >= 500;
1381
+ function answered(fetchImpl, host) {
1382
+ return async (input, init) => {
1383
+ const response = await fetchImpl(input, init).catch((error) => {
1384
+ throw unanswered(host, error);
1385
+ });
1386
+ if (unansweredStatus(response.status)) throw new Unanswered(host, response.status);
1387
+ const body = await response.arrayBuffer().catch((error) => {
1388
+ throw unanswered(host, error);
1389
+ });
1390
+ return new Response(body, response);
1391
+ };
1392
+ }
1367
1393
  async function releaseFor(version, policy, fetchImpl) {
1368
1394
  const source = policy.releaseSource;
1369
1395
  if (typeof source === "function") return source(version);
1370
- if (source === "github") return fetchGithubNodeRelease(version, { fetch: fetchImpl });
1371
- return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchImpl });
1396
+ const fetchMirror = answered(fetchImpl, "the release mirror");
1397
+ if (source === "github") return fetchGithubNodeRelease(version, { fetch: fetchMirror });
1398
+ return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchMirror });
1372
1399
  }
1373
1400
  function defaultCollateral(policy) {
1374
1401
  const source = policy.collateralSource ?? DEFAULT_COLLATERAL_MIRROR;
1375
1402
  if (source === "intel") {
1376
- return async (quote) => (await dcap("getCollateralFromPcs"))(quote);
1403
+ return async (quote) => {
1404
+ const get = await dcap("getCollateralFromPcs");
1405
+ return get(quote).catch((error) => {
1406
+ throw unanswered("Intel PCS", error);
1407
+ });
1408
+ };
1377
1409
  }
1378
- return async (quote) => (await dcap("getCollateral"))(source, quote);
1410
+ new URL(source);
1411
+ return async (quote) => {
1412
+ const get = await dcap("getCollateral");
1413
+ return get(source, quote).catch((error) => {
1414
+ throw unanswered(source, error);
1415
+ });
1416
+ };
1379
1417
  }
1380
1418
  function freshCollateral(fetch2, policy) {
1381
1419
  const maxDays = policy.maxCollateralAgeDays;
@@ -1400,9 +1438,14 @@ function freshCollateral(fetch2, policy) {
1400
1438
  }
1401
1439
  async function verifyRelease(doc, args, policy, fetchImpl) {
1402
1440
  const version = claimedRelease(doc, policy.minReleaseVersion);
1441
+ const profile = policy.profile ?? PRODUCTION_PROFILE;
1442
+ const release = await releaseFor(version, policy, fetchImpl);
1443
+ if (release.version !== version) {
1444
+ throw new Error(`The node names mero-tee release ${version}, but the release served is ${release.version}`);
1445
+ }
1403
1446
  const trusted = await trustSignedRelease({
1404
- release: await releaseFor(version, policy, fetchImpl),
1405
- profile: policy.profile ?? PRODUCTION_PROFILE,
1447
+ release,
1448
+ profile,
1406
1449
  allowDebugProfile: policy.allowDebugProfile,
1407
1450
  minReleaseVersion: policy.minReleaseVersion,
1408
1451
  identity: policy.identity,
@@ -1415,21 +1458,44 @@ async function verifyRelease(doc, args, policy, fetchImpl) {
1415
1458
  now: policy.now,
1416
1459
  ...trusted
1417
1460
  });
1418
- return verifier(args);
1461
+ return await verifier(args) ? { release: version, profile } : void 0;
1419
1462
  }
1420
1463
  async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
1464
+ return (await verifyNode(baseUrl, policy, fetchImpl)).key;
1465
+ }
1466
+ function nodeBoundAppHash(doc, policy) {
1467
+ const bound = fromHex(doc.appHash, "appHash", 32);
1468
+ if (bound.every((byte) => byte === 0)) throw new Error("The node bound no app: its app hash is all zero");
1469
+ if (policy.appHash && hex(bound) !== policy.appHash.toLowerCase()) {
1470
+ throw new Error(`The node's app hash ${hex(bound)} is not the pinned ${policy.appHash}`);
1471
+ }
1472
+ return bound;
1473
+ }
1474
+ async function verifyNode(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
1475
+ const url2 = baseUrl.replace(/\/+$/, "");
1421
1476
  const nonce2 = hex(crypto.getRandomValues(new Uint8Array(32)));
1422
- const url2 = new URL(`${baseUrl.replace(/\/+$/, "")}/attestation`);
1423
- url2.searchParams.set("nonce", nonce2);
1424
- if (policy.appHash) url2.searchParams.set("appHash", policy.appHash);
1425
- const response = await fetchImpl(url2.toString());
1477
+ const attestation = new URL(`${url2}/attestation`);
1478
+ attestation.searchParams.set("nonce", nonce2);
1479
+ if (policy.app) attestation.searchParams.set("app", policy.app);
1480
+ else if (policy.appHash) attestation.searchParams.set("appHash", policy.appHash);
1481
+ const response = await fetchImpl(attestation.toString());
1482
+ if (unansweredStatus(response.status)) throw new Unanswered("the node", response.status);
1426
1483
  if (!response.ok) throw new Error(`The node refused to attest: HTTP ${response.status}`);
1427
- const doc = await response.json();
1484
+ const doc = await response.json().catch((error) => {
1485
+ throw unanswered("the node", error);
1486
+ });
1428
1487
  const transportKey = fromHex(doc.transportKey, "transportKey", 32);
1429
- const inner = policy.appHash ? fromHex(policy.appHash, "appHash", 32) : new Uint8Array(32);
1488
+ const boundApp = policy.app ? nodeBoundAppHash(doc, policy) : void 0;
1489
+ const inner = boundApp ?? (policy.appHash ? fromHex(policy.appHash, "appHash", 32) : new Uint8Array(32));
1430
1490
  const suffix = await transportKeyBinding(inner, transportKey);
1431
1491
  const quote = base64ToBytes(doc.quote);
1432
1492
  const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);
1493
+ const verification = (facts2) => ({
1494
+ url: url2,
1495
+ ...facts2,
1496
+ ...boundApp ? { appHash: hex(boundApp) } : {},
1497
+ checkedAt: Date.now()
1498
+ });
1433
1499
  if (equal2(quote.slice(0, header.length), header)) {
1434
1500
  if (!policy.allowMock) {
1435
1501
  throw new Error("mock quote refused: this client only trusts real TEEs");
@@ -1438,19 +1504,19 @@ async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init) => fe
1438
1504
  if (!equal2(report.slice(0, 32), fromHex(nonce2, "nonce", 32)) || !equal2(report.slice(32), suffix)) {
1439
1505
  throw new Error("the quote does not bind this transport key, app and nonce");
1440
1506
  }
1441
- return transportKey;
1507
+ return { key: transportKey, verification: verification({ mock: true }) };
1442
1508
  }
1443
1509
  const args = { quoteB64: doc.quote, nonce: nonce2, reportDataSuffix: hex(suffix) };
1444
- let ok;
1510
+ let facts;
1445
1511
  if (policy.verifyQuote) {
1446
- ok = await policy.verifyQuote(args);
1512
+ facts = await policy.verifyQuote(args) ? {} : void 0;
1447
1513
  } else if (policy.release) {
1448
- ok = await verifyRelease(doc, args, policy.release, fetchImpl);
1514
+ facts = await verifyRelease(doc, args, policy.release, fetchImpl);
1449
1515
  } else {
1450
1516
  throw new Error("real quote refused: this client trusts no TD image (set policy.release)");
1451
1517
  }
1452
- if (!ok) throw new Error("The attestation did not verify, so its transport key is not trusted");
1453
- return transportKey;
1518
+ if (!facts) throw new Error("The attestation did not verify, so its transport key is not trusted");
1519
+ return { key: transportKey, verification: verification({ mock: false, ...facts }) };
1454
1520
  }
1455
1521
 
1456
1522
  // src/runtime/directory.ts
@@ -1998,6 +2064,11 @@ var NodeTransport = class {
1998
2064
  this.at = 0;
1999
2065
  /** A sealed fetch per node, each attesting its own node on first use. */
2000
2066
  this.channels = /* @__PURE__ */ new Map();
2067
+ /** The latest attestation check of each node, and the attempt it came from. */
2068
+ this.checks = /* @__PURE__ */ new Map();
2069
+ this.attempts = /* @__PURE__ */ new Map();
2070
+ /** The transport key each node's channel was attested to. */
2071
+ this.keys = /* @__PURE__ */ new Map();
2001
2072
  /** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */
2002
2073
  this.networkFailures = /* @__PURE__ */ new WeakSet();
2003
2074
  const trim = (url2) => url2.replace(/\/+$/, "");
@@ -2015,9 +2086,9 @@ var NodeTransport = class {
2015
2086
  };
2016
2087
  this.raw = raw;
2017
2088
  }
2018
- /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */
2089
+ /** Whether `error` is a host that gave no answer: a `fetch` that failed, or an attestation input left {@link Unanswered}. */
2019
2090
  isNetworkFailure(error) {
2020
- return error instanceof TypeError && this.networkFailures.has(error);
2091
+ return error instanceof TypeError && this.networkFailures.has(error) || error instanceof Unanswered;
2021
2092
  }
2022
2093
  /** Re-read the node list from `source` when it is due, and after a failover. */
2023
2094
  useDirectory(source) {
@@ -2051,16 +2122,94 @@ var NodeTransport = class {
2051
2122
  }
2052
2123
  /** The sealed channel to `url`, attested under the policy before its first request. */
2053
2124
  channel(url2) {
2054
- let sealed = this.channels.get(url2);
2055
- if (!sealed) {
2056
- sealed = createSealedFetch({
2125
+ let channel = this.channels.get(url2);
2126
+ if (!channel) {
2127
+ const live = () => this.channels.get(url2) === sealed;
2128
+ let first;
2129
+ const sealed = createSealedFetch({
2057
2130
  baseUrl: url2,
2058
- transportPublicKey: () => fetchAttestedKey(url2, this.policy, this.raw),
2131
+ transportPublicKey: () => {
2132
+ const key = first ?? this.attest(url2, live);
2133
+ first = void 0;
2134
+ return key;
2135
+ },
2059
2136
  fetch: this.raw
2060
2137
  });
2061
2138
  this.channels.set(url2, sealed);
2139
+ first = this.attest(url2, live);
2140
+ channel = sealed;
2141
+ }
2142
+ return channel;
2143
+ }
2144
+ /** Attest node `url` for the channel `live` tells is in use, keeping what the check verified or why it failed. */
2145
+ attest(url2, live) {
2146
+ if (!live()) return verifyNode(url2, this.policy, this.raw).then(({ key }) => key);
2147
+ this.checks.set(url2, { status: "checking", url: url2 });
2148
+ const attempt = verifyNode(url2, this.policy, this.raw).then(
2149
+ ({ key, verification }) => {
2150
+ if (live()) {
2151
+ this.checks.set(url2, { status: "verified", ...verification });
2152
+ this.keys.set(url2, key);
2153
+ }
2154
+ return key;
2155
+ },
2156
+ (error) => {
2157
+ const reason = error instanceof Error ? error.message : String(error);
2158
+ const unreachable = this.isNetworkFailure(error);
2159
+ if (live()) {
2160
+ this.checks.set(url2, { status: unreachable ? "unreachable" : "refused", url: url2, reason, checkedAt: Date.now() });
2161
+ if (unreachable) this.channels.delete(url2);
2162
+ }
2163
+ throw error;
2164
+ }
2165
+ );
2166
+ attempt.catch(() => void 0);
2167
+ this.attempts.set(url2, attempt);
2168
+ return attempt;
2169
+ }
2170
+ /** What the client's check of node `url` (a URL from `nodes`; default: the one in use) established; `undefined` before it is first used. */
2171
+ verification(url2 = this.nodeUrl) {
2172
+ return this.checks.get(url2);
2173
+ }
2174
+ /**
2175
+ * Attest `app` on node `url` (a URL from `nodes`; default: the one in use): the record's
2176
+ * `appHash` is the one the node bound. Throws on refusal, or when the quote's key is not the channel's.
2177
+ */
2178
+ async attestApp(app, url2 = this.nodeUrl) {
2179
+ const pinned = this.policy.app === app ? this.policy.appHash : void 0;
2180
+ const policy = { ...this.policy, app, appHash: pinned };
2181
+ await this.settled(url2);
2182
+ let attested = await verifyNode(url2, policy, this.raw);
2183
+ if (!this.sameKey(url2, attested.key)) {
2184
+ this.channels.delete(url2);
2185
+ await this.settled(url2);
2186
+ attested = await verifyNode(url2, policy, this.raw);
2187
+ if (!this.sameKey(url2, attested.key)) {
2188
+ throw new Error("The node attested the app under another transport key than its channel");
2189
+ }
2190
+ }
2191
+ return attested.verification;
2192
+ }
2193
+ /** The settled check of node `url`; throws the reason when it failed. */
2194
+ async settled(url2) {
2195
+ const state = await this.verify(url2);
2196
+ if (state.status === "refused" || state.status === "unreachable") throw new Error(state.reason);
2197
+ }
2198
+ sameKey(url2, key) {
2199
+ const channelKey = this.keys.get(url2);
2200
+ return channelKey !== void 0 && hex(channelKey) === hex(key);
2201
+ }
2202
+ /**
2203
+ * Start the check of node `url` if none runs and answer its settled outcome, without a request or a repeat.
2204
+ * `checkedAt` is when that check ran; a failure is answered, not thrown.
2205
+ */
2206
+ async verify(url2 = this.nodeUrl) {
2207
+ this.channel(url2);
2208
+ for (; ; ) {
2209
+ const attempt = this.attempts.get(url2);
2210
+ await attempt?.catch(() => void 0);
2211
+ if (this.attempts.get(url2) === attempt) return this.checks.get(url2);
2062
2212
  }
2063
- return sealed;
2064
2213
  }
2065
2214
  /**
2066
2215
  * Move on from node `from` (the one that answered `421 WRONG_NODE`) to the
@@ -4998,12 +5147,7 @@ async function exportFileTo(transport, app, id, sink, signal, recipientSecret) {
4998
5147
  }
4999
5148
  async function exportChecked(transport, app, id, sink, signal, recipientSecret) {
5000
5149
  const recipient = await x25519KeyPair(recipientSecret);
5001
- const answer = checked(
5002
- await transport.json("POST", routePath("apps/{app}/files/{id}/export", { app, id }), {
5003
- body: { recipient: hex(recipient.publicKey) },
5004
- signal
5005
- })
5006
- );
5150
+ const answer = checked(await transport.exportsExport({ app, id, recipient: hex(recipient.publicKey) }, { signal }));
5007
5151
  const { segments, named } = answer;
5008
5152
  if (segments.length === 0 || hex(await fileId(segments)) !== hex(named) || hex(named) !== id) {
5009
5153
  throw new ExportError("NOT_THE_FILE", `the node answered segments that are not the file ${id}`);
@@ -5164,8 +5308,14 @@ var RELEASE_VERIFIER = "https://mero-tee.vercel.app";
5164
5308
  function releaseNotesUrl(version) {
5165
5309
  return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;
5166
5310
  }
5311
+ function verifierUrl(query) {
5312
+ return `${RELEASE_VERIFIER}/mero-tee?${new URLSearchParams(query)}`;
5313
+ }
5167
5314
  function verifyReleaseUrl(version) {
5168
- return `${RELEASE_VERIFIER}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${version}`)}`;
5315
+ return verifierUrl({ release_tag: `mero-tee-v${version}` });
5316
+ }
5317
+ function verifyNodeUrl(nodeUrl, release) {
5318
+ return verifierUrl({ node_url: nodeUrl.replace(/\/+$/, ""), release_tag: `mero-tee-v${release}` });
5169
5319
  }
5170
5320
  function pendingApprovalsFrom(report, rules, now = Date.now() / 1e3) {
5171
5321
  const deadlineOf = (v) => rules.deadlines.find((d) => d.version === v) ?? null;
@@ -5355,6 +5505,14 @@ var CalimeroClient = class _CalimeroClient {
5355
5505
  get nodes() {
5356
5506
  return this.transport.nodes;
5357
5507
  }
5508
+ /** What the check of node `url` (from {@link nodes}; default: in use) established, or `undefined` before it first ran. */
5509
+ verification(url2) {
5510
+ return this.transport.verification(url2);
5511
+ }
5512
+ /** Wait for the check requests wait for, starting it if needed, and answer its outcome (not thrown) without a request. */
5513
+ verify(url2) {
5514
+ return this.transport.verify(url2);
5515
+ }
5358
5516
  /** Authenticate every request with an API key. */
5359
5517
  useApiKey(key) {
5360
5518
  this.transport.useApiKey(key);
@@ -5369,6 +5527,18 @@ var CalimeroClient = class _CalimeroClient {
5369
5527
  json(method, path, body) {
5370
5528
  return this.transport.json(method, path, { body });
5371
5529
  }
5530
+ /** Attest `app` on node `url` (from {@link nodes}; default: in use): the record's `appHash` is the one the node bound. */
5531
+ attestApp(app, url2) {
5532
+ return this.transport.attestApp(app, url2);
5533
+ }
5534
+ /** The manifest facts and ABI of a package version (of `service`, for a multi-service release), for a signed-in caller. */
5535
+ packageCapabilities(pkg, version, options = {}) {
5536
+ return this.transport.json(
5537
+ "GET",
5538
+ routePath("packages/{package}/{version}/capabilities", { package: pkg, version }),
5539
+ { query: { service: options.service } }
5540
+ );
5541
+ }
5372
5542
  // ---------------------------------------------------------------- identity
5373
5543
  /**
5374
5544
  * Create an account with a new passkey, and sign in. The node then asks the
@@ -5534,17 +5704,20 @@ var CalimeroClient = class _CalimeroClient {
5534
5704
  async downloadBlob(app, id) {
5535
5705
  return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());
5536
5706
  }
5707
+ get exportClient() {
5708
+ return { exportsExport: this.apps.exportsExport, request: this.transport.request.bind(this.transport) };
5709
+ }
5537
5710
  /**
5538
5711
  * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,
5539
5712
  * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of
5540
5713
  * the file. A failed check is an `ExportError`; `signal` aborts the download.
5541
5714
  */
5542
5715
  exportFileTo(app, id, sink, signal) {
5543
- return exportFileTo(this.transport, app, id, sink, signal);
5716
+ return exportFileTo(this.exportClient, app, id, sink, signal);
5544
5717
  }
5545
5718
  /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */
5546
5719
  exportFile(app, id, signal) {
5547
- return exportFile(this.transport, app, id, signal);
5720
+ return exportFile(this.exportClient, app, id, signal);
5548
5721
  }
5549
5722
  /**
5550
5723
  * Download a component app's blob with a grant one of its runs handed out