keymaster-connect 0.1.3 → 0.1.5

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/server.js CHANGED
@@ -1,4 +1,6 @@
1
- import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-W2TNWBLP.js';
1
+ import { isAiToolMessage, parseToolDefinitions, validateToolArguments, assertToolPayload } from './chunk-VVOTW5ZT.js';
2
+ export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-VVOTW5ZT.js';
3
+ import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-ZDIFZJYD.js';
2
4
  import { secp256k1 } from '@noble/curves/secp256k1.js';
3
5
  import { sha256 } from '@noble/hashes/sha2.js';
4
6
 
@@ -207,53 +209,31 @@ function assertOriginMatches(aud, eventOrigin) {
207
209
  throw new ProtocolValidationError("invalid_origin", "aud does not match event origin");
208
210
  }
209
211
  }
210
- function validatePaymentPayParams(raw, network) {
212
+ function validatePaymentPayParams(raw) {
211
213
  const obj = expectObject(raw, "payment.pay params");
212
- const allowed = ["channelId", "clientRequestId", "paymentType", "businessKind", "amountSatoshis", "feeRateSatoshisPerKb", "recipient"];
214
+ const allowed = ["clientRequestId", "outputs"];
213
215
  for (const key of Object.keys(obj))
214
216
  if (!allowed.includes(key))
215
217
  throw new ProtocolValidationError("invalid_request", "payment.pay contains an unsupported field");
216
218
  const clientRequestId = expectNonEmptyString(obj.clientRequestId, "clientRequestId");
217
219
  if (clientRequestId.length > 128 || !/^[A-Za-z0-9._:-]+$/u.test(clientRequestId))
218
220
  throw new ProtocolValidationError("invalid_request", "clientRequestId is invalid");
219
- const paymentType = obj.paymentType;
220
- if (paymentType !== "p2pkh" && paymentType !== "p2pk")
221
- throw new ProtocolValidationError("invalid_request", "paymentType is unsupported");
222
- const businessKind = expectNonEmptyString(obj.businessKind, "businessKind");
223
- if (businessKind.length > 64 || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(businessKind))
224
- throw new ProtocolValidationError("invalid_request", "businessKind is invalid");
225
- const recipient = expectObject(obj.recipient, "recipient");
226
- if (paymentType === "p2pkh") {
227
- if (recipient.type !== "p2pkh")
228
- throw new ProtocolValidationError("invalid_request", "recipient.type must match paymentType");
229
- for (const key of Object.keys(recipient))
230
- if (key !== "type" && key !== "address")
231
- throw new ProtocolValidationError("invalid_request", "recipient contains an unsupported field");
232
- const address = expectString(recipient.address, "recipient.address");
233
- const assetId = network === "test" ? "bsv-testnet" : "bsv-mainnet";
234
- assertP2pkhAddressForAsset(address, assetId ?? "bsv-mainnet");
235
- } else {
236
- if (recipient.type !== "p2pk")
237
- throw new ProtocolValidationError("invalid_request", "recipient.type must match paymentType");
238
- for (const key of Object.keys(recipient))
239
- if (key !== "type" && key !== "publicKeyHex")
240
- throw new ProtocolValidationError("invalid_request", "recipient contains an unsupported field");
241
- assertCompressedPubkeyHex(expectString(recipient.publicKeyHex, "recipient.publicKeyHex"));
242
- }
243
- const amountSatoshis = expectPositiveInteger(obj.amountSatoshis, "amountSatoshis");
244
- let feeRateSatoshisPerKb;
245
- if (obj.feeRateSatoshisPerKb !== void 0)
246
- feeRateSatoshisPerKb = expectPositiveInteger(obj.feeRateSatoshisPerKb, "feeRateSatoshisPerKb");
247
- const channelId = expectPaymentChannelId(obj.channelId);
248
- return {
249
- channelId,
250
- clientRequestId,
251
- paymentType,
252
- businessKind,
253
- amountSatoshis,
254
- ...feeRateSatoshisPerKb === void 0 ? {} : { feeRateSatoshisPerKb },
255
- recipient: paymentType === "p2pkh" ? { type: "p2pkh", address: expectString(recipient.address, "recipient.address") } : { type: "p2pk", publicKeyHex: expectString(recipient.publicKeyHex, "recipient.publicKeyHex").toLowerCase() }
256
- };
221
+ if (!Array.isArray(obj.outputs) || obj.outputs.length === 0)
222
+ throw new ProtocolValidationError("invalid_request", "outputs must be a non-empty array");
223
+ const outputs = obj.outputs.map((entry, index) => {
224
+ const item = expectObject(entry, `outputs[${index}]`);
225
+ for (const key of Object.keys(item))
226
+ if (key !== "amount" && key !== "script")
227
+ throw new ProtocolValidationError("invalid_request", `outputs[${index}] contains an unsupported field`);
228
+ const amount = item.amount;
229
+ if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount < 0)
230
+ throw new ProtocolValidationError("invalid_request", `outputs[${index}].amount must be a non-negative safe integer`);
231
+ const script = expectString(item.script, `outputs[${index}].script`);
232
+ if (script.length % 2 !== 0 || !/^[0-9a-fA-F]*$/u.test(script))
233
+ throw new ProtocolValidationError("invalid_request", `outputs[${index}].script must be even-length hex`);
234
+ return { amount, script: script.toLowerCase() };
235
+ });
236
+ return { clientRequestId, outputs };
257
237
  }
