UNPKG

2.27 kBJavaScriptView Raw
1/**
2 * Authorization Token
3 * @module auth_token
4 */
5
6const crypto = require('crypto');
7
8function digest(message, key) {
9 return crypto.createHmac("sha256", Buffer.from(key, "hex")).update(message).digest('hex');
10}
11
12/**
13 * Escape url using lowercase hex code
14 * @param {string} url a url string
15 * @return {string} escaped url
16 */
17function escapeToLower(url) {
18 return encodeURIComponent(url).replace(/%../g, function (match) {
19 return match.toLowerCase();
20 });
21}
22
23/**
24 * Auth token options
25 * @typedef {object} authTokenOptions
26 * @property {string} [token_name="__cld_token__"] The name of the token.
27 * @property {string} key The secret key required to sign the token.
28 * @property {string} ip The IP address of the client.
29 * @property {number} start_time=now The start time of the token in seconds from epoch.
30 * @property {string} expiration The expiration time of the token in seconds from epoch.
31 * @property {string} duration The duration of the token (from start_time).
32 * @property {string} acl The ACL for the token.
33 * @property {string} url The URL to authentication in case of a URL token.
34 *
35 */
36
37/**
38 * Generate an authorization token
39 * @param {authTokenOptions} options
40 * @returns {string} the authorization token
41 */
42module.exports = function (options) {
43 const tokenName = options.token_name ? options.token_name : "__cld_token__";
44 if (options.expiration == null) {
45 if (options.duration != null) {
46 let start = options.start_time != null ? options.start_time : Math.round(Date.now() / 1000);
47 options.expiration = start + options.duration;
48 } else {
49 throw new Error("Must provide either expiration or duration");
50 }
51 }
52 let tokenParts = [];
53 if (options.ip != null) {
54 tokenParts.push(`ip=${options.ip}`);
55 }
56 if (options.start_time != null) {
57 tokenParts.push(`st=${options.start_time}`);
58 }
59 tokenParts.push(`exp=${options.expiration}`);
60 if (options.acl != null) {
61 tokenParts.push(`acl=${escapeToLower(options.acl)}`);
62 }
63 let toSign = [...tokenParts];
64 if (options.url) {
65 let url = escapeToLower(options.url);
66 toSign.push(`url=${url}`);
67 }
68 let auth = digest(toSign.join("~"), options.key);
69 tokenParts.push(`hmac=${auth}`);
70 return `${tokenName}=${tokenParts.join('~')}`;
71};