@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.js CHANGED
@@ -56,8 +56,13 @@ var __defProp = Object.defineProperty;
56
56
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
57
57
  var __getOwnPropNames = Object.getOwnPropertyNames;
58
58
  var __hasOwnProp = Object.prototype.hasOwnProperty;
59
- var __esm = (fn, res) => function __init() {
60
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
59
+ var __esm = (fn, res, err) => function __init() {
60
+ if (err) throw err[0];
61
+ try {
62
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
63
+ } catch (e) {
64
+ throw err = [e], e;
65
+ }
61
66
  };
62
67
  var __export = (target, all) => {
63
68
  for (var name in all)
@@ -2923,24 +2928,6 @@ var AtomMeta = class _AtomMeta {
2923
2928
  this.merge({ shadowWalletClaim: Number(shadowWalletClaim) });
2924
2929
  return this;
2925
2930
  }
2926
- /**
2927
- * Set signing wallet metadata
2928
- * @param signingWallet - Wallet used for signing
2929
- * @return This instance for chaining
2930
- */
2931
- setSigningWallet(signingWallet) {
2932
- this.merge({
2933
- signingWallet: JSON.stringify({
2934
- tokenSlug: signingWallet.token,
2935
- bundleHash: signingWallet.bundle,
2936
- address: signingWallet.address,
2937
- position: signingWallet.position,
2938
- pubkey: signingWallet.pubkey,
2939
- characters: signingWallet.characters
2940
- })
2941
- });
2942
- return this;
2943
- }
2944
2931
  /**
2945
2932
  * Add policy metadata
2946
2933
  * @param policy - Policy object to add
@@ -4780,7 +4767,6 @@ var Rule = class _Rule {
4780
4767
 
4781
4768
  // src/libraries/CheckMolecule.ts
4782
4769
  init_exception();
4783
- init_Dot();
4784
4770
  var CheckMolecule = class _CheckMolecule {
4785
4771
  molecule;
4786
4772
  /**
@@ -4868,12 +4854,13 @@ var CheckMolecule = class _CheckMolecule {
4868
4854
  /**
4869
4855
  * Validate isotope U atoms
4870
4856
  * @return True if valid
4871
- * @throws WrongTokenTypeException if token is not AUTH
4857
+ * @throws WrongTokenTypeException if token is neither AUTH (fresh login) nor USER (re-login
4858
+ * signed from the ContinuID pointer)
4872
4859
  * @throws AtomIndexException if index is not 0
4873
4860
  */
4874
4861
  isotopeU() {
4875
4862
  for (const atom of this.molecule.getIsotopes("U")) {
4876
- if (atom.token !== "AUTH") {
4863
+ if (atom.token !== "AUTH" && atom.token !== "USER") {
4877
4864
  throw new WrongTokenTypeException(`Check::isotopeU() - "${atom.token}" is not a valid Token slug for "${atom.isotope}" isotope Atoms!`);
4878
4865
  }
4879
4866
  if (atom.index !== 0) {
@@ -5262,16 +5249,7 @@ var CheckMolecule = class _CheckMolecule {
5262
5249
  if (!signingAtom) {
5263
5250
  throw new SignatureMismatchException();
5264
5251
  }
5265
- let signingAddress = signingAtom.walletAddress;
5266
- const signingWallet = Dot.get(signingAtom.aggregatedMeta(), "signingWallet");
5267
- if (signingWallet) {
5268
- const parsedWallet = JSON.parse(signingWallet);
5269
- const walletAddress = Dot.get(parsedWallet, "address");
5270
- if (walletAddress) {
5271
- signingAddress = walletAddress;
5272
- }
5273
- }
5274
- if (address !== signingAddress) {
5252
+ if (address !== signingAtom.walletAddress) {
5275
5253
  throw new SignatureMismatchException();
5276
5254
  }
5277
5255
  return true;
@@ -5606,18 +5584,7 @@ var Molecule = class _Molecule {
5606
5584
  if (!signingAtom) {
5607
5585
  throw new SignatureMalformedException("No atoms available for signing!");
5608
5586
  }
5609
- let signingPosition = signingAtom.position;
5610
- const signingWalletMeta = signingAtom.aggregatedMeta ? signingAtom.aggregatedMeta() : null;
5611
- const signingWalletJson = signingWalletMeta?.signingWallet;
5612
- if (signingWalletJson) {
5613
- try {
5614
- const parsedSigningWallet = JSON.parse(signingWalletJson);
5615
- if (parsedSigningWallet.position) {
5616
- signingPosition = parsedSigningWallet.position;
5617
- }
5618
- } catch {
5619
- }
5620
- }
5587
+ const signingPosition = signingAtom.position;
5621
5588
  if (!signingPosition) {
5622
5589
  throw new SignatureMalformedException("Signing wallet must have a position!");
5623
5590
  }
@@ -6020,9 +5987,7 @@ var Molecule = class _Molecule {
6020
5987
  const atomMeta = new AtomMeta({
6021
5988
  rule: JSON.stringify(rules)
6022
5989
  });
6023
- if (policy && Object.keys(policy).length > 0) {
6024
- atomMeta.addPolicy(policy);
6025
- }
5990
+ atomMeta.addPolicy(policy ?? {});
6026
5991
  this.addAtom(Atom.create({
6027
5992
  isotope: "R",
6028
5993
  wallet: this.sourceWallet,
@@ -6275,12 +6240,10 @@ var Molecule = class _Molecule {
6275
6240
  * Matches JavaScript SDK Molecule.initWithdrawBuffer implementation exactly
6276
6241
  *
6277
6242
  * @param recipients - Map of recipientBundle → amount
6278
- * @param signingWallet - Optional signing wallet for reconciliation
6279
6243
  * @return This molecule instance for chaining
6280
6244
  */
6281
6245
  initWithdrawBuffer({
6282
- recipients,
6283
- signingWallet = null
6246
+ recipients
6284
6247
  }) {
6285
6248
  if (!this.sourceWallet) {
6286
6249
  throw new Error("Source wallet required for buffer withdrawal");
@@ -6292,15 +6255,10 @@ var Molecule = class _Molecule {
6292
6255
  if (Number(this.sourceWallet.balance) - amount < 0) {
6293
6256
  throw new BalanceInsufficientException();
6294
6257
  }
6295
- const firstAtomMeta = new AtomMeta();
6296
- if (signingWallet) {
6297
- firstAtomMeta.setSigningWallet(signingWallet);
6298
- }
6299
6258
  this.addAtom(Atom.create({
6300
6259
  isotope: "B",
6301
6260
  wallet: this.sourceWallet,
6302
6261
  value: -Number(this.sourceWallet.balance),
6303
- meta: firstAtomMeta,
6304
6262
  metaType: "walletBundle",
6305
6263
  metaId: this.sourceWallet.bundle
6306
6264
  }));
@@ -6735,7 +6693,7 @@ var AuthToken = class _AuthToken {
6735
6693
  static restore(snapshot, secret) {
6736
6694
  const wallet = new Wallet({
6737
6695
  secret,
6738
- token: "AUTH",
6696
+ token: snapshot.wallet?.token ?? "AUTH",
6739
6697
  position: snapshot.wallet?.position ?? null,
6740
6698
  characters: snapshot.wallet?.characters ?? null,
6741
6699
  mlKemParameterSet: _AuthToken.resolveMlKemParameterSet(snapshot)
@@ -6818,6 +6776,7 @@ var AuthToken = class _AuthToken {
6818
6776
  encrypt: this.$__encrypt,
6819
6777
  ...this.$__wallet ? {
6820
6778
  wallet: {
6779
+ token: this.$__wallet.token,
6821
6780
  position: this.$__wallet.position,
6822
6781
  characters: this.$__wallet.characters,
6823
6782
  mlKemParameterSet: this.$__wallet.mlKemParameterSet
@@ -8306,8 +8265,8 @@ var QueryContinuId = class extends Query {
8306
8265
  */
8307
8266
  constructor(graphQLClient, knishIOClient) {
8308
8267
  super(graphQLClient, knishIOClient);
8309
- this.$__query = gql`query ($bundle: String!) {
8310
- ContinuId(bundle: $bundle) {
8268
+ this.$__query = gql`query ($bundle: String!, $token: String) {
8269
+ ContinuId(bundle: $bundle, token: $token) {
8311
8270
  address,
8312
8271
  bundleHash,
8313
8272
  tokenSlug,
@@ -9593,7 +9552,7 @@ var ResponseProposeMolecule = class extends Response2 {
9593
9552
  code: "HASH_MISMATCH"
9594
9553
  });
9595
9554
  }
9596
- if (/ots.*position.*reuse|position.*already.*used|ots.*verification/.test(lc)) {
9555
+ if (/ots.*(?:position|key).*reuse|position.*already.*(?:used|consumed)|ots.*verification/.test(lc)) {
9597
9556
  return new SignatureMismatchException(reason, {
9598
9557
  details: { reason },
9599
9558
  code: "OTS_VERIFICATION_FAILED"
@@ -9611,6 +9570,18 @@ var ResponseProposeMolecule = class extends Response2 {
9611
9570
  code: "VERIFICATION_FAILED"
9612
9571
  });
9613
9572
  }
9573
+ if (/signer address mismatch/.test(lc)) {
9574
+ return new SignatureMismatchException(reason, {
9575
+ details: { reason },
9576
+ code: "SIGNER_ADDRESS_MISMATCH"
9577
+ });
9578
+ }
9579
+ if (/no accepted origin available/.test(lc)) {
9580
+ return new AtomIndexException(reason, {
9581
+ details: { reason },
9582
+ code: "ORIGIN_PENDING"
9583
+ });
9584
+ }
9614
9585
  return null;
9615
9586
  }
9616
9587
  /**
@@ -10108,12 +10079,10 @@ var MutationWithdrawBufferToken = class extends MutationProposeMolecule {
10108
10079
  * Fills the molecule with buffer withdrawal data
10109
10080
  */
10110
10081
  fillMolecule({
10111
- recipients,
10112
- signingWallet
10082
+ recipients
10113
10083
  }) {
10114
10084
  this.$__molecule.initWithdrawBuffer({
10115
- recipients,
10116
- signingWallet
10085
+ recipients
10117
10086
  });
10118
10087
  this.$__molecule.sign({});
10119
10088
  this.$__molecule.check(this.$__molecule.sourceWallet);
@@ -11599,24 +11568,27 @@ var KnishIOClient = class {
11599
11568
  this.setCellSlug(cellSlug);
11600
11569
  }
11601
11570
  this.$__authInProcess = true;
11602
- let response;
11603
- if (secret) {
11604
- response = await this.requestProfileAuthToken({
11605
- secret,
11606
- encrypt
11607
- });
11608
- } else {
11609
- response = await this.requestGuestAuthToken({
11610
- cellSlug: cellSlug || this.getCellSlug(),
11611
- encrypt
11612
- });
11613
- }
11614
- if (this.$__authToken) {
11615
- this.log("info", `KnishIOClient::requestAuthToken() - Successfully retrieved auth token...`);
11571
+ try {
11572
+ let response;
11573
+ if (secret) {
11574
+ response = await this.requestProfileAuthToken({
11575
+ secret,
11576
+ encrypt
11577
+ });
11578
+ } else {
11579
+ response = await this.requestGuestAuthToken({
11580
+ cellSlug: cellSlug || this.getCellSlug(),
11581
+ encrypt
11582
+ });
11583
+ }
11584
+ if (this.$__authToken) {
11585
+ this.log("info", `KnishIOClient::requestAuthToken() - Successfully retrieved auth token...`);
11586
+ }
11587
+ this.switchEncryption(encrypt);
11588
+ return response;
11589
+ } finally {
11590
+ this.$__authInProcess = false;
11616
11591
  }
11617
- this.switchEncryption(encrypt);
11618
- this.$__authInProcess = false;
11619
- return response;
11620
11592
  }
11621
11593
  /**
11622
11594
  * Logging utility
@@ -11760,14 +11732,16 @@ var KnishIOClient = class {
11760
11732
  }
11761
11733
  /**
11762
11734
  * Query next ContinuId wallet
11735
+ *
11736
+ * @param token - Restricts the lookup to wallets of this token. Without it the validator falls
11737
+ * back to the bundle's newest wallet of ANY token when the bundle has no ContinuID pointer.
11763
11738
  */
11764
11739
  async queryContinuId({
11765
- bundle
11740
+ bundle,
11741
+ token = null
11766
11742
  }) {
11767
11743
  const query = this.createQuery(QueryContinuId);
11768
- return this.executeQuery(query, {
11769
- bundle
11770
- });
11744
+ return this.executeQuery(query, token ? { bundle, token } : { bundle });
11771
11745
  }
11772
11746
  /**
11773
11747
  * Query metadata
@@ -12584,8 +12558,7 @@ var KnishIOClient = class {
12584
12558
  async withdrawBufferToken({
12585
12559
  tokenSlug,
12586
12560
  amount,
12587
- sourceWallet = null,
12588
- signingWallet = null
12561
+ sourceWallet = null
12589
12562
  }) {
12590
12563
  this.log("info", `KnishIOClient::withdrawBufferToken() - Withdrawing ${amount} of ${tokenSlug} from buffer...`);
12591
12564
  if (!sourceWallet) {
@@ -12594,11 +12567,7 @@ var KnishIOClient = class {
12594
12567
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationWithdrawBufferToken });
12595
12568
  const recipients = {};
12596
12569
  recipients[this.getBundle()] = amount;
12597
- const fillMoleculeParams = { recipients };
12598
- if (signingWallet) {
12599
- fillMoleculeParams.signingWallet = signingWallet;
12600
- }
12601
- await mutation.fillMolecule(fillMoleculeParams);
12570
+ await mutation.fillMolecule({ recipients });
12602
12571
  const response = await this.executeQuery(mutation);
12603
12572
  if (!response) {
12604
12573
  throw new CodeException("Buffer token withdrawal failed");
@@ -12616,21 +12585,33 @@ var KnishIOClient = class {
12616
12585
  encrypt = false
12617
12586
  } = {}) {
12618
12587
  this.log("info", "KnishIOClient::requestGuestAuthToken() - Requesting guest auth token...");
12619
- const mutation = this.createQuery(MutationRequestAuthorizationGuest);
12620
- const response = await this.executeQuery(mutation, {
12621
- cellSlug: cellSlug || this.getCellSlug()
12622
- });
12623
- if (!response) {
12624
- throw new CodeException("Guest auth token request failed");
12625
- }
12626
- if (encrypt) {
12627
- this.switchEncryption(true);
12588
+ const authInProcess = this.$__authInProcess;
12589
+ this.$__authInProcess = true;
12590
+ try {
12591
+ const mutation = this.createQuery(MutationRequestAuthorizationGuest);
12592
+ const response = await this.executeQuery(mutation, {
12593
+ cellSlug: cellSlug || this.getCellSlug()
12594
+ });
12595
+ if (!response) {
12596
+ throw new CodeException("Guest auth token request failed");
12597
+ }
12598
+ if (encrypt) {
12599
+ this.switchEncryption(true);
12600
+ }
12601
+ return response;
12602
+ } finally {
12603
+ this.$__authInProcess = authInProcess;
12628
12604
  }
12629
- return response;
12630
12605
  }
12631
12606
  /**
12632
12607
  * Request profile authentication token
12633
- * Matches JavaScript SDK requestProfileAuthToken implementation
12608
+ *
12609
+ * A returning user (the bundle has a USER ContinuID pointer) signs from the USER wallet
12610
+ * registered at that pointer, so validator 0.5.0+ marks the token proven and the identity keeps
12611
+ * read/subscription access to permissioned and private cells. A first login — or a pointer this
12612
+ * secret does not own — signs from a fresh AUTH wallet as before. A rejected pointer-signed
12613
+ * login falls back to the AUTH login exactly once, so one call sends at most two
12614
+ * authorization molecules (testnet allows 3 auths/min/IP).
12634
12615
  */
12635
12616
  async requestProfileAuthToken({
12636
12617
  secret,
@@ -12638,13 +12619,58 @@ var KnishIOClient = class {
12638
12619
  }) {
12639
12620
  this.log("info", "KnishIOClient::requestProfileAuthToken() - Requesting profile auth token...");
12640
12621
  this.setSecret(secret);
12641
- const wallet = new Wallet({
12642
- secret,
12643
- token: "AUTH",
12644
- mlKemParameterSet: this.getMlKemParameterSet()
12645
- });
12622
+ const authInProcess = this.$__authInProcess;
12623
+ this.$__authInProcess = true;
12624
+ try {
12625
+ const pointer = (await this.queryContinuId({
12626
+ bundle: this.getBundle(),
12627
+ token: "USER"
12628
+ }))?.payload();
12629
+ let pointerWallet = null;
12630
+ if (pointer && pointer.token === "USER" && pointer.position) {
12631
+ const wallet2 = new Wallet({
12632
+ secret,
12633
+ token: "USER",
12634
+ position: pointer.position,
12635
+ mlKemParameterSet: this.getMlKemParameterSet()
12636
+ });
12637
+ if (!pointer.address || wallet2.address === pointer.address) {
12638
+ pointerWallet = wallet2;
12639
+ } else {
12640
+ this.log("warn", "KnishIOClient::requestProfileAuthToken() - ContinuID wallet address does not derive from this secret; signing from a fresh AUTH wallet");
12641
+ }
12642
+ }
12643
+ if (pointerWallet) {
12644
+ const response2 = await this.proposeProfileAuthorization(pointerWallet, encrypt);
12645
+ if (response2.success()) {
12646
+ this.log("info", "KnishIOClient::requestProfileAuthToken() - Auth token signed from the ContinuID pointer (proven)");
12647
+ return this.acceptProfileAuthorization(response2, pointerWallet, encrypt);
12648
+ }
12649
+ this.log("warn", `KnishIOClient::requestProfileAuthToken() - Pointer-signed authorization rejected (${response2.reason()}); falling back once to an AUTH-wallet login`);
12650
+ }
12651
+ const wallet = new Wallet({
12652
+ secret,
12653
+ token: "AUTH",
12654
+ mlKemParameterSet: this.getMlKemParameterSet()
12655
+ });
12656
+ const response = await this.proposeProfileAuthorization(wallet, encrypt);
12657
+ if (!response.success()) {
12658
+ throw new AuthorizationRejectedException_default(
12659
+ `KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${response.reason()}`
12660
+ );
12661
+ }
12662
+ 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"})`);
12663
+ return this.acceptProfileAuthorization(response, wallet, encrypt);
12664
+ } finally {
12665
+ this.$__authInProcess = authInProcess;
12666
+ }
12667
+ }
12668
+ /**
12669
+ * Signs and proposes a profile authorization molecule from the given source wallet.
12670
+ */
12671
+ async proposeProfileAuthorization(wallet, encrypt) {
12646
12672
  const molecule = await this.createMolecule({
12647
- secret,
12673
+ secret: this.getSecret(),
12648
12674
  sourceWallet: wallet
12649
12675
  });
12650
12676
  const mutation = await this.createMoleculeMutation({
@@ -12662,19 +12688,20 @@ var KnishIOClient = class {
12662
12688
  if (!response) {
12663
12689
  throw new CodeException("Profile auth token request failed");
12664
12690
  }
12665
- if (response.success()) {
12666
- const authToken = AuthToken.create({
12667
- token: response.token(),
12668
- expiresAt: response.expiresAt(),
12669
- encrypt: String(response.encrypt()) === "true",
12670
- pubkey: response.pubKey()
12671
- }, wallet);
12672
- this.setAuthToken(authToken);
12673
- } else {
12674
- throw new AuthorizationRejectedException_default(
12675
- `KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${response.reason()}`
12676
- );
12677
- }
12691
+ return response;
12692
+ }
12693
+ /**
12694
+ * Binds the accepted authorization's token to the wallet that signed it.
12695
+ */
12696
+ acceptProfileAuthorization(response, wallet, encrypt) {
12697
+ const authToken = AuthToken.create({
12698
+ token: response.token(),
12699
+ expiresAt: response.expiresAt(),
12700
+ encrypt: String(response.encrypt()) === "true",
12701
+ pubkey: response.pubKey()
12702
+ }, wallet);
12703
+ this.setAuthToken(authToken);
12704
+ this.lastMoleculeQuery = null;
12678
12705
  if (encrypt) {
12679
12706
  this.switchEncryption(true);
12680
12707
  }
@@ -14032,7 +14059,7 @@ function createDefaultSecretStorage(options = {}) {
14032
14059
  }
14033
14060
 
14034
14061
  // src/index.ts
14035
- var SDK_VERSION = "1.2.0";
14062
+ var SDK_VERSION = "1.3.0";
14036
14063
  var SDK_NAME = "KnishIO-Client-TS";
14037
14064
  var COMPATIBLE_SERVER_VERSIONS = [4, 5];
14038
14065
  var SDK_INFO = {