@calimero-network/mero-js 35.2.1 → 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.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export * from './client/index.js';
2
2
  export * from './routes/index.js';
3
3
  export { DEFAULT_RETRY, NodeTransport, directoryTransport, newIdempotencyKey, queryString, refusal, retryDelayMs, routePath, sseFrames, } from './runtime/transport.js';
4
- export type { DirectorySource, HttpMethod, NodeTransportOptions, QueryValue, RequestOptions, Transport, } from './runtime/transport.js';
4
+ export type { DirectorySource, HttpMethod, NodeTransportOptions, NodeVerificationState, QueryValue, RequestOptions, Transport, } from './runtime/transport.js';
5
5
  export * from './sealed/index.js';
6
6
  export * from './agent-gate/index.js';
7
7
  export * from './recovery/backup-files.js';
package/dist/index.mjs CHANGED
@@ -1174,18 +1174,54 @@ function claimedRelease(doc, minReleaseVersion) {
1174
1174
  }
1175
1175
  return version;
1176
1176
  }
1177
+ var Unanswered = class extends Error {
1178
+ constructor(host, status, cause) {
1179
+ super(status ? `${host} answered HTTP ${status}` : `${host} could not be reached: ${cause?.message}`);
1180
+ this.host = host;
1181
+ this.status = status;
1182
+ this.cause = cause;
1183
+ }
1184
+ };
1185
+ function unanswered(host, error) {
1186
+ return error instanceof TypeError ? new Unanswered(host, void 0, error) : error;
1187
+ }
1188
+ var unansweredStatus = (status) => status === 429 || status >= 500;
1189
+ function answered(fetchImpl, host) {
1190
+ return async (input, init) => {
1191
+ const response = await fetchImpl(input, init).catch((error) => {
1192
+ throw unanswered(host, error);
1193
+ });
1194
+ if (unansweredStatus(response.status)) throw new Unanswered(host, response.status);
1195
+ const body = await response.arrayBuffer().catch((error) => {
1196
+ throw unanswered(host, error);
1197
+ });
1198
+ return new Response(body, response);
1199
+ };
1200
+ }
1177
1201
  async function releaseFor(version, policy, fetchImpl) {
1178
1202
  const source = policy.releaseSource;
1179
1203
  if (typeof source === "function") return source(version);
1180
- if (source === "github") return fetchGithubNodeRelease(version, { fetch: fetchImpl });
1181
- return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchImpl });
1204
+ const fetchMirror = answered(fetchImpl, "the release mirror");
1205
+ if (source === "github") return fetchGithubNodeRelease(version, { fetch: fetchMirror });
1206
+ return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchMirror });
1182
1207
  }
1183
1208
  function defaultCollateral(policy) {
1184
1209
  const source = policy.collateralSource ?? DEFAULT_COLLATERAL_MIRROR;
1185
1210
  if (source === "intel") {
1186
- return async (quote) => (await dcap("getCollateralFromPcs"))(quote);
1211
+ return async (quote) => {
1212
+ const get = await dcap("getCollateralFromPcs");
1213
+ return get(quote).catch((error) => {
1214
+ throw unanswered("Intel PCS", error);
1215
+ });
1216
+ };
1187
1217
  }
1188
- return async (quote) => (await dcap("getCollateral"))(source, quote);
1218
+ new URL(source);
1219
+ return async (quote) => {
1220
+ const get = await dcap("getCollateral");
1221
+ return get(source, quote).catch((error) => {
1222
+ throw unanswered(source, error);
1223
+ });
1224
+ };
1189
1225
  }
