@unicitylabs/sphere-sdk 0.7.1 → 0.7.2

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.
@@ -2363,6 +2363,20 @@ declare function signMessage(privateKeyHex: string, message: string): string;
2363
2363
  * @returns `true` if the signature is valid and matches the expected public key
2364
2364
  */
2365
2365
  declare function verifySignedMessage(message: string, signature: string, expectedPubkey: string): boolean;
2366
+ /**
2367
+ * Recover the compressed secp256k1 public key from a signed message.
2368
+ *
2369
+ * Use this when the server needs to identify the signer (not just verify
2370
+ * a signature against a known pubkey). Combined with `sphere.resolve(pubkey)`
2371
+ * it gives a fully cryptographically-attributable identity for backend auth,
2372
+ * without trusting any client-supplied identifier claim.
2373
+ *
2374
+ * @param message - The plaintext that was signed
2375
+ * @param signature - 130-char hex (v + r + s) as produced by `signMessage`
2376
+ * @returns - Compressed 66-char hex pubkey
2377
+ * @throws - On malformed signature length or out-of-range recovery byte
2378
+ */
2379
+ declare function recoverPubkeyFromSignature(message: string, signature: string): string;
2366
2380
 
2367
2381
  /**
2368
2382
  * Result of an instant split send operation
@@ -6491,23 +6505,6 @@ type LegacyFileType = 'dat' | 'txt' | 'json' | 'mnemonic' | 'unknown';
6491
6505
  */
6492
6506
  type DecryptionProgressCallback = (iteration: number, total: number) => Promise<void> | void;
6493
6507
 
6494
- /**
6495
- * Compute the Unicity L3 DIRECT:// address that corresponds to a given
6496
- * compressed secp256k1 public key.
6497
- *
6498
- * Deterministic — the underlying primitive `UnmaskedPredicateReference.create`
6499
- * only uses the public key, so the private key is never needed. This lets
6500
- * a backend trust only one thing from the client (the chain pubkey, whose
6501
- * ownership the client proves via signature) and derive everything else
6502
- * locally. Closes the entire class of "client claims an identifier the
6503
- * server can't verify" bugs at the API level.
6504
- *
6505
- * @param chainPubkey 33-byte compressed secp256k1 pubkey, hex-encoded
6506
- * (66 chars, leading 02 or 03).
6507
- * @throws if chainPubkey doesn't match the compressed-secp256k1 format.
6508
- */
6509
- declare function computeDirectAddressFromChainPubkey(chainPubkey: string): Promise<string>;
6510
-
6511
6508
  declare function isValidNametag(nametag: string): boolean;
6512
6509
 
6513
6510
  /** Steps reported by the onProgress callback during wallet init/create/load/import */
@@ -6749,7 +6746,6 @@ interface SphereInitResult {
6749
6746
  /** Generated mnemonic (only if autoGenerate was used) */
6750
6747
  generatedMnemonic?: string;
6751
6748
  }
6752
-
6753
6749
  /**
6754
6750
  * Holds all per-address module instances.
6755
6751
  * Each HD address gets its own set so modules can run independently in background.
@@ -7996,4 +7992,4 @@ interface CheckNetworkHealthOptions {
7996
7992
  */
7997
7993
  declare function checkNetworkHealth(network?: NetworkType, options?: CheckNetworkHealthOptions): Promise<NetworkHealthResult>;
7998
7994
 
