@wishknish/knishio-client-ts 1.2.0 → 1.3.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
@@ -62,8 +62,13 @@ var __defProp = Object.defineProperty;
62
62
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
63
63
  var __getOwnPropNames = Object.getOwnPropertyNames;
64
64
  var __hasOwnProp = Object.prototype.hasOwnProperty;
65
- var __esm = (fn, res) => function __init() {
66
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
65
+ var __esm = (fn, res, err) => function __init() {
66
+ if (err) throw err[0];
67
+ try {
68
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
69
+ } catch (e) {
70
+ throw err = [e], e;
71
+ }
67
72
  };
68
73
  var __export = (target, all) => {
69
74
  for (var name in all)
@@ -2929,24 +2934,6 @@ var AtomMeta = class _AtomMeta {
2929
2934
  this.merge({ shadowWalletClaim: Number(shadowWalletClaim) });
2930
2935
  return this;
2931
2936
  }
2932
- /**
2933
- * Set signing wallet metadata
2934
- * @param signingWallet - Wallet used for signing
2935
- * @return This instance for chaining
2936
- */
2937
- setSigningWallet(signingWallet) {
2938
- this.merge({
2939
- signingWallet: JSON.stringify({
2940
- tokenSlug: signingWallet.token,
2941
- bundleHash: signingWallet.bundle,
2942
- address: signingWallet.address,
2943
- position: signingWallet.position,
2944
- pubkey: signingWallet.pubkey,
2945
- characters: signingWallet.characters
2946
- })
2947
- });
2948
- return this;
2949
- }
2950
2937
  /**
2951
2938
  * Add policy metadata
2952
2939
  * @param policy - Policy object to add
@@ -4786,7 +4773,6 @@ var Rule = class _Rule {
4786
4773
 
4787
4774
  // src/libraries/CheckMolecule.ts
4788
4775
  init_exception();
4789
- init_Dot();
4790
4776
  var CheckMolecule = class _CheckMolecule {
4791
4777
  molecule;
4792
4778
  /**
@@ -4874,12 +4860,13 @@ var CheckMolecule = class _CheckMolecule {
4874
4860
  /**
4875
4861
  * Validate isotope U atoms
4876
4862
  * @return True if valid
4877
- * @throws WrongTokenTypeException if token is not AUTH
4863
+ * @throws WrongTokenTypeException if token is neither AUTH (fresh login) nor USER (re-login
4864
+ * signed from the ContinuID pointer)
4878
4865
  * @throws AtomIndexException if index is not 0
4879
4866
  */
4880
4867
  isotopeU() {
4881
4868
  for (const atom of this.molecule.getIsotopes("U")) {
4882
- if (atom.token !== "AUTH") {
4869
+ if (atom.token !== "AUTH" && atom.token !== "USER") {
4883
4870
  throw new WrongTokenTypeException(`Check::isotopeU() - "${atom.token}" is not a valid Token slug for "${atom.isotope}" isotope Atoms!`);
4884
4871
  }
4885
4872
  if (atom.index !== 0) {
@@ -5268,16 +5255,7 @@ var CheckMolecule = class _CheckMolecule {
5268
5255
  if (!signingAtom) {
5269
5256
  throw new exports.SignatureMismatchException();
5270
5257
  }
5271
- let signingAddress = signingAtom.walletAddress;
5272
- const signingWallet = exports.Dot.get(signingAtom.aggregatedMeta(), "signingWallet");
5273
- if (signingWallet) {
5274
- const parsedWallet = JSON.parse(signingWallet);
5275
- const walletAddress = exports.Dot.get(parsedWallet, "address");
5276
- if (walletAddress) {
5277
- signingAddress = walletAddress;
5278
- }
5279
- }
5280
- if (address !== signingAddress) {
5258
+ if (address !== signingAtom.walletAddress) {
5281
5259
  throw new exports.SignatureMismatchException();
5282
5260
  }
5283
5261
  return true;
@@ -5612,18 +5590,7 @@ var Molecule = class _Molecule {
5612
5590
  if (!signingAtom) {
5613
5591
  throw new SignatureMalformedException("No atoms available for signing!");
5614
5592
  }
5615
- let signingPosition = signingAtom.position;
5616
- const signingWalletMeta = signingAtom.aggregatedMeta ? signingAtom.aggregatedMeta() : null;
5617
- const signingWalletJson = signingWalletMeta?.signingWallet;
5618
- if (signingWalletJson) {
5619
- try {
5620
- const parsedSigningWallet = JSON.parse(signingWalletJson);
5621
- if (parsedSigningWallet.position) {
5622
- signingPosition = parsedSigningWallet.position;
5623
- }
5624
- } catch {
5625
- }
5626
- }
5593
+ const signingPosition = signingAtom.position;
5627
5594
  if (!signingPosition) {
5628
5595
  throw new SignatureMalformedException("Signing wallet must have a position!");
5629
5596
  }
@@ -6026,9 +5993,7 @@ var Molecule = class _Molecule {
6026
5993
  const atomMeta = new AtomMeta({
6027
5994
  rule: JSON.stringify(rules)
6028
5995
  });
6029
- if (policy && Object.keys(policy).length > 0) {
6030
- atomMeta.addPolicy(policy);
6031
- }
5996
+ atomMeta.addPolicy(policy ?? {});
6032
5997
  this.addAtom(Atom.create({
6033
5998
  isotope: "R",
6034
5999
  wallet: this.sourceWallet,
@@ -6281,12 +6246,10 @@ var Molecule = class _Molecule {
6281
6246
  * Matches JavaScript SDK Molecule.initWithdrawBuffer implementation exactly
6282
6247
  *
6283
6248
  * @param recipients - Map of recipientBundle → amount
6284
- * @param signingWallet - Optional signing wallet for reconciliation
6285
6249
  * @return This molecule instance for chaining
6286
6250
  */
6287
6251
  initWithdrawBuffer({
6288
- recipients,
6289
- signingWallet = null
6252
+ recipients
6290
6253
  }) {
6291
6254
  if (!this.sourceWallet) {
6292
6255
  throw new Error("Source wallet required for buffer withdrawal");
@@ -6298,15 +6261,10 @@ var Molecule = class _Molecule {
6298
6261
  if (Number(this.sourceWallet.balance) - amount < 0) {
6299
6262
  throw new BalanceInsufficientException();
6300
6263
  }
6301
- const firstAtomMeta = new AtomMeta();
6302
- if (signingWallet) {
6303
- firstAtomMeta.setSigningWallet(signingWallet);
6304
- }
6305
6264
  this.addAtom(Atom.create({
6306
6265
  isotope: "B",
6307
6266
  wallet: this.sourceWallet,
6308
6267
  value: -Number(this.sourceWallet.balance),
6309
- meta: firstAtomMeta,
6310
6268
  metaType: "walletBundle",
6311
6269
  metaId: this.sourceWallet.bundle
6312
6270
  }));
@@ -6741,7 +6699,7 @@ var AuthToken = class _AuthToken {
6741
6699
  static restore(snapshot, secret) {
6742
6700
  const wallet = new Wallet({
6743
6701
  secret,
6744
- token: "AUTH",
6702
+ token: snapshot.wallet?.token ?? "AUTH",
6745
6703
  position: snapshot.wallet?.position ?? null,
6746
6704
  characters: snapshot.wallet?.characters ?? null,
6747
6705
  mlKemParameterSet: _AuthToken.resolveMlKemParameterSet(snapshot)
@@ -6824,6 +6782,7 @@ var AuthToken = class _AuthToken {
6824
6782
  encrypt: this.$__encrypt,
6825
6783
  ...this.$__wallet ? {
6826
6784
  wallet: {
6785
+ token: this.$__wallet.token,
6827
6786
  position: this.$__wallet.position,
6828
6787
  characters: this.$__wallet.characters,
6829
6788
  mlKemParameterSet: this.$__wallet.mlKemParameterSet
@@ -8312,8 +8271,8 @@ var QueryContinuId = class extends Query {
8312
8271
  */
8313
8272
  constructor(graphQLClient, knishIOClient) {
8314
8273
  super(graphQLClient, knishIOClient);
8315
- this.$__query = core.gql`query ($bundle: String!) {
8316
- ContinuId(bundle: $bundle) {
8274
+ this.$__query = core.gql`query ($bundle: String!, $token: String) {
8275
+ ContinuId(bundle: $bundle, token: $token) {
8317
8276
  address,
8318
8277
  bundleHash,
8319
8278
  tokenSlug,
@@ -9599,7 +9558,7 @@ var ResponseProposeMolecule = class extends exports.Response {
9599
9558
  code: "HASH_MISMATCH"
9600
9559
  });
9601
9560
  }
9602
- if (/ots.*position.*reuse|position.*already.*used|ots.*verification/.test(lc)) {
9561
+ if (/ots.*(?:position|key).*reuse|position.*already.*(?:used|consumed)|ots.*verification/.test(lc)) {
9603
9562
  return new exports.SignatureMismatchException(reason, {
9604
9563
  details: { reason },
9605
9564
  code: "OTS_VERIFICATION_FAILED"
@@ -9617,6 +9576,18 @@ var ResponseProposeMolecule = class extends exports.Response {
9617
9576
  code: "VERIFICATION_FAILED"
9618
9577
  });
9619
9578
  }
9579
+ if (/signer address mismatch/.test(lc)) {
9580
+ return new exports.SignatureMismatchException(reason, {
9581
+ details: { reason },
9582
+ code: "SIGNER_ADDRESS_MISMATCH"
9583
+ });
9584
+ }
9585
+ if (/no accepted origin available/.test(lc)) {
9586
+ return new exports.AtomIndexException(reason, {
9587
+ details: { reason },
9588
+ code: "ORIGIN_PENDING"
9589
+ });
9590
+ }
9620
9591
  return null;
9621
9592
  }
9622
9593
  /**
@@ -10114,12 +10085,10 @@ var MutationWithdrawBufferToken = class extends MutationProposeMolecule {
10114
10085
  * Fills the molecule with buffer withdrawal data
10115
10086
  */
10116
10087
  fillMolecule({
10117
- recipients,
10118
- signingWallet
10088
+ recipients
10119
10089
  }) {
10120
10090
  this.$__molecule.initWithdrawBuffer({
10121
- recipients,
10122
- signingWallet
10091
+ recipients
10123
10092
  });
10124
10093
  this.$__molecule.sign({});
10125
10094
  this.$__molecule.check(this.$__molecule.sourceWallet);
@@ -11605,24 +11574,27 @@ var KnishIOClient = class {
11605
11574
  this.setCellSlug(cellSlug);
11606
11575
  }
11607
11576
  this.$__authInProcess = true;
11608
- let response;
11609
- if (secret) {
11610
- response = await this.requestProfileAuthToken({
11611
- secret,
11612
- encrypt
11613
- });
11614
- } else {
11615
- response = await this.requestGuestAuthToken({
11616
- cellSlug: cellSlug || this.getCellSlug(),
11617
- encrypt
11618
- });
11619
- }
11620
- if (this.$__authToken) {
11621
- this.log("info", `KnishIOClient::requestAuthToken() - Successfully retrieved auth token...`);
11577
+ try {
11578
+ let response;
11579
+ if (secret) {
11580
+ response = await this.requestProfileAuthToken({
11581
+ secret,
11582
+ encrypt
11583
+ });
11584
+ } else {
11585
+ response = await this.requestGuestAuthToken({
11586
+ cellSlug: cellSlug || this.getCellSlug(),
11587
+ encrypt
11588
+ });
11589
+ }
11590
+ if (this.$__authToken) {
11591
+ this.log("info", `KnishIOClient::requestAuthToken() - Successfully retrieved auth token...`);
11592
+ }
11593
+ this.switchEncryption(encrypt);
11594
+ return response;
11595
+ } finally {
11596
+ this.$__authInProcess = false;
11622
11597
  }
11623
- this.switchEncryption(encrypt);
11624
- this.$__authInProcess = false;
11625
- return response;
11626
11598
  }
11627
11599
  /**
11628
11600
  * Logging utility
@@ -11766,14 +11738,16 @@ var KnishIOClient = class {
11766
11738
  }
11767
11739
  /**
11768
11740
  * Query next ContinuId wallet
11741
+ *
11742
+ * @param token - Restricts the lookup to wallets of this token. Without it the validator falls
11743
+ * back to the bundle's newest wallet of ANY token when the bundle has no ContinuID pointer.
11769
11744
  */
11770
11745
  async queryContinuId({
11771
- bundle
11746
+ bundle,
11747
+ token = null
11772
11748
  }) {
11773
11749
  const query = this.createQuery(QueryContinuId);
11774
- return this.executeQuery(query, {
11775
- bundle
11776
- });
11750
+ return this.executeQuery(query, token ? { bundle, token } : { bundle });
11777
11751
  }
11778
11752
  /**
11779
11753
  * Query metadata
@@ -12590,8 +12564,7 @@ var KnishIOClient = class {
12590
12564
  async withdrawBufferToken({
12591
12565
  tokenSlug,
12592
12566
  amount,
12593
- sourceWallet = null,
12594
- signingWallet = null
12567
+ sourceWallet = null
12595
12568
  }) {
12596
12569
  this.log("info", `KnishIOClient::withdrawBufferToken() - Withdrawing ${amount} of ${tokenSlug} from buffer...`);
12597
12570
  if (!sourceWallet) {
@@ -12600,11 +12573,7 @@ var KnishIOClient = class {
12600
12573
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationWithdrawBufferToken });
12601
12574
  const recipients = {};
12602
12575
  recipients[this.getBundle()] = amount;
12603
- const fillMoleculeParams = { recipients };
12604
- if (signingWallet) {
12605
- fillMoleculeParams.signingWallet = signingWallet;
12606
- }
12607
- await mutation.fillMolecule(fillMoleculeParams);
12576
+ await mutation.fillMolecule({ recipients });
12608
12577
  const response = await this.executeQuery(mutation);
12609
12578
  if (!response) {
12610
12579
  throw new CodeException("Buffer token withdrawal failed");
@@ -12622,21 +12591,33 @@ var KnishIOClient = class {
12622
12591
  encrypt = false
12623
12592
  } = {}) {
12624
12593
  this.log("info", "KnishIOClient::requestGuestAuthToken() - Requesting guest auth token...");
12625
- const mutation = this.createQuery(MutationRequestAuthorizationGuest);
12626
- const response = await this.executeQuery(mutation, {
12627
- cellSlug: cellSlug || this.getCellSlug()
12628
- });
12629
- if (!response) {
12630
- throw new CodeException("Guest auth token request failed");
12631
- }
12632
- if (encrypt) {
12633
- this.switchEncryption(true);
12594
+ const authInProcess = this.$__authInProcess;
12595
+ this.$__authInProcess = true;
12596
+ try {
12597
+ const mutation = this.createQuery(MutationRequestAuthorizationGuest);
12598
+ const response = await this.executeQuery(mutation, {
12599
+ cellSlug: cellSlug || this.getCellSlug()
12600
+ });
12601
+ if (!response) {
12602
+ throw new CodeException("Guest auth token request failed");
12603
+ }
12604
+ if (encrypt) {
12605
+ this.switchEncryption(true);
12606
+ }
12607
+ return response;
12608
+ } finally {
12609
+ this.$__authInProcess = authInProcess;
12634
12610
  }
12635
- return response;
12636
12611
  }
12637
12612
  /**
12638
12613
  * Request profile authentication token
12639
- * Matches JavaScript SDK requestProfileAuthToken implementation
12614
+ *
12615
+ * A returning user (the bundle has a USER ContinuID pointer) signs from the USER wallet
12616
+ * registered at that pointer, so validator 0.5.0+ marks the token proven and the identity keeps
12617
+ * read/subscription access to permissioned and private cells. A first login — or a pointer this
12618
+ * secret does not own — signs from a fresh AUTH wallet as before. A rejected pointer-signed
12619
+ * login falls back to the AUTH login exactly once, so one call sends at most two
12620
+ * authorization molecules (testnet allows 3 auths/min/IP).
12640
12621
  */
12641
12622
  async requestProfileAuthToken({
12642
12623
  secret,
@@ -12644,13 +12625,58 @@ var KnishIOClient = class {
12644
12625
  }) {
12645
12626
  this.log("info", "KnishIOClient::requestProfileAuthToken() - Requesting profile auth token...");
12646
12627
  this.setSecret(secret);
12647
- const wallet = new Wallet({
12648
- secret,
12649
- token: "AUTH",
12650
- mlKemParameterSet: this.getMlKemParameterSet()
12651
- });
12628
+ const authInProcess = this.$__authInProcess;
12629
+ this.$__authInProcess = true;
12630
+ try {
12631
+ const pointer = (await this.queryContinuId({
12632
+ bundle: this.getBundle(),
12633
+ token: "USER"
12634
+ }))?.payload();
12635
+ let pointerWallet = null;
12636
+ if (pointer && pointer.token === "USER" && pointer.position) {
12637
+ const wallet2 = new Wallet({
12638
+ secret,
12639
+ token: "USER",
12640
+ position: pointer.position,
12641
+ mlKemParameterSet: this.getMlKemParameterSet()
12642
+ });
12643
+ if (!pointer.address || wallet2.address === pointer.address) {
12644
+ pointerWallet = wallet2;
12645
+ } else {
12646
+ this.log("warn", "KnishIOClient::requestProfileAuthToken() - ContinuID wallet address does not derive from this secret; signing from a fresh AUTH wallet");
12647
+ }
12648
+ }
12649
+ if (pointerWallet) {
12650
+ const response2 = await this.proposeProfileAuthorization(pointerWallet, encrypt);
12651
+ if (response2.success()) {
12652
+ this.log("info", "KnishIOClient::requestProfileAuthToken() - Auth token signed from the ContinuID pointer (proven)");
12653
+ return this.acceptProfileAuthorization(response2, pointerWallet, encrypt);
12654
+ }
12655
+ this.log("warn", `KnishIOClient::requestProfileAuthToken() - Pointer-signed authorization rejected (${response2.reason()}); falling back once to an AUTH-wallet login`);
12656
+ }
12657
+ const wallet = new Wallet({
12658
+ secret,
12659
+ token: "AUTH",
12660
+ mlKemParameterSet: this.getMlKemParameterSet()
12661
+ });
12662
+ const response = await this.proposeProfileAuthorization(wallet, encrypt);
12663
+ if (!response.success()) {
12664
+ throw new AuthorizationRejectedException_default(
12665
+ `KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${response.reason()}`
12666
+ );
12667
+ }
12668
+ this.log("info", `KnishIOClient::requestProfileAuthToken() - Auth token signed from a fresh AUTH wallet (${pointerWallet ? "fallback after the pointer-signed login was rejected" : "no usable ContinuID pointer"})`);
12669
+ return this.acceptProfileAuthorization(response, wallet, encrypt);
12670
+ } finally {
12671
+ this.$__authInProcess = authInProcess;
12672
+ }
12673
+ }
12674
+ /**
12675
+ * Signs and proposes a profile authorization molecule from the given source wallet.
12676
+ */
12677
+ async proposeProfileAuthorization(wallet, encrypt) {
12652
12678
  const molecule = await this.createMolecule({
12653
- secret,
12679
+ secret: this.getSecret(),
12654
12680
  sourceWallet: wallet
12655
12681
  });
12656
12682
  const mutation = await this.createMoleculeMutation({
@@ -12668,19 +12694,20 @@ var KnishIOClient = class {
12668
12694
  if (!response) {
12669
12695
  throw new CodeException("Profile auth token request failed");
12670
12696
  }
12671
- if (response.success()) {
12672
- const authToken = AuthToken.create({
12673
- token: response.token(),
12674
- expiresAt: response.expiresAt(),
12675
- encrypt: String(response.encrypt()) === "true",
12676
- pubkey: response.pubKey()
12677
- }, wallet);
12678
- this.setAuthToken(authToken);
12679
- } else {
12680
- throw new AuthorizationRejectedException_default(
12681
- `KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${response.reason()}`
12682
- );
12683
- }
12697
+ return response;
12698
+ }
12699
+ /**
12700
+ * Binds the accepted authorization's token to the wallet that signed it.
12701
+ */
12702
+ acceptProfileAuthorization(response, wallet, encrypt) {
12703
+ const authToken = AuthToken.create({
12704
+ token: response.token(),
12705
+ expiresAt: response.expiresAt(),
12706
+ encrypt: String(response.encrypt()) === "true",
12707
+ pubkey: response.pubKey()
12708
+ }, wallet);
12709
+ this.setAuthToken(authToken);
12710
+ this.lastMoleculeQuery = null;
12684
12711
  if (encrypt) {
12685
12712
  this.switchEncryption(true);
12686
12713
  }
@@ -14038,7 +14065,7 @@ function createDefaultSecretStorage(options = {}) {
14038
14065
  }
14039
14066
 
14040
14067
  // src/index.ts
14041
- var SDK_VERSION = "1.2.0";
14068
+ var SDK_VERSION = "1.3.0";
14042
14069
  var SDK_NAME = "KnishIO-Client-TS";
14043
14070
  var COMPATIBLE_SERVER_VERSIONS = [4, 5];
14044
14071
  var SDK_INFO = {