@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.d.cts CHANGED
@@ -1,47 +1,381 @@
1
+ declare const SecurityConstants: {
2
+ readonly AesGcmNonceSize: 12;
3
+ readonly AesGcmTagSize: 16;
4
+ readonly AesGcmTagSizeMin: 12;
5
+ readonly AesGcmTagSizeMax: 16;
6
+ readonly KeySizeBytes: 32;
7
+ readonly Pbkdf2IterationsDefault: 600000;
8
+ readonly Pbkdf2IterationsMinimum: 100000;
9
+ };
10
+
11
+ type HashAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512';
12
+
13
+ declare const SupportedHashAlgorithms: ReadonlyArray<HashAlgorithm>;
14
+
15
+ /**
16
+ * AES-GCM encryption options: nonce size, tag size, and optional AAD.
17
+ * Mutable builder-style; call {@link build} to validate.
18
+ */
19
+ declare class AesGcmOptions {
20
+ private _nonceSize;
21
+ private _tagSize;
22
+ /** Optional Additional Authenticated Data (not encrypted). */
23
+ associatedData?: Uint8Array;
24
+ /** Nonce size in bytes (must be 12). */
25
+ get nonceSize(): number;
26
+ set nonceSize(v: number);
27
+ /** Tag size in bytes (12–16, default 16). */
28
+ get tagSize(): number;
29
+ set tagSize(v: number);
30
+ /** Validates that {@link tagSize} is in the allowed range. */
31
+ validate(): void;
32
+ /** Default preset: nonce=12, tag=16, no AAD. */
33
+ static get default(): AesGcmOptions;
34
+ /** Fluent setter for {@link tagSize}. */
35
+ withTagSize(s: number): this;
36
+ /**
37
+ * Fluent setter for {@link associatedData}.
38
+ * Accepts a byte array or a UTF-8 string (encoded internally).
39
+ */
40
+ withAssociatedData(aad: Uint8Array | string | undefined): this;
41
+ /** Validates and returns this instance. */
42
+ build(): AesGcmOptions;
43
+ }
44
+
45
+ /**
46
+ * AES-GCM encryption/decryption service with JSON serialization.
47
+ * Encrypted output format (Base64): [Nonce][Ciphertext+Tag].
48
+ */
1
49
  declare class CryptoService {
2
- encryptData<T>(dataModel: T, key: Uint8Array): Promise<string>;
3
- decryptedData<T>(encryptedBase64: string, key: Uint8Array): Promise<T | null>;
50
+ /**
51
+ * Encrypts a serializable object to a Base64 string.
52
+ * @param dataModel - Object or Uint8Array to encrypt.
53
+ * @param key - AES-256 key (32 bytes).
54
+ * @param options - AES-GCM configuration; uses default if omitted.
55
+ * @returns Base64-encoded ciphertext with prepended nonce.
56
+ */
57
+ encryptData<T>(dataModel: T, key: Uint8Array, options?: AesGcmOptions): Promise<string>;
58
+ /**
59
+ * Decrypts a Base64-encoded ciphertext back to the original object.
60
+ * @param encryptedBase64 - The encrypted data.
61
+ * @param key - AES-256 key (32 bytes).
62
+ * @param options - AES-GCM configuration; uses default if omitted.
63
+ * @returns Deserialized object, or null if input is empty.
64
+ * @throws If authentication tag mismatch or corrupted data.
65
+ */
66
+ decryptData<T>(encryptedBase64: string, key: Uint8Array, options?: AesGcmOptions, isBytes?: boolean): Promise<T | null>;
67
+ /**
68
+ * Generates cryptographically secure random bytes.
69
+ * @param length - Number of bytes (default 32).
70
+ * @returns Uint8Array of random bytes.
71
+ */
4
72
  generateRandomBytes: (length?: number) => Uint8Array;
5
73
  }
6
74
 
