@wishknish/knishio-client-ts 0.9.5 → 0.9.7

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
@@ -521,6 +521,55 @@ var init_TransferBalanceException = __esm({
521
521
  }
522
522
  });
523
523
 
524
+ // src/exception/SecretStorageException.ts
525
+ var SecretStorageException;
526
+ var init_SecretStorageException = __esm({
527
+ "src/exception/SecretStorageException.ts"() {
528
+ init_BaseException();
529
+ SecretStorageException = class _SecretStorageException extends BaseException {
530
+ constructor(message = "Secret storage operation failed", options = {}) {
531
+ super("WALLET_CREDENTIAL_ERROR", message, {
532
+ code: "SECRET_STORAGE_ERROR",
533
+ ...options
534
+ });
535
+ }
536
+ /**
537
+ * Secret not found for the requested bundle hash
538
+ */
539
+ static notFound(bundleHash) {
540
+ return new _SecretStorageException(`Secret not found for bundle: ${bundleHash}`, {
541
+ code: "SECRET_NOT_FOUND",
542
+ details: { bundleHash }
543
+ });
544
+ }
545
+ /**
546
+ * Decryption failed (wrong passphrase or corrupted payload)
547
+ */
548
+ static decryptionFailed(reason) {
549
+ return new _SecretStorageException(
550
+ `Failed to decrypt master secret: ${reason || "Invalid passphrase or corrupted ciphertext"}`,
551
+ {
552
+ code: "DECRYPTION_FAILED",
553
+ details: { reason }
554
+ }
555
+ );
556
+ }
557
+ /**
558
+ * Provider is unavailable in current platform
559
+ */
560
+ static unavailable(provider, reason) {
561
+ return new _SecretStorageException(
562
+ `Secret storage provider '${provider}' is unavailable: ${reason || "Hardware or API not accessible"}`,
563
+ {
564
+ code: "STORAGE_UNAVAILABLE",
565
+ details: { provider, reason }
566
+ }
567
+ );
568
+ }
569
+ };
570
+ }
571
+ });
572
+
524
573
  // src/exception/InvalidResponseException.ts
525
574
  var InvalidResponseException;
