@calimero-network/mero-js 22.7.0 → 22.9.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.
Files changed (76) hide show
  1. package/dist/account/account.d.ts +99 -4
  2. package/dist/account/account.js +0 -0
  3. package/dist/account/index.d.ts +6 -2
  4. package/dist/account/index.js +3 -1
  5. package/dist/admin-api/admin-client.d.ts +154 -2
  6. package/dist/admin-api/admin-client.js +255 -1
  7. package/dist/admin-api/admin-types.d.ts +193 -5
  8. package/dist/cloud/cloud-client.d.ts +38 -8
  9. package/dist/cloud/cloud-client.js +38 -21
  10. package/dist/cloud/connect.d.ts +101 -2
  11. package/dist/cloud/connect.js +84 -8
  12. package/dist/cloud/enrol-redirect.d.ts +195 -0
  13. package/dist/cloud/enrol-redirect.js +236 -0
  14. package/dist/cloud/index.d.ts +6 -2
  15. package/dist/cloud/index.js +7 -1
  16. package/dist/cloud/link-redirect.d.ts +85 -0
  17. package/dist/cloud/link-redirect.js +105 -0
  18. package/dist/crypto/internal.d.ts +15 -0
  19. package/dist/crypto/internal.js +18 -0
  20. package/dist/device-cert/device-cert.d.ts +96 -2
  21. package/dist/device-cert/device-cert.js +101 -11
  22. package/dist/device-cert/device-scope.d.ts +58 -0
  23. package/dist/device-cert/device-scope.js +76 -0
  24. package/dist/device-cert/index.d.ts +4 -2
  25. package/dist/device-cert/index.js +2 -1
  26. package/dist/events/sse.d.ts +22 -2
  27. package/dist/events/sse.js +20 -11
  28. package/dist/http-client/http-types.d.ts +18 -0
  29. package/dist/http-client/web-client.js +21 -1
  30. package/dist/index.browser.mjs +2 -2
  31. package/dist/index.browser.mjs.map +4 -4
  32. package/dist/index.cjs +1955 -496
  33. package/dist/index.cjs.map +4 -4
  34. package/dist/index.d.ts +13 -4
  35. package/dist/index.js +21 -2
  36. package/dist/index.mjs +1955 -496
  37. package/dist/index.mjs.map +4 -4
  38. package/dist/invitation/index.d.ts +2 -0
  39. package/dist/invitation/index.js +2 -0
  40. package/dist/invitation/invitation.d.ts +106 -0
  41. package/dist/invitation/invitation.js +104 -0
  42. package/dist/login/login.d.ts +11 -1
  43. package/dist/login/login.js +5 -4
  44. package/dist/login/session.d.ts +21 -5
  45. package/dist/login/session.js +7 -15
  46. package/dist/namespace-op/namespace-op.d.ts +14 -2
  47. package/dist/namespace-op/namespace-op.js +13 -19
  48. package/dist/relay/index.d.ts +2 -2
  49. package/dist/relay/index.js +1 -1
  50. package/dist/relay/nonce-source.d.ts +135 -0
  51. package/dist/relay/nonce-source.js +187 -19
  52. package/dist/relay/relay-client.d.ts +60 -5
  53. package/dist/relay/relay-client.js +84 -4
  54. package/dist/relay-attestation/attest-node-key.d.ts +66 -0
  55. package/dist/relay-attestation/attest-node-key.js +110 -0
  56. package/dist/relay-attestation/index.d.ts +1 -0
  57. package/dist/relay-attestation/index.js +1 -0
  58. package/dist/request-proof/authorizer.d.ts +48 -0
  59. package/dist/request-proof/authorizer.js +65 -0
  60. package/dist/request-proof/index.d.ts +4 -0
  61. package/dist/request-proof/index.js +2 -0
  62. package/dist/request-proof/request-proof.d.ts +56 -0
  63. package/dist/request-proof/request-proof.js +111 -0
  64. package/dist/rpc/index.d.ts +21 -0
  65. package/dist/rpc/index.js +20 -0
  66. package/dist/transport/index.d.ts +6 -0
  67. package/dist/transport/index.js +3 -0
  68. package/dist/transport/mero-client.d.ts +286 -0
  69. package/dist/transport/mero-client.js +379 -0
  70. package/dist/transport/relay-observer.d.ts +152 -0
  71. package/dist/transport/relay-observer.js +173 -0
  72. package/dist/transport/relay-transport.d.ts +73 -0
  73. package/dist/transport/relay-transport.js +94 -0
  74. package/dist/transport/types.d.ts +100 -0
  75. package/dist/transport/types.js +32 -0
  76. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -170,8 +170,27 @@ var WebHttpClient = class {
170
170
  } else {
171
171
  headersObj = headers;
172
172
  }
173
+ const method = init?.method || "GET";
174
+ if (this.transport.authorizeRequest) {
175
+ const body = init?.body;
176
+ if (body !== void 0 && typeof body !== "string" && !(body instanceof Uint8Array)) {
177
+ throw new Error(
178
+ "this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send."
179
+ );
180
+ }
181
+ Object.assign(
182
+ headersObj,
183
+ await this.transport.authorizeRequest({
184
+ method,
185
+ path: new URL(url).pathname,
186
+ // Narrowed by the guard above; `BodyInit` is wider than what can be
187
+ // signed.
188
+ body
189
+ })
190
+ );
191
+ }
173
192
  const requestInit = {
174
- method: init?.method || "GET",
193
+ method,
175
194
  headers: headersObj
176
195
  };
177
196
  const isStreamBody = init?.body instanceof ReadableStream || typeof init?.body === "object" && init?.body !== null && "getReader" in init.body && !(init.body instanceof Blob);
@@ -931,6 +950,50 @@ async function redeemInvitation(parsed, redeemer) {
931
950
  }
932
951
 
933
952
  // src/admin-api/admin-client.ts
953
+ var WarrantNonceRouteUnavailableError = class extends Error {
954
+ constructor(path, cause) {
955
+ super(
956
+ `this node does not serve warrant-nonce discovery (404 on ${path}); it predates the route, so a client must fall back to its own nonce counter`
957
+ );
958
+ this.path = path;
959
+ this.cause = cause;
960
+ this.name = "WarrantNonceRouteUnavailableError";
961
+ }
962
+ };
963
+ function u64FromBody(body, parsed, field) {
964
+ const value = parsed[field];
965
+ if (value === void 0 || value === null) return void 0;
966
+ const digits = new RegExp(`"${field}"\\s*:\\s*(\\d+)`).exec(body);
967
+ if (digits) return BigInt(digits[1]);
968
+ if (typeof value === "string" && /^\d+$/.test(value)) return BigInt(value);
969
+ throw new Error(`warrant-nonce response field \`${field}\` is not a u64: ${JSON.stringify(value)}`);
970
+ }
971
+ function parseWarrantNonce(body) {
972
+ const parsed = JSON.parse(body);
973
+ const data = parsed?.data;
974
+ if (!data || typeof data !== "object") {
975
+ throw new Error(`warrant-nonce response had no \`data\`: ${body.slice(0, 200)}`);
976
+ }
977
+ const common = {
978
+ contextId: String(data.contextId ?? ""),
979
+ authorDeviceKey: String(data.authorDeviceKey ?? ""),
980
+ seen: data.seen === true,
981
+ highWaterNonce: u64FromBody(body, data, "highWaterNonce"),
982
+ // Not defaulted: a node that stopped sending it is a node whose window this
983
+ // client would be guessing at, and the window is not a nonce input anyway.
984
+ windowWidth: u64FromBody(body, data, "windowWidth") ?? 0n
985
+ };
986
+ const nextNonce = u64FromBody(body, data, "nextNonce");
987
+ if (nextNonce === void 0) {
988
+ return {
989
+ ...common,
990
+ kind: "exhausted",
991
+ seen: true,
992
+ highWaterNonce: common.highWaterNonce ?? 0xffffffffffffffffn
993
+ };
994
+ }
995
+ return { ...common, kind: "open", nextNonce };
996
+ }
934
997
  function unwrap(response) {
935
998
  return response?.data;
936
999
  }
@@ -1731,6 +1794,13 @@ var AdminApiClient = class {
1731
1794
  * `namespaceId` names where to publish from, not the extent of the revocation:
1732
1795
  * a device belongs to the account, so every namespace holding a binding for it
1733
1796
  * is withdrawn from and reported back.
1797
+ *
1798
+ * **Revocation is forward-only.** It withdraws the device's authority from
1799
+ * here on and does NOT retract past authorship: ops the device already signed
1800
+ * keep verifying and stay in the DAG, because the certificate that authorised
1801
+ * them was valid when the signature was made. Nothing in this system can
1802
+ * un-author what a device wrote, so a UI built on this call must not offer
1803
+ * that - "this device can no longer act" is the only claim it supports.
1734
1804
  */
1735
1805
  async revokeAccountDevice(namespaceId, request) {
1736
1806
  return unwrap(
@@ -1740,6 +1810,29 @@ var AdminApiClient = class {
1740
1810
  )
1741
1811
  );
1742
1812
  }
1813
+ /**
1814
+ * Carry the device link of an account **this node does not hold**, so the
1815
+ * namespace binds that device's key to the account.
1816
+ *
1817
+ * The relay half of a nodeless account minting invitations. An account added
1818
+ * to a group by account holds its grants but has no device bound, so peers
1819
+ * refuse whatever its device signs as "bound to no account". The credential
1820
+ * and scope are root-signed and self-certifying; this node adds its own
1821
+ * member endorsement and publishes the `AccountDeviceLinked`. After that the
1822
+ * device signs invitations itself — see `signGroupInvitation`.
1823
+ *
1824
+ * Refusals: `400` when a proof does not verify or the scope does not reach
1825
+ * this namespace (re-sign it), `403` when the device was revoked here or the
1826
+ * account is a member of nothing in the namespace (add it first).
1827
+ */
1828
+ async linkAccountDevice(namespaceId, request) {
1829
+ return unwrap(
1830
+ await this.httpClient.post(
1831
+ `/admin-api/namespaces/${namespaceId}/account/link-device`,
1832
+ request
1833
+ )
1834
+ );
1835
+ }
1743
1836
  // ---- Group Management ----
1744
1837
  async getGroupInfo(groupId) {
1745
1838
  return unwrap(await this.httpClient.get(`/admin-api/groups/${groupId}`));
@@ -1773,6 +1866,138 @@ var AdminApiClient = class {
1773
1866
  }
1774
1867
  return response;
1775
1868
  }
1869
+ /**
1870
+ * Account -> devices for the members of a group, as its live bindings record
1871
+ * them.
1872
+ *
1873
+ * The join between a group member listing, which names accounts, and a
1874
+ * context's identities, which name bare signing keys - both 64 hex, and
1875
+ * nothing but the source tells them apart. Batch rather than per-account
1876
+ * because the key -> account direction gets asked about arbitrary authors,
1877
+ * which a per-account route would answer in N calls.
1878
+ *
1879
+ * What comes back is **caller-scoped by the node**: an admin of the group sees
1880
+ * every member's devices, a plain member only its own entry. A single-entry
1881
+ * answer is therefore a statement about this caller's role, not about the
1882
+ * group's size.
1883
+ *
1884
+ * Only live bindings appear, so a revoked device is absent here - use
1885
+ * {@link listAccountDevices} for the account's own devices, which keeps a
1886
+ * revoked one with `revoked: true`. Absence here never means the device never
1887
+ * acted: revocation is forward-only and its past ops remain in the DAG.
1888
+ *
1889
+ * Wrapped in `members` on the wire rather than `data`, unwrapped here for the
1890
+ * same reason {@link listAccountDevices} unwraps `devices`.
1891
+ */
1892
+ async listGroupMemberDevices(groupId, options) {
1893
+ const params = new URLSearchParams();
1894
+ if (options?.offset !== void 0) params.set("offset", String(options.offset));
1895
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
1896
+ const query = params.toString();
1897
+ const base = `/admin-api/groups/${encodeURIComponent(groupId)}/member-devices`;
1898
+ const response = await this.httpClient.get(
1899
+ query ? `${base}?${query}` : base
1900
+ );
1901
+ return response.members;
1902
+ }
1903
+ /**
1904
+ * Where `authorDeviceKey` stands in its warrant-nonce sequence in `contextId`.
1905
+ *
1906
+ * # What this is for
1907
+ *
1908
+ * The nonce is the one input to a warrant that is stateful on the *client*.
1909
+ * Everything else an author needs it either holds (its keys, the method, the
1910
+ * args) or can read from the relay ({@link RelayClient.describe} gives the
1911
+ * executor account and the grant). So an author that has lost its counter —
1912
+ * a browser keyholder in partitioned or periodically cleared storage, which
1913
+ * is its normal lifecycle rather than a fault — otherwise has exactly one
1914
+ * strategy: guess upward and burn a refused round trip per wrong guess, with
1915
+ * each refusal indistinguishable at the API from a genuinely spent nonce.
1916
+ *
1917
+ * Read {@link WarrantNonceOpen.nextNonce} and mint there. If you still hold
1918
+ * your own counter, mint at `max(ownNext, nextNonce)`: nonce state folds per
1919
+ * peer, so a node can only be BEHIND a client whose warrants it has not
1920
+ * applied — never ahead of the truth. An author spread across several relays
1921
+ * asks each and takes the highest answer. {@link createRecoveringNonceSource}
1922
+ * does all of that.
1923
+ *
1924
+ * Purely a read. It spends nothing and advances nothing, so it may be called
1925
+ * as often as you like.
1926
+ *
1927
+ * # Forward compatibility — this route is NEW
1928
+ *
1929
+ * It is not on core `master` yet, so a current node answers **404**, which
1930
+ * this method surfaces as {@link WarrantNonceRouteUnavailableError} rather
1931
+ * than as an opaque {@link HTTPError}. That distinction matters because the
1932
+ * handler itself never 404s: a device with no row is a `200` with
1933
+ * `seen: false`, and a malformed id is a `400`. So a 404 here means the node
1934
+ * does not serve the route at all — an older build, or a deployment that has
1935
+ * not re-mounted it — and the answer is to fall back to a local counter, not
1936
+ * to retry.
1937
+ *
1938
+ * # Authentication
1939
+ *
1940
+ * On the PROTECTED admin router, unlike the two delegated-execution routes it
1941
+ * sits beside: it takes another principal's device key as input and reports
1942
+ * that principal's activity. A `--public-intents` deployment does not serve
1943
+ * this anonymously, so an admin credential is required.
1944
+ *
1945
+ * @param authorDeviceKey the device's signing key, base58 (43-44 chars) or
1946
+ * hex (exactly 64). The node accepts either; the two never collide.
1947
+ */
1948
+ async getWarrantNonce(contextId, authorDeviceKey) {
1949
+ const path = `/admin-api/contexts/${encodeURIComponent(contextId)}/warrant-nonce/${encodeURIComponent(authorDeviceKey)}`;
1950
+ let raw;
1951
+ try {
1952
+ raw = await this.httpClient.get(path, { parse: "text" });
1953
+ } catch (error) {
1954
+ if (error instanceof HTTPError && error.status === 404) {
1955
+ throw new WarrantNonceRouteUnavailableError(path, error);
1956
+ }
1957
+ throw error;
1958
+ }
1959
+ return parseWarrantNonce(raw);
1960
+ }
1961
+ /**
1962
+ * The same answer, asked for the way a delegated client has to ask.
1963
+ *
1964
+ * {@link getWarrantNonce} is on the protected admin router, so a keyholder
1965
+ * writing through a relay — the client this whole facility exists for — is
1966
+ * refused it: measured `403` for a session carrying exactly
1967
+ * `context:intent`, `context:query`, `context:subscribe`. That client has no
1968
+ * admin credential and cannot be given one without defeating the point of the
1969
+ * delegated surface.
1970
+ *
1971
+ * What it does have is the credential proving the device is its own, which it
1972
+ * already sends on every write. Presenting it here makes the request
1973
+ * self-scoped: you learn a device's position only by proving, at call time,
1974
+ * that the device is yours. So there is no oracle to protect against, and no
1975
+ * reason for an admin gate.
1976
+ *
1977
+ * The device key is NOT a parameter. It is read from the verified
1978
+ * certificate server-side, which is the only reading that cannot disagree
1979
+ * with the signature — a key supplied alongside would be a second spelling of
1980
+ * the same fact, and two spellings can differ.
1981
+ *
1982
+ * Returns the identical shape {@link getWarrantNonce} returns, so a caller can
1983
+ * swap one for the other without touching what it does with the answer.
1984
+ *
1985
+ * @param authorProof hex-encoded borsh `AccountProof<DeviceCert>` — the same
1986
+ * value passed as `authorProof` to the relay client.
1987
+ */
1988
+ async getWarrantNonceAsAuthor(contextId, authorProof) {
1989
+ const path = `/admin-api/contexts/${encodeURIComponent(contextId)}/warrant-nonce`;
1990
+ let raw;
1991
+ try {
1992
+ raw = await this.httpClient.post(path, { authorProof }, { parse: "text" });
1993
+ } catch (error) {
1994
+ if (error instanceof HTTPError && error.status === 404) {
1995
+ throw new WarrantNonceRouteUnavailableError(path, error);
1996
+ }
1997
+ throw error;
1998
+ }
1999
+ return parseWarrantNonce(raw);
2000
+ }
1776
2001
  /**
1777
2002
  * Member accounts in the group and the devices bound to each. An admin node
1778
2003
  * sees every account; a plain member only its own. `403` if this node is not a
@@ -2283,6 +2508,16 @@ async function importSigningKey(secretHex) {
2283
2508
  );
2284
2509
  }
2285
2510
  }
2511
+ async function verifySignature(publicKey, signature, payload) {
2512
+ const key = await crypto.subtle.importKey(
2513
+ "raw",
2514
+ fromHex(publicKey, "publicKey", 32),
2515
+ { name: "Ed25519" },
2516
+ false,
2517
+ ["verify"]
2518
+ );
2519
+ return crypto.subtle.verify({ name: "Ed25519" }, key, signature, payload);
2520
+ }
2286
2521
  async function derivePublicKey(secretHex) {
2287
2522
  const seed = fromHex(secretHex, "deviceSecret", 32);
2288
2523
  const pkcs8 = concat(PKCS8_ED25519_PREFIX, seed);
@@ -2406,6 +2641,15 @@ async function jsonRpcCall(httpClient, method, params) {
2406
2641
  }
2407
2642
  var RpcClient = class {
2408
2643
  constructor(opts) {
2644
+ /**
2645
+ * Which write path this is. Present so `RpcClient` satisfies
2646
+ * `ExecuteTransport` as-is — the transport abstraction adopted *this* class's
2647
+ * `execute` shape as the canonical one, so the node side is the interface
2648
+ * rather than an adapter onto it.
2649
+ */
2650
+ this.kind = "node";
2651
+ /** A node serves `/sse` and `/ws` to the credential it issued. */
2652
+ this.canSubscribe = true;
2409
2653
  this.httpClient = opts.httpClient;
2410
2654
  }