7999
- export { type AddressInfo, type AddressModuleSet, CHARSET, type CheckNetworkHealthOptions, CurrencyUtils, DEFAULT_DERIVATION_PATH, DEFAULT_TOKEN_DECIMALS, type DerivedKey, type DiscoverAddressProgress, type DiscoverAddressesOptions, type DiscoverAddressesResult, type DiscoveredAddress, type EncryptedData, type EncryptionOptions, type InitProgress, type InitProgressCallback, type InitProgressStep, type KeyPair, type L1Config, type LogHandler, type LogLevel, type LoggerConfig, type MasterKey, SIGN_MESSAGE_PREFIX, type ScanAddressProgress, type ScanAddressesOptions, type ScanAddressesResult, type ScannedAddressResult, Sphere, type SphereCreateOptions, SphereError, type SphereErrorCode, type SphereImportOptions, type SphereInitOptions, type SphereInitResult, type SphereLoadOptions, base58Decode, base58Encode, bytesToHex, checkNetworkHealth, computeDirectAddressFromChainPubkey, computeHash160, convertBits, createAddress, createBech32, createKeyPair, createSphere, decodeBech32, decrypt, decryptJson, decryptMnemonic, decryptSimple, decryptWithSalt, deriveAddressInfo, deriveChildKey, deriveKeyAtPath, deserializeEncrypted, discoverAddressesImpl, doubleSha256, ec, encodeBech32, encrypt, encryptMnemonic, encryptSimple, entropyToMnemonic, extractFromText, findPattern, formatAmount, generateAddressInfo, generateMasterKey, generateMnemonic, generateRandomKey, getAddressHrp, getPublicKey, getSphere, hash160, hash160ToBytes, hashSignMessage, hexToBytes, identityFromMnemonic, identityFromMnemonicSync, importSphere, initSphere, isEncryptedData, isSphereError, isValidBech32, isValidNametag, isValidPrivateKey, loadSphere, logger, mnemonicToEntropy, mnemonicToSeed, mnemonicToSeedSync, privateKeyToAddressInfo, publicKeyToAddress, randomBytes, randomHex, randomUUID, ripemd160, scanAddressesImpl, serializeEncrypted, sha256, signMessage, sleep, sphereExists, toHumanReadable, toSmallestUnit, validateMnemonic, verifySignedMessage };
7995
+ export { type AddressInfo, type AddressModuleSet, CHARSET, type CheckNetworkHealthOptions, CurrencyUtils, DEFAULT_DERIVATION_PATH, DEFAULT_TOKEN_DECIMALS, type DerivedKey, type DiscoverAddressProgress, type DiscoverAddressesOptions, type DiscoverAddressesResult, type DiscoveredAddress, type EncryptedData, type EncryptionOptions, type InitProgress, type InitProgressCallback, type InitProgressStep, type KeyPair, type L1Config, type LogHandler, type LogLevel, type LoggerConfig, type MasterKey, SIGN_MESSAGE_PREFIX, type ScanAddressProgress, type ScanAddressesOptions, type ScanAddressesResult, type ScannedAddressResult, Sphere, type SphereCreateOptions, SphereError, type SphereErrorCode, type SphereImportOptions, type SphereInitOptions, type SphereInitResult, type SphereLoadOptions, base58Decode, base58Encode, bytesToHex, checkNetworkHealth, computeHash160, convertBits, createAddress, createBech32, createKeyPair, createSphere, decodeBech32, decrypt, decryptJson, decryptMnemonic, decryptSimple, decryptWithSalt, deriveAddressInfo, deriveChildKey, deriveKeyAtPath, deserializeEncrypted, discoverAddressesImpl, doubleSha256, ec, encodeBech32, encrypt, encryptMnemonic, encryptSimple, entropyToMnemonic, extractFromText, findPattern, formatAmount, generateAddressInfo, generateMasterKey, generateMnemonic, generateRandomKey, getAddressHrp, getPublicKey, getSphere, hash160, hash160ToBytes, hashSignMessage, hexToBytes, identityFromMnemonic, identityFromMnemonicSync, importSphere, initSphere, isEncryptedData, isSphereError, isValidBech32, isValidNametag, isValidPrivateKey, loadSphere, logger, mnemonicToEntropy, mnemonicToSeed, mnemonicToSeedSync, privateKeyToAddressInfo, publicKeyToAddress, randomBytes, randomHex, randomUUID, recoverPubkeyFromSignature, ripemd160, scanAddressesImpl, serializeEncrypted, sha256, signMessage, sleep, sphereExists, toHumanReadable, toSmallestUnit, validateMnemonic, verifySignedMessage };
@@ -2363,6 +2363,20 @@ declare function signMessage(privateKeyHex: string, message: string): string;
2363
2363
  * @returns `true` if the signature is valid and matches the expected public key
2364
2364
  */
2365
2365
  declare function verifySignedMessage(message: string, signature: string, expectedPubkey: string): boolean;
2366
+ /**
2367
+ * Recover the compressed secp256k1 public key from a signed message.
2368
+ *
2369
+ * Use this when the server needs to identify the signer (not just verify
2370
+ * a signature against a known pubkey). Combined with `sphere.resolve(pubkey)`
2371
+ * it gives a fully cryptographically-attributable identity for backend auth,
2372
+ * without trusting any client-supplied identifier claim.
2373
+ *
2374
+ * @param message - The plaintext that was signed
2375
+ * @param signature - 130-char hex (v + r + s) as produced by `signMessage`
2376
+ * @returns - Compressed 66-char hex pubkey
2377
+ * @throws - On malformed signature length or out-of-range recovery byte
2378
+ */
2379
+ declare function recoverPubkeyFromSignature(message: string, signature: string): string;
2366
2380
 
