@digitaldefiance/secrets 2.0.3

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.
Files changed (79) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +445 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/browser-types.d.ts +112 -0
  5. package/dist/browser-types.d.ts.map +1 -0
  6. package/dist/browser-types.js +242 -0
  7. package/dist/browser-types.js.map +1 -0
  8. package/dist/errors.d.ts +33 -0
  9. package/dist/errors.d.ts.map +1 -0
  10. package/dist/errors.js +92 -0
  11. package/dist/errors.js.map +1 -0
  12. package/dist/esm/.tsbuildinfo +1 -0
  13. package/dist/esm/browser-types.d.ts +112 -0
  14. package/dist/esm/browser-types.d.ts.map +1 -0
  15. package/dist/esm/browser-types.js +201 -0
  16. package/dist/esm/browser-types.js.map +1 -0
  17. package/dist/esm/errors.d.ts +33 -0
  18. package/dist/esm/errors.d.ts.map +1 -0
  19. package/dist/esm/errors.js +54 -0
  20. package/dist/esm/errors.js.map +1 -0
  21. package/dist/esm/node-types.d.ts +87 -0
  22. package/dist/esm/node-types.d.ts.map +1 -0
  23. package/dist/esm/node-types.js +157 -0
  24. package/dist/esm/node-types.js.map +1 -0
  25. package/dist/esm/secrets.d.ts +262 -0
  26. package/dist/esm/secrets.d.ts.map +1 -0
  27. package/dist/esm/secrets.js +894 -0
  28. package/dist/esm/secrets.js.map +1 -0
  29. package/dist/esm/types.d.ts +249 -0
  30. package/dist/esm/types.d.ts.map +1 -0
  31. package/dist/esm/types.js +61 -0
  32. package/dist/esm/types.js.map +1 -0
  33. package/dist/esm/validation.d.ts +34 -0
  34. package/dist/esm/validation.d.ts.map +1 -0
  35. package/dist/esm/validation.js +72 -0
  36. package/dist/esm/validation.js.map +1 -0
  37. package/dist/node-types.d.ts +87 -0
  38. package/dist/node-types.d.ts.map +1 -0
  39. package/dist/node-types.js +191 -0
  40. package/dist/node-types.js.map +1 -0
  41. package/dist/secrets.d.ts +262 -0
  42. package/dist/secrets.d.ts.map +1 -0
  43. package/dist/secrets.js +897 -0
  44. package/dist/secrets.js.map +1 -0
  45. package/dist/types.d.ts +249 -0
  46. package/dist/types.d.ts.map +1 -0
  47. package/dist/types.js +67 -0
  48. package/dist/types.js.map +1 -0
  49. package/dist/umd/.tsbuildinfo +1 -0
  50. package/dist/umd/browser-types.d.ts +112 -0
  51. package/dist/umd/browser-types.d.ts.map +1 -0
  52. package/dist/umd/browser-types.js +252 -0
  53. package/dist/umd/browser-types.js.map +1 -0
  54. package/dist/umd/errors.d.ts +33 -0
  55. package/dist/umd/errors.d.ts.map +1 -0
  56. package/dist/umd/errors.js +102 -0
  57. package/dist/umd/errors.js.map +1 -0
  58. package/dist/umd/node-types.d.ts +87 -0
  59. package/dist/umd/node-types.d.ts.map +1 -0
  60. package/dist/umd/node-types.js +201 -0
  61. package/dist/umd/node-types.js.map +1 -0
  62. package/dist/umd/secrets.d.ts +262 -0
  63. package/dist/umd/secrets.d.ts.map +1 -0
  64. package/dist/umd/secrets.js +907 -0
  65. package/dist/umd/secrets.js.map +1 -0
  66. package/dist/umd/secrets.min.js +2 -0
  67. package/dist/umd/types.d.ts +249 -0
  68. package/dist/umd/types.d.ts.map +1 -0
  69. package/dist/umd/types.js +77 -0
  70. package/dist/umd/types.js.map +1 -0
  71. package/dist/umd/validation.d.ts +34 -0
  72. package/dist/umd/validation.d.ts.map +1 -0
  73. package/dist/umd/validation.js +92 -0
  74. package/dist/umd/validation.js.map +1 -0
  75. package/dist/validation.d.ts +34 -0
  76. package/dist/validation.d.ts.map +1 -0
  77. package/dist/validation.js +82 -0
  78. package/dist/validation.js.map +1 -0
  79. package/package.json +181 -0
