@calimero-network/mero-js 23.2.0 → 23.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -39,9 +39,11 @@ __export(index_exports, {
39
39
  MeroJs: () => MeroJs,
40
40
  NODE_RELEASE_SIGNER: () => NODE_RELEASE_SIGNER,
41
41
  OWNER_OP_KIND: () => OWNER_OP_KIND,
42
+ PRESENCE_DOMAIN: () => PRESENCE_DOMAIN,
42
43
  REQUEST_PROOF_HEADER: () => REQUEST_PROOF_HEADER,
43
44
  RelayClient: () => RelayClient,
44
45
  RelayObserver: () => RelayObserver,
46
+ RelayPresenceClient: () => RelayPresenceClient,
45
47
  RelayTransport: () => RelayTransport,
46
48
  RpcClient: () => RpcClient,
47
49
  RpcError: () => RpcError,
@@ -161,6 +163,7 @@ __export(index_exports, {
161
163
  parseDeviceCredential: () => parseDeviceCredential,
162
164
  parseGovernanceWarrant: () => parseGovernanceWarrant,
163
165
  parseWarrantNonce: () => parseWarrantNonce,
166
+ presenceStatementBytes: () => presenceStatementBytes,
164
167
  probeNodeHealth: () => probeNodeHealth,
165
168
  readCloudLinkCallback: () => readCloudLinkCallback,
166
169
  readEnrolmentCallback: () => readEnrolmentCallback,
@@ -190,8 +193,11 @@ __export(index_exports, {
190
193
  signedPath: () => signedPath,
191
194
  signerFromCryptoKey: () => signerFromCryptoKey,
192
195
  signerFromSecret: () => signerFromSecret,
196
+ stateHash: () => stateHash,
193
197
  subgroupCreation: () => subgroupCreation,
194
198
  subgroupVisibilitySetOp: () => subgroupVisibilitySetOp,
199
+ subscribePresence: () => subscribePresence,
200
+ targetApplicationSetOp: () => targetApplicationSetOp,
195
201
  teeAdmissionPolicyOp: () => teeAdmissionPolicyOp,
196
202
  teeAuthoringPolicyOp: () => teeAuthoringPolicyOp,
197
203
  teeReleaseAdmissionPolicyOp: () => teeReleaseAdmissionPolicyOp,
@@ -3501,28 +3507,32 @@ var EphemeralClient = class {
3501
3507
  * and zero mean different things). Returns an unsubscribe function.
3502
3508
  */
3503
3509
  subscribe(contextId, handler, codec = jsonCodec()) {
3504
- const listener = (event) => {
3505
- const e = event;
3506
- if (e.type !== "Ephemeral" || e.contextId !== contextId) return;
3507
- const data = e.data;
3508
- if (!data?.author) return;
3509
- const removed = Boolean(data.removed);
3510
- const entry = {
3511
- author: data.author,
3512
- state: removed || data.state === void 0 ? void 0 : codec.decode(data.state),
3513
- removed
3514
- };
3515
- if (data.ageMs !== void 0) entry.ageMs = data.ageMs;
3516
- handler(entry);
3517
- };
3518
- this.sse.on("event", listener);
3519
- void this.sse.connect().catch(() => void 0);
3520
- void this.sse.subscribe([contextId]).catch(() => void 0);
3521
- return () => {
3522
- this.sse.off("event", listener);
3523
- };
3510
+ return subscribePresence(this.sse, contextId, handler, codec);
3524
3511
  }
3525
3512
  };
3513
+ function subscribePresence(sse, contextId, handler, codec = jsonCodec()) {
3514
+ const listener = (event) => {
3515
+ const e = event;
3516
+ if (e.type !== "Ephemeral" || e.contextId !== contextId) return;
3517
+ const data = e.data;
3518
+ if (!data?.author) return;
3519
+ const removed = Boolean(data.removed);
3520
+ const entry = {
3521
+ author: data.author,
3522
+ state: removed || data.state === void 0 ? void 0 : codec.decode(data.state),
3523
+ removed
3524
+ };
3525
+ if (data.ageMs !== void 0) entry.ageMs = data.ageMs;
3526
+ if (data.account !== void 0) entry.account = data.account;
3527
+ handler(entry);
3528
+ };
3529
+ sse.on("event", listener);
3530
+ void sse.connect().catch(() => void 0);
3531
+ void sse.subscribe([contextId]).catch(() => void 0);
3532
+ return () => {
3533
+ sse.off("event", listener);
3534
+ };
3535
+ }
3526
3536
 
3527
3537
  // src/signer/signer.ts
3528
3538
  var PKCS8_ED25519_PREFIX2 = new Uint8Array([
@@ -7614,6 +7624,7 @@ var GROUP_OP = {
7614
7624
  MemberRoleSet: 4,
7615
7625
  MemberCapabilitySet: 5,
7616
7626
  DefaultCapabilitiesSet: 6,
7627
+ TargetApplicationSet: 7,
7617
7628
  ContextDetached: 9,
7618
7629
  SubgroupVisibilitySet: 10,
7619
7630
  GroupMetadataSet: 11,
@@ -7687,6 +7698,23 @@ async function createdSubgroupId(admin, parentId, restricted, salt) {
7687
7698
  ])
7688
7699
  );
7689
7700
  }
7701
+ function borshString2(value, what) {
7702
+ if (value.length === 0) throw new Error(`${what} must not be empty`);
7703
+ const bytes = new TextEncoder().encode(value);
7704
+ return concat(u32le(bytes.length), bytes);
7705
+ }
7706
+ function targetApplicationSetOp(input) {
7707
+ return {
7708
+ kind: "group",
7709
+ bytes: concat(
7710
+ tag(GROUP_OP.TargetApplicationSet),
7711
+ CLEARED_HASH,
7712
+ fromHex(input.applicationId, "applicationId", 32),
7713
+ borshString2(input.package, "package"),
7714
+ borshString2(input.version, "version")
7715
+ )
7716
+ };
7717
+ }
7690
7718
  function defaultCapabilitiesSetOp(capabilities) {
7691
7719
  if (!Number.isInteger(capabilities) || capabilities < 0 || capabilities > 4294967295) {
7692
7720
  throw new Error(`capabilities must be a u32 bit mask, got ${String(capabilities)}`);
@@ -7948,6 +7976,19 @@ var RelayClient = class {
7948
7976
  );
7949
7977
  return { rootHash: body.data.rootHash, returns: body.data.returns ?? null };
7950
7978
  }
7979
+ /**
7980
+ * Publish one presence statement through the relay (`presence-intents`).
7981
+ *
7982
+ * Not retried on 429: presence resends every 2.5 s anyway, and a retry would
7983
+ * only queue behind the next resend. A refusal throws with its `status`.
7984
+ */
7985
+ async presenceIntent(contextId, body) {
7986
+ await this.jsonOnce(
7987
+ "POST",
7988
+ `/admin-api/contexts/${encodeURIComponent(contextId)}/presence-intents`,
7989
+ body
7990
+ );
7991
+ }
7951
7992
  /**
7952
7993
  * Ask the relay what it can do about creating contexts in `groupId`.
7953
7994
  *
@@ -8128,6 +8169,7 @@ var RelayClient = class {
8128
8169
  salt
8129
8170
  });
8130
8171
  const capabilitiesOp = input.defaultCapabilities === void 0 ? void 0 : defaultCapabilitiesSetOp(input.defaultCapabilities);
8172
+ const applicationOp = input.application ? targetApplicationSetOp(input.application) : void 0;
8131
8173
  const signer = await this.authorSigner();
8132
8174
  const nonce2 = await this.config.nonces.next();
8133
8175
  const ttl = this.config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
@@ -8147,17 +8189,25 @@ var RelayClient = class {
8147
8189
  teeEnabled: data.teeEnabled ?? false,
8148
8190
  ...data.teeError ? { teeError: data.teeError } : {}
8149
8191
  };
8150
- if (!capabilitiesOp) return founded;
8151
- try {
8152
- await this.govern({ groupId: founded.namespaceId, op: capabilitiesOp });
8153
- return { ...founded, defaultCapabilitiesSet: true };
8154
- } catch (err) {
8155
- return {
8156
- ...founded,
8157
- defaultCapabilitiesSet: false,
8158
- defaultCapabilitiesError: err instanceof Error ? err.message : String(err)
8159
- };
8192
+ let result = founded;
8193
+ const message = (err) => err instanceof Error ? err.message : String(err);
8194
+ if (applicationOp) {
8195
+ try {
8196
+ await this.govern({ groupId: founded.namespaceId, op: applicationOp });
8197
+ result = { ...result, applicationSet: true };
8198
+ } catch (err) {
8199
+ result = { ...result, applicationSet: false, applicationError: message(err) };
8200
+ }
8201
+ }
8202
+ if (capabilitiesOp) {
8203
+ try {
8204
+ await this.govern({ groupId: founded.namespaceId, op: capabilitiesOp });
8205
+ result = { ...result, defaultCapabilitiesSet: true };
8206
+ } catch (err) {
8207
+ result = { ...result, defaultCapabilitiesSet: false, defaultCapabilitiesError: message(err) };
8208
+ }
8160
8209
  }
8210
+ return result;
8161
8211
  }
8162
8212
  async postGovernance(groupId, op, warrant) {
8163
8213
  const body = await this.json("POST", `/admin-api/groups/${encodeURIComponent(groupId)}/governance-intents`, {
@@ -8249,6 +8299,7 @@ var RelayClient = class {
8249
8299
  text
8250
8300
  );
8251
8301
  }
8302
+ if (response.status === 204) return void 0;
8252
8303
  return await response.json();
8253
8304
  }
8254
8305
  };
@@ -8676,6 +8727,121 @@ function signedPath(url) {
8676
8727
  return new URL(url).pathname;
8677
8728
  }
8678
8729
 
8730
+ // src/presence/statement.ts
8731
+ var PRESENCE_DOMAIN = new TextEncoder().encode("calimero/presence/1");
8732
+ async function stateHash(state) {
8733
+ const borsh = state === null ? new Uint8Array([0]) : concat(new Uint8Array([1]), u32le(state.length), state);
8734
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", borsh));
8735
+ }
8736
+ async function presenceStatementBytes(input) {
8737
+ return concat(
8738
+ PRESENCE_DOMAIN,
8739
+ fromHex(input.contextId, "contextId", 32),
8740
+ fromHex(input.author, "author", 32),
8741
+ u64le(input.seq),
8742
+ u64le(input.sentAtMs),
8743
+ await stateHash(input.state)
8744
+ );
8745
+ }
8746
+
8747
+ // src/presence/relay-presence.ts
8748
+ var HEARTBEAT_MS = 2500;
8749
+ var RelayPresenceClient = class {
8750
+ /**
8751
+ * @param opts.events the relay's event stream, asked for only on `subscribe`:
8752
+ * publishing needs none, so a client with no node key can still publish.
8753
+ */
8754
+ constructor(opts) {
8755
+ this.timers = /* @__PURE__ */ new Map();
8756
+ this.lastSeq = /* @__PURE__ */ new Map();
8757
+ this.refused = /* @__PURE__ */ new Set();
8758
+ /**
8759
+ * Bumped by every `set` and `close`, per context. A `set` installs its
8760
+ * resends only if nothing newer happened while its first send was in flight,
8761
+ * so a retract (or a newer state) can never be overtaken by an older one.
8762
+ */
8763
+ this.generation = /* @__PURE__ */ new Map();
8764
+ this.relay = opts.relay;
8765
+ this.events = opts.events;
8766
+ this.heartbeatMs = opts.heartbeatMs ?? HEARTBEAT_MS;
8767
+ this.now = opts.now ?? Date.now;
8768
+ }
8769
+ /**
8770
+ * Set this account's presence in `contextId`, or retract it with `null`.
8771
+ * Throws when the relay refuses this first send for good (a 4xx other than
8772
+ * 429), which also stops the resends. A rate limit, a network failure or a
8773
+ * 5xx is not thrown: the next resend covers it.
8774
+ */
8775
+ async set(contextId, state, codec = jsonCodec()) {
8776
+ const generation = this.bump(contextId);
8777
+ this.refused.delete(contextId);
8778
+ const bytes = state === null ? null : new Uint8Array(codec.encode(state));
8779
+ await this.send(contextId, bytes);
8780
+ if (bytes === null || this.refused.has(contextId)) return;
8781
+ if (this.generation.get(contextId) !== generation) return;
8782
+ this.timers.set(
8783
+ contextId,
8784
+ setInterval(() => void this.send(contextId, bytes).catch(() => void 0), this.heartbeatMs)
8785
+ );
8786
+ }
8787
+ subscribe(contextId, handler, codec = jsonCodec()) {
8788
+ return subscribePresence(this.events(), contextId, handler, codec);
8789
+ }
8790
+ /** Stop every resend. Entries expire on the relay and its peers within 7 s. */
8791
+ close() {
8792
+ for (const contextId of /* @__PURE__ */ new Set([...this.timers.keys(), ...this.generation.keys()])) {
8793
+ this.bump(contextId);
8794
+ }
8795
+ }
8796
+ /** Stop the context's resends and invalidate any `set` still in flight. */
8797
+ bump(contextId) {
8798
+ this.stop(contextId);
8799
+ const next = (this.generation.get(contextId) ?? 0) + 1;
8800
+ this.generation.set(contextId, next);
8801
+ return next;
8802
+ }
8803
+ stop(contextId) {
8804
+ const timer = this.timers.get(contextId);
8805
+ if (timer !== void 0) clearInterval(timer);
8806
+ this.timers.delete(contextId);
8807
+ }
8808
+ /** Wall-clock seeded and strictly rising, so a relay restart never sees an old seq. */
8809
+ nextSeq(contextId) {
8810
+ const seq = Math.max(this.now(), (this.lastSeq.get(contextId) ?? 0) + 1);
8811
+ this.lastSeq.set(contextId, seq);
8812
+ return seq;
8813
+ }
8814
+ async send(contextId, state) {
8815
+ if (this.refused.has(contextId)) return;
8816
+ const signer = await this.relay.authorSigner();
8817
+ const seq = this.nextSeq(contextId);
8818
+ const sentAtMs = this.now();
8819
+ const statement = await presenceStatementBytes({
8820
+ contextId,
8821
+ author: signer.publicKey,
8822
+ seq: BigInt(seq),
8823
+ sentAtMs: BigInt(sentAtMs),
8824
+ state
8825
+ });
8826
+ const signature = hex(await signer.sign(statement));
8827
+ try {
8828
+ await this.relay.presenceIntent(contextId, {
8829
+ state: state === null ? null : hex(state),
8830
+ seq,
8831
+ sentAtMs,
8832
+ signature,
8833
+ authorProof: this.relay.authorProof
8834
+ });
8835
+ } catch (err) {
8836
+ const status = err.status;
8837
+ if (status === void 0 || status === 0 || status === 429 || status >= 500) return;
8838
+ this.refused.add(contextId);
8839
+ this.stop(contextId);
8840
+ throw err;
8841
+ }
8842
+ }
8843
+ };
8844
+
8679
8845
  // src/transport/mero-client.ts
8680
8846
  function relayHasNo(surface, why) {
8681
8847
  return new Error(
@@ -8719,6 +8885,7 @@ var MeroClient = class {
8719
8885
  this.proofAuthorizer = null;
8720
8886
  this.relayUrl = null;
8721
8887
  this.proofEvents = null;
8888
+ this.relayPresence = null;
8722
8889
  if (config.transport === "relay") {
8723
8890
  this.transport = "relay";
8724
8891
  this.nodeClient = null;
@@ -8873,26 +9040,19 @@ var MeroClient = class {
8873
9040
  /**
8874
9041
  * Ephemeral presence. Node transport only.
8875
9042
  *
8876
- * Not extended to the relay even though a logged-in session could reach both
8877
- * halves of it mechanically. Publishing resolves the author from an *owned
8878
- * context identity on the node*, and whether a delegated session has one has
8879
- * not been established — a presence client that silently published nothing,
8880
- * or published as the wrong identity, is worse than one that says it is not
8881
- * available. The read half is not lost: presence arrives on `client.events`
8882
- * like any other context event, and can be filtered there.
8883
- *
8884
- * The rejected alternative was to expose it over the relay session and let
8885
- * `set` fail at the node. That trades a clear construction-time answer for a
8886
- * runtime failure inside a UI that has already rendered.
9043
+ * On a relay client this is an account's presence client
9044
+ * ({@link RelayPresenceClient}): `set` signs each update with the device key
9045
+ * and posts it to the relay's `presence-intents`, resending every 2.5 s, and
9046
+ * `subscribe` reads the relay's event stream. The relay checks and forwards
9047
+ * the update; other members verify the device's signature and certificate
9048
+ * themselves, so it can drop or delay an account's presence but not invent or
9049
+ * alter it. Only `subscribe` needs the relay's node key (for the event
9050
+ * stream), so publishing works on any relay client.
8887
9051
  */
8888
9052
  get ephemeral() {
8889
- if (!this.nodeClient) {
8890
- throw relayHasNo(
8891
- "ephemeral presence",
8892
- "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"
8893
- );
8894
- }
8895
- return this.nodeClient.ephemeral;
9053
+ if (this.nodeClient) return this.nodeClient.ephemeral;
9054
+ this.relayPresence ?? (this.relayPresence = new RelayPresenceClient({ relay: this.relay, events: () => this.events }));
9055
+ return this.relayPresence;
8896
9056
  }
8897
9057
  /**
8898
9058
  * Calimero Cloud.
@@ -10697,7 +10857,7 @@ function optionalBytes32(value, label2) {
10697
10857
  }
10698
10858
  return concat(new Uint8Array([1]), new Uint8Array(value));
10699
10859
  }
10700
- function borshString2(value) {
10860
+ function borshString3(value) {
10701
10861
  const bytes = new TextEncoder().encode(value);
10702
10862
  return concat(u32le(bytes.length), bytes);
10703
10863
  }
@@ -10711,7 +10871,7 @@ function encodeSignedInvitation(signed) {
10711
10871
  // ...then the enclosing SignedGroupOpenInvitation, in declaration order.
10712
10872
  // `inviter_account` sits between the signature and the addresses; putting it
10713
10873
  // anywhere else still encodes 32 bytes and still verifies as nothing.
10714
- borshString2(signed.inviter_signature),
10874
+ borshString3(signed.inviter_signature),
10715
10875
  signed.inviter_account ? concat(new Uint8Array([1]), fromHex(signed.inviter_account, "inviter_account", 32)) : new Uint8Array([0]),
10716
10876
  // A `Vec<String>`, so each entry is a bare borsh string. This carried an
10717
10877
  // enum until core dropped the URL variant, and an enum writes a
@@ -10719,7 +10879,7 @@ function encodeSignedInvitation(signed) {
10719
10879
  // every following byte and fail as `invalid invitation signature`, pointing
10720
10880
  // nowhere near this line.
10721
10881
  u32le(admitterAddrs.length),
10722
- ...admitterAddrs.map(borshString2),
10882
+ ...admitterAddrs.map(borshString3),
10723
10883
  optionalBytes32(signed.application_id, "application_id"),
10724
10884
  // Borsh order follows core's field order, where this is `bytecode_id`; the
10725
10885
  // JSON key is `app_key`, a rename covering both directions that core pins in
@@ -10792,12 +10952,12 @@ var te = new TextEncoder();
10792
10952
  function tag2(byte) {
10793
10953
  return new Uint8Array([byte]);
10794
10954
  }
10795
- function borshString3(value) {
10955
+ function borshString4(value) {
10796
10956
  const bytes = te.encode(value);
10797
10957
  return concat(u32le(bytes.length), bytes);
10798
10958
  }
10799
10959
  function borshStrings(values) {
10800
- return concat(u32le(values.length), ...values.map(borshString3));
10960
+ return concat(u32le(values.length), ...values.map(borshString4));
10801
10961
  }
10802
10962
  function borshBool(value) {
10803
10963
  return tag2(value ? 1 : 0);
@@ -10851,7 +11011,7 @@ function teeAdmissionPolicyOp(input) {
10851
11011
  };
10852
11012
  }
10853
11013
  function teeReleaseAdmissionPolicyOp(input) {
10854
- const minRelease = input.minReleaseVersion === void 0 ? tag2(0) : concat(tag2(1), borshString3(input.minReleaseVersion));
11014
+ const minRelease = input.minReleaseVersion === void 0 ? tag2(0) : concat(tag2(1), borshString4(input.minReleaseVersion));
10855
11015
  return {
10856
11016
  kind: "teeReleaseAdmissionPolicy",
10857
11017
  plane: "group",