75
+ /**
76
+ * PBKDF2 key derivation options: iterations count and hash algorithm.
77
+ * Mutable builder-style; call {@link build} to validate.
78
+ */
79
+ declare class KdfOptions {
80
+ private _pbkdf2Iterations;
81
+ private _hashAlgorithm;
82
+ /** PBKDF2 iteration count (minimum 100_000). */
83
+ get pbkdf2Iterations(): number;
84
+ set pbkdf2Iterations(v: number);
85
+ /** Hash algorithm used by PBKDF2. Must be one of {@link SupportedHashAlgorithms}. */
86
+ get hashAlgorithm(): HashAlgorithm;
87
+ set hashAlgorithm(v: HashAlgorithm);
88
+ /** Validates iterations and hash algorithm. */
89
+ validate(): void;
90
+ /** Default preset: SHA-256, 600_000 iterations. */
91
+ static get default(): KdfOptions;
92
+ /** Fluent setter for {@link pbkdf2Iterations}. */
93
+ withPbkdf2Iterations(i: number): this;
94
+ /** Fluent setter for {@link hashAlgorithm}. */
95
+ withHashAlgorithm(h: HashAlgorithm): this;
96
+ /** Validates and returns this instance. */
97
+ build(): KdfOptions;
98
+ }
99
+
100
+ /**
101
+ * Two-stage key derivation: PBKDF2 (master key) → HKDF (sub-keys).
102
+ */
7
103
  declare class KeyDerivationService {
8
- readonly ITERATIONS = 600000;
9
- readonly KEY_SIZE = 32;
10
- deriveKeysFromPassword(login: string, password: string, salt: Uint8Array): Promise<{
104
+ /**
105
+ * Derives KEK and Base64 AuthHash. Identity is normalized (trimmed, lowercase).
106
+ * @param identity - User identity (email, username).
107
+ * @param password - User password.
108
+ * @param salt - Random salt.
109
+ * @param options - KDF configuration; uses default if omitted.
110
+ * @returns Object with `kek` (Uint8Array) and `authHash` (Base64 string).
111
+ */
112
+ deriveKeysFromPassword(identity: string, password: string, salt: Uint8Array, options?: KdfOptions): Promise<{
11
113
  kek: Uint8Array;
12
114
  authHash: string;
13
115
  }>;
116
+ /**
117
+ * Derives an SRP-compatible authentication hash (output size = hash output length).
118
+ * @param identity - User identity.
119
+ * @param password - User password.
120
+ * @param salt - Random salt.
121
+ * @param srpHashAlgorithm - SRP hash algorithm (SHA-256/384/512).
122
+ * @param options - KDF configuration; uses default if omitted.
123
+ * @returns Raw hash bytes for use as SRP verifier input (x).
124
+ */
125
+ deriveAuthHashForSrp(identity: string, password: string, salt: Uint8Array, srpHashAlgorithm: HashAlgorithm, options?: KdfOptions): Promise<Uint8Array>;
14
126
  }
15
127
 
16
- declare class SecurityUtils {
17
- static readonly MODULUS_SIZE: number;
18
- static readonly NONCE_SIZE: number;
19
- static readonly TAG_SIZE: number;
20
- static readonly KEY_SIZE: number;
21
- static readonly N: bigint;
22
- static readonly g: bigint;
23
- static readonly k: bigint;
24
- static toBase64(bytes: Uint8Array): string;
25
- static fromBase64(base64: string): Uint8Array;
26
- static bytesToBigInt: (bytes: Uint8Array) => bigint;
27
- static bigIntToFixedBytes(bn: bigint, length: number): Uint8Array;
28
- private static fromHex;
29
- static expMod(base: bigint, exp: bigint, mod: bigint): bigint;
30
- static hashAsPerSrp6a(items: {
31
- value: bigint;
32
- length: number;
33
- }[]): Promise<bigint>;
128
+ /**
129
+ * Supported cryptographic profile versions.
130
+ * V1: baseline (PBKDF2-HMAC-SHA256, AES-256-GCM, 12-byte nonce, 16-byte tag).
131
+ * Append new members sequentially; never change existing values.
132
+ */
133
+ declare enum CryptoVersion {
134
+ /** Version 1 — initial profile. */
135
+ V1 = 1
34
136
  }
35
137
 
36
- declare class SrpService {
138
+ /**
139
+ * Immutable cryptographic profile bundling version, KDF, and AES-GCM settings.
140
+ * Thread-safe after construction.
141
+ */
142
+ declare class CryptoProfile {
143
+ /** Protocol version, influencing KDF defaults, cipher modes, and serialization. */
144
+ readonly version: CryptoVersion;
145
+ /** Key derivation parameters (iterations, hash algorithm). */
146
+ readonly kdfOptions: KdfOptions;
147
+ /** AES-GCM encryption parameters (nonce size, tag size, AAD). */
148
+ readonly aesGcmOptions: AesGcmOptions;
149
+ /**
150
+ * Creates a new CryptoProfile.
151
+ * @param params - Object containing version, kdfOptions, aesGcmOptions.
152
+ */
153
+ constructor(params: {
154
+ version: CryptoVersion;
155
+ kdfOptions: KdfOptions;
156
+ aesGcmOptions: AesGcmOptions;
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Registry of predefined {@link CryptoProfile} instances by version.
162
+ * Returns a fresh profile per call.
163
+ */
164
+ declare class CryptoProfileRegistry {
165
+ static getProfile(version: CryptoVersion): CryptoProfile;
166
+ /** Latest supported profile (currently V1). */
167
+ static get latest(): CryptoProfile;
168
+ }
169
+
170
+ /**
171
+ * Immutable SRP cryptographic context: modulus, generator, multiplier k, hash algorithm, and sizes.
172
+ */
173
+ interface SrpContext {
174
+ /** Prime modulus N. */
175
+ readonly N: bigint;
176
+ /** Generator g. */
177
+ readonly g: bigint;
178
+ /** Multiplier k = H(PAD(N) || PAD(g)) (RFC 5054, 2.5.3) */
179
+ readonly k: bigint;
180
+ /** Modulus size in bytes (ceil(bit length / 8)). */
181
+ readonly modulusSize: number;
182
+ /** Hash algorithm used for SRP computations. */
183
+ readonly hashAlgorithmName: HashAlgorithm;
184
+ /** Hash output size in bytes (e.g., 32 for SHA-256). */
185
+ readonly hashSize: number;
186
+ }
187
+
188
+ /**
189
+ * Client-side SRP-6a implementation: proof generation, verifier creation, server M2 verification.
190
+ */
191
+ declare class SrpClientService {
37
192
  private readonly keyDerivation;
38
- generateSrpVerifier(authHash: string): Promise<string>;
39
- generateSrpProof(login: string, password: string, saltBase64: string, B_base64: string): Promise<{
193
+ /**
194
+ * Computes SRP verifier v = g^x mod N from the authentication hash.
195
+ * @param authHash - Auth hash (Base64).
196
+ * @param ctx - SRP context (N, g, hash algorithm, etc.).
197
+ * @returns Verifier as Base64 string.
198
+ */
199
+ generateSrpVerifier(authHash: string, ctx: SrpContext): Promise<string>;
200
+ /**
201
+ * Generates client proof (A, M1, session key S) from server challenge.
202
+ * @param login - User login.
203
+ * @param password - Plaintext password.
204
+ * @param saltBase64 - Server salt (URL-safe Base64).
205
+ * @param B_base64 - Server public ephemeral B (URL-safe Base64).
206
+ * @param ctx - SRP context.
207
+ * @returns Object with A, M1, S as Base64 strings.
208
+ */
209
+ generateSrpProof(login: string, password: string, saltBase64: string, B_base64: string, ctx: SrpContext): Promise<{
40
210
  A: string;
41
211
  M1: string;
42
212
  S: string;
43
213
  }>;
44
- verifyServerM2(A_b64: string, M1_b64: string, S_b64: string, serverM2_b64: string): Promise<boolean>;
214
+ /**
215
+ * Validates the server proof M2 to authenticate the server.
216
+ * @param A_b64 - Client public A (Base64).
217
+ * @param M1_b64 - Client proof M1 (Base64).
218
+ * @param S_b64 - Session key S (Base64).
219
+ * @param serverM2_b64 - Server proof M2 (Base64).
220
+ * @param ctx - SRP context.
221
+ * @returns True if the server proof is valid.
222
+ */
223
+ verifyServerM2(A_b64: string, M1_b64: string, S_b64: string, serverM2_b64: string, ctx: SrpContext): Promise<boolean>;
224
+ }
225
+
226
+ /**
227
+ * Server-side SRP session state containing ephemeral keys and verifier.
228
+ */
229
+ interface SrpSessionState {
230
+ /** User login identifier. */
231
+ login: string;
232
+ /** Server private ephemeral key (Base64). */
233
+ privateKeyB: string;
234
+ /** Password verifier (Base64). */
235
+ verifier: string;
236
+ /** Server public ephemeral key B (Base64). */
237
+ publicKeyB: string;
238
+ }
239
+ /**
240
+ * Server-side SRP-6a: challenge generation, client proof verification, server proof creation.
241
+ */
242
+ declare class SrpServerService {
243
+ /**
244
+ * Generates server challenge B and session state from verifier.
245
+ * @param login - User login.
246
+ * @param verifierBytes - Stored verifier v as byte array.
247
+ * @param ctx - SRP context (hash, N, g, etc.).
248
+ * @returns Session state with private b, verifier, and public B.
249
+ */
250
+ getSrpChallenge(login: string, verifierBytes: Uint8Array, ctx: SrpContext): Promise<SrpSessionState>;
251
+ /**
252
+ * Verifies client M1 proof and returns server M2 proof.
253
+ * @param sessionState - Server session state.
254
+ * @param a - Client public A (Base64).
255
+ * @param m1 - Client proof M1 (Base64).
256
+ * @param ctx - SRP context.
257
+ * @returns Server proof M2 as Base64 string.
258
+ * @throws If verification fails or input is invalid.
259
+ */
260
+ verifySrpProof(sessionState: SrpSessionState, a: string, m1: string, ctx: SrpContext): Promise<string>;
261
+ }
262
+
263
+ /**
264
+ * SRP-6a Diffie-Hellman groups (RFC 5054).
265
+ * 1024 (~80) deprecated, 1536 (~90) legacy, 2048 (~112) baseline,
266
+ * 3072+ (≥128) preferred. g=2 for ≤2048, g=5 for 3072-6144, g=19 for 8192.
267
+ * Always use {@link SrpGroupParams} to get N and g.
268
+ */
269
+ declare enum SrpGroup {
270
+ /** 1024-bit, g=2, ~80-bit security. Deprecated, legacy only. */
271
+ Rfc5054_1024 = 1,
272
+ /** 1536-bit, g=2, ~90-bit security. Minimum for legacy systems. */
273
+ Rfc5054_1536 = 2,
274
+ /** 2048-bit, g=2, ~112-bit security. Recommended baseline. */
275
+ Rfc5054_2048 = 3,
276
+ /** 3072-bit, g=5, ~128-bit security. Preferred for long-term. */
277
+ Rfc5054_3072 = 4,
278
+ /** 4096-bit, g=5, ~156-bit security. High-security environments. */
279
+ Rfc5054_4096 = 5,
280
+ /** 6144-bit, g=5, ~192-bit security. Specialized high-assurance. */
281
+ Rfc5054_6144 = 6,
282
+ /** 8192-bit, g=19, ~256-bit security. Experimental, extremely slow. */
283
+ Rfc5054_8192 = 7,
284
+ /** User-supplied N and g. Validate safe prime and generator. */
285
+ Custom = 99
286
+ }
287
+
288
+ /**
289
+ * Immutable-style SRP-6a configuration. Parameters aligned with RFC 5054.
290
+ * Compute `k` via {@link computeK}.
291
+ */
292
+ declare class SrpOptions {
293
+ /** Diffie-Hellman group. Default Rfc5054_3072 (g=5). */
294
+ group: SrpGroup;
295
+ /** Hash algorithm for SRP computations. Default SHA-256. */
296
+ hashAlgorithmName: HashAlgorithm;
297
+ /** Salt size in bytes. Default 32. */
298
+ saltSize: number;
299
+ /** Prime modulus N for the selected group. */
300
+ get N(): bigint;
301
+ /** Generator g for the selected group (2, 5, or 19). */
302
+ get g(): bigint;
303
+ /** Byte length of N (ceil(bitLength / 8)). */
304
+ get modulusSize(): number;
305
+ /**
306
+ * Computes the multiplier parameter k = H(PAD(N) || PAD(g)) (RFC 5054, 2.5.3).
307
+ * @returns k as a bigint.
308
+ */
309
+ computeK(): Promise<bigint>;
310
+ }
311
+
312
+ /**
313
+ * Provides prime modulus (N) and generator (g) for SRP groups (RFC 5054).
314
+ */
315
+ declare class SrpGroupParams {
316
+ /**
317
+ * Returns the prime modulus N for the given SRP group.
318
+ * @param group - SRP group identifier.
319
+ * @returns N as a bigint.
320
+ */
321
+ static getN(group: SrpGroup): bigint;
322
+ /**
323
+ * Returns the generator g for the given SRP group.
324
+ * @param group - SRP group identifier.
325
+ * @returns g as a bigint (2, 5, or 19).
326
+ */
327
+ static getG(group: SrpGroup): bigint;
328
+ }
329
+
330
+ /**
331
+ * Factory for creating an {@link SrpContext} from an SRP group.
332
+ * Automatically selects the hash algorithm (SHA-256 for ≤3072-bit, SHA-384 for 4096+).
333
+ */
334
+ declare class SrpContextFactory {
335
+ /**
336
+ * Creates an SRP context with the specified group.
337
+ * @param group - SRP group (default Rfc5054_3072).
338
+ * @returns A ready-to-use SrpContext.
339
+ */
340
+ static create(group?: SrpGroup): Promise<SrpContext>;
341
+ }
342
+
343
+ /**
344
+ * Cryptographic utility functions: Base64, BigInteger conversion, constant-time comparison, modular exponentiation.
345
+ */
346
+ declare class SecurityUtils {
347
+ /** Encodes Uint8Array to standard Base64. */
348
+ static toBase64(bytes: Uint8Array): string;
349
+ /** Decodes URL-safe or standard Base64 to Uint8Array. */
350
+ static fromBase64(base64: string): Uint8Array;
351
+ /** Converts big-endian bytes to bigint. */
352
+ static bytesToBigInt(bytes: Uint8Array): bigint;
353
+ /** Converts bigint to fixed-length big-endian bytes (pads/truncates). */
354
+ static bigIntToFixedBytes(bn: bigint, length: number): Uint8Array;
355
+ /** Constant-time comparison of two Uint8Arrays. */
356
+ static fixedTimeEquals(a: Uint8Array, b: Uint8Array): boolean;
357
+ /** Modular exponentiation (base^exp mod mod) using binary exponentiation. */
358
+ static expMod(base: bigint, exp: bigint, mod: bigint): bigint;
359
+ }
360
+
361
+ /**
362
+ * SRP-specific serialization and hashing utilities.
363
+ */
364
+ declare class SrpEncoding {
365
+ /** Serializes a bigint to modulus-sized big-endian bytes. */
366
+ static toModulusBytes(ctx: SrpContext, value: bigint): Uint8Array;
367
+ /** Serializes a bigint to hash-sized big-endian bytes. */
368
+ static toHashBytes(ctx: SrpContext, value: bigint): Uint8Array;
369
+ /** Hashes modulus-sized values (e.g., u = H(A, B)). */
370
+ static hashModuli(ctx: SrpContext, ...values: bigint[]): Promise<bigint>;
371
+ /** Computes M1 = H(A || B || sessionKeyK). */
372
+ static computeM1(ctx: SrpContext, A: bigint, B: bigint, sessionKeyK: Uint8Array): Promise<bigint>;
373
+ /** Computes M2 = H(A || M1 || sessionKeyK). */
374
+ static computeM2(ctx: SrpContext, A: bigint, M1: bigint, sessionKeyK: Uint8Array): Promise<bigint>;
375
+ /** Computes session key K = H(S). */
376
+ static computeSessionKey(ctx: SrpContext, S: bigint): Promise<Uint8Array>;
377
+ /** Concatenates byte arrays and returns the hash as bigint. */
378
+ private static hash;
45
379
  }
46
380
 
47
- export { CryptoService, KeyDerivationService, SecurityUtils, SrpService };
381
+ export { AesGcmOptions, CryptoProfile, CryptoProfileRegistry, CryptoService, CryptoVersion, type HashAlgorithm, KdfOptions, KeyDerivationService, SecurityConstants, SecurityUtils, SrpClientService, type SrpContext, SrpContextFactory, SrpEncoding, SrpGroup, SrpGroupParams, SrpOptions, SrpServerService, type SrpSessionState, SupportedHashAlgorithms };