2367
2381
  /**
2368
2382
  * Result of an instant split send operation
@@ -6491,23 +6505,6 @@ type LegacyFileType = 'dat' | 'txt' | 'json' | 'mnemonic' | 'unknown';
6491
6505
  */
6492
6506
  type DecryptionProgressCallback = (iteration: number, total: number) => Promise<void> | void;
6493
6507
 
6494
- /**
6495
- * Compute the Unicity L3 DIRECT:// address that corresponds to a given
6496
- * compressed secp256k1 public key.
6497
- *
6498
- * Deterministic — the underlying primitive `UnmaskedPredicateReference.create`
6499
- * only uses the public key, so the private key is never needed. This lets
6500
- * a backend trust only one thing from the client (the chain pubkey, whose
6501
- * ownership the client proves via signature) and derive everything else
6502
- * locally. Closes the entire class of "client claims an identifier the
6503
- * server can't verify" bugs at the API level.
6504
- *
6505
- * @param chainPubkey 33-byte compressed secp256k1 pubkey, hex-encoded
6506
- * (66 chars, leading 02 or 03).
6507
- * @throws if chainPubkey doesn't match the compressed-secp256k1 format.
6508
- */
6509
- declare function computeDirectAddressFromChainPubkey(chainPubkey: string): Promise<string>;
6510
-
6511
6508
  declare function isValidNametag(nametag: string): boolean;
6512
6509
 
6513
6510
  /** Steps reported by the onProgress callback during wallet init/create/load/import */
@@ -6749,7 +6746,6 @@ interface SphereInitResult {
6749
6746
  /** Generated mnemonic (only if autoGenerate was used) */
6750
6747
  generatedMnemonic?: string;
6751
6748
  }
6752
-
6753
6749
  /**
6754
6750
  * Holds all per-address module instances.
6755
6751
  * Each HD address gets its own set so modules can run independently in background.
@@ -7996,4 +7992,4 @@ interface CheckNetworkHealthOptions {
7996
7992
  */
7997
7993
  declare function checkNetworkHealth(network?: NetworkType, options?: CheckNetworkHealthOptions): Promise<NetworkHealthResult>;
7998
7994
 