1190
1226
  function freshCollateral(fetch2, policy) {
1191
1227
  const maxDays = policy.maxCollateralAgeDays;
@@ -1210,9 +1246,14 @@ function freshCollateral(fetch2, policy) {
1210
1246
  }
1211
1247
  async function verifyRelease(doc, args, policy, fetchImpl) {
1212
1248
  const version = claimedRelease(doc, policy.minReleaseVersion);
1249
+ const profile = policy.profile ?? PRODUCTION_PROFILE;
1250
+ const release = await releaseFor(version, policy, fetchImpl);
1251
+ if (release.version !== version) {
1252
+ throw new Error(`The node names mero-tee release ${version}, but the release served is ${release.version}`);
1253
+ }
1213
1254
  const trusted = await trustSignedRelease({
1214
- release: await releaseFor(version, policy, fetchImpl),
1215
- profile: policy.profile ?? PRODUCTION_PROFILE,
1255
+ release,
1256
+ profile,
1216
1257
  allowDebugProfile: policy.allowDebugProfile,
1217
1258
  minReleaseVersion: policy.minReleaseVersion,
1218
1259
  identity: policy.identity,
@@ -1225,21 +1266,44 @@ async function verifyRelease(doc, args, policy, fetchImpl) {
1225
1266
  now: policy.now,
1226
1267
  ...trusted
1227
1268
  });
1228
- return verifier(args);
1269
+ return await verifier(args) ? { release: version, profile } : void 0;
1229
1270
  }
1230
1271
  async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
1272
+ return (await verifyNode(baseUrl, policy, fetchImpl)).key;
1273
+ }
1274
+ function nodeBoundAppHash(doc, policy) {
1275
+ const bound = fromHex(doc.appHash, "appHash", 32);
1276
+ if (bound.every((byte) => byte === 0)) throw new Error("The node bound no app: its app hash is all zero");
1277
+ if (policy.appHash && hex(bound) !== policy.appHash.toLowerCase()) {
1278
+ throw new Error(`The node's app hash ${hex(bound)} is not the pinned ${policy.appHash}`);
1279
+ }
1280
+ return bound;
1281
+ }
1282
+ async function verifyNode(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
1283
+ const url2 = baseUrl.replace(/\/+$/, "");
1231
1284
  const nonce2 = hex(crypto.getRandomValues(new Uint8Array(32)));
1232
- const url2 = new URL(`${baseUrl.replace(/\/+$/, "")}/attestation`);
1233
- url2.searchParams.set("nonce", nonce2);
1234
- if (policy.appHash) url2.searchParams.set("appHash", policy.appHash);
1235
- const response = await fetchImpl(url2.toString());
1285
+ const attestation = new URL(`${url2}/attestation`);
1286
+ attestation.searchParams.set("nonce", nonce2);
1287
+ if (policy.app) attestation.searchParams.set("app", policy.app);
1288
+ else if (policy.appHash) attestation.searchParams.set("appHash", policy.appHash);
1289
+ const response = await fetchImpl(attestation.toString());
1290
+ if (unansweredStatus(response.status)) throw new Unanswered("the node", response.status);
1236
1291
  if (!response.ok) throw new Error(`The node refused to attest: HTTP ${response.status}`);
1237
- const doc = await response.json();
1292
+ const doc = await response.json().catch((error) => {
1293
+ throw unanswered("the node", error);
1294
+ });
1238
1295
  const transportKey = fromHex(doc.transportKey, "transportKey", 32);
1239
- const inner = policy.appHash ? fromHex(policy.appHash, "appHash", 32) : new Uint8Array(32);
1296
+ const boundApp = policy.app ? nodeBoundAppHash(doc, policy) : void 0;
1297
+ const inner = boundApp ?? (policy.appHash ? fromHex(policy.appHash, "appHash", 32) : new Uint8Array(32));
1240
1298
  const suffix = await transportKeyBinding(inner, transportKey);
1241
1299
  const quote = base64ToBytes(doc.quote);
1242
1300
  const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);
1301
+ const verification = (facts2) => ({
1302
+ url: url2,
1303
+ ...facts2,
1304
+ ...boundApp ? { appHash: hex(boundApp) } : {},
1305
+ checkedAt: Date.now()
1306
+ });
1243
1307
  if (equal2(quote.slice(0, header.length), header)) {
1244
1308
  if (!policy.allowMock) {
1245
1309
  throw new Error("mock quote refused: this client only trusts real TEEs");
@@ -1248,19 +1312,19 @@ async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init) => fe
1248
1312
  if (!equal2(report.slice(0, 32), fromHex(nonce2, "nonce", 32)) || !equal2(report.slice(32), suffix)) {
1249
1313
  throw new Error("the quote does not bind this transport key, app and nonce");
1250
1314
  }
1251
- return transportKey;
1315
+ return { key: transportKey, verification: verification({ mock: true }) };
1252
1316
  }
1253
1317
  const args = { quoteB64: doc.quote, nonce: nonce2, reportDataSuffix: hex(suffix) };
1254
- let ok;
1318
+ let facts;
1255
1319
  if (policy.verifyQuote) {
1256
- ok = await policy.verifyQuote(args);
1320
+ facts = await policy.verifyQuote(args) ? {} : void 0;
1257
1321
  } else if (policy.release) {
1258
- ok = await verifyRelease(doc, args, policy.release, fetchImpl);
1322
+ facts = await verifyRelease(doc, args, policy.release, fetchImpl);
1259
1323
  } else {
1260
1324
  throw new Error("real quote refused: this client trusts no TD image (set policy.release)");
1261
1325
  }
1262
- if (!ok) throw new Error("The attestation did not verify, so its transport key is not trusted");
1263
- return transportKey;
1326
+ if (!facts) throw new Error("The attestation did not verify, so its transport key is not trusted");
1327
+ return { key: transportKey, verification: verification({ mock: false, ...facts }) };
1264
1328
  }
1265
1329
 
1266
1330
  // src/runtime/directory.ts