2411
2655
  async execute(params) {
@@ -2419,6 +2663,17 @@ var RpcClient = class {
2419
2663
  }
2420
2664
  return result;
2421
2665
  }
2666
+ /**
2667
+ * The same call, in the shape the transport abstraction shares with the
2668
+ * relay.
2669
+ *
2670
+ * `rootHash` is left absent rather than synthesized: JSON-RPC `execute` does
2671
+ * not report the context's scope root, and inventing a value — or a `''` —
2672
+ * would make "the node does not tell us" indistinguishable from an answer.
2673
+ */
2674
+ async executeWithMetadata(params) {
2675
+ return { returns: await this.execute(params), transport: "node" };
2676
+ }
2422
2677
  /**
2423
2678
  * One-tap owner-driven convert: re-signs the caller's identity-gated entries
2424
2679
  * to the current schema. The export converts all of the caller's
@@ -2464,7 +2719,14 @@ var SseClient = class {
2464
2719
  this.closed = false;
2465
2720
  this.listeners = { connect: [], event: [], error: [] };
2466
2721
  this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
2467
- this.getAuthToken = opts.getAuthToken;
2722
+ if (opts.authorize) {
2723
+ this.authorize = opts.authorize;
2724
+ } else if (opts.getAuthToken) {
2725
+ const getAuthToken = opts.getAuthToken;
2726
+ this.authorize = async () => ({ Authorization: `Bearer ${await getAuthToken()}` });
2727
+ } else {
2728
+ throw new Error("SseClient needs either `getAuthToken` or `authorize`");
2729
+ }
2468
2730
  this.reconnectDelayMs = opts.reconnectDelayMs ?? 3e3;
2469
2731
  this.fetchImpl = (url, init) => opts.fetch ? opts.fetch(url, init) : globalThis.fetch(url, init);
2470
2732
  }
@@ -2531,11 +2793,10 @@ var SseClient = class {
2531
2793
  this.closed = false;
2532
2794
  this.abortController = new AbortController();
2533
2795
  try {
2534
- const token = await this.getAuthToken();
2535
2796
  const url = `${this.baseUrl}/sse`;
2536
2797
  const response = await this.fetchImpl(url, {
2537
2798
  headers: {
2538
- "Authorization": `Bearer ${token}`,
2799
+ ...await this.authorize({ method: "GET", path: new URL(url).pathname }),
2539
2800
  "Accept": "text/event-stream"
2540
2801
  },
2541
2802
  signal: this.abortController.signal
@@ -2688,21 +2949,18 @@ var SseClient = class {
2688
2949
  }
2689
2950
  async sendSubscription(method, ids) {
2690
2951
  try {
2691
- const token = await this.getAuthToken();
2692
2952
  const params = {};
2693
2953
  if (ids.contextIds && ids.contextIds.length > 0) params.contextIds = ids.contextIds;
2694
2954
  if (ids.groupIds && ids.groupIds.length > 0) params.groupIds = ids.groupIds;
2695
- const response = await this.fetchImpl(`${this.baseUrl}/sse/subscription`, {
2955
+ const url = `${this.baseUrl}/sse/subscription`;
2956
+ const body = JSON.stringify({ id: this.sessionId, method, params });
2957
+ const response = await this.fetchImpl(url, {
2696
2958
  method: "POST",
2697
2959
  headers: {
2698
- "Authorization": `Bearer ${token}`,
2960
+ ...await this.authorize({ method: "POST", path: new URL(url).pathname, body }),
2699
2961
  "Content-Type": "application/json"
2700
2962
  },
2701
- body: JSON.stringify({
2702
- id: this.sessionId,
2703
- method,
2704
- params
2705
- })
2963
+ body
2706
2964
  });
2707
2965
  if (!response.ok) {
2708
2966
  const terminal = isTerminalAuthFailure(response);
@@ -3021,11 +3279,123 @@ var EphemeralClient = class {
3021
3279
  }
3022
3280
  };
3023
3281
 
3282
+ // src/signer/signer.ts
3283
+ var PKCS8_ED25519_PREFIX2 = new Uint8Array([
3284
+ 48,
3285
+ 46,
3286
+ 2,
3287
+ 1,
3288
+ 0,
3289
+ 48,
3290
+ 5,
3291
+ 6,
3292
+ 3,
3293
+ 43,
3294
+ 101,
3295
+ 112,
3296
+ 4,
3297
+ 34,
3298
+ 4,
3299
+ 32
3300
+ ]);
3301
+ function unsupported(cause) {
3302
+ const detail = cause instanceof Error ? `: ${cause.message}` : "";
3303
+ return new Error(
3304
+ "this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it" + detail
3305
+ );
3306
+ }
3307
+ async function signerFromSecret(secret, label2 = "secret") {
3308
+ const seed = fromHex(secret, label2, 32);
3309
+ const pkcs8 = concat(PKCS8_ED25519_PREFIX2, seed);
3310
+ let privateKey;
3311
+ let publicKey;
3312
+ try {
3313
+ const exportable = await crypto.subtle.importKey(
3314
+ "pkcs8",
3315
+ pkcs8,
3316
+ { name: "Ed25519" },
3317
+ true,
3318
+ ["sign"]
3319
+ );
3320
+ const jwk = await crypto.subtle.exportKey("jwk", exportable);
3321
+ publicKey = hex(
3322
+ Uint8Array.from(
3323
+ atob(jwk.x.replace(/-/g, "+").replace(/_/g, "/")),
3324
+ (c) => c.charCodeAt(0)
3325
+ )
3326
+ );
3327
+ privateKey = await crypto.subtle.importKey(
3328
+ "pkcs8",
3329
+ pkcs8,
3330
+ { name: "Ed25519" },
3331
+ false,
3332
+ ["sign"]
3333
+ );
3334
+ } catch (cause) {
3335
+ throw unsupported(cause);
3336
+ }
3337
+ return fromKeyAndPublic(privateKey, publicKey);
3338
+ }
3339
+ async function signerFromCryptoKey(privateKey, publicKey) {
3340
+ if (privateKey.type !== "private") {
3341
+ throw new Error(
3342
+ `signerFromCryptoKey needs the private half of the pair, got a ${privateKey.type} key`
3343
+ );
3344
+ }
3345
+ if (!privateKey.usages.includes("sign")) {
3346
+ throw new Error(
3347
+ "this CryptoKey cannot sign: generate it with usages ['sign', 'verify']"
3348
+ );
3349
+ }
3350
+ let publicHex;
3351
+ if (typeof publicKey === "string") {
3352
+ fromHex(publicKey, "publicKey", 32);
3353
+ publicHex = publicKey.trim().toLowerCase();
3354
+ } else {
3355
+ try {
3356
+ publicHex = hex(
3357
+ new Uint8Array(await crypto.subtle.exportKey("raw", publicKey))
3358
+ );
3359
+ } catch (cause) {
3360
+ const detail = cause instanceof Error ? `: ${cause.message}` : "";
3361
+ throw new Error(
3362
+ "could not read the public half of this key pair; pass the public key as 64 hex instead" + detail
3363
+ );
3364
+ }
3365
+ }
3366
+ return fromKeyAndPublic(privateKey, publicHex);
3367
+ }
3368
+ function fromKeyAndPublic(privateKey, publicKey) {
3369
+ return {
3370
+ publicKey,
3371
+ async sign(payload) {
3372
+ try {
3373
+ return new Uint8Array(
3374
+ await crypto.subtle.sign({ name: "Ed25519" }, privateKey, payload)
3375
+ );
3376
+ } catch (cause) {
3377
+ throw unsupported(cause);
3378
+ }
3379
+ }
3380
+ };
3381
+ }
3382
+ async function resolveSigner(secret, signer, label2) {
3383
+ if (signer && secret !== void 0) {
3384
+ throw new Error(
3385
+ `pass either ${label2} or signer, not both \u2014 they may name different keys`
3386
+ );
3387
+ }
3388
+ if (signer) return signer;
3389
+ if (secret !== void 0) return signerFromSecret(secret, label2);
3390
+ throw new Error(`${label2} or signer is required`);
3391
+ }
3392
+
3024
3393
  // src/device-cert/device-cert.ts
3025
3394
  var CERT_DOMAIN = new TextEncoder().encode("calimero.device.cert.v1");
3026
3395
  var ACCOUNT_ID_DOMAIN = new TextEncoder().encode("calimero.account.genesis.v1");
3027
3396
  var DEVICE_ID_DOMAIN = new TextEncoder().encode("calimero.device.id.v1");
3028
3397
  var ACCOUNT_GENESIS_VERSION = 2;
3398
+ var ACCOUNT_PROOF_BYTES = 237;
3029
3399
  async function mintDeviceId(account, nonce2) {
3030
3400
  if (nonce2.length !== 16) {
3031
3401
  throw new Error(`nonce must be 16 bytes, got ${nonce2.length}`);
@@ -3058,12 +3428,9 @@ function accountProofBytes(input) {
3058
3428
  );
3059
3429
  }
3060
3430
  async function signDeviceCert(input) {
3061
- const rootPublicKey = await derivePublicKey(input.rootSecret);
3062
- const account = hex(
3063
- await domainHash(ACCOUNT_ID_DOMAIN, [
3064
- concat(new Uint8Array([ACCOUNT_GENESIS_VERSION]), rootPublicKey)
3065
- ])
3066
- );
3431
+ const signer = await resolveSigner(input.rootSecret, input.signer, "rootSecret");
3432
+ const rootPublicKey = fromHex(signer.publicKey, "signer.publicKey", 32);
3433
+ const account = await accountForRootPublicKey(signer.publicKey);
3067
3434
  const keyEpoch = 0;
3068
3435
  const payload = await deviceCertPayload({
3069
3436
  account,
@@ -3073,10 +3440,7 @@ async function signDeviceCert(input) {
3073
3440
  keyEpoch,
3074
3441
  deviceEpoch: input.deviceEpoch
3075
3442
  });
3076
- const key = await importSigningKey(input.rootSecret);
3077
- const signature = new Uint8Array(
3078
- await crypto.subtle.sign("Ed25519", key, payload)
3079
- );
3443
+ const signature = await signer.sign(payload);
3080
3444
  const credential = accountProofBytes({
3081
3445
  rootPublicKey,
3082
3446
  account,
@@ -3089,15 +3453,119 @@ async function signDeviceCert(input) {
3089
3453
  });
3090
3454
  return hex(credential);
3091
3455
  }
3456
+ function parseDeviceCredential(credential) {
3457
+ const bytes = fromHex(
3458
+ credential,
3459
+ "credential",
3460
+ // Fixed-width with an empty chain: 1 + 32 + 4 + 32*4 + 4 + 4 + 64.
3461
+ ACCOUNT_PROOF_BYTES
3462
+ );
3463
+ if (bytes[0] !== ACCOUNT_GENESIS_VERSION) {
3464
+ throw new Error(
3465
+ `this credential has account genesis version ${bytes[0]}, not ${ACCOUNT_GENESIS_VERSION} \u2014 it names a different account than its root key derives here, and core would refuse it`
3466
+ );
3467
+ }
3468
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
3469
+ const chainLength = view.getUint32(33, true);
3470
+ if (chainLength !== 0) {
3471
+ throw new Error(
3472
+ `this credential carries a ${chainLength}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`
3473
+ );
3474
+ }
3475
+ const at = (offset, length) => hex(bytes.subarray(offset, offset + length));
3476
+ return {
3477
+ rootPublicKey: at(1, 32),
3478
+ account: at(37, 32),
3479
+ device: at(69, 32),
3480
+ signPublicKey: at(101, 32),
3481
+ kemPublicKey: at(133, 32),
3482
+ keyEpoch: view.getUint32(165, true),
3483
+ deviceEpoch: view.getUint32(169, true),
3484
+ signature: at(173, 64)
3485
+ };
3486
+ }
3487
+ async function verifyDeviceCredential(credential) {
3488
+ const parsed = parseDeviceCredential(credential);
3489
+ const derived = await accountForRootPublicKey(parsed.rootPublicKey);
3490
+ if (derived !== parsed.account) {
3491
+ throw new Error(
3492
+ `this credential names account ${parsed.account}, but its root key derives ${derived} \u2014 the certificate was re-pointed at another account`
3493
+ );
3494
+ }
3495
+ const signed = await verifySignature(
3496
+ parsed.rootPublicKey,
3497
+ fromHex(parsed.signature, "signature", 64),
3498
+ await deviceCertPayload(parsed)
3499
+ );
3500
+ if (!signed) {
3501
+ throw new Error(
3502
+ `the root key of account ${parsed.account} did not sign this certificate`
3503
+ );
3504
+ }
3505
+ return parsed;
3506
+ }
3092
3507
  async function accountForRoot(rootSecret) {
3093
- const rootPublicKey = await derivePublicKey(rootSecret);
3508
+ return accountForRootPublicKey(hex(await derivePublicKey(rootSecret)));
3509
+ }
3510
+ async function accountForRootPublicKey(rootPublicKey) {
3094
3511
  return hex(
3095
3512
  await domainHash(ACCOUNT_ID_DOMAIN, [
3096
- concat(new Uint8Array([ACCOUNT_GENESIS_VERSION]), rootPublicKey)
3513
+ concat(
3514
+ new Uint8Array([ACCOUNT_GENESIS_VERSION]),
3515
+ fromHex(rootPublicKey, "rootPublicKey", 32)
3516
+ )
3097
3517
  ])
3098
3518
  );
3099
3519
  }
3100
3520
 
3521
+ // src/device-cert/device-scope.ts
3522
+ var SCOPE_DOMAIN = new TextEncoder().encode("calimero.device.scope.v1");
3523
+ async function deviceScopePayload(input) {
3524
+ return domainHash(SCOPE_DOMAIN, [
3525
+ fromHex(input.account, "account", 32),
3526
+ fromHex(input.device, "device", 32),
3527
+ u32le(input.scopeEpoch),
3528
+ u32le(input.keyEpoch),
3529
+ ...input.applications.map((a, i) => fromHex(a, `applications[${i}]`, 32))
3530
+ ]);
3531
+ }
3532
+ async function signDeviceScope(input) {
3533
+ const signer = await resolveSigner(input.rootSecret, input.signer, "rootSecret");
3534
+ const rootPublicKey = fromHex(signer.publicKey, "signer.publicKey", 32);
3535
+ const account = await accountForRootPublicKey(hex(rootPublicKey));
3536
+ const applications = input.applications ?? [];
3537
+ const scopeEpoch = input.scopeEpoch ?? 0;
3538
+ if (!Number.isInteger(scopeEpoch) || scopeEpoch < 0 || scopeEpoch > 4294967295) {
3539
+ throw new Error(`scopeEpoch must be a u32, got ${scopeEpoch}`);
3540
+ }
3541
+ const keyEpoch = 0;
3542
+ const payload = await deviceScopePayload({
3543
+ account,
3544
+ device: input.device,
3545
+ applications,
3546
+ scopeEpoch,
3547
+ keyEpoch
3548
+ });
3549
+ const signature = await signer.sign(payload);
3550
+ if (signature.length !== 64) {
3551
+ throw new Error(`signer returned ${signature.length} bytes, expected a 64-byte Ed25519 signature`);
3552
+ }
3553
+ return hex(
3554
+ concat(
3555
+ new Uint8Array([ACCOUNT_GENESIS_VERSION]),
3556
+ rootPublicKey,
3557
+ u32le(0),
3558
+ fromHex(account, "account", 32),
3559
+ fromHex(input.device, "device", 32),
3560
+ u32le(applications.length),
3561
+ ...applications.map((a, i) => fromHex(a, `applications[${i}]`, 32)),
3562
+ u32le(scopeEpoch),
3563
+ u32le(keyEpoch),
3564
+ signature
3565
+ )
3566
+ );
3567
+ }
3568
+
3101
3569
  // src/account/wordlist.ts
3102
3570
  var ENGLISH_WORDLIST = [
3103
3571
  "abandon",
@@ -5176,27 +5644,50 @@ async function accountRootFromSecret(secret) {
5176
5644
  accountId: await accountForRoot(secret)
5177
5645
  };
5178
5646
  }
5647
+ async function createAccountRootSigner() {
5648
+ const entropy = crypto.getRandomValues(new Uint8Array(ENTROPY_BITS / 8));
5649
+ const phrase = await encodePhrase(entropy);
5650
+ return { ...await rootSignerFromEntropy(entropy), phrase };
5651
+ }
5652
+ async function accountRootSignerFromPhrase(phrase) {
5653
+ return rootSignerFromEntropy(await decodePhrase(normalisePhrase(phrase)));
5654
+ }
5655
+ async function rootSignerFromEntropy(entropy) {
5656
+ const signer = await signerFromSecret(hex(entropy), "rootSecret");
5657
+ entropy.fill(0);
5658
+ return {
5659
+ publicKey: signer.publicKey,
5660
+ accountId: await accountForRootPublicKey(signer.publicKey),
5661
+ signer
5662
+ };
5663
+ }
5664
+ async function resolveRoot(source) {
5665
+ const signer = typeof source === "string" ? await signerFromSecret(source, "rootSecret") : source;
5666
+ return identify(signer);
5667
+ }
5668
+ async function resolveRootPair(rootSecret, signer) {
5669
+ return identify(await resolveSigner(rootSecret, signer, "rootSecret"));
5670
+ }
5671
+ async function identify(signer) {
5672
+ return {
5673
+ signer,
5674
+ publicKey: signer.publicKey,
5675
+ accountId: await accountForRootPublicKey(signer.publicKey)
5676
+ };
5677
+ }
5179
5678
  async function signAccountLink(input) {
5180
5679
  if (!input.nonce) throw new Error("nonce is required to sign an account link");
5181
- const key = await importSigningKey(input.rootSecret);
5182
- const signature = new Uint8Array(
5183
- await crypto.subtle.sign(
5184
- "Ed25519",
5185
- key,
5186
- concat(ACCOUNT_LINK_DOMAIN, new TextEncoder().encode(input.nonce))
5187
- )
5680
+ const signer = await resolveSigner(input.rootSecret, input.signer, "rootSecret");
5681
+ const signature = await signer.sign(
5682
+ concat(ACCOUNT_LINK_DOMAIN, new TextEncoder().encode(input.nonce))
5188
5683
  );
5189
5684
  return base64(signature);
5190
5685
  }
5191
5686
  async function signAccountLogin(input) {
5192
5687
  if (!input.nonce) throw new Error("nonce is required to sign an account login");
5193
- const key = await importSigningKey(input.rootSecret);
5194
- const signature = new Uint8Array(
5195
- await crypto.subtle.sign(
5196
- "Ed25519",
5197
- key,
5198
- concat(ACCOUNT_LOGIN_DOMAIN, new TextEncoder().encode(input.nonce))
5199
- )
5688
+ const signer = await resolveSigner(input.rootSecret, input.signer, "rootSecret");
5689
+ const signature = await signer.sign(
5690
+ concat(ACCOUNT_LOGIN_DOMAIN, new TextEncoder().encode(input.nonce))
5200
5691
  );
5201
5692
  return base64(signature);
5202
5693
  }
@@ -5290,7 +5781,7 @@ function base642(bytes) {
5290
5781
  }
5291
5782
 
5292
5783
  // src/cloud/cloud-client.ts
5293
- var DEFAULT_CLOUD_BASE_URL = "https://cloud.calimero.network";
5784
+ var DEFAULT_CLOUD_BASE_URL = "https://manager.cloud.calimero.network";
5294
5785
  function canExecuteOf(row, legacy) {
5295
5786
  return typeof row.can_execute === "boolean" ? row.can_execute : legacy;
5296
5787
  }
@@ -5354,8 +5845,10 @@ var CloudClient = class {
5354
5845
  * account behind those reads was claimed by its owner. The claim is recorded
5355
5846
  * even when the session is refused.
5356
5847
  *
5357
- * @param rootSecret the account root's signing secret, 64 hex. It never
5358
- * leaves this process — only a signature over the cloud's nonce travels.
5848
+ * @param root the account root: its 64-hex secret, or a `Signer` over a root
5849
+ * this process may use and cannot read — the form a phrase-held root in a
5850
+ * browser takes. Either way nothing but a signature over the cloud's nonce
5851
+ * travels.
5359
5852
  *
5360
5853
  * A `403` means either the signature did not verify, or the account is not
5361
5854
  * linked to a cloud login: ownership alone says who you are, and the link
@@ -5363,13 +5856,13 @@ var CloudClient = class {
5363
5856
  * on the proof alone would authenticate perfectly and authorize nothing. The
5364
5857
  * ownership claim is recorded either way, so linking later needs no re-proof.
5365
5858
  */
