@trust-proto/auth-node 0.2.0 → 0.2.2

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.
@@ -0,0 +1,424 @@
1
+ import { SecureContextOptions } from 'tls';
2
+
3
+ /**
4
+ * Blockchain configuration constants
5
+ * Supports production and development environments
6
+ */
7
+ /** Environment type */
8
+ type Environment = 'production' | 'development';
9
+ /** Network configuration interface */
10
+ interface NetworkConfig {
11
+ RPC_ENDPOINT: string;
12
+ USER_CONTRACT_ADDRESS: string;
13
+ IPFS_GATEWAY: string;
14
+ TRUST_GATE_URL: string;
15
+ }
16
+ /**
17
+ * Get network configuration for specified environment
18
+ * @param env - Environment ('production' | 'development'), default: 'production'
19
+ * @returns Network configuration object
20
+ */
21
+ declare function getNetworkConfig(env?: Environment): NetworkConfig;
22
+ /** User contract ABI (minimal for tokenURI) */
23
+ declare const USER_CONTRACT_ABI: readonly [{
24
+ readonly inputs: readonly [{
25
+ readonly internalType: "address";
26
+ readonly name: "tokenId";
27
+ readonly type: "address";
28
+ }];
29
+ readonly name: "tokenURI";
30
+ readonly outputs: readonly [{
31
+ readonly internalType: "string";
32
+ readonly name: "";
33
+ readonly type: "string";
34
+ }];
35
+ readonly stateMutability: "view";
36
+ readonly type: "function";
37
+ }];
38
+
39
+ /**
40
+ * Liberion Auth Backend SDK Types
41
+ */
42
+
43
+ /**
44
+ * Logger interface for dependency injection
45
+ */
46
+ interface ILogger {
47
+ info(message: string, meta?: Record<string, unknown>): void;
48
+ warn(message: string, meta?: Record<string, unknown>): void;
49
+ error(message: string, meta?: Record<string, unknown>): void;
50
+ }
51
+ /**
52
+ * User SNFT token structure from IPFS
53
+ */
54
+ interface UserToken {
55
+ /** ML-DSA-87 public key (base64 encoded, 2592 bytes decoded) */
56
+ publicKeySign: string;
57
+ /** ML-KEM-1024 public key (base64 encoded, 1568 bytes decoded) */
58
+ publicKeyEncrypt: string;
59
+ /** Optional KYC assets */
60
+ assets?: Record<string, unknown>;
61
+ /** Additional token properties */
62
+ [key: string]: unknown;
63
+ }
64
+ /**
65
+ * SSL/TLS credentials for HTTPS server
66
+ * Accepts all options from Node.js tls.SecureContextOptions
67
+ * @see https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions
68
+ */
69
+ type SSLCredentials = SecureContextOptions;
70
+ /**
71
+ * Decline reason categories
72
+ */
73
+ type DeclineReason = 'user_declined' | 'timeout' | 'error' | 'unknown';
74
+ /**
75
+ * Information about declined authorization
76
+ */
77
+ interface DeclineInfo {
78
+ /** User wallet address (null if declined before activation) */
79
+ address: string | null;
80
+ /** Standardized decline reason */
81
+ reason: DeclineReason;
82
+ /** Detailed message */
83
+ message: string;
84
+ /** Who initiated the decline */
85
+ declinedBy: 'wallet' | 'browser';
86
+ /** Session identifier */
87
+ sessionId: string;
88
+ }
89
+ /**
90
+ * Payload received on successful authorization
91
+ */
92
+ interface AuthPayload {
93
+ /** User wallet address */
94
+ address: string;
95
+ /** KYC fields provided by user */
96
+ fields: Record<string, unknown>;
97
+ }
98
+ /**
99
+ * Result returned from onSuccess callback
100
+ */
101
+ interface AuthResult {
102
+ /** JWT token for authenticated user */
103
+ token?: string;
104
+ /** Error message if authentication failed */
105
+ error?: string;
106
+ }
107
+ /**
108
+ * Main configuration for LiberionAuth
109
+ */
110
+ interface LiberionAuthConfig {
111
+ /** Project UUID from Liberion dashboard */
112
+ projectId: string;
113
+ /** Secret code for AES-256-CBC encryption */
114
+ secretCode: string;
115
+ /** WebSocket server port (default: 31313) */
116
+ port?: number;
117
+ /** Enable debug logging (default: false) */
118
+ debug?: boolean;
119
+ /** SSL credentials for HTTPS (default: undefined, use HTTP) */
120
+ ssl?: SSLCredentials;
121
+ /** Environment: 'production' or 'development' (default: 'production') */
122
+ environment?: Environment;
123
+ /** Logger instance (default: NoOpLogger) */
124
+ logger?: ILogger;
125
+ /**
126
+ * Called when wallet activates (scans QR)
127
+ * @param address - User wallet address
128
+ * @returns true if user is registered, false otherwise
129
+ */
130
+ onHello?: (address: string) => Promise<boolean>;
131
+ /**
132
+ * Called on successful authorization
133
+ * @param payload - Contains address and KYC fields
134
+ * @returns Object with token or error
135
+ */
136
+ onSuccess?: (payload: AuthPayload) => Promise<AuthResult>;
137
+ /**
138
+ * Called when authorization is declined
139
+ * @param info - Decline details including reason and who declined
140
+ */
141
+ onDecline?: (info: DeclineInfo) => Promise<void>;
142
+ }
143
+ /**
144
+ * Session data stored for each connected client
145
+ */
146
+ interface Session {
147
+ /** WebSocket client reference */
148
+ client: unknown;
149
+ /** Session UUID (for browser-wallet linking) */
150
+ sessionId: string | null;
151
+ /** User wallet address (set after activation) */
152
+ address: string | null;
153
+ /** Client session ID (for wallet auth) */
154
+ clientSessionId: string | null;
155
+ /** True if this is a browser session */
156
+ isBrowserSession: boolean;
157
+ /** Stored auth result for reconnect scenario */
158
+ authResult?: {
159
+ token: string;
160
+ };
161
+ /** Stored decline result for reconnect scenario */
162
+ declineResult?: {
163
+ message: string;
164
+ };
165
+ /** Authorization timeout handle */
166
+ timeout?: NodeJS.Timeout;
167
+ }
168
+ /**
169
+ * Crypto instance for signature verification
170
+ */
171
+ interface CryptoInstance {
172
+ /** ML-DSA-87 public key */
173
+ dsaPublicKey: Uint8Array;
174
+ /** ML-KEM-1024 public key (optional) */
175
+ kemPublicKey: Uint8Array | null;
176
+ /** Algorithm identifier */
177
+ algorithm: string;
178
+ /** Original user token */
179
+ userToken: UserToken;
180
+ /**
181
+ * Verify ML-DSA-87 signature
182
+ * @param msg - Message that was signed
183
+ * @param signature - ML-DSA-87 signature
184
+ * @returns true if signature is valid
185
+ */
186
+ verifySignature: (msg: Buffer | Uint8Array, sig: Buffer | Uint8Array) => boolean;
187
+ }
188
+
189
+ /**
190
+ * LiberionAuth - Main SDK class for Liberion authentication
191
+ * Creates a WebSocket server that handles browser and wallet connections
192
+ */
193
+
194
+ declare class LiberionAuth {
195
+ private logger;
196
+ private projectId;
197
+ private secretCode;
198
+ private networkConfig;
199
+ private sessions;
200
+ private interval;
201
+ private onHello?;
202
+ private onSuccess?;
203
+ private onDecline?;
204
+ static readonly COMMAND_AUTH = "auth";
205
+ static readonly COMMAND_READY = "ready";
206
+ constructor(config: LiberionAuthConfig);
207
+ private encode;
208
+ private decode;
209
+ private request;
210
+ private send;
211
+ private readMessage;
212
+ private newClient;
213
+ private handleClose;
214
+ private responseInit;
215
+ private responseActivate;
216
+ private responseAuth;
217
+ private responseDeclined;
218
+ private responseReconnect;
219
+ private responseFailed;
220
+ private errorResponse;
221
+ private finalResponse;
222
+ private finalizeSession;
223
+ private closeClient;
224
+ private findSession;
225
+ }
226
+
227
+ /**
228
+ * Logger adapters for dependency injection
229
+ */
230
+
231
+ /**
232
+ * No-operation logger - default when no logger provided
233
+ * Silently ignores all log calls
234
+ */
235
+ declare class NoOpLogger implements ILogger {
236
+ info(): void;
237
+ warn(): void;
238
+ error(): void;
239
+ }
240
+ /**
241
+ * Console logger for development/debugging
242
+ * Outputs to stdout/stderr with timestamps
243
+ */
244
+ declare class ConsoleLogger implements ILogger {
245
+ private readonly prefix;
246
+ constructor(prefix?: string);
247
+ info(message: string, meta?: Record<string, unknown>): void;
248
+ warn(message: string, meta?: Record<string, unknown>): void;
249
+ error(message: string, meta?: Record<string, unknown>): void;
250
+ }
251
+ /**
252
+ * Create a logger adapter from Winston logger instance
253
+ * @param winston - Winston logger instance
254
+ * @returns ILogger compatible adapter
255
+ *
256
+ * @example
257
+ * ```typescript
258
+ * import { createWinstonAdapter } from '@trust-proto/auth-node';
259
+ * import { logger } from './my-winston-logger';
260
+ *
261
+ * const auth = new LiberionAuth({
262
+ * logger: createWinstonAdapter(logger),
263
+ * // ...
264
+ * });
265
+ * ```
266
+ */
267
+ declare function createWinstonAdapter(winston: {
268
+ info: (message: string, meta?: Record<string, unknown>) => void;
269
+ warn: (message: string, meta?: Record<string, unknown>) => void;
270
+ error: (message: string, meta?: Record<string, unknown>) => void;
271
+ }): ILogger;
272
+ /**
273
+ * Shorten blockchain address for logging (privacy protection)
274
+ * @param address - Full blockchain address
275
+ * @returns Shortened address like "0x1234...abcd"
276
+ */
277
+ declare function shortenAddress(address: string | null | undefined): string;
278
+
279
+ /**
280
+ * AES-256-CBC encryption utilities
281
+ */
282
+ /**
283
+ * Encrypt buffer using AES-256-CBC
284
+ * @param buffer - Data to encrypt
285
+ * @param key - Encryption key (will be hashed to 32 bytes)
286
+ * @returns Encrypted buffer with IV prepended (16 bytes IV + encrypted data)
287
+ */
288
+ declare function encryptBuffer(buffer: Buffer, key: string): Buffer;
289
+ /**
290
+ * Decrypt buffer using AES-256-CBC
291
+ * @param data - Encrypted data (16 bytes IV + encrypted data)
292
+ * @param key - Decryption key (will be hashed to 32 bytes)
293
+ * @returns Decrypted buffer
294
+ */
295
+ declare function decryptBuffer(data: Buffer, key: string): Buffer;
296
+
297
+ /**
298
+ * Post-Quantum Cryptography utility class
299
+ * Implements hybrid encryption: ML-KEM-1024 + XChaCha20-Poly1305 + ML-DSA-87
300
+ */
301
+
302
+ /**
303
+ * Post-Quantum Cryptography utility class
304
+ * Used by Trust Gate to:
305
+ * 1. Generate temporary session keys
306
+ * 2. Encrypt data for Wallet using user's public keys
307
+ * 3. Sign KEM ciphertext for authenticity
308
+ *
309
+ * Format matches client (cipher.js):
310
+ * version (1) + header (4) + sigLen (4) + signature + cipherText + nonce (24) + ct
311
+ */
312
+ declare class PQCrypto {
313
+ private logger;
314
+ private _kemPrivateKey;
315
+ private kemPublicKey;
316
+ private dsaPrivateKey;
317
+ private dsaPublicKey;
318
+ private peerKEMPublicKey;
319
+ private peerDSAPublicKey;
320
+ constructor(logger?: ILogger);
321
+ /**
322
+ * Generate Trust Gate session keys from cryptographic seed
323
+ * @param seed - Random seed (at least 96 bytes: 64 for ML-KEM + 32 for ML-DSA)
324
+ */
325
+ generateKeysFromSeed(seed: Uint8Array): Promise<void>;
326
+ /**
327
+ * Import peer's (user) public keys for encryption and verification
328
+ * @param kemPublicKey - ML-KEM-1024 public key (1568 bytes)
329
+ * @param dsaPublicKey - ML-DSA-87 public key (2592 bytes)
330
+ */
331
+ importPeerPublicKeys(kemPublicKey: Uint8Array | Buffer, dsaPublicKey: Uint8Array | Buffer): void;
332
+ /**
333
+ * Hybrid encryption: ML-KEM + XChaCha20-Poly1305 + ML-DSA signature
334
+ * Matches client format: version + header + sigLen + signature + cipherText + nonce + ct
335
+ * @param message - Data to encrypt
336
+ * @returns Encrypted package in client-compatible format
337
+ */
338
+ encrypt(message: ArrayBuffer | Uint8Array | Buffer): Promise<Buffer>;
339
+ /**
340
+ * Check if keys have been generated
341
+ */
342
+ hasKeys(): boolean;
343
+ /**
344
+ * Export Trust Gate public keys (for sending to client)
345
+ * @returns Object with publicKeyEncrypt and publicKeySign as Buffers
346
+ */
347
+ exportKeys(): {
348
+ publicKeyEncrypt: Buffer;
349
+ publicKeySign: Buffer;
350
+ };
351
+ }
352
+
353
+ /**
354
+ * ML-DSA-87 signature verification utilities
355
+ */
356
+
357
+ /**
358
+ * Initialize user crypto instance from SNFT token
359
+ * Parses ML-DSA-87 and ML-KEM-1024 public keys from base64-encoded token
360
+ *
361
+ * @param userToken - SNFT token with publicKeySign and publicKeyEncrypt (base64)
362
+ * @param logger - Optional logger instance
363
+ * @returns Crypto instance for signature verification
364
+ */
365
+ declare function initUserCrypto(userToken: UserToken, logger?: ILogger): CryptoInstance;
366
+ /**
367
+ * Verify ML-DSA-87 signature of data
368
+ *
369
+ * @param crypto - Crypto instance from initUserCrypto
370
+ * @param data - Data that was signed
371
+ * @param signature - ML-DSA-87 signature (~4595 bytes)
372
+ * @param logger - Optional logger instance
373
+ * @returns true if signature is valid
374
+ * @throws Error if verification fails
375
+ */
376
+ declare function checkSignature(crypto: CryptoInstance, data: Buffer | Uint8Array | ArrayBuffer | string, signature: Buffer | Uint8Array | ArrayBuffer | string, logger?: ILogger): boolean;
377
+
378
+ /**
379
+ * Token Provider - Fetches user SNFT tokens from blockchain and IPFS
380
+ */
381
+
382
+ /**
383
+ * Extract IPFS hash from tokenURI
384
+ * Handles multiple formats:
385
+ * - ipfs://QmHash...
386
+ * - https://gateway.pinata.cloud/ipfs/QmHash...
387
+ * - https://secure.liberion.com/QmHash...
388
+ * - QmHash... (raw hash)
389
+ */
390
+ declare function extractIpfsHash(tokenURI: string): string;
391
+ /**
392
+ * Get SNFT token from IPFS by user address
393
+ *
394
+ * @param address - User blockchain address
395
+ * @param logger - Optional logger instance
396
+ * @param networkConfig - Optional network configuration (defaults to production)
397
+ * @returns SNFT token object from IPFS
398
+ */
399
+ declare function getTokenFromIPFS(address: string, logger?: ILogger, networkConfig?: NetworkConfig): Promise<UserToken>;
400
+ /**
401
+ * Clear the token cache (for testing or manual invalidation)
402
+ */
403
+ declare function clearTokenCache(): void;
404
+
405
+ declare const COMMAND_READY = "ready";
406
+ declare const COMMAND_AUTH = "auth";
407
+ declare const COMMAND_AUTH_RESULT = "auth_result";
408
+ declare const COMMAND_ACTIVATED = "activated";
409
+ declare const COMMAND_AUTH_DECLINED = "declined";
410
+ declare const COMMAND_AUTH_TIMEOUT = "timeout";
411
+ declare const COMMAND_ERROR = "error";
412
+ declare const DEFAULT_PORT = 31313;
413
+ declare const STATUS: {
414
+ readonly OK: "ok";
415
+ readonly FAILED: "error";
416
+ };
417
+ declare const DECLINE_REASON: {
418
+ readonly USER: "user_declined";
419
+ readonly TIMEOUT: "timeout";
420
+ readonly ERROR: "error";
421
+ readonly UNKNOWN: "unknown";
422
+ };
423
+
424
+ export { type AuthPayload, type AuthResult, COMMAND_ACTIVATED, COMMAND_AUTH, COMMAND_AUTH_DECLINED, COMMAND_AUTH_RESULT, COMMAND_AUTH_TIMEOUT, COMMAND_ERROR, COMMAND_READY, ConsoleLogger, type CryptoInstance, DECLINE_REASON, DEFAULT_PORT, type DeclineInfo, type DeclineReason, type Environment, type ILogger, LiberionAuth, type LiberionAuthConfig, type NetworkConfig, NoOpLogger, PQCrypto, type SSLCredentials, STATUS, type Session, USER_CONTRACT_ABI, type UserToken, checkSignature, clearTokenCache, createWinstonAdapter, decryptBuffer, encryptBuffer, extractIpfsHash, getNetworkConfig, getTokenFromIPFS, initUserCrypto, shortenAddress };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { SecureContextOptions } from 'tls';
2
+
1
3
  /**
2
4
  * Blockchain configuration constants
3
5
  * Supports production and development environments
@@ -60,12 +62,11 @@ interface UserToken {
60
62
  [key: string]: unknown;
61
63
  }
62
64
  /**
63
- * SSL credentials for HTTPS server
65
+ * SSL/TLS credentials for HTTPS server
66
+ * Accepts all options from Node.js tls.SecureContextOptions
67
+ * @see https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions
64
68
  */