@@ -1808,6 +1872,11 @@ var NodeTransport = class {
1808
1872
  this.at = 0;
1809
1873
  /** A sealed fetch per node, each attesting its own node on first use. */
1810
1874
  this.channels = /* @__PURE__ */ new Map();
1875
+ /** The latest attestation check of each node, and the attempt it came from. */
1876
+ this.checks = /* @__PURE__ */ new Map();
1877
+ this.attempts = /* @__PURE__ */ new Map();
1878
+ /** The transport key each node's channel was attested to. */
1879
+ this.keys = /* @__PURE__ */ new Map();
1811
1880
  /** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */
1812
1881
  this.networkFailures = /* @__PURE__ */ new WeakSet();
1813
1882
  const trim = (url2) => url2.replace(/\/+$/, "");
@@ -1825,9 +1894,9 @@ var NodeTransport = class {
1825
1894
  };
1826
1895
  this.raw = raw;
1827
1896
  }
1828
- /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */
1897
+ /** Whether `error` is a host that gave no answer: a `fetch` that failed, or an attestation input left {@link Unanswered}. */
1829
1898
  isNetworkFailure(error) {
1830
- return error instanceof TypeError && this.networkFailures.has(error);
1899
+ return error instanceof TypeError && this.networkFailures.has(error) || error instanceof Unanswered;
1831
1900
  }
1832
1901
  /** Re-read the node list from `source` when it is due, and after a failover. */