5366
- async signInWithAccount(rootSecret) {
5367
- const root = await accountRootFromSecret(rootSecret);
5859
+ async signInWithAccount(root) {
5860
+ const { signer, publicKey } = await resolveRoot(root);
5368
5861
  const { nonce: nonce2 } = await this.getAccountLoginChallenge();
5369
5862
  return this.submitAccountLogin({
5370
- rootPublicKey: root.publicKey,
5863
+ rootPublicKey: publicKey,
5371
5864
  nonce: nonce2,
5372
- signature: await signAccountLogin({ rootSecret, nonce: nonce2 })
5865
+ signature: await signAccountLogin({ signer, nonce: nonce2 })
5373
5866
  });
5374
5867
  }
5375
5868
  /**
@@ -5466,6 +5959,7 @@ var CloudClient = class {
5466
5959
  peerId: String(row.peer_id ?? ""),
5467
5960
  relayUrl,
5468
5961
  executorAccount,
5962
+ nodeKey: row.node_key ?? row.node_public_key ?? null,
5469
5963
  status: String(row.status ?? ""),
5470
5964
  authorshipReady,
5471
5965
  teeRole: teeRoleOf(row),
@@ -5808,22 +6302,23 @@ var CloudClient = class {
5808
6302
  * an intent; the cloud needs it to know whose plan a hosted node is spending,
5809
6303
  * and to sign that account back in later.
5810
6304
  *
5811
- * @param rootSecret the account root's signing secret, 64 hex — from
5812
- * {@link generateAccountRoot}, from a restored recovery phrase, or from a
5813
- * desktop app or hardware key that already holds one.
6305
+ * @param root the account root: its 64-hex secret — from
6306
+ * {@link generateAccountRoot}, a restored recovery phrase, or a desktop app
6307
+ * or hardware key that already holds one — or a `Signer` over a root this
6308
+ * process cannot read, which is what a phrase-held browser root is.
5814
6309
  *
5815
6310
  * Idempotent for the same login. An account already linked to a *different*
5816
6311
  * cloud login is a `409`; a replayed or expired challenge is a `403`; and
5817
6312
  * exceeding the plan's account limit is a `402`.
5818
6313
  */
5819
- async linkAccount(rootSecret) {
5820
- const root = await accountRootFromSecret(rootSecret);
6314
+ async linkAccount(root) {
6315
+ const { signer, publicKey, accountId } = await resolveRoot(root);
5821
6316
  const { nonce: nonce2 } = await this.getAccountLinkChallenge();
5822
6317
  return this.submitAccountLink({
5823
- accountId: root.accountId,
5824
- rootPublicKey: root.publicKey,
6318
+ accountId,
6319
+ rootPublicKey: publicKey,
5825
6320
  nonce: nonce2,
5826
- signature: await signAccountLink({ rootSecret, nonce: nonce2 })
6321
+ signature: await signAccountLink({ signer, nonce: nonce2 })
5827
6322
  });
5828
6323
  }
5829
6324
  /**
@@ -5943,16 +6438,19 @@ var CloudClient = class {
5943
6438
  * login; `402` that the plan is full.
5944
6439
  */
5945
6440
  async linkAccountWithGrant(options) {
5946
- const root = await accountRootFromSecret(options.rootSecret);
6441
+ const { signer, publicKey, accountId } = await resolveRootPair(
6442
+ options.rootSecret,
6443
+ options.signer
6444
+ );
5947
6445
  const body = await this.request(
5948
6446
  "POST",
5949
6447
  "/api/cloud/accounts/link",
5950
6448
  {
5951
6449
  body: {
5952
6450
  grant: options.grant,
5953
- root_public_key: root.publicKey,
6451
+ root_public_key: publicKey,
5954
6452
  signature: await signAccountLink({
5955
- rootSecret: options.rootSecret,
6453
+ signer,
5956
6454
  nonce: options.grant
5957
6455
  })
5958
6456
  },
@@ -5960,7 +6458,7 @@ var CloudClient = class {
5960
6458
  }
5961
6459
  );
5962
6460
  return {
5963
- accountId: String(body.account_id ?? root.accountId),
6461
+ accountId: String(body.account_id ?? accountId),
5964
6462
  linkedAt: body.linked_at ?? null,
5965
6463
  alreadyLinked: body.already_linked === true
5966
6464
  };
@@ -6484,117 +6982,6 @@ var LocalStorageTokenStore = class {
6484
6982
  }
6485
6983
  };
6486
6984
 
6487
- // src/signer/signer.ts
6488
- var PKCS8_ED25519_PREFIX2 = new Uint8Array([
6489
- 48,
6490
- 46,
6491
- 2,
6492
- 1,
6493
- 0,
6494
- 48,
6495
- 5,
6496
- 6,
6497
- 3,
6498
- 43,
6499
- 101,
6500
- 112,
6501
- 4,
6502
- 34,
6503
- 4,
6504
- 32
6505
- ]);
6506
- function unsupported(cause) {
6507
- const detail = cause instanceof Error ? `: ${cause.message}` : "";
6508
- return new Error(
6509
- "this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it" + detail
6510
- );
6511
- }
6512
- async function signerFromSecret(secret, label2 = "secret") {
6513
- const seed = fromHex(secret, label2, 32);
6514
- const pkcs8 = concat(PKCS8_ED25519_PREFIX2, seed);
6515
- let privateKey;
6516
- let publicKey;
6517
- try {
6518
- const exportable = await crypto.subtle.importKey(
6519
- "pkcs8",
6520
- pkcs8,
6521
- { name: "Ed25519" },
6522
- true,
6523
- ["sign"]
6524
- );
6525
- const jwk = await crypto.subtle.exportKey("jwk", exportable);
6526
- publicKey = hex(
6527
- Uint8Array.from(
6528
- atob(jwk.x.replace(/-/g, "+").replace(/_/g, "/")),
6529
- (c) => c.charCodeAt(0)
6530
- )
6531
- );
6532
- privateKey = await crypto.subtle.importKey(
6533
- "pkcs8",
6534
- pkcs8,
6535
- { name: "Ed25519" },
6536
- false,
6537
- ["sign"]
6538
- );
6539
- } catch (cause) {
6540
- throw unsupported(cause);
6541
- }
6542
- return fromKeyAndPublic(privateKey, publicKey);
6543
- }
6544
- async function signerFromCryptoKey(privateKey, publicKey) {
6545
- if (privateKey.type !== "private") {
6546
- throw new Error(
6547
- `signerFromCryptoKey needs the private half of the pair, got a ${privateKey.type} key`
6548
- );
6549
- }
6550
- if (!privateKey.usages.includes("sign")) {
6551
- throw new Error(
6552
- "this CryptoKey cannot sign: generate it with usages ['sign', 'verify']"
6553
- );
6554
- }
6555
- let publicHex;
6556
- if (typeof publicKey === "string") {
6557
- fromHex(publicKey, "publicKey", 32);
6558
- publicHex = publicKey.trim().toLowerCase();
6559
- } else {
6560
- try {
6561
- publicHex = hex(
6562
- new Uint8Array(await crypto.subtle.exportKey("raw", publicKey))
6563
- );
6564
- } catch (cause) {
6565
- const detail = cause instanceof Error ? `: ${cause.message}` : "";
6566
- throw new Error(
6567
- "could not read the public half of this key pair; pass the public key as 64 hex instead" + detail
6568
- );
6569
- }
6570
- }
6571
- return fromKeyAndPublic(privateKey, publicHex);
6572
- }
6573
- function fromKeyAndPublic(privateKey, publicKey) {
6574
- return {
6575
- publicKey,
6576
- async sign(payload) {
6577
- try {
6578
- return new Uint8Array(
6579
- await crypto.subtle.sign({ name: "Ed25519" }, privateKey, payload)
6580
- );
6581
- } catch (cause) {
6582
- throw unsupported(cause);
6583
- }
6584
- }
6585
- };
6586
- }
6587
- async function resolveSigner(secret, signer, label2) {
6588
- if (signer && secret !== void 0) {
6589
- throw new Error(
6590
- `pass either ${label2} or signer, not both \u2014 they may name different keys`
6591
- );
6592
- }
6593
- if (signer) return signer;
6594
- if (secret !== void 0) return signerFromSecret(secret, label2);
6595
- throw new Error(`${label2} or signer is required`);
6596
- }
6597
-
6598
6985
  // src/warrant/warrant.ts
6599
6986
  var SIGN_DOMAIN2 = new TextEncoder().encode("calimero.warrant.v2");
6600
6987
  var INTENT_DOMAIN = new TextEncoder().encode("calimero.warrant.intent.v1");
@@ -7099,6 +7486,16 @@ var IntentRefusedError = class extends Error {
7099
7486
  this.name = "IntentRefusedError";
7100
7487
  }
7101
7488
  };
7489
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7490
+ function retryAfterMs(headers) {
7491
+ const raw = headers?.get?.("Retry-After");
7492
+ if (!raw) return null;
7493
+ const seconds = Number.parseInt(raw, 10);
7494
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
7495
+ const at = Date.parse(raw);
7496
+ if (Number.isFinite(at)) return Math.max(0, at - Date.now());
7497
+ return null;
7498
+ }
7102
7499
  var RelayClient = class {
7103
7500
  constructor(config) {
7104
7501
  this.config = config;
@@ -7107,11 +7504,40 @@ var RelayClient = class {
7107
7504
  const injected = config.fetch;
7108
7505
  this.fetchImpl = injected ? (input, init) => injected(input, init) : (input, init) => globalThis.fetch(input, init);
7109
7506
  this.timeoutMs = config.timeoutMs ?? 1e4;
7507
+ this.rateLimitRetries = config.rateLimitRetries ?? 3;
7508
+ }
7509
+ /**
7510
+ * The relay's origin, trailing slash stripped.
7511
+ *
7512
+ * Exposed because a relay **is a node**: the same origin that answers the
7513
+ * intents routes also answers `/auth/challenge`, `/auth/token`, `/sse` and
7514
+ * `/ws`. Anything building an observing session over this relay needs the
7515
+ * URL, and asking the caller to pass it a second time is how the two drift.
7516
+ */
7517
+ get relayUrl() {
7518
+ return this.baseUrl;
7519
+ }
7520
+ /** The author's account, hex — whose consent every warrant here carries. */
7521
+ get authorAccount() {
7522
+ return this.config.authorAccount;
7523
+ }
7524
+ /**
7525
+ * The author's `AccountProof<DeviceCert>`, hex.
7526
+ *
7527
+ * The same credential `login()` wants, which is why it is readable: a caller
7528
+ * that already handed it to this client should not have to hand an identical
7529
+ * copy to the login as well, where the two could disagree.
7530
+ */
7531
+ get authorProof() {
7532
+ return this.config.authorProof;
7110
7533
  }
7111
7534
  /**
7112
- * The author device's signer, built from `deviceSecret` when that is what was
7113
- * configured. A {@link Signer} and never the secret, so no caller of a
7114
- * `RelayClient` gains the ability to read key material.
7535
+ * The author device's signer.
7536
+ *
7537
+ * A {@link Signer} and never the secret: this returns something that can
7538
+ * *sign*, so no caller of a `RelayClient` gains the ability to read a key
7539
+ * that was passed in as `deviceSecret`. That asymmetry is the point — the
7540
+ * login needs a signature, not key material.
7115
7541
  */
7116
7542
  async authorSigner() {
7117
7543
  return resolveSigner(this.config.deviceSecret, this.config.signer, "deviceSecret");
@@ -7390,7 +7816,37 @@ var RelayClient = class {
7390
7816
  this.executorAccount = answered;
7391
7817
  return answered;
7392
7818
  }
7819
+ /**
7820
+ * One request, waiting out a rate limit rather than failing the caller.
7821
+ *
7822
+ * The relay's ingress limits the delegated-execution routes to 20 requests a
7823
+ * second per source IP, burst 40 — tighter than everything else it serves,
7824
+ * because those two routes are the ones it answers to anonymous callers.
7825
+ *
7826
+ * Retrying a 429 is safe here in a way retrying most refusals is not: the
7827
+ * limiter sits *first* in the middleware chain, so a throttled request never
7828
+ * reached the node and its warrant nonce was never spent. The same bytes can
7829
+ * go again. Contrast the spent-nonce 403 below, which needs a fresh warrant.
7830
+ *
7831
+ * `Retry-After` is honoured when the ingress sends one; otherwise the wait
7832
+ * doubles from a little over the limiter's own window, which is the shortest
7833
+ * delay that can actually clear.
7834
+ */
7393
7835
  async json(method, path, body) {
7836
+ let wait = 250;
7837
+ for (let attempt = 0; ; attempt += 1) {
7838
+ try {
7839
+ return await this.jsonOnce(method, path, body);
7840
+ } catch (err) {
7841
+ const limited = err instanceof HTTPError && err.status === 429;
7842
+ if (!limited || attempt >= this.rateLimitRetries) throw err;
7843
+ const after = retryAfterMs(err.headers);
7844
+ await sleep(after ?? wait);
7845
+ wait *= 2;
7846
+ }
7847
+ }
7848
+ }
7849
+ async jsonOnce(method, path, body) {
7394
7850
  const headers = { Accept: "application/json" };
7395
7851
  if (body !== void 0) headers["Content-Type"] = "application/json";
7396
7852
  const controller = new AbortController();
@@ -7443,133 +7899,879 @@ function extractReason(bodyText) {
7443
7899
  return bodyText;
7444
7900
  }
7445
7901
 
7446
- // src/relay/nonce-source.ts
7447
- function createMemoryNonceSource(start = 1) {
7448
- let next = BigInt(start);
7449
- if (next < 1n) {
7450
- throw new Error("nonce sequence starts at 1");
7451
- }
7452
- return {
7453
- next() {
7454
- const value = next;
7455
- next += 1n;
7456
- return Promise.resolve(value);
7457
- }
7458
- };
7459
- }
7460
- function createLocalStorageNonceSource(key, storage) {
7461
- const store = storage ?? globalThis.localStorage;
7462
- if (!store) {
7463
- throw new Error(
7464
- "no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence"
7465
- );
7466
- }
7467
- return {
7468
- next() {
7469
- const raw = store.getItem(key);
7470
- let current = 0n;
7471
- if (raw !== null && raw !== "") {
7472
- try {
7473
- const parsed = BigInt(raw);
7474
- if (parsed > 0n) current = parsed;
7475
- } catch {
7476
- current = 0n;
7477
- }
7478
- }
7479
- const value = current + 1n;
7480
- store.setItem(key, value.toString());
7481
- return Promise.resolve(value);
7482
- }
7483
- };
7484
- }
7485
-
7486
- // src/sealed/noise.ts
7487
- var PROTOCOL_NAME = "Noise_NK_25519_AESGCM_SHA256";
7488
- var DH_LEN = 32;
7489
- var TAG_LEN = 16;
7490
- var PKCS8_X25519_PREFIX = new Uint8Array([
7491
- 48,
7492
- 46,
7493
- 2,
7494
- 1,
7495
- 0,
7496
- 48,
7497
- 5,
7498
- 6,
7499
- 3,
7500
- 43,
7501
- 101,
7502
- 110,
7503
- 4,
7504
- 34,
7505
- 4,
7506
- 32
7507
- ]);
7508
- var SymmetricState = class _SymmetricState {
7509
- constructor(h) {
7510
- this.k = null;
7511
- this.n = 0;
7512
- this.ck = h;
7513
- this.h = h;
7902
+ // src/transport/relay-transport.ts
7903
+ var RelayTransport = class {
7904
+ constructor(relay, observer = null) {
7905
+ this.relay = relay;
7906
+ this.observer = observer;
7907
+ this.kind = "relay";
7514
7908
  }
7515
- static async initialize() {
7516
- const name = new TextEncoder().encode(PROTOCOL_NAME);
7517
- const h = new Uint8Array(32);
7518
- h.set(name);
7519
- return new _SymmetricState(h);
7909
+ /**
7910
+ * Whether this relay can be observed — a fact, not a constant.
7911
+ *
7912
+ * A relay IS a node: it serves `/auth/challenge`, `/auth/token`, `/sse` and
7913
+ * `/ws`, and the `account_proof` provider grants `context:subscribe` by
7914
+ * default. What decides the answer is therefore not the transport but whether
7915
+ * a caller supplied the node's device signing key, which cannot be inferred
7916
+ * from the node or from its `peerId`. See `./relay-observer.ts`.
7917
+ */
7918
+ get canSubscribe() {
7919
+ return this.observer !== null;
7520
7920
  }
7521
- async mixHash(data) {
7522
- this.h = await sha256(concat(this.h, data));
7921
+ /** The event session, or `null` when no node key was supplied. */
7922
+ get events() {
7923
+ return this.observer;
7523
7924
  }
7524
- async mixKey(inputKeyMaterial) {
7525
- const [ck, key] = await hkdf2(this.ck, inputKeyMaterial);
7526
- this.ck = ck;
7527
- this.k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt", "decrypt"]);
7528
- this.n = 0;
7925
+ /** The underlying client, for `describe()` and anything else relay-specific. */
7926
+ get client() {
7927
+ return this.relay;
7529
7928
  }
7530
- async encryptAndHash(plaintext) {
7531
- if (!this.k) throw new Error("Noise: no cipher key yet");
7532
- const ciphertext = new Uint8Array(
7533
- await crypto.subtle.encrypt(
7534
- { name: "AES-GCM", iv: noiseNonce(this.n), additionalData: this.h },
7535
- this.k,
7536
- plaintext
7537
- )
7929
+ async execute(params) {
7930
+ const { returns } = await this.executeWithMetadata(params);
7931
+ return returns;
7932
+ }
7933
+ async executeWithMetadata(params) {
7934
+ const result = await this.relay.execute(
7935
+ params.contextId,
7936
+ params.method,
7937
+ // The node defaults a missing `argsJson` to `{}`; matching that here keeps
7938
+ // a zero-argument call identical on both transports rather than sending
7939
+ // `undefined` and letting the relay's JSON body decide.
7940
+ params.argsJson ?? {}
7538
7941
  );
7539
- this.n += 1;
7540
- await this.mixHash(ciphertext);
7541
- return ciphertext;
7942
+ return {
7943
+ // Verbatim. `RelayClient` has already normalized a missing `returns` to
7944
+ // `null`, which is what a node reports for a null output — see the
7945
+ // module note on why this is not rewritten to `undefined`.
7946
+ returns: result.returns,
7947
+ transport: "relay",
7948
+ rootHash: result.rootHash
7949
+ };
7542
7950
  }
7543
- async decryptAndHash(ciphertext) {
7544
- if (!this.k) throw new Error("Noise: no cipher key yet");
7545
- const plaintext = new Uint8Array(
7546
- await crypto.subtle.decrypt(
7547
- { name: "AES-GCM", iv: noiseNonce(this.n), additionalData: this.h },
7548
- this.k,
7549
- ciphertext
7550
- )
7551
- );
7552
- this.n += 1;
7553
- await this.mixHash(ciphertext);
7554
- return plaintext;
7951
+ /**
7952
+ * Both of these are plain context methods, so they work through a relay
7953
+ * exactly as they do on a node — the warrant names `migrate_my_entries` and
7954
+ * the delta is attributed to the author, which is precisely the identity the
7955
+ * convert is scoped to. They are re-declared rather than inherited because
7956
+ * `ExecuteTransport` is an interface, not a base class.
7957
+ */
7958
+ async migrateMyEntries(contextId) {
7959
+ return this.execute({
7960
+ contextId,
7961
+ method: "migrate_my_entries"
7962
+ });
7555
7963
  }
7556
- /** The initiator-to-responder key, then the responder-to-initiator key. */
7557
- split() {
7558
- return hkdf2(this.ck, new Uint8Array());
7964
+ /** Read-only count of the caller's entries still below the target schema. */
7965
+ async countMyPending(contextId) {
7966
+ return this.execute({ contextId, method: "count_my_pending" });
7559
7967
  }
7560
7968
  };
7561
- async function initiate(remoteStatic, prologue, fixedEphemeral) {
7562
- const state = await SymmetricState.initialize();
7563
- await state.mixHash(prologue);
7564
- await state.mixHash(remoteStatic);
7565
- const ephemeral = await x25519KeyPair(fixedEphemeral);
7566
- await state.mixHash(ephemeral.publicKey);
7567
- await state.mixKey(await dh(ephemeral.privateKey, remoteStatic));
7568
- const message1 = concat(ephemeral.publicKey, await state.encryptAndHash(new Uint8Array()));
7569
- return {
7570
- message1,
7571
- async finish(message2) {
7572
- if (message2.length < DH_LEN + TAG_LEN) throw new Error("Noise: message 2 is too short");
7969
+
7970
+ // src/login/login.ts
7971
+ var SIGN_DOMAIN5 = new TextEncoder().encode("calimero.auth.login.v1");
7972
+ var AUDIENCE_TAG = {
7973
+ webOrigin: 0,
7974
+ codeSigningId: 1,
7975
+ cli: 2
7976
+ };
7977
+ function audienceBody(audience) {
7978
+ const encoder = new TextEncoder();
7979
+ switch (audience.kind) {
7980
+ case "webOrigin":
7981
+ return encoder.encode(audience.origin);
7982
+ case "codeSigningId":
7983
+ return encoder.encode(audience.id);
7984
+ case "cli":
7985
+ return new Uint8Array(0);
7986
+ }
7987
+ }
7988
+ function audienceSigningBytes(audience) {
7989
+ return concat(
7990
+ Uint8Array.from([AUDIENCE_TAG[audience.kind]]),
7991
+ audienceBody(audience)
7992
+ );
7993
+ }
7994
+ function audienceWire(audience) {
7995
+ const tag2 = Uint8Array.from([AUDIENCE_TAG[audience.kind]]);
7996
+ if (audience.kind === "cli") {
7997
+ return tag2;
7998
+ }
7999
+ const body = audienceBody(audience);
8000
+ return concat(tag2, u32le(body.length), body);
8001
+ }
8002
+ async function signLoginStatement(input) {
8003
+ const node = fromHex(input.node, "node", 32);
8004
+ const challenge = fromHex(input.challenge, "challenge", 32);
8005
+ const sessionKey = fromHex(input.sessionKey, "sessionKey", 32);
8006
+ const signer = await resolveSigner(
8007
+ input.deviceSecret,
8008
+ input.signer,
8009
+ "deviceSecret"
8010
+ );
8011
+ const deviceKey = fromHex(signer.publicKey, "signer.publicKey", 32);
8012
+ const issuedAt = u64le(input.issuedAt);
8013
+ const expiresAt = u64le(input.expiresAt);
8014
+ const preimage = await domainHash(SIGN_DOMAIN5, [
8015
+ node,
8016
+ audienceSigningBytes(input.audience),
8017
+ challenge,
8018
+ sessionKey,
8019
+ deviceKey,
8020
+ issuedAt,
8021
+ expiresAt
8022
+ ]);
8023
+ const signature = await signer.sign(preimage);
8024
+ return hex(
8025
+ concat(
8026
+ node,
8027
+ audienceWire(input.audience),
8028
+ challenge,
8029
+ sessionKey,
8030
+ deviceKey,
8031
+ issuedAt,
8032
+ expiresAt,
8033
+ signature
8034
+ )
8035
+ );
8036
+ }
8037
+
8038
+ // src/login/session.ts
8039
+ var DEFAULT_TTL_SECONDS2 = 300;
8040
+ async function generateSessionKey() {
8041
+ const secret = hex(crypto.getRandomValues(new Uint8Array(32)));
8042
+ return { publicKey: hex(await derivePublicKey(secret)), secret };
8043
+ }
8044
+ async function login(config) {
8045
+ const baseUrl = config.nodeUrl.replace(/\/+$/, "");
8046
+ const timeoutMs = config.timeoutMs ?? 1e4;
8047
+ const request = async (path, init) => {
8048
+ const controller = new AbortController();
8049
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8050
+ let response;
8051
+ try {
8052
+ const requestInit = { ...init, signal: controller.signal };
8053
+ response = config.fetch ? await config.fetch(`${baseUrl}${path}`, requestInit) : await globalThis.fetch(`${baseUrl}${path}`, requestInit);
8054
+ } catch (err) {
8055
+ throw new HTTPError(
8056
+ 0,
8057
+ err instanceof Error ? err.name : "NetworkError",
8058
+ `${baseUrl}${path}`,
8059
+ new Headers(),
8060
+ err instanceof Error ? err.message : String(err)
8061
+ );
8062
+ } finally {
8063
+ clearTimeout(timer);
8064
+ }
8065
+ const text = await response.text().catch(() => "");
8066
+ if (!response.ok) {
8067
+ throw new HTTPError(
8068
+ response.status,
8069
+ response.statusText,
8070
+ `${baseUrl}${path}`,
8071
+ response.headers,
8072
+ text
8073
+ );
8074
+ }
8075
+ return text ? JSON.parse(text) : {};
8076
+ };
8077
+ const challengeBody = await request("/auth/challenge", {
8078
+ method: "GET",
8079
+ headers: { Accept: "application/json" }
8080
+ });
8081
+ const challenge = challengeBody.challenge ?? challengeBody.data?.challenge;
8082
+ if (!challenge) {
8083
+ throw new Error("the node issued no challenge");
8084
+ }
8085
+ const session = await generateSessionKey();
8086
+ const issuedAt = Math.floor(Date.now() / 1e3);
8087
+ const statement = await signLoginStatement({
8088
+ node: config.node,
8089
+ audience: config.audience,
8090
+ challenge,
8091
+ sessionKey: session.publicKey,
8092
+ issuedAt,
8093
+ expiresAt: issuedAt + (config.ttlSeconds ?? DEFAULT_TTL_SECONDS2),
8094
+ // Resolved once and handed on, so a config carrying a secret and a config
8095
+ // carrying a `CryptoKey` take exactly the same path from here down.
8096
+ signer: await resolveSigner(config.deviceSecret, config.signer, "deviceSecret")
8097
+ });
8098
+ const tokenBody = await request("/auth/token", {
8099
+ method: "POST",
8100
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
8101
+ body: JSON.stringify({
8102
+ auth_method: "account_proof",
8103
+ public_key: session.publicKey,
8104
+ client_name: config.clientName ?? baseUrl,
8105
+ timestamp: issuedAt,
8106
+ provider_data: {
8107
+ challenge,
8108
+ login_statement: statement,
8109
+ account_proof: config.accountProof
8110
+ }
8111
+ })
8112
+ });
8113
+ const accessToken = tokenBody.access_token ?? tokenBody.data?.access_token;
8114
+ const refreshToken = tokenBody.refresh_token ?? tokenBody.data?.refresh_token;
8115
+ if (!accessToken) {
8116
+ throw new Error("the node minted no session");
8117
+ }
8118
+ return {
8119
+ accessToken,
8120
+ refreshToken: refreshToken ?? "",
8121
+ sessionKey: session.publicKey,
8122
+ sessionSecret: session.secret
8123
+ };
8124
+ }
8125
+
8126
+ // src/transport/relay-observer.ts
8127
+ var EXPIRY_SKEW_MS = 3e4;
8128
+ function defaultAudience() {
8129
+ const origin = globalThis.location?.origin;
8130
+ return origin ? { kind: "webOrigin", origin } : { kind: "cli" };
8131
+ }
8132
+ function jwtExpiryMs(token) {
8133
+ try {
8134
+ const parts = token.split(".");
8135
+ if (parts.length !== 3) return null;
8136
+ let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
8137
+ while (b64.length % 4) b64 += "=";
8138
+ const payload = JSON.parse(atob(b64));
8139
+ return typeof payload.exp === "number" ? payload.exp * 1e3 : null;
8140
+ } catch {
8141
+ return null;
8142
+ }
8143
+ }
8144
+ var RelayObserver = class {
8145
+ constructor(config) {
8146
+ this.session = null;
8147
+ this.sessionExpiresAt = null;
8148
+ /** In-flight login, so two surfaces asking at once mint one session, not two. */
8149
+ this.pending = null;
8150
+ this.sseClient = null;
8151
+ this.wsClient = null;
8152
+ this.config = config;
8153
+ }
8154
+ /** The node key this observer logs in with. Read for diagnostics. */
8155
+ get nodeKey() {
8156
+ return this.config.nodeKey;
8157
+ }
8158
+ /**
8159
+ * A usable access token, logging in if there is not one.
8160
+ *
8161
+ * Re-mints once the current token is within {@link EXPIRY_SKEW_MS} of
8162
+ * expiring, and on every call when the token's lifetime cannot be read —
8163
+ * reconnects are backed off, so an extra handshake costs far less than a
8164
+ * stream that silently stops. The refresh token is *held* but not spent:
8165
+ * rotating it is tracked in #87/#88 and a second login is correct in the
8166
+ * meantime, where re-presenting an unrotated refresh token would not be.
8167
+ */
8168
+ async accessToken() {
8169
+ const now = Date.now();
8170
+ if (this.session && this.sessionExpiresAt !== null && this.sessionExpiresAt - EXPIRY_SKEW_MS > now) {
8171
+ return this.session.accessToken;
8172
+ }
8173
+ if (!this.pending) {
8174
+ this.pending = this.loginNow().finally(() => {
8175
+ this.pending = null;
8176
+ });
8177
+ }
8178
+ const session = await this.pending;
8179
+ return session.accessToken;
8180
+ }
8181
+ async loginNow() {
8182
+ const session = await login({
8183
+ nodeUrl: this.config.nodeUrl,
8184
+ node: this.config.nodeKey,
8185
+ signer: await this.config.signer(),
8186
+ accountProof: this.config.accountProof,
8187
+ audience: this.config.audience,
8188
+ clientName: this.config.clientName,
8189
+ ttlSeconds: this.config.ttlSeconds,
8190
+ fetch: this.config.fetch,
8191
+ timeoutMs: this.config.timeoutMs
8192
+ });
8193
+ this.session = session;
8194
+ this.sessionExpiresAt = jwtExpiryMs(session.accessToken);
8195
+ return session;
8196
+ }
8197
+ /**
8198
+ * SSE events over the relay node — the same `SseClient` a node client hands
8199
+ * out, constructed the same way, so nothing downstream can tell which
8200
+ * transport produced it.
8201
+ */
8202
+ get events() {
8203
+ if (!this.sseClient) {
8204
+ this.sseClient = new SseClient({
8205
+ baseUrl: this.config.nodeUrl,
8206
+ getAuthToken: () => this.accessToken()
8207
+ });
8208
+ }
8209
+ return this.sseClient;
8210
+ }
8211
+ /** WebSocket events over the relay node. @experimental — prefer `events`. */
8212
+ get ws() {
8213
+ if (!this.wsClient) {
8214
+ this.wsClient = new WsClient({
8215
+ baseUrl: this.config.nodeUrl,
8216
+ getAuthToken: () => this.accessToken()
8217
+ });
8218
+ }
8219
+ return this.wsClient;
8220
+ }
8221
+ /** Close whatever was opened. Never touches the relay's write path. */
8222
+ close() {
8223
+ this.sseClient?.close();
8224
+ this.wsClient?.close();
8225
+ }
8226
+ };
8227
+
8228
+ // src/request-proof/request-proof.ts
8229
+ var utf8 = (text) => new TextEncoder().encode(text);
8230
+ var REQUEST_SIGN_DOMAIN = utf8("calimero.auth.request.v1");
8231
+ var REQUEST_BODY_DOMAIN = utf8("calimero.auth.request.body.v1");
8232
+ var REQUEST_PROOF_HEADER = "X-Calimero-Proof";
8233
+ var DEFAULT_VALID_FOR = 300;
8234
+ async function signRequestProof(input) {
8235
+ const { method, path, credential } = input;
8236
+ if (!method) throw new Error("signRequestProof needs the method the request will use");
8237
+ if (!path.startsWith("/")) {
8238
+ throw new Error(`signRequestProof needs a path, got ${JSON.stringify(path)}`);
8239
+ }
8240
+ if (path.includes("?")) {
8241
+ throw new Error(
8242
+ `the path must carry no query string, got ${JSON.stringify(path)} \u2014 a query is excluded from the signature on purpose, because a proxy may rewrite one. Anything that must be bound belongs in the body.`
8243
+ );
8244
+ }
8245
+ const bodyBytes2 = input.body === void 0 ? new Uint8Array() : typeof input.body === "string" ? utf8(input.body) : input.body;
8246
+ const bodyHash = await domainHash(REQUEST_BODY_DOMAIN, [bodyBytes2]);
8247
+ const issuedAt = Math.floor(input.now ?? Date.now() / 1e3);
8248
+ const expiresAt = issuedAt + (input.validForSeconds ?? DEFAULT_VALID_FOR);
8249
+ const payload = await domainHash(REQUEST_SIGN_DOMAIN, [
8250
+ utf8(method),
8251
+ utf8(path),
8252
+ bodyHash,
8253
+ u64le(issuedAt),
8254
+ u64le(expiresAt)
8255
+ ]);
8256
+ const signature = await signPayload(payload, input);
8257
+ if (signature.length !== 64) {
8258
+ throw new Error(`the signer returned ${signature.length} bytes, not a 64-byte signature`);
8259
+ }
8260
+ const requestSig = concat(
8261
+ u32le(utf8(method).length),
8262
+ utf8(method),
8263
+ u32le(utf8(path).length),
8264
+ utf8(path),
8265
+ bodyHash,
8266
+ u64le(issuedAt),
8267
+ u64le(expiresAt),
8268
+ signature
8269
+ );
8270
+ const accountProof = hexToBytes(credential, "credential");
8271
+ return hex(concat(accountProof, new Uint8Array([0]), requestSig));
8272
+ }
8273
+ async function signPayload(payload, input) {
8274
+ if (input.signer) return input.signer.sign(payload);
8275
+ if (!input.deviceSecret) {
8276
+ throw new Error("signRequestProof needs either `deviceSecret` or `signer`");
8277
+ }
8278
+ const key = await importSigningKey(input.deviceSecret);
8279
+ return new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, key, payload));
8280
+ }
8281
+ function hexToBytes(value, label2) {
8282
+ const clean = value.trim();
8283
+ if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length % 2 !== 0) {
8284
+ throw new Error(`${label2} is not an even-length hex string`);
8285
+ }
8286
+ return fromHex(clean, label2, clean.length / 2);
8287
+ }
8288
+
8289
+ // src/request-proof/authorizer.ts
8290
+ function createProofAuthorizer(credential) {
8291
+ if (!credential.credential) {
8292
+ throw new Error("a proof authorizer needs the `credential` from signDeviceCert");
8293
+ }
8294
+ if (!credential.deviceSecret && !credential.signer) {
8295
+ throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");
8296
+ }
8297
+ return async ({ method, path, body }) => {
8298
+ const proof = await signRequestProof({
8299
+ method,
8300
+ path,
8301
+ body,
8302
+ credential: credential.credential,
8303
+ deviceSecret: credential.deviceSecret,
8304
+ signer: credential.signer,
8305
+ validForSeconds: credential.validForSeconds
8306
+ });
8307
+ return { [REQUEST_PROOF_HEADER]: proof };
8308
+ };
8309
+ }
8310
+ function signedPath(url) {
8311
+ return new URL(url).pathname;
8312
+ }
8313
+
8314
+ // src/transport/mero-client.ts
8315
+ function relayHasNo(surface, why) {
8316
+ return new Error(
8317
+ `this client was constructed with the relay transport, which has no ${surface}: ${why}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`
8318
+ );
8319
+ }
8320
+ function missingNodeKey(surface) {
8321
+ return new Error(
8322
+ `this relay-transport client cannot open ${surface}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`
8323
+ );
8324
+ }
8325
+ function buildObserver(relay, observe) {
8326
+ const nodeKey = observe?.nodeKey;
8327
+ if (!nodeKey) return null;
8328
+ return new RelayObserver({
8329
+ nodeUrl: observe?.nodeUrl ?? relay.relayUrl,
8330
+ nodeKey,
8331
+ accountProof: observe?.accountProof ?? relay.authorProof,
8332
+ audience: observe?.audience ?? defaultAudience(),
8333
+ signer: observe?.signer ? async () => observe.signer : () => relay.authorSigner(),
8334
+ clientName: observe?.clientName,
8335
+ ttlSeconds: observe?.ttlSeconds,
8336
+ fetch: observe?.fetch,
8337
+ timeoutMs: observe?.timeoutMs
8338
+ });
8339
+ }
8340
+ var MeroClient = class {
8341
+ constructor(config) {
8342
+ /** The relay's event session, or `null` on a node client / with no node key. */
8343
+ this.relayObserver = null;
8344
+ /** Admin reads against the relay, when a session or a proof was supplied. */
8345
+ this.relayAdmin = null;
8346
+ /**
8347
+ * Events off the relay authenticated by a request proof, built lazily.
8348
+ *
8349
+ * Separate from {@link relayObserver} rather than a mode inside it: the
8350
+ * observer's whole subject is a session addressed to a node key, and a proof
8351
+ * has neither. Holding the authorizer instead of the client keeps construction
8352
+ * free of the first signature.
8353
+ */
8354
+ this.proofAuthorizer = null;
8355
+ this.relayUrl = null;
8356
+ this.proofEvents = null;
8357
+ if (config.transport === "relay") {
8358
+ this.transport = "relay";
8359
+ this.nodeClient = null;
8360
+ const relay = config.relay instanceof RelayClient ? config.relay : new RelayClient(config.relay);
8361
+ this.relayObserver = buildObserver(relay, config.observe);
8362
+ this.rpcTransport = new RelayTransport(relay, this.relayObserver);
8363
+ this.relayUrl = relay.relayUrl;
8364
+ if (config.proof) {
8365
+ this.proofAuthorizer = createProofAuthorizer(config.proof);
8366
+ }
8367
+ if (config.session) {
8368
+ const token = config.session;
8369
+ this.relayAdmin = createAdminApiClient({
8370
+ baseUrl: relay.relayUrl,
8371
+ getAuthToken: typeof token === "string" ? async () => token : token
8372
+ });
8373
+ } else if (this.proofAuthorizer) {
8374
+ const authorizeRequest = this.proofAuthorizer;
8375
+ this.relayAdmin = createAdminApiClientFromHttpClient(
8376
+ createHttpClient({
8377
+ fetch: (url, init) => globalThis.fetch(url, init),
8378
+ baseUrl: relay.relayUrl,
8379
+ authorizeRequest
8380
+ }),
8381
+ { baseUrl: relay.relayUrl }
8382
+ );
8383
+ }
8384
+ return;
8385
+ }
8386
+ this.transport = "node";
8387
+ const { transport: _ignored, ...nodeConfig } = config;
8388
+ this.nodeClient = new MeroJs(nodeConfig);
8389
+ this.rpcTransport = this.nodeClient.rpc;
8390
+ }
8391
+ /**
8392
+ * The write surface. Identical on both transports — this is the whole point.
8393
+ *
8394
+ * On a node this IS the `RpcClient` a `MeroJs` would have handed out, not a
8395
+ * wrapper around it, so `client.rpc` and `client.node.rpc` are the same
8396
+ * object.
8397
+ */
8398
+ get rpc() {
8399
+ return this.rpcTransport;
8400
+ }
8401
+ /**
8402
+ * Whether `events` / `ws` will work on this client.
8403
+ *
8404
+ * Always `true` on the node transport. On the relay transport it says whether
8405
+ * a node key was supplied — the relay can be observed, but only by a caller
8406
+ * who can name the key the login statement is signed against.
8407
+ */
8408
+ get canSubscribe() {
8409
+ return this.rpcTransport.canSubscribe || this.proofAuthorizer !== null;
8410
+ }
8411
+ /** The underlying `MeroJs`. Node transport only. */
8412
+ get node() {
8413
+ if (!this.nodeClient) {
8414
+ throw relayHasNo("node connection", "it holds a signing key and a relay URL, not a node");
8415
+ }
8416
+ return this.nodeClient;
8417
+ }
8418
+ /** The underlying `RelayClient`, for `describe()`. Relay transport only. */
8419
+ get relay() {
8420
+ if (!(this.rpcTransport instanceof RelayTransport)) {
8421
+ throw new Error("this client was constructed with the node transport and has no relay");
8422
+ }
8423
+ return this.rpcTransport.client;
8424
+ }
8425
+ /**
8426
+ * Admin API. Node transport only.
8427
+ *
8428
+ * Two different things live behind this accessor today, and only one of them
8429
+ * is genuinely unavailable through a relay.
8430
+ *
8431
+ * The **mutations** — `createNamespace`, `setMemberCapabilities`,
8432
+ * `upgradeGroup` and the rest — are operator actions on somebody else's
8433
+ * machine. A keyholder does not get those, and should not; admin is for
8434
+ * admins.
8435
+ *
8436
+ * The **reads** are a different matter. `getContext`, `getContexts`,
8437
+ * `getApplication`, `listNamespaces`, `getBlob` are an app asking what it is
8438
+ * looking at, not an operator administering anything. They sit under
8439
+ * `/admin-api/` for historical reasons, and a delegated session is refused
8440
+ * them (measured: `403`, while the same session reads context state through
8441
+ * `POST /contexts/{ctx}/query` and writes through `/intents` quite happily).
8442
+ *
8443
+ * So this is the one place where "the same code runs on both transports"
8444
+ * does not hold yet, and it is a missing surface rather than a missing
8445
+ * permission. A transport-independent read API is designed but not built; the
8446
+ * throw below is deliberate until it exists, because the alternative — quietly
8447
+ * reaching for a node the caller did not choose — is worse than a clear stop.
8448
+ */
8449
+ /**
8450
+ * The admin surface.
8451
+ *
8452
+ * On a node client this is the node's own. On a relay client it exists only
8453
+ * when a `session` was supplied, and it is **the relay's admin API
8454
+ * authenticated as the account** — so the caller-scoped reads answer:
8455
+ * `getContexts` and `listNamespaces` return this account's own, because
8456
+ * `account_proof` grants `context:list-own` and `namespace:list-own`.
8457
+ *
8458
+ * Mutations are not filtered out here, deliberately. A delegated session does
8459
+ * not carry the grants they require, so the node refuses them with a `403`
8460
+ * that names the missing permission — which is a better answer than a
8461
+ * client-side guess, and keeps the policy in the one place that owns it.
8462
+ */
8463
+ get admin() {
8464
+ if (this.nodeClient) return this.nodeClient.admin;
8465
+ if (this.relayAdmin) return this.relayAdmin;
8466
+ throw new Error(
8467
+ "this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way."
8468
+ );
8469
+ }
8470
+ /** Auth API. Node transport only — a relay issues no node credential. */
8471
+ get auth() {
8472
+ return this.node.auth;
8473
+ }
8474
+ /**
8475
+ * SSE events — on **both** transports.
8476
+ *
8477
+ * On a relay client this is an `SseClient` against the relay node, fed by a
8478
+ * session minted with the author's account proof. The session is minted
8479
+ * lazily, on the first token the stream asks for, so reading this getter
8480
+ * performs no network call.
8481
+ *
8482
+ * Throws only when the relay client was given no node key: the one input
8483
+ * that cannot be inferred. See {@link missingNodeKey}.
8484
+ */
8485
+ get events() {
8486
+ if (this.nodeClient) return this.nodeClient.events;
8487
+ if (this.relayObserver) return this.relayObserver.events;
8488
+ if (this.proofAuthorizer && this.relayUrl) {
8489
+ this.proofEvents ?? (this.proofEvents = new SseClient({
8490
+ baseUrl: this.relayUrl,
8491
+ authorize: this.proofAuthorizer
8492
+ }));
8493
+ return this.proofEvents;
8494
+ }
8495
+ throw missingNodeKey("SSE events");
8496
+ }
8497
+ /** WebSocket events, on both transports. @experimental — prefer `events`. */
8498
+ get ws() {
8499
+ if (this.nodeClient) return this.nodeClient.ws;
8500
+ if (this.relayObserver) return this.relayObserver.ws;
8501
+ if (this.proofAuthorizer) {
8502
+ throw new Error(
8503
+ "this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."
8504
+ );
8505
+ }
8506
+ throw missingNodeKey("WebSocket events");
8507
+ }
8508
+ /**
8509
+ * Ephemeral presence. Node transport only.
8510
+ *
8511
+ * Not extended to the relay even though a logged-in session could reach both
8512
+ * halves of it mechanically. Publishing resolves the author from an *owned
8513
+ * context identity on the node*, and whether a delegated session has one has
8514
+ * not been established — a presence client that silently published nothing,
8515
+ * or published as the wrong identity, is worse than one that says it is not
8516
+ * available. The read half is not lost: presence arrives on `client.events`
8517
+ * like any other context event, and can be filtered there.
8518
+ *
8519
+ * The rejected alternative was to expose it over the relay session and let
8520
+ * `set` fail at the node. That trades a clear construction-time answer for a
8521
+ * runtime failure inside a UI that has already rendered.
8522
+ */
8523
+ get ephemeral() {
8524
+ if (!this.nodeClient) {
8525
+ throw relayHasNo(
8526
+ "ephemeral presence",
8527
+ "publishing resolves the author from an owned context identity on the node, which a delegated session is not known to have \u2014 read presence off `client.events` instead"
8528
+ );
8529
+ }
8530
+ return this.nodeClient.ephemeral;
8531
+ }
8532
+ /**
8533
+ * Calimero Cloud.
8534
+ *
8535
+ * Available on both transports, because it is neither: the cloud session is
8536
+ * independent of the node credential and of the relay's signing key, and a
8537
+ * relay-transport app still needs it to list namespaces and manage billing.
8538
+ */
8539
+ get cloud() {
8540
+ if (!this.nodeClient) {
8541
+ throw relayHasNo(
8542
+ "bundled cloud client",
8543
+ "a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly"
8544
+ );
8545
+ }
8546
+ return this.nodeClient.cloud;
8547
+ }
8548
+ /**
8549
+ * Release whatever the transport is holding.
8550
+ *
8551
+ * Safe on a relay client, where there is nothing open to close — a caller
8552
+ * that tears down on unmount should not have to know which transport it got.
8553
+ */
8554
+ close() {
8555
+ this.nodeClient?.close();
8556
+ this.relayObserver?.close();
8557
+ this.proofEvents?.close();
8558
+ }
8559
+ };
8560
+ function createMeroClient(config) {
8561
+ return new MeroClient(config);
8562
+ }
8563
+
8564
+ // src/relay/nonce-source.ts
8565
+ function createMemoryNonceSource(start = 1) {
8566
+ let next = BigInt(start);
8567
+ if (next < 1n) {
8568
+ throw new Error("nonce sequence starts at 1");
8569
+ }
8570
+ return {
8571
+ next() {
8572
+ const value = next;
8573
+ next += 1n;
8574
+ return Promise.resolve(value);
8575
+ },
8576
+ advanceTo(floor) {
8577
+ if (floor > next) next = floor;
8578
+ return Promise.resolve();
8579
+ }
8580
+ };
8581
+ }
8582
+ function createLocalStorageNonceSource(key, storage) {
8583
+ const store = storage ?? globalThis.localStorage;
8584
+ if (!store) {
8585
+ throw new Error(
8586
+ "no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence"
8587
+ );
8588
+ }
8589
+ const lastHandedOut = () => {
8590
+ const raw = store.getItem(key);
8591
+ if (raw === null || raw === "") return 0n;
8592
+ try {
8593
+ const parsed = BigInt(raw);
8594
+ return parsed > 0n ? parsed : 0n;
8595
+ } catch {
8596
+ return 0n;
8597
+ }
8598
+ };
8599
+ return {
8600
+ next() {
8601
+ const value = lastHandedOut() + 1n;
8602
+ store.setItem(key, value.toString());
8603
+ return Promise.resolve(value);
8604
+ },
8605
+ advanceTo(floor) {
8606
+ const wanted = floor > 0n ? floor - 1n : 0n;
8607
+ if (wanted > lastHandedOut()) store.setItem(key, wanted.toString());
8608
+ return Promise.resolve();
8609
+ }
8610
+ };
8611
+ }
8612
+ function authorNonceLookup(options) {
8613
+ return {
8614
+ getWarrantNonce: (contextId, _authorDeviceKey) => options.client.getWarrantNonceAsAuthor(contextId, options.authorProof)
8615
+ };
8616
+ }
8617
+ var WarrantNonceExhaustedError = class extends Error {
8618
+ constructor(contextId, authorDeviceKey) {
8619
+ super(
8620
+ `author device ${authorDeviceKey} has spent every nonce in context ${contextId}; it must re-key to write again`
8621
+ );
8622
+ this.contextId = contextId;
8623
+ this.authorDeviceKey = authorDeviceKey;
8624
+ this.name = "WarrantNonceExhaustedError";
8625
+ }
8626
+ };
8627
+ function createRecoveringNonceSource(options) {
8628
+ const lookups = Array.isArray(options.lookups) ? options.lookups : [options.lookups];
8629
+ if (lookups.length === 0) {
8630
+ throw new Error("a recovering nonce source needs at least one node to ask");
8631
+ }
8632
+ const local = options.local ?? createMemoryNonceSource(1);
8633
+ const onLookupFailure = options.onLookupFailure ?? "throw";
8634
+ let floor = null;
8635
+ let pending = null;
8636
+ const resolveFloor = async () => {
8637
+ const answers = await Promise.allSettled(
8638
+ lookups.map(
8639
+ (lookup) => lookup.getWarrantNonce(options.contextId, options.authorDeviceKey)
8640
+ )
8641
+ );
8642
+ let highest = null;
8643
+ let exhausted = false;
8644
+ for (const answer of answers) {
8645
+ if (answer.status !== "fulfilled") continue;
8646
+ const state = answer.value;
8647
+ if (state.kind === "exhausted") {
8648
+ exhausted = true;
8649
+ continue;
8650
+ }
8651
+ if (highest === null || state.nextNonce > highest) highest = state.nextNonce;
8652
+ }
8653
+ if (highest === null && exhausted) {
8654
+ throw new WarrantNonceExhaustedError(options.contextId, options.authorDeviceKey);
8655
+ }
8656
+ if (highest === null) {
8657
+ const first = answers.find((a) => a.status === "rejected");
8658
+ const reason = first && first.status === "rejected" ? first.reason : void 0;
8659
+ if (onLookupFailure === "local") {
8660
+ floor = 0n;
8661
+ return;
8662
+ }
8663
+ throw reason instanceof Error ? reason : new Error(`no node could answer where the warrant-nonce sequence stands: ${String(reason)}`);
8664
+ }
8665
+ floor = highest;
8666
+ await local.advanceTo?.(highest);
8667
+ };
8668
+ return {
8669
+ async next() {
8670
+ if (floor === null) {
8671
+ pending ?? (pending = resolveFloor().finally(() => {
8672
+ pending = null;
8673
+ }));
8674
+ await pending;
8675
+ }
8676
+ const mine = await local.next();
8677
+ const value = floor !== null && floor > mine ? floor : mine;
8678
+ floor = value + 1n;
8679
+ return value;
8680
+ },
8681
+ async advanceTo(wanted) {
8682
+ if (floor === null || wanted > floor) floor = wanted;
8683
+ await local.advanceTo?.(wanted);
8684
+ }
8685
+ };
8686
+ }
8687
+
8688
+ // src/sealed/noise.ts
8689
+ var PROTOCOL_NAME = "Noise_NK_25519_AESGCM_SHA256";
8690
+ var DH_LEN = 32;
8691
+ var TAG_LEN = 16;
8692
+ var PKCS8_X25519_PREFIX = new Uint8Array([
8693
+ 48,
8694
+ 46,
8695
+ 2,
8696
+ 1,
8697
+ 0,
8698
+ 48,
8699
+ 5,
8700
+ 6,
8701
+ 3,
8702
+ 43,
8703
+ 101,
8704
+ 110,
8705
+ 4,
8706
+ 34,
8707
+ 4,
8708
+ 32
8709
+ ]);
8710
+ var SymmetricState = class _SymmetricState {
8711
+ constructor(h) {
8712
+ this.k = null;
8713
+ this.n = 0;
8714
+ this.ck = h;
8715
+ this.h = h;
8716
+ }
8717
+ static async initialize() {
8718
+ const name = new TextEncoder().encode(PROTOCOL_NAME);
8719
+ const h = new Uint8Array(32);
8720
+ h.set(name);
8721
+ return new _SymmetricState(h);
8722
+ }
8723
+ async mixHash(data) {
8724
+ this.h = await sha256(concat(this.h, data));
8725
+ }
8726
+ async mixKey(inputKeyMaterial) {
8727
+ const [ck, key] = await hkdf2(this.ck, inputKeyMaterial);
8728
+ this.ck = ck;
8729
+ this.k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt", "decrypt"]);
8730
+ this.n = 0;
8731
+ }
8732
+ async encryptAndHash(plaintext) {
8733
+ if (!this.k) throw new Error("Noise: no cipher key yet");
8734
+ const ciphertext = new Uint8Array(
8735
+ await crypto.subtle.encrypt(
8736
+ { name: "AES-GCM", iv: noiseNonce(this.n), additionalData: this.h },
8737
+ this.k,
8738
+ plaintext
8739
+ )
8740
+ );
8741
+ this.n += 1;
8742
+ await this.mixHash(ciphertext);
8743
+ return ciphertext;
8744
+ }
8745
+ async decryptAndHash(ciphertext) {
8746
+ if (!this.k) throw new Error("Noise: no cipher key yet");
8747
+ const plaintext = new Uint8Array(
8748
+ await crypto.subtle.decrypt(
8749
+ { name: "AES-GCM", iv: noiseNonce(this.n), additionalData: this.h },
8750
+ this.k,
8751
+ ciphertext
8752
+ )
8753
+ );
8754
+ this.n += 1;
8755
+ await this.mixHash(ciphertext);
8756
+ return plaintext;
8757
+ }
8758
+ /** The initiator-to-responder key, then the responder-to-initiator key. */
8759
+ split() {
8760
+ return hkdf2(this.ck, new Uint8Array());
8761
+ }
8762
+ };
8763
+ async function initiate(remoteStatic, prologue, fixedEphemeral) {
8764
+ const state = await SymmetricState.initialize();
8765
+ await state.mixHash(prologue);
8766
+ await state.mixHash(remoteStatic);
8767
+ const ephemeral = await x25519KeyPair(fixedEphemeral);
8768
+ await state.mixHash(ephemeral.publicKey);
8769
+ await state.mixKey(await dh(ephemeral.privateKey, remoteStatic));
8770
+ const message1 = concat(ephemeral.publicKey, await state.encryptAndHash(new Uint8Array()));
8771
+ return {
8772
+ message1,
8773
+ async finish(message2) {
8774
+ if (message2.length < DH_LEN + TAG_LEN) throw new Error("Noise: message 2 is too short");
7573
8775
  const remoteEphemeral = message2.slice(0, DH_LEN);
7574
8776
  await state.mixHash(remoteEphemeral);
7575
8777
  await state.mixKey(await dh(ephemeral.privateKey, remoteEphemeral));
@@ -7651,7 +8853,7 @@ var MAX_HANDSHAKE_REPLY = 1024;
7651
8853
  var RENEW_BEFORE_MS = 6e4;
7652
8854
  var TRANSPORT_BINDING_DOMAIN = "calimero.tee-attest.transport-key.v1";
7653
8855
  var NULL_BODY_STATUSES = [101, 204, 205, 304];
7654
- var utf8 = new TextEncoder();
8856
+ var utf82 = new TextEncoder();
7655
8857
  var StaleTransportKeyError = class extends Error {
7656
8858
  constructor() {
7657
8859
  super("The node no longer holds the attested transport key; attest again for the current one");
@@ -7659,18 +8861,18 @@ var StaleTransportKeyError = class extends Error {
7659
8861
  }
7660
8862
  };
7661
8863
  var SealedTransportError = class extends Error {
7662
- constructor(status, code, message, retryAfterMs) {
8864
+ constructor(status, code, message, retryAfterMs2) {
7663
8865
  super(message);
7664
8866
  this.status = status;
7665
8867
  this.code = code;
7666
- this.retryAfterMs = retryAfterMs;
8868
+ this.retryAfterMs = retryAfterMs2;
7667
8869
  this.name = "SealedTransportError";
7668
8870
  }
7669
8871
  };
7670
8872
  async function transportKeyBinding(inner, transportKey) {
7671
8873
  const digest = await crypto.subtle.digest(
7672
8874
  "SHA-256",
7673
- concat(utf8.encode(TRANSPORT_BINDING_DOMAIN), inner, transportKey)
8875
+ concat(utf82.encode(TRANSPORT_BINDING_DOMAIN), inner, transportKey)
7674
8876
  );
7675
8877
  return new Uint8Array(digest);
7676
8878
  }
@@ -7874,7 +9076,7 @@ function nonce(requestId, index) {
7874
9076
  return bytes;
7875
9077
  }
7876
9078
  function joinInner(head, body) {
7877
- const encoded = utf8.encode(JSON.stringify(head));
9079
+ const encoded = utf82.encode(JSON.stringify(head));
7878
9080
  const len = new Uint8Array(4);
7879
9081
  new DataView(len.buffer).setUint32(0, encoded.length, false);
7880
9082
  return concat(len, encoded, body);
@@ -7983,8 +9185,8 @@ async function envelopeRefusal(response) {
7983
9185
  }
7984
9186
  if (code === "stale_transport_key") return new StaleTransportKeyError();
7985
9187
  const retryAfter = Number(response.headers.get("retry-after"));
7986
- const retryAfterMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 5) * 1e3 : void 0;
7987
- return new SealedTransportError(response.status, code, message, retryAfterMs);
9188
+ const retryAfterMs2 = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 5) * 1e3 : void 0;
9189
+ return new SealedTransportError(response.status, code, message, retryAfterMs2);
7988
9190
  }
7989
9191
 
7990
9192
  // src/cloud/connect.ts
@@ -7992,6 +9194,7 @@ async function connectCloud(options) {
7992
9194
  if (!options.sessionToken && !options.googleIdToken) {
7993
9195
  throw new Error("connectCloud needs either a sessionToken or a googleIdToken");
7994
9196
  }
9197
+ const signer = await resolveSigner(options.deviceSecret, options.signer, "deviceSecret");
7995
9198
  const cloud = new CloudClient({
7996
9199
  cloudBaseUrl: options.cloudBaseUrl,
7997
9200
  sessionToken: options.sessionToken,
@@ -8017,8 +9220,8 @@ async function connectCloud(options) {
8017
9220
  executorAccount: relayInfo.executorAccount,
8018
9221
  authorAccount: options.authorAccount,
8019
9222
  authorProof: options.authorProof,
8020
- deviceSecret: options.deviceSecret,
8021
- nonces: options.nonces ?? await defaultNonceSource(options.deviceSecret),
9223
+ signer,
9224
+ nonces: options.nonces ?? defaultNonceSource(signer.publicKey),
8022
9225
  ttlSeconds: options.ttlSeconds,
8023
9226
  // Only the relay is sealed: a sealed fetch is bound to one node and refuses
8024
9227
  // any other URL, and the cloud calls above carry no intent.
@@ -8035,9 +9238,50 @@ async function connectCloud(options) {
8035
9238
  namespaceId: namespace.namespaceId,
8036
9239
  namespace,
8037
9240
  relayInfo,
8038
- execute: (contextId, method, argsJson) => relay.execute(contextId, method, argsJson)
9241
+ execute: (contextId, method, argsJson) => relay.execute(contextId, method, argsJson),
9242
+ // Built from the same `relay`, not a second one: one nonce sequence, one
9243
+ // warrant signer. Two clients over one relay would hand out the same nonce
9244
+ // twice and have the network refuse the loser as a replay.
9245
+ //
9246
+ // `observe` is always passed, with whatever key is known — the caller's if
9247
+ // they had one, otherwise the cloud's, which is `null` until mdma #312. One
9248
+ // code path rather than two, so the hosted case starts observing the day
9249
+ // the field appears, without a line changing here or at the call site.
9250
+ client: new MeroClient({
9251
+ transport: "relay",
9252
+ relay,
9253
+ observe: {
9254
+ nodeKey: options.relayNodeKey ?? relayInfo.nodeKey,
9255
+ audience: options.observeAudience,
9256
+ fetch: options.fetch,
9257
+ timeoutMs: options.timeoutMs
9258
+ }
9259
+ })
8039
9260
  };
8040
9261
  }
9262
+ async function connectCloudWithAccount(options) {
9263
+ const { root, authorAccount, ...rest } = options;
9264
+ const signer = await resolveSigner(rest.deviceSecret, rest.signer, "deviceSecret");
9265
+ const resolved = await resolveRoot(root);
9266
+ const cloud = new CloudClient({
9267
+ cloudBaseUrl: options.cloudBaseUrl,
9268
+ // Reported here as well as on the connection's own client: this is where
9269
+ // the session is first minted, and a caller persisting it would otherwise
9270
+ // only hear about the rolling refreshes of a token it never saw.
9271
+ onSession: options.onSession,
9272
+ fetch: options.fetch,
9273
+ timeoutMs: options.timeoutMs
9274
+ });
9275
+ const session = await cloud.signInWithAccount(resolved.signer);
9276
+ return connectCloud({
9277
+ ...rest,
9278
+ // Already resolved above, and passing both forms on would be refused.
9279
+ deviceSecret: void 0,
9280
+ signer,
9281
+ sessionToken: session.sessionToken,
9282
+ authorAccount: authorAccount ?? resolved.accountId
9283
+ });
9284
+ }
8041
9285
  function pickNamespace(namespaces, requested) {
8042
9286
  if (requested) {
8043
9287
  const found = namespaces.find((n) => n.namespaceId === requested);
@@ -8068,19 +9312,181 @@ function explainNoRelay(namespace, relays) {
8068
9312
  if (replicas.length === relays.length) {
8069
9313
  return `every node on namespace ${namespace.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;
8070
9314
  }
8071
- const waitingOnGrant = relays.filter((r) => r.teeRole === null && !r.authorshipReady);
8072
- if (waitingOnGrant.length > 0 && waitingOnGrant.length + replicas.length === relays.length) {
8073
- return `every relay on namespace ${namespace.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${waitingOnGrant.map((r) => r.executorAccount ?? r.peerId).join(", ") || "the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`;
9315
+ const waitingOnGrant = relays.filter((r) => r.teeRole === null && !r.authorshipReady);
9316
+ if (waitingOnGrant.length > 0 && waitingOnGrant.length + replicas.length === relays.length) {
9317
+ return `every relay on namespace ${namespace.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${waitingOnGrant.map((r) => r.executorAccount ?? r.peerId).join(", ") || "the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`;
9318
+ }
9319
+ return `namespace ${namespace.namespaceId} has ${relays.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`;
9320
+ }
9321
+ function defaultNonceSource(devicePublicKey) {
9322
+ const key = `mero-js:warrant-nonce:${devicePublicKey}`;
9323
+ try {
9324
+ return createLocalStorageNonceSource(key);
9325
+ } catch {
9326
+ return createMemoryNonceSource(1);
9327
+ }
9328
+ }
9329
+
9330
+ // src/cloud/link-redirect.ts
9331
+ var DEFAULT_CLOUD_WEB_URL = "https://cloud.calimero.network";
9332
+ function cloudLinkUrl(options) {
9333
+ if (!/^[0-9a-f]{64}$/.test(options.accountId)) {
9334
+ throw new Error("accountId must be 64 lowercase hex characters");
9335
+ }
9336
+ const url = new URL(options.cloudWebUrl ?? DEFAULT_CLOUD_WEB_URL);
9337
+ url.searchParams.set("link-account", options.accountId);
9338
+ url.searchParams.set("callback-url", options.returnTo);
9339
+ return url.toString();
9340
+ }
9341
+ function beginCloudLink(options) {
9342
+ window.location.assign(cloudLinkUrl(options));
9343
+ throw new Error("redirecting to the cloud to authorise this link");
9344
+ }
9345
+ function readCloudLinkCallback(location2 = window.location) {
9346
+ const params = new URLSearchParams(location2.hash.replace(/^#/, ""));
9347
+ const error = params.get("error");
9348
+ if (error) {
9349
+ stripFragment();
9350
+ throw new Error(
9351
+ error === "denied" ? "the account link was declined at the cloud" : `the cloud refused this link: ${error}`
9352
+ );
9353
+ }
9354
+ const grant = params.get("grant");
9355
+ const account = params.get("account");
9356
+ if (!grant || !account) return null;
9357
+ stripFragment();
9358
+ return { grant, account };
9359
+ }
9360
+ function stripFragment() {
9361
+ if (typeof history === "undefined" || !history.replaceState) return;
9362
+ history.replaceState(null, "", location.pathname + location.search);
9363
+ }
9364
+ async function completeCloudLink(options) {
9365
+ const root = await resolveRoot(options.root);
9366
+ if (root.accountId !== options.account) {
9367
+ throw new Error(
9368
+ `this grant is for account ${options.account}, but the root here derives ${root.accountId} \u2014 it was minted for a different account`
9369
+ );
9370
+ }
9371
+ const cloud = new CloudClient({
9372
+ cloudBaseUrl: options.cloudBaseUrl,
9373
+ fetch: options.fetch
9374
+ });
9375
+ return cloud.linkAccountWithGrant({ grant: options.grant, signer: root.signer });
9376
+ }
9377
+
9378
+ // src/cloud/enrol-redirect.ts
9379
+ var DEVICE_PARAM = "enrol-device";
9380
+ var KEM_PARAM = "enrol-kem";
9381
+ var CALLBACK_PARAM = "callback-url";
9382
+ var STATE_PARAM = "state";
9383
+ function deviceEnrolmentUrl(options) {
9384
+ assertHex(options.devicePublicKey, "devicePublicKey");
9385
+ assertHex(options.kemPublicKey, "kemPublicKey");
9386
+ assertSafeReturnTo(options.returnTo);
9387
+ warnOnForeignCallback(options.returnTo);
9388
+ const url = new URL(options.walletUrl);
9389
+ url.searchParams.set(DEVICE_PARAM, options.devicePublicKey);
9390
+ url.searchParams.set(KEM_PARAM, options.kemPublicKey);
9391
+ url.searchParams.set(CALLBACK_PARAM, options.returnTo);
9392
+ if (options.state) url.searchParams.set(STATE_PARAM, options.state);
9393
+ return url.toString();
9394
+ }
9395
+ function beginDeviceEnrolment(options) {
9396
+ window.location.assign(deviceEnrolmentUrl(options));
9397
+ throw new Error("redirecting to the wallet to approve this device");
9398
+ }
9399
+ function readEnrolmentCallback(location2 = window.location) {
9400
+ const params = new URLSearchParams(location2.hash.replace(/^#/, ""));
9401
+ const error = params.get("error");
9402
+ if (error) {
9403
+ stripFragment2();
9404
+ throw new Error(
9405
+ error === "denied" || error === "cancelled" ? "the device was not approved at the wallet" : `the wallet refused this enrolment: ${error}`
9406
+ );
9407
+ }
9408
+ const credential = params.get("credential");
9409
+ const account = params.get("account");
9410
+ const device = params.get("device");
9411
+ if (!credential || !account || !device) return null;
9412
+ stripFragment2();
9413
+ const state = params.get("state");
9414
+ return { credential, account, device, ...state ? { state } : {} };
9415
+ }
9416
+ function stripFragment2() {
9417
+ if (typeof history === "undefined" || !history.replaceState) return;
9418
+ history.replaceState(null, "", location.pathname + location.search);
9419
+ }
9420
+ async function completeDeviceEnrolment(options) {
9421
+ if (options.expectState !== void 0 && options.expectState !== options.state) {
9422
+ throw new Error(
9423
+ "this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent"
9424
+ );
9425
+ }
9426
+ const certificate = await verifyDeviceCredential(options.credential);
9427
+ if (certificate.signPublicKey !== normaliseHex(options.devicePublicKey)) {
9428
+ throw new Error(
9429
+ `this credential certifies device key ${certificate.signPublicKey}, but this app holds ${normaliseHex(options.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`
9430
+ );
9431
+ }
9432
+ if (options.kemPublicKey !== void 0 && certificate.kemPublicKey !== normaliseHex(options.kemPublicKey)) {
9433
+ throw new Error(
9434
+ `this credential names delivery key ${certificate.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`
9435
+ );
9436
+ }
9437
+ if (certificate.account !== normaliseHex(options.account)) {
9438
+ throw new Error(
9439
+ `the wallet reported account ${normaliseHex(options.account)}, but the credential names ${certificate.account}`
9440
+ );
9441
+ }
9442
+ if (certificate.device !== normaliseHex(options.device)) {
9443
+ throw new Error(
9444
+ `the wallet reported device ${normaliseHex(options.device)}, but the credential names ${certificate.device}`
9445
+ );
9446
+ }
9447
+ return {
9448
+ credential: options.credential,
9449
+ account: certificate.account,
9450
+ device: certificate.device,
9451
+ certificate
9452
+ };
9453
+ }
9454
+ function assertHex(value, label2) {
9455
+ if (!/^[0-9a-f]{64}$/.test(value)) {
9456
+ throw new Error(`${label2} must be 64 lowercase hex characters`);
8074
9457
  }
8075
- return `namespace ${namespace.namespaceId} has ${relays.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`;
8076
9458
  }
8077
- async function defaultNonceSource(deviceSecret) {
8078
- const key = `mero-js:warrant-nonce:${hex(await derivePublicKey(deviceSecret))}`;
9459
+ function normaliseHex(value) {
9460
+ return value.trim().toLowerCase();
9461
+ }
9462
+ function callbackIsForeign(returnTo, pageOrigin) {
9463
+ const here = pageOrigin ?? (typeof window === "undefined" ? void 0 : window.location.origin);
9464
+ if (!here) return false;
8079
9465
  try {
8080
- return createLocalStorageNonceSource(key);
9466
+ return new URL(returnTo).origin !== here;
8081
9467
  } catch {
8082
- return createMemoryNonceSource(1);
9468
+ return false;
9469
+ }
9470
+ }
9471
+ function warnOnForeignCallback(returnTo) {
9472
+ if (!callbackIsForeign(returnTo)) return;
9473
+ console.warn(
9474
+ `[calimero] enrolling a device but sending the credential to ${new URL(returnTo).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`
9475
+ );
9476
+ }
9477
+ function assertSafeReturnTo(returnTo) {
9478
+ let url;
9479
+ try {
9480
+ url = new URL(returnTo);
9481
+ } catch {
9482
+ throw new Error(`returnTo must be an absolute URL, got ${returnTo}`);
8083
9483
  }
9484
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "::1";
9485
+ if (url.protocol === "https:") return;
9486
+ if (url.protocol === "http:" && loopback) return;
9487
+ throw new Error(
9488
+ `returnTo must be https:, or http: on localhost \u2014 got ${url.protocol}//${url.hostname}`
9489
+ );
8084
9490
  }
8085
9491
 
8086
9492
  // src/sealed/verify.ts
@@ -8451,7 +9857,7 @@ var FULCIO_ISSUER_V1 = "1.3.6.1.4.1.57264.1.1";
8451
9857
  var SAN_URI = 134;
8452
9858
  var UTF8_STRING = 12;
8453
9859
  var SEQUENCE2 = 48;
8454
- var utf82 = new TextEncoder();
9860
+ var utf83 = new TextEncoder();
8455
9861
  var fromUtf8 = (bytes) => new TextDecoder().decode(bytes);
8456
9862
  async function verifyCosignBundle(body, bundle, signer, signature) {
8457
9863
  const { base64Signature, cert, rekorBundle } = cosignBundle(bundle);
@@ -8464,7 +9870,7 @@ async function verifyCosignBundle(body, bundle, signer, signature) {
8464
9870
  const leaf = parseCertificate(leafDer);
8465
9871
  const log = REKOR_LOGS.find((candidate) => candidate.logId === payload.logID.toLowerCase());
8466
9872
  if (!log) throw new Error(`The bundle names Rekor log ${payload.logID}, which the Sigstore trust root does not know`);
8467
- const canonical = utf82.encode(
9873
+ const canonical = utf83.encode(
8468
9874
  `{"body":${JSON.stringify(payload.body)},"integratedTime":${payload.integratedTime},"logID":${JSON.stringify(payload.logID)},"logIndex":${payload.logIndex}}`
8469
9875
  );
8470
9876
  const setVerifies = await verifyEcdsa(
@@ -8768,6 +10174,101 @@ function splitVersion2(version) {
8768
10174
  return [[Number(match[1]), Number(match[2]), Number(match[3])], match[4]];
8769
10175
  }
8770
10176
 
10177
+ // src/invitation/invitation.ts
10178
+ var MAX_INVITATION_VALIDITY_SECS = 24 * 60 * 60;
10179
+ var INVITED_ROLE = { Admin: 0, Member: 1, ReadOnly: 2 };
10180
+ function encodeGroupInvitation(body) {
10181
+ const admitters = body.admitters ?? [];
10182
+ return concat(
10183
+ // `SignerId` and `ContextGroupId` cross JSON as 32 numbers; `AccountId`
10184
+ // crosses as hex. Same width, different spelling.
10185
+ bytes32(body.inviter_identity, "inviter_identity"),
10186
+ bytes32(body.group_id, "group_id"),
10187
+ u64le(body.expiration_timestamp),
10188
+ bytes32(body.secret_salt, "secret_salt"),
10189
+ new Uint8Array([body.invited_role]),
10190
+ u32le(admitters.length),
10191
+ ...admitters.map((a, i) => fromHex(a, `admitters[${i}]`, 32))
10192
+ );
10193
+ }
10194
+ async function groupInvitationHash(body) {
10195
+ return new Uint8Array(
10196
+ await crypto.subtle.digest("SHA-256", encodeGroupInvitation(body))
10197
+ );
10198
+ }
10199
+ function defaultAdmitters(members) {
10200
+ const admins = new Set(
10201
+ members.filter((m) => m.role === "Admin").map((m) => m.identity.toLowerCase())
10202
+ );
10203
+ return [...admins].sort();
10204
+ }
10205
+ async function signGroupInvitation(input) {
10206
+ const signer = await resolveSigner(input.deviceSecret, input.signer, "deviceSecret");
10207
+ const inviterKey = fromHex(signer.publicKey, "signer.publicKey", 32);
10208
+ const groupId = fromHex(input.groupId, "groupId", 32);
10209
+ fromHex(input.inviterAccount, "inviterAccount", 32);
10210
+ let admitters = [...input.admitters ?? []].map((a) => a.trim().toLowerCase());
10211
+ if (admitters.length === 0) {
10212
+ if (!input.members) {
10213
+ throw new Error(
10214
+ "name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast"
10215
+ );
10216
+ }
10217
+ admitters = defaultAdmitters(input.members);
10218
+ if (admitters.length === 0) {
10219
+ throw new Error(
10220
+ "the member list names no admin, so there is nobody to default the admitters to"
10221
+ );
10222
+ }
10223
+ }
10224
+ admitters.forEach((a, i) => fromHex(a, `admitters[${i}]`, 32));
10225
+ const invitedRole = input.invitedRole ?? INVITED_ROLE.Member;
10226
+ if (![0, 1, 2].includes(invitedRole)) {
10227
+ throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${invitedRole}`);
10228
+ }
10229
+ const now = input.now ?? Math.floor(Date.now() / 1e3);
10230
+ const validFor = Math.min(
10231
+ input.validForSecs ?? MAX_INVITATION_VALIDITY_SECS,
10232
+ MAX_INVITATION_VALIDITY_SECS
10233
+ );
10234
+ if (!Number.isInteger(validFor) || validFor <= 0) {
10235
+ throw new Error(`validForSecs must be a positive whole number, got ${input.validForSecs}`);
10236
+ }
10237
+ const nonce2 = input.nonce ?? crypto.getRandomValues(new Uint8Array(32));
10238
+ if (nonce2.length !== 32) {
10239
+ throw new Error(`nonce must be 32 bytes, got ${nonce2.length}`);
10240
+ }
10241
+ const invitation = {
10242
+ inviter_identity: Array.from(inviterKey),
10243
+ group_id: Array.from(groupId),
10244
+ expiration_timestamp: now + validFor,
10245
+ secret_salt: Array.from(nonce2),
10246
+ invited_role: invitedRole,
10247
+ admitters
10248
+ };
10249
+ const signature = await signer.sign(await groupInvitationHash(invitation));
10250
+ if (signature.length !== 64) {
10251
+ throw new Error(`signer returned ${signature.length} bytes, expected a 64-byte Ed25519 signature`);
10252
+ }
10253
+ const signed = {
10254
+ invitation,
10255
+ inviter_signature: hex(signature),
10256
+ inviter_account: input.inviterAccount.trim().toLowerCase()
10257
+ };
10258
+ if (input.admitterAddrs?.length) signed.admitter_addrs = [...input.admitterAddrs];
10259
+ if (input.applicationId) {
10260
+ signed.application_id = Array.from(fromHex(input.applicationId, "applicationId", 32));
10261
+ }
10262
+ if (input.appKey) signed.app_key = Array.from(fromHex(input.appKey, "appKey", 32));
10263
+ return signed;
10264
+ }
10265
+ function bytes32(value, label2) {
10266
+ if (value.length !== 32) {
10267
+ throw new Error(`${label2} must be 32 bytes, got ${value.length}`);
10268
+ }
10269
+ return new Uint8Array(value);
10270
+ }
10271
+
8771
10272
  // src/namespace-op/namespace-op.ts
8772
10273
  var SIGNED_NAMESPACE_OP_SCHEMA_VERSION = 16;
8773
10274
  var NAMESPACE_SIGN_DOMAIN = new TextEncoder().encode("calimero.namespace.v1");
@@ -8785,12 +10286,6 @@ var ROOT_OP2 = {
8785
10286
  NamespaceCreatedV2: 9,
8786
10287
  MemberJoinedViaTeeAttestation: 10
8787
10288
  };
8788
- function bytes32(value, label2) {
8789
- if (value.length !== 32) {
8790
- throw new Error(`${label2} must be 32 bytes, got ${value.length}`);
8791
- }
8792
- return new Uint8Array(value);
8793
- }
8794
10289
  function optionalBytes32(value, label2) {
8795
10290
  if (value === null || value === void 0) {
8796
10291
  return new Uint8Array([0]);
@@ -8806,21 +10301,11 @@ function borshString2(value) {
8806
10301
  }
8807
10302
  function encodeSignedInvitation(signed) {
8808
10303
  const body = signed.invitation;
8809
- const admitters = body.admitters ?? [];
8810
10304
  const admitterAddrs = signed.admitter_addrs ?? [];
8811
10305
  return concat(
8812
- // GroupInvitationFromAdmin.
8813
- //
8814
- // `SignerId` and `ContextGroupId` cross JSON as 32 numbers; `AccountId`
8815
- // crosses as hex. Same width, different spelling, and reading either the
8816
- // wrong way yields 32 bytes that encode cleanly and verify as nothing.
8817
- bytes32(body.inviter_identity, "inviter_identity"),
8818
- bytes32(body.group_id, "group_id"),
8819
- u64le(body.expiration_timestamp),
8820
- bytes32(body.secret_salt, "secret_salt"),
8821
- new Uint8Array([body.invited_role]),
8822
- u32le(admitters.length),
8823
- ...admitters.map((a, i) => fromHex(a, `admitters[${i}]`, 32)),
10306
+ // GroupInvitationFromAdmin, from the one encoder the SDK's own invitation
10307
+ // signer uses: the bytes signed and the bytes carried must not drift.
10308
+ encodeGroupInvitation(body),
8824
10309
  // ...then the enclosing SignedGroupOpenInvitation, in declaration order.
8825
10310
  // `inviter_account` sits between the signature and the addresses; putting it
8826
10311
  // anywhere else still encodes 32 bytes and still verifies as nothing.
@@ -8859,186 +10344,22 @@ async function signMemberJoinOp(input) {
8859
10344
  credential
8860
10345
  );
8861
10346
  const op = concat(new Uint8Array([NAMESPACE_OP_ROOT]), rootOp);
8862
- const key = await importSigningKey(input.deviceSecret);
8863
- const signer = await derivePublicKey(input.deviceSecret);
10347
+ const signingKey = await resolveSigner(input.deviceSecret, input.signer, "deviceSecret");
10348
+ const signerPublicKey = fromHex(signingKey.publicKey, "signer.publicKey", 32);
8864
10349
  const signable = concat(
8865
10350
  new Uint8Array([SIGNED_NAMESPACE_OP_SCHEMA_VERSION]),
8866
10351
  fromHex(input.namespaceId, "namespaceId", 32),
8867
10352
  u32le(parents.length),
8868
10353
  ...parents.map((p, i) => fromHex(p, `parentOpHashes[${i}]`, 32)),
8869
- signer,
10354
+ signerPublicKey,
8870
10355
  u64le(input.nonce),
8871
10356
  op
8872
10357
  );
8873
- const signature = new Uint8Array(
8874
- await crypto.subtle.sign("Ed25519", key, concat(NAMESPACE_SIGN_DOMAIN, signable))
8875
- );
10358
+ const signature = await signingKey.sign(concat(NAMESPACE_SIGN_DOMAIN, signable));
8876
10359
  const unendorsed = new Uint8Array([0]);
8877
10360
  return hex(concat(signable, signature, unendorsed));
8878
10361
  }
8879
10362
 
8880
- // src/login/login.ts
8881
- var SIGN_DOMAIN5 = new TextEncoder().encode("calimero.auth.login.v1");
8882
- var AUDIENCE_TAG = {
8883
- webOrigin: 0,
8884
- codeSigningId: 1,
8885
- cli: 2
8886
- };
8887
- function audienceBody(audience) {
8888
- const encoder = new TextEncoder();
8889
- switch (audience.kind) {
8890
- case "webOrigin":
8891
- return encoder.encode(audience.origin);
8892
- case "codeSigningId":
8893
- return encoder.encode(audience.id);
8894
- case "cli":
8895
- return new Uint8Array(0);
8896
- }
8897
- }
8898
- function audienceSigningBytes(audience) {
8899
- return concat(
8900
- Uint8Array.from([AUDIENCE_TAG[audience.kind]]),
8901
- audienceBody(audience)
8902
- );
8903
- }
8904
- function audienceWire(audience) {
8905
- const tag2 = Uint8Array.from([AUDIENCE_TAG[audience.kind]]);
8906
- if (audience.kind === "cli") {
8907
- return tag2;
8908
- }
8909
- const body = audienceBody(audience);
8910
- return concat(tag2, u32le(body.length), body);
8911
- }
8912
- async function signLoginStatement(input) {
8913
- const node = fromHex(input.node, "node", 32);
8914
- const challenge = fromHex(input.challenge, "challenge", 32);
8915
- const sessionKey = fromHex(input.sessionKey, "sessionKey", 32);
8916
- const key = await importSigningKey(input.deviceSecret);
8917
- const deviceKey = await derivePublicKey(input.deviceSecret);
8918
- const issuedAt = u64le(input.issuedAt);
8919
- const expiresAt = u64le(input.expiresAt);
8920
- const preimage = await domainHash(SIGN_DOMAIN5, [
8921
- node,
8922
- audienceSigningBytes(input.audience),
8923
- challenge,
8924
- sessionKey,
8925
- deviceKey,
8926
- issuedAt,
8927
- expiresAt
8928
- ]);
8929
- const signature = new Uint8Array(
8930
- await crypto.subtle.sign({ name: "Ed25519" }, key, preimage)
8931
- );
8932
- return hex(
8933
- concat(
8934
- node,
8935
- audienceWire(input.audience),
8936
- challenge,
8937
- sessionKey,
8938
- deviceKey,
8939
- issuedAt,
8940
- expiresAt,
8941
- signature
8942
- )
8943
- );
8944
- }
8945
-
8946
- // src/login/session.ts
8947
- var DEFAULT_TTL_SECONDS2 = 300;
8948
- async function generateSessionKey() {
8949
- const secret = hex(crypto.getRandomValues(new Uint8Array(32)));
8950
- return { publicKey: hex(await derivePublicKey(secret)), secret };
8951
- }
8952
- function audienceLabel(audience) {
8953
- switch (audience.kind) {
8954
- case "webOrigin":
8955
- return audience.origin;
8956
- case "codeSigningId":
8957
- return audience.id;
8958
- case "cli":
8959
- return "cli";
8960
- }
8961
- }
8962
- async function login(config) {
8963
- const baseUrl = config.nodeUrl.replace(/\/+$/, "");
8964
- const timeoutMs = config.timeoutMs ?? 1e4;
8965
- const request = async (path, init) => {
8966
- const controller = new AbortController();
8967
- const timer = setTimeout(() => controller.abort(), timeoutMs);
8968
- let response;
8969
- try {
8970
- const requestInit = { ...init, signal: controller.signal };
8971
- response = config.fetch ? await config.fetch(`${baseUrl}${path}`, requestInit) : await globalThis.fetch(`${baseUrl}${path}`, requestInit);
8972
- } catch (err) {
8973
- throw new HTTPError(
8974
- 0,
8975
- err instanceof Error ? err.name : "NetworkError",
8976
- `${baseUrl}${path}`,
8977
- new Headers(),
8978
- err instanceof Error ? err.message : String(err)
8979
- );
8980
- } finally {
8981
- clearTimeout(timer);
8982
- }
8983
- const text = await response.text().catch(() => "");
8984
- if (!response.ok) {
8985
- throw new HTTPError(
8986
- response.status,
8987
- response.statusText,
8988
- `${baseUrl}${path}`,
8989
- response.headers,
8990
- text
8991
- );
8992
- }
8993
- return text ? JSON.parse(text) : {};
8994
- };
8995
- const challengeBody = await request("/auth/challenge", {
8996
- method: "GET",
8997
- headers: { Accept: "application/json" }
8998
- });
8999
- const challenge = challengeBody.challenge ?? challengeBody.data?.challenge;
9000
- if (!challenge) {
9001
- throw new Error("the node issued no challenge");
9002
- }
9003
- const session = await generateSessionKey();
9004
- const issuedAt = Math.floor(Date.now() / 1e3);
9005
- const statement = await signLoginStatement({
9006
- node: config.node,
9007
- audience: config.audience,
9008
- challenge,
9009
- sessionKey: session.publicKey,
9010
- issuedAt,
9011
- expiresAt: issuedAt + (config.ttlSeconds ?? DEFAULT_TTL_SECONDS2),
9012
- deviceSecret: config.deviceSecret
9013
- });
9014
- const tokenBody = await request("/auth/token", {
9015
- method: "POST",
9016
- headers: { "Content-Type": "application/json", Accept: "application/json" },
9017
- body: JSON.stringify({
9018
- auth_method: "account_proof",
9019
- public_key: session.publicKey,
9020
- client_name: config.clientName ?? audienceLabel(config.audience),
9021
- timestamp: issuedAt,
9022
- provider_data: {
9023
- challenge,
9024
- login_statement: statement,
9025
- account_proof: config.accountProof
9026
- }
9027
- })
9028
- });
9029
- const accessToken = tokenBody.access_token ?? tokenBody.data?.access_token;
9030
- const refreshToken = tokenBody.refresh_token ?? tokenBody.data?.refresh_token;
9031
- if (!accessToken) {
9032
- throw new Error("the node minted no session");
9033
- }
9034
- return {
9035
- accessToken,
9036
- refreshToken: refreshToken ?? "",
9037
- sessionKey: session.publicKey,
9038
- sessionSecret: session.secret
9039
- };
9040
- }
9041
-
9042
10363
  // src/nodeDiscovery.ts
9043
10364
  var DEFAULT_LOCAL_NODE_PORTS = [2428, 2429, 2528, 2529];
9044
10365
  var LOCAL_HOST = "localhost";
@@ -9091,6 +10412,102 @@ async function discoverLocalNodes(options = {}) {
9091
10412
  );
9092
10413
  return results.filter((url) => url !== null);
9093
10414
  }
10415
+
10416
+ // src/relay-attestation/attest-node-key.ts
10417
+ var KEY_BINDING_DOMAIN = new TextEncoder().encode("calimero.tee-attest.key-binding.v1");
10418
+ var MOCK_QUOTE_HEADER = new TextEncoder().encode("MOCK_TDX_QUOTE_V1");
10419
+ var TDX_REPORT_DATA_OFFSET = 48 + 520;
10420
+ function concat2(...parts) {
10421
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
10422
+ let at = 0;
10423
+ for (const p of parts) {
10424
+ out.set(p, at);
10425
+ at += p.length;
10426
+ }
10427
+ return out;
10428
+ }
10429
+ function equal2(a, b) {
10430
+ if (a.length !== b.length) return false;
10431
+ let diff = 0;
10432
+ for (let i = 0; i < a.length; i += 1) diff |= a[i] ^ b[i];
10433
+ return diff === 0;
10434
+ }
10435
+ function fromBase643(b64) {
10436
+ const bin = atob(b64);
10437
+ const out = new Uint8Array(bin.length);
10438
+ for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);
10439
+ return out;
10440
+ }
10441
+ function fromHex32(value, label2) {
10442
+ if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value)) {
10443
+ throw new Error(`${label2} must be 64 hex characters`);
10444
+ }
10445
+ const out = new Uint8Array(32);
10446
+ for (let i = 0; i < 32; i += 1) out[i] = Number.parseInt(value.slice(i * 2, i * 2 + 2), 16);
10447
+ return out;
10448
+ }
10449
+ async function attestKeyBinding(nodeKey) {
10450
+ const digest = await crypto.subtle.digest(
10451
+ "SHA-256",
10452
+ concat2(KEY_BINDING_DOMAIN, new Uint8Array(32), nodeKey)
10453
+ );
10454
+ return new Uint8Array(digest);
10455
+ }
10456
+ function reportDataOf(quote) {
10457
+ const mock = quote.length >= MOCK_QUOTE_HEADER.length && equal2(quote.subarray(0, MOCK_QUOTE_HEADER.length), MOCK_QUOTE_HEADER);
10458
+ const at = mock ? MOCK_QUOTE_HEADER.length : TDX_REPORT_DATA_OFFSET;
10459
+ if (quote.length < at + 64) {
10460
+ throw new Error(`the quote is too short to carry report data (${quote.length} bytes)`);
10461
+ }
10462
+ return { reportData: quote.slice(at, at + 64), mock };
10463
+ }
10464
+ async function attestRelayNodeKey(opts) {
10465
+ const nonce2 = crypto.getRandomValues(new Uint8Array(32));
10466
+ const url = `${opts.relayUrl.replace(/\/+$/, "")}/admin-api/tee/attest`;
10467
+ const body = JSON.stringify({
10468
+ nonce: hex(nonce2),
10469
+ bindNodeKey: true,
10470
+ ...opts.verify?.includeCollateral ? { includeCollateral: true } : {}
10471
+ });
10472
+ const init = { method: "POST", headers: { "Content-Type": "application/json" }, body };
10473
+ const response = opts.fetch ? await opts.fetch(url, init) : await globalThis.fetch(url, init);
10474
+ if (!response.ok) {
10475
+ const text = await response.text().catch(() => "");
10476
+ throw new Error(`the relay would not attest (HTTP ${response.status})${text ? `: ${text}` : ""}`);
10477
+ }
10478
+ const parsed = await response.json();
10479
+ const data = parsed.data ?? parsed;
10480
+ if (typeof data.quoteB64 !== "string") throw new Error("the relay returned no quote");
10481
+ const nodeKey = fromHex32(data.boundPublicKey, "boundPublicKey");
10482
+ const quote = fromBase643(data.quoteB64);
10483
+ const { reportData, mock } = reportDataOf(quote);
10484
+ if (mock) {
10485
+ if (!opts.allowMock) {
10486
+ throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware");
10487
+ }
10488
+ } else if (opts.verify) {
10489
+ const accepted = await opts.verify({
10490
+ quoteB64: data.quoteB64,
10491
+ nonce: hex(nonce2),
10492
+ reportDataSuffix: hex(await attestKeyBinding(nodeKey)),
10493
+ ...data.collateral ? { collateral: data.collateral } : {}
10494
+ });
10495
+ if (!accepted) {
10496
+ throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request");
10497
+ }
10498
+ } else if (opts.verifyQuote) {
10499
+ await opts.verifyQuote(quote);
10500
+ } else {
10501
+ throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");
10502
+ }
10503
+ if (!equal2(reportData.subarray(0, 32), nonce2)) {
10504
+ throw new Error("the quote does not carry our nonce: it was not made for this request");
10505
+ }
10506
+ if (!equal2(reportData.subarray(32, 64), await attestKeyBinding(nodeKey))) {
10507
+ throw new Error("the quote does not bind the key the relay named: refusing it");
10508
+ }
10509
+ return { nodeKey: hex(nodeKey), mock };
10510
+ }
9094
10511
  export {
9095
10512
  AdminApiClient,
9096
10513
  AuthApiClient,
@@ -9103,12 +10520,18 @@ export {
9103
10520
  EphemeralClient,
9104
10521
  HANDSHAKE_PATH,
9105
10522
  HTTPError,
10523
+ INVITED_ROLE,
9106
10524
  IntentRefusedError,
9107
10525
  LocalStorageTokenStore,
10526
+ MAX_INVITATION_VALIDITY_SECS,
9108
10527
  MemoryTokenStore,
10528
+ MeroClient,
9109
10529
  MeroJs,
9110
10530
  NODE_RELEASE_SIGNER,
10531
+ REQUEST_PROOF_HEADER,
9111
10532
  RelayClient,
10533
+ RelayObserver,
10534
+ RelayTransport,
9112
10535
  RpcClient,
9113
10536
  RpcError,
9114
10537
  SEALED_CONTENT_TYPE,
@@ -9117,21 +10540,36 @@ export {
9117
10540
  SealedTransportError,
9118
10541
  SseClient,
9119
10542
  StaleTransportKeyError,
10543
+ WarrantNonceExhaustedError,
10544
+ WarrantNonceRouteUnavailableError,
9120
10545
  WebHttpClient,
9121
10546
  WsClient,
9122
10547
  accountForRoot,
10548
+ accountForRootPublicKey,
9123
10549
  accountRootFromPhrase,
9124
10550
  accountRootFromSecret,
10551
+ accountRootSignerFromPhrase,
9125
10552
  admitterAddrsFromNetworkStatus,
10553
+ attestKeyBinding,
10554
+ attestRelayNodeKey,
10555
+ authorNonceLookup,
10556
+ beginCloudLink,
10557
+ beginDeviceEnrolment,
9126
10558
  buildAuthLoginUrl,
10559
+ callbackIsForeign,
9127
10560
  callerProof,
9128
10561
  capMask,
9129
10562
  capNames,
9130
10563
  classifyError,
10564
+ cloudLinkUrl,
9131
10565
  cloudNodeReleaseUrl,
9132
10566
  combineSignals,
9133
10567
  compareSemver,
10568
+ completeCloudLink,
10569
+ completeDeviceEnrolment,
9134
10570
  connectCloud,
10571
+ connectCloudWithAccount,
10572
+ createAccountRootSigner,
9135
10573
  createAdminApiClient,
9136
10574
  createAdminApiClientFromHttpClient,
9137
10575
  createAttestedSealedFetch,
@@ -9143,12 +10581,15 @@ export {
9143
10581
  createHttpClient,
9144
10582
  createLocalStorageNonceSource,
9145
10583
  createMemoryNonceSource,
10584
+ createMeroClient,
9146
10585
  createMeroJs,
9147
10586
  createNodeAdminApiClient,
9148
10587
  createNodeAuthApiClient,
9149
10588
  createNodeHttpClient,
10589
+ createProofAuthorizer,
9150
10590
  createProofSigner,
9151
10591
  createQuoteVerifier,
10592
+ createRecoveringNonceSource,
9152
10593
  createRetryableMethod,
9153
10594
  createSealedFetch,
9154
10595
  createSignedReleaseSealedFetch,
@@ -9156,9 +10597,14 @@ export {
9156
10597
  createTimeoutSignal,
9157
10598
  createUniversalHttpClient,
9158
10599
  creationInitHash,
10600
+ defaultAdmitters,
10601
+ defaultAudience,
9159
10602
  defaultCapabilitiesSetOp,
9160
10603
  deviceCertPayload,
10604
+ deviceEnrolmentUrl,
10605
+ deviceScopePayload,
9161
10606
  discoverLocalNodes,
10607
+ encodeGroupInvitation,
9162
10608
  encodeSignedInvitation,
9163
10609
  fetchAttestedTransportKey,
9164
10610
  fetchNodeRelease,
@@ -9169,6 +10615,7 @@ export {
9169
10615
  governanceOpHash,
9170
10616
  groupCreatedOp,
9171
10617
  groupDeletedOp,
10618
+ groupInvitationHash,
9172
10619
  groupReparentedOp,
9173
10620
  hasCap,
9174
10621
  hexEncodeUtf8,
@@ -9187,27 +10634,39 @@ export {
9187
10634
  nodeReleaseVersionFromImage,
9188
10635
  parseAuthCallback,
9189
10636
  parseCreationWarrant,
10637
+ parseDeviceCredential,
9190
10638
  parseGovernanceWarrant,
10639
+ parseWarrantNonce,
9191
10640
  probeNodeHealth,
10641
+ readCloudLinkCallback,
10642
+ readEnrolmentCallback,
9192
10643
  redeemInvitation,
10644
+ reportDataOf,
9193
10645
  requestBodyHash,
10646
+ resolveRoot,
10647
+ resolveRootPair,
9194
10648
  routingProofHeaders,
9195
10649
  shouldRetain,
9196
10650
  signAccountLink,
9197
10651
  signAccountLogin,
9198
10652
  signCreationWarrant,
9199
10653
  signDeviceCert,
10654
+ signDeviceScope,
9200
10655
  signGovernanceWarrant,
10656
+ signGroupInvitation,
9201
10657
  signLoginStatement,
9202
10658
  signMemberJoinOp,
9203
10659
  signRequest,
10660
+ signRequestProof,
9204
10661
  signRoutingChallenge,
9205
10662
  signWarrant,
10663
+ signedPath,
9206
10664
  signerFromCryptoKey,
9207
10665
  signerFromSecret,
9208
10666
  transportKeyBinding,
9209
10667
  trustSignedRelease,
9210
10668
  trustedMeasurementsFromReleases,
10669
+ verifyDeviceCredential,
9211
10670
  verifySignedNodeRelease,
9212
10671
  withCap,
9213
10672
  withRetry,