Repository navigation
Expand file tree
/
Copy pathtoken-generator.js
More file actions
164 lines (143 loc) · 6.69 KB
/
Copy pathtoken-generator.js
File metadata and controls
164 lines (143 loc) · 6.69 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
/**
* FCS API - Token Generator (Node.js)
*
* Generate secure tokens for frontend JavaScript authentication
*
* Usage:
* 1. Set your accessKey and publicKey
* 2. Call generateToken()
* 3. Pass the token data to your frontend JavaScript
*
* @package FcsApi
* @author FCS API <[email protected]>
* @link https://fcsapi.com
*/
const crypto = require('crypto');
class FcsTokenGenerator {
/**
* Initialize token generator
* @param {string} accessKey - Your API access key (get from https://fcsapi.com/dashboard)
* @param {string} publicKey - Your public key (get from https://fcsapi.com/dashboard)
* @param {number} tokenExpiry - Token expiry in seconds (default: 3600 = 1 hour)
* Options: 300 (5min), 900 (15min), 1800 (30min),
* 3600 (1hr), 86400 (24hr)
*/
constructor(accessKey = 'YOUR_ACCESS_KEY_HERE', publicKey = 'YOUR_PUBLIC_KEY_HERE', tokenExpiry = 3600) {
this.accessKey = accessKey;
this.publicKey = publicKey;
this.tokenExpiry = tokenExpiry;
}
/**
* Generate token for frontend authentication
* @returns {Object} Token data with _token, _expiry, _public_key
*/
generateToken() {
const expiry = Math.floor(Date.now() / 1000) + this.tokenExpiry;
const message = this.publicKey + expiry;
const token = crypto.createHmac('sha256', this.accessKey)
.update(message)
.digest('hex');
return {
_token: token,
_expiry: expiry,
_public_key: this.publicKey
};
}
/**
* Generate token and return as JSON string
* @returns {string} JSON string of token data
*/
toJson() {
return JSON.stringify(this.generateToken());
}
/**
* Generate HTML meta tags for token
* @returns {string} HTML meta tags
*/
getMetaTags() {
const token = this.generateToken();
return `<meta name="fcs-public-key" content="${token._public_key}">
<meta name="fcs-token" content="${token._token}">
<meta name="fcs-token-expiry" content="${token._expiry}">`;
}
/**
* Generate a JWT (header.payload.signature) that the client sends alone as the parameter jwt_token
* @param {string} domain - '' = plain token (works from any site), 'customer.com' = token that only works from that site
* @returns {string} the JWT
*/
generateJwt(domain = '') {
return FcsTokenGenerator.jwt(this.publicKey, this.accessKey, this.tokenExpiry, domain);
}
/**
* Build a JWT without an instance: payload {"pub","exp"}, signed HMAC-SHA256 with the access key (plain)
* or with hex(HMAC-SHA256("jwt|" + domain, access key)) (bound to one site)
* @param {string} publicKey - Your public key
* @param {string} accessKey - Your API access key (never send it to a browser)
* @param {number} seconds - How long the token stays valid (30 to 86400 is the range the mint endpoint allows)
* @param {string} domain - Exact page host the browser sends as Origin (scheme, www., port and path are removed)
* @returns {string} the JWT
* @throws {Error} when a key is empty, seconds is below 1, or a non-empty domain is not a valid host
*/
static jwt(publicKey, accessKey, seconds = 300, domain = '') {
seconds = Math.floor(Number(seconds));
if (!publicKey || !accessKey || !(seconds >= 1)) {
throw new Error('publicKey, accessKey and seconds (1 or more) are required');
}
// The signing key is the access key itself, or a key derived from it and the domain when the token is bound.
let key = accessKey;
if (domain !== '' && domain != null) {
const host = FcsTokenGenerator.normalizeDomain(domain);
if (host === '') {
throw new Error('domain is not a valid host name: ' + domain);
}
key = crypto.createHmac('sha256', accessKey).update('jwt|' + host).digest('hex');
}
const head = FcsTokenGenerator._base64Url('{"alg":"HS256","typ":"JWT"}');
const body = FcsTokenGenerator._base64Url(JSON.stringify({ pub: publicKey, exp: Math.floor(Date.now() / 1000) + seconds }));
const sig = FcsTokenGenerator._base64Url(crypto.createHmac('sha256', key).update(head + '.' + body).digest());
return head + '.' + body + '.' + sig;
}
// Base64url without padding, the JWT way.
static _base64Url(data) {
return Buffer.from(data).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// Same host normalisation as the FCS API server: lowercase, no scheme, no "www.", no port, no path.
static normalizeDomain(value) {
value = String(value == null ? '' : value).trim().replace(/[A-Z]/g, c => c.toLowerCase());
if (value === '' || value === 'null') return '';
if (value.indexOf('://') !== -1) {
const m = value.match(/^[a-z][a-z0-9+.-]*:\/\/(?:[^\/?#@]*@)?(\[[^\]]*\]|[^\/?#:]*)/);
value = m ? m[1] : '';
} else {
value = value.split('/')[0];
if (value.split(':').length === 2) value = value.split(':')[0];
}
value = value.replace(/^\.+|\.+$/g, '');
if (value.startsWith('www.')) value = value.slice(4);
if (value === '' || value.length > 253 || !/^[a-z0-9._:\[\]-]+$/.test(value)) return '';
return value;
}
}
// Export for Node.js
module.exports = FcsTokenGenerator;
// ============================================
// USAGE EXAMPLES
// ============================================
// Example 1: Generate token
// const FcsTokenGenerator = require('./token-generator.js');
// const generator = new FcsTokenGenerator('your_access_key', 'your_public_key');
// const tokenData = generator.generateToken();
// console.log(tokenData);
// Example 2: Express.js endpoint
// app.get('/api/fcs-token', (req, res) => {
// const generator = new FcsTokenGenerator('your_access_key', 'your_public_key');
// res.json(generator.generateToken());
// });
// Example 3: Get meta tags for SSR
// const generator = new FcsTokenGenerator('your_access_key', 'your_public_key');
// const metaTags = generator.getMetaTags();
// Example 4: JWT token (the client sends only this one value, as jwt_token)
// const generator = new FcsTokenGenerator('your_access_key', 'your_public_key', 300);
// const jwt = generator.generateJwt(); // plain: works from any site (or from Allowed Domains if you saved some)
// const jwt = generator.generateJwt('customer.com'); // bound: only works when the browser's Origin is customer.com
// https://api-v4.fcsapi.com/forex/latest?symbol=EUR/USD&jwt_token=<jwt> (or header "Authorization: Bearer <jwt>")