1833
1902
  useDirectory(source) {
@@ -1861,16 +1930,94 @@ var NodeTransport = class {
1861
1930
  }
1862
1931
  /** The sealed channel to `url`, attested under the policy before its first request. */
1863
1932
  channel(url2) {
1864
- let sealed = this.channels.get(url2);
1865
- if (!sealed) {
1866
- sealed = createSealedFetch({
1933
+ let channel = this.channels.get(url2);
1934
+ if (!channel) {
1935
+ const live = () => this.channels.get(url2) === sealed;
1936
+ let first;
1937
+ const sealed = createSealedFetch({
1867
1938
  baseUrl: url2,
1868
- transportPublicKey: () => fetchAttestedKey(url2, this.policy, this.raw),
1939
+ transportPublicKey: () => {
1940
+ const key = first ?? this.attest(url2, live);
1941
+ first = void 0;
1942
+ return key;
1943
+ },
1869
1944
  fetch: this.raw
1870
1945
  });
1871
1946
  this.channels.set(url2, sealed);
1947
+ first = this.attest(url2, live);
1948
+ channel = sealed;
1949
+ }
1950
+ return channel;
1951
+ }
1952
+ /** Attest node `url` for the channel `live` tells is in use, keeping what the check verified or why it failed. */
1953
+ attest(url2, live) {
1954
+ if (!live()) return verifyNode(url2, this.policy, this.raw).then(({ key }) => key);
1955
+ this.checks.set(url2, { status: "checking", url: url2 });
1956
+ const attempt = verifyNode(url2, this.policy, this.raw).then(
1957
+ ({ key, verification }) => {
1958
+ if (live()) {
1959
+ this.checks.set(url2, { status: "verified", ...verification });
1960
+ this.keys.set(url2, key);
1961
+ }
1962
+ return key;
1963
+ },
1964
+ (error) => {
1965
+ const reason = error instanceof Error ? error.message : String(error);
1966
+ const unreachable = this.isNetworkFailure(error);
1967
+ if (live()) {
1968
+ this.checks.set(url2, { status: unreachable ? "unreachable" : "refused", url: url2, reason, checkedAt: Date.now() });
1969
+ if (unreachable) this.channels.delete(url2);
1970
+ }
1971
+ throw error;
1972
+ }
1973
+ );
1974
+ attempt.catch(() => void 0);
1975
+ this.attempts.set(url2, attempt);
1976
+ return attempt;
1977
+ }
1978
+ /** What the client's check of node `url` (a URL from `nodes`; default: the one in use) established; `undefined` before it is first used. */
1979
+ verification(url2 = this.nodeUrl) {
1980
+ return this.checks.get(url2);
1981
+ }
1982
+ /**
1983
+ * Attest `app` on node `url` (a URL from `nodes`; default: the one in use): the record's
1984
+ * `appHash` is the one the node bound. Throws on refusal, or when the quote's key is not the channel's.
1985
+ */
1986
+ async attestApp(app, url2 = this.nodeUrl) {
1987
+ const pinned = this.policy.app === app ? this.policy.appHash : void 0;
1988
+ const policy = { ...this.policy, app, appHash: pinned };
1989
+ await this.settled(url2);
1990
+ let attested = await verifyNode(url2, policy, this.raw);
1991
+ if (!this.sameKey(url2, attested.key)) {
1992
+ this.channels.delete(url2);
1993
+ await this.settled(url2);
1994
+ attested = await verifyNode(url2, policy, this.raw);
1995
+ if (!this.sameKey(url2, attested.key)) {
1996
+ throw new Error("The node attested the app under another transport key than its channel");
1997
+ }
1998
+ }
1999
+ return attested.verification;
2000
+ }
2001
+ /** The settled check of node `url`; throws the reason when it failed. */
2002
+ async settled(url2) {
2003
+ const state = await this.verify(url2);
2004
+ if (state.status === "refused" || state.status === "unreachable") throw new Error(state.reason);
2005
+ }
2006
+ sameKey(url2, key) {
2007
+ const channelKey = this.keys.get(url2);
2008
+ return channelKey !== void 0 && hex(channelKey) === hex(key);
2009
+ }
2010
+ /**
2011
+ * Start the check of node `url` if none runs and answer its settled outcome, without a request or a repeat.
2012
+ * `checkedAt` is when that check ran; a failure is answered, not thrown.
2013
+ */
2014
+ async verify(url2 = this.nodeUrl) {
2015
+ this.channel(url2);
2016
+ for (; ; ) {
2017
+ const attempt = this.attempts.get(url2);
2018
+ await attempt?.catch(() => void 0);
2019
+ if (this.attempts.get(url2) === attempt) return this.checks.get(url2);
1872
2020
  }
1873
- return sealed;
1874
2021
  }
1875
2022
  /**
1876
2023
  * Move on from node `from` (the one that answered `421 WRONG_NODE`) to the
@@ -4969,8 +5116,14 @@ var RELEASE_VERIFIER = "https://mero-tee.vercel.app";
4969
5116
  function releaseNotesUrl(version) {
4970
5117
  return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;
4971
5118
  }
5119
+ function verifierUrl(query) {
5120
+ return `${RELEASE_VERIFIER}/mero-tee?${new URLSearchParams(query)}`;
5121
+ }
4972
5122
  function verifyReleaseUrl(version) {
4973
- return `${RELEASE_VERIFIER}/mero-tee?release_tag=${encodeURIComponent(`mero-tee-v${version}`)}`;
5123
+ return verifierUrl({ release_tag: `mero-tee-v${version}` });
5124
+ }
5125
+ function verifyNodeUrl(nodeUrl, release) {
5126
+ return verifierUrl({ node_url: nodeUrl.replace(/\/+$/, ""), release_tag: `mero-tee-v${release}` });
4974
5127
  }
4975
5128
  function pendingApprovalsFrom(report, rules, now = Date.now() / 1e3) {
4976
5129
  const deadlineOf = (v) => rules.deadlines.find((d) => d.version === v) ?? null;
@@ -5160,6 +5313,14 @@ var CalimeroClient = class _CalimeroClient {
5160
5313
  get nodes() {
5161
5314
  return this.transport.nodes;
5162
5315
  }
5316
+ /** What the check of node `url` (from {@link nodes}; default: in use) established, or `undefined` before it first ran. */
5317
+ verification(url2) {
5318
+ return this.transport.verification(url2);
5319
+ }
5320
+ /** Wait for the check requests wait for, starting it if needed, and answer its outcome (not thrown) without a request. */
5321
+ verify(url2) {
5322
+ return this.transport.verify(url2);
5323
+ }
5163
5324
  /** Authenticate every request with an API key. */
5164
5325
  useApiKey(key) {
5165
5326
  this.transport.useApiKey(key);
@@ -5174,6 +5335,18 @@ var CalimeroClient = class _CalimeroClient {
5174
5335
  json(method, path, body) {
5175
5336
  return this.transport.json(method, path, { body });
5176
5337
  }
5338
+ /** Attest `app` on node `url` (from {@link nodes}; default: in use): the record's `appHash` is the one the node bound. */
5339
+ attestApp(app, url2) {
5340
+ return this.transport.attestApp(app, url2);
5341
+ }
5342
+ /** The manifest facts and ABI of a package version (of `service`, for a multi-service release), for a signed-in caller. */
5343
+ packageCapabilities(pkg, version, options = {}) {
5344
+ return this.transport.json(
5345
+ "GET",
5346
+ routePath("packages/{package}/{version}/capabilities", { package: pkg, version }),
5347
+ { query: { service: options.service } }
5348
+ );
5349
+ }
5177
5350
  // ---------------------------------------------------------------- identity
5178
5351
  /**
5179
5352
  * Create an account with a new passkey, and sign in. The node then asks the
@@ -6710,6 +6883,8 @@ export {
6710
6883
  trustedMeasurementsFromReleases,
6711
6884
  upgradeConsent,
6712
6885
  validateAgentId,
6886
+ verifyNode,
6887
+ verifyNodeUrl,
6713
6888
  verifyRecoveryAttestation,
6714
6889
  verifyRecoveryHeader,
6715
6890
  verifyReleaseUrl,