258
238
  function validatePaymentStatusParams(raw) {
259
239
  const obj = expectObject(raw, "payment.status params");
@@ -265,21 +245,6 @@ function validatePaymentStatusParams(raw) {
265
245
  throw new ProtocolValidationError("invalid_request", "clientRequestId is invalid");
266
246
  return { clientRequestId };
267
247
  }
268
- function expectPaymentChannelId(raw) {
269
- const id = expectNonEmptyString(raw, "channelId");
270
- if (id.length > 96 || !/^[a-z][a-z0-9.-]+$/.test(id))
271
- throw new ProtocolValidationError("invalid_request", "Invalid payment channelId");
272
- return id;
273
- }
274
- function validatePaymentChannelRegisterParams(raw) {
275
- const obj = expectObject(raw, "payment.channel.register params");
276
- const channelName = expectNonEmptyString(obj.channelName, "channelName");
277
- if (!/^[a-z][a-z0-9.-]{0,31}$/.test(channelName))
278
- throw new ProtocolValidationError("invalid_request", "Invalid channelName");
279
- if (obj.paymentType !== "p2pkh" && obj.paymentType !== "p2pk")
280
- throw new ProtocolValidationError("invalid_request", "Unsupported paymentType");
281
- return { channelName, paymentType: obj.paymentType };
282
- }
283
248
  function validateConnectLoginParams(raw) {
284
249
  const obj = expectObject(raw, "connect.login params");
285
250
  for (const key of Object.keys(obj))
@@ -591,12 +556,6 @@ function assertCompressedPubkeyHex(hex2) {
591
556
  throw new ProtocolValidationError("invalid_request", "counterpartyPublicKeyHex must be hex");
592
557
  }
593
558
  }
594
- function expectPositiveInteger(v, name) {
595
- if (typeof v !== "number" || !Number.isInteger(v) || v <= 0) {
596
- throw new ProtocolValidationError("invalid_request", `${name} must be a positive integer`);
597
- }
598
- return v;
599
- }
600
559
  function expectNonEmptyString(v, name) {
601
560
  if (typeof v !== "string" || v.length === 0) {
602
561
  throw new ProtocolValidationError("invalid_request", `${name} must be a non-empty string`);
@@ -706,15 +665,14 @@ function parseRequestMessage(raw, receiverIdentity) {
706
665
  const id = expectNonEmptyString(value.id, "Request id");
707
666
  if (["networkIdentity", "walletPublicKeyHex"].some((field) => field in value)) throw new ProtocolValidationError("invalid_request", "Wallet selectors have been removed");
708
667
  if (typeof value.method !== "string") throw new ProtocolValidationError("invalid_request", "Unknown method");
709
- if (value.method === "feepool.prepare" || value.method === "feepool.commit" || value.method === "p2pkh.transfer") throw new ProtocolValidationError("unsupported_scope", "Method is outside Connect v1 scope");
668
+ if (value.method === "feepool.prepare" || value.method === "feepool.commit" || value.method === "p2pkh.transfer" || value.method === "payment.channel.register") throw new ProtocolValidationError("unsupported_scope", "Method is outside Connect v1 scope");
710
669
  if (!PROTOCOL_METHODS.includes(value.method)) throw new ProtocolValidationError("invalid_request", "Unknown method");
711
670
  const params = expectObject(value.params, "Params");
712
671
  for (const field of ["walletPublicKeyHex", "networkIdentity", "bsvNetwork", "assetId"]) {
713
672
  if (field in params) throw new ProtocolValidationError("invalid_request", `Removed wallet selector: ${field}`);
714
673
  }
715
674
  const method = value.method;
716
- if (method === "payment.channel.register" && params.paymentType === "feepool.connect") throw new ProtocolValidationError("unsupported_scope", "Connect v1 does not create fee-pool channels");
717
- const identity = validateNetworkIdentity(receiverIdentity);
675
+ validateNetworkIdentity(receiverIdentity);
718
676
  let normalized;
719
677
  switch (method) {
720
678
  case "connect.login":
@@ -742,14 +700,11 @@ function parseRequestMessage(raw, receiverIdentity) {
742
700
  normalized = validateCipherDecryptParams(params);
743
701
  break;
744
702
  case "payment.pay":
745
- normalized = validatePaymentPayParams(params, identity.bsvNetwork);
703
+ normalized = validatePaymentPayParams(params);
746
704
  break;
747
705
  case "payment.status":
748
706
  normalized = validatePaymentStatusParams(params);
749
707
  break;
750
- case "payment.channel.register":
751
- normalized = validatePaymentChannelRegisterParams(params);
752
- break;
753
708
  case "channel.publish":
754
709
  normalized = validateChannelPublishParams(params);
755
710
  break;
@@ -765,9 +720,11 @@ function parseRequestMessage(raw, receiverIdentity) {
765
720
  case "storage.directory.delete":
766
721
  normalized = validateStorageDirectoryParams(params, method, false);
767
722
  break;
723
+ case "storage.encrypted.put":
768
724
  case "storage.put":
769
725
  normalized = validateStoragePutParams(params);
770
726
  break;
727
+ case "storage.encrypted.get":
771
728
  case "storage.get":
772
729
  normalized = validateStorageGetParams(params);
773
730
  break;
@@ -789,6 +746,110 @@ function parseRequestMessage(raw, receiverIdentity) {
789
746
  return { id, method, params: normalized };
790
747
  }
791
748
 
749
+ // src/toolReceiver.ts
750
+ var KeymasterAiToolReceiver = class {
751
+ constructor(options) {
752
+ this.options = options;
753
+ }
754
+ options;
755
+ definitions = [];
756
+ bindingId = null;
757
+ pending = /* @__PURE__ */ new Map();
758
+ disposed = false;
759
+ /** Host calls on connection changes; revoke stale in-flight calls without replay. */
760
+ sync() {
761
+ if (this.bindingId && !this.options.isCurrent(this.bindingId)) this.clear();
762
+ }
763
+ list() {
764
+ return !this.disposed && this.bindingId && this.options.isCurrent(this.bindingId) ? structuredClone(this.definitions) : [];
765
+ }
766
+ available(name) {
767
+ return this.list().some((tool) => tool.name === name);
768
+ }
769
+ handle(value) {
770
+ if (this.disposed || !isAiToolMessage(value)) return false;
771
+ if (!this.options.isCurrent(value.bindingId)) return true;
772
+ if (value.type === "tools.register") {
773
+ try {
774
+ const definitions = parseToolDefinitions(value.tools);
775
+ if (this.pending.size && definitions.length) throw new Error("Cannot replace tools while calls are pending");
776
+ if (!definitions.length && this.pending.size) this.clear();
777
+ const names = this.options.names(definitions);
778
+ this.options.send({ v: 1, type: "tools.registered", bindingId: value.bindingId, id: value.id, ok: true, names });
779
+ this.definitions = definitions;
780
+ this.bindingId = value.bindingId;
781
+ this.options.changed();
782
+ } catch {
783
+ this.options.send({ v: 1, type: "tools.registered", bindingId: value.bindingId, id: value.id, ok: false, error: "Tool registration rejected: invalid schema, conflicting live connection or pending invocation" });
784
+ }
785
+ } else if (value.type === "tools.result") {
786
+ const pending = this.pending.get(value.id);
787
+ if (!pending || pending.bindingId !== value.bindingId) return true;
788
+ pending.cleanup();
789
+ this.pending.delete(value.id);
790
+ if (value.ok) pending.resolve(value.result);
791
+ else pending.reject(new Error(`App tool failed: ${value.error}`));
792
+ }
793
+ return true;
794
+ }
795
+ invoke(name, args, signal, timeoutMs = 12e4) {
796
+ const tool = this.list().find((tool2) => tool2.name === name), bindingId = this.bindingId;
797
+ if (!tool || !bindingId) return Promise.reject(new Error("App tool is offline"));
798
+ if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Tool call aborted"));
799
+ if (this.pending.size >= 16) return Promise.reject(new Error("Too many pending tool calls"));
800
+ validateToolArguments(args, tool.parameters);
801
+ const id = this.options.randomUUID?.() ?? crypto.randomUUID();
802
+ return new Promise((resolve, reject) => {
803
+ const fail = (error) => {
804
+ const pending = this.pending.get(id);
805
+ if (!pending) return;
806
+ pending.cleanup();
807
+ this.pending.delete(id);
808
+ if (this.options.isCurrent(bindingId)) {
809
+ try {
810
+ this.options.send({ v: 1, type: "tools.cancel", bindingId, id });
811
+ } catch {
812
+ }
813
+ }
814
+ reject(error);
815
+ };
816
+ const abort = () => fail(new Error("App tool cancelled; side effects may already have occurred"));
817
+ const timer = setTimeout(() => fail(new Error("App tool timed out; outcome unknown, not retried")), timeoutMs);
818
+ signal.addEventListener("abort", abort, { once: true });
819
+ this.pending.set(id, { bindingId, resolve, reject, cleanup: () => {
820
+ clearTimeout(timer);
821
+ signal.removeEventListener("abort", abort);
822
+ } });
823
+ try {
824
+ const message = { v: 1, type: "tools.invoke", bindingId, id, name, arguments: structuredClone(args) };
825
+ assertToolPayload(message);
826
+ this.options.send(message);
827
+ } catch {
828
+ fail(new Error("Unable to deliver App tool call; outcome unknown"));
829
+ }
830
+ });
831
+ }
832
+ clear() {
833
+ for (const [id, pending] of this.pending) {
834
+ try {
835
+ this.options.send({ v: 1, type: "tools.cancel", bindingId: pending.bindingId, id });
836
+ } catch {
837
+ }
838
+ pending.cleanup();
839
+ pending.reject(new Error("App connection lost; tool outcome unknown, not retried"));
840
+ }
841
+ this.pending.clear();
842
+ this.definitions = [];
843
+ this.bindingId = null;
844
+ this.options.changed();
845
+ }
846
+ dispose() {
847
+ if (this.disposed) return;
848
+ this.disposed = true;
849
+ this.clear();
850
+ }
851
+ };
852
+
792
853
  // src/server.ts
793
854
  function isEstablishing(method) {
794
855
  return ["connect.login", "connect.resume", "connect.launch"].includes(method);
@@ -796,7 +857,14 @@ function isEstablishing(method) {
796
857
  function parseReconnectMessage(data) {
797
858
  if (!data || typeof data !== "object") return null;
798
859
  const value = data;
799
- if (value.v !== PROTOCOL_VERSION || value.type !== "reconnect" || typeof value.id !== "string" || !value.id || value.id.length > 128 || typeof value.authorizationId !== "string" || !value.authorizationId || value.authorizationId.length > 128 || value.bindingId !== void 0 && typeof value.bindingId !== "string" || Object.keys(value).some((key) => !["v", "type", "id", "authorizationId", "bindingId"].includes(key))) return null;
860
+ if (value.v !== PROTOCOL_VERSION || value.type !== "reconnect" || typeof value.id !== "string" || !value.id || value.id.length > 128 || typeof value.authorizationId !== "string" || !value.authorizationId || value.authorizationId.length > 128 || value.bindingId !== void 0 && typeof value.bindingId !== "string" || Object.keys(value).some((key) => !["v", "type", "id", "authorizationId", "bindingId", "appIdentity"].includes(key))) return null;
861
+ if (value.appIdentity !== void 0) {
862
+ try {
863
+ verifyAppIdentityProof(value.appIdentity);
864
+ } catch {
865
+ return null;
866
+ }
867
+ }
800
868
  return value;
801
869
  }
802
870
  var KeymasterConnectReceiver = class {
@@ -835,7 +903,7 @@ var KeymasterConnectReceiver = class {
835
903
  async accept(event) {
836
904
  if (!this.isAllowedPeer(event)) return null;
837
905
  const reconnect = parseReconnectMessage(event.data);
838
- const raw = reconnect ? { v: PROTOCOL_VERSION, type: "request", id: reconnect.id, method: "connect.resume", params: {} } : event.data;
906
+ const raw = reconnect ? { v: PROTOCOL_VERSION, type: "request", id: reconnect.id, method: "connect.resume", params: reconnect.appIdentity ? { appIdentity: reconnect.appIdentity } : {} } : event.data;
839
907
  if (!raw || typeof raw !== "object" || raw.type !== "request") return null;
840
908
  if (typeof raw.id === "string" && this.pending.get(event.source)?.has(raw.id)) return null;
841
909
  try {
@@ -915,8 +983,14 @@ var KeymasterConnectReceiver = class {
915
983
  const connected = result;
916
984
  if (!sameNetworkIdentity(validateNetworkIdentity(connected.networkIdentity), context.networkIdentity) || "walletPublicKeyHex" in connected || "ownerPublicKeyHex" in connected) throw new ProtocolValidationError("invalid_request", "Invalid public connection result");
917
985
  publicResult = { ...result, networkIdentity: context.networkIdentity };
918
- bindingId = this.options.randomUUID?.() || crypto.randomUUID();
919
- this.bindings.set(context.source, { id: bindingId, origin: context.origin, identity: context.networkIdentity, walletGeneration: context.walletGeneration, runGeneration: context.runGeneration });
986
+ const existing = this.bindings.get(context.source);
987
+ const reusable = context.method === "connect.resume" && existing && existing.origin === context.origin && existing.walletGeneration === context.walletGeneration && existing.runGeneration === context.runGeneration && sameNetworkIdentity(existing.identity, context.networkIdentity);
988
+ if (reusable) {
989
+ bindingId = existing.id;
990
+ } else {
991
+ bindingId = this.options.randomUUID?.() || crypto.randomUUID();
992
+ this.bindings.set(context.source, { id: bindingId, origin: context.origin, identity: context.networkIdentity, walletGeneration: context.walletGeneration, runGeneration: context.runGeneration });
993
+ }
920
994
  }
921
995
  this.finish(context);
922
996
  if (context.method === "connect.logout") this.bindings.delete(context.source);
@@ -993,6 +1067,6 @@ var KeymasterConnectReceiver = class {
993
1067
  }
994
1068
  };
995
1069
 
996
- export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
1070
+ export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterAiToolReceiver, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
997
1071
  //# sourceMappingURL=server.js.map
998
1072
  //# sourceMappingURL=server.js.map