-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
360 lines (307 loc) · 10.7 KB
/
app.js
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import express from 'express';
import { Authsignal } from "@authsignal/node";
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const app = express();
app.use(express.json());
app.use(express.static('public'));
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Initialize Authsignal
const authsignal = new Authsignal({
secret: "oS1gcJlBJMQ4oZ7kzD2vUwChSrlPc15+BHJgZnkDa102IFW4CrvPlQ==",
apiBaseUrl: "https://eu.api.authsignal.com/v1",
tenant: "4dc4249b-a3cd-467d-992c-d26646f78c7d",
});
// Add storage for pending payments
const pendingPayments = new Map();
// Endpoint to initiate payment with MFA
app.post('/api/payment/authorize', async (req, res) => {
const { userId, amount, currency, beneficiaryId, beneficiaryName } = req.body;
console.log('\n=== PAYMENT AUTHORIZATION REQUEST ===');
console.log('Payment Details:', {
userId,
amount,
currency,
beneficiaryId,
beneficiaryName
});
try {
const result = await authsignal.track({
userId: userId,
action: "payment_authorization",
redirectUrl: "https://mfa-dynamic-linking-demonstration.onrender.com/payment-validation.html",
custom: {
amount: amount,
currency: currency,
beneficiaryId: beneficiaryId,
beneficiaryName: beneficiaryName,
timestamp: new Date().toISOString()
},
ipAddress: req.ip,
userAgent: req.headers['user-agent'],
forceChallenge: true
});
console.log('\n=== AUTHSIGNAL TRACK RESPONSE ===');
console.log('State:', result.state);
console.log('Challenge URL:', result.url);
console.log('TOTP Challenge Token:', result.token);
if (result.state === "CHALLENGE_REQUIRED") {
// Parse the token to get the idempotencyKey
const tokenPayload = JSON.parse(Buffer.from(result.token.split('.')[1], 'base64').toString());
const idempotencyKey = tokenPayload.other?.idempotencyKey;
console.log('IdempotencyKey:', idempotencyKey);
const paymentData = {
amount: amount,
currency: currency,
beneficiaryId: beneficiaryId,
beneficiaryName: beneficiaryName,
timestamp: new Date()
};
pendingPayments.set(idempotencyKey, paymentData);
console.log('\n=== PAYMENT DETAILS STORED ===');
console.log('IdempotencyKey:', idempotencyKey);
console.log('Stored Payment Data:', paymentData);
res.json({
requiresChallenge: true,
challengeUrl: result.url,
token: result.token
});
} else if (result.state === "ALLOW") {
console.log('\n=== PAYMENT APPROVED WITHOUT CHALLENGE ===');
res.json({
requiresChallenge: false,
status: 'approved'
});
} else {
console.log('\n=== PAYMENT BLOCKED ===');
console.log('State:', result.state);
res.status(403).json({
error: 'Payment authorization blocked'
});
}
} catch (error) {
console.error('\n=== AUTHORIZATION ERROR ===');
console.error('Error:', error);
res.status(500).json({ error: error.message });
}
});
// Callback endpoint after MFA completion
app.post('/api/payment/validate', async (req, res) => {
const { token } = req.body;
try {
const result = await authsignal.validateChallenge({ token });
console.log('\n=== PAYMENT COMPLETION REQUEST ===');
console.log('TOTP Validation Token:', token);
if (result.state === "CHALLENGE_SUCCEEDED") {
const tokenPayload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const userId = tokenPayload.sub;
const idempotencyKey = tokenPayload.other?.idempotencyKey;
console.log('\n=== ACTION DETAILS REQUEST ===');
console.log('UserId:', userId);
console.log('IdempotencyKey:', idempotencyKey);
const actionDetails = await authsignal.getAction({
userId: userId,
action: "payment_authorization",
idempotencyKey: idempotencyKey
});
console.log('\n=== ACTION DETAILS RESPONSE ===');
console.log('Action Details:', actionDetails);
// Get payment details from our stored map
const paymentDetails = pendingPayments.get(idempotencyKey);
if (!paymentDetails) {
throw new Error('Payment details not found');
}
console.log('\n=== PAYMENT AUTHORIZATION TOKEN ===');
console.log('Payment Details:', paymentDetails);
console.log('Authorization Token:', actionDetails);
res.json({
success: true,
verificationMethod: result.verificationMethod,
state: actionDetails.state,
paymentDetails: paymentDetails,
actionDetails: actionDetails
});
} else {
res.json({
success: false,
error: 'Challenge failed'
});
}
} catch (error) {
console.error('\n=== VALIDATION ERROR ===');
console.error('Error:', error);
res.json({
success: false,
error: error.message
});
}
});
// Simplified completion endpoint
app.get('/payment/complete', async (req, res) => {
const token = req.query.token;
try {
console.log('\n=== PAYMENT COMPLETION REQUEST ===');
const result = await authsignal.validateChallenge({ token });
// Log the token for debugging (ensure this is ONLY in a test environment)
console.log('AuthSignal ValidateChallenge Token:', token);
if (result.state === "CHALLENGE_SUCCEEDED") {
const tokenPayload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const userId = tokenPayload.sub;
const idempotencyKey = tokenPayload.other?.idempotencyKey;
console.log('\n=== ACTION DETAILS REQUEST ===');
console.log('UserId:', userId);
console.log('IdempotencyKey:', idempotencyKey);
const actionDetails = await authsignal.getAction({
userId: userId,
action: "payment_authorization",
idempotencyKey: idempotencyKey
});
console.log('\n=== ACTION DETAILS RESPONSE ===');
console.log('Action Details:', actionDetails);
// Get payment details from our stored map
const paymentDetails = pendingPayments.get(idempotencyKey);
if (!paymentDetails) {
throw new Error('Payment details not found');
}
res.json({
success: true,
verificationMethod: result.verificationMethod,
state: actionDetails.state,
paymentDetails: paymentDetails,
actionDetails: actionDetails
});
} else {
res.json({
success: false,
error: 'Challenge failed'
});
}
} catch (error) {
console.error('\n=== VALIDATION ERROR ===');
console.error('Error:', error);
res.json({
success: false,
error: error.message
});
}
});
// New endpoint to initiate enrollment
app.post('/api/enroll', async (req, res) => {
const { userId, email } = req.body;
console.log('\n=== ENROLLMENT REQUEST ===');
console.log('User Details:', { userId, email });
try {
const result = await authsignal.track({
userId: userId,
email: email,
action: "enroll",
redirectUrl: "https://mfa-dynamic-linking-demonstration.onrender.com/enrollment/complete",
verificationMethods: ["authenticator_app", "passkey"], // You can customize these methods
ipAddress: req.ip,
userAgent: req.headers['user-agent'],
forceChallenge: true
});
console.log('\n=== ENROLLMENT TRACK RESPONSE ===');
console.log('State:', result.state);
console.log('Challenge URL:', result.url);
res.json({
enrollmentUrl: result.url
});
} catch (error) {
console.error('\n=== ENROLLMENT ERROR ===');
console.error('Error:', error);
res.status(500).json({ error: error.message });
}
});
// Enrollment completion endpoint
app.get('/enrollment/complete', (req, res) => {
res.sendFile(path.join(__dirname, 'public/enrollment-complete.html'));
});
// Add validation endpoint for enrollment
app.post('/api/enrollment/validate', async (req, res) => {
const { token } = req.body;
try {
const result = await authsignal.validateChallenge({ token });
console.log('Validation Result:', result);
if (result.state === "CHALLENGE_SUCCEEDED") {
const tokenPayload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
res.json({
success: true,
userId: tokenPayload.sub,
email: result.email || tokenPayload.sub
});
} else {
res.json({
success: false,
error: 'Challenge failed'
});
}
} catch (error) {
console.error('Validation Error:', error);
res.json({
success: false,
error: error.message
});
}
});
// New endpoint to handle sign in
app.post('/api/signin', async (req, res) => {
const { email } = req.body;
console.log('\n=== SIGNIN REQUEST ===');
console.log('User Details:', { email });
try {
const result = await authsignal.track({
userId: email, // Using email as userId for signin
email: email,
action: "signin",
redirectUrl: "https://mfa-dynamic-linking-demonstration.onrender.com/signin/complete",
ipAddress: req.ip,
userAgent: req.headers['user-agent'],
forceChallenge: true
});
console.log('\n=== SIGNIN TRACK RESPONSE ===');
console.log('State:', result.state);
console.log('Challenge URL:', result.url);
res.json({
challengeUrl: result.url
});
} catch (error) {
console.error('\n=== SIGNIN ERROR ===');
console.error('Error:', error);
res.status(500).json({ error: error.message });
}
});
// Signin completion endpoint
app.get('/signin/complete', (req, res) => {
res.sendFile(path.join(__dirname, 'public/signin-complete.html'));
});
// Add validation endpoint for signin
app.post('/api/signin/validate', async (req, res) => {
const { token } = req.body;
try {
const result = await authsignal.validateChallenge({ token });
if (result.state === "CHALLENGE_SUCCEEDED") {
const tokenPayload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
res.json({
success: true,
userId: tokenPayload.sub,
email: result.email || tokenPayload.sub
});
} else {
res.json({
success: false,
error: 'Authentication failed'
});
}
} catch (error) {
res.json({
success: false,
error: error.message
});
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});