-
Notifications
You must be signed in to change notification settings - Fork 12
Main #64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Main #64
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d8f7889
feat: implement enterprise KYC verification API with HMAC signing and…
rajshah1609 2c06f8a
Merge branch 'main' of https://github.com/rajshah1609/MasterNode-App
rajshah1609 6014f38
fixed lint and fb issue
rajshah1609 92ef781
feat: initialize project with core app structure, blockchain models, …
rajshah1609 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| 'use strict' | ||
| const express = require('express') | ||
| const router = express.Router() | ||
| const crypto = require('crypto') | ||
| const config = require('config') | ||
| const db = require('../models/mongodb') | ||
| const axios = require('axios') | ||
| const FormData = require('form-data') | ||
|
|
||
| const IPFS_API_ADD_URL = 'https://ipfs.xinfin.network/api/v0/add' | ||
|
|
||
| function addFileToXinfinIpfs (buffer, filename, callback) { | ||
| const form = new FormData() | ||
| form.append('file', buffer, { | ||
| filename: filename || 'kyc.pdf', | ||
| contentType: 'application/pdf', | ||
| knownLength: buffer.length | ||
| }) | ||
|
|
||
| axios.post(IPFS_API_ADD_URL, form, { | ||
| headers: form.getHeaders(), | ||
| maxBodyLength: Infinity, | ||
| maxContentLength: Infinity, | ||
| timeout: 10000 | ||
| }).then((response) => { | ||
| const hash = response.data && response.data.Hash | ||
| if (!hash) { | ||
| return callback(new Error('IPFS API did not return a hash')) | ||
| } | ||
| callback(null, [{ hash: hash }]) | ||
| }).catch(callback) | ||
| } | ||
|
|
||
| function unauthorized (res, reason) { | ||
| return res.status(401).json({ | ||
| message: 'Unauthorized', | ||
| reason: reason | ||
| }) | ||
| } | ||
|
|
||
| // Manually create API key and secret for an enterprise | ||
| router.post('/keys', async (req, res) => { | ||
| try { | ||
| const authHeader = req.headers['authorization'] | ||
| const expectedToken = config.get('enterpriseMasterToken') | ||
|
|
||
| if (!authHeader || authHeader !== `Bearer ${expectedToken}`) { | ||
| return unauthorized(res, 'invalid_master_token') | ||
| } | ||
|
|
||
| const enterpriseName = req.body.enterpriseName | ||
| if (!enterpriseName) { | ||
| return res.status(400).json({ message: 'enterpriseName is required' }) | ||
| } | ||
|
|
||
| const apiKey = crypto.randomBytes(16).toString('hex') | ||
| const apiSecret = crypto.randomBytes(32).toString('hex') | ||
|
|
||
| await db.EnterpriseKey.create({ | ||
| apiKey, | ||
| apiSecret, | ||
| enterpriseName | ||
| }) | ||
|
|
||
| res.status(201).json({ | ||
| message: 'Enterprise API credentials generated successfully. Save the apiSecret as it will not be shown again.', | ||
| enterpriseName, | ||
| apiKey, | ||
| apiSecret | ||
| }) | ||
| } catch (err) { | ||
| console.error('Error creating enterprise keys:', err) | ||
| res.status(500).send('Internal Server Error') | ||
| } | ||
| }) | ||
|
|
||
| // Enterprise addKYC endpoint | ||
| router.post('/addKYC', async (req, res) => { | ||
| try { | ||
| const apiKey = req.headers['x-api-key'] | ||
| const apiTimestamp = req.headers['x-api-timestamp'] | ||
| const apiSignature = req.headers['x-api-signature'] | ||
| const apiNonce = req.headers['x-api-nonce'] | ||
|
|
||
| if (!apiKey || !apiTimestamp || !apiSignature || !apiNonce) { | ||
| return unauthorized(res, 'missing_auth_headers') | ||
| } | ||
|
|
||
| // Validate timestamp (5 minutes window) | ||
| const requestTime = parseInt(apiTimestamp, 10) | ||
| const currentTime = Date.now() | ||
| const fiveMinutes = 5 * 60 * 1000 | ||
|
|
||
| if (isNaN(requestTime) || Math.abs(currentTime - requestTime) > fiveMinutes) { | ||
| return unauthorized(res, 'timestamp_expired') | ||
| } | ||
|
|
||
| // Check if nonce has already been used to prevent replay | ||
| const nonceExists = await db.EnterpriseNonce.findOne({ apiKey, nonce: apiNonce }) | ||
| if (nonceExists) { | ||
| return unauthorized(res, 'nonce_reused') | ||
| } | ||
|
|
||
| // Validate file presence | ||
| if (!req.files || !req.files.filename) { | ||
| return res.status(400).json({ message: 'No file uploaded' }) | ||
| } | ||
|
|
||
| const uploadedFile = req.files.filename | ||
|
|
||
| // Strict PDF checks: mimetype AND filename AND magic bytes | ||
| const isPdfMagic = uploadedFile.data && uploadedFile.data.length >= 5 && | ||
| uploadedFile.data.toString('ascii', 0, 5) === '%PDF-' | ||
|
|
||
| if (uploadedFile.mimetype !== 'application/pdf' || !uploadedFile.name.toLowerCase().endsWith('.pdf') || !isPdfMagic) { | ||
| return res.status(400).json({ message: 'Only PDF files are allowed' }) | ||
| } | ||
|
|
||
| // 10MB validation | ||
| const maxSize = 10 * 1024 * 1024 | ||
| if (uploadedFile.size > maxSize) { | ||
| return res.status(400).json({ message: 'File size should not exceed 10MB' }) | ||
| } | ||
|
|
||
| // Fetch enterprise key and select select: false fields (apiSecret) | ||
| const enterprise = await db.EnterpriseKey.findOne({ apiKey }).select('+apiSecret') | ||
| if (!enterprise) { | ||
| return unauthorized(res, 'invalid_api_key') | ||
| } | ||
|
|
||
| // Hash of file content | ||
| const fileHash = crypto.createHash('sha256').update(uploadedFile.data).digest('hex') | ||
|
|
||
| // Validate signature | ||
| // We expect signature to be HMAC SHA256 of "METHOD:PATH:TIMESTAMP:NONCE:FILENAME:FILESIZE:FILEHASH" | ||
| const method = req.method.toUpperCase() | ||
| const path = req.originalUrl.split('?')[0] // Strip query params just in case | ||
| const stringToSign = `${method}:${path}:${apiTimestamp}:${apiNonce}:${uploadedFile.name}:${uploadedFile.size}:${fileHash}` | ||
|
|
||
| const expectedSignature = crypto | ||
| .createHmac('sha256', enterprise.apiSecret) | ||
| .update(stringToSign) | ||
| .digest('hex') | ||
|
|
||
| if (typeof apiSignature !== 'string') { | ||
| return unauthorized(res, 'invalid_signature') | ||
| } | ||
|
|
||
| const sigBuf = Buffer.from(apiSignature, 'hex') | ||
| const expectedBuf = Buffer.from(expectedSignature, 'hex') | ||
|
|
||
| if (sigBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(sigBuf, expectedBuf)) { | ||
| return unauthorized(res, 'invalid_signature') | ||
| } | ||
|
|
||
| // Save nonce to prevent future replay | ||
| await db.EnterpriseNonce.create({ apiKey, nonce: apiNonce }) | ||
|
|
||
| // Upload to IPFS | ||
| addFileToXinfinIpfs(uploadedFile.data, uploadedFile.name, async (err, ipfsHash) => { | ||
| if (err != null) { | ||
| console.error('Some error occured while adding KYC at /enterprise/addKYC: ', err) | ||
| return res.status(500).send('IPFS Upload Error') | ||
| } | ||
|
|
||
| let hash = ipfsHash[0].hash | ||
| res.status(200).json({ hash }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }) | ||
| } catch (err) { | ||
| console.error('Error in /enterprise/addKYC:', err) | ||
| res.status(500).send('Internal Server Error') | ||
| } | ||
| }) | ||
|
|
||
| module.exports = router | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.