65
- interface SSLCredentials {
66
- key: string;
67
- cert: string;
68
- }
69
+ type SSLCredentials = SecureContextOptions;
69
70
  /**
70
71
  * Decline reason categories
71
72
  */
package/dist/index.js CHANGED
@@ -1152,6 +1152,7 @@ var PQCrypto = class {
1152
1152
  sharedSecretSize: sharedSecret.length
1153
1153
  // 32 bytes
1154
1154
  });
1155
+ const sharedSecretBuffer = Uint8Array.from(sharedSecret);
1155
1156
  const secretKeyRaw = await subtle.deriveBits(
1156
1157
  {
1157
1158
  name: "HKDF",
@@ -1159,12 +1160,13 @@ var PQCrypto = class {
1159
1160
  salt: PROTOCOL_AAD,
1160
1161
  info: PROTOCOL_AAD
1161
1162
  },
1162
- await subtle.importKey("raw", sharedSecret, { name: "HKDF" }, false, [
1163
+ await subtle.importKey("raw", sharedSecretBuffer, { name: "HKDF" }, false, [
1163
1164
  "deriveBits"
1164
1165
  ]),
1165
1166
  256
1166
1167
  );
1167
1168
  sharedSecret.fill(0);
1169
+ sharedSecretBuffer.fill(0);
1168
1170
  const versionBuf = new Uint8Array([1]);
1169
1171
  const header = new Uint8Array(4);
1170
1172
  new DataView(header.buffer).setUint32(0, kemCiphertext.length, false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trust-proto/auth-node",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Liberion Auth Backend SDK with post-quantum cryptography",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,7 +8,8 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
12
13
  }
13
14
  },
14
15
  "files": [
@@ -41,7 +42,7 @@
41
42
  },
42
43
  "dependencies": {
43
44
  "@msgpack/msgpack": "^3.1.2",
44
- "@noble/post-quantum": "^0.5.2",
45
+ "@noble/post-quantum": "^0.5.4",
45
46
  "ethers": "^6.16.0",
46
47
  "libsodium-wrappers": "^0.7.15",
47
48
  "uuid": "^13.0.0",
@@ -49,19 +50,19 @@
49
50
  },
50
51
  "devDependencies": {
51
52
  "@types/libsodium-wrappers": "^0.7.14",
52
- "@types/node": "^24.10.1",
53
+ "@types/node": "^25.0.3",
53
54
  "@types/ws": "^8.5.0",
54
- "@vitest/coverage-v8": "^4.0.15",
55
+ "@vitest/coverage-v8": "^4.0.16",
55
56
  "tsup": "^8.0.0",
56
57
  "typescript": "^5.7.0",
57
- "vitest": "^4.0.15"
58
+ "vitest": "^4.0.16"
58
59
  },
59
60
  "publishConfig": {
60
61
  "access": "public"
61
62
  },
62
63
  "scripts": {
63
- "build": "tsup src/index.ts --format esm --dts --clean",
64
- "dev": "tsup src/index.ts --format esm --dts --watch",
64
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
65
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
65
66
  "test": "vitest --run",
66
67
  "test:watch": "vitest",
67
68
  "test:coverage": "vitest --run --coverage",