-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-client.js
More file actions
259 lines (204 loc) Β· 8.39 KB
/
Copy pathtest-client.js
File metadata and controls
259 lines (204 loc) Β· 8.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**
* Test client for FISE Fastify backend
* Run this after starting the server to see FISE in action
*/
import { fiseDecrypt, fiseEncrypt, FiseBuilder } from 'fise';
// Must match backend rules!
const clientRules = FiseBuilder.defaults()
.withSaltRange(15, 50)
.build();
const BASE_URL = 'http://localhost:3008';
// Helper to get current timestamp
function getTimestamp() {
return Math.floor(Date.now() / 60000);
}
// ============================================================================
// Test Functions
// ============================================================================
async function testHealthCheck() {
console.log('\nπ‘ Testing Health Check...');
const response = await fetch(`${BASE_URL}/health`);
const data = await response.json();
console.log('β
Health:', data);
}
async function testProtectedUserData() {
console.log('\nπ€ Testing Protected User Data...');
const response = await fetch(`${BASE_URL}/api/user/123`);
const { data } = await response.json();
console.log('π Encrypted response:', data);
// Decrypt the response (using current timestamp)
const plaintext = fiseDecrypt(data, clientRules, {
timestamp: getTimestamp()
});
const userData = JSON.parse(plaintext);
console.log('π Decrypted user data:', userData);
}
async function testProductList() {
console.log('\nποΈ Testing Protected Product List...');
const response = await fetch(`${BASE_URL}/api/products`);
const { data } = await response.json();
console.log('π Encrypted response length:', data.length, 'chars');
const plaintext = fiseDecrypt(data, clientRules, {
timestamp: getTimestamp()
});
const products = JSON.parse(plaintext);
console.log('π Decrypted products:', products);
}
async function testGenerateKey() {
console.log('\nπ Testing API Key Generation...');
const response = await fetch(`${BASE_URL}/api/generate-key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: 'user_456' })
});
const { data } = await response.json();
console.log('π Encrypted key data:', data.substring(0, 50) + '...');
const plaintext = fiseDecrypt(data, clientRules, {
timestamp: getTimestamp()
});
const keyData = JSON.parse(plaintext);
console.log('π Decrypted API key:', keyData);
}
async function testSubmitForm() {
console.log('\nπ Testing Encrypted Form Submission...');
const formData = {
name: 'Jane Smith',
email: 'jane@example.com',
message: 'This form data is encrypted before sending!'
};
// Encrypt the form data before sending
const encrypted = fiseEncrypt(
JSON.stringify(formData),
clientRules,
{ timestamp: getTimestamp() }
);
console.log('π Sending encrypted form:', encrypted.substring(0, 50) + '...');
const response = await fetch(`${BASE_URL}/api/submit-form`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: encrypted })
});
const { data: encryptedResult } = await response.json();
// Decrypt the confirmation
const confirmationText = fiseDecrypt(encryptedResult, clientRules, {
timestamp: getTimestamp()
});
const confirmation = JSON.parse(confirmationText);
console.log('π Server confirmation:', confirmation);
}
async function testLogin() {
console.log('\nπ Testing Login...');
const response = await fetch(`${BASE_URL}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: 'demo',
password: 'demo123'
})
});
const { token } = await response.json();
if (token) {
console.log('β
Login successful!');
console.log('π Encrypted token:', token.substring(0, 50) + '...');
// Decrypt the token to see what's inside
const tokenText = fiseDecrypt(token, clientRules, {
timestamp: getTimestamp()
});
const tokenData = JSON.parse(tokenText);
console.log('π Token contents:', tokenData);
// Use the token to access protected resource
await testProtectedResource(token);
}
}
async function testProtectedResource(token) {
console.log('\nπ‘οΈ Testing Protected Resource with Token...');
const response = await fetch(`${BASE_URL}/api/limited-resource?token=${encodeURIComponent(token)}`);
const { data } = await response.json();
const plaintext = fiseDecrypt(data, clientRules, {
timestamp: getTimestamp()
});
const resource = JSON.parse(plaintext);
console.log('π Protected resource:', resource);
}
async function testAnalytics() {
console.log('\nπ Testing Analytics Data...');
const response = await fetch(`${BASE_URL}/api/analytics?page=1&limit=5`);
const { data } = await response.json();
console.log('π Encrypted analytics length:', data.length, 'chars');
const plaintext = fiseDecrypt(data, clientRules, {
timestamp: getTimestamp()
});
const analytics = JSON.parse(plaintext);
console.log('π Analytics:', {
page: analytics.page,
total: analytics.total,
dataPoints: analytics.data.length,
firstEntry: analytics.data[0]
});
}
async function compareProtection() {
console.log('\nπ Comparing Protected vs Unprotected...');
// Unprotected
const plainResponse = await fetch(`${BASE_URL}/api/demo/plaintext`);
const plainData = await plainResponse.json();
console.log('\nβ Unprotected endpoint:');
console.log(' Response:', JSON.stringify(plainData, null, 2));
console.log(' β οΈ Easily readable! API keys and internal IDs are visible!');
// Protected
const protectedResponse = await fetch(`${BASE_URL}/api/demo/protected`);
const { data } = await protectedResponse.json();
console.log('\nβ
FISE-protected endpoint:');
console.log(' Encrypted:', data.substring(0, 60) + '...');
console.log(' β Obscured! Harder to reverse engineer!');
// Decrypt to show it's the same data
const decrypted = fiseDecrypt(data, clientRules, {
timestamp: getTimestamp()
});
console.log(' Decrypted:', JSON.parse(decrypted));
}
// ============================================================================
// Run All Tests
// ============================================================================
async function runAllTests() {
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('π§ͺ FISE Fastify Backend Test Client');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
try {
await testHealthCheck();
await testProtectedUserData();
await testProductList();
await testGenerateKey();
await testSubmitForm();
await testLogin();
await testAnalytics();
await compareProtection();
console.log('\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β
All tests completed successfully!');
console.log('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
} catch (error) {
console.error('\nβ Test failed:', error.message);
console.error('Stack:', error.stack);
process.exit(1);
}
}
// Check if server is running
async function checkServer() {
try {
const response = await fetch(`${BASE_URL}/health`, { timeout: 2000 });
if (response.ok) {
return true;
}
} catch (error) {
return false;
}
return false;
}
// Main execution
const serverRunning = await checkServer();
if (!serverRunning) {
console.error('\nβ Server is not running!');
console.error('Please start the server first:');
console.error(' npm run dev\n');
process.exit(1);
}
await runAllTests();