@calimero-network/mero-js 35.3.0 → 35.4.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,6 +1,6 @@
1
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);
2
+ var __defNormalProp = (obj2, key, value) => key in obj2 ? __defProp(obj2, key, { enumerable: true, configurable: true, writable: true, value }) : obj2[key] = value;
3
+ var __publicField = (obj2, key, value) => __defNormalProp(obj2, typeof key !== "symbol" ? key + "" : key, value);
4
4
 
5
5
  // src/crypto/internal.ts
6
6
  function hex(bytes) {
@@ -632,8 +632,8 @@ function parseCertificate(der) {
632
632
  const extensions = /* @__PURE__ */ new Map();
633
633
  const extensionsField = optional.find((field) => field.tag === CONTEXT_3);
634
634
  if (extensionsField) {
635
- const [list] = children(extensionsField);
636
- for (const extension of children(expectTag(list, SEQUENCE, "The extensions"))) {
635
+ const [list2] = children(extensionsField);
636
+ for (const extension of children(expectTag(list2, SEQUENCE, "The extensions"))) {
637
637
  const parts = children(expectTag(extension, SEQUENCE, "An extension"));
638
638
  if (parts.length === 3) expectTag(parts[1], BOOLEAN, "An extension's critical flag");
639
639
  else if (parts.length !== 2) throw new Error("it has a malformed extension");
@@ -878,7 +878,7 @@ function createQuoteVerifier(options) {
878
878
  if (allowedMrtd.length === 0) {
879
879
  throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");
880
880
  }
881
- if (allowedRtmr.slice(1).some((list) => list.length === 0)) {
881
+ if (allowedRtmr.slice(1).some((list2) => list2.length === 0)) {
882
882
  throw new Error(
883
883
  "allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too"
884
884
  );
@@ -1268,6 +1268,31 @@ async function verifyRelease(doc, args, policy, fetchImpl) {
1268
1268
  });
1269
1269
  return await verifier(args) ? { release: version, profile } : void 0;
1270
1270
  }
1271
+ async function verifyQuoteBinding(doc, nonce2, suffix, policy, what, fetchImpl = (input, init) => fetch(input, init)) {
1272
+ const quote = base64ToBytes(doc.quote);
1273
+ const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);
1274
+ if (equal2(quote.slice(0, header.length), header)) {
1275
+ if (!policy.allowMock) {
1276
+ throw new Error("mock quote refused: this client only trusts real TEEs");
1277
+ }
1278
+ const report = quote.slice(header.length, header.length + 64);
1279
+ if (!equal2(report.slice(0, 32), nonce2) || !equal2(report.slice(32), suffix)) {
1280
+ throw new Error(`the quote does not bind this ${what} and nonce`);
1281
+ }
1282
+ return { mock: true };
1283
+ }
1284
+ const args = { quoteB64: doc.quote, nonce: hex(nonce2), reportDataSuffix: hex(suffix) };
1285
+ let facts;
1286
+ if (policy.verifyQuote) {
1287
+ facts = await policy.verifyQuote(args) ? {} : void 0;
1288
+ } else if (policy.release) {
1289
+ facts = await verifyRelease(doc, args, policy.release, fetchImpl);
1290
+ } else {
1291
+ throw new Error("real quote refused: this client trusts no TD image (set policy.release)");
1292
+ }
1293
+ if (!facts) throw new Error(`The attestation did not verify, so its ${what} is not trusted`);
1294
+ return { mock: false, ...facts };
1295
+ }
1271
1296
  async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
1272
1297
  return (await verifyNode(baseUrl, policy, fetchImpl)).key;
1273
1298
  }
@@ -1296,35 +1321,14 @@ async function verifyNode(baseUrl, policy, fetchImpl = (input, init) => fetch(in
1296
1321
  const boundApp = policy.app ? nodeBoundAppHash(doc, policy) : void 0;
1297
1322
  const inner = boundApp ?? (policy.appHash ? fromHex(policy.appHash, "appHash", 32) : new Uint8Array(32));
1298
1323
  const suffix = await transportKeyBinding(inner, transportKey);
1299
- const quote = base64ToBytes(doc.quote);
1300
- const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);
1301
- const verification = (facts2) => ({
1324
+ const facts = await verifyQuoteBinding(doc, fromHex(nonce2, "nonce", 32), suffix, policy, "transport key", fetchImpl);
1325
+ const verification = {
1302
1326
  url: url2,
1303
- ...facts2,
1327
+ ...facts,
1304
1328
  ...boundApp ? { appHash: hex(boundApp) } : {},
1305
1329
  checkedAt: Date.now()
1306
- });
1307
- if (equal2(quote.slice(0, header.length), header)) {
1308
- if (!policy.allowMock) {
1309
- throw new Error("mock quote refused: this client only trusts real TEEs");
1310
- }
1311
- const report = quote.slice(header.length, header.length + 64);
1312
- if (!equal2(report.slice(0, 32), fromHex(nonce2, "nonce", 32)) || !equal2(report.slice(32), suffix)) {
1313
- throw new Error("the quote does not bind this transport key, app and nonce");
1314
- }
1315
- return { key: transportKey, verification: verification({ mock: true }) };
1316
- }
1317
- const args = { quoteB64: doc.quote, nonce: nonce2, reportDataSuffix: hex(suffix) };
1318
- let facts;
1319
- if (policy.verifyQuote) {
1320
- facts = await policy.verifyQuote(args) ? {} : void 0;
1321
- } else if (policy.release) {
1322
- facts = await verifyRelease(doc, args, policy.release, fetchImpl);
1323
- } else {
1324
- throw new Error("real quote refused: this client trusts no TD image (set policy.release)");
1325
- }
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 }) };
1330
+ };
1331
+ return { key: transportKey, verification };
1328
1332
  }
1329
1333
 
1330
1334
  // src/runtime/directory.ts
@@ -1852,8 +1856,8 @@ function queryString(query) {
1852
1856
  if (!query) return "";
1853
1857
  const search = new URLSearchParams();
1854
1858
  for (const [name, value] of Object.entries(query)) {
1855
- for (const one of Array.isArray(value) ? value : [value]) {
1856
- if (one !== void 0 && one !== null) search.append(name, String(one));
1859
+ for (const one2 of Array.isArray(value) ? value : [value]) {
1860
+ if (one2 !== void 0 && one2 !== null) search.append(name, String(one2));
1857
1861
  }
1858
1862
  }
1859
1863
  const text = search.toString();
@@ -1928,6 +1932,10 @@ var NodeTransport = class {
1928
1932
  get session() {
1929
1933
  return this.current;
1930
1934
  }
1935
+ /** @internal The policy nodes are attested under, for the client's own verification (not part of the public API). */
1936
+ get nodePolicy() {
1937
+ return this.policy;
1938
+ }
1931
1939
  /** The sealed channel to `url`, attested under the policy before its first request. */
1932
1940
  channel(url2) {
1933
1941
  let channel = this.channels.get(url2);
@@ -3075,7 +3083,7 @@ function createRoutes(api) {
3075
3083
  * `GET /apps/{app}/pipeline-runs/{run}/receipt` (`pipeline_receipt_receipt`). **Who:** signed in (a session or an API key).
3076
3084
  * A `421 WRONG_NODE` moves the client to the next node of the cluster.
3077
3085
  */
3078
- pipelineReceiptReceipt: (args, options) => route(api, { "method": "GET", "path": "/apps/{app}/pipeline-runs/{run}/receipt", "pathParams": ["app", "run"], "query": [], "body": "none", "optionalBody": false, "reply": "json" }, args, options),
3086
+ pipelineReceiptReceipt: (args, options) => route(api, { "method": "GET", "path": "/apps/{app}/pipeline-runs/{run}/receipt", "pathParams": ["app", "run"], "query": ["version"], "body": "none", "optionalBody": false, "reply": "json" }, args, options),
3079
3087
  /**
3080
3088
  * Cancel a pipeline run.
3081
3089
  *
@@ -3672,6 +3680,12 @@ function createRoutes(api) {
3672
3680
  * Answers `428 OPERATOR_SIGNATURE_REQUIRED` first: give `operatorProof` (here or on the client).
3673
3681
  */
3674
3682
  deploymentsGranted: (args = {}, options) => route(api, { "method": "POST", "path": "/ops/deployments/granted", "pathParams": [], "query": [], "body": "fields", "optionalBody": true, "reply": "json", "operator": true }, args, options),
3683
+ /**
3684
+ * Whether the cluster accepts a job node.
3685
+ *
3686
+ * `GET /ops/job-nodes/{id}/attestation` (`ops_job_node_attestation`). **Who:** the ops token.
3687
+ */
3688
+ jobNodeAttestation: (args, options) => route(api, { "method": "GET", "path": "/ops/job-nodes/{id}/attestation", "pathParams": ["id"], "query": [], "body": "none", "optionalBody": false, "reply": "json" }, args, options),
3675
3689
  /**
3676
3690
  * Prometheus metrics.
3677
3691
  *
@@ -4693,15 +4707,15 @@ var SHA2_32B = class extends HashMD {
4693
4707
  this.H = IV[7] | 0;
4694
4708
  }
4695
4709
  get() {
4696
- const { A, B, C, D, E, F, G, H } = this;
4697
- return [A, B, C, D, E, F, G, H];
4710
+ const { A, B, C, D: D2, E, F, G, H } = this;
4711
+ return [A, B, C, D2, E, F, G, H];
4698
4712
  }
4699
4713
  // prettier-ignore
4700
- set(A, B, C, D, E, F, G, H) {
4714
+ set(A, B, C, D2, E, F, G, H) {
4701
4715
  this.A = A | 0;
4702
4716
  this.B = B | 0;
4703
4717
  this.C = C | 0;
4704
- this.D = D | 0;
4718
+ this.D = D2 | 0;
4705
4719
  this.E = E | 0;
4706
4720
  this.F = F | 0;
4707
4721
  this.G = G | 0;
@@ -4721,7 +4735,7 @@ var SHA2_32B = class extends HashMD {
4721
4735
  const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
4722
4736
  SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
4723
4737
  }
4724
- let { A, B, C, D, E, F, G, H } = this;
4738
+ let { A, B, C, D: D2, E, F, G, H } = this;
4725
4739
  for (let i = 0; i < 64; i++) {
4726
4740
  const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
4727
4741
  const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
@@ -4730,8 +4744,8 @@ var SHA2_32B = class extends HashMD {
4730
4744
  H = G;
4731
4745
  G = F;
4732
4746
  F = E;
4733
- E = D + T1 | 0;
4734
- D = C;
4747
+ E = D2 + T1 | 0;
4748
+ D2 = C;
4735
4749
  C = B;
4736
4750
  B = A;
4737
4751
  A = T1 + T2 | 0;
@@ -4739,12 +4753,12 @@ var SHA2_32B = class extends HashMD {
4739
4753
  A = A + this.A | 0;
4740
4754
  B = B + this.B | 0;
4741
4755
  C = C + this.C | 0;
4742
- D = D + this.D | 0;
4756
+ D2 = D2 + this.D | 0;
4743
4757
  E = E + this.E | 0;
4744
4758
  F = F + this.F | 0;
4745
4759
  G = G + this.G | 0;
4746
4760
  H = H + this.H | 0;
4747
- this.set(A, B, C, D, E, F, G, H);
4761
+ this.set(A, B, C, D2, E, F, G, H);
4748
4762
  }
4749
4763
  roundClean() {
4750
4764
  clean(SHA256_W);
@@ -5045,1692 +5059,2124 @@ function privateKey(seed, extractable) {
5045
5059
  }
5046
5060
  var buf2 = (b) => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
5047
5061
 
5048
- // src/client/approvals.ts
5049
- var MAX_REPORT_PAGE = 100;
5050
- function pageQuery(page = {}) {
5051
- const q = new URLSearchParams();
5052
- if (page.after !== void 0) q.set("after", page.after);
5053
- if (page.limit !== void 0) {
5054
- if (!Number.isInteger(page.limit) || page.limit < 1 || page.limit > MAX_REPORT_PAGE) {
5055
- throw new RangeError(`limit is 1 to ${MAX_REPORT_PAGE}`);
5056
- }
5057
- q.set("limit", String(page.limit));
5062
+ // src/recovery/backup-files.ts
5063
+ var RECOVERY_FORMAT = 1;
5064
+ var SIGNING_LABEL = new TextEncoder().encode("calimero.recovery-backup.v1\0");
5065
+ var HPKE_INFO = new TextEncoder().encode("calimero.recovery-backup.v1");
5066
+ var HPKE_AAD = new TextEncoder().encode("calimero.recovery-backup.key.v1");
5067
+ var KEM_ID = 32;
5068
+ var KDF_ID = 1;
5069
+ var AEAD_ID = 2;
5070
+ var MODE_BASE = 0;
5071
+ var utf83 = (s) => new TextEncoder().encode(s);
5072
+ var i2osp2 = (n) => new Uint8Array([n >> 8 & 255, n & 255]);
5073
+ var KEM_SUITE = concat(utf83("KEM"), i2osp2(KEM_ID));
5074
+ var HPKE_SUITE = concat(utf83("HPKE"), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));
5075
+ function holderKey(holder) {
5076
+ return holder.kind === "operator" ? "operator" : `${holder.kind}:${holder.id}`;
5077
+ }
5078
+ async function newBackupKeyPair() {
5079
+ const secret = crypto.getRandomValues(new Uint8Array(32));
5080
+ return { secret, publicKey: await backupPublicKey(secret) };
5081
+ }
5082
+ async function backupPublicKey(secret) {
5083
+ return hex((await x25519KeyPair(secret)).publicKey);
5084
+ }
5085
+ async function verifyRecoveryHeader(file) {
5086
+ const bytes = utf83(file.header);
5087
+ const header = JSON.parse(file.header);
5088
+ if (typeof header.format !== "number" || header.format > RECOVERY_FORMAT) {
5089
+ throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);
5058
5090
  }
5059
- const s = q.toString();
5060
- return s ? `?${s}` : "";
5091
+ const key = await crypto.subtle.importKey(
5092
+ "raw",
5093
+ fromHex(header.signingKey, "signing key", 32),
5094
+ { name: "Ed25519" },
5095
+ false,
5096
+ ["verify"]
5097
+ );
5098
+ const ok = await crypto.subtle.verify(
5099
+ "Ed25519",
5100
+ key,
5101
+ fromHex(file.signature, "signature", 64),
5102
+ concat(SIGNING_LABEL, bytes)
5103
+ );
5104
+ if (!ok) throw new Error("the node's signature over the header does not hold");
5105
+ return header;
5061
5106
  }
5062
- function compareVersions(a, b) {
5107
+ async function hmac(key, data) {
5108
+ const raw = key.length === 0 ? new Uint8Array(32) : key;
5109
+ const k = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
5110
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
5111
+ }
5112
+ async function expand(prk, info, length) {
5113
+ const out = new Uint8Array(length);
5114
+ let previous = new Uint8Array(0);
5115
+ for (let i = 1, offset = 0; offset < length; i += 1) {
5116
+ previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));
5117
+ out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
5118
+ offset += previous.length;
5119
+ }
5120
+ return out;
5121
+ }
5122
+ var labeledExtract = (suite, salt, label, ikm) => hmac(salt, concat(utf83("HPKE-v1"), suite, utf83(label), ikm));
5123
+ var labeledExpand = (suite, prk, label, info, length) => expand(prk, concat(i2osp2(length), utf83("HPKE-v1"), suite, utf83(label), info), length);
5124
+ async function openDataKey(header, secret) {
5125
+ const recipient = await x25519KeyPair(secret);
5126
+ if (hex(recipient.publicKey) !== header.recipient) {
5127
+ throw new Error("this key is not the one the file was sealed to");
5128
+ }
5129
+ const enc2 = fromHex(header.enc, "encapsulated key", 32);
5130
+ const dhValue = await dh(recipient.privateKey, enc2);
5131
+ const empty = new Uint8Array(0);
5132
+ const prk = await labeledExtract(KEM_SUITE, empty, "eae_prk", dhValue);
5133
+ const shared = await labeledExpand(KEM_SUITE, prk, "shared_secret", concat(enc2, recipient.publicKey), 32);
5134
+ const pskIdHash = await labeledExtract(HPKE_SUITE, empty, "psk_id_hash", empty);
5135
+ const infoHash = await labeledExtract(HPKE_SUITE, empty, "info_hash", HPKE_INFO);
5136
+ const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);
5137
+ const schedule = await labeledExtract(HPKE_SUITE, shared, "secret", empty);
5138
+ const key = await labeledExpand(HPKE_SUITE, schedule, "key", context, 32);
5139
+ const nonce2 = await labeledExpand(HPKE_SUITE, schedule, "base_nonce", context, 12);
5140
+ const aes = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
5141
+ let plain;
5063
5142
  try {
5064
- return compareReleaseVersions(a, b);
5143
+ plain = new Uint8Array(
5144
+ await crypto.subtle.decrypt(
5145
+ { name: "AES-GCM", iv: nonce2, additionalData: HPKE_AAD },
5146
+ aes,
5147
+ fromHex(header.wrappedKey, "wrapped key", 48)
5148
+ )
5149
+ );
5065
5150
  } catch {
5066
- return a < b ? -1 : a > b ? 1 : 0;
5151
+ throw new Error("this key does not open the file");
5067
5152
  }
5153
+ if (plain.length !== 32) throw new Error("the data key is not 32 bytes");
5154
+ return plain;
5068
5155
  }
5069
- function stalledBy(approved, deadlines, now = Date.now() / 1e3) {
5070
- if (approved === null || approved.length === 0) return null;
5071
- const newest = approved.reduce((a, b) => compareVersions(a, b) >= 0 ? a : b);
5072
- let stall = null;
5073
- for (const d of deadlines) {
5074
- if (d.afterSecs <= now && compareVersions(newest, d.version) < 0) {
5075
- if (stall === null || compareVersions(d.version, stall.version) > 0) stall = d;
5156
+ async function holderRecoveryBody(holder, files, secret, options = {}) {
5157
+ const checked2 = [];
5158
+ for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
5159
+ const header = await verifyRecoveryHeader(f);
5160
+ if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);
5161
+ if (holderKey(header.holder) !== holderKey(holder)) {
5162
+ throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);
5076
5163
  }
5164
+ checked2.push({ name: f.name, header });
5077
5165
  }
5078
- return stall;
5079
- }
5080
- function publisherBindingMessage(cluster, org, signerId, generation) {
5081
- return `calimero-publisher-binding/v1
5082
- ${cluster}
5083
- ${org}
5084
- ${signerId}
5085
- ${generation}`;
5086
- }
5087
- function publisherBindingBytes(cluster, org, signerId, generation) {
5088
- return new TextEncoder().encode(publisherBindingMessage(cluster, org, signerId, generation));
5089
- }
5090
- var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5091
- async function confirmationCode(requestId) {
5092
- const h = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(requestId)));
5093
- const word = (h[0] << 24 | h[1] << 16 | h[2] << 8 | h[3]) >>> 0;
5094
- let code = "";
5095
- for (let i = 0; i < 6; i++) {
5096
- if (i === 3) code += "-";
5097
- code += CROCKFORD[word >>> 27 - 5 * i & 31];
5166
+ const open = async (c) => ({
5167
+ file: c.name,
5168
+ key: hex(await openDataKey(c.header, secret))
5169
+ });
5170
+ const slice = checked2.filter((c) => c.header.kind === "holder").pop();
5171
+ if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);
5172
+ const newestByApp = /* @__PURE__ */ new Map();
5173
+ for (const c of checked2) {
5174
+ if (c.header.kind === "app" && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {
5175
+ newestByApp.set(c.header.app, c);
5176
+ }
5098
5177
  }
5099
- return code;
5100
- }
5101
- function consentReturn(href) {
5102
- const url2 = typeof href === "string" ? new URL(href) : href;
5103
- const requestId = url2.searchParams.get("request_id");
5104
- const result = url2.searchParams.get("result");
5105
- if (!requestId || result !== "approved" && result !== "declined") return null;
5106
- return { requestId, result };
5178
+ return {
5179
+ holder: holderKey(holder),
5180
+ slice: await open(slice),
5181
+ apps: await Promise.all([...newestByApp.values()].map(open)),
5182
+ code: await Promise.all(checked2.filter((c) => c.header.kind === "code").map(open))
5183
+ };
5107
5184
  }
5108
- function withoutConsentReturn(href) {
5109
- const url2 = new URL(String(href));
5110
- url2.searchParams.delete("request_id");
5111
- url2.searchParams.delete("result");
5112
- return url2.toString();
5185
+ async function sha2564(data) {
5186
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
5113
5187
  }
5114
- var CONSENT_STORAGE_KEY = "calimero.consent";
5115
- var RELEASE_VERIFIER = "https://mero-tee.vercel.app";
5116
- function releaseNotesUrl(version) {
5117
- return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;
5188
+ async function recoveryAttestationNonce(cluster, node) {
5189
+ const name = utf83(cluster);
5190
+ const len = new Uint8Array(4);
5191
+ new DataView(len.buffer).setUint32(0, name.length, false);
5192
+ const id = new Uint8Array(8);
5193
+ new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
5194
+ return hex(await sha2564(concat(utf83("calimero.recovery-backup.attest.v1\0"), len, name, id)));
5118
5195
  }
5119
- function verifierUrl(query) {
5120
- return `${RELEASE_VERIFIER}/mero-tee?${new URLSearchParams(query)}`;
5196
+ var one = (value, allowed, label, fallback) => {
5197
+ if (value === void 0 && fallback) return fallback;
5198
+ if (!allowed.includes(value)) throw new Error(`the governance's ${label} is not one of ${allowed.join(", ")}`);
5199
+ return value;
5200
+ };
5201
+ function governanceCanonical(g) {
5202
+ const out = {
5203
+ releases: one(g.releases, ["owner", "operator"], "releases"),
5204
+ appUpgrades: one(g.appUpgrades, ["owner", "operator"], "appUpgrades"),
5205
+ outbound: one(g.outbound, ["owner", "operator"], "outbound")
5206
+ };
5207
+ const deployments = one(g.deployments, ["open", "granted"], "deployments", "open");
5208
+ if (deployments !== "open") out.deployments = deployments;
5209
+ const deployers = one(g.deployers, ["operator", "owner"], "deployers", "operator");
5210
+ if (deployers !== "operator") out.deployers = deployers;
5211
+ const signUp = one(g.signUp, ["open", "invite", "closed"], "signUp", "open");
5212
+ if (signUp !== "open") out.signUp = signUp;
5213
+ return utf83(JSON.stringify(out));
5121
5214
  }
5122
- function verifyReleaseUrl(version) {
5123
- return verifierUrl({ release_tag: `mero-tee-v${version}` });
5215
+ async function receiptKeyBinding(receiptKey, governance, cluster, node) {
5216
+ const g = await sha2564(governanceCanonical(governance));
5217
+ const name = utf83(cluster);
5218
+ const len = new Uint8Array(4);
5219
+ new DataView(len.buffer).setUint32(0, name.length, false);
5220
+ const id = new Uint8Array(8);
5221
+ new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
5222
+ return hex(await sha2564(concat(utf83("calimero.tee-attest.receipt-key.v3"), receiptKey, g, len, name, id)));
5124
5223
  }
5125
- function verifyNodeUrl(nodeUrl, release) {
5126
- return verifierUrl({ node_url: nodeUrl.replace(/\/+$/, ""), release_tag: `mero-tee-v${release}` });
5224
+ async function verifyRecoveryAttestation(header, verifyQuote) {
5225
+ const doc = header.attestation;
5226
+ if (!doc || typeof doc.quote !== "string") throw new Error("the file carries no attestation");
5227
+ if (doc.cluster !== header.cluster || doc.node !== header.node) {
5228
+ throw new Error("the attestation is another node's");
5229
+ }
5230
+ if (doc.receiptKey !== header.signingKey) {
5231
+ throw new Error("the attested key is not the one that signed the file");
5232
+ }
5233
+ const nonce2 = await recoveryAttestationNonce(header.cluster, header.node);
5234
+ if (doc.nonce !== nonce2) throw new Error("the attestation is not over the recovery nonce");
5235
+ if (!doc.governance) throw new Error("the attestation names no governance");
5236
+ const reportDataSuffix = await receiptKeyBinding(
5237
+ fromHex(header.signingKey, "signing key", 32),
5238
+ doc.governance,
5239
+ header.cluster,
5240
+ header.node
5241
+ );
5242
+ const ok = await verifyQuote({ quoteB64: doc.quote, nonce: nonce2, reportDataSuffix });
5243
+ if (!ok) throw new Error("the quote was not accepted");
5127
5244
  }
5128
- function pendingApprovalsFrom(report, rules, now = Date.now() / 1e3) {
5129
- const deadlineOf = (v) => rules.deadlines.find((d) => d.version === v) ?? null;
5130
- const releasesActionable = report.governance.releases === "owner";
5131
- const upgradesActionable = report.governance.appUpgrades === "owner";
5132
- const releases = report.clusterReleases.filter((r) => !r.approved).sort((a, b) => compareVersions(b.release, a.release)).map((r) => ({
5133
- version: r.release,
5134
- nodes: r.nodes,
5135
- actionable: releasesActionable,
5136
- releaseNotesUrl: releaseNotesUrl(r.release),
5137
- verifyUrl: verifyReleaseUrl(r.release),
5138
- deadline: deadlineOf(r.release)
5139
- }));
5140
- const upgrades = [];
5141
- for (const a of report.apps) {
5142
- const available = a.availableVersions ?? [];
5143
- if (a.package === null || available.length === 0) continue;
5144
- const latest = available[available.length - 1];
5145
- const reachable = a.latestReachable === void 0 ? latest : a.latestReachable;
5146
- upgrades.push({
5147
- app: a.app,
5148
- name: a.name ?? null,
5149
- package: a.package.package,
5150
- from: a.package.version,
5151
- to: reachable ?? latest,
5152
- reachable: reachable !== null,
5153
- blocked: a.latestBlocked ?? null,
5154
- available,
5155
- actionable: upgradesActionable
5156
- });
5245
+
5246
+ // src/package/pack.ts
5247
+ var MAX_MANIFEST_BYTES = 1024 * 1024;
5248
+ var MAX_PIPELINES_PER_PACKAGE = 16;
5249
+ var MAX_PIPELINE_BYTES = 64 * 1024;
5250
+ var MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
5251
+ var MAX_MPK_BYTES = (64 * 1024 * 1024 - 1024 * 1024) / 4 * 3;
5252
+ var DEV_SIGNER_ID = "did:key:z6MknF3p5L5FDHJQ7FREUapuX4Wmp4MtF6WrHYaXS2B3eZQd";
5253
+ var MANIFEST_SIGNING_DOMAIN = new TextEncoder().encode("calimero.bundle.manifest.v1\0");
5254
+ var MIN_RUNTIME_VERSION = "0.1.0";
5255
+ var ED25519_PUB_MULTICODEC = [237, 1];
5256
+ var BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
5257
+ var COMPONENT_HEADER = [0, 97, 115, 109, 13, 0, 1, 0];
5258
+ var PIPELINE_PATH = /^pipelines\/[A-Za-z0-9._-]+\.yaml$/;
5259
+ var SEED_B64URL = /^[A-Za-z0-9_-]{43}$/;
5260
+ var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
5261
+ var utf84 = (s) => new TextEncoder().encode(s);
5262
+ var hex2 = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
5263
+ var concat2 = (...parts) => {
5264
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
5265
+ let off = 0;
5266
+ for (const p of parts) out.set(p, off), off += p.length;
5267
+ return out;
5268
+ };
5269
+ async function requireEd25519() {
5270
+ const unsupported = new Error("this runtime cannot sign Ed25519 packages (WebCrypto Ed25519 is missing)");
5271
+ if (!globalThis.crypto?.subtle) throw unsupported;
5272
+ try {
5273
+ await privateKey(new Uint8Array(32), false);
5274
+ } catch {
5275
+ throw unsupported;
5157
5276
  }
5158
- return {
5159
- scope: report.scope,
5160
- governance: report.governance,
5161
- approvedReleases: report.approvedReleases,
5162
- releases,
5163
- upgrades,
5164
- stalledBy: stalledBy(report.approvedReleases, rules.deadlines, now),
5165
- actionable: releases.some((r) => r.actionable) || upgrades.some((u) => u.actionable)
5166
- };
5167
- }
5168
- function releaseConsent(scope, version, returnTo, options = {}) {
5169
- return {
5170
- kind: "release",
5171
- scope: scope.kind === "org" ? { org: scope.org } : "account",
5172
- subject: options.withdraw ? { version, withdraw: true } : { version },
5173
- returnTo
5174
- };
5175
- }
5176
- function withdrawConsent(scope, version, returnTo) {
5177
- return releaseConsent(scope, version, returnTo, { withdraw: true });
5178
5277
  }
5179
- function upgradeConsent(app, toVersion, returnTo) {
5180
- return { kind: "upgrade", subject: { app, toVersion }, returnTo };
5278
+ async function keyOfSeed(seed) {
5279
+ await requireEd25519();
5280
+ if (seed.length !== 32) throw new Error("a publisher seed is 32 bytes");
5281
+ const publicKey = fromB64url(await recoveryPublicKey(seed));
5282
+ return { seed: Uint8Array.from(seed), publicKey };
5181
5283
  }
5182
- function createOrgConsent(name, returnTo) {
5183
- return { kind: "createOrg", subject: { name }, returnTo };
5284
+ async function generatePublisherKey() {
5285
+ await requireEd25519();
5286
+ return keyOfSeed(crypto.getRandomValues(new Uint8Array(32)));
5184
5287
  }
5185
- function createInviteConsent(subject, returnTo) {
5186
- return { kind: "createInvite", subject, returnTo };
5288
+ async function webCryptoPublisherKey(key) {
5289
+ await requireEd25519();
5290
+ return { privateKey: await privateKey(Uint8Array.from(key.seed), false), publicKey: Uint8Array.from(key.publicKey) };
5187
5291
  }
5188
- function acceptInviteConsent(token, returnTo) {
5189
- return { kind: "acceptInvite", subject: { token }, returnTo };
5292
+ function base58(bytes) {
5293
+ let n = 0n;
5294
+ for (const b of bytes) n = n << 8n | BigInt(b);
5295
+ let out = "";
5296
+ for (; n > 0n; n /= 58n) out = BASE58[Number(n % 58n)] + out;
5297
+ return "1".repeat(bytes.findIndex((b) => b !== 0) === -1 ? bytes.length : bytes.findIndex((b) => b !== 0)) + out;
5190
5298
  }
5191
- function leaveOrgConsent(org, returnTo) {
5192
- return { kind: "leaveOrg", subject: { org }, returnTo };
5299
+ function signerIdOf(key) {
5300
+ return `did:key:z${base58(concat2(Uint8Array.from(ED25519_PUB_MULTICODEC), key.publicKey))}`;
5193
5301
  }
5194
- function removeMemberConsent(org, account, returnTo) {
5195
- return { kind: "removeMember", subject: { org, account }, returnTo };
5302
+ function isDevPublisherKey(key) {
5303
+ return signerIdOf(key) === DEV_SIGNER_ID;
5196
5304
  }
5197
- function setMemberRoleConsent(org, account, role, returnTo) {
5198
- return { kind: "setMemberRole", subject: { org, account, role }, returnTo };
5305
+ function exportPublisherKey(key) {
5306
+ return utf84(
5307
+ JSON.stringify({ private_key: b64url(key.seed), public_key: b64url(key.publicKey), signer_id: signerIdOf(key) }, null, 2)
5308
+ );
5199
5309
  }
5200
- function setMemberTeamsConsent(org, account, teams, returnTo) {
5201
- return { kind: "setMemberTeams", subject: { org, account, teams }, returnTo };
5310
+ async function importPublisherKey(bytes) {
5311
+ let file;
5312
+ try {
5313
+ file = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
5314
+ } catch {
5315
+ throw new Error("a publisher key backup is a JSON document");
5316
+ }
5317
+ const seed = file?.private_key;
5318
+ if (typeof seed !== "string" || !SEED_B64URL.test(seed) || b64url(fromB64url(seed)) !== seed) {
5319
+ throw new Error("the backup private_key is not an unpadded base64url 32-byte seed");
5320
+ }
5321
+ const key = await keyOfSeed(fromB64url(seed));
5322
+ if (file.public_key !== void 0 && file.public_key !== b64url(key.publicKey)) {
5323
+ throw new Error("the backup public_key is not the seed's");
5324
+ }
5325
+ if (file.signer_id !== void 0 && file.signer_id !== signerIdOf(key)) {
5326
+ throw new Error("the backup signer_id is not the seed's");
5327
+ }
5328
+ return key;
5202
5329
  }
5203
- function removeMemberTeamsConsent(org, account, teams, returnTo) {
5204
- return { kind: "removeMemberTeams", subject: { org, account, teams }, returnTo };
5330
+ function canonicalizeManifest(manifest) {
5331
+ const signed = Object.fromEntries(Object.entries(manifest).filter(([k]) => k !== "signature" && !k.startsWith("_")));
5332
+ return utf84(jcs(signed));
5205
5333
  }
5206
- function revokeInviteConsent(org, inviteKey, returnTo) {
5207
- return { kind: "revokeInvite", subject: { org, inviteKey }, returnTo };
5334
+ function jcs(value, anyNumber = false) {
5335
+ if (typeof value === "string") {
5336
+ if (/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)) {
5337
+ throw new Error("a lone surrogate cannot be canonicalized");
5338
+ }
5339
+ return JSON.stringify(value);
5340
+ }
5341
+ if (typeof value === "number") {
5342
+ if (anyNumber ? !Number.isFinite(value) : !Number.isSafeInteger(value)) {
5343
+ throw new Error(anyNumber ? "a non-finite number cannot be canonicalized" : "only safe integers can be canonicalized");
5344
+ }
5345
+ return String(value);
5346
+ }
5347
+ if (value === null || typeof value === "boolean") return String(value);
5348
+ if (typeof value !== "object") throw new Error(`a ${typeof value} cannot be canonicalized`);
5349
+ if (Array.isArray(value)) return `[${value.map((v) => jcs(v, anyNumber)).join(",")}]`;
5350
+ return `{${Object.keys(value).sort().map((k) => `${jcs(k, anyNumber)}:${jcs(value[k], anyNumber)}`).join(",")}}`;
5208
5351
  }
5209
- function renameOrgConsent(org, name, returnTo) {
5210
- return { kind: "renameOrg", subject: { org, name }, returnTo };
5352
+ async function signingPayload(manifest) {
5353
+ return sha2562(concat2(MANIFEST_SIGNING_DOMAIN, canonicalizeManifest(manifest)));
5211
5354
  }
5212
- function deleteOrgConsent(org, returnTo) {
5213
- return { kind: "deleteOrg", subject: { org }, returnTo };
5355
+ async function verifyManifestSignature(manifest) {
5356
+ await requireEd25519();
5357
+ const sig = manifest.signature;
5358
+ if (!sig) throw new Error("manifest is missing required 'signature' field");
5359
+ if (sig.algorithm !== "ed25519") throw new Error(`unsupported signature algorithm: '${sig.algorithm}'`);
5360
+ const publicKey = fromB64url(sig.publicKey ?? "");
5361
+ const signature = fromB64url(sig.signature ?? "");
5362
+ if (publicKey.length !== 32 || signature.length !== 64) throw new Error("malformed signature field");
5363
+ const key = await crypto.subtle.importKey("raw", buf2(publicKey), { name: "Ed25519" }, false, ["verify"]);
5364
+ const ok = await crypto.subtle.verify("Ed25519", key, buf2(signature), buf2(await signingPayload(manifest)));
5365
+ if (!ok) throw new Error("Ed25519 signature verification failed");
5366
+ const derived = signerIdOf({ publicKey });
5367
+ if (manifest.signerId !== derived) {
5368
+ throw new Error(`signerId mismatch: manifest declares '${manifest.signerId}' but signature public key derives to '${derived}'`);
5369
+ }
5370
+ return derived;
5214
5371
  }
5215
- function setCapabilitiesConsent(subject, returnTo) {
5216
- return { kind: "setCapabilities", subject, returnTo };
5372
+ function checkPathComponent(value, field) {
5373
+ if (!value) throw new Error(`${field} is empty`);
5374
+ if (value.includes("..")) throw new Error(`${field} contains path traversal sequence '..'`);
5375
+ if (value.includes("/") || value.includes("\\")) throw new Error(`${field} contains directory separator`);
5376
+ if (value.includes("\0")) throw new Error(`${field} contains null byte`);
5377
+ if (value.length >= 2 && value[1] === ":") throw new Error(`${field} appears to be an absolute path`);
5217
5378
  }
5218
- function setAllAppsConsent(org, account, allApps, returnTo) {
5219
- return { kind: "setAllApps", subject: { org, account, allApps }, returnTo };
5379
+ function checkPipelinePath(value, field) {
5380
+ if (!value) throw new Error(`${field} is empty`);
5381
+ if (value.includes("\0")) throw new Error(`${field} contains null byte`);
5382
+ if (value.includes("\\")) throw new Error(`${field} contains backslash (use forward slashes)`);
5383
+ if (value.startsWith("/")) throw new Error(`${field} is an absolute path`);
5384
+ if (value[1] === ":") throw new Error(`${field} appears to be an absolute Windows path`);
5385
+ if (value.split("/").includes("..")) throw new Error(`${field} contains path traversal component '..'`);
5386
+ if (!PIPELINE_PATH.test(value) || utf84(value).length > 100) {
5387
+ throw new Error(`${field} must be pipelines/<name>.yaml (A-Z a-z 0-9 . _ -), at most 100 bytes`);
5388
+ }
5220
5389
  }
5221
-
5222
- // src/client/calimero-client.ts
5223
- var FILE_PART_BYTES = 16 * 1024 * 1024;
5224
- var PART_RESENDS = 1;
5225
- var MAX_FAILURES = 8;
5226
- var MAX_JUMPS = 16;
5227
- var CALL_RETRIES = 8;
5228
- function deployerKey(deployer) {
5229
- return "account" in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
5390
+ var METADATA_STRINGS = ["name", "description", "author", "icon", "license", "category", "guide"];
5391
+ function normalizeMetadata(m) {
5392
+ const bad = (what) => new Error(`metadata ${what}`);
5393
+ if (typeof m !== "object" || m === null || Array.isArray(m)) throw bad("must be an object");
5394
+ const known = /* @__PURE__ */ new Set([...METADATA_STRINGS, "tags"]);
5395
+ const unknown = Object.keys(m).find((k) => !known.has(k));
5396
+ if (unknown !== void 0) throw bad(`has an unknown field '${unknown}'`);
5397
+ const out = {};
5398
+ for (const k of METADATA_STRINGS) {
5399
+ const v = m[k];
5400
+ if (v === void 0) continue;
5401
+ if (typeof v !== "string") throw bad(`${k} must be a string`);
5402
+ out[k] = v;
5403
+ }
5404
+ if (typeof out.name !== "string") throw bad("name is required");
5405
+ if (m.tags !== void 0) {
5406
+ if (!Array.isArray(m.tags) || m.tags.some((t) => typeof t !== "string")) throw bad("tags must be an array of strings");
5407
+ out.tags = [...m.tags];
5408
+ }
5409
+ return out;
5230
5410
  }
5231
- async function frontendManifest(origin, fetcher = fetch) {
5232
- const base = origin ?? globalThis.location?.origin;
5233
- if (!base) throw new Error("no page origin to read the frontend manifest from; pass `origin`");
5234
- const response = await fetcher(new URL("/.well-known/calimero.json", base).toString());
5235
- if (!response.ok) throw await refusal(response);
5236
- const manifest = await response.json();
5237
- return { ...manifest, deployments: manifest.deployments ?? [] };
5411
+ var artifact = (path, bytes) => ({ path, hash: hex2(sha2562(bytes)), size: bytes.length });
5412
+ var padded = (n) => 512 + Math.ceil(n / 512) * 512;
5413
+ function tarEntry(name, data) {
5414
+ const header = new Uint8Array(512);
5415
+ const put = (off, text) => header.set(utf84(text), off);
5416
+ put(0, name);
5417
+ put(100, "0000644\0");
5418
+ put(108, "0000000\0");
5419
+ put(116, "0000000\0");
5420
+ put(124, `${data.length.toString(8).padStart(11, "0")}\0`);
5421
+ put(136, "00000000000\0");
5422
+ put(148, " ");
5423
+ put(156, "0");
5424
+ put(257, "ustar\0");
5425
+ put(263, "00");
5426
+ put(148, `${header.reduce((n, b) => n + b, 0).toString(8).padStart(6, "0")}\0 `);
5427
+ return concat2(header, data, new Uint8Array((512 - data.length % 512) % 512));
5238
5428
  }
5239
- function pageDeployment(href) {
5240
- const at = href ?? globalThis.location?.href;
5241
- if (!at) return null;
5242
- try {
5243
- return new URL(at).searchParams.get("deployment") || null;
5244
- } catch {
5245
- return null;
5429
+ function readTar(tar) {
5430
+ const out = /* @__PURE__ */ new Map();
5431
+ const text = (a, b) => new TextDecoder().decode(tar.subarray(a, b)).replace(/\0.*$/s, "");
5432
+ for (let off = 0; off + 512 <= tar.length && tar[off] !== 0; ) {
5433
+ const name = text(off, off + 100);
5434
+ const size = parseInt(text(off + 124, off + 136).trim(), 8);
5435
+ if (out.has(name)) throw new Error(`the archive has more than one entry at '${name}'`);
5436
+ out.set(name, tar.subarray(off + 512, off + 512 + size));
5437
+ off += padded(size);
5246
5438
  }
5439
+ return out;
5247
5440
  }
5248
- function pageParams(page) {
5249
- pageQuery(page);
5250
- return { after: page.after, limit: page.limit };
5251
- }
5252
- function toHex(bytes) {
5253
- return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
5441
+ async function checkPackage(tar, publicKey) {
5442
+ const entries = readTar(tar);
5443
+ const raw = entries.get("manifest.json");
5444
+ if (!raw) throw new Error("manifest.json not found in bundle");
5445
+ const manifest = JSON.parse(new TextDecoder().decode(raw));
5446
+ await verifyManifestSignature(manifest);
5447
+ if (manifest.signature.publicKey !== b64url(publicKey)) throw new Error("the manifest is not signed by the publisher key");
5448
+ const declared = [manifest.compute, ...manifest.pipelines ?? []];
5449
+ const names = ["manifest.json", ...declared.map((a) => a.path)];
5450
+ if (names.length !== entries.size || names.some((n) => !entries.has(n))) {
5451
+ throw new Error("the archive does not hold exactly the files its manifest declares");
5452
+ }
5453
+ for (const a of declared) {
5454
+ const bytes = entries.get(a.path);
5455
+ if (!bytes || bytes.length !== a.size || hex2(sha2562(bytes)) !== a.hash) {
5456
+ throw new Error(`bundle artifact '${a.path}' failed its integrity check`);
5457
+ }
5458
+ }
5254
5459
  }
5255
- function presenceState(state) {
5256
- return state === null ? null : toHex(state);
5460
+ async function gzip(bytes) {
5461
+ if (typeof CompressionStream === "undefined") throw new Error("this runtime cannot gzip packages (no CompressionStream)");
5462
+ const stream = new Blob([buf2(bytes)]).stream().pipeThrough(new CompressionStream("gzip"));
5463
+ return new Uint8Array(await new Response(stream).arrayBuffer());
5257
5464
  }
5258
- async function readSlice(data, start, end) {
5259
- if (data instanceof Blob) return new Uint8Array(await data.slice(start, end).arrayBuffer());
5260
- return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);
5465
+ async function signerOf(key, seed, publicKey) {
5466
+ if (seed) {
5467
+ const derived = fromB64url(await recoveryPublicKey(seed));
5468
+ if (hex2(derived) !== hex2(publicKey)) throw new Error("the publisher key's publicKey is not its seed's");
5469
+ return { signing: await privateKey(seed, false), publicKey: derived };
5470
+ }
5471
+ const k = key.privateKey;
5472
+ if (k?.algorithm?.name !== "Ed25519" || k.type !== "private" || !k.usages.includes("sign")) {
5473
+ throw new Error("the publisher key is not an Ed25519 signing key");
5474
+ }
5475
+ return { signing: k, publicKey };
5261
5476
  }
5262
- function nextPart(answer, parts) {
5263
- const next = answer?.next;
5264
- if (typeof next === "number" && Number.isInteger(next) && next >= 0 && next <= parts) return next;
5265
- throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);
5477
+ async function packComputePackage(input, key) {
5478
+ const seed = "seed" in key && key.seed ? Uint8Array.from(key.seed) : void 0;
5479
+ const publicKey = Uint8Array.from(key.publicKey);
5480
+ const job = prepare(input);
5481
+ await requireEd25519();
5482
+ const { signing, publicKey: pub } = await signerOf(key, seed, publicKey);
5483
+ const manifest = { ...job.manifest, signerId: signerIdOf({ publicKey: pub }) };
5484
+ const signature = await crypto.subtle.sign("Ed25519", signing, buf2(await signingPayload(manifest)));
5485
+ manifest.signature = { algorithm: "ed25519", publicKey: b64url(pub), signature: b64url(new Uint8Array(signature)) };
5486
+ const manifestBytes = utf84(jcs(manifest));
5487
+ if (manifestBytes.length > MAX_MANIFEST_BYTES) {
5488
+ throw new Error(`bundle manifest.json exceeds the ${MAX_MANIFEST_BYTES} byte cap`);
5489
+ }
5490
+ const files = [["manifest.json", manifestBytes], ["compute.wasm", job.compute], ...job.files];
5491
+ checkArchiveSize(files.map(([, b]) => b.length));
5492
+ const tar = concat2(...files.map(([n, b]) => tarEntry(n, b)), new Uint8Array(1024));
5493
+ await checkPackage(tar, pub);
5494
+ const mpk = await gzip(tar);
5495
+ if (mpk.length > MAX_MPK_BYTES) throw new Error(`a package is limited to ${MAX_MPK_BYTES >> 20} MiB`);
5496
+ return mpk;
5266
5497
  }
5267
- var CalimeroClient = class _CalimeroClient {
5268
- /**
5269
- * A client for the Calimero Cloud cluster named `cluster`: its node list read
5270
- * from the public node directory, those in `zone` first, each group in
5271
- * weighted-random order. The directory only picks which nodes to try: each is
5272
- * attested under `policy` before anything is sent to it. Throws
5273
- * {@link DirectoryError} when the directory names no usable node.
5274
- *
5275
- * The list is read again in the background after a failover, and at the
5276
- * first request once the directory's `refreshAfterSeconds` has passed.
5277
- */
5278
- static async connect(options, challenges = {}) {
5279
- const transport = await directoryTransport({ ...options, directory: options.directory ?? DEFAULT_DIRECTORY });
5280
- return new _CalimeroClient(transport, challenges);
5498
+ function checkArchiveSize(sizes) {
5499
+ if (sizes.reduce((n, s) => n + padded(s), 1024) > MAX_ARCHIVE_BYTES) {
5500
+ throw new Error(`bundle archive exceeds the ${MAX_ARCHIVE_BYTES} byte decompressed cap`);
5281
5501
  }
5282
- /**
5283
- * A client of the nodes `options` names, or one sending through an existing
5284
- * `transport`. `challenges` answers the node's challenges for every
5285
- * generated method a call's own options leave open (`confirm` a
5286
- * `412 CONFIRM_REQUIRED`, `operatorProof` a `428 OPERATOR_SIGNATURE_REQUIRED`).
5287
- */
5288
- constructor(options, challenges = {}) {
5289
- this.transport = options instanceof NodeTransport ? options : new NodeTransport(options);
5290
- const routes = createRoutes(createRouteClient(this.transport, challenges));
5291
- this.apps = routes.apps;
5292
- this.auth = routes.auth;
5293
- this.consent = routes.consent;
5294
- this.ops = routes.ops;
5295
- this.orgs = routes.orgs;
5296
- this.public = routes.public;
5297
- this.packages = routes.packages;
5298
- this.deployments = routes.deployments;
5502
+ }
5503
+ function prepare(input) {
5504
+ checkPathComponent(input.package, "package");
5505
+ checkPathComponent(input.version, "appVersion");
5506
+ if (!SEMVER.test(input.version)) throw new Error(`appVersion '${input.version}' is not a semantic version`);
5507
+ if (!input.compute?.length) throw new Error("the package ships no WASM");
5508
+ if (input.pipelines.length > MAX_PIPELINES_PER_PACKAGE) {
5509
+ throw new Error(`bundle declares ${input.pipelines.length} pipelines, at most ${MAX_PIPELINES_PER_PACKAGE} are allowed`);
5299
5510
  }
5300
- /** A generated method's answer, as the type this class has always answered. */
5301
- as(result) {
5302
- return result;
5511
+ checkArchiveSize([input.compute.length]);
5512
+ const compute = Uint8Array.from(input.compute);
5513
+ if (COMPONENT_HEADER.some((b, i) => compute[i] !== b)) {
5514
+ throw new Error("compute: not a WASM component (an SDK 0.12 core module is refused by the node)");
5303
5515
  }
5304
- /** The options that answer a `412 CONFIRM_REQUIRED` with `passkey`, when one is given. */
5305
- confirmWith(passkey, options = {}) {
5306
- return passkey ? { confirm: passkeyConfirm(passkey, options) } : void 0;
5516
+ const files = input.pipelines.map((p, i) => {
5517
+ checkPipelinePath(p.path, `pipelines[${i}].path`);
5518
+ return [p.path, utf84(p.source)];
5519
+ });
5520
+ const big = files.find(([, b]) => b.length > MAX_PIPELINE_BYTES);
5521
+ if (big) throw new Error(`pipeline '${big[0]}' exceeds the ${MAX_PIPELINE_BYTES} byte cap`);
5522
+ const lower = files.map(([n]) => n.toLowerCase());
5523
+ if (new Set(lower).size !== files.length) throw new Error("two pipelines have the same path");
5524
+ const metadata = input.metadata === void 0 ? void 0 : normalizeMetadata(input.metadata);
5525
+ const manifest = {
5526
+ version: "1.0",
5527
+ package: input.package,
5528
+ appVersion: input.version,
5529
+ minRuntimeVersion: MIN_RUNTIME_VERSION,
5530
+ ...metadata ? { metadata } : {},
5531
+ compute: artifact("compute.wasm", compute),
5532
+ ...files.length ? { pipelines: files.map(([n, b]) => artifact(n, b)) } : {}
5533
+ };
5534
+ return { manifest, compute, files };
5535
+ }
5536
+
5537
+ // src/client/receipts.ts
5538
+ var PIPELINE_RECEIPT_DOMAIN = "calimero.pipeline.receipt.v1\0";
5539
+ var utf85 = (s) => new TextEncoder().encode(s);
5540
+ var fail = (path, what) => {
5541
+ throw new Error(`the receipt's ${path} ${what}`);
5542
+ };
5543
+ var hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
5544
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
5545
+ var str = (v, p) => typeof v === "string" || fail(p, "is not a string");
5546
+ var bool = (v, p) => typeof v === "boolean" || fail(p, "is not a boolean");
5547
+ var any = () => void 0;
5548
+ var obj = (v, p) => isObject(v) || fail(p, "is not an object");
5549
+ var uint = (max) => (v, p) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= max || fail(p, "is not an unsigned integer in range");
5550
+ var u32 = uint(4294967295);
5551
+ var u64 = (v, p) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v < 2 ** 64 || fail(p, "is not an unsigned integer in range");
5552
+ var list = (item) => (v, p) => {
5553
+ if (!Array.isArray(v)) fail(p, "is not an array");
5554
+ v.forEach((x, i) => item(x, `${p}[${i}]`));
5555
+ };
5556
+ var map = (value) => (v, p) => {
5557
+ if (!isObject(v)) fail(p, "is not an object");
5558
+ for (const [k, x] of Object.entries(v)) value(x, `${p}.${k}`);
5559
+ };
5560
+ var struct = (required, optional = {}, defaulted = {}, open = false) => (v, p) => {
5561
+ if (!isObject(v)) return fail(p, "is not an object");
5562
+ for (const k of Object.keys(v)) {
5563
+ if (!open && !hasOwn(required, k) && !hasOwn(optional, k) && !hasOwn(defaulted, k)) fail(`${p}.${k}`, "is not a known field");
5307
5564
  }
5308
- /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved the client on. */
5309
- get nodeUrl() {
5310
- return this.transport.nodeUrl;
5565
+ for (const [k, check2] of Object.entries(required)) {
5566
+ if (!hasOwn(v, k)) fail(`${p}.${k}`, "is missing");
5567
+ check2(v[k], `${p}.${k}`);
5311
5568
  }
5312
- /** Every node this client may use, in the order it moves through them. */
5313
- get nodes() {
5314
- return this.transport.nodes;
5569
+ for (const [k, check2] of Object.entries(optional)) {
5570
+ if (hasOwn(v, k) && v[k] !== null) check2(v[k], `${p}.${k}`);
5315
5571
  }
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);
5572
+ for (const [k, check2] of Object.entries(defaulted)) {
5573
+ if (hasOwn(v, k)) check2(v[k], `${p}.${k}`);
5319
5574
  }
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);
5575
+ };
5576
+ var fileRef = struct({ id: str, size: u64, sha256: str });
5577
+ var jobOutput = struct({ id: str, size: u64, sha256: str, segments: list(str) });
5578
+ var jobEvidence = struct({ resultSha256: str, segments: list(list(str)) }, { log: jobOutput }, { message: str });
5579
+ var attestationDoc = struct(
5580
+ {
5581
+ quote: str,
5582
+ transportKey: str,
5583
+ appHash: str,
5584
+ nonce: str,
5585
+ release: struct({ version: str, profile: str }, {}, {}, true),
5586
+ cluster: str,
5587
+ node: u64,
5588
+ mock: bool
5589
+ },
5590
+ { receiptKey: str, governance: obj, kms: obj, jobKey: str, clusterIdentity: str },
5591
+ {},
5592
+ true
5593
+ );
5594
+ var stepRun = struct(
5595
+ {
5596
+ run: str,
5597
+ step: str,
5598
+ index: u32,
5599
+ outcome: str,
5600
+ attempt: u32,
5601
+ outputs: list(fileRef),
5602
+ usage: struct({ cpuMicros: str, gibMicros: str, fuel: str })
5603
+ },
5604
+ { node: u64, jobKey: str, assignmentDigest: str, reportSha256: str, signature: str, job: jobEvidence }
5605
+ );
5606
+ var cachedRun = struct({ index: u32, cached: bool, cacheKey: str });
5607
+ var runEntry = (v, p) => {
5608
+ try {
5609
+ cachedRun(v, p);
5610
+ } catch {
5611
+ stepRun(v, p);
5323
5612
  }
5324
- /** Authenticate every request with an API key. */
5325
- useApiKey(key) {
5326
- this.transport.useApiKey(key);
5613
+ };
5614
+ var pipelineReceipt = struct(
5615
+ {
5616
+ version: u32,
5617
+ cluster: str,
5618
+ app: str,
5619
+ run: str,
5620
+ pipeline: str,
5621
+ release: str,
5622
+ pipelineHash: str,
5623
+ modules: map(str),
5624
+ inputs: map(list(fileRef)),
5625
+ params: map(any),
5626
+ state: str,
5627
+ startTsMs: u64,
5628
+ endTsMs: u64,
5629
+ steps: map(struct({ status: str, runs: list(runEntry) }, { reason: str }))
5630
+ },
5631
+ { costSoFar: str },
5632
+ { jobAttestations: map(attestationDoc) }
5633
+ );
5634
+ function strictHex(value, label, bytes) {
5635
+ if (typeof value !== "string" || value.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(value)) {
5636
+ throw new Error(`${label} is not ${bytes} bytes of hex`);
5327
5637
  }
5328
- useSession(session) {
5329
- this.transport.useSession(session);
5638
+ return fromHex(value, label, bytes);
5639
+ }
5640
+ function nodeId(value, label) {
5641
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label} is not a node id`);
5642
+ return value;
5643
+ }
5644
+ async function verifyReceiptKey(doc, nonce2, cluster, node, policy) {
5645
+ if (typeof doc.quote !== "string") throw new Error("the attestation carries no quote");
5646
+ if (!doc.receiptKey) throw new Error("the attestation names no receipt key");
5647
+ if (!isObject(doc.governance)) throw new Error("the attestation names no governance");
5648
+ const key = strictHex(doc.receiptKey, "the receipt key", 32);
5649
+ const suffix = fromHex(await receiptKeyBinding(key, doc.governance, cluster, node), "binding", 32);
5650
+ await verifyQuoteBinding(doc, nonce2, suffix, policy, "receipt key");
5651
+ return { key, governance: JSON.parse(new TextDecoder().decode(governanceCanonical(doc.governance))) };
5652
+ }
5653
+ async function verifyAppCluster(client, app, policy) {
5654
+ const nonce2 = crypto.getRandomValues(new Uint8Array(32));
5655
+ const answer = await client.apps.attestation({ app, nonce: hex(nonce2) });
5656
+ if (!isObject(answer) || typeof answer.cluster !== "string" || !Array.isArray(answer.replicas)) {
5657
+ throw new Error("the node answered a malformed attestation");
5658
+ }
5659
+ const cluster = answer.cluster;
5660
+ const keys = /* @__PURE__ */ new Map();
5661
+ let governance;
5662
+ for (const replica of answer.replicas) {
5663
+ if (!isObject(replica)) throw new Error("a replica entry is not an object");
5664
+ const node = nodeId(replica.node, "a replica");
5665
+ if (hasOwn(replica, "error")) throw new Error(`replica ${node} gave no attestation: ${String(replica.error)}`);
5666
+ const doc = replica.attestation;
5667
+ if (!isObject(doc)) throw new Error(`replica ${node} gave neither an attestation nor an error`);
5668
+ if (nodeId(doc.node, `replica ${node}'s document`) !== node) throw new Error(`replica ${node} answered as node ${String(doc.node)}`);
5669
+ let attested;
5670
+ try {
5671
+ attested = await verifyReceiptKey(doc, nonce2, cluster, node, policy);
5672
+ } catch (error) {
5673
+ throw new Error(`replica ${node}: ${error instanceof Error ? error.message : String(error)}`);
5674
+ }
5675
+ if (governance && JSON.stringify(governance) !== JSON.stringify(attested.governance)) {
5676
+ throw new Error(`replica ${node} attests other governance`);
5677
+ }
5678
+ governance = attested.governance;
5679
+ keys.set(node, attested.key);
5680
+ }
5681
+ if (!governance) throw new Error(`no replica of ${app} attested`);
5682
+ return { keys, governance, cluster };
5683
+ }
5684
+ var canonicalReceipt = (receipt) => jcs(receipt, true);
5685
+ var receiptMessage = (receipt) => concat(utf85(PIPELINE_RECEIPT_DOMAIN), utf85(canonicalReceipt(receipt)));
5686
+ async function verifyReceiptSignature(answer, key) {
5687
+ if (!isObject(answer)) throw new Error("the receipt answer is not an object");
5688
+ const unknown = Object.keys(answer).find((k) => !["receipt", "node", "signature"].includes(k));
5689
+ if (unknown !== void 0) throw new Error(`the receipt answer's ${unknown} is not a known field`);
5690
+ const signature = strictHex(answer.signature, "the signature", 64);
5691
+ const canonical = canonicalReceipt(answer.receipt);
5692
+ const publicKey = await crypto.subtle.importKey("raw", buf2(key), { name: "Ed25519" }, false, ["verify"]);
5693
+ if (!await crypto.subtle.verify("Ed25519", publicKey, buf2(signature), buf2(concat(utf85(PIPELINE_RECEIPT_DOMAIN), utf85(canonical))))) {
5694
+ throw new Error("the receipt is not signed by that key");
5695
+ }
5696
+ const receipt = JSON.parse(canonical);
5697
+ pipelineReceipt(receipt, "receipt");
5698
+ return receipt;
5699
+ }
5700
+ var JOB_REPORT_DOMAIN = "calimero.compute.report.v1\0";
5701
+ var JOB_REPORT_LOG_DOMAIN = "calimero.compute.report.log.v1\0";
5702
+ var JOB_KEY_DOMAIN = "calimero.tee-attest.job-key.v1";
5703
+ var RECEIPT_VERSION_JOBS = 2;
5704
+ var JOB_FAIL_REASONS = ["fuel", "memory", "trap", "app-error", "integrity", "cancelled"];
5705
+ var LEADER_FAIL_REASONS = ["lost", "refused", "timeout", "quota", "not-granted", "too-large"];
5706
+ var U64_MAX = 2n ** 64n - 1n;
5707
+ var sha2565 = async (bytes) => new Uint8Array(await crypto.subtle.digest("SHA-256", buf2(bytes)));
5708
+ var u32be = (n) => {
5709
+ const out = new Uint8Array(4);
5710
+ new DataView(out.buffer).setUint32(0, n, false);
5711
+ return out;
5712
+ };
5713
+ var u64be = (n) => {
5714
+ const big = BigInt(n);
5715
+ if (big < 0n || big > U64_MAX) throw new Error("a number is past 2^64-1");
5716
+ const out = new Uint8Array(8);
5717
+ new DataView(out.buffer).setBigUint64(0, big, false);
5718
+ return out;
5719
+ };
5720
+ var prefixed2 = (text) => {
5721
+ const bytes = utf85(text);
5722
+ return concat(u32be(bytes.length), bytes);
5723
+ };
5724
+ function hashBytes(text) {
5725
+ if (typeof text !== "string" || !/^[0-9a-f]{64}$/.test(text)) throw new Error("a hash is 64 lowercase hex digits");
5726
+ return fromHex(text, "hash", 32);
5727
+ }
5728
+ function decimal(text) {
5729
+ if (!/^[0-9]+$/.test(text)) throw new Error(`${JSON.stringify(text)} is not a decimal integer`);
5730
+ const n = BigInt(text);
5731
+ if (n > U64_MAX) throw new Error(`${JSON.stringify(text)} is not a decimal integer`);
5732
+ return n;
5733
+ }
5734
+ function outputBytes(o) {
5735
+ return concat(hashBytes(o.id), u64be(o.size), hashBytes(o.sha256), u32be(o.segments.length), ...o.segments.map(hashBytes));
5736
+ }
5737
+ function reportMessage(f) {
5738
+ return concat(
5739
+ utf85(JOB_REPORT_DOMAIN),
5740
+ hashBytes(f.assignment),
5741
+ prefixed2(f.app),
5742
+ prefixed2(f.run),
5743
+ u32be(f.attempt),
5744
+ new Uint8Array([f.reason === null ? 0 : 1]),
5745
+ prefixed2(f.reason ?? ""),
5746
+ prefixed2(f.message),
5747
+ hashBytes(f.resultSha256),
5748
+ u32be(f.outputs.length),
5749
+ ...f.outputs.map(outputBytes),
5750
+ ...f.usage.map((n) => u64be(decimal(n))),
5751
+ ...f.log ? [utf85(JOB_REPORT_LOG_DOMAIN), outputBytes(f.log)] : []
5752
+ );
5753
+ }
5754
+ async function jobKeyBinding(transportKey, jobKey, release, cluster, node, clusterIdentity) {
5755
+ return hex(
5756
+ await sha2565(
5757
+ concat(utf85(JOB_KEY_DOMAIN), transportKey, jobKey, prefixed2(release), prefixed2(cluster), u64be(node), clusterIdentity ?? new Uint8Array(0))
5758
+ )
5759
+ );
5760
+ }
5761
+ function signedReason(outcome, reported) {
5762
+ if (outcome === "done") return { reason: null };
5763
+ if (outcome === "cancelled") return reported ? { reason: "cancelled" } : null;
5764
+ const bad = () => new Error(`the outcome ${JSON.stringify(outcome)} is not one a run ends with`);
5765
+ if (!outcome.startsWith("failed:")) throw bad();
5766
+ const reason = outcome.slice("failed:".length);
5767
+ if (JOB_FAIL_REASONS.includes(reason)) return { reason };
5768
+ if (!LEADER_FAIL_REASONS.includes(reason)) throw bad();
5769
+ return null;
5770
+ }
5771
+ var L = 2n ** 252n + 27742317777372353535851937790883648493n;
5772
+ var P = 2n ** 255n - 19n;
5773
+ var D = (P - 121665n) % P * modPow(121666n, P - 2n) % P;
5774
+ function modPow(base, exp) {
5775
+ let result = 1n;
5776
+ base %= P;
5777
+ for (; exp > 0n; exp >>= 1n, base = base * base % P) if (exp & 1n) result = result * base % P;
5778
+ return result;
5779
+ }
5780
+ function isSmallOrder(encoded) {
5781
+ let y = 0n;
5782
+ for (let i = 31; i >= 0; i--) y = y << 8n | BigInt(encoded[i] & (i === 31 ? 127 : 255));
5783
+ y %= P;
5784
+ const sign = encoded[31] >> 7 & 1;
5785
+ const y2 = y * y % P;
5786
+ const x2 = (y2 - 1n + P) % P * modPow((D * y2 + 1n) % P, P - 2n) % P;
5787
+ let x = modPow(x2, (P + 3n) / 8n);
5788
+ if (x * x % P !== x2) x = x * modPow(2n, (P - 1n) / 4n) % P;
5789
+ if (x * x % P !== x2) return false;
5790
+ if (Number(x & 1n) !== sign) x = (P - x) % P;
5791
+ let pt = [x, y];
5792
+ for (let i = 0; i < 3; i++) {
5793
+ const [x1, y1] = pt;
5794
+ const k = D * x1 * x1 * y1 * y1 % P;
5795
+ pt = [2n * x1 * y1 * modPow((1n + k) % P, P - 2n) % P, (y1 * y1 + x1 * x1) * modPow((1n - k + P) % P, P - 2n) % P];
5796
+ }
5797
+ return pt[0] === 0n && pt[1] === 1n;
5798
+ }
5799
+ async function verifyStrict(key, message, signature) {
5800
+ let s = 0n;
5801
+ for (let i = 63; i >= 32; i--) s = s << 8n | BigInt(signature[i]);
5802
+ if (s >= L || isSmallOrder(key) || isSmallOrder(signature.slice(0, 32))) return false;
5803
+ const publicKey = await crypto.subtle.importKey("raw", buf2(key), { name: "Ed25519" }, false, ["verify"]);
5804
+ return crypto.subtle.verify("Ed25519", publicKey, buf2(signature), buf2(message));
5805
+ }
5806
+ async function checkProof(receipt, step, p) {
5807
+ const expected = `${receipt.run}.${step}.${p.index}`;
5808
+ if (p.run !== expected || p.step !== step) throw new Error(`the proof of ${p.run} is listed as ${expected}`);
5809
+ const reported = p.signature != null;
5810
+ const signed = signedReason(p.outcome, reported);
5811
+ if (!signed) {
5812
+ const zero = [p.usage.cpuMicros, p.usage.gibMicros, p.usage.fuel].every((n) => n === "0");
5813
+ if (reported || p.reportSha256 != null || p.job != null || p.outputs.length > 0 || !zero) {
5814
+ throw new Error(`${p.run} ended ${p.outcome} by the leader, yet names a report, outputs or usage`);
5815
+ }
5816
+ return null;
5330
5817
  }
5331
- get session() {
5332
- return this.transport.session;
5818
+ const missing = (what) => new Error(`${p.run} ended ${p.outcome} but its proof has no ${what}`);
5819
+ if (p.node == null) throw missing("job node");
5820
+ if (p.jobKey == null) throw missing("job key");
5821
+ if (p.assignmentDigest == null) throw missing("assignment digest");
5822
+ if (p.reportSha256 == null) throw missing("report hash");
5823
+ if (p.signature == null) throw missing("report signature");
5824
+ if (p.job == null) throw missing("job evidence (it ended before receipts carried it)");
5825
+ const job = p.job;
5826
+ if (job.segments.length !== p.outputs.length) {
5827
+ throw new Error(`${p.run}: the job evidence lists segments for ${job.segments.length} outputs, the proof ${p.outputs.length}`);
5828
+ }
5829
+ const outputs = p.outputs.map((o, i) => ({ id: o.id, size: o.size, sha256: o.sha256, segments: job.segments[i] }));
5830
+ let message;
5831
+ try {
5832
+ message = reportMessage({
5833
+ assignment: p.assignmentDigest,
5834
+ app: receipt.app,
5835
+ run: p.run,
5836
+ attempt: p.attempt,
5837
+ reason: signed.reason,
5838
+ message: job.message ?? "",
5839
+ resultSha256: job.resultSha256,
5840
+ outputs,
5841
+ usage: [p.usage.cpuMicros, p.usage.gibMicros, p.usage.fuel],
5842
+ log: job.log
5843
+ });
5844
+ } catch (error) {
5845
+ throw new Error(`${p.run}: ${error instanceof Error ? error.message : String(error)}`);
5846
+ }
5847
+ if (hex(await sha2565(message)) !== p.reportSha256) throw new Error(`${p.run}: the report hash is not that of what the proof says`);
5848
+ const key = hashBytes(p.jobKey);
5849
+ if (!/^[0-9a-fA-F]{128}$/.test(p.signature)) throw new Error(`${p.run}: the report signature is not 64 bytes of hex`);
5850
+ if (!await verifyStrict(key, message, fromHex(p.signature, "signature", 64))) {
5851
+ throw new Error(`${p.run}: the job key did not sign what the proof says`);
5852
+ }
5853
+ return { key: p.jobKey, node: p.node };
5854
+ }
5855
+ async function verifyJobReports(receipt) {
5856
+ if (receipt.version !== RECEIPT_VERSION_JOBS) {
5857
+ throw new Error(`the receipt is version ${receipt.version}; only version ${RECEIPT_VERSION_JOBS} carries what each job signed`);
5858
+ }
5859
+ const keys = /* @__PURE__ */ new Map();
5860
+ for (const [step, s] of Object.entries(receipt.steps)) {
5861
+ for (const [i, entry] of s.runs.entries()) {
5862
+ if (entry.index !== i) throw new Error(`step ${step} lists run ${entry.index} where run ${i} belongs`);
5863
+ if ("cached" in entry) {
5864
+ if (!entry.cached) throw new Error(`step ${step} run ${i} is listed as not cached`);
5865
+ continue;
5866
+ }
5867
+ const proved = await checkProof(receipt, step, entry);
5868
+ if (proved && (keys.get(proved.key) ?? proved.node) !== proved.node) throw new Error(`job key ${proved.key} is named on two nodes`);
5869
+ if (proved) keys.set(proved.key, proved.node);
5870
+ }
5333
5871
  }
5334
- /** A JSON request through the transport, to an untyped path. */
5335
- json(method, path, body) {
5336
- return this.transport.json(method, path, { body });
5872
+ return keys;
5873
+ }
5874
+ async function verifyJobAttestation(receipt, cluster, key, node, policy) {
5875
+ const doc = receipt.jobAttestations && hasOwn(receipt.jobAttestations, key) ? receipt.jobAttestations[key] : void 0;
5876
+ if (!doc) throw new Error("the receipt carries no attestation for it");
5877
+ if (doc.jobKey !== key) throw new Error("its attestation is another key's");
5878
+ if (doc.node !== node || doc.cluster !== cluster) {
5879
+ throw new Error(`it is attested as node ${doc.node} of cluster ${doc.cluster}, not node ${node} of ${cluster}`);
5337
5880
  }
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);
5881
+ if (doc.clusterIdentity !== receipt.cluster) throw new Error("its job node takes work from another cluster identity");
5882
+ let nonce2;
5883
+ try {
5884
+ nonce2 = hashBytes(doc.nonce);
5885
+ } catch {
5886
+ throw new Error("its attestation's nonce is not 32 bytes of hex");
5887
+ }
5888
+ const binding = await jobKeyBinding(
5889
+ strictHex(doc.transportKey, "the transport key", 32),
5890
+ fromHex(key, "the job key", 32),
5891
+ doc.release.version,
5892
+ doc.cluster,
5893
+ doc.node,
5894
+ strictHex(doc.clusterIdentity, "the cluster identity", 32)
5895
+ );
5896
+ await verifyQuoteBinding(doc, nonce2, fromHex(binding, "binding", 32), policy, "job key");
5897
+ }
5898
+ async function verifyPipelineReceipt(client, app, run, answer, policy) {
5899
+ const { keys, cluster } = await verifyAppCluster(client, app, policy);
5900
+ if (!isObject(answer)) throw new Error("the receipt answer is not an object");
5901
+ const node = nodeId(answer.node, "the receipt answer");
5902
+ const key = keys.get(node);
5903
+ if (!key) throw new Error(`node ${node} is not an attested replica of ${app}`);
5904
+ const receipt = await verifyReceiptSignature(answer, key);
5905
+ if (receipt.app !== app) throw new Error(`the receipt is for app ${receipt.app}, not ${app}`);
5906
+ if (receipt.run !== run) throw new Error(`the receipt is for run ${receipt.run}, not ${run}`);
5907
+ for (const [jobKey, jobNode] of await verifyJobReports(receipt)) {
5908
+ try {
5909
+ await verifyJobAttestation(receipt, cluster, jobKey, jobNode, policy);
5910
+ } catch (error) {
5911
+ throw new Error(`job key ${jobKey}: ${error instanceof Error ? error.message : String(error)}`);
5912
+ }
5341
5913
  }
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
- );
5914
+ return receipt;
5915
+ }
5916
+
5917
+ // src/client/approvals.ts
5918
+ var MAX_REPORT_PAGE = 100;
5919
+ function pageQuery(page = {}) {
5920
+ const q = new URLSearchParams();
5921
+ if (page.after !== void 0) q.set("after", page.after);
5922
+ if (page.limit !== void 0) {
5923
+ if (!Number.isInteger(page.limit) || page.limit < 1 || page.limit > MAX_REPORT_PAGE) {
5924
+ throw new RangeError(`limit is 1 to ${MAX_REPORT_PAGE}`);
5925
+ }
5926
+ q.set("limit", String(page.limit));
5349
5927
  }
5350
- // ---------------------------------------------------------------- identity
5351
- /**
5352
- * Create an account with a new passkey, and sign in. The node then asks the
5353
- * new passkey to sign the account it creates (`412 CONFIRM_REQUIRED`), so a
5354
- * sign-up prompts twice: create, then sign. On a page whose origin is not
5355
- * the cluster's ({@link SignInOptions}), the node makes the passkey for that
5356
- * origin's relying party (the confirmation's `rpId` is that origin's too)
5357
- * and binds the session to the package the origin is registered for; an
5358
- * unregistered origin is refused with {@link OriginNotRegistered}.
5359
- *
5360
- * `invite` ({@link SignUpOptions}) goes on both halves and on the retry,
5361
- * as the node judges it on each before it spends anything; a sign-up the
5362
- * cluster's policy refuses, or an unknown, expired or used invite, is
5363
- * {@link SignUpRefused} (from `begin`, before any passkey is made).
5364
- */
5365
- async signUp(passkey, name, options = {}) {
5366
- const origin = this.pageOrigin(options);
5367
- const invite = options.invite ? { invite: options.invite } : {};
5368
- const begin = await this.begin(
5369
- this.auth.registerBegin({ ...origin === void 0 ? { name, ...invite } : { name, origin, ...invite } }),
5370
- origin
5371
- );
5372
- const signal = options.signal;
5373
- const registration = await (signal ? passkey.create(begin.options, { signal }) : passkey.create(begin.options));
5374
- const session = await this.auth.registerFinish({ challengeId: begin.challengeId, registration, ...invite }, this.confirmWith(passkey, { signal }));
5375
- this.useSession(session);
5376
- return session;
5377
- }
5378
- /**
5379
- * Sign in with an existing passkey. On a page whose origin is not the
5380
- * cluster's ({@link SignInOptions}), the assertion is made for that
5381
- * origin's relying-party id, as the node answers it, and the session is
5382
- * bound to the origin's package; an unregistered origin is refused with
5383
- * {@link OriginNotRegistered}. A passkey this cluster does not know (made
5384
- * on another cluster, or removed) is refused with {@link PasskeyUnknownHere}.
5385
- */
5386
- async signIn(passkey, options = {}) {
5387
- const origin = this.pageOrigin(options);
5388
- const begin = await this.begin(this.auth.loginBegin({ ...origin === void 0 ? {} : { origin } }), origin);
5389
- const rpId = begin.options.rpId ?? begin.options.rp?.id ?? "";
5390
- const challenge = fromB64url(begin.options.challenge);
5391
- const assertion = await (options.signal ? passkey.get(challenge, rpId, void 0, { signal: options.signal }) : passkey.get(challenge, rpId));
5392
- const session = await this.auth.loginFinish({ challengeId: begin.challengeId, assertion });
5393
- this.useSession(session);
5394
- return session;
5395
- }
5396
- /**
5397
- * The origin a sign-up or sign-in sends: the one given, or the page's own
5398
- * when it is not a node's origin; `undefined` for none.
5399
- */
5400
- pageOrigin(options) {
5401
- if (options.origin !== void 0) return options.origin ?? void 0;
5402
- const page = globalThis.location?.origin;
5403
- if (!page || page === "null") return void 0;
5404
- const nodes = new Set(
5405
- this.transport.nodes.map((url2) => {
5406
- try {
5407
- return new URL(url2).origin;
5408
- } catch {
5409
- return url2;
5410
- }
5411
- })
5412
- );
5413
- return nodes.has(page) ? void 0 : page;
5928
+ const s = q.toString();
5929
+ return s ? `?${s}` : "";
5930
+ }
5931
+ function compareVersions(a, b) {
5932
+ try {
5933
+ return compareReleaseVersions(a, b);
5934
+ } catch {
5935
+ return a < b ? -1 : a > b ? 1 : 0;
5414
5936
  }
5415
- /** POST a ceremony's `begin`, naming the page's `origin` in an {@link OriginNotRegistered} the node leaves it out of. */
5416
- async begin(result, origin) {
5417
- try {
5418
- return await this.as(result);
5419
- } catch (error) {
5420
- if (error instanceof OriginNotRegistered && !error.origin && origin !== void 0) {
5421
- throw new OriginNotRegistered(error.nodeMessage, { ...error.details, origin });
5422
- }
5423
- throw error;
5937
+ }
5938
+ function stalledBy(approved, deadlines, now = Date.now() / 1e3) {
5939
+ if (approved === null || approved.length === 0) return null;
5940
+ const newest = approved.reduce((a, b) => compareVersions(a, b) >= 0 ? a : b);
5941
+ let stall = null;
5942
+ for (const d of deadlines) {
5943
+ if (d.afterSecs <= now && compareVersions(newest, d.version) < 0) {
5944
+ if (stall === null || compareVersions(d.version, stall.version) > 0) stall = d;
5424
5945
  }
5425
5946
  }
5426
- /**
5427
- * Swap the refresh token for a new session, on whichever node the client
5428
- * uses: any node of the cluster takes it. A refresh token is used once, so
5429
- * calls made while one refresh is under way share it rather than sending the
5430
- * same token again (which would revoke the session).
5431
- */
5432
- refresh() {
5433
- return this.transport.refresh();
5434
- }
5435
- /**
5436
- * End this session. The client is signed out whether or not the node
5437
- * answers: the revoke (`POST /auth/logout`) is attempted, and its failure
5438
- * (the node unreachable, say) is thrown after the session is dropped, so a
5439
- * caller can say the server may still hold it, but no request after this
5440
- * one carries its token.
5441
- */
5442
- async signOut() {
5443
- await this.signingOut(this.auth.logout());
5444
- }
5445
- /**
5446
- * End every session of the signed-in account, on every device, this one
5447
- * too. Like {@link signOut}, this client is signed out even when the
5448
- * request fails, and the failure is thrown.
5449
- */
5450
- async signOutEverywhere() {
5451
- await this.signingOut(this.auth.logoutAll());
5452
- }
5453
- async signingOut(result) {
5454
- try {
5455
- await result;
5456
- } finally {
5457
- this.transport.signOut();
5458
- }
5947
+ return stall;
5948
+ }
5949
+ function publisherBindingMessage(cluster, org, signerId, generation) {
5950
+ return `calimero-publisher-binding/v1
5951
+ ${cluster}
5952
+ ${org}
5953
+ ${signerId}
5954
+ ${generation}`;
5955
+ }
5956
+ function publisherBindingBytes(cluster, org, signerId, generation) {
5957
+ return new TextEncoder().encode(publisherBindingMessage(cluster, org, signerId, generation));
5958
+ }
5959
+ var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5960
+ async function confirmationCode(requestId) {
5961
+ const h = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(requestId)));
5962
+ const word = (h[0] << 24 | h[1] << 16 | h[2] << 8 | h[3]) >>> 0;
5963
+ let code = "";
5964
+ for (let i = 0; i < 6; i++) {
5965
+ if (i === 3) code += "-";
5966
+ code += CROCKFORD[word >>> 27 - 5 * i & 31];
5459
5967
  }
5460
- /**
5461
- * Add another passkey (another device, `passkey`) to the signed-in account;
5462
- * answers its credential id. The node asks for the approval of a passkey
5463
- * the account already has (`412 CONFIRM_REQUIRED`, never the new one),
5464
- * which `approver` gives.
5465
- */
5466
- async addPasskey(passkey, approver) {
5467
- const begin = await this.as(this.auth.passkeyAddBegin());
5468
- const registration = await passkey.create(begin.options);
5469
- const { credentialId } = await this.auth.passkeyAddFinish({ challengeId: begin.challengeId, registration }, this.confirmWith(approver));
5470
- return credentialId;
5968
+ return code;
5969
+ }
5970
+ function consentReturn(href) {
5971
+ const url2 = typeof href === "string" ? new URL(href) : href;
5972
+ const requestId = url2.searchParams.get("request_id");
5973
+ const result = url2.searchParams.get("result");
5974
+ if (!requestId || result !== "approved" && result !== "declined") return null;
5975
+ return { requestId, result };
5976
+ }
5977
+ function withoutConsentReturn(href) {
5978
+ const url2 = new URL(String(href));
5979
+ url2.searchParams.delete("request_id");
5980
+ url2.searchParams.delete("result");
5981
+ return url2.toString();
5982
+ }
5983
+ var CONSENT_STORAGE_KEY = "calimero.consent";
5984
+ var RELEASE_VERIFIER = "https://mero-tee.vercel.app";
5985
+ function releaseNotesUrl(version) {
5986
+ return `https://github.com/calimero-network/mero-tee/releases/tag/mero-tee-v${encodeURIComponent(version)}`;
5987
+ }
5988
+ function verifierUrl(query) {
5989
+ return `${RELEASE_VERIFIER}/mero-tee?${new URLSearchParams(query)}`;
5990
+ }
5991
+ function verifyReleaseUrl(version) {
5992
+ return verifierUrl({ release_tag: `mero-tee-v${version}` });
5993
+ }
5994
+ function verifyNodeUrl(nodeUrl, release) {
5995
+ return verifierUrl({ node_url: nodeUrl.replace(/\/+$/, ""), release_tag: `mero-tee-v${release}` });
5996
+ }
5997
+ function pendingApprovalsFrom(report, rules, now = Date.now() / 1e3) {
5998
+ const deadlineOf = (v) => rules.deadlines.find((d) => d.version === v) ?? null;
5999
+ const releasesActionable = report.governance.releases === "owner";
6000
+ const upgradesActionable = report.governance.appUpgrades === "owner";
6001
+ const releases = report.clusterReleases.filter((r) => !r.approved).sort((a, b) => compareVersions(b.release, a.release)).map((r) => ({
6002
+ version: r.release,
6003
+ nodes: r.nodes,
6004
+ actionable: releasesActionable,
6005
+ releaseNotesUrl: releaseNotesUrl(r.release),
6006
+ verifyUrl: verifyReleaseUrl(r.release),
6007
+ deadline: deadlineOf(r.release)
6008
+ }));
6009
+ const upgrades = [];
6010
+ for (const a of report.apps) {
6011
+ const available = a.availableVersions ?? [];
6012
+ if (a.package === null || available.length === 0) continue;
6013
+ const latest = available[available.length - 1];
6014
+ const reachable = a.latestReachable === void 0 ? latest : a.latestReachable;
6015
+ upgrades.push({
6016
+ app: a.app,
6017
+ name: a.name ?? null,
6018
+ package: a.package.package,
6019
+ from: a.package.version,
6020
+ to: reachable ?? latest,
6021
+ reachable: reachable !== null,
6022
+ blocked: a.latestBlocked ?? null,
6023
+ available,
6024
+ actionable: upgradesActionable
6025
+ });
5471
6026
  }
5472
- // ---------------------------------------------------------------- account recovery
5473
- //
5474
- // core #4844 (`docs/specs/account-recovery.md`): a recovery code, made with
5475
- // a passkey and shown once, lets someone who lost every passkey register a
5476
- // new one; it is added, and the account signed in, 72 hours later unless a
5477
- // passkey the account still has cancels it first.
5478
- /**
5479
- * Signed out: start recovering the account `code` names. `passkey` makes a
5480
- * new passkey for it (the browser's create prompt, user verified); the
5481
- * node spends the code and keeps the passkey as pending. Nothing is added
5482
- * and no session opens: finish with {@link finishAccountRecovery} at
5483
- * `readyAt`. A code the cluster does not hold (mistyped, replaced or
5484
- * spent) is {@link WrongRecoveryCode}; an account with a recovery already
5485
- * under way `409 RECOVERY_PENDING`.
5486
- */
5487
- async startAccountRecovery(code, passkey) {
5488
- try {
5489
- const begin = await this.as(this.auth.accountRecoveryBegin({ code }));
5490
- const registration = await passkey.create(begin.options);
5491
- return await this.auth.accountRecoveryStart({ challengeId: begin.challengeId, code, registration });
5492
- } catch (error) {
5493
- if (error instanceof LoginRequired) throw new WrongRecoveryCode(error.message.replace(/^401 UNAUTHENTICATED: /, ""), error.details);
5494
- throw error;
5495
- }
6027
+ return {
6028
+ scope: report.scope,
6029
+ governance: report.governance,
6030
+ approvedReleases: report.approvedReleases,
6031
+ releases,
6032
+ upgrades,
6033
+ stalledBy: stalledBy(report.approvedReleases, rules.deadlines, now),
6034
+ actionable: releases.some((r) => r.actionable) || upgrades.some((u) => u.actionable)
6035
+ };
6036
+ }
6037
+ function releaseConsent(scope, version, returnTo, options = {}) {
6038
+ return {
6039
+ kind: "release",
6040
+ scope: scope.kind === "org" ? { org: scope.org } : "account",
6041
+ subject: options.withdraw ? { version, withdraw: true } : { version },
6042
+ returnTo
6043
+ };
6044
+ }
6045
+ function withdrawConsent(scope, version, returnTo) {
6046
+ return releaseConsent(scope, version, returnTo, { withdraw: true });
6047
+ }
6048
+ function upgradeConsent(app, toVersion, returnTo) {
6049
+ return { kind: "upgrade", subject: { app, toVersion }, returnTo };
6050
+ }
6051
+ function createOrgConsent(name, returnTo) {
6052
+ return { kind: "createOrg", subject: { name }, returnTo };
6053
+ }
6054
+ function createInviteConsent(subject, returnTo) {
6055
+ return { kind: "createInvite", subject, returnTo };
6056
+ }
6057
+ function acceptInviteConsent(token, returnTo) {
6058
+ return { kind: "acceptInvite", subject: { token }, returnTo };
6059
+ }
6060
+ function leaveOrgConsent(org, returnTo) {
6061
+ return { kind: "leaveOrg", subject: { org }, returnTo };
6062
+ }
6063
+ function removeMemberConsent(org, account, returnTo) {
6064
+ return { kind: "removeMember", subject: { org, account }, returnTo };
6065
+ }
6066
+ function setMemberRoleConsent(org, account, role, returnTo) {
6067
+ return { kind: "setMemberRole", subject: { org, account, role }, returnTo };
6068
+ }
6069
+ function setMemberTeamsConsent(org, account, teams, returnTo) {
6070
+ return { kind: "setMemberTeams", subject: { org, account, teams }, returnTo };
6071
+ }
6072
+ function removeMemberTeamsConsent(org, account, teams, returnTo) {
6073
+ return { kind: "removeMemberTeams", subject: { org, account, teams }, returnTo };
6074
+ }
6075
+ function revokeInviteConsent(org, inviteKey, returnTo) {
6076
+ return { kind: "revokeInvite", subject: { org, inviteKey }, returnTo };
6077
+ }
6078
+ function renameOrgConsent(org, name, returnTo) {
6079
+ return { kind: "renameOrg", subject: { org, name }, returnTo };
6080
+ }
6081
+ function deleteOrgConsent(org, returnTo) {
6082
+ return { kind: "deleteOrg", subject: { org }, returnTo };
6083
+ }
6084
+ function setCapabilitiesConsent(subject, returnTo) {
6085
+ return { kind: "setCapabilities", subject, returnTo };
6086
+ }
6087
+ function setAllAppsConsent(org, account, allApps, returnTo) {
6088
+ return { kind: "setAllApps", subject: { org, account, allApps }, returnTo };
6089
+ }
6090
+
6091
+ // src/client/calimero-client.ts
6092
+ var FILE_PART_BYTES = 16 * 1024 * 1024;
6093
+ var PART_RESENDS = 1;
6094
+ var MAX_FAILURES = 8;
6095
+ var MAX_JUMPS = 16;
6096
+ var CALL_RETRIES = 8;
6097
+ function deployerKey(deployer) {
6098
+ return "account" in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
6099
+ }
6100
+ async function frontendManifest(origin, fetcher = fetch) {
6101
+ const base = origin ?? globalThis.location?.origin;
6102
+ if (!base) throw new Error("no page origin to read the frontend manifest from; pass `origin`");
6103
+ const response = await fetcher(new URL("/.well-known/calimero.json", base).toString());
6104
+ if (!response.ok) throw await refusal(response);
6105
+ const manifest = await response.json();
6106
+ return { ...manifest, deployments: manifest.deployments ?? [] };
6107
+ }
6108
+ function pageDeployment(href) {
6109
+ const at = href ?? globalThis.location?.href;
6110
+ if (!at) return null;
6111
+ try {
6112
+ return new URL(at).searchParams.get("deployment") || null;
6113
+ } catch {
6114
+ return null;
5496
6115
  }
6116
+ }
6117
+ function pageParams(page) {
6118
+ pageQuery(page);
6119
+ return { after: page.after, limit: page.limit };
6120
+ }
6121
+ function toHex(bytes) {
6122
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
6123
+ }
6124
+ function presenceState(state) {
6125
+ return state === null ? null : toHex(state);
6126
+ }
6127
+ async function readSlice(data, start, end) {
6128
+ if (data instanceof Blob) return new Uint8Array(await data.slice(start, end).arrayBuffer());
6129
+ return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);
6130
+ }
6131
+ function nextPart(answer, parts) {
6132
+ const next = answer?.next;
6133
+ if (typeof next === "number" && Number.isInteger(next) && next >= 0 && next <= parts) return next;
6134
+ throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);
6135
+ }
6136
+ var CalimeroClient = class _CalimeroClient {
5497
6137
  /**
5498
- * Signed out, once the delay passed: finish the recovery with the passkey
5499
- * it registered (`passkey` signs the node's sign-in challenge). The passkey
5500
- * joins the account, every other session of the account ends, and this
5501
- * client is signed in. `accountId` (from the start) lets the node refuse
5502
- * early and offer only that passkey; before `readyAt` it is
5503
- * {@link RecoveryNotReady}, with no recovery under way {@link NotFound}.
6138
+ * A client for the Calimero Cloud cluster named `cluster`: its node list read
6139
+ * from the public node directory, those in `zone` first, each group in
6140
+ * weighted-random order. The directory only picks which nodes to try: each is
6141
+ * attested under `policy` before anything is sent to it. Throws
6142
+ * {@link DirectoryError} when the directory names no usable node.
6143
+ *
6144
+ * The list is read again in the background after a failover, and at the
6145
+ * first request once the directory's `refreshAfterSeconds` has passed.
5504
6146
  */
5505
- async finishAccountRecovery(passkey, accountId) {
5506
- const session = await this.auth.accountRecoveryFinish({ ...accountId ? { accountId } : {} }, this.confirmWith(passkey));
5507
- this.useSession(session);
5508
- return session;
5509
- }
5510
- // ---------------------------------------------------------------- apps
5511
- /** One of `app`'s blobs, by id (base58 or hex). */
5512
- async downloadBlob(app, id) {
5513
- return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());
5514
- }
5515
- get exportClient() {
5516
- return { exportsExport: this.apps.exportsExport, request: this.transport.request.bind(this.transport) };
6147
+ static async connect(options, challenges = {}) {
6148
+ const transport = await directoryTransport({ ...options, directory: options.directory ?? DEFAULT_DIRECTORY });
6149
+ return new _CalimeroClient(transport, challenges);
5517
6150
  }
5518
6151
  /**
5519
- * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,
5520
- * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of
5521
- * the file. A failed check is an `ExportError`; `signal` aborts the download.
6152
+ * A client of the nodes `options` names, or one sending through an existing
6153
+ * `transport`. `challenges` answers the node's challenges for every
6154
+ * generated method a call's own options leave open (`confirm` a
6155
+ * `412 CONFIRM_REQUIRED`, `operatorProof` a `428 OPERATOR_SIGNATURE_REQUIRED`).
5522
6156
  */
5523
- exportFileTo(app, id, sink, signal) {
5524
- return exportFileTo(this.exportClient, app, id, sink, signal);
6157
+ constructor(options, challenges = {}) {
6158
+ this.transport = options instanceof NodeTransport ? options : new NodeTransport(options);
6159
+ const routes = createRoutes(createRouteClient(this.transport, challenges));
6160
+ this.apps = routes.apps;
6161
+ this.auth = routes.auth;
6162
+ this.consent = routes.consent;
6163
+ this.ops = routes.ops;
6164
+ this.orgs = routes.orgs;
6165
+ this.public = routes.public;
6166
+ this.packages = routes.packages;
6167
+ this.deployments = routes.deployments;
5525
6168
  }
5526
- /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */
5527
- exportFile(app, id, signal) {
5528
- return exportFile(this.exportClient, app, id, signal);
6169
+ /** A generated method's answer, as the type this class has always answered. */
6170
+ as(result) {
6171
+ return result;
5529
6172
  }
5530
- /**
5531
- * Download a component app's blob with a grant one of its runs handed out
5532
- * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
5533
- * permission. A bad or expired grant answers `NotFound`, as a missing blob.
5534
- */
5535
- async downloadBlobGranted(app, id, grant) {
5536
- return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());
6173
+ /** The options that answer a `412 CONFIRM_REQUIRED` with `passkey`, when one is given. */
6174
+ confirmWith(passkey, options = {}) {
6175
+ return passkey ? { confirm: passkeyConfirm(passkey, options) } : void 0;
5537
6176
  }
5538
- /**
5539
- * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
5540
- * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
5541
- * file for each, so one that may have reached it is never repeated); a larger file
5542
- * is a session of parts, each sent again after a dropped connection or a `503`.
5543
- * A session the node lost is begun again once; any other failure aborts it.
5544
- * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
5545
- */
5546
- async uploadFile(app, data) {
5547
- const size = data instanceof Blob ? data.size : data.byteLength;
5548
- if (size <= FILE_PART_BYTES) return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });
5549
- try {
5550
- return await this.uploadSession(app, data, size);
5551
- } catch (error) {
5552
- if (!(error instanceof CalimeroError) || error.code !== "UPLOAD_UNKNOWN") throw error;
5553
- return this.uploadSession(app, data, size);
5554
- }
6177
+ /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved the client on. */
6178
+ get nodeUrl() {
6179
+ return this.transport.nodeUrl;
5555
6180
  }
5556
- /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
5557
- async uploadSession(app, data, size) {
5558
- const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));
5559
- const { uploadId: upload, partBytes, parts } = begin;
5560
- if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {
5561
- throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);
5562
- }
5563
- try {
5564
- await this.sendParts(app, upload, data, size, partBytes, parts);
5565
- return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));
5566
- } catch (error) {
5567
- if (!(error instanceof CalimeroError && error.code === "UPLOAD_UNKNOWN")) await this.apps.uploadAbort({ app, upload }).catch(() => void 0);
5568
- throw error;
5569
- }
6181
+ /** Every node this client may use, in the order it moves through them. */
6182
+ get nodes() {
6183
+ return this.transport.nodes;
5570
6184
  }
5571
- /** Send every part, in order, from wherever the node says the session is. */
5572
- async sendParts(app, upload, data, size, partBytes, parts) {
5573
- let [next, failures, jumps] = [0, 0, 0];
5574
- while (next < parts) {
5575
- try {
5576
- const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));
5577
- next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);
5578
- failures = 0;
5579
- continue;
5580
- } catch (error) {
5581
- if (error instanceof CalimeroError && error.code === "PART_OUT_OF_ORDER") {
5582
- jumps += 1;
5583
- if (jumps > MAX_JUMPS) throw error;
5584
- next = nextPart(error.details, parts);
5585
- continue;
5586
- }
5587
- if (!this.isTransient(error) || ++failures > MAX_FAILURES) throw error;
5588
- await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));
5589
- if (failures > PART_RESENDS) {
5590
- try {
5591
- const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);
5592
- if (at > next) failures = 0;
5593
- next = at;
5594
- } catch (asked) {
5595
- if (!this.isTransient(asked)) throw asked;
5596
- }
5597
- }
5598
- }
5599
- }
6185
+ /** What the check of node `url` (from {@link nodes}; default: in use) established, or `undefined` before it first ran. */
6186
+ verification(url2) {
6187
+ return this.transport.verification(url2);
5600
6188
  }
5601
- /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
5602
- async untilAvailable(send) {
5603
- for (let retry = 0; ; retry++) {
5604
- try {
5605
- return await send();
5606
- } catch (error) {
5607
- if (!this.isTransient(error) || retry >= CALL_RETRIES) throw error;
5608
- await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));
5609
- }
5610
- }
6189
+ /** Wait for the check requests wait for, starting it if needed, and answer its outcome (not thrown) without a request. */
6190
+ verify(url2) {
6191
+ return this.transport.verify(url2);
5611
6192
  }
5612
- /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
5613
- isTransient(error) {
5614
- return error instanceof UnavailableError || this.transport.isNetworkFailure(error);
6193
+ /** Authenticate every request with an API key. */
6194
+ useApiKey(key) {
6195
+ this.transport.useApiKey(key);
5615
6196
  }
5616
- // ---------------------------------------------------------------- packages
5617
- // ---------------------------------------------------------------- app instances
5618
- /** Committed events from index `from`, then live, until `signal` aborts. */
5619
- events(app, from = 0, signal) {
5620
- return this.transport.events(routePath("apps/{app}/events", { app }), { query: { from }, signal });
6197
+ useSession(session) {
6198
+ this.transport.useSession(session);
5621
6199
  }
5622
- // ---------------------------------------------------------------- presence
5623
- /**
5624
- * Presence as a stream until `signal` aborts: a `snapshot` event (`data` the
5625
- * entries present), then a `presence` event (`data` one entry) per change.
5626
- */
5627
- presenceStream(app, signal) {
5628
- return this.transport.events(routePath("apps/{app}/presence/stream", { app }), { signal });
6200
+ get session() {
6201
+ return this.transport.session;
5629
6202
  }
5630
- // ---------------------------------------------------------------- aliases
5631
- // ---------------------------------------------------------------- organizations
5632
- /**
5633
- * Start handing `org` to the signed-in account with the recovery seed,
5634
- * which signs here and never leaves this process. Finish with
5635
- * `client.orgs.recoveryFinish` once `readyAt` has passed; until then the owner may
5636
- * cancel. A wrong seed (or no organization, or none set) is a `403`.
5637
- */
5638
- async startRecovery(org, seed) {
5639
- const account = (await this.auth.me()).accountId;
5640
- const nonce2 = b64url(crypto.getRandomValues(new Uint8Array(16)));
5641
- const signature = await signRecovery(seed, org, account, nonce2);
5642
- return this.orgs.recoveryStart({ org, nonce: nonce2, signature });
6203
+ /** A JSON request through the transport, to an untyped path. */
6204
+ json(method, path, body) {
6205
+ return this.transport.json(method, path, { body });
5643
6206
  }
5644
- // ---------------------------------------------------------------- approvals
5645
- /** The report of a scope's apps (`GET /orgs/{org}/apps`, or with `org` `null` the account's own, `GET /auth/apps`), every page, with the apps of all of them in `apps`. */
5646
- async appsReportAll(org) {
5647
- const report = (page = {}) => org === null ? this.auth.accountApps(pageParams(page)) : this.orgs.apps({ org, ...pageParams(page) });
5648
- const first = await report();
5649
- const apps = [...first.apps];
5650
- let next = first.next;
5651
- while (next !== null) {
5652
- const page = await report({ after: next });
5653
- apps.push(...page.apps);
5654
- next = page.next;
5655
- }
5656
- return { ...first, apps, next: null };
6207
+ /** Attest `app` on node `url` (from {@link nodes}; default: in use): the record's `appHash` is the one the node bound. */
6208
+ attestApp(app, url2) {
6209
+ return this.transport.attestApp(app, url2);
5657
6210
  }
5658
- /**
5659
- * What waits for a decision in a scope (`org`, or the account's own apps
5660
- * with `null`): mero-tee releases the cluster's nodes run that the scope has
5661
- * not approved, apps with newer releases of their package, and whether a
5662
- * passed deadline stops new work. Read over the sealed channel; act on an
5663
- * item by sending the user to the consent page (`client.consent.pageCreate`,
5664
- * `releaseConsent`, `upgradeConsent`).
5665
- */
5666
- async pendingApprovals(org = null) {
5667
- const [report, rules] = await Promise.all([this.appsReportAll(org), this.public.releasesPublic()]);
5668
- return pendingApprovalsFrom(report, rules);
6211
+ /** The manifest facts and ABI of a package version (of `service`, for a multi-service release), for a signed-in caller. */
6212
+ packageCapabilities(pkg, version, options = {}) {
6213
+ return this.transport.json(
6214
+ "GET",
6215
+ routePath("packages/{package}/{version}/capabilities", { package: pkg, version }),
6216
+ { query: { service: options.service } }
6217
+ );
5669
6218
  }
6219
+ // ---------------------------------------------------------------- identity
5670
6220
  /**
5671
- * `client.consent.pageCreate`, then send the browser to the consent page
5672
- * (`navigate`, by default `window.location.assign`). Pass `navigate` itself
5673
- * or {@link OpenConsentOptions}, whose `confirm` runs first with the node's
5674
- * answer so the app can show the person its `code`; when it answers `false`
5675
- * the page is not opened. When the node sends a `code` that is not
5676
- * {@link confirmationCode} of `requestId`, it throws `CalimeroError`
5677
- * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
5678
- * once `navigate` returns (or `confirm` declines): with a popup
5679
- * (`url => window.open(url)`), poll it with {@link waitForConsent}.
5680
- * Before navigating it keeps `requestId` in `sessionStorage` (where there
5681
- * is one), for {@link resumeConsent} when the page sends the person back.
6221
+ * Create an account with a new passkey, and sign in. The node then asks the
6222
+ * new passkey to sign the account it creates (`412 CONFIRM_REQUIRED`), so a
6223
+ * sign-up prompts twice: create, then sign. On a page whose origin is not
6224
+ * the cluster's ({@link SignInOptions}), the node makes the passkey for that
6225
+ * origin's relying party (the confirmation's `rpId` is that origin's too)
6226
+ * and binds the session to the package the origin is registered for; an
6227
+ * unregistered origin is refused with {@link OriginNotRegistered}.
6228
+ *
6229
+ * `invite` ({@link SignUpOptions}) goes on both halves and on the retry,
6230
+ * as the node judges it on each before it spends anything; a sign-up the
6231
+ * cluster's policy refuses, or an unknown, expired or used invite, is
6232
+ * {@link SignUpRefused} (from `begin`, before any passkey is made).
5682
6233
  */
5683
- async openConsentPage(request, navigateOrOptions = {}) {
5684
- const options = typeof navigateOrOptions === "function" ? { navigate: navigateOrOptions } : navigateOrOptions;
5685
- const navigate = options.navigate ?? ((url2) => {
5686
- const w = globalThis.window;
5687
- if (!w) throw new Error("no window to open the consent page in; pass `navigate`");
5688
- w.location.assign(url2);
5689
- });
5690
- const started = await this.consent.pageCreate({ body: request });
5691
- if (started.code !== void 0) {
5692
- const expected = await confirmationCode(started.requestId);
5693
- if (started.code !== expected) {
5694
- throw new CalimeroError(200, "CONSENT_CODE_MISMATCH", "the consent page code does not match the request", {
5695
- requestId: started.requestId,
5696
- code: started.code,
5697
- expected
5698
- });
5699
- }
5700
- }
5701
- if (options.confirm && !await options.confirm(started)) return started;
5702
- try {
5703
- consentStorage()?.setItem(CONSENT_STORAGE_KEY, started.requestId);
5704
- } catch {
5705
- }
5706
- navigate(started.url);
5707
- return started;
6234
+ async signUp(passkey, name, options = {}) {
6235
+ const origin = this.pageOrigin(options);
6236
+ const invite = options.invite ? { invite: options.invite } : {};
6237
+ const begin = await this.begin(
6238
+ this.auth.registerBegin({ ...origin === void 0 ? { name, ...invite } : { name, origin, ...invite } }),
6239
+ origin
6240
+ );
6241
+ const signal = options.signal;
6242
+ const registration = await (signal ? passkey.create(begin.options, { signal }) : passkey.create(begin.options));
6243
+ const session = await this.auth.registerFinish({ challengeId: begin.challengeId, registration, ...invite }, this.confirmWith(passkey, { signal }));
6244
+ this.useSession(session);
6245
+ return session;
5708
6246
  }
5709
6247
  /**
5710
- * On the page the consent page sent the person back to
5711
- * (`returnTo?request_id=…&result=…`): the decision on the request this page
5712
- * started, read from the node (`GET /consent/{id}/result`), never from the
5713
- * URL. `null` when the URL carries no `request_id`. The request is
5714
- * `options.requestId`, or the one {@link openConsentPage} stored in this
5715
- * tab; with the default `href` (`location.href`) the parameters are then
5716
- * removed with `history.replaceState`, and the stored id once decided.
5717
- *
5718
- * Throws `CalimeroError`:
5719
- * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;
5720
- * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;
5721
- * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the
5722
- * page sent the person back, a sign that another request was approved on a
5723
- * page that was not the node's. Do not act on it;
5724
- * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):
5725
- * an account has one undecided request per node, and a newer one replaced
5726
- * it, possibly on a page that was not the node's. Do not act on it either.
5727
- *
5728
- * The URL's `result` is never trusted: the answer's `status` is the node's.
5729
- * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is
5730
- * in the answer, typed by `kind`.
6248
+ * Sign in with an existing passkey. On a page whose origin is not the
6249
+ * cluster's ({@link SignInOptions}), the assertion is made for that
6250
+ * origin's relying-party id, as the node answers it, and the session is
6251
+ * bound to the origin's package; an unregistered origin is refused with
6252
+ * {@link OriginNotRegistered}. A passkey this cluster does not know (made
6253
+ * on another cluster, or removed) is refused with {@link PasskeyUnknownHere}.
5731
6254
  */
5732
- async resumeConsent(options = {}) {
5733
- const g = globalThis;
5734
- const href = options.href ?? g.location?.href;
5735
- if (href === void 0) throw new Error("no page to read the consent return from; pass `href`");
5736
- const url2 = new URL(href);
5737
- const returned = url2.searchParams.get("request_id");
5738
- if (!returned) return null;
5739
- if (options.href === void 0 && g.history) g.history.replaceState(g.history.state, "", withoutConsentReturn(url2));
5740
- let ownId = options.requestId;
5741
- if (ownId === void 0) {
5742
- try {
5743
- ownId = consentStorage()?.getItem(CONSENT_STORAGE_KEY) ?? void 0;
5744
- } catch {
5745
- ownId = void 0;
5746
- }
5747
- }
5748
- if (!ownId) {
5749
- throw new CalimeroError(200, "CONSENT_NOT_STARTED", "this page started no consent request", { returned });
5750
- }
5751
- if (returned !== ownId) {
5752
- throw new CalimeroError(200, "CONSENT_REQUEST_MISMATCH", "the consent page returned another request than this page started", {
5753
- requestId: ownId,
5754
- returned
5755
- });
5756
- }
5757
- let result;
5758
- try {
5759
- result = await this.consent.pageResult({ request: ownId });
5760
- } catch (e) {
5761
- if (e instanceof NotFound) {
5762
- forgetConsent(ownId);
5763
- throw new CalimeroError(404, "CONSENT_REPLACED", "this page's consent request was replaced by a newer one", {
5764
- requestId: ownId
5765
- });
5766
- }
5767
- throw e;
5768
- }
5769
- if (result.requestId !== ownId) {
5770
- throw new CalimeroError(200, "CONSENT_REQUEST_MISMATCH", "the node answered another request", { requestId: ownId, returned: result.requestId });
5771
- }
5772
- if (result.status === "pending") {
5773
- throw new CalimeroError(200, "CONSENT_NOT_DECIDED", "the consent page returned, but this request is still pending", {
5774
- requestId: ownId
5775
- });
5776
- }
5777
- forgetConsent(ownId);
5778
- return result;
6255
+ async signIn(passkey, options = {}) {
6256
+ const origin = this.pageOrigin(options);
6257
+ const begin = await this.begin(this.auth.loginBegin({ ...origin === void 0 ? {} : { origin } }), origin);
6258
+ const rpId = begin.options.rpId ?? begin.options.rp?.id ?? "";
6259
+ const challenge = fromB64url(begin.options.challenge);
6260
+ const assertion = await (options.signal ? passkey.get(challenge, rpId, void 0, { signal: options.signal }) : passkey.get(challenge, rpId));
6261
+ const session = await this.auth.loginFinish({ challengeId: begin.challengeId, assertion });
6262
+ this.useSession(session);
6263
+ return session;
5779
6264
  }
5780
6265
  /**
5781
- * Poll `client.consent.pageResult` until the request is decided, every
5782
- * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
5783
- * passes, when it answers the last `pending` result.
6266
+ * The origin a sign-up or sign-in sends: the one given, or the page's own
6267
+ * when it is not a node's origin; `undefined` for none.
5784
6268
  */
5785
- async waitForConsent(requestId, options = {}) {
5786
- const interval = options.intervalMs ?? 2e3;
5787
- for (; ; ) {
5788
- const result = await this.consent.pageResult({ request: requestId });
5789
- if (result.status !== "pending") return result;
5790
- if (options.signal?.aborted) return result;
5791
- if (options.expiresAt !== void 0 && Date.now() / 1e3 >= options.expiresAt) return result;
5792
- await new Promise((resolve) => setTimeout(resolve, interval));
5793
- }
5794
- }
5795
- // ---------------------------------------------------------------- operator
5796
- // ---------------------------------------------------------------- app teams
5797
- // ---------------------------------------------------------------- package origins
5798
- // ---------------------------------------------------------------- deployers
5799
- // ---------------------------------------------------------------- deployments
5800
- };
5801
- function consentStorage() {
5802
- try {
5803
- return globalThis.sessionStorage;
5804
- } catch {
5805
- return void 0;
5806
- }
5807
- }
5808
- function forgetConsent(requestId) {
5809
- try {
5810
- const store = consentStorage();
5811
- if (store?.getItem(CONSENT_STORAGE_KEY) === requestId) store.removeItem(CONSENT_STORAGE_KEY);
5812
- } catch {
6269
+ pageOrigin(options) {
6270
+ if (options.origin !== void 0) return options.origin ?? void 0;
6271
+ const page = globalThis.location?.origin;
6272
+ if (!page || page === "null") return void 0;
6273
+ const nodes = new Set(
6274
+ this.transport.nodes.map((url2) => {
6275
+ try {
6276
+ return new URL(url2).origin;
6277
+ } catch {
6278
+ return url2;
6279
+ }
6280
+ })
6281
+ );
6282
+ return nodes.has(page) ? void 0 : page;
6283
+ }
6284
+ /** POST a ceremony's `begin`, naming the page's `origin` in an {@link OriginNotRegistered} the node leaves it out of. */
6285
+ async begin(result, origin) {
6286
+ try {
6287
+ return await this.as(result);
6288
+ } catch (error) {
6289
+ if (error instanceof OriginNotRegistered && !error.origin && origin !== void 0) {
6290
+ throw new OriginNotRegistered(error.nodeMessage, { ...error.details, origin });
6291
+ }
6292
+ throw error;
6293
+ }
5813
6294
  }
5814
- }
5815
-
5816
- // src/client/capabilities.ts
5817
- var ORG_CAPABILITIES = {
5818
- /** Create an app in the organization (on its team, or org-wide). */
5819
- CREATE_APP: 1 << 0,
5820
- /** Mint invites (org-wide, or on each team the invite names). */
5821
- INVITE_MEMBERS: 1 << 1,
5822
- /** Inherited into open teams; denying it keeps a member out of them. */
5823
- JOIN_OPEN_TEAMS: 1 << 2,
5824
- /** Add and remove a team's members. */
5825
- MANAGE_MEMBERS: 1 << 3,
5826
- /** Upgrade the organization's apps (and, as a publisher, every instance of its `publisher` packages), start org upgrade runs, approve outbound hosts (org-wide). */
5827
- MANAGE_APPLICATION: 1 << 4,
5828
- /** Create a top-level team without being an admin. */
5829
- CREATE_TEAM: 1 << 5,
5830
- /** Delete a team, and what it holds, without being an admin. */
5831
- DELETE_TEAM: 1 << 6,
5832
- /** Change who may join a team (open or invite-only). */
5833
- MANAGE_VISIBILITY: 1 << 7,
5834
- /** Set the organization's and its teams' metadata. */
5835
- MANAGE_METADATA: 1 << 8,
5836
6295
  /**
5837
- * Approve (or withdraw) the mero-tee releases that hold the apps the
5838
- * organization governs (those of the packages it publishes, and its own of
5839
- * unbound packages), and bind a package signing key to it
5840
- * (`client.orgs.publisher`). Organization-wide only. Bit 9 is left unused.
6296
+ * Swap the refresh token for a new session, on whichever node the client
6297
+ * uses: any node of the cluster takes it. A refresh token is used once, so
6298
+ * calls made while one refresh is under way share it rather than sending the
6299
+ * same token again (which would revoke the session).
5841
6300
  */
5842
- APPROVE_RELEASES: 1 << 10
5843
- };
5844
- var DEFAULT_ORG_CAPABILITIES = ORG_CAPABILITIES.JOIN_OPEN_TEAMS;
5845
- function orgCapabilities(...names) {
5846
- return names.reduce((mask, name) => mask | ORG_CAPABILITIES[name], 0);
5847
- }
5848
-
5849
- // src/agent-gate/chacha20poly1305.ts
5850
- var KEY_LEN = 32;
5851
- var NONCE_LEN = 12;
5852
- var TAG_LEN2 = 16;
5853
- function rotl(value, shift) {
5854
- return (value << shift | value >>> 32 - shift) >>> 0;
5855
- }
5856
- function quarterRound(s, a, b, c, d) {
5857
- s[a] = s[a] + s[b] >>> 0;
5858
- s[d] = rotl(s[d] ^ s[a], 16);
5859
- s[c] = s[c] + s[d] >>> 0;
5860
- s[b] = rotl(s[b] ^ s[c], 12);
5861
- s[a] = s[a] + s[b] >>> 0;
5862
- s[d] = rotl(s[d] ^ s[a], 8);
5863
- s[c] = s[c] + s[d] >>> 0;
5864
- s[b] = rotl(s[b] ^ s[c], 7);
5865
- }
5866
- function u32le(bytes, offset) {
5867
- return (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
5868
- }
5869
- function chacha20Block(key, counter, nonce2) {
5870
- const state = new Uint32Array(16);
5871
- state[0] = 1634760805;
5872
- state[1] = 857760878;
5873
- state[2] = 2036477234;
5874
- state[3] = 1797285236;
5875
- for (let i = 0; i < 8; i += 1) state[4 + i] = u32le(key, i * 4);
5876
- state[12] = counter >>> 0;
5877
- for (let i = 0; i < 3; i += 1) state[13 + i] = u32le(nonce2, i * 4);
5878
- const working = state.slice();
5879
- for (let round = 0; round < 10; round += 1) {
5880
- quarterRound(working, 0, 4, 8, 12);
5881
- quarterRound(working, 1, 5, 9, 13);
5882
- quarterRound(working, 2, 6, 10, 14);
5883
- quarterRound(working, 3, 7, 11, 15);
5884
- quarterRound(working, 0, 5, 10, 15);
5885
- quarterRound(working, 1, 6, 11, 12);
5886
- quarterRound(working, 2, 7, 8, 13);
5887
- quarterRound(working, 3, 4, 9, 14);
5888
- }
5889
- const out = new Uint8Array(64);
5890
- for (let i = 0; i < 16; i += 1) {
5891
- const word = working[i] + state[i] >>> 0;
5892
- out[i * 4] = word & 255;
5893
- out[i * 4 + 1] = word >>> 8 & 255;
5894
- out[i * 4 + 2] = word >>> 16 & 255;
5895
- out[i * 4 + 3] = word >>> 24 & 255;
6301
+ refresh() {
6302
+ return this.transport.refresh();
5896
6303
  }
5897
- return out;
5898
- }
5899
- function chacha20(key, counter, nonce2, data) {
5900
- const out = new Uint8Array(data.length);
5901
- for (let offset = 0, block = counter; offset < data.length; offset += 64, block += 1) {
5902
- const stream = chacha20Block(key, block, nonce2);
5903
- const end = Math.min(offset + 64, data.length);
5904
- for (let i = offset; i < end; i += 1) out[i] = data[i] ^ stream[i - offset];
6304
+ /**
6305
+ * End this session. The client is signed out whether or not the node
6306
+ * answers: the revoke (`POST /auth/logout`) is attempted, and its failure
6307
+ * (the node unreachable, say) is thrown after the session is dropped, so a
6308
+ * caller can say the server may still hold it, but no request after this
6309
+ * one carries its token.
6310
+ */
6311
+ async signOut() {
6312
+ await this.signingOut(this.auth.logout());
5905
6313
  }
5906
- return out;
5907
- }
5908
- function leToBigInt(bytes) {
5909
- let value = 0n;
5910
- for (let i = bytes.length - 1; i >= 0; i -= 1) value = value << 8n | BigInt(bytes[i]);
5911
- return value;
5912
- }
5913
- var P1305 = (1n << 130n) - 5n;
5914
- function poly1305(key, message) {
5915
- const r = leToBigInt(key.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn;
5916
- const s = leToBigInt(key.subarray(16, 32));
5917
- let acc = 0n;
5918
- for (let offset = 0; offset < message.length; offset += 16) {
5919
- const block = message.subarray(offset, Math.min(offset + 16, message.length));
5920
- const n = leToBigInt(block) + (1n << BigInt(8 * block.length));
5921
- acc = (acc + n) * r % P1305;
6314
+ /**
6315
+ * End every session of the signed-in account, on every device, this one
6316
+ * too. Like {@link signOut}, this client is signed out even when the
6317
+ * request fails, and the failure is thrown.
6318
+ */
6319
+ async signOutEverywhere() {
6320
+ await this.signingOut(this.auth.logoutAll());
5922
6321
  }
5923
- let tag = acc + s & (1n << 128n) - 1n;
5924
- const out = new Uint8Array(TAG_LEN2);
5925
- for (let i = 0; i < TAG_LEN2; i += 1) {
5926
- out[i] = Number(tag & 0xffn);
5927
- tag >>= 8n;
6322
+ async signingOut(result) {
6323
+ try {
6324
+ await result;
6325
+ } finally {
6326
+ this.transport.signOut();
6327
+ }
5928
6328
  }
5929
- return out;
5930
- }
5931
- function pad16(length) {
5932
- return new Uint8Array((16 - length % 16) % 16);
5933
- }
5934
- function u64le(value) {
5935
- const out = new Uint8Array(8);
5936
- new DataView(out.buffer).setBigUint64(0, BigInt(value), true);
5937
- return out;
5938
- }
5939
- function macData(aad, ciphertext) {
5940
- const parts = [aad, pad16(aad.length), ciphertext, pad16(ciphertext.length), u64le(aad.length), u64le(ciphertext.length)];
5941
- const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
5942
- let offset = 0;
5943
- for (const part of parts) {
5944
- out.set(part, offset);
5945
- offset += part.length;
6329
+ /**
6330
+ * Add another passkey (another device, `passkey`) to the signed-in account;
6331
+ * answers its credential id. The node asks for the approval of a passkey
6332
+ * the account already has (`412 CONFIRM_REQUIRED`, never the new one),
6333
+ * which `approver` gives.
6334
+ */
6335
+ async addPasskey(passkey, approver) {
6336
+ const begin = await this.as(this.auth.passkeyAddBegin());
6337
+ const registration = await passkey.create(begin.options);
6338
+ const { credentialId } = await this.auth.passkeyAddFinish({ challengeId: begin.challengeId, registration }, this.confirmWith(approver));
6339
+ return credentialId;
5946
6340
  }
5947
- return out;
5948
- }
5949
- function check(key, nonce2) {
5950
- if (key.length !== KEY_LEN) throw new Error("ChaCha20-Poly1305 needs a 32-byte key");
5951
- if (nonce2.length !== NONCE_LEN) throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce");
5952
- }
5953
- function chacha20Poly1305Seal(key, nonce2, plaintext, aad = new Uint8Array(0)) {
5954
- check(key, nonce2);
5955
- const otk = chacha20Block(key, 0, nonce2).subarray(0, 32);
5956
- const ciphertext = chacha20(key, 1, nonce2, plaintext);
5957
- const tag = poly1305(otk, macData(aad, ciphertext));
5958
- const out = new Uint8Array(ciphertext.length + TAG_LEN2);
5959
- out.set(ciphertext);
5960
- out.set(tag, ciphertext.length);
5961
- return out;
5962
- }
5963
-
5964
- // src/agent-gate/hpke.ts
5965
- var KEM_ID = 32;
5966
- var KDF_ID = 1;
5967
- var AEAD_ID = 3;
5968
- var MODE_AUTH = 2;
5969
- var N_SECRET = 32;
5970
- var N_KEY = 32;
5971
- var N_NONCE = 12;
5972
- var utf83 = (s) => new TextEncoder().encode(s);
5973
- var i2osp2 = (n) => new Uint8Array([n >> 8 & 255, n & 255]);
5974
- var KEM_SUITE = concat(utf83("KEM"), i2osp2(KEM_ID));
5975
- var HPKE_SUITE = concat(utf83("HPKE"), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));
5976
- async function hmac(key, data) {
5977
- const raw = key.length === 0 ? new Uint8Array(32) : key;
5978
- const k = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
5979
- return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
5980
- }
5981
- async function expand(prk, info, length) {
5982
- const out = new Uint8Array(length);
5983
- let previous = new Uint8Array(0);
5984
- for (let i = 1, offset = 0; offset < length; i += 1) {
5985
- previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));
5986
- out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
5987
- offset += previous.length;
6341
+ // ---------------------------------------------------------------- account recovery
6342
+ //
6343
+ // core #4844 (`docs/specs/account-recovery.md`): a recovery code, made with
6344
+ // a passkey and shown once, lets someone who lost every passkey register a
6345
+ // new one; it is added, and the account signed in, 72 hours later unless a
6346
+ // passkey the account still has cancels it first.
6347
+ /**
6348
+ * Signed out: start recovering the account `code` names. `passkey` makes a
6349
+ * new passkey for it (the browser's create prompt, user verified); the
6350
+ * node spends the code and keeps the passkey as pending. Nothing is added
6351
+ * and no session opens: finish with {@link finishAccountRecovery} at
6352
+ * `readyAt`. A code the cluster does not hold (mistyped, replaced or
6353
+ * spent) is {@link WrongRecoveryCode}; an account with a recovery already
6354
+ * under way `409 RECOVERY_PENDING`.
6355
+ */
6356
+ async startAccountRecovery(code, passkey) {
6357
+ try {
6358
+ const begin = await this.as(this.auth.accountRecoveryBegin({ code }));
6359
+ const registration = await passkey.create(begin.options);
6360
+ return await this.auth.accountRecoveryStart({ challengeId: begin.challengeId, code, registration });
6361
+ } catch (error) {
6362
+ if (error instanceof LoginRequired) throw new WrongRecoveryCode(error.message.replace(/^401 UNAUTHENTICATED: /, ""), error.details);
6363
+ throw error;
6364
+ }
5988
6365
  }
5989
- return out;
5990
- }
5991
- function labeledExtract(suite, salt, label, ikm) {
5992
- return hmac(salt, concat(utf83("HPKE-v1"), suite, utf83(label), ikm));
5993
- }
5994
- function labeledExpand(suite, prk, label, info, length) {
5995
- return expand(prk, concat(i2osp2(length), utf83("HPKE-v1"), suite, utf83(label), info), length);
5996
- }
5997
- async function extractAndExpand(dhValue, kemContext) {
5998
- const prk = await labeledExtract(KEM_SUITE, new Uint8Array(0), "eae_prk", dhValue);
5999
- return labeledExpand(KEM_SUITE, prk, "shared_secret", kemContext, N_SECRET);
6000
- }
6001
- async function keySchedule(sharedSecret, info) {
6002
- const empty = new Uint8Array(0);
6003
- const pskIdHash = await labeledExtract(HPKE_SUITE, empty, "psk_id_hash", empty);
6004
- const infoHash = await labeledExtract(HPKE_SUITE, empty, "info_hash", info);
6005
- const context = concat(new Uint8Array([MODE_AUTH]), pskIdHash, infoHash);
6006
- const secret = await labeledExtract(HPKE_SUITE, sharedSecret, "secret", empty);
6007
- return {
6008
- key: await labeledExpand(HPKE_SUITE, secret, "key", context, N_KEY),
6009
- nonce: await labeledExpand(HPKE_SUITE, secret, "base_nonce", context, N_NONCE)
6010
- };
6011
- }
6012
- async function hpkeSealAuth(recipientPublic, senderSecret, info, plaintext, aad = new Uint8Array(0), ephemeralSecret) {
6013
- if (recipientPublic.length !== 32) throw new Error("The recipient key is not 32 bytes of X25519");
6014
- const ephemeral = await x25519KeyPair(ephemeralSecret);
6015
- const sender = await x25519KeyPair(senderSecret);
6016
- const dhValue = concat(await dh(ephemeral.privateKey, recipientPublic), await dh(sender.privateKey, recipientPublic));
6017
- const shared = await extractAndExpand(dhValue, concat(ephemeral.publicKey, recipientPublic, sender.publicKey));
6018
- const { key, nonce: nonce2 } = await keySchedule(shared, info);
6019
- return { enc: ephemeral.publicKey, ciphertext: chacha20Poly1305Seal(key, nonce2, plaintext, aad) };
6020
- }
6021
-
6022
- // src/agent-gate/gate.ts
6023
- var AGENT_ATTEST_DOMAIN = "mero-agent-gate/attest/v3";
6024
- var AGENT_PROVISION_INFO_DOMAIN = "mero-agent-gate/provision/v2";
6025
- var AGENT_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
6026
- var SECRET_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
6027
- var MAX_SECRETS = 64;
6028
- var MAX_SECRET_LEN = 64 * 1024;
6029
- var AgentGateError = class extends Error {
6030
- constructor(message, status, code) {
6031
- super(message);
6032
- this.status = status;
6033
- this.code = code;
6034
- this.name = "AgentGateError";
6366
+ /**
6367
+ * Signed out, once the delay passed: finish the recovery with the passkey
6368
+ * it registered (`passkey` signs the node's sign-in challenge). The passkey
6369
+ * joins the account, every other session of the account ends, and this
6370
+ * client is signed in. `accountId` (from the start) lets the node refuse
6371
+ * early and offer only that passkey; before `readyAt` it is
6372
+ * {@link RecoveryNotReady}, with no recovery under way {@link NotFound}.
6373
+ */
6374
+ async finishAccountRecovery(passkey, accountId) {
6375
+ const session = await this.auth.accountRecoveryFinish({ ...accountId ? { accountId } : {} }, this.confirmWith(passkey));
6376
+ this.useSession(session);
6377
+ return session;
6035
6378
  }
6036
- };
6037
- function validateAgentId(agentId) {
6038
- if (!AGENT_ID.test(agentId)) {
6039
- throw new Error(`Agent id ${JSON.stringify(agentId)} must match [a-z0-9][a-z0-9-]{0,62}`);
6379
+ // ---------------------------------------------------------------- apps
6380
+ /** One of `app`'s blobs, by id (base58 or hex). */
6381
+ async downloadBlob(app, id) {
6382
+ return new Uint8Array(await (await this.apps.blobDownload({ app, id })).arrayBuffer());
6040
6383
  }
6041
- }
6042
- function utf84(value) {
6043
- return new TextEncoder().encode(value);
6044
- }
6045
- function lengthPrefixed(agentId) {
6046
- const id = utf84(agentId);
6047
- return concat(new Uint8Array([id.length]), id);
6048
- }
6049
- function toBase64(bytes) {
6050
- let binary = "";
6051
- for (const byte of bytes) binary += String.fromCharCode(byte);
6052
- return btoa(binary);
6053
- }
6054
- function fromBase643(value, label, length) {
6055
- let bytes;
6056
- try {
6057
- bytes = Uint8Array.from(atob(value.trim()), (c) => c.charCodeAt(0));
6058
- } catch {
6059
- throw new Error(`${label} is not base64`);
6384
+ get exportClient() {
6385
+ return { exportsExport: this.apps.exportsExport, request: this.transport.request.bind(this.transport) };
6060
6386
  }
6061
- if (length !== void 0 && bytes.length !== length) throw new Error(`${label} is not ${length} bytes`);
6062
- return bytes;
6063
- }
6064
- async function agentKeyBinding(provisioningPublic, agentId, signingPublic, ownerPublic) {
6065
- const zero = new Uint8Array(32);
6066
- const data = concat(
6067
- utf84(AGENT_ATTEST_DOMAIN),
6068
- provisioningPublic,
6069
- lengthPrefixed(agentId),
6070
- signingPublic ?? zero,
6071
- ownerPublic ?? zero
6072
- );
6073
- return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
6074
- }
6075
- function provisionInfo(recipientPublic, agentId) {
6076
- return concat(utf84(AGENT_PROVISION_INFO_DOMAIN), recipientPublic, lengthPrefixed(agentId));
6077
- }
6078
- async function generateOwnerKey() {
6079
- const secret = crypto.getRandomValues(new Uint8Array(32));
6080
- return { secret, publicKey: await ownerPublicKey(secret) };
6081
- }
6082
- async function ownerPublicKey(secret) {
6083
- if (secret.length !== 32) throw new Error("An owner key is 32 bytes");
6084
- return toBase64((await x25519KeyPair(secret)).publicKey);
6085
- }
6086
- function url(gateUrl, path) {
6087
- return `${gateUrl.replace(/\/+$/, "")}${path}`;
6088
- }
6089
- async function postJson(fetchImpl, target, body) {
6090
- const response = await fetchImpl(target, {
6091
- method: "POST",
6092
- headers: { "content-type": "application/json" },
6093
- body: JSON.stringify(body)
6094
- });
6095
- const text = await response.text();
6096
- let parsed = void 0;
6097
- try {
6098
- parsed = text ? JSON.parse(text) : void 0;
6099
- } catch {
6387
+ /**
6388
+ * Write the plaintext of sealed file `id` of component app `app` to `sink`, checked against its id,
6389
+ * size and hash. On rejection, discard what `sink` received: it is authentic but may be a prefix of
6390
+ * the file. A failed check is an `ExportError`; `signal` aborts the download.
6391
+ */
6392
+ exportFileTo(app, id, sink, signal) {
6393
+ return exportFileTo(this.exportClient, app, id, sink, signal);
6100
6394
  }
6101
- if (!response.ok) {
6102
- const error = parsed;
6103
- throw new AgentGateError(
6104
- `The gate answered ${response.status}${error?.error ? ` ${error.error}` : ""}: ${error?.details ?? text.slice(0, 200)}`,
6105
- response.status,
6106
- error?.error
6107
- );
6395
+ /** The plaintext of sealed file `id` of component app `app`, in memory; use {@link exportFileTo} for a large one. */
6396
+ exportFile(app, id, signal) {
6397
+ return exportFile(this.exportClient, app, id, signal);
6108
6398
  }
6109
- return parsed;
6110
- }
6111
- async function attestAgent(options) {
6112
- const agentId = options.agentId ?? "";
6113
- if (agentId) validateAgentId(agentId);
6114
- const nonce2 = crypto.getRandomValues(new Uint8Array(32));
6115
- const body = await postJson(options.fetch ?? fetch, url(options.gateUrl, "/attest"), {
6116
- nonceB64: toBase64(nonce2),
6117
- ...agentId ? { agentId } : {}
6118
- });
6119
- if ((body?.agentId ?? "") !== agentId) {
6120
- throw new Error(`Asked about agent ${JSON.stringify(agentId)}, the gate answered for ${JSON.stringify(body?.agentId)}`);
6399
+ /** The policy this client attests nodes under; a client without one verifies nothing. */
6400
+ get attestationPolicy() {
6401
+ const policy = this.transport.nodePolicy;
6402
+ if (!policy) throw new Error("this client has no attestation policy, so it cannot verify an attestation");
6403
+ return policy;
6121
6404
  }
6122
- const provisioning = fromBase643(body.provisioningPublicKeyB64 ?? "", "provisioningPublicKeyB64", 32);
6123
- const signing = body.signingPublicKeyB64 ? fromBase643(body.signingPublicKeyB64, "signingPublicKeyB64", 32) : void 0;
6124
- const owner = body.ownerPublicKeyB64 ? fromBase643(body.ownerPublicKeyB64, "ownerPublicKeyB64", 32) : void 0;
6125
- if (!signing !== !owner) {
6126
- throw new Error("A claimed agent has both a signing key and an owner; the gate named one");
6405
+ /**
6406
+ * Verify every replica of `app` under this client's policy: each one's quote binds its receipt key,
6407
+ * the cluster's governance, and its cluster and node id. Answers the attested receipt key per node
6408
+ * and the governance.
6409
+ */
6410
+ async verifyAppCluster(app) {
6411
+ return verifyAppCluster(this, app, this.attestationPolicy);
6127
6412
  }
6128
- const binding = await agentKeyBinding(provisioning, agentId, signing, owner);
6129
- await options.verifier({ quoteB64: body.quoteB64, nonce: hex(nonce2), reportDataSuffix: hex(binding) });
6130
- return {
6131
- agentId,
6132
- provisioningPublicKey: toBase64(provisioning),
6133
- ...signing ? { signingPublicKey: toBase64(signing) } : {},
6134
- ...owner ? { ownerPublicKey: toBase64(owner) } : {}
6135
- };
6136
- }
6137
- async function checkOwner(agent, ownerSecret) {
6138
- const mine = await ownerPublicKey(ownerSecret);
6139
- if (agent.ownerPublicKey && agent.ownerPublicKey !== mine) {
6140
- throw new AgentGateError(
6141
- `This agent is claimed by another key (${agent.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,
6142
- void 0,
6143
- "not_yours"
6144
- );
6413
+ /**
6414
+ * The signed receipt of an ended pipeline run, version 2 (`client.apps.pipelineReceiptReceipt`):
6415
+ * with each job's report evidence and job node attestation. A version 1 answer does not verify.
6416
+ */
6417
+ async pipelineReceipt(app, run) {
6418
+ return await this.apps.pipelineReceiptReceipt({ app, run, version: 2 });
6145
6419
  }
6146
- return mine;
6147
- }
6148
- function validateSecrets(secrets) {
6149
- const names = Object.keys(secrets);
6150
- if (names.length === 0) throw new Error("There are no secrets to provision");
6151
- if (names.length > MAX_SECRETS) throw new Error(`At most ${MAX_SECRETS} secrets at once`);
6152
- for (const name of names) {
6153
- if (!SECRET_NAME.test(name)) throw new Error(`Secret name ${JSON.stringify(name)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);
6154
- if (typeof secrets[name] !== "string") throw new Error(`Secret ${name} is not a string`);
6155
- if (utf84(secrets[name]).length > MAX_SECRET_LEN) throw new Error(`Secret ${name} is over ${MAX_SECRET_LEN} bytes`);
6420
+ /**
6421
+ * Verify the receipt of a pipeline run ({@link pipelineReceipt}): signed by the key an attested replica
6422
+ * holds, for `app` and `run`, with every job's report signed by a job key a job node attests. Throws
6423
+ * when it is not; answers the receipt.
6424
+ */
6425
+ async verifyPipelineReceipt(app, run, answer) {
6426
+ return verifyPipelineReceipt(this, app, run, answer, this.attestationPolicy);
6156
6427
  }
6157
- }
6158
- async function sendSealed(fetchImpl, gateUrl, path, agent, ownerSecret, message) {
6159
- if (!agent.agentId) throw new Error("This quote names no agent; attest with the agent id");
6160
- const mine = await checkOwner(agent, ownerSecret);
6161
- const recipient = fromBase643(agent.provisioningPublicKey, "provisioningPublicKey", 32);
6162
- const sealed = await hpkeSealAuth(
6163
- recipient,
6164
- ownerSecret,
6165
- provisionInfo(recipient, agent.agentId),
6166
- utf84(JSON.stringify(message))
6167
- );
6168
- return postJson(fetchImpl, url(gateUrl, path), {
6169
- agentId: agent.agentId,
6170
- provisioningPublicKeyB64: agent.provisioningPublicKey,
6171
- senderPublicKeyB64: mine,
6172
- encappedKeyB64: toBase64(sealed.enc),
6173
- ciphertextB64: toBase64(sealed.ciphertext)
6174
- });
6175
- }
6176
- async function provisionAgent(options) {
6177
- validateSecrets(options.secrets);
6178
- const fetchImpl = options.fetch ?? fetch;
6179
- const answer = await sendSealed(fetchImpl, options.gateUrl, "/provision", options.agent, options.ownerSecret, {
6180
- secrets: options.secrets
6181
- });
6182
- const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });
6183
- const mine = await ownerPublicKey(options.ownerSecret);
6184
- if (after.ownerPublicKey !== mine || !after.signingPublicKey) {
6185
- throw new AgentGateError("The gate accepted the secrets, but its quote does not name your key as owner");
6428
+ /**
6429
+ * Download a component app's blob with a grant one of its runs handed out
6430
+ * (`BlobRef::grant`, up to 24 h). No session needed: the grant is the
6431
+ * permission. A bad or expired grant answers `NotFound`, as a missing blob.
6432
+ */
6433
+ async downloadBlobGranted(app, id, grant) {
6434
+ return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());
6186
6435
  }
6187
- if (options.agent.signingPublicKey && options.agent.signingPublicKey !== after.signingPublicKey) {
6188
- throw new AgentGateError("The agent's signing key changed while provisioning");
6436
+ /**
6437
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
6438
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
6439
+ * file for each, so one that may have reached it is never repeated); a larger file
6440
+ * is a session of parts, each sent again after a dropped connection or a `503`.
6441
+ * A session the node lost is begun again once; any other failure aborts it.
6442
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
6443
+ */
6444
+ async uploadFile(app, data) {
6445
+ const size = data instanceof Blob ? data.size : data.byteLength;
6446
+ if (size <= FILE_PART_BYTES) return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });
6447
+ try {
6448
+ return await this.uploadSession(app, data, size);
6449
+ } catch (error) {
6450
+ if (!(error instanceof CalimeroError) || error.code !== "UPLOAD_UNKNOWN") throw error;
6451
+ return this.uploadSession(app, data, size);
6452
+ }
6453
+ }
6454
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
6455
+ async uploadSession(app, data, size) {
6456
+ const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));
6457
+ const { uploadId: upload, partBytes, parts } = begin;
6458
+ if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {
6459
+ throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);
6460
+ }
6461
+ try {
6462
+ await this.sendParts(app, upload, data, size, partBytes, parts);
6463
+ return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));
6464
+ } catch (error) {
6465
+ if (!(error instanceof CalimeroError && error.code === "UPLOAD_UNKNOWN")) await this.apps.uploadAbort({ app, upload }).catch(() => void 0);
6466
+ throw error;
6467
+ }
6468
+ }
6469
+ /** Send every part, in order, from wherever the node says the session is. */
6470
+ async sendParts(app, upload, data, size, partBytes, parts) {
6471
+ let [next, failures, jumps] = [0, 0, 0];
6472
+ while (next < parts) {
6473
+ try {
6474
+ const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));
6475
+ next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);
6476
+ failures = 0;
6477
+ continue;
6478
+ } catch (error) {
6479
+ if (error instanceof CalimeroError && error.code === "PART_OUT_OF_ORDER") {
6480
+ jumps += 1;
6481
+ if (jumps > MAX_JUMPS) throw error;
6482
+ next = nextPart(error.details, parts);
6483
+ continue;
6484
+ }
6485
+ if (!this.isTransient(error) || ++failures > MAX_FAILURES) throw error;
6486
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));
6487
+ if (failures > PART_RESENDS) {
6488
+ try {
6489
+ const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);
6490
+ if (at > next) failures = 0;
6491
+ next = at;
6492
+ } catch (asked) {
6493
+ if (!this.isTransient(asked)) throw asked;
6494
+ }
6495
+ }
6496
+ }
6497
+ }
6498
+ }
6499
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
6500
+ async untilAvailable(send) {
6501
+ for (let retry = 0; ; retry++) {
6502
+ try {
6503
+ return await send();
6504
+ } catch (error) {
6505
+ if (!this.isTransient(error) || retry >= CALL_RETRIES) throw error;
6506
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));
6507
+ }
6508
+ }
6509
+ }
6510
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
6511
+ isTransient(error) {
6512
+ return error instanceof UnavailableError || this.transport.isNetworkFailure(error);
6513
+ }
6514
+ // ---------------------------------------------------------------- packages
6515
+ // ---------------------------------------------------------------- app instances
6516
+ /** Committed events from index `from`, then live, until `signal` aborts. */
6517
+ events(app, from = 0, signal) {
6518
+ return this.transport.events(routePath("apps/{app}/events", { app }), { query: { from }, signal });
6519
+ }
6520
+ // ---------------------------------------------------------------- presence
6521
+ /**
6522
+ * Presence as a stream until `signal` aborts: a `snapshot` event (`data` the
6523
+ * entries present), then a `presence` event (`data` one entry) per change.
6524
+ */
6525
+ presenceStream(app, signal) {
6526
+ return this.transport.events(routePath("apps/{app}/presence/stream", { app }), { signal });
6189
6527
  }
6190
- return {
6191
- agentId: after.agentId,
6192
- provisioningPublicKey: after.provisioningPublicKey,
6193
- signingPublicKey: after.signingPublicKey,
6194
- ownerPublicKey: mine,
6195
- written: answer?.written ?? [],
6196
- claimed: answer?.claimed === true
6197
- };
6198
- }
6199
- async function releaseAgent(options) {
6200
- if (!options.agent.ownerPublicKey) throw new Error("This agent is not claimed; there is nothing to release");
6201
- const fetchImpl = options.fetch ?? fetch;
6202
- await sendSealed(fetchImpl, options.gateUrl, "/release", options.agent, options.ownerSecret, { release: true });
6203
- const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });
6204
- if (after.ownerPublicKey) {
6205
- throw new AgentGateError("The gate says it released the agent, but its quote still names an owner");
6528
+ // ---------------------------------------------------------------- aliases
6529
+ // ---------------------------------------------------------------- organizations
6530
+ /**
6531
+ * Start handing `org` to the signed-in account with the recovery seed,
6532
+ * which signs here and never leaves this process. Finish with
6533
+ * `client.orgs.recoveryFinish` once `readyAt` has passed; until then the owner may
6534
+ * cancel. A wrong seed (or no organization, or none set) is a `403`.
6535
+ */
6536
+ async startRecovery(org, seed) {
6537
+ const account = (await this.auth.me()).accountId;
6538
+ const nonce2 = b64url(crypto.getRandomValues(new Uint8Array(16)));
6539
+ const signature = await signRecovery(seed, org, account, nonce2);
6540
+ return this.orgs.recoveryStart({ org, nonce: nonce2, signature });
6206
6541
  }
6207
- }
6208
-
6209
- // src/agent-gate/policy.ts
6210
- var KMS_RELEASE_SIGNER = Object.freeze({
6211
- identity: "https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",
6212
- issuer: "https://token.actions.githubusercontent.com"
6213
- });
6214
- var LISTS = [
6215
- "allowed_tcb_statuses",
6216
- "allowed_mrtd",
6217
- "allowed_rtmr0",
6218
- "allowed_rtmr1",
6219
- "allowed_rtmr2",
6220
- "allowed_rtmr3"
6221
- ];
6222
- async function verifySignedAgentPolicy(policy, bundle, options = {}) {
6223
- const body = typeof policy === "string" ? new TextEncoder().encode(policy) : policy;
6224
- await verifyCosignBundle(body, bundle, {
6225
- identity: options.identity ?? KMS_RELEASE_SIGNER.identity,
6226
- issuer: options.issuer ?? KMS_RELEASE_SIGNER.issuer
6227
- });
6228
- let parsed;
6229
- try {
6230
- parsed = JSON.parse(new TextDecoder().decode(body));
6231
- } catch {
6232
- throw new Error("The signed agent policy is not JSON");
6542
+ // ---------------------------------------------------------------- approvals
6543
+ /** The report of a scope's apps (`GET /orgs/{org}/apps`, or with `org` `null` the account's own, `GET /auth/apps`), every page, with the apps of all of them in `apps`. */
6544
+ async appsReportAll(org) {
6545
+ const report = (page = {}) => org === null ? this.auth.accountApps(pageParams(page)) : this.orgs.apps({ org, ...pageParams(page) });
6546
+ const first = await report();
6547
+ const apps = [...first.apps];
6548
+ let next = first.next;
6549
+ while (next !== null) {
6550
+ const page = await report({ after: next });
6551
+ apps.push(...page.apps);
6552
+ next = page.next;
6553
+ }
6554
+ return { ...first, apps, next: null };
6233
6555
  }
6234
- const role = options.role ?? "agent";
6235
- if (parsed?.role !== role) {
6236
- throw new Error(`The signed file is a ${JSON.stringify(parsed?.role)} policy, not an ${role} one`);
6556
+ /**
6557
+ * What waits for a decision in a scope (`org`, or the account's own apps
6558
+ * with `null`): mero-tee releases the cluster's nodes run that the scope has
6559
+ * not approved, apps with newer releases of their package, and whether a
6560
+ * passed deadline stops new work. Read over the sealed channel; act on an
6561
+ * item by sending the user to the consent page (`client.consent.pageCreate`,
6562
+ * `releaseConsent`, `upgradeConsent`).
6563
+ */
6564
+ async pendingApprovals(org = null) {
6565
+ const [report, rules] = await Promise.all([this.appsReportAll(org), this.public.releasesPublic()]);
6566
+ return pendingApprovalsFrom(report, rules);
6237
6567
  }
6238
- const profile = options.profile ?? PRODUCTION_PROFILE;
6239
- if (parsed.profile !== profile) {
6240
- throw new Error(`The signed agent policy is for the ${JSON.stringify(parsed.profile)} profile, not ${profile}`);
6568
+ /**
6569
+ * `client.consent.pageCreate`, then send the browser to the consent page
6570
+ * (`navigate`, by default `window.location.assign`). Pass `navigate` itself
6571
+ * or {@link OpenConsentOptions}, whose `confirm` runs first with the node's
6572
+ * answer so the app can show the person its `code`; when it answers `false`
6573
+ * the page is not opened. When the node sends a `code` that is not
6574
+ * {@link confirmationCode} of `requestId`, it throws `CalimeroError`
6575
+ * (`CONSENT_CODE_MISMATCH`) and does not navigate. Answers the request
6576
+ * once `navigate` returns (or `confirm` declines): with a popup
6577
+ * (`url => window.open(url)`), poll it with {@link waitForConsent}.
6578
+ * Before navigating it keeps `requestId` in `sessionStorage` (where there
6579
+ * is one), for {@link resumeConsent} when the page sends the person back.
6580
+ */
6581
+ async openConsentPage(request, navigateOrOptions = {}) {
6582
+ const options = typeof navigateOrOptions === "function" ? { navigate: navigateOrOptions } : navigateOrOptions;
6583
+ const navigate = options.navigate ?? ((url2) => {
6584
+ const w = globalThis.window;
6585
+ if (!w) throw new Error("no window to open the consent page in; pass `navigate`");
6586
+ w.location.assign(url2);
6587
+ });
6588
+ const started = await this.consent.pageCreate({ body: request });
6589
+ if (started.code !== void 0) {
6590
+ const expected = await confirmationCode(started.requestId);
6591
+ if (started.code !== expected) {
6592
+ throw new CalimeroError(200, "CONSENT_CODE_MISMATCH", "the consent page code does not match the request", {
6593
+ requestId: started.requestId,
6594
+ code: started.code,
6595
+ expected
6596
+ });
6597
+ }
6598
+ }
6599
+ if (options.confirm && !await options.confirm(started)) return started;
6600
+ try {
6601
+ consentStorage()?.setItem(CONSENT_STORAGE_KEY, started.requestId);
6602
+ } catch {
6603
+ }
6604
+ navigate(started.url);
6605
+ return started;
6241
6606
  }
6242
- if (options.expectedVersion !== void 0 && parsed.version !== options.expectedVersion) {
6243
- throw new Error(`The signed agent policy is release ${JSON.stringify(parsed.version)}, not ${options.expectedVersion}`);
6607
+ /**
6608
+ * On the page the consent page sent the person back to
6609
+ * (`returnTo?request_id=…&result=…`): the decision on the request this page
6610
+ * started, read from the node (`GET /consent/{id}/result`), never from the
6611
+ * URL. `null` when the URL carries no `request_id`. The request is
6612
+ * `options.requestId`, or the one {@link openConsentPage} stored in this
6613
+ * tab; with the default `href` (`location.href`) the parameters are then
6614
+ * removed with `history.replaceState`, and the stored id once decided.
6615
+ *
6616
+ * Throws `CalimeroError`:
6617
+ * - `CONSENT_NOT_STARTED`: the URL names a request, and this page started none;
6618
+ * - `CONSENT_REQUEST_MISMATCH`: the URL names another request than this page's;
6619
+ * - `CONSENT_NOT_DECIDED`: this page's request is still pending although the
6620
+ * page sent the person back, a sign that another request was approved on a
6621
+ * page that was not the node's. Do not act on it;
6622
+ * - `CONSENT_REPLACED`: the node no longer knows this page's request (`404`):
6623
+ * an account has one undecided request per node, and a newer one replaced
6624
+ * it, possibly on a page that was not the node's. Do not act on it either.
6625
+ *
6626
+ * The URL's `result` is never trusted: the answer's `status` is the node's.
6627
+ * An approval's `outcome` (`orgId`, an invite's `token`, the `org` joined) is
6628
+ * in the answer, typed by `kind`.
6629
+ */
6630
+ async resumeConsent(options = {}) {
6631
+ const g = globalThis;
6632
+ const href = options.href ?? g.location?.href;
6633
+ if (href === void 0) throw new Error("no page to read the consent return from; pass `href`");
6634
+ const url2 = new URL(href);
6635
+ const returned = url2.searchParams.get("request_id");
6636
+ if (!returned) return null;
6637
+ if (options.href === void 0 && g.history) g.history.replaceState(g.history.state, "", withoutConsentReturn(url2));
6638
+ let ownId = options.requestId;
6639
+ if (ownId === void 0) {
6640
+ try {
6641
+ ownId = consentStorage()?.getItem(CONSENT_STORAGE_KEY) ?? void 0;
6642
+ } catch {
6643
+ ownId = void 0;
6644
+ }
6645
+ }
6646
+ if (!ownId) {
6647
+ throw new CalimeroError(200, "CONSENT_NOT_STARTED", "this page started no consent request", { returned });
6648
+ }
6649
+ if (returned !== ownId) {
6650
+ throw new CalimeroError(200, "CONSENT_REQUEST_MISMATCH", "the consent page returned another request than this page started", {
6651
+ requestId: ownId,
6652
+ returned
6653
+ });
6654
+ }
6655
+ let result;
6656
+ try {
6657
+ result = await this.consent.pageResult({ request: ownId });
6658
+ } catch (e) {
6659
+ if (e instanceof NotFound) {
6660
+ forgetConsent(ownId);
6661
+ throw new CalimeroError(404, "CONSENT_REPLACED", "this page's consent request was replaced by a newer one", {
6662
+ requestId: ownId
6663
+ });
6664
+ }
6665
+ throw e;
6666
+ }
6667
+ if (result.requestId !== ownId) {
6668
+ throw new CalimeroError(200, "CONSENT_REQUEST_MISMATCH", "the node answered another request", { requestId: ownId, returned: result.requestId });
6669
+ }
6670
+ if (result.status === "pending") {
6671
+ throw new CalimeroError(200, "CONSENT_NOT_DECIDED", "the consent page returned, but this request is still pending", {
6672
+ requestId: ownId
6673
+ });
6674
+ }
6675
+ forgetConsent(ownId);
6676
+ return result;
6244
6677
  }
6245
- checkLists(parsed);
6246
- return parsed;
6247
- }
6248
- function checkLists(policy) {
6249
- for (const list of LISTS) {
6250
- if (!Array.isArray(policy?.[list]) || policy[list].length === 0) {
6251
- throw new Error(`The agent policy's ${list} is empty, so no agent would be accepted`);
6678
+ /**
6679
+ * Poll `client.consent.pageResult` until the request is decided, every
6680
+ * `intervalMs` (2 s), until `signal` aborts or `expiresAt` (Unix seconds)
6681
+ * passes, when it answers the last `pending` result.
6682
+ */
6683
+ async waitForConsent(requestId, options = {}) {
6684
+ const interval = options.intervalMs ?? 2e3;
6685
+ for (; ; ) {
6686
+ const result = await this.consent.pageResult({ request: requestId });
6687
+ if (result.status !== "pending") return result;
6688
+ if (options.signal?.aborted) return result;
6689
+ if (options.expiresAt !== void 0 && Date.now() / 1e3 >= options.expiresAt) return result;
6690
+ await new Promise((resolve) => setTimeout(resolve, interval));
6252
6691
  }
6253
6692
  }
6693
+ // ---------------------------------------------------------------- operator
6694
+ // ---------------------------------------------------------------- app teams
6695
+ // ---------------------------------------------------------------- package origins
6696
+ // ---------------------------------------------------------------- deployers
6697
+ // ---------------------------------------------------------------- deployments
6698
+ };
6699
+ function consentStorage() {
6700
+ try {
6701
+ return globalThis.sessionStorage;
6702
+ } catch {
6703
+ return void 0;
6704
+ }
6254
6705
  }
6255
- var TCB_STATUSES2 = [
6256
- "UpToDate",
6257
- "SWHardeningNeeded",
6258
- "ConfigurationNeeded",
6259
- "ConfigurationAndSWHardeningNeeded",
6260
- "OutOfDate",
6261
- "OutOfDateConfigurationNeeded"
6262
- ];
6263
- function tcbStatus2(value) {
6264
- const found = TCB_STATUSES2.find((status) => status.toLowerCase() === value.trim().toLowerCase());
6265
- if (!found) throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(value)}`);
6266
- return found;
6267
- }
6268
- var register = (value) => value.trim().replace(/^0x/i, "");
6269
- function agentQuoteVerifier(policy, options) {
6270
- checkLists(policy);
6271
- return createQuoteVerifier({
6272
- dcapVerify: options.dcapVerify,
6273
- fetchCollateral: options.fetchCollateral,
6274
- now: options.now,
6275
- allowedTcbStatuses: policy.allowed_tcb_statuses.map(tcbStatus2),
6276
- allowedMrtd: policy.allowed_mrtd.map(register),
6277
- allowedRtmr0: policy.allowed_rtmr0.map(register),
6278
- allowedRtmr1: policy.allowed_rtmr1.map(register),
6279
- allowedRtmr2: policy.allowed_rtmr2.map(register),
6280
- allowedRtmr3: policy.allowed_rtmr3.map(register)
6281
- });
6282
- }
6283
-
6284
- // src/recovery/backup-files.ts
6285
- var RECOVERY_FORMAT = 1;
6286
- var SIGNING_LABEL = new TextEncoder().encode("calimero.recovery-backup.v1\0");
6287
- var HPKE_INFO = new TextEncoder().encode("calimero.recovery-backup.v1");
6288
- var HPKE_AAD = new TextEncoder().encode("calimero.recovery-backup.key.v1");
6289
- var KEM_ID2 = 32;
6290
- var KDF_ID2 = 1;
6291
- var AEAD_ID2 = 2;
6292
- var MODE_BASE = 0;
6293
- var utf85 = (s) => new TextEncoder().encode(s);
6294
- var i2osp22 = (n) => new Uint8Array([n >> 8 & 255, n & 255]);
6295
- var KEM_SUITE2 = concat(utf85("KEM"), i2osp22(KEM_ID2));
6296
- var HPKE_SUITE2 = concat(utf85("HPKE"), i2osp22(KEM_ID2), i2osp22(KDF_ID2), i2osp22(AEAD_ID2));
6297
- function holderKey(holder) {
6298
- return holder.kind === "operator" ? "operator" : `${holder.kind}:${holder.id}`;
6706
+ function forgetConsent(requestId) {
6707
+ try {
6708
+ const store = consentStorage();
6709
+ if (store?.getItem(CONSENT_STORAGE_KEY) === requestId) store.removeItem(CONSENT_STORAGE_KEY);
6710
+ } catch {
6711
+ }
6299
6712
  }
6300
- async function newBackupKeyPair() {
6301
- const secret = crypto.getRandomValues(new Uint8Array(32));
6302
- return { secret, publicKey: await backupPublicKey(secret) };
6713
+
6714
+ // src/client/capabilities.ts
6715
+ var ORG_CAPABILITIES = {
6716
+ /** Create an app in the organization (on its team, or org-wide). */
6717
+ CREATE_APP: 1 << 0,
6718
+ /** Mint invites (org-wide, or on each team the invite names). */
6719
+ INVITE_MEMBERS: 1 << 1,
6720
+ /** Inherited into open teams; denying it keeps a member out of them. */
6721
+ JOIN_OPEN_TEAMS: 1 << 2,
6722
+ /** Add and remove a team's members. */
6723
+ MANAGE_MEMBERS: 1 << 3,
6724
+ /** Upgrade the organization's apps (and, as a publisher, every instance of its `publisher` packages), start org upgrade runs, approve outbound hosts (org-wide). */
6725
+ MANAGE_APPLICATION: 1 << 4,
6726
+ /** Create a top-level team without being an admin. */
6727
+ CREATE_TEAM: 1 << 5,
6728
+ /** Delete a team, and what it holds, without being an admin. */
6729
+ DELETE_TEAM: 1 << 6,
6730
+ /** Change who may join a team (open or invite-only). */
6731
+ MANAGE_VISIBILITY: 1 << 7,
6732
+ /** Set the organization's and its teams' metadata. */
6733
+ MANAGE_METADATA: 1 << 8,
6734
+ /**
6735
+ * Approve (or withdraw) the mero-tee releases that hold the apps the
6736
+ * organization governs (those of the packages it publishes, and its own of
6737
+ * unbound packages), and bind a package signing key to it
6738
+ * (`client.orgs.publisher`). Organization-wide only. Bit 9 is left unused.
6739
+ */
6740
+ APPROVE_RELEASES: 1 << 10
6741
+ };
6742
+ var DEFAULT_ORG_CAPABILITIES = ORG_CAPABILITIES.JOIN_OPEN_TEAMS;
6743
+ function orgCapabilities(...names) {
6744
+ return names.reduce((mask, name) => mask | ORG_CAPABILITIES[name], 0);
6303
6745
  }
6304
- async function backupPublicKey(secret) {
6305
- return hex((await x25519KeyPair(secret)).publicKey);
6746
+
6747
+ // src/agent-gate/chacha20poly1305.ts
6748
+ var KEY_LEN = 32;
6749
+ var NONCE_LEN = 12;
6750
+ var TAG_LEN2 = 16;
6751
+ function rotl(value, shift) {
6752
+ return (value << shift | value >>> 32 - shift) >>> 0;
6306
6753
  }
6307
- async function verifyRecoveryHeader(file) {
6308
- const bytes = utf85(file.header);
6309
- const header = JSON.parse(file.header);
6310
- if (typeof header.format !== "number" || header.format > RECOVERY_FORMAT) {
6311
- throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);
6312
- }
6313
- const key = await crypto.subtle.importKey(
6314
- "raw",
6315
- fromHex(header.signingKey, "signing key", 32),
6316
- { name: "Ed25519" },
6317
- false,
6318
- ["verify"]
6319
- );
6320
- const ok = await crypto.subtle.verify(
6321
- "Ed25519",
6322
- key,
6323
- fromHex(file.signature, "signature", 64),
6324
- concat(SIGNING_LABEL, bytes)
6325
- );
6326
- if (!ok) throw new Error("the node's signature over the header does not hold");
6327
- return header;
6754
+ function quarterRound(s, a, b, c, d) {
6755
+ s[a] = s[a] + s[b] >>> 0;
6756
+ s[d] = rotl(s[d] ^ s[a], 16);
6757
+ s[c] = s[c] + s[d] >>> 0;
6758
+ s[b] = rotl(s[b] ^ s[c], 12);
6759
+ s[a] = s[a] + s[b] >>> 0;
6760
+ s[d] = rotl(s[d] ^ s[a], 8);
6761
+ s[c] = s[c] + s[d] >>> 0;
6762
+ s[b] = rotl(s[b] ^ s[c], 7);
6328
6763
  }
6329
- async function hmac2(key, data) {
6330
- const raw = key.length === 0 ? new Uint8Array(32) : key;
6331
- const k = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
6332
- return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
6764
+ function u32le(bytes, offset) {
6765
+ return (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
6333
6766
  }
6334
- async function expand2(prk, info, length) {
6335
- const out = new Uint8Array(length);
6336
- let previous = new Uint8Array(0);
6337
- for (let i = 1, offset = 0; offset < length; i += 1) {
6338
- previous = await hmac2(prk, concat(previous, info, new Uint8Array([i])));
6339
- out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
6340
- offset += previous.length;
6767
+ function chacha20Block(key, counter, nonce2) {
6768
+ const state = new Uint32Array(16);
6769
+ state[0] = 1634760805;
6770
+ state[1] = 857760878;
6771
+ state[2] = 2036477234;
6772
+ state[3] = 1797285236;
6773
+ for (let i = 0; i < 8; i += 1) state[4 + i] = u32le(key, i * 4);
6774
+ state[12] = counter >>> 0;
6775
+ for (let i = 0; i < 3; i += 1) state[13 + i] = u32le(nonce2, i * 4);
6776
+ const working = state.slice();
6777
+ for (let round = 0; round < 10; round += 1) {
6778
+ quarterRound(working, 0, 4, 8, 12);
6779
+ quarterRound(working, 1, 5, 9, 13);
6780
+ quarterRound(working, 2, 6, 10, 14);
6781
+ quarterRound(working, 3, 7, 11, 15);
6782
+ quarterRound(working, 0, 5, 10, 15);
6783
+ quarterRound(working, 1, 6, 11, 12);
6784
+ quarterRound(working, 2, 7, 8, 13);
6785
+ quarterRound(working, 3, 4, 9, 14);
6786
+ }
6787
+ const out = new Uint8Array(64);
6788
+ for (let i = 0; i < 16; i += 1) {
6789
+ const word = working[i] + state[i] >>> 0;
6790
+ out[i * 4] = word & 255;
6791
+ out[i * 4 + 1] = word >>> 8 & 255;
6792
+ out[i * 4 + 2] = word >>> 16 & 255;
6793
+ out[i * 4 + 3] = word >>> 24 & 255;
6341
6794
  }
6342
6795
  return out;
6343
6796
  }
6344
- var labeledExtract2 = (suite, salt, label, ikm) => hmac2(salt, concat(utf85("HPKE-v1"), suite, utf85(label), ikm));
6345
- var labeledExpand2 = (suite, prk, label, info, length) => expand2(prk, concat(i2osp22(length), utf85("HPKE-v1"), suite, utf85(label), info), length);
6346
- async function openDataKey(header, secret) {
6347
- const recipient = await x25519KeyPair(secret);
6348
- if (hex(recipient.publicKey) !== header.recipient) {
6349
- throw new Error("this key is not the one the file was sealed to");
6350
- }
6351
- const enc2 = fromHex(header.enc, "encapsulated key", 32);
6352
- const dhValue = await dh(recipient.privateKey, enc2);
6353
- const empty = new Uint8Array(0);
6354
- const prk = await labeledExtract2(KEM_SUITE2, empty, "eae_prk", dhValue);
6355
- const shared = await labeledExpand2(KEM_SUITE2, prk, "shared_secret", concat(enc2, recipient.publicKey), 32);
6356
- const pskIdHash = await labeledExtract2(HPKE_SUITE2, empty, "psk_id_hash", empty);
6357
- const infoHash = await labeledExtract2(HPKE_SUITE2, empty, "info_hash", HPKE_INFO);
6358
- const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);
6359
- const schedule = await labeledExtract2(HPKE_SUITE2, shared, "secret", empty);
6360
- const key = await labeledExpand2(HPKE_SUITE2, schedule, "key", context, 32);
6361
- const nonce2 = await labeledExpand2(HPKE_SUITE2, schedule, "base_nonce", context, 12);
6362
- const aes = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
6363
- let plain;
6364
- try {
6365
- plain = new Uint8Array(
6366
- await crypto.subtle.decrypt(
6367
- { name: "AES-GCM", iv: nonce2, additionalData: HPKE_AAD },
6368
- aes,
6369
- fromHex(header.wrappedKey, "wrapped key", 48)
6370
- )
6371
- );
6372
- } catch {
6373
- throw new Error("this key does not open the file");
6797
+ function chacha20(key, counter, nonce2, data) {
6798
+ const out = new Uint8Array(data.length);
6799
+ for (let offset = 0, block = counter; offset < data.length; offset += 64, block += 1) {
6800
+ const stream = chacha20Block(key, block, nonce2);
6801
+ const end = Math.min(offset + 64, data.length);
6802
+ for (let i = offset; i < end; i += 1) out[i] = data[i] ^ stream[i - offset];
6374
6803
  }
6375
- if (plain.length !== 32) throw new Error("the data key is not 32 bytes");
6376
- return plain;
6804
+ return out;
6377
6805
  }
6378
- async function holderRecoveryBody(holder, files, secret, options = {}) {
6379
- const checked2 = [];
6380
- for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
6381
- const header = await verifyRecoveryHeader(f);
6382
- if (options.verifyQuote) await verifyRecoveryAttestation(header, options.verifyQuote);
6383
- if (holderKey(header.holder) !== holderKey(holder)) {
6384
- throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);
6385
- }
6386
- checked2.push({ name: f.name, header });
6806
+ function leToBigInt(bytes) {
6807
+ let value = 0n;
6808
+ for (let i = bytes.length - 1; i >= 0; i -= 1) value = value << 8n | BigInt(bytes[i]);
6809
+ return value;
6810
+ }
6811
+ var P1305 = (1n << 130n) - 5n;
6812
+ function poly1305(key, message) {
6813
+ const r = leToBigInt(key.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn;
6814
+ const s = leToBigInt(key.subarray(16, 32));
6815
+ let acc = 0n;
6816
+ for (let offset = 0; offset < message.length; offset += 16) {
6817
+ const block = message.subarray(offset, Math.min(offset + 16, message.length));
6818
+ const n = leToBigInt(block) + (1n << BigInt(8 * block.length));
6819
+ acc = (acc + n) * r % P1305;
6387
6820
  }
6388
- const open = async (c) => ({
6389
- file: c.name,
6390
- key: hex(await openDataKey(c.header, secret))
6391
- });
6392
- const slice = checked2.filter((c) => c.header.kind === "holder").pop();
6393
- if (!slice) throw new Error(`no holder file of ${holderKey(holder)}`);
6394
- const newestByApp = /* @__PURE__ */ new Map();
6395
- for (const c of checked2) {
6396
- if (c.header.kind === "app" && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {
6397
- newestByApp.set(c.header.app, c);
6398
- }
6821
+ let tag = acc + s & (1n << 128n) - 1n;
6822
+ const out = new Uint8Array(TAG_LEN2);
6823
+ for (let i = 0; i < TAG_LEN2; i += 1) {
6824
+ out[i] = Number(tag & 0xffn);
6825
+ tag >>= 8n;
6399
6826
  }
6400
- return {
6401
- holder: holderKey(holder),
6402
- slice: await open(slice),
6403
- apps: await Promise.all([...newestByApp.values()].map(open)),
6404
- code: await Promise.all(checked2.filter((c) => c.header.kind === "code").map(open))
6405
- };
6406
- }
6407
- async function sha2564(data) {
6408
- return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
6827
+ return out;
6409
6828
  }
6410
- async function recoveryAttestationNonce(cluster, node) {
6411
- const name = utf85(cluster);
6412
- const len = new Uint8Array(4);
6413
- new DataView(len.buffer).setUint32(0, name.length, false);
6414
- const id = new Uint8Array(8);
6415
- new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
6416
- return hex(await sha2564(concat(utf85("calimero.recovery-backup.attest.v1\0"), len, name, id)));
6829
+ function pad16(length) {
6830
+ return new Uint8Array((16 - length % 16) % 16);
6417
6831
  }
6418
- async function receiptKeyBinding(receiptKey, governance, cluster, node) {
6419
- const g = await sha2564(utf85(JSON.stringify(governance)));
6420
- const name = utf85(cluster);
6421
- const len = new Uint8Array(4);
6422
- new DataView(len.buffer).setUint32(0, name.length, false);
6423
- const id = new Uint8Array(8);
6424
- new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
6425
- return hex(await sha2564(concat(utf85("calimero.tee-attest.receipt-key.v3"), receiptKey, g, len, name, id)));
6832
+ function u64le(value) {
6833
+ const out = new Uint8Array(8);
6834
+ new DataView(out.buffer).setBigUint64(0, BigInt(value), true);
6835
+ return out;
6426
6836
  }
6427
- async function verifyRecoveryAttestation(header, verifyQuote) {
6428
- const doc = header.attestation;
6429
- if (!doc || typeof doc.quote !== "string") throw new Error("the file carries no attestation");
6430
- if (doc.cluster !== header.cluster || doc.node !== header.node) {
6431
- throw new Error("the attestation is another node's");
6432
- }
6433
- if (doc.receiptKey !== header.signingKey) {
6434
- throw new Error("the attested key is not the one that signed the file");
6435
- }
6436
- const nonce2 = await recoveryAttestationNonce(header.cluster, header.node);
6437
- if (doc.nonce !== nonce2) throw new Error("the attestation is not over the recovery nonce");
6438
- const reportDataSuffix = await receiptKeyBinding(
6439
- fromHex(header.signingKey, "signing key", 32),
6440
- doc.governance,
6441
- header.cluster,
6442
- header.node
6443
- );
6444
- const ok = await verifyQuote({ quoteB64: doc.quote, nonce: nonce2, reportDataSuffix });
6445
- if (!ok) throw new Error("the quote was not accepted");
6837
+ function macData(aad, ciphertext) {
6838
+ const parts = [aad, pad16(aad.length), ciphertext, pad16(ciphertext.length), u64le(aad.length), u64le(ciphertext.length)];
6839
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
6840
+ let offset = 0;
6841
+ for (const part of parts) {
6842
+ out.set(part, offset);
6843
+ offset += part.length;
6844
+ }
6845
+ return out;
6846
+ }
6847
+ function check(key, nonce2) {
6848
+ if (key.length !== KEY_LEN) throw new Error("ChaCha20-Poly1305 needs a 32-byte key");
6849
+ if (nonce2.length !== NONCE_LEN) throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce");
6850
+ }
6851
+ function chacha20Poly1305Seal(key, nonce2, plaintext, aad = new Uint8Array(0)) {
6852
+ check(key, nonce2);
6853
+ const otk = chacha20Block(key, 0, nonce2).subarray(0, 32);
6854
+ const ciphertext = chacha20(key, 1, nonce2, plaintext);
6855
+ const tag = poly1305(otk, macData(aad, ciphertext));
6856
+ const out = new Uint8Array(ciphertext.length + TAG_LEN2);
6857
+ out.set(ciphertext);
6858
+ out.set(tag, ciphertext.length);
6859
+ return out;
6446
6860
  }
6447
6861
 
6448
- // src/package/pack.ts
6449
- var MAX_MANIFEST_BYTES = 1024 * 1024;
6450
- var MAX_PIPELINES_PER_PACKAGE = 16;
6451
- var MAX_PIPELINE_BYTES = 64 * 1024;
6452
- var MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
6453
- var MAX_MPK_BYTES = (64 * 1024 * 1024 - 1024 * 1024) / 4 * 3;
6454
- var DEV_SIGNER_ID = "did:key:z6MknF3p5L5FDHJQ7FREUapuX4Wmp4MtF6WrHYaXS2B3eZQd";
6455
- var MANIFEST_SIGNING_DOMAIN = new TextEncoder().encode("calimero.bundle.manifest.v1\0");
6456
- var MIN_RUNTIME_VERSION = "0.1.0";
6457
- var ED25519_PUB_MULTICODEC = [237, 1];
6458
- var BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
6459
- var COMPONENT_HEADER = [0, 97, 115, 109, 13, 0, 1, 0];
6460
- var PIPELINE_PATH = /^pipelines\/[A-Za-z0-9._-]+\.yaml$/;
6461
- var SEED_B64URL = /^[A-Za-z0-9_-]{43}$/;
6462
- var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
6862
+ // src/agent-gate/hpke.ts
6863
+ var KEM_ID2 = 32;
6864
+ var KDF_ID2 = 1;
6865
+ var AEAD_ID2 = 3;
6866
+ var MODE_AUTH = 2;
6867
+ var N_SECRET = 32;
6868
+ var N_KEY = 32;
6869
+ var N_NONCE = 12;
6463
6870
  var utf86 = (s) => new TextEncoder().encode(s);
6464
- var hex2 = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
6465
- var concat2 = (...parts) => {
6466
- const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
6467
- let off = 0;
6468
- for (const p of parts) out.set(p, off), off += p.length;
6469
- return out;
6470
- };
6471
- async function requireEd25519() {
6472
- const unsupported = new Error("this runtime cannot sign Ed25519 packages (WebCrypto Ed25519 is missing)");
6473
- if (!globalThis.crypto?.subtle) throw unsupported;
6474
- try {
6475
- await privateKey(new Uint8Array(32), false);
6476
- } catch {
6477
- throw unsupported;
6871
+ var i2osp22 = (n) => new Uint8Array([n >> 8 & 255, n & 255]);
6872
+ var KEM_SUITE2 = concat(utf86("KEM"), i2osp22(KEM_ID2));
6873
+ var HPKE_SUITE2 = concat(utf86("HPKE"), i2osp22(KEM_ID2), i2osp22(KDF_ID2), i2osp22(AEAD_ID2));
6874
+ async function hmac2(key, data) {
6875
+ const raw = key.length === 0 ? new Uint8Array(32) : key;
6876
+ const k = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
6877
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
6878
+ }
6879
+ async function expand2(prk, info, length) {
6880
+ const out = new Uint8Array(length);
6881
+ let previous = new Uint8Array(0);
6882
+ for (let i = 1, offset = 0; offset < length; i += 1) {
6883
+ previous = await hmac2(prk, concat(previous, info, new Uint8Array([i])));
6884
+ out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
6885
+ offset += previous.length;
6478
6886
  }
6887
+ return out;
6479
6888
  }
6480
- async function keyOfSeed(seed) {
6481
- await requireEd25519();
6482
- if (seed.length !== 32) throw new Error("a publisher seed is 32 bytes");
6483
- const publicKey = fromB64url(await recoveryPublicKey(seed));
6484
- return { seed: Uint8Array.from(seed), publicKey };
6889
+ function labeledExtract2(suite, salt, label, ikm) {
6890
+ return hmac2(salt, concat(utf86("HPKE-v1"), suite, utf86(label), ikm));
6485
6891
  }
6486
- async function generatePublisherKey() {
6487
- await requireEd25519();
6488
- return keyOfSeed(crypto.getRandomValues(new Uint8Array(32)));
6892
+ function labeledExpand2(suite, prk, label, info, length) {
6893
+ return expand2(prk, concat(i2osp22(length), utf86("HPKE-v1"), suite, utf86(label), info), length);
6489
6894
  }
6490
- async function webCryptoPublisherKey(key) {
6491
- await requireEd25519();
6492
- return { privateKey: await privateKey(Uint8Array.from(key.seed), false), publicKey: Uint8Array.from(key.publicKey) };
6895
+ async function extractAndExpand(dhValue, kemContext) {
6896
+ const prk = await labeledExtract2(KEM_SUITE2, new Uint8Array(0), "eae_prk", dhValue);
6897
+ return labeledExpand2(KEM_SUITE2, prk, "shared_secret", kemContext, N_SECRET);
6493
6898
  }
6494
- function base58(bytes) {
6495
- let n = 0n;
6496
- for (const b of bytes) n = n << 8n | BigInt(b);
6497
- let out = "";
6498
- for (; n > 0n; n /= 58n) out = BASE58[Number(n % 58n)] + out;
6499
- return "1".repeat(bytes.findIndex((b) => b !== 0) === -1 ? bytes.length : bytes.findIndex((b) => b !== 0)) + out;
6899
+ async function keySchedule(sharedSecret, info) {
6900
+ const empty = new Uint8Array(0);
6901
+ const pskIdHash = await labeledExtract2(HPKE_SUITE2, empty, "psk_id_hash", empty);
6902
+ const infoHash = await labeledExtract2(HPKE_SUITE2, empty, "info_hash", info);
6903
+ const context = concat(new Uint8Array([MODE_AUTH]), pskIdHash, infoHash);
6904
+ const secret = await labeledExtract2(HPKE_SUITE2, sharedSecret, "secret", empty);
6905
+ return {
6906
+ key: await labeledExpand2(HPKE_SUITE2, secret, "key", context, N_KEY),
6907
+ nonce: await labeledExpand2(HPKE_SUITE2, secret, "base_nonce", context, N_NONCE)
6908
+ };
6500
6909
  }
6501
- function signerIdOf(key) {
6502
- return `did:key:z${base58(concat2(Uint8Array.from(ED25519_PUB_MULTICODEC), key.publicKey))}`;
6910
+ async function hpkeSealAuth(recipientPublic, senderSecret, info, plaintext, aad = new Uint8Array(0), ephemeralSecret) {
6911
+ if (recipientPublic.length !== 32) throw new Error("The recipient key is not 32 bytes of X25519");
6912
+ const ephemeral = await x25519KeyPair(ephemeralSecret);
6913
+ const sender = await x25519KeyPair(senderSecret);
6914
+ const dhValue = concat(await dh(ephemeral.privateKey, recipientPublic), await dh(sender.privateKey, recipientPublic));
6915
+ const shared = await extractAndExpand(dhValue, concat(ephemeral.publicKey, recipientPublic, sender.publicKey));
6916
+ const { key, nonce: nonce2 } = await keySchedule(shared, info);
6917
+ return { enc: ephemeral.publicKey, ciphertext: chacha20Poly1305Seal(key, nonce2, plaintext, aad) };
6503
6918
  }
6504
- function isDevPublisherKey(key) {
6505
- return signerIdOf(key) === DEV_SIGNER_ID;
6919
+
6920
+ // src/agent-gate/gate.ts
6921
+ var AGENT_ATTEST_DOMAIN = "mero-agent-gate/attest/v3";
6922
+ var AGENT_PROVISION_INFO_DOMAIN = "mero-agent-gate/provision/v2";
6923
+ var AGENT_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
6924
+ var SECRET_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
6925
+ var MAX_SECRETS = 64;
6926
+ var MAX_SECRET_LEN = 64 * 1024;
6927
+ var AgentGateError = class extends Error {
6928
+ constructor(message, status, code) {
6929
+ super(message);
6930
+ this.status = status;
6931
+ this.code = code;
6932
+ this.name = "AgentGateError";
6933
+ }
6934
+ };
6935
+ function validateAgentId(agentId) {
6936
+ if (!AGENT_ID.test(agentId)) {
6937
+ throw new Error(`Agent id ${JSON.stringify(agentId)} must match [a-z0-9][a-z0-9-]{0,62}`);
6938
+ }
6506
6939
  }
6507
- function exportPublisherKey(key) {
6508
- return utf86(
6509
- JSON.stringify({ private_key: b64url(key.seed), public_key: b64url(key.publicKey), signer_id: signerIdOf(key) }, null, 2)
6510
- );
6940
+ function utf87(value) {
6941
+ return new TextEncoder().encode(value);
6511
6942
  }
6512
- async function importPublisherKey(bytes) {
6513
- let file;
6943
+ function lengthPrefixed(agentId) {
6944
+ const id = utf87(agentId);
6945
+ return concat(new Uint8Array([id.length]), id);
6946
+ }
6947
+ function toBase64(bytes) {
6948
+ let binary = "";
6949
+ for (const byte of bytes) binary += String.fromCharCode(byte);
6950
+ return btoa(binary);
6951
+ }
6952
+ function fromBase643(value, label, length) {
6953
+ let bytes;
6514
6954
  try {
6515
- file = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
6955
+ bytes = Uint8Array.from(atob(value.trim()), (c) => c.charCodeAt(0));
6516
6956
  } catch {
6517
- throw new Error("a publisher key backup is a JSON document");
6518
- }
6519
- const seed = file?.private_key;
6520
- if (typeof seed !== "string" || !SEED_B64URL.test(seed) || b64url(fromB64url(seed)) !== seed) {
6521
- throw new Error("the backup private_key is not an unpadded base64url 32-byte seed");
6522
- }
6523
- const key = await keyOfSeed(fromB64url(seed));
6524
- if (file.public_key !== void 0 && file.public_key !== b64url(key.publicKey)) {
6525
- throw new Error("the backup public_key is not the seed's");
6526
- }
6527
- if (file.signer_id !== void 0 && file.signer_id !== signerIdOf(key)) {
6528
- throw new Error("the backup signer_id is not the seed's");
6957
+ throw new Error(`${label} is not base64`);
6529
6958
  }
6530
- return key;
6959
+ if (length !== void 0 && bytes.length !== length) throw new Error(`${label} is not ${length} bytes`);
6960
+ return bytes;
6531
6961
  }
6532
- function canonicalizeManifest(manifest) {
6533
- const signed = Object.fromEntries(Object.entries(manifest).filter(([k]) => k !== "signature" && !k.startsWith("_")));
6534
- return utf86(jcs(signed));
6962
+ async function agentKeyBinding(provisioningPublic, agentId, signingPublic, ownerPublic) {
6963
+ const zero = new Uint8Array(32);
6964
+ const data = concat(
6965
+ utf87(AGENT_ATTEST_DOMAIN),
6966
+ provisioningPublic,
6967
+ lengthPrefixed(agentId),
6968
+ signingPublic ?? zero,
6969
+ ownerPublic ?? zero
6970
+ );
6971
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
6535
6972
  }
6536
- function jcs(value) {
6537
- if (typeof value === "string") {
6538
- if (/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)) {
6539
- throw new Error("a lone surrogate cannot be canonicalized");
6540
- }
6541
- return JSON.stringify(value);
6542
- }
6543
- if (typeof value === "number") {
6544
- if (!Number.isSafeInteger(value)) throw new Error("only safe integers can be canonicalized");
6545
- return String(value);
6546
- }
6547
- if (value === null || typeof value === "boolean") return String(value);
6548
- if (Array.isArray(value)) return `[${value.map(jcs).join(",")}]`;
6549
- return `{${Object.keys(value).sort().map((k) => `${jcs(k)}:${jcs(value[k])}`).join(",")}}`;
6973
+ function provisionInfo(recipientPublic, agentId) {
6974
+ return concat(utf87(AGENT_PROVISION_INFO_DOMAIN), recipientPublic, lengthPrefixed(agentId));
6550
6975
  }
6551
- async function signingPayload(manifest) {
6552
- return sha2562(concat2(MANIFEST_SIGNING_DOMAIN, canonicalizeManifest(manifest)));
6976
+ async function generateOwnerKey() {
6977
+ const secret = crypto.getRandomValues(new Uint8Array(32));
6978
+ return { secret, publicKey: await ownerPublicKey(secret) };
6553
6979
  }
6554
- async function verifyManifestSignature(manifest) {
6555
- await requireEd25519();
6556
- const sig = manifest.signature;
6557
- if (!sig) throw new Error("manifest is missing required 'signature' field");
6558
- if (sig.algorithm !== "ed25519") throw new Error(`unsupported signature algorithm: '${sig.algorithm}'`);
6559
- const publicKey = fromB64url(sig.publicKey ?? "");
6560
- const signature = fromB64url(sig.signature ?? "");
6561
- if (publicKey.length !== 32 || signature.length !== 64) throw new Error("malformed signature field");
6562
- const key = await crypto.subtle.importKey("raw", buf2(publicKey), { name: "Ed25519" }, false, ["verify"]);
6563
- const ok = await crypto.subtle.verify("Ed25519", key, buf2(signature), buf2(await signingPayload(manifest)));
6564
- if (!ok) throw new Error("Ed25519 signature verification failed");
6565
- const derived = signerIdOf({ publicKey });
6566
- if (manifest.signerId !== derived) {
6567
- throw new Error(`signerId mismatch: manifest declares '${manifest.signerId}' but signature public key derives to '${derived}'`);
6568
- }
6569
- return derived;
6980
+ async function ownerPublicKey(secret) {
6981
+ if (secret.length !== 32) throw new Error("An owner key is 32 bytes");
6982
+ return toBase64((await x25519KeyPair(secret)).publicKey);
6570
6983
  }
6571
- function checkPathComponent(value, field) {
6572
- if (!value) throw new Error(`${field} is empty`);
6573
- if (value.includes("..")) throw new Error(`${field} contains path traversal sequence '..'`);
6574
- if (value.includes("/") || value.includes("\\")) throw new Error(`${field} contains directory separator`);
6575
- if (value.includes("\0")) throw new Error(`${field} contains null byte`);
6576
- if (value.length >= 2 && value[1] === ":") throw new Error(`${field} appears to be an absolute path`);
6984
+ function url(gateUrl, path) {
6985
+ return `${gateUrl.replace(/\/+$/, "")}${path}`;
6577
6986
  }
6578
- function checkPipelinePath(value, field) {
6579
- if (!value) throw new Error(`${field} is empty`);
6580
- if (value.includes("\0")) throw new Error(`${field} contains null byte`);
6581
- if (value.includes("\\")) throw new Error(`${field} contains backslash (use forward slashes)`);
6582
- if (value.startsWith("/")) throw new Error(`${field} is an absolute path`);
6583
- if (value[1] === ":") throw new Error(`${field} appears to be an absolute Windows path`);
6584
- if (value.split("/").includes("..")) throw new Error(`${field} contains path traversal component '..'`);
6585
- if (!PIPELINE_PATH.test(value) || utf86(value).length > 100) {
6586
- throw new Error(`${field} must be pipelines/<name>.yaml (A-Z a-z 0-9 . _ -), at most 100 bytes`);
6987
+ async function postJson(fetchImpl, target, body) {
6988
+ const response = await fetchImpl(target, {
6989
+ method: "POST",
6990
+ headers: { "content-type": "application/json" },
6991
+ body: JSON.stringify(body)
6992
+ });
6993
+ const text = await response.text();
6994
+ let parsed = void 0;
6995
+ try {
6996
+ parsed = text ? JSON.parse(text) : void 0;
6997
+ } catch {
6998
+ }
6999
+ if (!response.ok) {
7000
+ const error = parsed;
7001
+ throw new AgentGateError(
7002
+ `The gate answered ${response.status}${error?.error ? ` ${error.error}` : ""}: ${error?.details ?? text.slice(0, 200)}`,
7003
+ response.status,
7004
+ error?.error
7005
+ );
6587
7006
  }
7007
+ return parsed;
6588
7008
  }
6589
- var METADATA_STRINGS = ["name", "description", "author", "icon", "license", "category", "guide"];
6590
- function normalizeMetadata(m) {
6591
- const bad = (what) => new Error(`metadata ${what}`);
6592
- if (typeof m !== "object" || m === null || Array.isArray(m)) throw bad("must be an object");
6593
- const known = /* @__PURE__ */ new Set([...METADATA_STRINGS, "tags"]);
6594
- const unknown = Object.keys(m).find((k) => !known.has(k));
6595
- if (unknown !== void 0) throw bad(`has an unknown field '${unknown}'`);
6596
- const out = {};
6597
- for (const k of METADATA_STRINGS) {
6598
- const v = m[k];
6599
- if (v === void 0) continue;
6600
- if (typeof v !== "string") throw bad(`${k} must be a string`);
6601
- out[k] = v;
7009
+ async function attestAgent(options) {
7010
+ const agentId = options.agentId ?? "";
7011
+ if (agentId) validateAgentId(agentId);
7012
+ const nonce2 = crypto.getRandomValues(new Uint8Array(32));
7013
+ const body = await postJson(options.fetch ?? fetch, url(options.gateUrl, "/attest"), {
7014
+ nonceB64: toBase64(nonce2),
7015
+ ...agentId ? { agentId } : {}
7016
+ });
7017
+ if ((body?.agentId ?? "") !== agentId) {
7018
+ throw new Error(`Asked about agent ${JSON.stringify(agentId)}, the gate answered for ${JSON.stringify(body?.agentId)}`);
6602
7019
  }
6603
- if (typeof out.name !== "string") throw bad("name is required");
6604
- if (m.tags !== void 0) {
6605
- if (!Array.isArray(m.tags) || m.tags.some((t) => typeof t !== "string")) throw bad("tags must be an array of strings");
6606
- out.tags = [...m.tags];
7020
+ const provisioning = fromBase643(body.provisioningPublicKeyB64 ?? "", "provisioningPublicKeyB64", 32);
7021
+ const signing = body.signingPublicKeyB64 ? fromBase643(body.signingPublicKeyB64, "signingPublicKeyB64", 32) : void 0;
7022
+ const owner = body.ownerPublicKeyB64 ? fromBase643(body.ownerPublicKeyB64, "ownerPublicKeyB64", 32) : void 0;
7023
+ if (!signing !== !owner) {
7024
+ throw new Error("A claimed agent has both a signing key and an owner; the gate named one");
6607
7025
  }
6608
- return out;
6609
- }
6610
- var artifact = (path, bytes) => ({ path, hash: hex2(sha2562(bytes)), size: bytes.length });
6611
- var padded = (n) => 512 + Math.ceil(n / 512) * 512;
6612
- function tarEntry(name, data) {
6613
- const header = new Uint8Array(512);
6614
- const put = (off, text) => header.set(utf86(text), off);
6615
- put(0, name);
6616
- put(100, "0000644\0");
6617
- put(108, "0000000\0");
6618
- put(116, "0000000\0");
6619
- put(124, `${data.length.toString(8).padStart(11, "0")}\0`);
6620
- put(136, "00000000000\0");
6621
- put(148, " ");
6622
- put(156, "0");
6623
- put(257, "ustar\0");
6624
- put(263, "00");
6625
- put(148, `${header.reduce((n, b) => n + b, 0).toString(8).padStart(6, "0")}\0 `);
6626
- return concat2(header, data, new Uint8Array((512 - data.length % 512) % 512));
7026
+ const binding = await agentKeyBinding(provisioning, agentId, signing, owner);
7027
+ await options.verifier({ quoteB64: body.quoteB64, nonce: hex(nonce2), reportDataSuffix: hex(binding) });
7028
+ return {
7029
+ agentId,
7030
+ provisioningPublicKey: toBase64(provisioning),
7031
+ ...signing ? { signingPublicKey: toBase64(signing) } : {},
7032
+ ...owner ? { ownerPublicKey: toBase64(owner) } : {}
7033
+ };
6627
7034
  }
6628
- function readTar(tar) {
6629
- const out = /* @__PURE__ */ new Map();
6630
- const text = (a, b) => new TextDecoder().decode(tar.subarray(a, b)).replace(/\0.*$/s, "");
6631
- for (let off = 0; off + 512 <= tar.length && tar[off] !== 0; ) {
6632
- const name = text(off, off + 100);
6633
- const size = parseInt(text(off + 124, off + 136).trim(), 8);
6634
- if (out.has(name)) throw new Error(`the archive has more than one entry at '${name}'`);
6635
- out.set(name, tar.subarray(off + 512, off + 512 + size));
6636
- off += padded(size);
7035
+ async function checkOwner(agent, ownerSecret) {
7036
+ const mine = await ownerPublicKey(ownerSecret);
7037
+ if (agent.ownerPublicKey && agent.ownerPublicKey !== mine) {
7038
+ throw new AgentGateError(
7039
+ `This agent is claimed by another key (${agent.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,
7040
+ void 0,
7041
+ "not_yours"
7042
+ );
6637
7043
  }
6638
- return out;
7044
+ return mine;
6639
7045
  }
6640
- async function checkPackage(tar, publicKey) {
6641
- const entries = readTar(tar);
6642
- const raw = entries.get("manifest.json");
6643
- if (!raw) throw new Error("manifest.json not found in bundle");
6644
- const manifest = JSON.parse(new TextDecoder().decode(raw));
6645
- await verifyManifestSignature(manifest);
6646
- if (manifest.signature.publicKey !== b64url(publicKey)) throw new Error("the manifest is not signed by the publisher key");
6647
- const declared = [manifest.compute, ...manifest.pipelines ?? []];
6648
- const names = ["manifest.json", ...declared.map((a) => a.path)];
6649
- if (names.length !== entries.size || names.some((n) => !entries.has(n))) {
6650
- throw new Error("the archive does not hold exactly the files its manifest declares");
6651
- }
6652
- for (const a of declared) {
6653
- const bytes = entries.get(a.path);
6654
- if (!bytes || bytes.length !== a.size || hex2(sha2562(bytes)) !== a.hash) {
6655
- throw new Error(`bundle artifact '${a.path}' failed its integrity check`);
6656
- }
7046
+ function validateSecrets(secrets) {
7047
+ const names = Object.keys(secrets);
7048
+ if (names.length === 0) throw new Error("There are no secrets to provision");
7049
+ if (names.length > MAX_SECRETS) throw new Error(`At most ${MAX_SECRETS} secrets at once`);
7050
+ for (const name of names) {
7051
+ if (!SECRET_NAME.test(name)) throw new Error(`Secret name ${JSON.stringify(name)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);
7052
+ if (typeof secrets[name] !== "string") throw new Error(`Secret ${name} is not a string`);
7053
+ if (utf87(secrets[name]).length > MAX_SECRET_LEN) throw new Error(`Secret ${name} is over ${MAX_SECRET_LEN} bytes`);
6657
7054
  }
6658
7055
  }
6659
- async function gzip(bytes) {
6660
- if (typeof CompressionStream === "undefined") throw new Error("this runtime cannot gzip packages (no CompressionStream)");
6661
- const stream = new Blob([buf2(bytes)]).stream().pipeThrough(new CompressionStream("gzip"));
6662
- return new Uint8Array(await new Response(stream).arrayBuffer());
7056
+ async function sendSealed(fetchImpl, gateUrl, path, agent, ownerSecret, message) {
7057
+ if (!agent.agentId) throw new Error("This quote names no agent; attest with the agent id");
7058
+ const mine = await checkOwner(agent, ownerSecret);
7059
+ const recipient = fromBase643(agent.provisioningPublicKey, "provisioningPublicKey", 32);
7060
+ const sealed = await hpkeSealAuth(
7061
+ recipient,
7062
+ ownerSecret,
7063
+ provisionInfo(recipient, agent.agentId),
7064
+ utf87(JSON.stringify(message))
7065
+ );
7066
+ return postJson(fetchImpl, url(gateUrl, path), {
7067
+ agentId: agent.agentId,
7068
+ provisioningPublicKeyB64: agent.provisioningPublicKey,
7069
+ senderPublicKeyB64: mine,
7070
+ encappedKeyB64: toBase64(sealed.enc),
7071
+ ciphertextB64: toBase64(sealed.ciphertext)
7072
+ });
6663
7073
  }
6664
- async function signerOf(key, seed, publicKey) {
6665
- if (seed) {
6666
- const derived = fromB64url(await recoveryPublicKey(seed));
6667
- if (hex2(derived) !== hex2(publicKey)) throw new Error("the publisher key's publicKey is not its seed's");
6668
- return { signing: await privateKey(seed, false), publicKey: derived };
7074
+ async function provisionAgent(options) {
7075
+ validateSecrets(options.secrets);
7076
+ const fetchImpl = options.fetch ?? fetch;
7077
+ const answer = await sendSealed(fetchImpl, options.gateUrl, "/provision", options.agent, options.ownerSecret, {
7078
+ secrets: options.secrets
7079
+ });
7080
+ const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });
7081
+ const mine = await ownerPublicKey(options.ownerSecret);
7082
+ if (after.ownerPublicKey !== mine || !after.signingPublicKey) {
7083
+ throw new AgentGateError("The gate accepted the secrets, but its quote does not name your key as owner");
6669
7084
  }
6670
- const k = key.privateKey;
6671
- if (k?.algorithm?.name !== "Ed25519" || k.type !== "private" || !k.usages.includes("sign")) {
6672
- throw new Error("the publisher key is not an Ed25519 signing key");
7085
+ if (options.agent.signingPublicKey && options.agent.signingPublicKey !== after.signingPublicKey) {
7086
+ throw new AgentGateError("The agent's signing key changed while provisioning");
6673
7087
  }
6674
- return { signing: k, publicKey };
7088
+ return {
7089
+ agentId: after.agentId,
7090
+ provisioningPublicKey: after.provisioningPublicKey,
7091
+ signingPublicKey: after.signingPublicKey,
7092
+ ownerPublicKey: mine,
7093
+ written: answer?.written ?? [],
7094
+ claimed: answer?.claimed === true
7095
+ };
6675
7096
  }
6676
- async function packComputePackage(input, key) {
6677
- const seed = "seed" in key && key.seed ? Uint8Array.from(key.seed) : void 0;
6678
- const publicKey = Uint8Array.from(key.publicKey);
6679
- const job = prepare(input);
6680
- await requireEd25519();
6681
- const { signing, publicKey: pub } = await signerOf(key, seed, publicKey);
6682
- const manifest = { ...job.manifest, signerId: signerIdOf({ publicKey: pub }) };
6683
- const signature = await crypto.subtle.sign("Ed25519", signing, buf2(await signingPayload(manifest)));
6684
- manifest.signature = { algorithm: "ed25519", publicKey: b64url(pub), signature: b64url(new Uint8Array(signature)) };
6685
- const manifestBytes = utf86(jcs(manifest));
6686
- if (manifestBytes.length > MAX_MANIFEST_BYTES) {
6687
- throw new Error(`bundle manifest.json exceeds the ${MAX_MANIFEST_BYTES} byte cap`);
7097
+ async function releaseAgent(options) {
7098
+ if (!options.agent.ownerPublicKey) throw new Error("This agent is not claimed; there is nothing to release");
7099
+ const fetchImpl = options.fetch ?? fetch;
7100
+ await sendSealed(fetchImpl, options.gateUrl, "/release", options.agent, options.ownerSecret, { release: true });
7101
+ const after = await attestAgent({ gateUrl: options.gateUrl, agentId: options.agent.agentId, verifier: options.verifier, fetch: fetchImpl });
7102
+ if (after.ownerPublicKey) {
7103
+ throw new AgentGateError("The gate says it released the agent, but its quote still names an owner");
6688
7104
  }
6689
- const files = [["manifest.json", manifestBytes], ["compute.wasm", job.compute], ...job.files];
6690
- checkArchiveSize(files.map(([, b]) => b.length));
6691
- const tar = concat2(...files.map(([n, b]) => tarEntry(n, b)), new Uint8Array(1024));
6692
- await checkPackage(tar, pub);
6693
- const mpk = await gzip(tar);
6694
- if (mpk.length > MAX_MPK_BYTES) throw new Error(`a package is limited to ${MAX_MPK_BYTES >> 20} MiB`);
6695
- return mpk;
6696
7105
  }
6697
- function checkArchiveSize(sizes) {
6698
- if (sizes.reduce((n, s) => n + padded(s), 1024) > MAX_ARCHIVE_BYTES) {
6699
- throw new Error(`bundle archive exceeds the ${MAX_ARCHIVE_BYTES} byte decompressed cap`);
7106
+
7107
+ // src/agent-gate/policy.ts
7108
+ var KMS_RELEASE_SIGNER = Object.freeze({
7109
+ identity: "https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",
7110
+ issuer: "https://token.actions.githubusercontent.com"
7111
+ });
7112
+ var LISTS = [
7113
+ "allowed_tcb_statuses",
7114
+ "allowed_mrtd",
7115
+ "allowed_rtmr0",
7116
+ "allowed_rtmr1",
7117
+ "allowed_rtmr2",
7118
+ "allowed_rtmr3"
7119
+ ];
7120
+ async function verifySignedAgentPolicy(policy, bundle, options = {}) {
7121
+ const body = typeof policy === "string" ? new TextEncoder().encode(policy) : policy;
7122
+ await verifyCosignBundle(body, bundle, {
7123
+ identity: options.identity ?? KMS_RELEASE_SIGNER.identity,
7124
+ issuer: options.issuer ?? KMS_RELEASE_SIGNER.issuer
7125
+ });
7126
+ let parsed;
7127
+ try {
7128
+ parsed = JSON.parse(new TextDecoder().decode(body));
7129
+ } catch {
7130
+ throw new Error("The signed agent policy is not JSON");
6700
7131
  }
6701
- }
6702
- function prepare(input) {
6703
- checkPathComponent(input.package, "package");
6704
- checkPathComponent(input.version, "appVersion");
6705
- if (!SEMVER.test(input.version)) throw new Error(`appVersion '${input.version}' is not a semantic version`);
6706
- if (!input.compute?.length) throw new Error("the package ships no WASM");
6707
- if (input.pipelines.length > MAX_PIPELINES_PER_PACKAGE) {
6708
- throw new Error(`bundle declares ${input.pipelines.length} pipelines, at most ${MAX_PIPELINES_PER_PACKAGE} are allowed`);
7132
+ const role = options.role ?? "agent";
7133
+ if (parsed?.role !== role) {
7134
+ throw new Error(`The signed file is a ${JSON.stringify(parsed?.role)} policy, not an ${role} one`);
6709
7135
  }
6710
- checkArchiveSize([input.compute.length]);
6711
- const compute = Uint8Array.from(input.compute);
6712
- if (COMPONENT_HEADER.some((b, i) => compute[i] !== b)) {
6713
- throw new Error("compute: not a WASM component (an SDK 0.12 core module is refused by the node)");
7136
+ const profile = options.profile ?? PRODUCTION_PROFILE;
7137
+ if (parsed.profile !== profile) {
7138
+ throw new Error(`The signed agent policy is for the ${JSON.stringify(parsed.profile)} profile, not ${profile}`);
6714
7139
  }
6715
- const files = input.pipelines.map((p, i) => {
6716
- checkPipelinePath(p.path, `pipelines[${i}].path`);
6717
- return [p.path, utf86(p.source)];
7140
+ if (options.expectedVersion !== void 0 && parsed.version !== options.expectedVersion) {
7141
+ throw new Error(`The signed agent policy is release ${JSON.stringify(parsed.version)}, not ${options.expectedVersion}`);
7142
+ }
7143
+ checkLists(parsed);
7144
+ return parsed;
7145
+ }
7146
+ function checkLists(policy) {
7147
+ for (const list2 of LISTS) {
7148
+ if (!Array.isArray(policy?.[list2]) || policy[list2].length === 0) {
7149
+ throw new Error(`The agent policy's ${list2} is empty, so no agent would be accepted`);
7150
+ }
7151
+ }
7152
+ }
7153
+ var TCB_STATUSES2 = [
7154
+ "UpToDate",
7155
+ "SWHardeningNeeded",
7156
+ "ConfigurationNeeded",
7157
+ "ConfigurationAndSWHardeningNeeded",
7158
+ "OutOfDate",
7159
+ "OutOfDateConfigurationNeeded"
7160
+ ];
7161
+ function tcbStatus2(value) {
7162
+ const found = TCB_STATUSES2.find((status) => status.toLowerCase() === value.trim().toLowerCase());
7163
+ if (!found) throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(value)}`);
7164
+ return found;
7165
+ }
7166
+ var register = (value) => value.trim().replace(/^0x/i, "");
7167
+ function agentQuoteVerifier(policy, options) {
7168
+ checkLists(policy);
7169
+ return createQuoteVerifier({
7170
+ dcapVerify: options.dcapVerify,
7171
+ fetchCollateral: options.fetchCollateral,
7172
+ now: options.now,
7173
+ allowedTcbStatuses: policy.allowed_tcb_statuses.map(tcbStatus2),
7174
+ allowedMrtd: policy.allowed_mrtd.map(register),
7175
+ allowedRtmr0: policy.allowed_rtmr0.map(register),
7176
+ allowedRtmr1: policy.allowed_rtmr1.map(register),
7177
+ allowedRtmr2: policy.allowed_rtmr2.map(register),
7178
+ allowedRtmr3: policy.allowed_rtmr3.map(register)
6718
7179
  });
6719
- const big = files.find(([, b]) => b.length > MAX_PIPELINE_BYTES);
6720
- if (big) throw new Error(`pipeline '${big[0]}' exceeds the ${MAX_PIPELINE_BYTES} byte cap`);
6721
- const lower = files.map(([n]) => n.toLowerCase());
6722
- if (new Set(lower).size !== files.length) throw new Error("two pipelines have the same path");
6723
- const metadata = input.metadata === void 0 ? void 0 : normalizeMetadata(input.metadata);
6724
- const manifest = {
6725
- version: "1.0",
6726
- package: input.package,
6727
- appVersion: input.version,
6728
- minRuntimeVersion: MIN_RUNTIME_VERSION,
6729
- ...metadata ? { metadata } : {},
6730
- compute: artifact("compute.wasm", compute),
6731
- ...files.length ? { pipelines: files.map(([n, b]) => artifact(n, b)) } : {}
6732
- };
6733
- return { manifest, compute, files };
6734
7180
  }
6735
7181
  export {
6736
7182
  AGENT_ATTEST_DOMAIN,
@@ -6831,10 +7277,12 @@ export {
6831
7277
  frontendManifest,
6832
7278
  generateOwnerKey,
6833
7279
  generatePublisherKey,
7280
+ governanceCanonical,
6834
7281
  holderKey,
6835
7282
  holderRecoveryBody,
6836
7283
  importPublisherKey,
6837
7284
  isDevPublisherKey,
7285
+ jobKeyBinding,
6838
7286
  leaveOrgConsent,
6839
7287
  newBackupKeyPair,
6840
7288
  newIdempotencyKey,
@@ -6855,6 +7303,7 @@ export {
6855
7303
  publisherBindingMessage,
6856
7304
  queryString,
6857
7305
  receiptKeyBinding,
7306
+ receiptMessage,
6858
7307
  recoveryAttestationNonce,
6859
7308
  recoveryMessage,
6860
7309
  recoveryPublicKey,
@@ -6866,6 +7315,7 @@ export {
6866
7315
  removeMemberConsent,
6867
7316
  removeMemberTeamsConsent,
6868
7317
  renameOrgConsent,
7318
+ reportMessage,
6869
7319
  retryDelayMs,
6870
7320
  revokeInviteConsent,
6871
7321
  routePath,
@@ -6883,8 +7333,12 @@ export {
6883
7333
  trustedMeasurementsFromReleases,
6884
7334
  upgradeConsent,
6885
7335
  validateAgentId,
7336
+ verifyAppCluster,
7337
+ verifyJobReports,
6886
7338
  verifyNode,
6887
7339
  verifyNodeUrl,
7340
+ verifyPipelineReceipt,
7341
+ verifyReceiptKey,
6888
7342
  verifyRecoveryAttestation,
6889
7343
  verifyRecoveryHeader,
6890
7344
  verifyReleaseUrl,