526
575
  var init_InvalidResponseException = __esm({
@@ -983,6 +1032,7 @@ var init_exception = __esm({
983
1032
  init_SignatureMismatchException();
984
1033
  init_TransferBalanceException();
985
1034
  init_WalletCredentialException();
1035
+ init_SecretStorageException();
986
1036
  init_InvalidResponseException();
987
1037
  init_BalanceInsufficientException();
988
1038
  init_BatchIdException();
@@ -2172,11 +2222,9 @@ function verifyOTSSignature(otsFragments, molecularHash, signingAddress) {
2172
2222
  const base17Hash = convertToBase17(molecularHash);
2173
2223
  const enumerated = enumerateMolecularHash(base17Hash);
2174
2224
  const normalized = normalizeMolecularHash(enumerated);
2175
- let ots = otsFragments;
2225
+ const ots = otsFragments;
2176
2226
  if (ots.length !== 2048) {
2177
- if (ots.length !== 2048) {
2178
- return false;
2179
- }
2227
+ return false;
2180
2228
  }
2181
2229
  const otsChunks = [];
2182
2230
  for (let i = 0; i < ots.length; i += CRYPTO_CONSTANTS.KEY_FRAGMENT_SIZE) {
@@ -2679,6 +2727,123 @@ var Meta = class {
2679
2727
  });
2680
2728
  }
2681
2729
  };
2730
+
2731
+ // src/libraries/array.ts
2732
+ function deepCloning(o, h) {
2733
+ let i;
2734
+ let r;
2735
+ let x;
2736
+ const t = [Array, Date, Number, String, Boolean];
2737
+ const s = Object.prototype.toString;
2738
+ h = h || [];
2739
+ for (i = 0; i < h.length; i += 2) {
2740
+ if (o === h[i]) {
2741
+ return h[i + 1];
2742
+ }
2743
+ }
2744
+ if (!r && o && typeof o === "object") {
2745
+ r = {};
2746
+ for (i = 0; i < t.length; i++) {
2747
+ if (s.call(o) === s.call(x = new t[i](o))) {
2748
+ r = i ? x : [];
2749
+ }
2750
+ }
2751
+ h.push(o, r);
2752
+ for (i in o) {
2753
+ if (Object.prototype.hasOwnProperty.call(o, i)) {
2754
+ r[i] = deepCloning(o[i], h);
2755
+ }
2756
+ }
2757
+ }
2758
+ return r || o;
2759
+ }
2760
+ function chunkArray(arr, size) {
2761
+ const chunks = [];
2762
+ for (let i = 0; i < arr.length; i += size) {
2763
+ chunks.push(arr.slice(i, i + size));
2764
+ }
2765
+ return chunks;
2766
+ }
2767
+ function diff(...arrays) {
2768
+ return [].concat(...arrays.map((arr, i) => {
2769
+ const others = arrays.slice(0);
2770
+ others.splice(i, 1);
2771
+ const unique = [...new Set([].concat(...others))];
2772
+ return arr.filter((item) => !unique.includes(item));
2773
+ }));
2774
+ }
2775
+ function intersect(...arrays) {
2776
+ if (arrays.length === 0) return [];
2777
+ if (arrays.length === 1) return arrays[0];
2778
+ return arrays.reduce(
2779
+ (first, second) => first.filter((item) => second.includes(item))
2780
+ );
2781
+ }
2782
+
2783
+ // src/core/PolicyMeta.ts
2784
+ var PolicyMeta = class _PolicyMeta {
2785
+ policy;
2786
+ /**
2787
+ * Create new PolicyMeta instance
2788
+ * Matches JavaScript SDK constructor signature exactly
2789
+ */
2790
+ constructor(policy = {}, metaKeys = []) {
2791
+ this.policy = _PolicyMeta.normalizePolicy(policy);
2792
+ this.fillDefault(metaKeys);
2793
+ }
2794
+ /**
2795
+ * Normalize policy object structure
2796
+ * Matches JavaScript SDK normalizePolicy method exactly
2797
+ */
2798
+ static normalizePolicy(policy = {}) {
2799
+ const policyMeta = {};
2800
+ for (const [policyKey, value] of Object.entries(policy)) {
2801
+ if (value !== null && ["read", "write"].includes(policyKey)) {
2802
+ policyMeta[policyKey] = {};
2803
+ for (const [key, content] of Object.entries(value)) {
2804
+ policyMeta[policyKey][key] = content;
2805
+ }
2806
+ }
2807
+ }
2808
+ return policyMeta;
2809
+ }
2810
+ /**
2811
+ * Fill default policy values for metadata keys
2812
+ * Matches JavaScript SDK fillDefault method exactly
2813
+ */
2814
+ fillDefault(metaKeys = []) {
2815
+ const readPolicy = Array.from(this.policy).filter((item) => item.action === "read");
2816
+ const writePolicy = Array.from(this.policy).filter((item) => item.action === "write");
2817
+ for (const [type, value] of Object.entries({
2818
+ read: readPolicy,
2819
+ write: writePolicy
2820
+ })) {
2821
+ const policyKey = value.map((item) => item.key);
2822
+ if (!this.policy[type]) {
2823
+ this.policy[type] = {};
2824
+ }
2825
+ for (const key of diff(metaKeys, policyKey)) {
2826
+ if (!this.policy[type][key]) {
2827
+ this.policy[type][key] = type === "write" && !["characters", "pubkey"].includes(key) ? ["self"] : ["all"];
2828
+ }
2829
+ }
2830
+ }
2831
+ }
2832
+ /**
2833
+ * Get the policy object
2834
+ * Matches JavaScript SDK get method exactly
2835
+ */
2836
+ get() {
2837
+ return this.policy;
2838
+ }
2839
+ /**
2840
+ * Convert policy to JSON string
2841
+ * Matches JavaScript SDK toJson method exactly
2842
+ */
2843
+ toJson() {
2844
+ return JSON.stringify(this.get());
2845
+ }
2846
+ };
2682
2847
  var AtomMeta = class _AtomMeta {
2683
2848
  meta;
2684
2849
  /**
@@ -2774,8 +2939,9 @@ var AtomMeta = class _AtomMeta {
2774
2939
  * @return This instance for chaining
2775
2940
  */
2776
2941
  addPolicy(policy) {
2942
+ const policyMeta = new PolicyMeta(policy, Object.keys(this.meta));
2777
2943
  this.merge({
2778
- policy: JSON.stringify(policy)
2944
+ policy: policyMeta.toJson()
2779
2945
  });
2780
2946
  return this;
2781
2947
  }
@@ -3408,6 +3574,87 @@ function createMolecularHash(value) {
3408
3574
  }
3409
3575
  return value;
3410
3576
  }
3577
+
3578
+ // src/core/TokenUnit.ts
3579
+ var TokenUnit = class _TokenUnit {
3580
+ id;
3581
+ name;
3582
+ metas;
3583
+ /**
3584
+ * Create new TokenUnit instance
3585
+ * Matches JavaScript SDK constructor signature exactly
3586
+ */
3587
+ constructor(id, name, metas) {
3588
+ this.id = id;
3589
+ this.name = name;
3590
+ this.metas = metas || {};
3591
+ }
3592
+ /**
3593
+ * Create TokenUnit from GraphQL response data
3594
+ * Matches JavaScript SDK createFromGraphQL method exactly
3595
+ */
3596
+ static createFromGraphQL(data) {
3597
+ let metas = data.metas || {};
3598
+ if (Array.isArray(metas) && metas.length) {
3599
+ try {
3600
+ metas = JSON.parse(metas);
3601
+ if (!metas) {
3602
+ metas = {};
3603
+ }
3604
+ } catch (error) {
3605
+ metas = {};
3606
+ }
3607
+ }
3608
+ return new _TokenUnit(
3609
+ data.id,
3610
+ data.name,
3611
+ metas
3612
+ );
3613
+ }
3614
+ /**
3615
+ * Create TokenUnit from database array data
3616
+ * Matches JavaScript SDK createFromDB method exactly
3617
+ */
3618
+ static createFromDB(data) {
3619
+ return new _TokenUnit(
3620
+ data[0],
3621
+ data[1],
3622
+ data.length > 2 ? data[2] : {}
3623
+ );
3624
+ }
3625
+ /**
3626
+ * Get fragment zone from metadata
3627
+ * Matches JavaScript SDK getFragmentZone method exactly
3628
+ */
3629
+ getFragmentZone() {
3630
+ return this.metas.fragmentZone || null;
3631
+ }
3632
+ /**
3633
+ * Get fused token units from metadata
3634
+ * Matches JavaScript SDK getFusedTokenUnits method exactly
3635
+ */
3636
+ getFusedTokenUnits() {
3637
+ return this.metas.fusedTokenUnits || null;
3638
+ }
3639
+ /**
3640
+ * Convert to data array format
3641
+ * Matches JavaScript SDK toData method exactly
3642
+ */
3643
+ toData() {
3644
+ return [this.id, this.name, this.metas];
3645
+ }
3646
+ /**
3647
+ * Convert to GraphQL response format
3648
+ * Matches JavaScript SDK toGraphQLResponse method exactly
3649
+ */
3650
+ toGraphQLResponse() {
3651
+ return {
3652
+ id: this.id,
3653
+ name: this.name,
3654
+ metas: JSON.stringify(this.metas)
3655
+ };
3656
+ }
3657
+ };
3411
3658
  var Wallet = class _Wallet {
3412
3659
  token;
3413
3660
  balance;
@@ -3548,11 +3795,13 @@ var Wallet = class _Wallet {
3548
3795
  return typeof maybeBundleHash === "string" && isBundleHash(maybeBundleHash);
3549
3796
  }
3550
3797
  /**
3551
- * Get formatted token units from raw data
3552
- * Stub implementation for now
3798
+ * Map raw token-unit tuples to TokenUnit instances.
3799
+ * Matches JS SDK Wallet.getTokenUnits (Wallet.js:190-196). The serialised shape reaches hashed
3800
+ * atom meta via AtomMeta.setAtomWallet -> JSON.stringify(getTokenUnitsData()), so returning raw
3801
+ * tuples here would diverge from every other SDK.
3553
3802
  */
3554
3803
  static getTokenUnits(unitsData) {
3555
- return unitsData;
3804
+ return unitsData.map((unitData) => TokenUnit.createFromDB(unitData));
3556
3805
  }
3557
3806
  /**
3558
3807
  * Create a remainder wallet for transactions
@@ -3849,7 +4098,7 @@ z.string().regex(base17HashRegex, "Molecular hash must be base17 format (0-9,a-g
3849
4098
  var TokenSlugSchema = z.string().min(1, "Token slug cannot be empty").max(64, "Token slug cannot exceed 64 characters").transform((val) => val.toUpperCase()).brand();
3850
4099
  var MetaTypeSchema = z.string().min(1, "Meta type cannot be empty").max(256, "Meta type cannot exceed 256 characters").brand();
3851
4100
  var MetaIdSchema = z.string().min(1, "Meta ID cannot be empty").brand();
3852
- var BatchIdSchema = z.string().min(1, "Batch ID cannot be empty").brand();
4101
+ var BatchIdSchema = z.string().regex(/^[0-9a-fA-F]{64}$/, "Batch ID must be 64 hexadecimal characters").brand();
3853
4102
  var CellSlugSchema = z.string().min(1, "Cell slug cannot be empty").max(64, "Cell slug cannot exceed 64 characters").brand();
3854
4103
  var AtomIsotopeSchema = z.enum(["C", "V", "U", "T", "M", "I", "R", "B", "F"], {
3855
4104
  error: "Invalid atom isotope. Must be one of: C, V, U, T, M, I, R, B, F"
@@ -3910,7 +4159,8 @@ z.object({
3910
4159
  socket: z.unknown().optional(),
3911
4160
  serverSdkVersion: z.number().int().min(1).optional(),
3912
4161
  logging: z.boolean().optional(),
3913
- defaultRequestPolicy: z.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional()
4162
+ defaultRequestPolicy: z.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional(),
4163
+ secretStorage: z.unknown().optional()
3914
4164
  }).strict();
3915
4165
  z.object({
3916
4166
  token: z.string().min(1, "Auth token cannot be empty"),
@@ -4173,58 +4423,6 @@ var RuleArgumentException = class extends BaseException {
4173
4423
  };
4174
4424
  var RuleArgumentException_default = RuleArgumentException;
4175
4425
 
4176
- // src/libraries/array.ts
4177
- function deepCloning(o, h) {
4178
- let i;
4179
- let r;
4180
- let x;
4181
- const t = [Array, Date, Number, String, Boolean];
4182
- const s = Object.prototype.toString;
4183
- h = h || [];
4184
- for (i = 0; i < h.length; i += 2) {
4185
- if (o === h[i]) {
4186
- return h[i + 1];
4187
- }
4188
- }
4189
- if (!r && o && typeof o === "object") {
4190
- r = {};
4191
- for (i = 0; i < t.length; i++) {
4192
- if (s.call(o) === s.call(x = new t[i](o))) {
4193
- r = i ? x : [];
4194
- }
4195
- }
4196
- h.push(o, r);
4197
- for (i in o) {
4198
- if (Object.prototype.hasOwnProperty.call(o, i)) {
4199
- r[i] = deepCloning(o[i], h);
4200
- }
4201
- }
4202
- }
4203
- return r || o;
4204
- }
4205
- function chunkArray(arr, size) {
4206
- const chunks = [];
4207
- for (let i = 0; i < arr.length; i += size) {
4208
- chunks.push(arr.slice(i, i + size));
4209
- }
4210
- return chunks;
4211
- }
4212
- function diff(...arrays) {
4213
- return [].concat(...arrays.map((arr, i) => {
4214
- const others = arrays.slice(0);
4215
- others.splice(i, 1);
4216
- const unique = [...new Set([].concat(...others))];
4217
- return arr.filter((item) => !unique.includes(item));
4218
- }));
4219
- }
4220
- function intersect(...arrays) {
4221
- if (arrays.length === 0) return [];
4222
- if (arrays.length === 1) return arrays[0];
4223
- return arrays.reduce(
4224
- (first, second) => first.filter((item) => second.includes(item))
4225
- );
4226
- }
4227
-
4228
4426
  // src/instance/rules/Callback.ts
4229
4427
  init_exception();
4230
4428
  var CallbackParamsSchema = z.object({
@@ -5555,6 +5753,51 @@ var Molecule = class _Molecule {
5555
5753
  }));
5556
5754
  return this;
5557
5755
  }
5756
+ /**
5757
+ * Replenishes non-finite token supplies.
5758
+ * Matches JS SDK Molecule.replenishToken (Molecule.js:521-566) exactly.
5759
+ *
5760
+ * Two orderings here are load-bearing for the molecular hash and must not be reordered:
5761
+ * the remainder balance is computed BEFORE the source balance is overwritten, and the
5762
+ * source V-atom is added BEFORE the remainder V-atom.
5763
+ */
5764
+ replenishToken({
5765
+ amount,
5766
+ units = []
5767
+ }) {
5768
+ if (amount < 0) {
5769
+ throw new NegativeAmountException("Molecule::replenishToken() - Amount to replenish must be positive!");
5770
+ }
5771
+ if (!this.sourceWallet || !this.remainderWallet) {
5772
+ throw new Error("Source and remainder wallets required for token replenishment");
5773
+ }
5774
+ if (units.length) {
5775
+ const formatted = Wallet.getTokenUnits(units);
5776
+ this.remainderWallet.tokenUnits = this.sourceWallet.tokenUnits;
5777
+ for (const unit of formatted) {
5778
+ this.remainderWallet.tokenUnits.push(unit);
5779
+ }
5780
+ this.remainderWallet.balance = String(this.remainderWallet.tokenUnits.length);
5781
+ this.sourceWallet.tokenUnits = formatted;
5782
+ this.sourceWallet.balance = String(this.sourceWallet.tokenUnits.length);
5783
+ } else {
5784
+ this.remainderWallet.balance = String(Number(this.sourceWallet.balance) + amount);
5785
+ this.sourceWallet.balance = String(amount);
5786
+ }
5787
+ this.addAtom(Atom.create({
5788
+ isotope: "V",
5789
+ wallet: this.sourceWallet,
5790
+ value: Number(this.sourceWallet.balance)
5791
+ }));
5792
+ this.addAtom(Atom.create({
5793
+ isotope: "V",
5794
+ wallet: this.remainderWallet,
5795
+ value: Number(this.remainderWallet.balance),
5796
+ metaType: "walletBundle",
5797
+ metaId: this.remainderWallet.bundle
5798
+ }));
5799
+ return this;
5800
+ }
5558
5801
  /**
5559
5802
  * Initialize authorization request
5560
5803
  * Creates U-isotope (authorization) atom for requesting auth token
@@ -6089,16 +6332,27 @@ var GraphQLClient = class {
6089
6332
  return createClient$1({
6090
6333
  url: serverUri,
6091
6334
  exchanges,
6092
- // PQ-transport Phase E: when encryption is on, route fetch through the CipherHash wrapper
6093
- // (encrypt the request body to the validator's ML-KEM pubkey, decrypt the response).
6094
- // Omitted → urql uses the global fetch (plaintext).
6095
- ...this.cipherLink ? { fetch: ((input, init) => this.cipherFetch(input, init)) } : {},
6335
+ // urql 5 had no default and always POSTed; urql 6 defaults to 'within-url-limit', which
6336
+ // URL-encodes short queries and sends NO body. That would silently disable the CipherHash
6337
+ // envelope below — cipherFetch's `typeof init.body === 'string'` guard fails on a GET, so
6338
+ // the query would leave as plaintext URL parameters with no error. Pin POST explicitly.
6339
+ preferGetMethod: false,
6340
+ // Always route through our own fetch. Two reasons: (1) PQ-transport Phase E — when
6341
+ // encryption is on, cipherFetch wraps the request body in the CipherHash envelope and
6342
+ // decrypts the response; (2) the 60s timeout. urql's makeFetchSource unconditionally
6343
+ // overwrites init.signal with its own AbortController, so a signal returned from
6344
+ // fetchOptions() is discarded and never fired. Combining it here is the only place it
6345
+ // survives.
6346
+ fetch: ((input, init) => {
6347
+ const timeoutSignal = AbortSignal.timeout(6e4);
6348
+ const signal = init?.signal && typeof AbortSignal.any === "function" ? AbortSignal.any([init.signal, timeoutSignal]) : init?.signal ?? timeoutSignal;
6349
+ const timedInit = { ...init, signal };
6350
+ return this.cipherLink ? this.cipherFetch(input, timedInit) : fetch(input, timedInit);
6351
+ }),
6096
6352
  fetchOptions: () => ({
6097
6353
  headers: {
6098
6354
  "X-Auth-Token": this.$__authToken
6099
- },
6100
- // Add 60 second timeout
6101
- signal: AbortSignal.timeout(6e4)
6355
+ }
6102
6356
  })
6103
6357
  });
6104
6358
  }
@@ -6611,12 +6865,12 @@ var TokenSlugSchema2 = createBrandedSchema(
6611
6865
  );
6612
6866
  var BatchIdSchema2 = createBrandedSchema(
6613
6867
  "BatchId",
6614
- // v3's `.uuid()` regex, inlined verbatim. Zod 4's `z.uuid()` additionally enforces the
6615
- // RFC 9562 version/variant nibbles and would reject batch IDs v3 accepted.
6616
- z.string().regex(
6617
- /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,
6618
- "Invalid batch ID format"
6619
- )
6868
+ // 64 hex characters. generateBatchId (src/libraries/crypto.ts) returns either
6869
+ // shake256(molecularHash + index, 256) — 256 bits, 64 hex chars — or randomString(64) over the
6870
+ // alphabet 'abcdef0123456789'. A UUID shape matches nothing this SDK can produce, so the
6871
+ // previous 8-4-4-4-12 regex rejected every real batch ID. Agrees with isBatchId in
6872
+ // src/types/guards.ts.
6873
+ z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid batch ID format")
6620
6874
  );
6621
6875
  var CellSlugSchema2 = createBrandedSchema(
6622
6876
  "CellSlug",
@@ -6706,7 +6960,9 @@ var KnishIOClientConfigSchema2 = z.object({
6706
6960
  // Optional default urql request policy for reads (server/sync clients pass
6707
6961
  // 'network-only'). Permitted by the strict schema so the constructor option
6708
6962
  // isn't rejected.
6709
- defaultRequestPolicy: z.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional()
6963
+ defaultRequestPolicy: z.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional(),
6964
+ // Pluggable hardware envelope encryption secret storage provider
6965
+ secretStorage: z.unknown().optional()
6710
6966
  }).strict();
6711
6967
  var EnvironmentConfigSchema = z.object({
6712
6968
  NODE_ENV: z.enum(["development", "production", "test"]).optional(),
@@ -7481,127 +7737,44 @@ var ConfigValidator = class _ConfigValidator {
7481
7737
  duration
7482
7738
  });
7483
7739
  if (this.performanceMetrics.length > 1e3) {
7484
- this.performanceMetrics = this.performanceMetrics.slice(-1e3);
7485
- }
7486
- }
7487
- /**
7488
- * Clean up validation cache
7489
- */
7490
- cleanupCache() {
7491
- if (this.validationCache.size > 500) {
7492
- const entries = Array.from(this.validationCache.entries());
7493
- const toKeep = entries.slice(-250);
7494
- this.validationCache.clear();
7495
- toKeep.forEach(([key, value]) => this.validationCache.set(key, value));
7496
- }
7497
- }
7498
- /**
7499
- * Get validation statistics
7500
- */
7501
- getValidationStats() {
7502
- const recent = this.performanceMetrics.slice(-100);
7503
- const avgTime = recent.reduce((sum, m) => sum + m.duration, 0) / recent.length || 0;
7504
- return {
7505
- totalValidations: this.performanceMetrics.length,
7506
- cacheSize: this.validationCache.size,
7507
- averageValidationTime: Math.round(avgTime * 100) / 100,
7508
- recentValidations: recent.length
7509
- };
7510
- }
7511
- /**
7512
- * Clear validation cache and metrics
7513
- */
7514
- clearCache() {
7515
- this.validationCache.clear();
7516
- this.performanceMetrics = [];
7517
- }
7518
- };
7519
-
7520
- // src/response/ResponseBalance.ts
7521
- init_Response();
7522
-
7523
- // src/core/TokenUnit.ts
7524
- var TokenUnit = class _TokenUnit {
7525
- id;
7526
- name;
7527
- metas;
7528
- /**
7529
- * Create new TokenUnit instance
7530
- * Matches JavaScript SDK constructor signature exactly
7531
- */
7532
- constructor(id, name, metas) {
7533
- this.id = id;
7534
- this.name = name;
7535
- this.metas = metas || {};
7536
- }
7537
- /**
7538
- * Create TokenUnit from GraphQL response data
7539
- * Matches JavaScript SDK createFromGraphQL method exactly
7540
- */
7541
- static createFromGraphQL(data) {
7542
- let metas = data.metas || {};
7543
- if (Array.isArray(metas) && metas.length) {
7544
- try {
7545
- metas = JSON.parse(metas);
7546
- if (!metas) {
7547
- metas = {};
7548
- }
7549
- } catch (error) {
7550
- metas = {};
7551
- }
7552
- }
7553
- return new _TokenUnit(
7554
- data.id,
7555
- data.name,
7556
- metas
7557
- );
7558
- }
7559
- /**
7560
- * Create TokenUnit from database array data
7561
- * Matches JavaScript SDK createFromDB method exactly
7562
- */
7563
- static createFromDB(data) {
7564
- return new _TokenUnit(
7565
- data[0],
7566
- data[1],
7567
- data.length > 2 ? data[2] : {}
7568
- );
7569
- }
7570
- /**
7571
- * Get fragment zone from metadata
7572
- * Matches JavaScript SDK getFragmentZone method exactly
7573
- */
7574
- getFragmentZone() {
7575
- return this.metas.fragmentZone || null;
7576
- }
7577
- /**
7578
- * Get fused token units from metadata
7579
- * Matches JavaScript SDK getFusedTokenUnits method exactly
7580
- */
7581
- getFusedTokenUnits() {
7582
- return this.metas.fusedTokenUnits || null;
7740
+ this.performanceMetrics = this.performanceMetrics.slice(-1e3);
7741
+ }
7583
7742
  }
7584
7743
  /**
7585
- * Convert to data array format
7586
- * Matches JavaScript SDK toData method exactly
7744
+ * Clean up validation cache
7587
7745
  */
7588
- toData() {
7589
- return [this.id, this.name, this.metas];
7746
+ cleanupCache() {
7747
+ if (this.validationCache.size > 500) {
7748
+ const entries = Array.from(this.validationCache.entries());
7749
+ const toKeep = entries.slice(-250);
7750
+ this.validationCache.clear();
7751
+ toKeep.forEach(([key, value]) => this.validationCache.set(key, value));
7752
+ }
7590
7753
  }
7591
7754
  /**
7592
- * Convert to GraphQL response format
7593
- * Matches JavaScript SDK toGraphQLResponse method exactly
7755
+ * Get validation statistics
7594
7756
  */
7595
- toGraphQLResponse() {
7757
+ getValidationStats() {
7758
+ const recent = this.performanceMetrics.slice(-100);
7759
+ const avgTime = recent.reduce((sum, m) => sum + m.duration, 0) / recent.length || 0;
7596
7760
  return {
7597
- id: this.id,
7598
- name: this.name,
7599
- metas: JSON.stringify(this.metas)
7761
+ totalValidations: this.performanceMetrics.length,
7762
+ cacheSize: this.validationCache.size,
7763
+ averageValidationTime: Math.round(avgTime * 100) / 100,
7764
+ recentValidations: recent.length
7600
7765
  };
7601
7766
  }
7767
+ /**
7768
+ * Clear validation cache and metrics
7769
+ */
7770
+ clearCache() {
7771
+ this.validationCache.clear();
7772
+ this.performanceMetrics = [];
7773
+ }
7602
7774
  };
7603
7775
 
7604
7776
  // src/response/ResponseBalance.ts
7777
+ init_Response();
7605
7778
  var ResponseBalance = class _ResponseBalance extends Response2 {
7606
7779
  /**
7607
7780
  * Class constructor
@@ -10110,6 +10283,12 @@ var MutationAppendRequest = class extends MutationProposeMolecule {
10110
10283
  }
10111
10284
  };
10112
10285
 
10286
+ // src/mutation/MutationReplenishToken.ts
10287
+ var MutationReplenishToken = class extends MutationProposeMolecule {
10288
+ fillMolecule() {
10289
+ }
10290
+ };
10291
+
10113
10292
  // src/subscribe/Subscribe.ts
10114
10293
  init_exception();
10115
10294
  var Subscribe = class {
@@ -10321,9 +10500,134 @@ var ActiveSessionSubscribe = class extends Subscribe {
10321
10500
 
10322
10501
  // src/KnishIOClient.ts
10323
10502
  init_exception();
10503
+
10504
+ // src/storage/MemorySecretStorageProvider.ts
10505
+ init_SecretStorageException();
10506
+
10507
+ // src/libraries/secureMemory.ts
10508
+ var textEncoder = new TextEncoder();
10509
+ function zeroizeBytes(buffer) {
10510
+ if (buffer instanceof Uint8Array) {
10511
+ buffer.fill(0);
10512
+ } else if (Array.isArray(buffer)) {
10513
+ for (let i = 0; i < buffer.length; i++) {
10514
+ buffer[i] = 0;
10515
+ }
10516
+ }
10517
+ }
10518
+ async function withSecureBytes(bytes, fn) {
10519
+ try {
10520
+ return await fn(bytes);
10521
+ } finally {
10522
+ zeroizeBytes(bytes);
10523
+ }
10524
+ }
10525
+ async function withSecureString(secret, fn) {
10526
+ const bytes = textEncoder.encode(secret);
10527
+ try {
10528
+ return await fn(secret);
10529
+ } finally {
10530
+ zeroizeBytes(bytes);
10531
+ }
10532
+ }
10533
+ function constantTimeCompare(a, b) {
10534
+ const bytesA = typeof a === "string" ? textEncoder.encode(a) : a;
10535
+ const bytesB = typeof b === "string" ? textEncoder.encode(b) : b;
10536
+ let result = bytesA.length === bytesB.length ? 0 : 1;
10537
+ const len = Math.min(bytesA.length, bytesB.length);
10538
+ for (let i = 0; i < len; i++) {
10539
+ const byteA = bytesA[i] ?? 0;
10540
+ const byteB = bytesB[i] ?? 0;
10541
+ result |= byteA ^ byteB;
10542
+ }
10543
+ if (typeof a === "string") zeroizeBytes(bytesA);
10544
+ if (typeof b === "string") zeroizeBytes(bytesB);
10545
+ return result === 0;
10546
+ }
10547
+
10548
+ // src/storage/MemorySecretStorageProvider.ts
10549
+ var MemorySecretStorageProvider = class {
10550
+ providerType = "memory";
10551
+ secrets = /* @__PURE__ */ new Map();
10552
+ /**
10553
+ * Memory storage is not hardware backed
10554
+ */
10555
+ isHardwareBacked() {
10556
+ return false;
10557
+ }
10558
+ /**
10559
+ * Memory storage is always available
10560
+ */
10561
+ async isAvailable() {
10562
+ return true;
10563
+ }
10564
+ /**
10565
+ * Store a secret in memory
10566
+ */
10567
+ async storeSecret(bundleHash, secret, options) {
10568
+ if (!bundleHash) {
10569
+ throw new SecretStorageException("Bundle hash cannot be empty");
10570
+ }
10571
+ if (!secret) {
10572
+ throw new SecretStorageException("Secret cannot be empty");
10573
+ }
10574
+ const metadata = {
10575
+ bundleHash,
10576
+ label: options?.label,
10577
+ createdAt: Date.now(),
10578
+ hardwareBacked: false,
10579
+ providerType: this.providerType
10580
+ };
10581
+ this.secrets.set(bundleHash, { secret, metadata });
10582
+ }
10583
+ /**
10584
+ * Retrieve a secret from memory
10585
+ */
10586
+ async retrieveSecret(bundleHash) {
10587
+ const entry = this.secrets.get(bundleHash);
10588
+ return entry ? entry.secret : null;
10589
+ }
10590
+ /**
10591
+ * Delete a stored secret
10592
+ */
10593
+ async deleteSecret(bundleHash) {
10594
+ return this.secrets.delete(bundleHash);
10595
+ }
10596
+ /**
10597
+ * Check if a secret exists
10598
+ */
10599
+ async hasSecret(bundleHash) {
10600
+ return this.secrets.has(bundleHash);
10601
+ }
10602
+ /**
10603
+ * List all stored secret metadata
10604
+ */
10605
+ async listSecrets() {
10606
+ return Array.from(this.secrets.values()).map((entry) => ({ ...entry.metadata }));
10607
+ }
10608
+ /**
10609
+ * Execute callback with unwrapped secret and ensure cleanup
10610
+ */
10611
+ async withSecret(bundleHash, fn) {
10612
+ const entry = this.secrets.get(bundleHash);
10613
+ if (!entry) {
10614
+ throw SecretStorageException.notFound(bundleHash);
10615
+ }
10616
+ return withSecureString(entry.secret, fn);
10617
+ }
10618
+ /**
10619
+ * Clear all secrets from memory
10620
+ */
10621
+ clear() {
10622
+ this.secrets.clear();
10623
+ }
10624
+ };
10625
+
10626
+ // src/KnishIOClient.ts
10324
10627
  var KnishIOClient = class {
10325
10628
  $__secret = "";
10326
10629
  $__bundle = "";
10630
+ $__secretStorage = null;
10327
10631
  $__cellSlug = null;
10328
10632
  $__encrypt = false;
10329
10633
  $__uris = [];
@@ -10383,6 +10687,9 @@ var KnishIOClient = class {
10383
10687
  logging,
10384
10688
  defaultRequestPolicy
10385
10689
  });
10690
+ if (config.secretStorage) {
10691
+ this.$__secretStorage = config.secretStorage;
10692
+ }
10386
10693
  }
10387
10694
  /**
10388
10695
  * Initializes a new Knish.IO client session
@@ -10484,6 +10791,7 @@ var KnishIOClient = class {
10484
10791
  reset() {
10485
10792
  this.$__secret = "";
10486
10793
  this.$__bundle = "";
10794
+ this.$__secretStorage = null;
10487
10795
  this.$__encrypt = false;
10488
10796
  this.$__cellSlug = null;
10489
10797
  this.$__authToken = null;
@@ -10545,7 +10853,7 @@ var KnishIOClient = class {
10545
10853
  * Returns whether a secret is stored for this session
10546
10854
  */
10547
10855
  hasSecret() {
10548
- return !!this.$__secret && this.$__secret.length > 0;
10856
+ return !!this.$__secret && this.$__secret.length > 0 || !!this.$__secretStorage && !!this.$__bundle && this.$__bundle.length > 0;
10549
10857
  }
10550
10858
  /**
10551
10859
  * Returns the stored secret
@@ -10556,6 +10864,33 @@ var KnishIOClient = class {
10556
10864
  }
10557
10865
  return this.$__secret;
10558
10866
  }
10867
+ /**
10868
+ * Sets the secret storage provider and optionally sets the bundle hash
10869
+ */
10870
+ setSecretStorage(storage, bundleHash) {
10871
+ this.$__secretStorage = storage;
10872
+ if (bundleHash) {
10873
+ this.$__bundle = bundleHash;
10874
+ }
10875
+ }
10876
+ /**
10877
+ * Returns current secret storage provider
10878
+ */
10879
+ getSecretStorage() {
10880
+ return this.$__secretStorage;
10881
+ }
10882
+ /**
10883
+ * Asynchronously retrieves the secret from storage or returns in-memory secret
10884
+ */
10885
+ async retrieveSecret(options) {
10886
+ if (this.$__secret && this.$__secret.length > 0) {
10887
+ return this.$__secret;
10888
+ }
10889
+ if (this.$__secretStorage && this.$__bundle && this.$__bundle.length > 0) {
10890
+ return await this.$__secretStorage.retrieveSecret(this.$__bundle, options);
10891
+ }
10892
+ return null;
10893
+ }
10559
10894
  /**
10560
10895
  * Returns whether a bundle hash is being stored for this session
10561
10896
  */
@@ -10594,6 +10929,13 @@ var KnishIOClient = class {
10594
10929
  remainderWallet = null
10595
10930
  } = {}) {
10596
10931
  this.log("info", "KnishIOClient::createMolecule() - Creating a new molecule...");
10932
+ if (!secret) {
10933
+ if (this.$__secret && this.$__secret.length > 0) {
10934
+ secret = this.getSecret();
10935
+ } else if (this.$__secretStorage && this.$__bundle && this.$__bundle.length > 0) {
10936
+ secret = await this.$__secretStorage.retrieveSecret(this.$__bundle);
10937
+ }
10938
+ }
10597
10939
  secret = secret || this.getSecret();
10598
10940
  bundle = bundle || this.getBundle();
10599
10941
  let continuIdPosition = null;
@@ -10623,6 +10965,7 @@ var KnishIOClient = class {
10623
10965
  }));
10624
10966
  return new Molecule({
10625
10967
  secret,
10968
+ bundle,
10626
10969
  sourceWallet,
10627
10970
  remainderWallet: this.getRemainderWallet(),
10628
10971
  cellSlug: this.getCellSlug(),
@@ -10669,8 +11012,9 @@ var KnishIOClient = class {
10669
11012
  async executeQuery(query, variables = null, context = {}) {
10670
11013
  if (this.$__authToken && this.$__authToken.isExpired() && !this.$__authInProcess) {
10671
11014
  this.log("info", "KnishIOClient::executeQuery() - Access token is expired. Getting new one...");
11015
+ const authSecret = this.$__secret || await this.retrieveSecret() || "";
10672
11016
  await this.requestAuthToken({
10673
- secret: this.$__secret,
11017
+ secret: authSecret,
10674
11018
  cellSlug: this.$__cellSlug,
10675
11019
  encrypt: this.$__encrypt
10676
11020
  });
@@ -10710,6 +11054,13 @@ var KnishIOClient = class {
10710
11054
  setSecret(secret) {
10711
11055
  this.$__secret = secret;
10712
11056
  this.$__bundle = generateBundleHash(secret);
11057
+ if (!this.$__secretStorage) {
11058
+ const memStorage = new MemorySecretStorageProvider();
11059
+ memStorage.storeSecret(this.$__bundle, secret);
11060
+ this.$__secretStorage = memStorage;
11061
+ } else {
11062
+ this.$__secretStorage.storeSecret(this.$__bundle, secret);
11063
+ }
10713
11064
  }
10714
11065
  /**
10715
11066
  * Sets the auth token for this session
@@ -10893,6 +11244,9 @@ var KnishIOClient = class {
10893
11244
  if (secret === null && seed) {
10894
11245
  secret = generateSecret(seed);
10895
11246
  }
11247
+ if (secret === null && this.$__secretStorage && this.$__bundle) {
11248
+ secret = await this.$__secretStorage.retrieveSecret(this.$__bundle);
11249
+ }
10896
11250
  if (cellSlug) {
10897
11251
  this.setCellSlug(cellSlug);
10898
11252
  }
@@ -11543,20 +11897,42 @@ var KnishIOClient = class {
11543
11897
  return response;
11544
11898
  }
11545
11899
  /**
11546
- * Replenish tokens
11900
+ * Replenish a non-finite token supply.
11901
+ * Matches JS SDK KnishIOClient.replenishToken (KnishIOClient.js:2195-2231).
11547
11902
  */
11548
11903
  async replenishToken({
11549
11904
  token,
11550
11905
  amount = null,
11551
11906
  units = null,
11552
- sourceWallet: _sourceWallet = null
11907
+ sourceWallet = null
11553
11908
  }) {
11554
11909
  this.log("info", `KnishIOClient::replenishToken() - Replenishing ${amount || "units"} of ${token}...`);
11555
- return this.requestTokens({
11556
- token,
11557
- amount,
11558
- units
11910
+ if (!sourceWallet) {
11911
+ sourceWallet = (await this.queryBalance({ token }))?.payload();
11912
+ }
11913
+ if (!sourceWallet) {
11914
+ throw new TransferBalanceException("Source wallet is missing or invalid.");
11915
+ }
11916
+ const remainderWallet = sourceWallet.createRemainder(this.getSecret());
11917
+ const molecule = await this.createMolecule({
11918
+ sourceWallet,
11919
+ remainderWallet
11920
+ });
11921
+ molecule.replenishToken({
11922
+ amount: Number(amount ?? 0),
11923
+ units: units ?? []
11559
11924
  });
11925
+ molecule.sign({ bundle: this.getBundle() });
11926
+ molecule.check();
11927
+ const mutation = await this.createMoleculeMutation({
11928
+ mutationClass: MutationReplenishToken,
11929
+ molecule
11930
+ });
11931
+ const response = await this.executeQuery(mutation);
11932
+ if (!response) {
11933
+ throw new CodeException("Token replenishment failed");
11934
+ }
11935
+ return response;
11560
11936
  }
11561
11937
  /**
11562
11938
  * Fuse token units
@@ -12007,75 +12383,298 @@ var KnishIOClient = class {
12007
12383
 
12008
12384
  // src/index.ts
12009
12385
  init_Response();
12386
+ init_exception();
12010
12387
 
12011
- // src/core/PolicyMeta.ts
12012
- var PolicyMeta = class _PolicyMeta {
12013
- policy;
12388
+ // src/storage/WebCryptoSecretStorageProvider.ts
12389
+ init_SecretStorageException();
12390
+ var MemoryStorageBackend = class {
12391
+ store = /* @__PURE__ */ new Map();
12392
+ getItem(key) {
12393
+ return this.store.get(key) ?? null;
12394
+ }
12395
+ setItem(key, value) {
12396
+ this.store.set(key, value);
12397
+ }
12398
+ removeItem(key) {
12399
+ return this.store.delete(key);
12400
+ }
12401
+ keys() {
12402
+ return Array.from(this.store.keys());
12403
+ }
12404
+ };
12405
+ function uint8ArrayToBase64(bytes) {
12406
+ let binary = "";
12407
+ const len = bytes.byteLength;
12408
+ for (let i = 0; i < len; i++) {
12409
+ const byte = bytes[i];
12410
+ if (byte !== void 0) {
12411
+ binary += String.fromCharCode(byte);
12412
+ }
12413
+ }
12414
+ return btoa(binary);
12415
+ }
12416
+ function base64ToUint8Array(base64) {
12417
+ const binary = atob(base64);
12418
+ const len = binary.length;
12419
+ const bytes = new Uint8Array(len);
12420
+ for (let i = 0; i < len; i++) {
12421
+ bytes[i] = binary.charCodeAt(i);
12422
+ }
12423
+ return bytes;
12424
+ }
12425
+ var textEncoder2 = new TextEncoder();
12426
+ var textDecoder = new TextDecoder();
12427
+ var KEY_PREFIX = "knishio:secret:";
12428
+ var DEFAULT_ITERATIONS = 1e5;
12429
+ var WebCryptoSecretStorageProvider = class {
12430
+ providerType = "webcrypto-aes-gcm";
12431
+ backend;
12432
+ defaultPassphrase;
12433
+ hardwareBacked;
12434
+ constructor(options = {}) {
12435
+ this.backend = options.backend ?? new MemoryStorageBackend();
12436
+ this.defaultPassphrase = options.defaultPassphrase;
12437
+ this.hardwareBacked = options.hardwareBacked ?? false;
12438
+ }
12014
12439
  /**
12015
- * Create new PolicyMeta instance
12016
- * Matches JavaScript SDK constructor signature exactly
12440
+ * Whether this provider is backed by hardware (e.g. WebAuthn PRF wrapping)
12017
12441
  */
12018
- constructor(policy = {}, metaKeys = []) {
12019
- this.policy = _PolicyMeta.normalizePolicy(policy);
12020
- this.fillDefault(metaKeys);
12442
+ isHardwareBacked() {
12443
+ return this.hardwareBacked;
12021
12444
  }
12022
12445
  /**
12023
- * Normalize policy object structure
12024
- * Matches JavaScript SDK normalizePolicy method exactly
12446
+ * Check if WebCrypto subtle API is available
12025
12447
  */
12026
- static normalizePolicy(policy = {}) {
12027
- const policyMeta = {};
12028
- for (const [policyKey, value] of Object.entries(policy)) {
12029
- if (value !== null && ["read", "write"].includes(policyKey)) {
12030
- policyMeta[policyKey] = {};
12031
- for (const [key, content] of Object.entries(value)) {
12032
- policyMeta[policyKey][key] = content;
12033
- }
12034
- }
12448
+ async isAvailable() {
12449
+ return typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.subtle !== "undefined";
12450
+ }
12451
+ /**
12452
+ * Derive an AES-GCM CryptoKey from a passphrase and salt using PBKDF2
12453
+ */
12454
+ async deriveKey(passphrase, salt, iterations = DEFAULT_ITERATIONS) {
12455
+ if (!await this.isAvailable()) {
12456
+ throw SecretStorageException.unavailable(this.providerType, "WebCrypto API is not available");
12457
+ }
12458
+ const passphraseBytes = textEncoder2.encode(passphrase);
12459
+ try {
12460
+ const baseKey = await globalThis.crypto.subtle.importKey(
12461
+ "raw",
12462
+ passphraseBytes,
12463
+ "PBKDF2",
12464
+ false,
12465
+ ["deriveKey"]
12466
+ );
12467
+ return await globalThis.crypto.subtle.deriveKey(
12468
+ {
12469
+ name: "PBKDF2",
12470
+ salt,
12471
+ iterations,
12472
+ hash: "SHA-256"
12473
+ },
12474
+ baseKey,
12475
+ { name: "AES-GCM", length: 256 },
12476
+ false,
12477
+ ["encrypt", "decrypt"]
12478
+ );
12479
+ } finally {
12480
+ zeroizeBytes(passphraseBytes);
12035
12481
  }
12036
- return policyMeta;
12037
12482
  }
12038
12483
  /**
12039
- * Fill default policy values for metadata keys
12040
- * Matches JavaScript SDK fillDefault method exactly
12484
+ * Store and encrypt a master secret
12041
12485
  */
12042
- fillDefault(metaKeys = []) {
12043
- const readPolicy = Array.from(this.policy).filter((item) => item.action === "read");
12044
- const writePolicy = Array.from(this.policy).filter((item) => item.action === "write");
12045
- for (const [type, value] of Object.entries({
12046
- read: readPolicy,
12047
- write: writePolicy
12048
- })) {
12049
- const policyKey = value.map((item) => item.key);
12050
- if (!this.policy[type]) {
12051
- this.policy[type] = {};
12052
- }
12053
- for (const key of diff(metaKeys, policyKey)) {
12054
- if (!this.policy[type][key]) {
12055
- this.policy[type][key] = type === "write" && !["characters", "pubkey"].includes(key) ? ["self"] : ["all"];
12056
- }
12486
+ async storeSecret(bundleHash, secret, options) {
12487
+ if (!bundleHash) {
12488
+ throw new SecretStorageException("Bundle hash cannot be empty");
12489
+ }
12490
+ if (!secret) {
12491
+ throw new SecretStorageException("Secret cannot be empty");
12492
+ }
12493
+ const passphrase = options?.passphrase ?? this.defaultPassphrase;
12494
+ if (!passphrase) {
12495
+ throw new SecretStorageException("Passphrase required for envelope encryption");
12496
+ }
12497
+ const salt = new Uint8Array(16);
12498
+ const iv = new Uint8Array(12);
12499
+ globalThis.crypto.getRandomValues(salt);
12500
+ globalThis.crypto.getRandomValues(iv);
12501
+ const key = await this.deriveKey(passphrase, salt, DEFAULT_ITERATIONS);
12502
+ const secretBytes = textEncoder2.encode(secret);
12503
+ try {
12504
+ const encryptedBuffer = await globalThis.crypto.subtle.encrypt(
12505
+ {
12506
+ name: "AES-GCM",
12507
+ iv
12508
+ },
12509
+ key,
12510
+ secretBytes
12511
+ );
12512
+ const ciphertext = uint8ArrayToBase64(new Uint8Array(encryptedBuffer));
12513
+ const metadata = {
12514
+ bundleHash,
12515
+ label: options?.label,
12516
+ createdAt: Date.now(),
12517
+ hardwareBacked: this.hardwareBacked,
12518
+ providerType: this.providerType
12519
+ };
12520
+ const payload = {
12521
+ version: 1,
12522
+ ciphertext,
12523
+ iv: uint8ArrayToBase64(iv),
12524
+ salt: uint8ArrayToBase64(salt),
12525
+ algorithm: "AES-GCM",
12526
+ iterations: DEFAULT_ITERATIONS,
12527
+ metadata
12528
+ };
12529
+ await this.backend.setItem(`${KEY_PREFIX}${bundleHash}`, JSON.stringify(payload));
12530
+ } catch (err) {
12531
+ const msg = err instanceof Error ? err.message : String(err);
12532
+ throw new SecretStorageException(`Encryption failed: ${msg}`);
12533
+ } finally {
12534
+ zeroizeBytes(secretBytes);
12535
+ }
12536
+ }
12537
+ /**
12538
+ * Retrieve and decrypt the master secret
12539
+ */
12540
+ async retrieveSecret(bundleHash, options) {
12541
+ const raw = await this.backend.getItem(`${KEY_PREFIX}${bundleHash}`);
12542
+ if (!raw) {
12543
+ return null;
12544
+ }
12545
+ let payload;
12546
+ try {
12547
+ payload = JSON.parse(raw);
12548
+ } catch {
12549
+ throw SecretStorageException.decryptionFailed("Corrupted payload format");
12550
+ }
12551
+ const passphrase = options?.passphrase ?? this.defaultPassphrase;
12552
+ if (!passphrase) {
12553
+ throw new SecretStorageException("Passphrase required for secret decryption");
12554
+ }
12555
+ const salt = base64ToUint8Array(payload.salt);
12556
+ const iv = base64ToUint8Array(payload.iv);
12557
+ const ciphertext = base64ToUint8Array(payload.ciphertext);
12558
+ try {
12559
+ const key = await this.deriveKey(passphrase, salt, payload.iterations ?? DEFAULT_ITERATIONS);
12560
+ const decryptedBuffer = await globalThis.crypto.subtle.decrypt(
12561
+ {
12562
+ name: "AES-GCM",
12563
+ iv
12564
+ },
12565
+ key,
12566
+ ciphertext
12567
+ );
12568
+ const decryptedBytes = new Uint8Array(decryptedBuffer);
12569
+ try {
12570
+ return textDecoder.decode(decryptedBytes);
12571
+ } finally {
12572
+ zeroizeBytes(decryptedBytes);
12057
12573
  }
12574
+ } catch (err) {
12575
+ const msg = err instanceof Error ? err.message : String(err);
12576
+ throw SecretStorageException.decryptionFailed(msg);
12058
12577
  }
12059
12578
  }
12060
12579
  /**
12061
- * Get the policy object
12062
- * Matches JavaScript SDK get method exactly
12580
+ * Delete a stored secret
12063
12581
  */
12064
- get() {
12065
- return this.policy;
12582
+ async deleteSecret(bundleHash) {
12583
+ const key = `${KEY_PREFIX}${bundleHash}`;
12584
+ const result = await this.backend.removeItem(key);
12585
+ return result !== false;
12066
12586
  }
12067
12587
  /**
12068
- * Convert policy to JSON string
12069
- * Matches JavaScript SDK toJson method exactly
12588
+ * Check if a secret exists
12070
12589
  */
12071
- toJson() {
12072
- return JSON.stringify(this.get());
12590
+ async hasSecret(bundleHash) {
12591
+ const raw = await this.backend.getItem(`${KEY_PREFIX}${bundleHash}`);
12592
+ return raw !== null;
12593
+ }
12594
+ /**
12595
+ * List all stored secret metadata
12596
+ */
12597
+ async listSecrets() {
12598
+ const keys = await this.backend.keys();
12599
+ const matchingKeys = keys.filter((k) => k.startsWith(KEY_PREFIX));
12600
+ const results = [];
12601
+ for (const key of matchingKeys) {
12602
+ const raw = await this.backend.getItem(key);
12603
+ if (raw) {
12604
+ try {
12605
+ const payload = JSON.parse(raw);
12606
+ if (payload.metadata) {
12607
+ results.push(payload.metadata);
12608
+ }
12609
+ } catch {
12610
+ }
12611
+ }
12612
+ }
12613
+ return results;
12614
+ }
12615
+ /**
12616
+ * Execute callback with unwrapped secret, zeroizing the decrypted buffer upon completion
12617
+ */
12618
+ async withSecret(bundleHash, fn, options) {
12619
+ const raw = await this.backend.getItem(`${KEY_PREFIX}${bundleHash}`);
12620
+ if (!raw) {
12621
+ throw SecretStorageException.notFound(bundleHash);
12622
+ }
12623
+ let payload;
12624
+ try {
12625
+ payload = JSON.parse(raw);
12626
+ } catch {
12627
+ throw SecretStorageException.decryptionFailed("Corrupted payload format");
12628
+ }
12629
+ const passphrase = options?.passphrase ?? this.defaultPassphrase;
12630
+ if (!passphrase) {
12631
+ throw new SecretStorageException("Passphrase required for secret decryption");
12632
+ }
12633
+ const salt = base64ToUint8Array(payload.salt);
12634
+ const iv = base64ToUint8Array(payload.iv);
12635
+ const ciphertext = base64ToUint8Array(payload.ciphertext);
12636
+ try {
12637
+ const key = await this.deriveKey(passphrase, salt, payload.iterations ?? DEFAULT_ITERATIONS);
12638
+ const decryptedBuffer = await globalThis.crypto.subtle.decrypt(
12639
+ {
12640
+ name: "AES-GCM",
12641
+ iv
12642
+ },
12643
+ key,
12644
+ ciphertext
12645
+ );
12646
+ const decryptedBytes = new Uint8Array(decryptedBuffer);
12647
+ return await withSecureBytes(decryptedBytes, async (bytes) => {
12648
+ const secretString = textDecoder.decode(bytes);
12649
+ return await fn(secretString);
12650
+ });
12651
+ } catch (err) {
12652
+ if (err instanceof SecretStorageException) {
12653
+ throw err;
12654
+ }
12655
+ const msg = err instanceof Error ? err.message : String(err);
12656
+ throw SecretStorageException.decryptionFailed(msg);
12657
+ }
12073
12658
  }
12074
12659
  };
12075
12660
 
12661
+ // src/storage/index.ts
12662
+ function createDefaultSecretStorage(options = {}) {
12663
+ if (options.type === "memory") {
12664
+ return new MemorySecretStorageProvider();
12665
+ }
12666
+ if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.subtle !== "undefined") {
12667
+ return new WebCryptoSecretStorageProvider({
12668
+ backend: options.backend,
12669
+ defaultPassphrase: options.defaultPassphrase,
12670
+ hardwareBacked: options.hardwareBacked
12671
+ });
12672
+ }
12673
+ return new MemorySecretStorageProvider();
12674
+ }
12675
+
12076
12676
  // src/index.ts
12077
- init_exception();
12078
- var SDK_VERSION = "0.9.5";
12677
+ var SDK_VERSION = "0.9.7";
12079
12678
  var SDK_NAME = "KnishIO-Client-TS";
12080
12679
  var COMPATIBLE_SERVER_VERSIONS = [4, 5];
12081
12680
  var SDK_INFO = {
@@ -12165,6 +12764,6 @@ var KnishIO = {
12165
12764
  SDK_INFO
12166
12765
  };
12167
12766
 
12168
- export { Atom, AtomIndexException, AtomMeta, AtomsMissingException, AuthToken, BaseException, COMPATIBLE_SERVER_VERSIONS, CRYPTO_CONSTANTS, CheckMolecule, DevUtils, Dot, EXCEPTION_CODES, EXCEPTION_TYPES, EXTENDED_COMPATIBILITY_TEST_VECTORS, ExceptionFactory, GraphQLClient, InvalidResponseException, KnishIO, KnishIOClient, Meta, MolecularHashMismatchException, Molecule, Mutation, MutationAppendRequest, MutationCreateMeta, MutationCreateToken, MutationCreateWallet, MutationPeering, MutationProposeMolecule, MutationRequestAuthorization, MutationRequestTokens, MutationTransferTokens, PolicyMeta, Query, QueryAtom, QueryBalance, QueryBatch, QueryContinuId, QueryEmbeddingStatus, QueryMetaType, QueryMetaTypeViaAtom, QueryWalletBundle, QueryWalletList, Response2 as Response, ResponseAppendRequest, ResponseAtom, ResponseBalance, ResponseContinuId, ResponseCreateMeta, ResponseCreateToken, ResponseCreateWallet, ResponseEmbeddingStatus, ResponseMetaType, ResponseMetaTypeViaAtom, ResponsePeering, ResponseProposeMolecule, ResponseRequestAuthorization, ResponseRequestTokens, ResponseTransferTokens, ResponseWalletBundle, ResponseWalletList, SDK_INFO, SDK_NAME, SDK_VERSION, SignatureMismatchException, TokenUnit, TransferBalanceException, Wallet, WalletCredentialException, base64ToHex, bufferToHexString, capitalize, charsetBaseConvert, chunkArray, chunkSubstr, configureSDK, convertToBase17, createBundleHash, createMolecularHash, createPosition, createTokenSlug, createWalletAddress, deepCloning, diff, enumerateMolecularHash, generateBatchId, generateBundleHash, generateOTSSignature, generatePosition, generateSecret, generateWalletAddress, generateWalletKey, getSDKConfig, hexStringToBuffer, hexToBase64, intersect, isAtomIsotope, isBundleHash, isHex, isHexString, isMolecularHash, isNumeric, isPosition2 as isPosition, isWalletAddress2 as isWalletAddress, normalizeMolecularHash, randomString, runCompatibilityTests, runExtendedCompatibilityTests, shake256, toCamelCase, toSnakeCase, truncate, validateBundleHash, validateMolecularHashForSignature, validateOTSSignature, validatePosition, validateSecret, validateWalletAddress, verifyOTSSignature };
12767
+ export { Atom, AtomIndexException, AtomMeta, AtomsMissingException, AuthToken, BaseException, COMPATIBLE_SERVER_VERSIONS, CRYPTO_CONSTANTS, CheckMolecule, DevUtils, Dot, EXCEPTION_CODES, EXCEPTION_TYPES, EXTENDED_COMPATIBILITY_TEST_VECTORS, ExceptionFactory, GraphQLClient, InvalidResponseException, KnishIO, KnishIOClient, MemorySecretStorageProvider, MemoryStorageBackend, Meta, MolecularHashMismatchException, Molecule, Mutation, MutationAppendRequest, MutationCreateMeta, MutationCreateToken, MutationCreateWallet, MutationPeering, MutationProposeMolecule, MutationRequestAuthorization, MutationRequestTokens, MutationTransferTokens, PolicyMeta, Query, QueryAtom, QueryBalance, QueryBatch, QueryContinuId, QueryEmbeddingStatus, QueryMetaType, QueryMetaTypeViaAtom, QueryWalletBundle, QueryWalletList, Response2 as Response, ResponseAppendRequest, ResponseAtom, ResponseBalance, ResponseContinuId, ResponseCreateMeta, ResponseCreateToken, ResponseCreateWallet, ResponseEmbeddingStatus, ResponseMetaType, ResponseMetaTypeViaAtom, ResponsePeering, ResponseProposeMolecule, ResponseRequestAuthorization, ResponseRequestTokens, ResponseTransferTokens, ResponseWalletBundle, ResponseWalletList, SDK_INFO, SDK_NAME, SDK_VERSION, SecretStorageException, SignatureMismatchException, TokenUnit, TransferBalanceException, Wallet, WalletCredentialException, WebCryptoSecretStorageProvider, base64ToHex, bufferToHexString, capitalize, charsetBaseConvert, chunkArray, chunkSubstr, configureSDK, constantTimeCompare, convertToBase17, createBundleHash, createDefaultSecretStorage, createMolecularHash, createPosition, createTokenSlug, createWalletAddress, deepCloning, diff, enumerateMolecularHash, generateBatchId, generateBundleHash, generateOTSSignature, generatePosition, generateSecret, generateWalletAddress, generateWalletKey, getSDKConfig, hexStringToBuffer, hexToBase64, intersect, isAtomIsotope, isBundleHash, isHex, isHexString, isMolecularHash, isNumeric, isPosition2 as isPosition, isWalletAddress2 as isWalletAddress, normalizeMolecularHash, randomString, runCompatibilityTests, runExtendedCompatibilityTests, shake256, toCamelCase, toSnakeCase, truncate, validateBundleHash, validateMolecularHashForSignature, validateOTSSignature, validatePosition, validateSecret, validateWalletAddress, verifyOTSSignature, withSecureBytes, withSecureString, zeroizeBytes };
12169
12768
  //# sourceMappingURL=index.js.map
12170
12769
  //# sourceMappingURL=index.js.map