@crossdyne/security 0.2.0-beta.1 → 0.3.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,84 +1,152 @@
1
1
  'use strict';
2
2
 
3
+ // src/configurations/security-constants.ts
4
+ var SecurityConstants = {
5
+ AesGcmNonceSize: 12,
6
+ AesGcmTagSize: 16,
7
+ AesGcmTagSizeMin: 12,
8
+ AesGcmTagSizeMax: 16,
9
+ KeySizeBytes: 32,
10
+ // 256 bits
11
+ Pbkdf2IterationsDefault: 6e5,
12
+ Pbkdf2IterationsMinimum: 1e5
13
+ };
14
+
15
+ // src/configurations/supported-hash-algorithms.ts
16
+ var SupportedHashAlgorithms = ["SHA-256", "SHA-384", "SHA-512"];
17
+
3
18
  // src/utils/security.utils.ts
4
19
  var SecurityUtils = class {
5
- /*
6
- Base64 helpers
7
- */
20
+ /** Encodes Uint8Array to standard Base64. */
8
21
  static toBase64(bytes) {
9
22
  let binary = "";
10
- for (let i = 0; i < bytes.byteLength; i++)
23
+ for (let i = 0; i < bytes.length; i++)
11
24
  binary += String.fromCharCode(bytes[i]);
12
- return window.btoa(binary);
25
+ return btoa(binary);
13
26
  }
27
+ /** Decodes URL-safe or standard Base64 to Uint8Array. */
14
28
  static fromBase64(base64) {
15
- const cleaned = base64.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
16
- const binary = window.atob(cleaned);
29
+ let cleaned = base64.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
30
+ const mod = cleaned.length % 4;
31
+ if (mod !== 0) {
32
+ cleaned += "=".repeat(4 - mod);
33
+ }
34
+ const binary = atob(cleaned);
17
35
  const bytes = new Uint8Array(binary.length);
18
36
  for (let i = 0; i < binary.length; i++)
19
37
  bytes[i] = binary.charCodeAt(i);
20
38
  return bytes;
21
39
  }
40
+ /** Converts big-endian bytes to bigint. */
41
+ static bytesToBigInt(bytes) {
42
+ if (bytes.length === 0)
43
+ return 0n;
44
+ return BigInt("0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""));
45
+ }
46
+ /** Converts bigint to fixed-length big-endian bytes (pads/truncates). */
22
47
  static bigIntToFixedBytes(bn, length) {
23
48
  let hex = bn.toString(16);
24
49
  if (hex.length % 2 !== 0)
25
50
  hex = "0" + hex;
26
51
  if (hex.length > length * 2)
27
- throw new Error(`\u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0432\u0435\u043B\u0438\u043A\u043E \u0434\u043B\u044F ${length} \u0431\u0430\u0439\u0442`);
28
- hex = hex.padStart(length * 2, "0");
29
- return this.fromHex(hex);
52
+ hex = hex.slice(hex.length - length * 2);
53
+ else
54
+ hex = hex.padStart(length * 2, "0");
55
+ return new Uint8Array(hex.match(/.{1,2}/g)?.map((b) => parseInt(b, 16)) || []);
30
56
  }
31
- static fromHex(hex) {
32
- const matches = hex.match(/.{1,2}/g);
33
- return new Uint8Array(matches ? matches.map((byte) => parseInt(byte, 16)) : []);
57
+ /** Constant-time comparison of two Uint8Arrays. */
58
+ static fixedTimeEquals(a, b) {
59
+ if (a.length !== b.length)
60
+ return false;
61
+ let diff = 0;
62
+ for (let i = 0; i < a.length; i++)
63
+ diff |= a[i] ^ b[i];
64
+ return diff === 0;
34
65
  }
35
- /*
36
- Math
37
- */
66
+ /** Modular exponentiation (base^exp mod mod) using binary exponentiation. */
38
67
  static expMod(base, exp, mod) {
39
68
  let res = BigInt(1);
40
69
  base = base % mod;
41
- while (exp > 0) {
42
- if (exp % BigInt(2) === BigInt(1)) res = res * base % mod;
70
+ while (exp > 0n) {
71
+ if (exp % 2n === 1n)
72
+ res = res * base % mod;
43
73
  base = base * base % mod;
44
- exp = exp / BigInt(2);
74
+ exp = exp / 2n;
45
75
  }
46
76
  return res;
47
77
  }
48
- /*
49
- SRP helper
50
- */
51
- static async hashAsPerSrp6a(items) {
52
- const buffers = items.map(({ value, length }) => this.bigIntToFixedBytes(value, length));
53
- const totalLen = buffers.reduce((sum, buf) => sum + buf.length, 0);
54
- const combined = new Uint8Array(totalLen);
55
- let offset = 0;
56
- for (const buf of buffers) {
57
- combined.set(buf, offset);
58
- offset += buf.length;
59
- }
60
- const hash = await crypto.subtle.digest("SHA-256", combined);
61
- return this.bytesToBigInt(new Uint8Array(hash));
78
+ };
79
+
80
+ // src/crypto/aes-gcm-options.ts
81
+ var AesGcmOptions = class _AesGcmOptions {
82
+ constructor() {
83
+ this._nonceSize = SecurityConstants.AesGcmNonceSize;
84
+ this._tagSize = SecurityConstants.AesGcmTagSize;
85
+ }
86
+ /** Nonce size in bytes (must be 12). */
87
+ get nonceSize() {
88
+ return this._nonceSize;
89
+ }
90
+ set nonceSize(v) {
91
+ if (v !== SecurityConstants.AesGcmNonceSize) throw new RangeError(`AES-GCM requires ${SecurityConstants.AesGcmNonceSize}-byte nonce`);
92
+ this._nonceSize = v;
93
+ }
94
+ /** Tag size in bytes (12–16, default 16). */
95
+ get tagSize() {
96
+ return this._tagSize;
97
+ }
98
+ set tagSize(v) {
99
+ if (v < SecurityConstants.AesGcmTagSizeMin || v > SecurityConstants.AesGcmTagSizeMax) throw new RangeError(`Tag size must be between ${SecurityConstants.AesGcmTagSizeMin} and ${SecurityConstants.AesGcmTagSizeMax}`);
100
+ this._tagSize = v;
101
+ }
102
+ /** Validates that {@link tagSize} is in the allowed range. */
103
+ validate() {
104
+ if (this.tagSize < SecurityConstants.AesGcmTagSizeMin || this.tagSize > SecurityConstants.AesGcmTagSizeMax) throw new Error(`Invalid Tag Size: ${this.tagSize}`);
105
+ }
106
+ /** Default preset: nonce=12, tag=16, no AAD. */
107
+ static get default() {
108
+ return new _AesGcmOptions();
109
+ }
110
+ /** Fluent setter for {@link tagSize}. */
111
+ withTagSize(s) {
112
+ this.tagSize = s;
113
+ return this;
114
+ }
115
+ /**
116
+ * Fluent setter for {@link associatedData}.
117
+ * Accepts a byte array or a UTF-8 string (encoded internally).
118
+ */
119
+ withAssociatedData(aad) {
120
+ this.associatedData = typeof aad === "string" ? new TextEncoder().encode(aad) : aad;
121
+ return this;
122
+ }
123
+ /** Validates and returns this instance. */
124
+ build() {
125
+ this.validate();
126
+ return this;
62
127
  }
63
128
  };
64
- SecurityUtils.MODULUS_SIZE = 384;
65
- SecurityUtils.NONCE_SIZE = 12;
66
- SecurityUtils.TAG_SIZE = 16;
67
- SecurityUtils.KEY_SIZE = 32;
68
- SecurityUtils.N = BigInt("0xAC6BDB41324A9A9BF166DE5E1F403D434A6E1B3B94A7E62AC1211858E002C75AD4455C9D19C0A3180296917A376205164043E20144FF485719D181A99EB574671AC58054457ED444A67032EA17D03AD43464D2397449CA593630A670D90D95A78E846A3C8AF80862098D80F33C42ED7059E75225E0A52718E2379369F65B79680A6560B080092EE71986066735A96A7D42E7597116742B02D3A154471B6A23D84E0D642C790D597A2BB7F5A48F734898BDD138C69493E723491959C1B4BD40C91C1C7924F88D046467A006507E781220A80C55A927906A7C6C9C227E674686DD5D1B855D28F0D604E24586C608630B9A34C4808381A54F0D9080A5F90B60187F");
69
- SecurityUtils.g = BigInt(2);
70
- SecurityUtils.k = BigInt("0xD55AE1AEC9F9115621E93E16E5DE4517DF8450D0957024D1256AA32B71E4E412");
71
- /*
72
- BigInt helpers
73
- */
74
- SecurityUtils.bytesToBigInt = (bytes) => BigInt("0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""));
75
129
 
76
130
  // src/crypto/crypto.service.ts
77
131
  var CryptoService = class {
78
132
  constructor() {
133
+ /**
134
+ * Generates cryptographically secure random bytes.
135
+ * @param length - Number of bytes (default 32).
136
+ * @returns Uint8Array of random bytes.
137
+ */
79
138
  this.generateRandomBytes = (length = 32) => crypto.getRandomValues(new Uint8Array(length));
80
139
  }
81
- async encryptData(dataModel, key) {
140
+ /**
141
+ * Encrypts a serializable object to a Base64 string.
142
+ * @param dataModel - Object or Uint8Array to encrypt.
143
+ * @param key - AES-256 key (32 bytes).
144
+ * @param options - AES-GCM configuration; uses default if omitted.
145
+ * @returns Base64-encoded ciphertext with prepended nonce.
146
+ */
147
+ async encryptData(dataModel, key, options) {
148
+ const opts = options ?? AesGcmOptions.default;
149
+ opts.validate();
82
150
  const encoder = new TextEncoder();
83
151
  let jsonString;
84
152
  if (dataModel instanceof Uint8Array) {
@@ -87,7 +155,7 @@ var CryptoService = class {
87
155
  jsonString = JSON.stringify(dataModel);
88
156
  }
89
157
  const plainBytes = encoder.encode(jsonString);
90
- const nonce = crypto.getRandomValues(new Uint8Array(SecurityUtils.NONCE_SIZE));
158
+ const nonce = crypto.getRandomValues(new Uint8Array(opts.nonceSize));
91
159
  const cryptoKey = await crypto.subtle.importKey(
92
160
  "raw",
93
161
  key,
@@ -95,28 +163,43 @@ var CryptoService = class {
95
163
  false,
96
164
  ["encrypt"]
97
165
  );
166
+ let associatedData = new Uint8Array(0);
167
+ if (opts.associatedData != null) {
168
+ associatedData = opts.associatedData;
169
+ }
98
170
  const encryptedContent = await crypto.subtle.encrypt(
99
171
  {
100
172
  name: "AES-GCM",
101
173
  iv: nonce,
102
- tagLength: SecurityUtils.TAG_SIZE * 8
174
+ tagLength: opts.tagSize * 8,
175
+ additionalData: associatedData
103
176
  },
104
177
  cryptoKey,
105
178
  plainBytes
106
179
  );
107
- const result = new Uint8Array(SecurityUtils.NONCE_SIZE + encryptedContent.byteLength);
180
+ const result = new Uint8Array(opts.nonceSize + encryptedContent.byteLength);
108
181
  result.set(nonce, 0);
109
- result.set(new Uint8Array(encryptedContent), SecurityUtils.NONCE_SIZE);
182
+ result.set(new Uint8Array(encryptedContent), opts.nonceSize);
110
183
  return SecurityUtils.toBase64(result);
111
184
  }
112
- async decryptedData(encryptedBase64, key) {
185
+ /**
186
+ * Decrypts a Base64-encoded ciphertext back to the original object.
187
+ * @param encryptedBase64 - The encrypted data.
188
+ * @param key - AES-256 key (32 bytes).
189
+ * @param options - AES-GCM configuration; uses default if omitted.
190
+ * @returns Deserialized object, or null if input is empty.
191
+ * @throws If authentication tag mismatch or corrupted data.
192
+ */
193
+ async decryptData(encryptedBase64, key, options, isBytes = false) {
113
194
  if (!encryptedBase64)
114
195
  return null;
196
+ const opts = options ?? AesGcmOptions.default;
197
+ opts.validate();
115
198
  const encryptedBytes = SecurityUtils.fromBase64(encryptedBase64);
116
- if (encryptedBytes.length < SecurityUtils.NONCE_SIZE + SecurityUtils.TAG_SIZE)
117
- throw new Error("\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442 \u0437\u0430\u0448\u0438\u0444\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0445 \u0434\u0430\u043D\u043D\u044B\u0445");
118
- const nonce = encryptedBytes.slice(0, SecurityUtils.NONCE_SIZE);
119
- const ciphertextWithTag = encryptedBytes.slice(SecurityUtils.NONCE_SIZE);
199
+ if (encryptedBytes.length < opts.nonceSize + opts.tagSize)
200
+ throw new Error(`Invalid format: minimum expected ${opts.nonceSize + opts.tagSize} byte.`);
201
+ const nonce = encryptedBytes.slice(0, opts.nonceSize);
202
+ const ciphertextWithTag = encryptedBytes.slice(opts.nonceSize);
120
203
  const cryptoKey = await crypto.subtle.importKey(
121
204
  "raw",
122
205
  key,
@@ -125,125 +208,540 @@ var CryptoService = class {
125
208
  ["decrypt"]
126
209
  );
127
210
  try {
211
+ let associatedData = new Uint8Array(0);
212
+ if (opts.associatedData != null) {
213
+ associatedData = opts.associatedData;
214
+ }
128
215
  const decryptedBuffer = await crypto.subtle.decrypt(
129
216
  {
130
217
  name: "AES-GCM",
131
218
  iv: nonce,
132
- tagLength: SecurityUtils.TAG_SIZE * 8
219
+ tagLength: opts.tagSize * 8,
220
+ additionalData: associatedData
133
221
  },
134
222
  cryptoKey,
135
223
  ciphertextWithTag
136
224
  );
137
225
  const decoder = new TextDecoder();
138
226
  const jsonString = decoder.decode(decryptedBuffer);
227
+ const parsed = JSON.parse(jsonString);
228
+ if (isBytes && typeof parsed === "string") {
229
+ return SecurityUtils.fromBase64(parsed);
230
+ }
139
231
  return JSON.parse(jsonString);
140
232
  } catch (e) {
141
- console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0434\u0435\u0448\u0438\u0444\u0440\u043E\u0432\u0430\u043D\u0438\u044F:", e);
142
- return null;
233
+ console.error("Decryption error:", e);
234
+ throw new Error("Decryption failed: authentication tag mismatch or corrupted data.");
143
235
  }
144
236
  }
145
237
  };
146
238
 
147
- // src/crypto/key-derivation.service.ts
148
- var KeyDerivationService = class {
239
+ // src/crypto/kdf-options.ts
240
+ var KdfOptions = class _KdfOptions {
149
241
  constructor() {
150
- this.ITERATIONS = 6e5;
151
- this.KEY_SIZE = 32;
242
+ this._pbkdf2Iterations = SecurityConstants.Pbkdf2IterationsDefault;
243
+ this._hashAlgorithm = "SHA-256";
244
+ }
245
+ /** PBKDF2 iteration count (minimum 100_000). */
246
+ get pbkdf2Iterations() {
247
+ return this._pbkdf2Iterations;
248
+ }
249
+ set pbkdf2Iterations(v) {
250
+ if (v < SecurityConstants.Pbkdf2IterationsMinimum)
251
+ throw new RangeError(`PBKDF2 iterations must be \u2265 ${SecurityConstants.Pbkdf2IterationsMinimum}`);
252
+ this._pbkdf2Iterations = v;
253
+ }
254
+ /** Hash algorithm used by PBKDF2. Must be one of {@link SupportedHashAlgorithms}. */
255
+ get hashAlgorithm() {
256
+ return this._hashAlgorithm;
257
+ }
258
+ set hashAlgorithm(v) {
259
+ if (!SupportedHashAlgorithms.includes(v))
260
+ throw new RangeError(`Unsupported hash: ${v}`);
261
+ this._hashAlgorithm = v;
262
+ }
263
+ /** Validates iterations and hash algorithm. */
264
+ validate() {
265
+ if (this.pbkdf2Iterations < SecurityConstants.Pbkdf2IterationsMinimum)
266
+ throw new Error(`Pbkdf2Iterations (${this.pbkdf2Iterations}) below minimum`);
267
+ if (!SupportedHashAlgorithms.includes(this.hashAlgorithm))
268
+ throw new Error(`Invalid hash algorithm: ${this.hashAlgorithm}`);
152
269
  }
153
- async deriveKeysFromPassword(login, password, salt) {
270
+ /** Default preset: SHA-256, 600_000 iterations. */
271
+ static get default() {
272
+ return new _KdfOptions();
273
+ }
274
+ /** Fluent setter for {@link pbkdf2Iterations}. */
275
+ withPbkdf2Iterations(i) {
276
+ this.pbkdf2Iterations = i;
277
+ return this;
278
+ }
279
+ /** Fluent setter for {@link hashAlgorithm}. */
280
+ withHashAlgorithm(h) {
281
+ this.hashAlgorithm = h;
282
+ return this;
283
+ }
284
+ /** Validates and returns this instance. */
285
+ build() {
286
+ this.validate();
287
+ return this;
288
+ }
289
+ };
290
+
291
+ // src/crypto/key-derivation.service.ts
292
+ var KeyDerivationService = class {
293
+ /**
294
+ * Derives KEK and Base64 AuthHash. Identity is normalized (trimmed, lowercase).
295
+ * @param identity - User identity (email, username).
296
+ * @param password - User password.
297
+ * @param salt - Random salt.
298
+ * @param options - KDF configuration; uses default if omitted.
299
+ * @returns Object with `kek` (Uint8Array) and `authHash` (Base64 string).
300
+ */
301
+ async deriveKeysFromPassword(identity, password, salt, options) {
302
+ const opts = options ?? KdfOptions.default;
303
+ opts.validate();
154
304
  const safeSalt = new Uint8Array(salt);
155
305
  const encoder = new TextEncoder();
156
- const normalizedLogin = login.trim().toLocaleLowerCase();
306
+ const normalizedLogin = identity.trim().toLowerCase();
157
307
  const combinedPassword = `${normalizedLogin}:${password}`;
158
308
  const passwordBytes = encoder.encode(combinedPassword);
159
309
  const baseKey = await crypto.subtle.importKey("raw", passwordBytes, "PBKDF2", false, ["deriveBits", "deriveKey"]);
160
310
  const masterKeyBits = await crypto.subtle.deriveBits({
161
311
  name: "PBKDF2",
162
312
  salt: safeSalt,
163
- iterations: this.ITERATIONS,
164
- hash: "SHA-256"
165
- }, baseKey, this.KEY_SIZE * 8);
313
+ iterations: opts.pbkdf2Iterations,
314
+ hash: opts.hashAlgorithm
315
+ }, baseKey, SecurityConstants.KeySizeBytes * 8);
166
316
  const masterKey = await crypto.subtle.importKey("raw", masterKeyBits, "HKDF", false, ["deriveBits"]);
167
317
  const kek = await crypto.subtle.deriveBits(
168
- { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: encoder.encode("AES-GCM-KEK-v1") },
318
+ { name: "HKDF", hash: opts.hashAlgorithm, salt: new Uint8Array(0), info: encoder.encode("AES-GCM-KEK-v1") },
169
319
  masterKey,
170
- this.KEY_SIZE * 8
320
+ SecurityConstants.KeySizeBytes * 8
171
321
  );
172
322
  const authBytes = await crypto.subtle.deriveBits(
173
- { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: encoder.encode("SERVER-AUTH-HASH-v1") },
323
+ { name: "HKDF", hash: opts.hashAlgorithm, salt: new Uint8Array(0), info: encoder.encode("SERVER-AUTH-HASH-v1") },
174
324
  masterKey,
175
- this.KEY_SIZE * 8
325
+ SecurityConstants.KeySizeBytes * 8
176
326
  );
177
327
  return {
178
328
  kek: new Uint8Array(kek),
179
329
  authHash: SecurityUtils.toBase64(new Uint8Array(authBytes))
180
330
  };
181
331
  }
332
+ /**
333
+ * Derives an SRP-compatible authentication hash (output size = hash output length).
334
+ * @param identity - User identity.
335
+ * @param password - User password.
336
+ * @param salt - Random salt.
337
+ * @param srpHashAlgorithm - SRP hash algorithm (SHA-256/384/512).
338
+ * @param options - KDF configuration; uses default if omitted.
339
+ * @returns Raw hash bytes for use as SRP verifier input (x).
340
+ */
341
+ async deriveAuthHashForSrp(identity, password, salt, srpHashAlgorithm, options) {
342
+ const opts = options ?? KdfOptions.default;
343
+ opts.validate();
344
+ const srpHashSize = srpHashAlgorithm === "SHA-256" ? 32 : srpHashAlgorithm === "SHA-384" ? 48 : 64;
345
+ const normalizedLogin = identity.trim().toLowerCase();
346
+ const combinedPassword = `${normalizedLogin}:${password}`;
347
+ const passwordBytes = new TextEncoder().encode(combinedPassword);
348
+ const baseKey = await crypto.subtle.importKey(
349
+ "raw",
350
+ passwordBytes,
351
+ "PBKDF2",
352
+ false,
353
+ ["deriveBits"]
354
+ );
355
+ const masterKeyBits = await crypto.subtle.deriveBits({
356
+ name: "PBKDF2",
357
+ salt,
358
+ iterations: opts.pbkdf2Iterations,
359
+ hash: srpHashAlgorithm
360
+ }, baseKey, SecurityConstants.KeySizeBytes * 8);
361
+ const masterKey = await crypto.subtle.importKey(
362
+ "raw",
363
+ masterKeyBits,
364
+ "HKDF",
365
+ false,
366
+ ["deriveBits"]
367
+ );
368
+ const info = new TextEncoder().encode("SRP-AUTH-HASH-v1");
369
+ const authBytes = await crypto.subtle.deriveBits(
370
+ {
371
+ name: "HKDF",
372
+ hash: srpHashAlgorithm,
373
+ salt: new Uint8Array(0),
374
+ info
375
+ },
376
+ masterKey,
377
+ srpHashSize * 8
378
+ );
379
+ return new Uint8Array(authBytes);
380
+ }
381
+ };
382
+
383
+ // src/crypto/crypto-version.ts
384
+ var CryptoVersion = /* @__PURE__ */ ((CryptoVersion2) => {
385
+ CryptoVersion2[CryptoVersion2["V1"] = 1] = "V1";
386
+ return CryptoVersion2;
387
+ })(CryptoVersion || {});
388
+
389
+ // src/crypto/crypto-profile.ts
390
+ var CryptoProfile = class {
391
+ /**
392
+ * Creates a new CryptoProfile.
393
+ * @param params - Object containing version, kdfOptions, aesGcmOptions.
394
+ */
395
+ constructor(params) {
396
+ this.version = params.version;
397
+ this.kdfOptions = params.kdfOptions;
398
+ this.aesGcmOptions = params.aesGcmOptions;
399
+ }
400
+ };
401
+
402
+ // src/crypto/crypto-profile-registry.ts
403
+ var CryptoProfileRegistry = class {
404
+ static getProfile(version) {
405
+ switch (version) {
406
+ case 1 /* V1 */:
407
+ return new CryptoProfile({
408
+ version: 1 /* V1 */,
409
+ kdfOptions: KdfOptions.default,
410
+ aesGcmOptions: AesGcmOptions.default
411
+ });
412
+ default:
413
+ throw new Error(`Unsupported crypto version: ${version}`);
414
+ }
415
+ }
416
+ /** Latest supported profile (currently V1). */
417
+ static get latest() {
418
+ return this.getProfile(1 /* V1 */);
419
+ }
420
+ };
421
+
422
+ // src/utils/srp-encoding.ts
423
+ var SrpEncoding = class {
424
+ /** Serializes a bigint to modulus-sized big-endian bytes. */
425
+ static toModulusBytes(ctx, value) {
426
+ return SecurityUtils.bigIntToFixedBytes(value, ctx.modulusSize);
427
+ }
428
+ /** Serializes a bigint to hash-sized big-endian bytes. */
429
+ static toHashBytes(ctx, value) {
430
+ return SecurityUtils.bigIntToFixedBytes(value, ctx.hashSize);
431
+ }
432
+ /** Hashes modulus-sized values (e.g., u = H(A, B)). */
433
+ static async hashModuli(ctx, ...values) {
434
+ const buffers = values.map((v) => this.toModulusBytes(ctx, v));
435
+ return this.hash(ctx.hashAlgorithmName, ...buffers);
436
+ }
437
+ /** Computes M1 = H(A || B || sessionKeyK). */
438
+ static async computeM1(ctx, A, B, sessionKeyK) {
439
+ return this.hash(ctx.hashAlgorithmName, this.toModulusBytes(ctx, A), this.toModulusBytes(ctx, B), sessionKeyK);
440
+ }
441
+ /** Computes M2 = H(A || M1 || sessionKeyK). */
442
+ static async computeM2(ctx, A, M1, sessionKeyK) {
443
+ return this.hash(ctx.hashAlgorithmName, this.toModulusBytes(ctx, A), this.toHashBytes(ctx, M1), sessionKeyK);
444
+ }
445
+ /** Computes session key K = H(S). */
446
+ static async computeSessionKey(ctx, S) {
447
+ const sBytes = this.toModulusBytes(ctx, S);
448
+ const hashBuffer = await crypto.subtle.digest(
449
+ ctx.hashAlgorithmName,
450
+ sBytes
451
+ );
452
+ return new Uint8Array(hashBuffer);
453
+ }
454
+ /** Concatenates byte arrays and returns the hash as bigint. */
455
+ static async hash(algo, ...buffers) {
456
+ const totalLen = buffers.reduce((sum, b) => sum + b.length, 0);
457
+ const combined = new Uint8Array(totalLen);
458
+ let offset = 0;
459
+ for (const buf of buffers) {
460
+ combined.set(buf, offset);
461
+ offset += buf.length;
462
+ }
463
+ const hashBuffer = await crypto.subtle.digest(algo, combined);
464
+ return SecurityUtils.bytesToBigInt(new Uint8Array(hashBuffer));
465
+ }
182
466
  };
183
467
 
184
- // src/srp/srp.service.ts
185
- var SrpService = class {
468
+ // src/srp/srp-client-service.ts
469
+ var SrpClientService = class {
186
470
  constructor() {
187
471
  this.keyDerivation = new KeyDerivationService();
188
472
  }
189
- async generateSrpVerifier(authHash) {
473
+ /**
474
+ * Computes SRP verifier v = g^x mod N from the authentication hash.
475
+ * @param authHash - Auth hash (Base64).
476
+ * @param ctx - SRP context (N, g, hash algorithm, etc.).
477
+ * @returns Verifier as Base64 string.
478
+ */
479
+ async generateSrpVerifier(authHash, ctx) {
190
480
  const x = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(authHash));
191
- const v = SecurityUtils.expMod(SecurityUtils.g, x, SecurityUtils.N);
192
- return SecurityUtils.toBase64(SecurityUtils.bigIntToFixedBytes(v, SecurityUtils.MODULUS_SIZE));
481
+ const v = SecurityUtils.expMod(ctx.g, x, ctx.N);
482
+ return SecurityUtils.toBase64(SrpEncoding.toModulusBytes(ctx, v));
193
483
  }
194
- async generateSrpProof(login, password, saltBase64, B_base64) {
484
+ /**
485
+ * Generates client proof (A, M1, session key S) from server challenge.
486
+ * @param login - User login.
487
+ * @param password - Plaintext password.
488
+ * @param saltBase64 - Server salt (URL-safe Base64).
489
+ * @param B_base64 - Server public ephemeral B (URL-safe Base64).
490
+ * @param ctx - SRP context.
491
+ * @returns Object with A, M1, S as Base64 strings.
492
+ */
493
+ async generateSrpProof(login, password, saltBase64, B_base64, ctx) {
195
494
  const salt = SecurityUtils.fromBase64(saltBase64);
196
- const { authHash } = await this.keyDerivation.deriveKeysFromPassword(login, password, salt);
197
- const x = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(authHash));
495
+ const authHash = await this.keyDerivation.deriveAuthHashForSrp(login, password, salt, ctx.hashAlgorithmName);
496
+ const x = SecurityUtils.bytesToBigInt(authHash);
198
497
  const aBytes = crypto.getRandomValues(new Uint8Array(32));
199
498
  const a = SecurityUtils.bytesToBigInt(aBytes);
200
- const A = SecurityUtils.expMod(SecurityUtils.g, a, SecurityUtils.N);
201
- if (A % SecurityUtils.N === 0n)
202
- throw new Error("\u041A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430: A % N === 0");
499
+ const A = SecurityUtils.expMod(ctx.g, a, ctx.N);
500
+ if (A % ctx.N === 0n)
501
+ throw new Error("Critical error: A % N === 0");
203
502
  const B = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(B_base64));
204
- if (B % SecurityUtils.N === 0n)
205
- throw new Error("\u041A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430: B % N === 0");
206
- const u = await SecurityUtils.hashAsPerSrp6a([
207
- { value: A, length: SecurityUtils.MODULUS_SIZE },
208
- { value: B, length: SecurityUtils.MODULUS_SIZE }
209
- ]);
503
+ if (B % ctx.N === 0n)
504
+ throw new Error("Critical error: B % N === 0");
505
+ const u = await SrpEncoding.hashModuli(ctx, A, B);
210
506
  if (u === 0n)
211
507
  throw new Error("\u041D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 u");
212
- const gX = SecurityUtils.expMod(SecurityUtils.g, x, SecurityUtils.N);
213
- const term = SecurityUtils.k * gX % SecurityUtils.N;
214
- const base = (B - term + SecurityUtils.N) % SecurityUtils.N;
508
+ const gX = SecurityUtils.expMod(ctx.g, x, ctx.N);
509
+ const term = ctx.k * gX % ctx.N;
510
+ const base = (B - term + ctx.N) % ctx.N;
215
511
  const exponent = a + u * x;
216
- const S = SecurityUtils.expMod(base, exponent, SecurityUtils.N);
512
+ const S = SecurityUtils.expMod(base, exponent, ctx.N);
217
513
  if (S === 0n)
218
- throw new Error("\u041A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430: S === 0");
219
- const M1 = await SecurityUtils.hashAsPerSrp6a([
220
- { value: A, length: SecurityUtils.MODULUS_SIZE },
221
- { value: B, length: SecurityUtils.MODULUS_SIZE },
222
- { value: S, length: SecurityUtils.MODULUS_SIZE }
223
- ]);
514
+ throw new Error("Critical error: S === 0");
515
+ const sessionKeyK = await SrpEncoding.computeSessionKey(ctx, S);
516
+ const M1 = await SrpEncoding.computeM1(ctx, A, B, sessionKeyK);
224
517
  return {
225
- A: SecurityUtils.toBase64(SecurityUtils.bigIntToFixedBytes(A, SecurityUtils.MODULUS_SIZE)),
226
- M1: SecurityUtils.toBase64(SecurityUtils.bigIntToFixedBytes(M1, 32)),
227
- S: SecurityUtils.toBase64(SecurityUtils.bigIntToFixedBytes(S, SecurityUtils.MODULUS_SIZE))
518
+ A: SecurityUtils.toBase64(SrpEncoding.toModulusBytes(ctx, A)),
519
+ M1: SecurityUtils.toBase64(SrpEncoding.toHashBytes(ctx, M1)),
520
+ S: SecurityUtils.toBase64(SrpEncoding.toModulusBytes(ctx, S))
228
521
  };
229
522
  }
230
- async verifyServerM2(A_b64, M1_b64, S_b64, serverM2_b64) {
523
+ /**
524
+ * Validates the server proof M2 to authenticate the server.
525
+ * @param A_b64 - Client public A (Base64).
526
+ * @param M1_b64 - Client proof M1 (Base64).
527
+ * @param S_b64 - Session key S (Base64).
528
+ * @param serverM2_b64 - Server proof M2 (Base64).
529
+ * @param ctx - SRP context.
530
+ * @returns True if the server proof is valid.
531
+ */
532
+ async verifyServerM2(A_b64, M1_b64, S_b64, serverM2_b64, ctx) {
231
533
  const A = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(A_b64));
232
534
  const M1 = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(M1_b64));
233
535
  const S = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(S_b64));
234
- const computedM2 = await SecurityUtils.hashAsPerSrp6a([
235
- { value: A, length: SecurityUtils.MODULUS_SIZE },
236
- { value: M1, length: 32 },
237
- { value: S, length: SecurityUtils.MODULUS_SIZE }
238
- ]);
239
- const computedM2_b64 = SecurityUtils.toBase64(SecurityUtils.bigIntToFixedBytes(computedM2, 32));
240
- return serverM2_b64 === computedM2_b64;
536
+ const sessionKeyK = await SrpEncoding.computeSessionKey(ctx, S);
537
+ const computedM2 = await SrpEncoding.computeM2(ctx, A, M1, sessionKeyK);
538
+ const computedM2Bytes = SrpEncoding.toHashBytes(ctx, computedM2);
539
+ const serverM2Bytes = SecurityUtils.fromBase64(serverM2_b64);
540
+ return SecurityUtils.fixedTimeEquals(computedM2Bytes, serverM2Bytes);
541
+ }
542
+ };
543
+
544
+ // src/srp/srp-server-service.ts
545
+ var SrpServerService = class {
546
+ /**
547
+ * Generates server challenge B and session state from verifier.
548
+ * @param login - User login.
549
+ * @param verifierBytes - Stored verifier v as byte array.
550
+ * @param ctx - SRP context (hash, N, g, etc.).
551
+ * @returns Session state with private b, verifier, and public B.
552
+ */
553
+ async getSrpChallenge(login, verifierBytes, ctx) {
554
+ const v = SecurityUtils.bytesToBigInt(verifierBytes);
555
+ const bBytes = crypto.getRandomValues(new Uint8Array(32));
556
+ const b = SecurityUtils.bytesToBigInt(bBytes);
557
+ const gB = SecurityUtils.expMod(ctx.g, b, ctx.N);
558
+ const B = (ctx.k * v + gB) % ctx.N;
559
+ return {
560
+ login,
561
+ privateKeyB: SecurityUtils.toBase64(bBytes),
562
+ verifier: SecurityUtils.toBase64(verifierBytes),
563
+ publicKeyB: SecurityUtils.toBase64(SrpEncoding.toModulusBytes(ctx, B))
564
+ };
565
+ }
566
+ /**
567
+ * Verifies client M1 proof and returns server M2 proof.
568
+ * @param sessionState - Server session state.
569
+ * @param a - Client public A (Base64).
570
+ * @param m1 - Client proof M1 (Base64).
571
+ * @param ctx - SRP context.
572
+ * @returns Server proof M2 as Base64 string.
573
+ * @throws If verification fails or input is invalid.
574
+ */
575
+ async verifySrpProof(sessionState, a, m1, ctx) {
576
+ const A = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(a));
577
+ const M1_client = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(m1));
578
+ const b = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(sessionState.privateKeyB));
579
+ const v = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(sessionState.verifier));
580
+ const B = SecurityUtils.bytesToBigInt(SecurityUtils.fromBase64(sessionState.publicKeyB));
581
+ if (v <= 0n)
582
+ throw new Error("The verifier is corrupted");
583
+ if (A % ctx.N === 0n)
584
+ throw new Error("Incorrect value of A");
585
+ if (A <= 0n || A >= ctx.N)
586
+ throw new Error("Invalid A (out of range)");
587
+ const u = await SrpEncoding.hashModuli(ctx, A, B);
588
+ if (u === 0n)
589
+ throw new Error("Error in calculating the parameter u");
590
+ const vU = SecurityUtils.expMod(v, u, ctx.N);
591
+ const S = SecurityUtils.expMod(A * vU % ctx.N, b, ctx.N);
592
+ const sessionKeyK = await SrpEncoding.computeSessionKey(ctx, S);
593
+ const M1_server = await SrpEncoding.computeM1(ctx, A, B, sessionKeyK);
594
+ const m1ServerBytes = SrpEncoding.toHashBytes(ctx, M1_server);
595
+ const m1ClientBytes = SrpEncoding.toHashBytes(ctx, M1_client);
596
+ if (!SecurityUtils.fixedTimeEquals(m1ServerBytes, m1ClientBytes))
597
+ throw new Error("Invalid password");
598
+ const M2_server = await SrpEncoding.computeM2(ctx, A, M1_client, sessionKeyK);
599
+ return SecurityUtils.toBase64(SrpEncoding.toHashBytes(ctx, M2_server));
600
+ }
601
+ };
602
+
603
+ // src/srp/srp-group.ts
604
+ var SrpGroup = /* @__PURE__ */ ((SrpGroup2) => {
605
+ SrpGroup2[SrpGroup2["Rfc5054_1024"] = 1] = "Rfc5054_1024";
606
+ SrpGroup2[SrpGroup2["Rfc5054_1536"] = 2] = "Rfc5054_1536";
607
+ SrpGroup2[SrpGroup2["Rfc5054_2048"] = 3] = "Rfc5054_2048";
608
+ SrpGroup2[SrpGroup2["Rfc5054_3072"] = 4] = "Rfc5054_3072";
609
+ SrpGroup2[SrpGroup2["Rfc5054_4096"] = 5] = "Rfc5054_4096";
610
+ SrpGroup2[SrpGroup2["Rfc5054_6144"] = 6] = "Rfc5054_6144";
611
+ SrpGroup2[SrpGroup2["Rfc5054_8192"] = 7] = "Rfc5054_8192";
612
+ SrpGroup2[SrpGroup2["Custom"] = 99] = "Custom";
613
+ return SrpGroup2;
614
+ })(SrpGroup || {});
615
+
616
+ // src/srp/srp-group-params.ts
617
+ var SrpGroupParams = class {
618
+ /**
619
+ * Returns the prime modulus N for the given SRP group.
620
+ * @param group - SRP group identifier.
621
+ * @returns N as a bigint.
622
+ */
623
+ static getN(group) {
624
+ switch (group) {
625
+ case 1 /* Rfc5054_1024 */:
626
+ return BigInt("0xEEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3");
627
+ case 2 /* Rfc5054_1536 */:
628
+ return BigInt("0x9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA9614B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F84380B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0BE3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF56EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734AF7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB");
629
+ case 3 /* Rfc5054_2048 */:
630
+ return BigInt("0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73");
631
+ case 4 /* Rfc5054_3072 */:
632
+ return BigInt("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF");
633
+ case 5 /* Rfc5054_4096 */:
634
+ return BigInt("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF");
635
+ case 6 /* Rfc5054_6144 */:
636
+ return BigInt("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF");
637
+ case 7 /* Rfc5054_8192 */:
638
+ return BigInt("0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF");
639
+ default:
640
+ throw new Error("Unsupported group");
641
+ }
642
+ }
643
+ /**
644
+ * Returns the generator g for the given SRP group.
645
+ * @param group - SRP group identifier.
646
+ * @returns g as a bigint (2, 5, or 19).
647
+ */
648
+ static getG(group) {
649
+ switch (group) {
650
+ case 1 /* Rfc5054_1024 */:
651
+ return BigInt(2);
652
+ case 2 /* Rfc5054_1536 */:
653
+ return BigInt(2);
654
+ case 3 /* Rfc5054_2048 */:
655
+ return BigInt(2);
656
+ case 4 /* Rfc5054_3072 */:
657
+ return BigInt(5);
658
+ case 5 /* Rfc5054_4096 */:
659
+ return BigInt(5);
660
+ case 6 /* Rfc5054_6144 */:
661
+ return BigInt(5);
662
+ case 7 /* Rfc5054_8192 */:
663
+ return BigInt(19);
664
+ default:
665
+ throw new Error("Unsupported group");
666
+ }
667
+ }
668
+ };
669
+
670
+ // src/srp/srp-options.ts
671
+ var SrpOptions = class {
672
+ constructor() {
673
+ /** Diffie-Hellman group. Default Rfc5054_3072 (g=5). */
674
+ this.group = 4 /* Rfc5054_3072 */;
675
+ /** Hash algorithm for SRP computations. Default SHA-256. */
676
+ this.hashAlgorithmName = "SHA-256";
677
+ /** Salt size in bytes. Default 32. */
678
+ this.saltSize = 32;
679
+ }
680
+ /** Prime modulus N for the selected group. */
681
+ get N() {
682
+ return SrpGroupParams.getN(this.group);
683
+ }
684
+ /** Generator g for the selected group (2, 5, or 19). */
685
+ get g() {
686
+ return SrpGroupParams.getG(this.group);
687
+ }
688
+ /** Byte length of N (ceil(bitLength / 8)). */
689
+ get modulusSize() {
690
+ return Math.floor((this.N.toString(2).length + 7) / 8);
691
+ }
692
+ /**
693
+ * Computes the multiplier parameter k = H(PAD(N) || PAD(g)) (RFC 5054, 2.5.3).
694
+ * @returns k as a bigint.
695
+ */
696
+ async computeK() {
697
+ const nBytes = SecurityUtils.bigIntToFixedBytes(this.N, this.modulusSize);
698
+ const gBytes = SecurityUtils.bigIntToFixedBytes(this.g, this.modulusSize);
699
+ const combined = new Uint8Array(nBytes.length + gBytes.length);
700
+ combined.set(nBytes, 0);
701
+ combined.set(gBytes, nBytes.length);
702
+ const hash = await crypto.subtle.digest(this.hashAlgorithmName, combined);
703
+ return SecurityUtils.bytesToBigInt(new Uint8Array(hash));
704
+ }
705
+ };
706
+
707
+ // src/srp/srp-context-factory.ts
708
+ var SrpContextFactory = class {
709
+ /**
710
+ * Creates an SRP context with the specified group.
711
+ * @param group - SRP group (default Rfc5054_3072).
712
+ * @returns A ready-to-use SrpContext.
713
+ */
714
+ static async create(group = 4 /* Rfc5054_3072 */) {
715
+ const opts = new SrpOptions();
716
+ opts.group = group;
717
+ opts.hashAlgorithmName = group === 5 /* Rfc5054_4096 */ || group === 6 /* Rfc5054_6144 */ || group === 7 /* Rfc5054_8192 */ ? "SHA-384" : "SHA-256";
718
+ return {
719
+ N: opts.N,
720
+ g: opts.g,
721
+ k: await opts.computeK(),
722
+ modulusSize: opts.modulusSize,
723
+ hashAlgorithmName: opts.hashAlgorithmName,
724
+ hashSize: opts.hashAlgorithmName === "SHA-256" ? 32 : opts.hashAlgorithmName === "SHA-384" ? 48 : 64
725
+ };
241
726
  }
242
727
  };
243
728
 
729
+ exports.AesGcmOptions = AesGcmOptions;
730
+ exports.CryptoProfile = CryptoProfile;
731
+ exports.CryptoProfileRegistry = CryptoProfileRegistry;
244
732
  exports.CryptoService = CryptoService;
733
+ exports.CryptoVersion = CryptoVersion;
734
+ exports.KdfOptions = KdfOptions;
245
735
  exports.KeyDerivationService = KeyDerivationService;
736
+ exports.SecurityConstants = SecurityConstants;
246
737
  exports.SecurityUtils = SecurityUtils;
247
- exports.SrpService = SrpService;
738
+ exports.SrpClientService = SrpClientService;
739
+ exports.SrpContextFactory = SrpContextFactory;
740
+ exports.SrpEncoding = SrpEncoding;
741
+ exports.SrpGroup = SrpGroup;
742
+ exports.SrpGroupParams = SrpGroupParams;
743
+ exports.SrpOptions = SrpOptions;
744
+ exports.SrpServerService = SrpServerService;
745
+ exports.SupportedHashAlgorithms = SupportedHashAlgorithms;
248
746
  //# sourceMappingURL=index.cjs.map
249
747
  //# sourceMappingURL=index.cjs.map