7999
- export { type AddressInfo, type AddressModuleSet, CHARSET, type CheckNetworkHealthOptions, CurrencyUtils, DEFAULT_DERIVATION_PATH, DEFAULT_TOKEN_DECIMALS, type DerivedKey, type DiscoverAddressProgress, type DiscoverAddressesOptions, type DiscoverAddressesResult, type DiscoveredAddress, type EncryptedData, type EncryptionOptions, type InitProgress, type InitProgressCallback, type InitProgressStep, type KeyPair, type L1Config, type LogHandler, type LogLevel, type LoggerConfig, type MasterKey, SIGN_MESSAGE_PREFIX, type ScanAddressProgress, type ScanAddressesOptions, type ScanAddressesResult, type ScannedAddressResult, Sphere, type SphereCreateOptions, SphereError, type SphereErrorCode, type SphereImportOptions, type SphereInitOptions, type SphereInitResult, type SphereLoadOptions, base58Decode, base58Encode, bytesToHex, checkNetworkHealth, computeDirectAddressFromChainPubkey, computeHash160, convertBits, createAddress, createBech32, createKeyPair, createSphere, decodeBech32, decrypt, decryptJson, decryptMnemonic, decryptSimple, decryptWithSalt, deriveAddressInfo, deriveChildKey, deriveKeyAtPath, deserializeEncrypted, discoverAddressesImpl, doubleSha256, ec, encodeBech32, encrypt, encryptMnemonic, encryptSimple, entropyToMnemonic, extractFromText, findPattern, formatAmount, generateAddressInfo, generateMasterKey, generateMnemonic, generateRandomKey, getAddressHrp, getPublicKey, getSphere, hash160, hash160ToBytes, hashSignMessage, hexToBytes, identityFromMnemonic, identityFromMnemonicSync, importSphere, initSphere, isEncryptedData, isSphereError, isValidBech32, isValidNametag, isValidPrivateKey, loadSphere, logger, mnemonicToEntropy, mnemonicToSeed, mnemonicToSeedSync, privateKeyToAddressInfo, publicKeyToAddress, randomBytes, randomHex, randomUUID, ripemd160, scanAddressesImpl, serializeEncrypted, sha256, signMessage, sleep, sphereExists, toHumanReadable, toSmallestUnit, validateMnemonic, verifySignedMessage };
7995
+ export { type AddressInfo, type AddressModuleSet, CHARSET, type CheckNetworkHealthOptions, CurrencyUtils, DEFAULT_DERIVATION_PATH, DEFAULT_TOKEN_DECIMALS, type DerivedKey, type DiscoverAddressProgress, type DiscoverAddressesOptions, type DiscoverAddressesResult, type DiscoveredAddress, type EncryptedData, type EncryptionOptions, type InitProgress, type InitProgressCallback, type InitProgressStep, type KeyPair, type L1Config, type LogHandler, type LogLevel, type LoggerConfig, type MasterKey, SIGN_MESSAGE_PREFIX, type ScanAddressProgress, type ScanAddressesOptions, type ScanAddressesResult, type ScannedAddressResult, Sphere, type SphereCreateOptions, SphereError, type SphereErrorCode, type SphereImportOptions, type SphereInitOptions, type SphereInitResult, type SphereLoadOptions, base58Decode, base58Encode, bytesToHex, checkNetworkHealth, computeHash160, convertBits, createAddress, createBech32, createKeyPair, createSphere, decodeBech32, decrypt, decryptJson, decryptMnemonic, decryptSimple, decryptWithSalt, deriveAddressInfo, deriveChildKey, deriveKeyAtPath, deserializeEncrypted, discoverAddressesImpl, doubleSha256, ec, encodeBech32, encrypt, encryptMnemonic, encryptSimple, entropyToMnemonic, extractFromText, findPattern, formatAmount, generateAddressInfo, generateMasterKey, generateMnemonic, generateRandomKey, getAddressHrp, getPublicKey, getSphere, hash160, hash160ToBytes, hashSignMessage, hexToBytes, identityFromMnemonic, identityFromMnemonicSync, importSphere, initSphere, isEncryptedData, isSphereError, isValidBech32, isValidNametag, isValidPrivateKey, loadSphere, logger, mnemonicToEntropy, mnemonicToSeed, mnemonicToSeedSync, privateKeyToAddressInfo, publicKeyToAddress, randomBytes, randomHex, randomUUID, recoverPubkeyFromSignature, ripemd160, scanAddressesImpl, serializeEncrypted, sha256, signMessage, sleep, sphereExists, toHumanReadable, toSmallestUnit, validateMnemonic, verifySignedMessage };
@@ -4837,6 +4837,27 @@ function verifySignedMessage(message, signature, expectedPubkey) {
4837
4837
  return false;
4838
4838
  }
4839
4839
  }
4840
+ function recoverPubkeyFromSignature(message, signature) {
4841
+ if (signature.length !== 130) {
4842
+ throw new SphereError(
4843
+ `Invalid signature length: expected 130 hex chars, got ${signature.length}`,
4844
+ "SIGNING_ERROR"
4845
+ );
4846
+ }
4847
+ const v = parseInt(signature.slice(0, 2), 16) - 31;
4848
+ const r = signature.slice(2, 66);
4849
+ const s = signature.slice(66, 130);
4850
+ if (v < 0 || v > 3) {
4851
+ throw new SphereError(
4852
+ `Invalid recovery byte: v=${v} out of range [0..3]`,
4853
+ "SIGNING_ERROR"
4854
+ );
4855
+ }
4856
+ const hashHex = hashSignMessage(message);
4857
+ const hashBytes = Buffer.from(hashHex, "hex");
4858
+ const recovered = ec.recoverPubKey(hashBytes, { r, s }, v);
4859
+ return recovered.encode("hex", true);
4860
+ }
4840
4861
 
4841
4862
  // l1/crypto.ts
4842
4863
  import CryptoJS3 from "crypto-js";
