foronce 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 reaper <ahoy@barelyhuman.dev>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1 +1,89 @@
1
1
  # foronce
2
+
3
+ - [foronce](#foronce)
4
+ - [Usage](#usage)
5
+ - [Examples](#examples)
6
+ - [One Time Email Validation](#one-time-email-validation)
7
+ - [API](#api)
8
+
9
+ > TOTP in a few functions
10
+
11
+ ## Usage
12
+
13
+ - Install the `foronce` library
14
+
15
+ ```sh
16
+ ; npm install foronce
17
+ ```
18
+
19
+ ### Examples
20
+
21
+ #### One Time Email Validation
22
+
23
+ ```ts
24
+ import { generateTOTPSecret, totp, isTOTPValid } from 'foronce'
25
+
26
+ app.post('/login', (req, res) => {
27
+ const email = req.body.email
28
+ const secret = generateTOTPSecret()
29
+
30
+ const user = new User()
31
+ user.email = email
32
+ user.OTPSecret = secret
33
+ await user.save()
34
+
35
+ const otp = totp(secret)
36
+
37
+ EmailProvider.sendLoginEmail(email, otp)
38
+ })
39
+
40
+ app.post('/verify', (req, res) => {
41
+ const { email, otp } = req.body
42
+ const user = await User.find({
43
+ where: {
44
+ email: email,
45
+ },
46
+ })
47
+
48
+ if (!isTOTPValid(user.OTPSecret, otp)) {
49
+ res.status(400)
50
+ res.send({ message: 'Invalid OTP' })
51
+ return
52
+ }
53
+
54
+ res.send(generateLoginToken(user))
55
+ return
56
+ })
57
+ ```
58
+
59
+ ## API
60
+
61
+ ```ts
62
+ export function totp(
63
+ secret: string,
64
+ when?: number,
65
+ options?: {
66
+ period?: number
67
+ algorithm?: 'sha1' | 'sha256' | 'sha512'
68
+ }
69
+ ): string
70
+
71
+ export function isTOTPValid(
72
+ secret: string,
73
+ token: string,
74
+ options?: {
75
+ period?: number
76
+ algorithm?: 'sha1' | 'sha256' | 'sha512'
77
+ }
78
+ ): boolean
79
+
80
+ export function generateTOTPURL(
81
+ secret: string,
82
+ options: {
83
+ company: string
84
+ email: string
85
+ }
86
+ ): string
87
+
88
+ export function generateTOTPSecret(num?: number): string
89
+ ```
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * base-32.js
5
+ * Copyright(c) 2024 Reaper
6
+ * MIT Licensed
7
+ */
8
+
9
+ // Simple implementation based of RFC 4648 for base32 encoding and decoding
10
+
11
+ const pad = '=';
12
+ const base32alphaMap = {
13
+ 0: 'A',
14
+ 1: 'B',
15
+ 2: 'C',
16
+ 3: 'D',
17
+ 4: 'E',
18
+ 5: 'F',
19
+ 6: 'G',
20
+ 7: 'H',
21
+ 8: 'I',
22
+ 9: 'J',
23
+ 10: 'K',
24
+ 11: 'L',
25
+ 12: 'M',
26
+ 13: 'N',
27
+ 14: 'O',
28
+ 15: 'P',
29
+ 16: 'Q',
30
+ 17: 'R',
31
+ 18: 'S',
32
+ 19: 'T',
33
+ 20: 'U',
34
+ 21: 'V',
35
+ 22: 'W',
36
+ 23: 'X',
37
+ 24: 'Y',
38
+ 25: 'Z',
39
+ 26: '2',
40
+ 27: '3',
41
+ 28: '4',
42
+ 29: '5',
43
+ 30: '6',
44
+ 31: '7',
45
+ };
46
+
47
+ const base32alphaMapDecode = Object.fromEntries(
48
+ Object.entries(base32alphaMap).map(([k, v]) => [v, k])
49
+ );
50
+
51
+ /**
52
+ * @param {string} str
53
+ */
54
+ const encode = str => {
55
+ const splits = str.split('');
56
+
57
+ if (!splits.length) {
58
+ return ''
59
+ }
60
+
61
+ let binaryGroup = [];
62
+ let bitText = '';
63
+
64
+ splits.forEach(c => {
65
+ bitText += toBinary(c);
66
+
67
+ if (bitText.length == 40) {
68
+ binaryGroup.push(bitText);
69
+ bitText = '';
70
+ }
71
+ });
72
+
73
+ if (bitText.length > 0) {
74
+ binaryGroup.push(bitText);
75
+ bitText = '';
76
+ }
77
+
78
+ return binaryGroup
79
+ .map(x => {
80
+ let fiveBitGrouping = [];
81
+ let lex = '';
82
+ let bitOn = x;
83
+
84
+ bitOn.split('').forEach(d => {
85
+ lex += d;
86
+ if (lex.length == 5) {
87
+ fiveBitGrouping.push(lex);
88
+ lex = '';
89
+ }
90
+ });
91
+
92
+ if (lex.length > 0) {
93
+ fiveBitGrouping.push(lex.padEnd(5, '0'));
94
+ lex = '';
95
+ }
96
+
97
+ let paddedArray = Array.from(fiveBitGrouping);
98
+ paddedArray.length = 8;
99
+ paddedArray = paddedArray.fill('-1', fiveBitGrouping.length, 8);
100
+
101
+ return paddedArray
102
+ .map(f => {
103
+ if (f == '-1') {
104
+ return pad
105
+ }
106
+ return base32alphaMap[parseInt(f, 2).toString(10)]
107
+ })
108
+ .join('')
109
+ })
110
+ .join('')
111
+ };
112
+
113
+ /**
114
+ * @param {string} str
115
+ * @returns
116
+ */
117
+ const decode = str => {
118
+ const overallBinary = str
119
+ .split('')
120
+ .map(x => {
121
+ if (x === pad) {
122
+ return '00000'
123
+ }
124
+ const d = base32alphaMapDecode[x];
125
+ const binary = parseInt(d, 10).toString(2);
126
+ return binary.padStart(5, '0')
127
+ })
128
+ .join('');
129
+
130
+ const characterBitGrouping = chunk(overallBinary.split(''), 8);
131
+ return characterBitGrouping
132
+ .map(x => {
133
+ const binaryL = x.join('');
134
+ const str = String.fromCharCode(+parseInt(binaryL, 2).toString(10));
135
+ return str.replace('\x00', '')
136
+ })
137
+ .join('')
138
+ };
139
+
140
+ const toBinary = (char, padLimit = 8) => {
141
+ const binary = String(char).charCodeAt(0).toString(2);
142
+ return binary.padStart(padLimit, '0')
143
+ };
144
+
145
+ const chunk = (arr, chunkSize = 1, cache = []) => {
146
+ const tmp = [...arr];
147
+ if (chunkSize <= 0) return cache
148
+ while (tmp.length) cache.push(tmp.splice(0, chunkSize));
149
+ return cache
150
+ };
151
+
152
+ exports.decode = decode;
153
+ exports.encode = encode;
@@ -0,0 +1,2 @@
1
+ export function encode(str: string): string;
2
+ export function decode(str: string): string;
package/dist/index.cjs CHANGED
@@ -2,16 +2,15 @@
2
2
 
3
3
  var node_crypto = require('node:crypto');
4
4
  var node_buffer = require('node:buffer');
5
- var base32 = require('hi-base32');
5
+ var base32 = require('./base32.cjs');
6
6
 
7
- /**
8
- * Simplified implementation of TOTP with existing node libs
9
- *
10
- * helpers to handle the following
11
- * - generate QR codes with the otpauth:// URL scheme
12
- * - algo and implmentation taken from https://drewdevault.com/2022/10/18/TOTP-is-easy.html
7
+ /*!
8
+ * base-32.js
9
+ * Copyright(c) 2024 Reaper
10
+ * MIT Licensed
13
11
  */
14
12
 
13
+
15
14
  const { floor } = Math;
16
15
 
17
16
  /**
@@ -20,14 +19,15 @@ const { floor } = Math;
20
19
  * @param {number} when
21
20
  * @param {object} [options]
22
21
  * @param {number} [options.period] in seconds (eg: 30 => 30 seconds)
22
+ * @param {"sha1" | "sha256" | "sha512"} [options.algorithm] (default: sha512)
23
23
  * @returns {string}
24
24
  */
25
25
  function totp(secret, when = floor(Date.now() / 1000), options = {}) {
26
- const _options = Object.assign({ period: 30 }, options);
26
+ const _options = Object.assign({ period: 30, algorithm: 'sha512' }, options);
27
27
  const now = floor(when / _options.period);
28
28
  const key = base32.decode(secret);
29
29
  const buff = bigEndian64(BigInt(now));
30
- const hmac = node_crypto.createHmac('sha512', key).update(buff).digest();
30
+ const hmac = node_crypto.createHmac(_options.algorithm, key).update(buff).digest();
31
31
  const offset = hmac[hmac.length - 1] & 0xf;
32
32
  const truncatedHash = hmac.subarray(offset, offset + 4);
33
33
  const otp = (
@@ -42,10 +42,11 @@ function totp(secret, when = floor(Date.now() / 1000), options = {}) {
42
42
  * @param {string} token
43
43
  * @param {object} [options]
44
44
  * @param {number} [options.period] in seconds (eg: 30 => 30 seconds)
45
+ * @param {"sha1" | "sha256" | "sha512"} [options.algorithm] (default: sha512)
45
46
  * @returns {boolean}
46
47
  */
47
- function isValid(secret, token, options = {}) {
48
- const _options = Object.assign({ period: 30 }, options);
48
+ function isTOTPValid(secret, token, options = {}) {
49
+ const _options = Object.assign({ period: 30, algorithm: 'sha512' }, options);
49
50
  for (let index = -2; index < 3; index += 1) {
50
51
  const fromSys = totp(secret, Date.now() / 1000 + index, _options);
51
52
  const valid = fromSys === token;
@@ -88,5 +89,5 @@ function generateTOTPSecret(num = 32) {
88
89
 
89
90
  exports.generateTOTPSecret = generateTOTPSecret;
90
91
  exports.generateTOTPURL = generateTOTPURL;
91
- exports.isValid = isValid;
92
+ exports.isTOTPValid = isTOTPValid;
92
93
  exports.totp = totp;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export function totp(secret: string, when?: number, options?: {
2
2
  period?: number;
3
+ algorithm?: "sha1" | "sha256" | "sha512";
3
4
  }): string;
4
- export function isValid(secret: string, token: string, options?: {
5
+ export function isTOTPValid(secret: string, token: string, options?: {
5
6
  period?: number;
7
+ algorithm?: "sha1" | "sha256" | "sha512";
6
8
  }): boolean;
7
9
  export function generateTOTPURL(secret: string, options: {
8
10
  company: string;
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "foronce",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
+ "description": "TOTP in a few functions",
4
5
  "repository": "git@github.com:dumbjs/foronce.git",
5
6
  "license": "MIT",
6
7
  "author": "Reaper <ahoy@barelyhuman.dev>",
@@ -11,6 +12,11 @@
11
12
  "import": "./src/index.js",
12
13
  "require": "./dist/index.cjs"
13
14
  },
15
+ "./base32": {
16
+ "types": "./dist/base32.d.ts",
17
+ "import": "./src/base32.js",
18
+ "require": "./dist/base32.cjs"
19
+ },
14
20
  "./package.json": "./package.json"
15
21
  },
16
22
  "main": "./dist/index.cjs",
@@ -34,10 +40,6 @@
34
40
  "*.{js,css,md,json}": "prettier --write"
35
41
  },
36
42
  "prettier": "@barelyhuman/prettier-config",
37
- "dependencies": {
38
- "hi-base32": "^0.5.1",
39
- "uncrypto": "^0.1.3"
40
- },
41
43
  "devDependencies": {
42
44
  "@barelyhuman/prettier-config": "^1.0.0",
43
45
  "@types/node": "^20.10.8",
@@ -63,7 +65,8 @@
63
65
  "files": [
64
66
  "dist/*.dts",
65
67
  "dist/*.ts",
66
- "dist/*.js"
68
+ "dist/*.js",
69
+ "dist/*.cjs"
67
70
  ]
68
71
  }
69
72
  }
package/src/base32.js ADDED
@@ -0,0 +1,150 @@
1
+ /*!
2
+ * base-32.js
3
+ * Copyright(c) 2024 Reaper
4
+ * MIT Licensed
5
+ */
6
+
7
+ // Simple implementation based of RFC 4648 for base32 encoding and decoding
8
+
9
+ const pad = '='
10
+ const base32alphaMap = {
11
+ 0: 'A',
12
+ 1: 'B',
13
+ 2: 'C',
14
+ 3: 'D',
15
+ 4: 'E',
16
+ 5: 'F',
17
+ 6: 'G',
18
+ 7: 'H',
19
+ 8: 'I',
20
+ 9: 'J',
21
+ 10: 'K',
22
+ 11: 'L',
23
+ 12: 'M',
24
+ 13: 'N',
25
+ 14: 'O',
26
+ 15: 'P',
27
+ 16: 'Q',
28
+ 17: 'R',
29
+ 18: 'S',
30
+ 19: 'T',
31
+ 20: 'U',
32
+ 21: 'V',
33
+ 22: 'W',
34
+ 23: 'X',
35
+ 24: 'Y',
36
+ 25: 'Z',
37
+ 26: '2',
38
+ 27: '3',
39
+ 28: '4',
40
+ 29: '5',
41
+ 30: '6',
42
+ 31: '7',
43
+ }
44
+
45
+ const base32alphaMapDecode = Object.fromEntries(
46
+ Object.entries(base32alphaMap).map(([k, v]) => [v, k])
47
+ )
48
+
49
+ /**
50
+ * @param {string} str
51
+ */
52
+ export const encode = str => {
53
+ const splits = str.split('')
54
+
55
+ if (!splits.length) {
56
+ return ''
57
+ }
58
+
59
+ let binaryGroup = []
60
+ let bitText = ''
61
+
62
+ splits.forEach(c => {
63
+ bitText += toBinary(c)
64
+
65
+ if (bitText.length == 40) {
66
+ binaryGroup.push(bitText)
67
+ bitText = ''
68
+ }
69
+ })
70
+
71
+ if (bitText.length > 0) {
72
+ binaryGroup.push(bitText)
73
+ bitText = ''
74
+ }
75
+
76
+ return binaryGroup
77
+ .map(x => {
78
+ let fiveBitGrouping = []
79
+ let lex = ''
80
+ let bitOn = x
81
+
82
+ bitOn.split('').forEach(d => {
83
+ lex += d
84
+ if (lex.length == 5) {
85
+ fiveBitGrouping.push(lex)
86
+ lex = ''
87
+ }
88
+ })
89
+
90
+ if (lex.length > 0) {
91
+ fiveBitGrouping.push(lex.padEnd(5, '0'))
92
+ lex = ''
93
+ }
94
+
95
+ let paddedArray = Array.from(fiveBitGrouping)
96
+ paddedArray.length = 8
97
+ paddedArray = paddedArray.fill('-1', fiveBitGrouping.length, 8)
98
+
99
+ return paddedArray
100
+ .map(f => {
101
+ if (f == '-1') {
102
+ return pad
103
+ }
104
+ return base32alphaMap[parseInt(f, 2).toString(10)]
105
+ })
106
+ .join('')
107
+ })
108
+ .join('')
109
+ }
110
+
111
+ /**
112
+ * @param {string} str
113
+ * @returns
114
+ */
115
+ export const decode = str => {
116
+ const overallBinary = str
117
+ .split('')
118
+ .map(x => {
119
+ if (x === pad) {
120
+ return '00000'
121
+ }
122
+ const d = base32alphaMapDecode[x]
123
+ const binary = parseInt(d, 10).toString(2)
124
+ return binary.padStart(5, '0')
125
+ })
126
+ .join('')
127
+
128
+ const characterBitGrouping = chunk(overallBinary.split(''), 8)
129
+ return characterBitGrouping
130
+ .map(x => {
131
+ const binaryL = x.join('')
132
+ const str = String.fromCharCode(+parseInt(binaryL, 2).toString(10))
133
+ return str.replace('\x00', '')
134
+ })
135
+ .join('')
136
+
137
+ return ''
138
+ }
139
+
140
+ const toBinary = (char, padLimit = 8) => {
141
+ const binary = String(char).charCodeAt(0).toString(2)
142
+ return binary.padStart(padLimit, '0')
143
+ }
144
+
145
+ const chunk = (arr, chunkSize = 1, cache = []) => {
146
+ const tmp = [...arr]
147
+ if (chunkSize <= 0) return cache
148
+ while (tmp.length) cache.push(tmp.splice(0, chunkSize))
149
+ return cache
150
+ }
package/src/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ /*!
2
+ * base-32.js
3
+ * Copyright(c) 2024 Reaper
4
+ * MIT Licensed
5
+ */
6
+
1
7
  /**
2
8
  * Simplified implementation of TOTP with existing node libs
3
9
  *
@@ -7,7 +13,7 @@
7
13
  */
8
14
  import { createHmac, randomBytes } from 'node:crypto'
9
15
  import { Buffer } from 'buffer'
10
- import base32 from 'hi-base32'
16
+ import { decode, encode } from './base32.js'
11
17
 
12
18
  const { floor } = Math
13
19
 
@@ -17,14 +23,15 @@ const { floor } = Math
17
23
  * @param {number} when
18
24
  * @param {object} [options]
19
25
  * @param {number} [options.period] in seconds (eg: 30 => 30 seconds)
26
+ * @param {"sha1" | "sha256" | "sha512"} [options.algorithm] (default: sha512)
20
27
  * @returns {string}
21
28
  */
22
29
  export function totp(secret, when = floor(Date.now() / 1000), options = {}) {
23
- const _options = Object.assign({ period: 30 }, options)
30
+ const _options = Object.assign({ period: 30, algorithm: 'sha512' }, options)
24
31
  const now = floor(when / _options.period)
25
- const key = base32.decode(secret)
32
+ const key = decode(secret)
26
33
  const buff = bigEndian64(BigInt(now))
27
- const hmac = createHmac('sha512', key).update(buff).digest()
34
+ const hmac = createHmac(_options.algorithm, key).update(buff).digest()
28
35
  const offset = hmac[hmac.length - 1] & 0xf
29
36
  const truncatedHash = hmac.subarray(offset, offset + 4)
30
37
  const otp = (
@@ -39,10 +46,11 @@ export function totp(secret, when = floor(Date.now() / 1000), options = {}) {
39
46
  * @param {string} token
40
47
  * @param {object} [options]
41
48
  * @param {number} [options.period] in seconds (eg: 30 => 30 seconds)
49
+ * @param {"sha1" | "sha256" | "sha512"} [options.algorithm] (default: sha512)
42
50
  * @returns {boolean}
43
51
  */
44
- export function isValid(secret, token, options = {}) {
45
- const _options = Object.assign({ period: 30 }, options)
52
+ export function isTOTPValid(secret, token, options = {}) {
53
+ const _options = Object.assign({ period: 30, algorithm: 'sha512' }, options)
46
54
  for (let index = -2; index < 3; index += 1) {
47
55
  const fromSys = totp(secret, Date.now() / 1000 + index, _options)
48
56
  const valid = fromSys === token
@@ -80,5 +88,5 @@ function bigEndian64(hash) {
80
88
  }
81
89
 
82
90
  export function generateTOTPSecret(num = 32) {
83
- return base32.encode(randomBytes(num).toString('ascii'))
91
+ return encode(randomBytes(num).toString('ascii'))
84
92
  }
package/dist/index.js DELETED
@@ -1,89 +0,0 @@
1
- 'use strict';
2
-
3
- var node_crypto = require('node:crypto');
4
- var node_buffer = require('node:buffer');
5
- var base32 = require('hi-base32');
6
-
7
- /**
8
- * Simplified implementation of TOTP with existing node libs
9
- *
10
- * helpers to handle the following
11
- * - generate QR codes with the otpauth:// URL scheme
12
- * - algo and implmentation taken from https://drewdevault.com/2022/10/18/TOTP-is-easy.html
13
- */
14
-
15
- const { floor } = Math;
16
-
17
- /**
18
- *
19
- * @param {string} secret
20
- * @param {number} when
21
- * @param {object} [options]
22
- * @param {number} [options.period]
23
- * @returns {string}
24
- */
25
- function totp(secret, when = floor(Date.now() / 1000), options = {}) {
26
- const _options = Object.assign({ period: 30 }, options);
27
- const now = floor(when / _options.period);
28
- const key = base32.decode(secret);
29
- const buff = bigEndian64(BigInt(now));
30
- const hmac = node_crypto.createHmac('sha1', key).update(buff).digest();
31
- const offset = hmac[hmac.length - 1] & 0xf;
32
- const truncatedHash = hmac.subarray(offset, offset + 4);
33
- const otp = (
34
- (truncatedHash.readInt32BE() & 0x7f_ff_ff_ff) %
35
- 1_000_000
36
- ).toString(10);
37
- return otp.length < 6 ? `${otp}`.padStart(6, '0') : otp
38
- }
39
-
40
- /**
41
- * @param {string} secret
42
- * @param {string} token
43
- * @returns {boolean}
44
- */
45
- function isValid(secret, token) {
46
- for (let index = -2; index < 3; index += 1) {
47
- const fromSys = totp(secret, Date.now() / 1000 + index);
48
- const valid = fromSys === token;
49
- if (valid) return true
50
- }
51
- return false
52
- }
53
-
54
- /**
55
- * @param {string} secret
56
- * @param {object} options
57
- * @param {string} options.company
58
- * @param {string} options.email
59
- * @returns {string}
60
- */
61
- function generateTOTPURL(secret, options) {
62
- const parameters = new URLSearchParams();
63
- parameters.append('secret', secret);
64
- parameters.append('issuer', options.company);
65
- parameters.append('digits', '6');
66
- const url = `otpauth://totp/${options.company}:${
67
- options.email
68
- }?${parameters.toString()}`;
69
- return new URL(url).toString()
70
- }
71
-
72
- /**
73
- * @param {bigint} hash
74
- * @returns {Buffer}
75
- */
76
- function bigEndian64(hash) {
77
- const buf = node_buffer.Buffer.allocUnsafe(64 / 8);
78
- buf.writeBigInt64BE(hash, 0);
79
- return buf
80
- }
81
-
82
- function generateTOTPSecret(num = 32) {
83
- return base32.encode(node_crypto.randomBytes(num).toString('ascii'))
84
- }
85
-
86
- exports.generateTOTPSecret = generateTOTPSecret;
87
- exports.generateTOTPURL = generateTOTPURL;
88
- exports.isValid = isValid;
89
- exports.totp = totp;