@@ -0,0 +1,201 @@
1
+ // Node.js-specific type definitions and error handling
2
+ // Provides enhanced typing for Node.js crypto APIs and environment-specific behavior
3
+ var __extends = (this && this.__extends) || (function () {
4
+ var extendStatics = function (d, b) {
5
+ extendStatics = Object.setPrototypeOf ||
6
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
8
+ return extendStatics(d, b);
9
+ };
10
+ return function (d, b) {
11
+ if (typeof b !== "function" && b !== null)
12
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
13
+ extendStatics(d, b);
14
+ function __() { this.constructor = d; }
15
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16
+ };
17
+ })();
18
+ (function (factory) {
19
+ if (typeof module === "object" && typeof module.exports === "object") {
20
+ var v = factory(require, exports);
21
+ if (v !== undefined) module.exports = v;
22
+ }
23
+ else if (typeof define === "function" && define.amd) {
24
+ define(["require", "exports", "./errors"], factory);
25
+ }
26
+ })(function (require, exports) {
27
+ "use strict";
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.NodeEnvironmentError = exports.NodeCryptoError = void 0;
30
+ exports.isNodeBuffer = isNodeBuffer;
31
+ exports.isNodeEnvironment = isNodeEnvironment;
32
+ exports.getNodeCrypto = getNodeCrypto;
33
+ exports.hasNodeCryptoRandomBytes = hasNodeCryptoRandomBytes;
34
+ exports.createNodeRNG = createNodeRNG;
35
+ exports.createNodeCryptoEnvironment = createNodeCryptoEnvironment;
36
+ exports.validateNodeBuffer = validateNodeBuffer;
37
+ exports.requireNodeCrypto = requireNodeCrypto;
38
+ var errors_1 = require("./errors");
39
+ /**
40
+ * Node.js Buffer type guard
41
+ */
42
+ function isNodeBuffer(value) {
43
+ return value !== null &&
44
+ typeof value === 'object' &&
45
+ 'length' in value &&
46
+ typeof value.readUInt8 === 'function';
47
+ }
48
+ // ============================================================================
49
+ // Node.js Environment Detection
50
+ // ============================================================================
51
+ /**
52
+ * Detects if the current environment is Node.js
53
+ * @returns true if running in Node.js, false otherwise
54
+ */
55
+ function isNodeEnvironment() {
56
+ return typeof process !== 'undefined' &&
57
+ process.versions != null &&
58
+ process.versions.node != null;
59
+ }
60
+ /**
61
+ * Attempts to load the Node.js crypto module
62
+ * @returns NodeCryptoModule if available, null otherwise
63
+ */
64
+ function getNodeCrypto() {
65
+ if (!isNodeEnvironment()) {
66
+ return null;
67
+ }
68
+ try {
69
+ // Dynamic require to avoid bundler issues
70
+ var crypto_1 = require('crypto');
71
+ if (typeof crypto_1 === 'object' && typeof crypto_1.randomBytes === 'function') {
72
+ return crypto_1;
73
+ }
74
+ return null;
75
+ }
76
+ catch (error) {
77
+ return null;
78
+ }
79
+ }
80
+ /**
81
+ * Checks if Node.js crypto.randomBytes is available
82
+ * @returns true if crypto.randomBytes is available
83
+ */
84
+ function hasNodeCryptoRandomBytes() {
85
+ var crypto = getNodeCrypto();
86
+ return crypto !== null && typeof crypto.randomBytes === 'function';
87
+ }
88
+ // ============================================================================
89
+ // Node.js-Specific Error Types
90
+ // ============================================================================
91
+ /**
92
+ * Error thrown when Node.js crypto operations fail
93
+ */
94
+ var NodeCryptoError = /** @class */ (function (_super) {
95
+ __extends(NodeCryptoError, _super);
96
+ function NodeCryptoError(operation, reason, originalError) {
97
+ var _this = _super.call(this, operation, "Node.js crypto error: ".concat(reason)) || this;
98
+ _this.originalError = originalError;
99
+ _this.name = 'NodeCryptoError';
100
+ if (originalError && Error.captureStackTrace) {
101
+ Error.captureStackTrace(_this, NodeCryptoError);
102
+ }
103
+ return _this;
104
+ }
105
+ return NodeCryptoError;
106
+ }(errors_1.CryptoError));
107
+ exports.NodeCryptoError = NodeCryptoError;
108
+ /**
109
+ * Error thrown when Node.js environment is required but not available
110
+ */
111
+ var NodeEnvironmentError = /** @class */ (function (_super) {
112
+ __extends(NodeEnvironmentError, _super);
113
+ function NodeEnvironmentError(feature) {
114
+ var _this = _super.call(this, 'environment_check', "Feature '".concat(feature, "' requires Node.js environment but is not available")) || this;
115
+ _this.name = 'NodeEnvironmentError';
116
+ return _this;
117
+ }
118
+ return NodeEnvironmentError;
119
+ }(errors_1.CryptoError));
120
+ exports.NodeEnvironmentError = NodeEnvironmentError;
121
+ // ============================================================================
122
+ // Node.js RNG Implementation
123
+ // ============================================================================
124
+ /**
125
+ * Creates a Node.js-specific RNG function using crypto.randomBytes
126
+ * @param crypto - Node.js crypto module
127
+ * @returns RNG function that generates random binary strings
128
+ * @throws {NodeCryptoError} If random byte generation fails
129
+ */
130
+ function createNodeRNG(crypto) {
131
+ return function nodeCryptoRandomBytes(bits) {
132
+ if (typeof bits !== 'number' || bits <= 0 || bits % 1 !== 0) {
133
+ throw new NodeCryptoError('randomBytes', "Invalid bits parameter: ".concat(bits, ". Must be a positive integer."));
134
+ }
135
+ var bytes = Math.ceil(bits / 8);
136
+ try {
137
+ var buffer = crypto.randomBytes(bytes);
138
+ // Convert buffer to hex string
139
+ var hex = '';
140
+ for (var i = 0; i < buffer.length; i++) {
141
+ var byte = buffer[i].toString(16);
142
+ hex += byte.length === 1 ? '0' + byte : byte;
143
+ }
144
+ // Convert hex to binary
145
+ var binary = '';
146
+ for (var i = 0; i < hex.length; i++) {
147
+ var num = parseInt(hex[i], 16);
148
+ var bin = num.toString(2);
149
+ binary += '0000'.substring(bin.length) + bin;
150
+ }
151
+ // Return exactly the requested number of bits
152
+ return binary.substring(0, bits);
153
+ }
154
+ catch (error) {
155
+ throw new NodeCryptoError('randomBytes', 'Failed to generate random bytes', error);
156
+ }
157
+ };
158
+ }
159
+ /**
160
+ * Creates a Node.js crypto environment descriptor
161
+ * @returns NodeCryptoEnvironment if Node.js crypto is available, null otherwise
162
+ */
163
+ function createNodeCryptoEnvironment() {
164
+ var crypto = getNodeCrypto();
165
+ if (!crypto) {
166
+ return null;
167
+ }
168
+ return {
169
+ type: 'node',
170
+ crypto: crypto,
171
+ rngType: 'nodeCryptoRandomBytes',
172
+ rng: createNodeRNG(crypto)
173
+ };
174
+ }
175
+ // ============================================================================
176
+ // Type Validation for Node.js
177
+ // ============================================================================
178
+ /**
179
+ * Validates that a value is a valid Node.js Buffer
180
+ * @param value - Value to validate
181
+ * @param paramName - Parameter name for error messages
182
+ * @throws {NodeCryptoError} If value is not a valid Buffer
183
+ */
184
+ function validateNodeBuffer(value, paramName) {
185
+ if (!isNodeBuffer(value)) {
186
+ throw new NodeCryptoError('validation', "Parameter '".concat(paramName, "' must be a Node.js Buffer"));
187
+ }
188
+ }
189
+ /**
190
+ * Validates that Node.js crypto is available
191
+ * @throws {NodeEnvironmentError} If Node.js crypto is not available
192
+ */
193
+ function requireNodeCrypto() {
194
+ var crypto = getNodeCrypto();
195
+ if (!crypto) {
196
+ throw new NodeEnvironmentError('crypto.randomBytes');
197
+ }
198
+ return crypto;
199
+ }
200
+ });
201
+ //# sourceMappingURL=node-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-types.js","sourceRoot":"","sources":["../../src/node-types.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,qFAAqF;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAiCrF,oCAKC;IAUD,8CAIC;IAMD,sCAiBC;IAMD,4DAGC;IA2CD,sCAwCC;IAgBD,kEAaC;IAYD,gDAOC;IAMD,8CAQC;IAlOD,mCAAuC;IA2BvC;;OAEG;IACH,SAAgB,YAAY,CAAC,KAAc;QACzC,OAAO,KAAK,KAAK,IAAI;YACd,OAAO,KAAK,KAAK,QAAQ;YACzB,QAAQ,IAAI,KAAK;YACjB,OAAQ,KAAa,CAAC,SAAS,KAAK,UAAU,CAAC;IACxD,CAAC;IAED,+EAA+E;IAC/E,gCAAgC;IAChC,+EAA+E;IAE/E;;;OAGG;IACH,SAAgB,iBAAiB;QAC/B,OAAO,OAAO,OAAO,KAAK,WAAW;YAC9B,OAAO,CAAC,QAAQ,IAAI,IAAI;YACxB,OAAO,CAAC,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC;IACvC,CAAC;IAED;;;OAGG;IACH,SAAgB,aAAa;QAC3B,IAAI,CAAC,iBAAiB,EAAE,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,CAAC;YACH,0CAA0C;YA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AAC;gBAED,8CAA8C;gBAC9C,OAAO,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;YAEnC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,eAAe,CACvB,aAAa,EACb,iCAAiC,EACjC,KAAc,CACf,CAAC;YACJ,CAAC;QACH,CAAC,CAAC;IACJ,CAAC;IAYD;;;OAGG;IACH,SAAgB,2BAA2B;QACzC,IAAM,MAAM,GAAG,aAAa,EAAE,CAAC;QAE/B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,MAAM,QAAA;YACN,OAAO,EAAE,uBAAuB;YAChC,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC;SAC3B,CAAC;IACJ,CAAC;IAED,+EAA+E;IAC/E,8BAA8B;IAC9B,+EAA+E;IAE/E;;;;;OAKG;IACH,SAAgB,kBAAkB,CAAC,KAAc,EAAE,SAAiB;QAClE,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,MAAM,IAAI,eAAe,CACvB,YAAY,EACZ,qBAAc,SAAS,+BAA4B,CACpD,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;;OAGG;IACH,SAAgB,iBAAiB;QAC/B,IAAM,MAAM,GAAG,aAAa,EAAE,CAAC;QAE/B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,IAAI,oBAAoB,CAAC,oBAAoB,CAAC,CAAC;QACvD,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC"}
@@ -0,0 +1,262 @@
1
+ import type { BinaryString, CSPRNGType, HexString, RNGFunction, SecretsConfig, Share, ShareComponents, Shares } from './types';
2
+ declare global {
3
+ interface Window {
4
+ secrets: typeof SecretsLibrary;
5
+ }
6
+ }
7
+ declare function reset(): void;
8
+ declare function isSetRNG(): boolean;
9
+ declare function padLeft(str: string, multipleOfBits?: number): string;
10
+ declare function hex2bin(str: string): BinaryString;
11
+ declare function bin2hex(str: BinaryString): HexString;
12
+ declare function bytesToHex(bytes: Uint8Array | Buffer): HexString;
13
+ declare function hasCryptoGetRandomValues(): boolean;
14
+ declare function hasCryptoRandomBytes(): boolean;
15
+ declare function getRNG(type?: CSPRNGType): RNGFunction | undefined;
16
+ declare function splitNumStringToIntArray(str: string, padLength?: number): number[];
17
+ declare function horner(x: number, coeffs: number[]): number;
18
+ declare function lagrange(at: number, x: number[], y: number[]): number;
19
+ declare function getShares(secret: number, numShares: number, threshold: number): Share[];
20
+ declare function constructPublicShareString(bits: number | string, id: number | string, data: string): string;
21
+ declare const SecretsLibrary: {
22
+ /**
23
+ * Initialize the secrets library with specified bit length and RNG type.
24
+ *
25
+ * This function sets up the Galois Field arithmetic tables (logs and exps)
26
+ * required for Shamir's Secret Sharing. It must be called before using
27
+ * share() or combine() operations.
28
+ *
29
+ * @param bits - Number of bits for the Galois Field (between 3 and 20, default 8).
30
+ * Determines the maximum number of shares (2^bits - 1).
31
+ * @param rngType - Type of cryptographically secure random number generator to use.
32
+ * If not specified, automatically detects the best available CSPRNG.
33
+ * @throws {Error} If bits is not an integer between 3 and 20, inclusive.
34
+ * @throws {Error} If rngType is invalid or RNG initialization fails.
35
+ * @throws {Error} If initialization fails for any reason.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * // Initialize with default 8 bits (max 255 shares)
40
+ * secrets.init();
41
+ *
42
+ * // Initialize with 10 bits (max 1023 shares)
43
+ * secrets.init(10);
44
+ *
45
+ * // Initialize with specific RNG type
46
+ * secrets.init(8, 'nodeCryptoRandomBytes');
47
+ * ```
48
+ */
49
+ init(bits?: number, rngType?: CSPRNGType): void;
50
+ /**
51
+ * Combine shares to reconstruct the original secret.
52
+ *
53
+ * Uses Lagrange interpolation to reconstruct the secret from a threshold
54
+ * number of shares. The shares must have been created with the same bit
55
+ * configuration.
56
+ *
57
+ * @param shares - Array of share strings to combine. Must contain at least
58
+ * the threshold number of shares used during secret creation.
59
+ * @param at - Point at which to evaluate the polynomial (default 0 for secret recovery).
60
+ * Use non-zero values to generate new shares.
61
+ * @returns The reconstructed secret as a hexadecimal string.
62
+ * @throws {Error} If shares have mismatched bit settings.
63
+ * @throws {Error} If share format is invalid.
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * const shares = secrets.share('deadbeef', 5, 3);
68
+ * const secret = secrets.combine(shares.slice(0, 3));
69
+ * console.log(secret); // 'deadbeef'
70
+ * ```
71
+ */
72
+ combine(shares: Shares | string[], at?: number): string;
73
+ /**
74
+ * Get the current configuration of the secrets library.
75
+ *
76
+ * Returns information about the current Galois Field configuration,
77
+ * including bit length, radix, maximum shares, and RNG status.
78
+ *
79
+ * @returns Configuration object with current settings.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const config = secrets.getConfig();
84
+ * console.log(`Max shares: ${config.maxShares}`);
85
+ * console.log(`Has CSPRNG: ${config.hasCSPRNG}`);
86
+ * console.log(`RNG Type: ${config.typeCSPRNG}`);
87
+ * ```
88
+ */
89
+ getConfig(): SecretsConfig;
90
+ /**
91
+ * Extract the components from a public share string.
92
+ *
93
+ * Parses a share string to extract the bit configuration, share ID,
94
+ * and share data. Useful for inspecting shares or validating share format.
95
+ *
96
+ * @param share - The share string to parse.
97
+ * @returns Object containing bits, id, and data components.
98
+ * @throws {Error} If share format is invalid.
99
+ * @throws {Error} If share ID is out of valid range.
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * const shares = secrets.share('abc123', 5, 3);
104
+ * const components = secrets.extractShareComponents(shares[0]);
105
+ * console.log(`Bits: ${components.bits}`);
106
+ * console.log(`ID: ${components.id}`);
107
+ * console.log(`Data: ${components.data}`);
108
+ * ```
109
+ */
110
+ extractShareComponents(share: string): ShareComponents;
111
+ /**
112
+ * Set the random number generator to use for share generation.
113
+ *
114
+ * Allows specifying a custom RNG or selecting a specific CSPRNG type.
115
+ * If no argument is provided, automatically detects and uses the best
116
+ * available CSPRNG for the current environment.
117
+ *
118
+ * @param rng - Either a CSPRNG type string or a custom RNG function.
119
+ * Custom functions must return a binary string of specified length.
120
+ * @returns True if RNG was successfully set.
121
+ * @throws {Error} If RNG type is invalid.
122
+ * @throws {Error} If custom RNG function fails validation tests.
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * // Use specific CSPRNG type
127
+ * secrets.setRNG('nodeCryptoRandomBytes');
128
+ *
129
+ * // Use custom RNG function
130
+ * secrets.setRNG((bits) => {
131
+ * // Return binary string of specified length
132
+ * return customRandomBits(bits);
133
+ * });
134
+ * ```
135
+ */
136
+ setRNG(rng?: CSPRNGType | RNGFunction): boolean;
137
+ /**
138
+ * Convert a UTF-16 string to hexadecimal representation.
139
+ *
140
+ * Each character is represented by bytesPerChar bytes in the output.
141
+ * Useful for converting text secrets to hex format before sharing.
142
+ *
143
+ * @param str - The string to convert to hexadecimal.
144
+ * @param bytesPerChar - Number of bytes per character (1-6, default 2).
145
+ * Higher values support larger character codes.
146
+ * @returns Hexadecimal string representation.
147
+ * @throws {Error} If input is not a string.
148
+ * @throws {Error} If bytesPerChar is not an integer between 1 and 6.
149
+ * @throws {Error} If character code exceeds maximum for bytesPerChar.
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * const hex = secrets.str2hex('Hello');
154
+ * const shares = secrets.share(hex, 5, 3);
155
+ * ```
156
+ */
157
+ str2hex(str: string, bytesPerChar?: number): HexString;
158
+ /**
159
+ * Convert a hexadecimal string to UTF-16 string representation.
160
+ *
161
+ * Reverses the str2hex operation. Each bytesPerChar bytes in the input
162
+ * represents one character in the output.
163
+ *
164
+ * @param str - The hexadecimal string to convert.
165
+ * @param bytesPerChar - Number of bytes per character (1-6, default 2).
166
+ * Must match the value used in str2hex.
167
+ * @returns UTF-16 string representation.
168
+ * @throws {Error} If input is not a hexadecimal string.
169
+ * @throws {Error} If bytesPerChar is not an integer between 1 and 6.
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * const shares = secrets.share(secrets.str2hex('Hello'), 5, 3);
174
+ * const recovered = secrets.hex2str(secrets.combine(shares));
175
+ * console.log(recovered); // 'Hello'
176
+ * ```
177
+ */
178
+ hex2str(str: string, bytesPerChar?: number): string;
179
+ /**
180
+ * Generate a random hexadecimal string of specified bit length.
181
+ *
182
+ * Uses the configured CSPRNG to generate cryptographically secure
183
+ * random numbers. Useful for generating random secrets.
184
+ *
185
+ * @param bits - Number of random bits to generate (2-65536).
186
+ * @returns Random hexadecimal string.
187
+ * @throws {Error} If bits is not an integer between 2 and 65536.
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * const randomSecret = secrets.random(128);
192
+ * const shares = secrets.share(randomSecret, 5, 3);
193
+ * ```
194
+ */
195
+ random(bits: number): HexString;
196
+ /**
197
+ * Split a secret into shares using Shamir's Secret Sharing.
198
+ *
199
+ * Creates numShares shares such that any threshold number of shares
200
+ * can reconstruct the original secret, but fewer shares reveal no
201
+ * information about the secret.
202
+ *
203
+ * @param secret - The secret to split, as a hexadecimal string.
204
+ * @param numShares - Total number of shares to generate (2 to 2^bits-1).
205
+ * @param threshold - Minimum number of shares needed to reconstruct (2 to numShares).
206
+ * @param padLength - Zero-pad the secret to a multiple of this length (0-1024, default 128).
207
+ * @returns Array of share strings.
208
+ * @throws {Error} If secret is not a string.
209
+ * @throws {Error} If numShares or threshold are invalid.
210
+ * @throws {Error} If threshold exceeds numShares.
211
+ * @throws {Error} If padLength is invalid.
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * // Split a hex secret into 5 shares, requiring 3 to reconstruct
216
+ * const shares = secrets.share('deadbeef', 5, 3);
217
+ *
218
+ * // Any 3 shares can reconstruct the secret
219
+ * const recovered = secrets.combine([shares[0], shares[2], shares[4]]);
220
+ * console.log(recovered); // 'deadbeef'
221
+ * ```
222
+ */
223
+ share(secret: string, numShares: number, threshold: number, padLength?: number): string[];
224
+ /**
225
+ * Generate a new share with a specific ID from existing shares.
226
+ *
227
+ * Uses Lagrange interpolation to create a new share at the specified
228
+ * ID point. Useful for generating additional shares without access to
229
+ * the original secret.
230
+ *
231
+ * @param id - The ID for the new share (1 to 2^bits-1).
232
+ * @param shares - Array of existing shares (at least threshold number).
233
+ * @returns New share string with the specified ID.
234
+ * @throws {Error} If id is invalid.
235
+ * @throws {Error} If shares array is invalid or empty.
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * const shares = secrets.share('abc123', 5, 3);
240
+ * // Generate a new share with ID 10
241
+ * const newShare = secrets.newShare(10, shares.slice(0, 3));
242
+ * ```
243
+ */
244
+ newShare(id: number | string, shares: Shares | string[]): string;
245
+ _reset: typeof reset;
246
+ _padLeft: typeof padLeft;
247
+ _hex2bin: typeof hex2bin;
248
+ _bin2hex: typeof bin2hex;
249
+ _bytesToHex: typeof bytesToHex;
250
+ _hasCryptoGetRandomValues: typeof hasCryptoGetRandomValues;
251
+ _hasCryptoRandomBytes: typeof hasCryptoRandomBytes;
252
+ _getRNG: typeof getRNG;
253
+ _isSetRNG: typeof isSetRNG;
254
+ _splitNumStringToIntArray: typeof splitNumStringToIntArray;
255
+ _horner: typeof horner;
256
+ _lagrange: typeof lagrange;
257
+ _getShares: typeof getShares;
258
+ _constructPublicShareString: typeof constructPublicShareString;
259
+ };
260
+ export default SecretsLibrary;
261
+ export declare const init: (bits?: number, rngType?: CSPRNGType) => void, combine: (shares: Shares | string[], at?: number) => string, getConfig: () => SecretsConfig, extractShareComponents: (share: string) => ShareComponents, setRNG: (rng?: CSPRNGType | RNGFunction) => boolean, str2hex: (str: string, bytesPerChar?: number) => HexString, hex2str: (str: string, bytesPerChar?: number) => string, random: (bits: number) => HexString, share: (secret: string, numShares: number, threshold: number, padLength?: number) => string[], newShare: (id: number | string, shares: Shares | string[]) => string;
262
+ //# sourceMappingURL=secrets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../../src/secrets.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAER,YAAY,EACZ,UAAU,EAEV,S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