@@ -27373,42 +27394,27 @@ async function parseAndDecryptWalletDat(data, password, onProgress) {
27373
27394
 
27374
27395
  // core/Sphere.ts
27375
27396
  import { SigningService as SigningService2 } from "@unicitylabs/state-transition-sdk/lib/sign/SigningService";
27376
- import { normalizeNametag as normalizeNametag2, isPhoneNumber } from "@unicitylabs/nostr-js-sdk";
27377
-
27378
- // core/address-derivation.ts
27379
27397
  import { TokenType as TokenType5 } from "@unicitylabs/state-transition-sdk/lib/token/TokenType";
27380
27398
  import { HashAlgorithm as HashAlgorithm7 } from "@unicitylabs/state-transition-sdk/lib/hash/HashAlgorithm";
27381
27399
  import { UnmaskedPredicateReference as UnmaskedPredicateReference3 } from "@unicitylabs/state-transition-sdk/lib/predicate/embedded/UnmaskedPredicateReference";
27382
- var UNICITY_TOKEN_TYPE_HEX2 = "f8aa13834268d29355ff12183066f0cb902003629bbc5eb9ef0efbe397867509";
27383
- var COMPRESSED_PUBKEY_RE = /^(02|03)[0-9a-fA-F]{64}$/;
27384
- async function computeDirectAddressFromChainPubkey(chainPubkey) {
27385
- if (typeof chainPubkey !== "string" || !COMPRESSED_PUBKEY_RE.test(chainPubkey)) {
27386
- throw new Error(
27387
- `computeDirectAddressFromChainPubkey: chainPubkey must be 66-char hex with 02/03 prefix, got "${String(chainPubkey).slice(0, 12)}..."`
27388
- );
27389
- }
27390
- const tokenTypeBytes = Buffer.from(UNICITY_TOKEN_TYPE_HEX2, "hex");
27391
- const tokenType = new TokenType5(tokenTypeBytes);
27392
- const publicKeyBytes = Buffer.from(chainPubkey, "hex");
27393
- const predicateRef = await UnmaskedPredicateReference3.create(
27394
- tokenType,
27395
- "secp256k1",
27396
- publicKeyBytes,
27397
- HashAlgorithm7.SHA256
27398
- );
27399
- return (await predicateRef.toAddress()).toString();
27400
- }
27401
-
27402
- // core/Sphere.ts
27400
+ import { normalizeNametag as normalizeNametag2, isPhoneNumber } from "@unicitylabs/nostr-js-sdk";
27403
27401
  function isValidNametag2(nametag) {
27404
27402
  if (isPhoneNumber(nametag)) return true;
27405
27403
  return /^[a-z0-9_-]{3,20}$/.test(nametag);
27406
27404
  }
27405
+ var UNICITY_TOKEN_TYPE_HEX2 = "f8aa13834268d29355ff12183066f0cb902003629bbc5eb9ef0efbe397867509";
27407
27406
  async function deriveL3PredicateAddress(privateKey) {
27408
27407
  const secret = Buffer.from(privateKey, "hex");
27409
27408
  const signingService = await SigningService2.createFromSecret(secret);
27410
- const pubkeyHex = Buffer.from(signingService.publicKey).toString("hex");
27411
- return computeDirectAddressFromChainPubkey(pubkeyHex);
27409
+ const tokenTypeBytes = Buffer.from(UNICITY_TOKEN_TYPE_HEX2, "hex");
27410
+ const tokenType = new TokenType5(tokenTypeBytes);
27411
+ const predicateRef = UnmaskedPredicateReference3.create(
27412
+ tokenType,
27413
+ signingService.algorithm,
27414
+ signingService.publicKey,
27415
+ HashAlgorithm7.SHA256
27416
+ );
27417
+ return (await (await predicateRef).toAddress()).toString();
27412
27418
  }
27413
27419
  var Sphere = class _Sphere {
27414
27420
  // Singleton
@@ -30792,7 +30798,6 @@ export {
30792
30798
  base58Encode,
30793
30799
  bytesToHex3 as bytesToHex,
30794
30800
  checkNetworkHealth,
30795
- computeDirectAddressFromChainPubkey,
30796
30801
  computeHash160,
30797
30802
  convertBits,
30798
30803
  createAddress,
@@ -30850,6 +30855,7 @@ export {
30850
30855
  randomBytes2 as randomBytes,
30851
30856
  randomHex,
30852
30857
  randomUUID,
30858
+ recoverPubkeyFromSignature,
30853
30859
  ripemd160,
30854
30860
  scanAddressesImpl,
30855
30861
  serializeEncrypted,