@trust-proto/auth-node 0.2.1 → 0.2.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.
package/README.md CHANGED
@@ -1,7 +1,14 @@
1
1
  # @trust-proto/auth-node
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@trust-proto/auth-node.svg)](https://www.npmjs.com/package/@trust-proto/auth-node)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
3
6
  Backend SDK for Liberion decentralized authentication system. This package provides a WebSocket server that handles browser-wallet authentication flow.
4
7
 
8
+ ## Requirements
9
+
10
+ - Node.js >= 20.0.0
11
+
5
12
  ## Installation
6
13
 
7
14
  ```bash
@@ -18,37 +25,146 @@ const auth = new LiberionAuth({
18
25
  secretCode: 'your-secret-code',
19
26
  port: 31313, // optional, default: 31313
20
27
 
21
- // Check if user exists in your database
28
+ // Check if user is already registered in your database
29
+ // Return true if user exists - wallet will skip permission request
30
+ // Return false if user is new - wallet will show permission request
22
31
  onHello: async (address) => {
23
32
  return await userExists(address);
24
33
  },
25
34
 
26
35
  // Generate JWT token after successful authentication
27
36
  onSuccess: async ({ address, fields }) => {
37
+ // Save user data to your database
38
+ await db.users.upsert({
39
+ address,
40
+ nickname: fields?.nickname,
41
+ email: fields?.email,
42
+ // ... other KYC fields
43
+ });
44
+
28
45
  const token = generateJWT(address);
29
46
  return { token };
30
47
  },
31
48
 
32
49
  // Handle declined authorization (optional)
33
- onDecline: async ({ address, reason, message }) => {
34
- console.log(`Auth declined: ${reason}`);
50
+ onDecline: async ({ address, reason, message, declinedBy, sessionId }) => {
51
+ console.log(`Auth declined by ${declinedBy}: ${reason}`);
35
52
  },
36
53
  });
37
54
  ```
38
55
 
39
56
  ## Configuration
40
57
 
41
- | Option | Type | Required | Default | Description |
42
- |--------|------|----------|---------|-------------|
43
- | `projectId` | `string` | Yes | - | Project UUID from Liberion dashboard |
44
- | `secretCode` | `string` | Yes | - | Secret code for encryption |
45
- | `port` | `number` | No | `31313` | WebSocket server port |
46
- | `ssl` | `{ key: string; cert: string }` | No | - | SSL credentials for HTTPS |
47
- | `debug` | `boolean` | No | `false` | Enable debug logging |
48
- | `logger` | `ILogger` | No | `NoOpLogger` | Custom logger instance |
49
- | `onHello` | `(address: string) => Promise<boolean>` | No | - | Called when wallet activates |
50
- | `onSuccess` | `(payload: AuthPayload) => Promise<AuthResult>` | No | - | Called on successful auth |
51
- | `onDecline` | `(info: DeclineInfo) => Promise<void>` | No | - | Called when auth is declined |
58
+ | Option | Type | Required | Default | Description |
59
+ | ------------ | ----------------------------------------------- | -------- | ------------ | ------------------------------------ |
60
+ | `projectId` | `string` | | - | Project UUID from Liberion dashboard |
61
+ | `secretCode` | `string` | | - | Secret code for encryption |
62
+ | `port` | `number` | | `31313` | WebSocket server port |
63
+ | `ssl` | `SSLCredentials` | | - | SSL/TLS options for HTTPS server |
64
+ | `debug` | `boolean` | | `false` | Enable debug logging |
65
+ | `logger` | `ILogger` | | `NoOpLogger` | Custom logger instance |
66
+ | `onHello` | `(address: string) => Promise<boolean>` | | - | Check if user is registered |
67
+ | `onSuccess` | `(payload: AuthPayload) => Promise<AuthResult>` | | - | Called on successful auth |
68
+ | `onDecline` | `(info: DeclineInfo) => Promise<void>` | | - | Called when auth is declined |
69
+
70
+ ## Callbacks
71
+
72
+ ### onHello
73
+
74
+ Called when the wallet activates and sends the user's address. This callback should check if the user is already registered in your database.
75
+
76
+ **Return value (`isRegistered`):**
77
+
78
+ - Return `true` if user exists - wallet will **skip** the permission request screen
79
+ - Return `false` if user is new - wallet will **show** the permission request screen
80
+
81
+ This allows returning users to have a smoother authentication experience without repeatedly granting permissions.
82
+
83
+ ```typescript
84
+ onHello: async (address) => {
85
+ const user = await db.users.findOne({ address });
86
+ return !!user; // true if registered, false if new user
87
+ }
88
+ ```
89
+
90
+ ### onSuccess
91
+
92
+ Called after successful authentication and signature verification. Use this callback to save user data and generate a JWT token.
93
+
94
+ **Parameters:**
95
+
96
+ - `address` - User's blockchain address
97
+ - `fields` - KYC data object (nickname, email, name, sex, dateOfBirth, etc.)
98
+
99
+ **Return value:**
100
+
101
+ - `{ token: string }` - JWT token for successful auth
102
+ - `{ error: string }` - (Optional) Error message if auth should fail
103
+
104
+ ```typescript
105
+ onSuccess: async ({ address, fields }) => {
106
+ // Save user data to your database
107
+ await db.users.upsert({
108
+ address,
109
+ nickname: fields?.nickname,
110
+ email: fields?.email,
111
+ name: fields?.name,
112
+ sex: fields?.sex,
113
+ dateOfBirth: fields?.dateOfBirth,
114
+ documentCountry: fields?.documentCountry,
115
+ imageAvatar: fields?.imageAvatar,
116
+ // ... other KYC fields from the wallet
117
+ });
118
+
119
+ // Generate JWT token
120
+ const token = jwt.sign({ address }, SECRET_KEY);
121
+
122
+ return { token };
123
+ }
124
+ ```
125
+
126
+ **Error handling:**
127
+
128
+ If you need to reject authentication based on your business logic, return an error:
129
+
130
+ ```typescript
131
+ onSuccess: async ({ address, fields }) => {
132
+ // Example: Check if user meets requirements
133
+ if (!await meetsRequirements(address)) {
134
+ return { error: 'Account not eligible for this service' };
135
+ }
136
+
137
+ await db.users.upsert({ address, ...fields });
138
+ const token = jwt.sign({ address }, SECRET_KEY);
139
+ return { token };
140
+ }
141
+ ```
142
+
143
+ ### onDecline
144
+
145
+ Called when authentication is declined by the user or fails. Useful for logging or analytics.
146
+
147
+ **Parameters:**
148
+
149
+ - `address` - User's blockchain address (may be null if declined before activation)
150
+ - `reason` - Standardized decline reason: `'user_declined'`, `'timeout'`, `'error'`, `'unknown'`
151
+ - `message` - Detailed decline message
152
+ - `declinedBy` - Who declined: `'wallet'` or `'browser'`
153
+ - `sessionId` - Session ID for tracking
154
+
155
+ ```typescript
156
+ onDecline: async ({ address, reason, message, declinedBy, sessionId }) => {
157
+ // Log decline for analytics
158
+ await db.authLogs.create({
159
+ address,
160
+ reason, // 'user_declined', 'timeout', 'error', 'unknown'
161
+ message, // Detailed message
162
+ declinedBy, // 'wallet' or 'browser'
163
+ sessionId,
164
+ timestamp: new Date(),
165
+ });
166
+ }
167
+ ```
52
168
 
53
169
  ## Logger Integration
54
170
 
@@ -93,46 +209,37 @@ const customLogger: ILogger = {
93
209
 
94
210
  ## Authentication Flow
95
211
 
96
- 1. **Browser** connects to WebSocket server and sends `auth_init`
212
+ 1. **Browser** connects to WebSocket Server and sends `auth_init`
97
213
  2. **Server** creates authorization task via Trust Gate
98
214
  3. **Server** returns QR code link to browser
99
215
  4. **User** scans QR code with Liberion Wallet
100
- 5. **Wallet** sends activation request with encrypted session data
101
- 6. **Server** calls `onHello` callback, sends ACTIVATED to browser
102
- 7. **Wallet** sends signed auth data with KYC fields
103
- 8. **Server** verifies ML-DSA-87 signature, calls `onSuccess`
104
- 9. **Server** sends JWT token to browser, closes connections
216
+ 5. **Wallet** sends activation request with signed session data to Trust Gate server
217
+ 6. **Trust Gate server** gets public keys from Blockchain User's S-NFT & checks signatures
218
+ 7. **Trust Gate server** calls `onHello` callback to Server
219
+ 8. **Server** calls `onHello` callback into its runtime
220
+ 9. **Server** sends ACTIVATED to browser
221
+ 10. **Server** sends `onHello` response to Trust Gate server
222
+ 11. **Trust Gate server** checks the project settings and required fields
223
+ 12. **Trust Gate server** sends payload back to Liberion Wallet
224
+ 13. **Liberion Wallet** sends signed auth data with KYC fields (Merkle Tree or ZK-proofs) to Server
225
+ 14. **Server** verifies ML-DSA-87 signature, checks data validity of proofs with Blockchain and calls `onSuccess` or `onDecline` callbacks respectively
226
+ 15. **Server** sends auth data to Browser, closes all session's connections
227
+ 16. **Browser** authorizes using auth data
105
228
 
106
229
  ## Security Features
107
230
 
108
- - **Post-Quantum Cryptography**: ML-KEM-1024 + ML-DSA-87 (FIPS 203/204)
109
- - **AES-256-CBC**: Session encryption with project secret
110
- - **Signature Verification**: All auth data is cryptographically signed
231
+ - **Post-Quantum Cryptography**: ML-KEM-1024 + XChaCha20-Poly1305 + ML-DSA-87 (FIPS 203/204)
232
+ - Used by Trust Gate for encrypting data sent to Wallet
233
+ - ML-KEM-1024: Key encapsulation mechanism
234
+ - XChaCha20-Poly1305: Authenticated encryption
235
+ - ML-DSA-87: Digital signatures
236
+ - **Layered Encryption**:
237
+ - **Server ↔ Trust Gate/Wallet**: AES-256-CBC with project `secretCode`
238
+ - **Trust Gate → Wallet**: Critical data additionally encrypted with ML-KEM-1024 + XChaCha20-Poly1305
239
+ - **Signature Verification**: All auth data is cryptographically signed and verified
111
240
  - **Session Timeout**: 10-minute authorization window
112
241
  - **WebSocket Ping/Pong**: Keep-alive with 30-second interval
113
242
 
114
- ## Types
115
-
116
- ```typescript
117
- interface AuthPayload {
118
- address: string;
119
- fields: Record<string, unknown>;
120
- }
121
-
122
- interface AuthResult {
123
- token?: string;
124
- error?: string;
125
- }
126
-
127
- interface DeclineInfo {
128
- address: string | null;
129
- reason: 'user_declined' | 'timeout' | 'error' | 'unknown';
130
- message: string;
131
- declinedBy: 'wallet' | 'browser';
132
- sessionId: string;
133
- }
134
- ```
135
-
136
243
  ## License
137
244
 
138
245
  MIT
package/dist/index.d.cts 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.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trust-proto/auth-node",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Liberion Auth Backend SDK with post-quantum cryptography",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@msgpack/msgpack": "^3.1.2",
45
- "@noble/post-quantum": "^0.5.3",
45
+ "@noble/post-quantum": "^0.5.4",
46
46
  "ethers": "^6.16.0",
47
47
  "libsodium-wrappers": "^0.7.15",
48
48
  "uuid": "^13.0.0",