@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.
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,147 @@ 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
+ | `environment` | `'production' \| 'development'` | | `'production'` | Target environment |
66
+ | `logger` | `ILogger` | | `NoOpLogger` | Custom logger instance |
67
+ | `onHello` | `(address: string) => Promise<boolean>` | | - | Check if user is registered |
68
+ | `onSuccess` | `(payload: AuthPayload) => Promise<AuthResult>` | | - | Called on successful auth |
69
+ | `onDecline` | `(info: DeclineInfo) => Promise<void>` | ❌ | - | Called when auth is declined |
70
+
71
+ ## Callbacks
72
+
73
+ ### onHello
74
+
75
+ Called when the wallet activates and sends the user's address. This callback should check if the user is already registered in your database.
76
+
77
+ **Return value (`isRegistered`):**
78
+
79
+ - Return `true` if user exists - wallet will **skip** the permission request screen
80
+ - Return `false` if user is new - wallet will **show** the permission request screen
81
+
82
+ This allows returning users to have a smoother authentication experience without repeatedly granting permissions.
83
+
84
+ ```typescript
85
+ onHello: async (address) => {
86
+ const user = await db.users.findOne({ address });
87
+ return !!user; // true if registered, false if new user
88
+ }
89
+ ```
90
+
91
+ ### onSuccess
92
+
93
+ Called after successful authentication and signature verification. Use this callback to save user data and generate a JWT token.
94
+
95
+ **Parameters:**
96
+
97
+ - `address` - User's blockchain address
98
+ - `fields` - KYC data object (nickname, email, name, sex, dateOfBirth, etc.)
99
+
100
+ **Return value:**
101
+
102
+ - `{ token: string }` - JWT token for successful auth
103
+ - `{ error: string }` - (Optional) Error message if auth should fail
104
+
105
+ ```typescript
106
+ onSuccess: async ({ address, fields }) => {
107
+ // Save user data to your database
108
+ await db.users.upsert({
109
+ address,
110
+ nickname: fields?.nickname,
111
+ email: fields?.email,
112
+ name: fields?.name,
113
+ sex: fields?.sex,
114
+ dateOfBirth: fields?.dateOfBirth,
115
+ documentCountry: fields?.documentCountry,
116
+ imageAvatar: fields?.imageAvatar,
117
+ // ... other KYC fields from the wallet
118
+ });
119
+
120
+ // Generate JWT token
121
+ const token = jwt.sign({ address }, SECRET_KEY);
122
+
123
+ return { token };
124
+ }
125
+ ```
126
+
127
+ **Error handling:**
128
+
129
+ If you need to reject authentication based on your business logic, return an error:
130
+
131
+ ```typescript
132
+ onSuccess: async ({ address, fields }) => {
133
+ // Example: Check if user meets requirements
134
+ if (!await meetsRequirements(address)) {
135
+ return { error: 'Account not eligible for this service' };
136
+ }
137
+
138
+ await db.users.upsert({ address, ...fields });
139
+ const token = jwt.sign({ address }, SECRET_KEY);
140
+ return { token };
141
+ }
142
+ ```
143
+
144
+ ### onDecline
145
+
146
+ Called when authentication is declined by the user or fails. Useful for logging or analytics.
147
+
148
+ **Parameters:**
149
+
150
+ - `address` - User's blockchain address (may be null if declined before activation)
151
+ - `reason` - Standardized decline reason: `'user_declined'`, `'timeout'`, `'error'`, `'unknown'`
152
+ - `message` - Detailed decline message
153
+ - `declinedBy` - Who declined: `'wallet'` or `'browser'`
154
+ - `sessionId` - Session ID for tracking
155
+
156
+ ```typescript
157
+ onDecline: async ({ address, reason, message, declinedBy, sessionId }) => {
158
+ // Log decline for analytics
159
+ await db.authLogs.create({
160
+ address,
161
+ reason, // 'user_declined', 'timeout', 'error', 'unknown'
162
+ message, // Detailed message
163
+ declinedBy, // 'wallet' or 'browser'
164
+ sessionId,
165
+ timestamp: new Date(),
166
+ });
167
+ }
168
+ ```
52
169
 
53
170
  ## Logger Integration
54
171
 
@@ -93,46 +210,37 @@ const customLogger: ILogger = {
93
210
 
94
211
  ## Authentication Flow
95
212
 
96
- 1. **Browser** connects to WebSocket server and sends `auth_init`
213
+ 1. **Browser** connects to WebSocket Server and sends `auth_init`
97
214
  2. **Server** creates authorization task via Trust Gate
98
215
  3. **Server** returns QR code link to browser
99
216
  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
217
+ 5. **Wallet** sends activation request with signed session data to Trust Gate server
218
+ 6. **Trust Gate server** gets public keys from Blockchain User's S-NFT & checks signatures
219
+ 7. **Trust Gate server** calls `onHello` callback to Server
220
+ 8. **Server** calls `onHello` callback into its runtime
221
+ 9. **Server** sends ACTIVATED to browser
222
+ 10. **Server** sends `onHello` response to Trust Gate server
223
+ 11. **Trust Gate server** checks the project settings and required fields
224
+ 12. **Trust Gate server** sends payload back to Liberion Wallet
225
+ 13. **Liberion Wallet** sends signed auth data with KYC fields (Merkle Tree or ZK-proofs) to Server
226
+ 14. **Server** verifies ML-DSA-87 signature, checks data validity of proofs with Blockchain and calls `onSuccess` or `onDecline` callbacks respectively
227
+ 15. **Server** sends auth data to Browser, closes all session's connections
228
+ 16. **Browser** authorizes using auth data
105
229
 
106
230
  ## Security Features
107
231
 
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
232
+ - **Post-Quantum Cryptography**: ML-KEM-1024 + XChaCha20-Poly1305 + ML-DSA-87 (FIPS 203/204)
233
+ - Used by Trust Gate for encrypting data sent to Wallet
234
+ - ML-KEM-1024: Key encapsulation mechanism
235
+ - XChaCha20-Poly1305: Authenticated encryption
236
+ - ML-DSA-87: Digital signatures
237
+ - **Layered Encryption**:
238
+ - **Server ↔ Trust Gate/Wallet**: AES-256-CBC with project `secretCode`
239
+ - **Trust Gate → Wallet**: Critical data additionally encrypted with ML-KEM-1024 + XChaCha20-Poly1305
240
+ - **Signature Verification**: All auth data is cryptographically signed and verified
111
241
  - **Session Timeout**: 10-minute authorization window
112
242
  - **WebSocket Ping/Pong**: Keep-alive with 30-second interval
113
243
 
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
244
  ## License
137
245
 
138
246
  MIT