@nixxie-cms/auth-2fa 1.0.1

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,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nixxie International DMCC
4
+ Portions Copyright (c) 2023 Thinkmill Labs Pty Ltd and contributors
5
+ (this software is derived from the KeystoneJS project, https://keystonejs.com)
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # @nixxie-cms/auth-2fa
2
+
3
+ Authenticator-app two-factor authentication (TOTP, RFC 6238) for Nixxie CMS. Pure Node `crypto` —
4
+ no dependencies. Works with Google Authenticator, 1Password, Authy, etc.
5
+
6
+ ```ts
7
+ import { createTwoFactor } from '@nixxie-cms/auth-2fa'
8
+
9
+ const twoFactor = createTwoFactor({ issuer: 'My App' })
10
+
11
+ // Enrolment: store `secret` (encrypted) on the user, render `otpauthUrl` as a QR code.
12
+ const { secret, otpauthUrl } = twoFactor.generateSecret(user.email)
13
+
14
+ // Verify a code from the user's app:
15
+ const ok = twoFactor.verify(submittedToken, user.totpSecret)
16
+
17
+ // Recovery codes (store hashed):
18
+ const backupCodes = twoFactor.generateBackupCodes()
19
+ ```
20
+
21
+ Render `otpauthUrl` as a QR with any QR library, or show the base32 `secret` for manual entry.
@@ -0,0 +1,5 @@
1
+ /** RFC 4648 base32 encode (no padding). */
2
+ export declare function base32Encode(buffer: Buffer): string;
3
+ /** RFC 4648 base32 decode. Ignores casing, spaces and `=` padding. */
4
+ export declare function base32Decode(input: string): Buffer;
5
+ //# sourceMappingURL=base32.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base32.d.ts","sourceRoot":"../../../src","sources":["base32.ts"],"names":[],"mappings":"AAEA,2CAA2C;AAC3C,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAcnD;AAED,sEAAsE;AACtE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAgBlD"}
@@ -0,0 +1,21 @@
1
+ import type { GeneratedSecret, TwoFactorConfig } from "./types.js";
2
+ /** Time-based one-time-password (TOTP, RFC 6238) provider for authenticator-app 2FA. */
3
+ export declare class TwoFactor {
4
+ private issuer;
5
+ private digits;
6
+ private period;
7
+ private window;
8
+ constructor(config?: TwoFactorConfig);
9
+ /** Create a new shared secret + otpauth URL for enrolment. `account` is usually the user's email. */
10
+ generateSecret(account: string): GeneratedSecret;
11
+ /** Compute the current TOTP code for a secret (mainly useful in tests). */
12
+ generate(secret: string, atMs?: number): string;
13
+ /** Verify a user-supplied token against the secret, tolerating `window` steps of drift. */
14
+ verify(token: string, secret: string, atMs?: number): boolean;
15
+ /** Generate single-use recovery codes to store (hashed) alongside the secret. */
16
+ generateBackupCodes(count?: number): string[];
17
+ }
18
+ export declare function createTwoFactor(config?: TwoFactorConfig): TwoFactor;
19
+ export { base32Encode, base32Decode } from "./base32.js";
20
+ export type { TwoFactorConfig, GeneratedSecret } from "./types.js";
21
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"../../../src","sources":["index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,mBAAe;AAiB/D,wFAAwF;AACxF,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,MAAM,CAAQ;gBAEV,MAAM,GAAE,eAAoB;IAOxC,qGAAqG;IACrG,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,eAAe;IAahD,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,MAAmB,GAAG,MAAM;IAK3D,2FAA2F;IAC3F,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,MAAmB,GAAG,OAAO;IAiBzE,iFAAiF;IACjF,mBAAmB,CAAC,KAAK,SAAK,GAAG,MAAM,EAAE;CAO1C;AAED,wBAAgB,eAAe,CAAC,MAAM,CAAC,EAAE,eAAe,GAAG,SAAS,CAEnE;AAED,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,oBAAgB;AACrD,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,mBAAe"}
@@ -0,0 +1,20 @@
1
+ export type TwoFactorConfig = {
2
+ /** Label shown in the authenticator app, usually your app/brand name. Default: 'Nixxie CMS' */
3
+ issuer?: string;
4
+ /** Number of digits in the code. Default: 6 */
5
+ digits?: number;
6
+ /** Time step in seconds. Default: 30 */
7
+ period?: number;
8
+ /**
9
+ * How many time steps before/after now are accepted, to tolerate clock drift. Default: 1
10
+ * (i.e. the previous, current and next codes are valid).
11
+ */
12
+ window?: number;
13
+ };
14
+ export type GeneratedSecret = {
15
+ /** Base32-encoded shared secret to store (encrypted) against the user. */
16
+ secret: string;
17
+ /** otpauth:// URI to render as a QR code in the enrolment UI. */
18
+ otpauthUrl: string;
19
+ };
20
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"../../../src","sources":["types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,eAAe,GAAG;IAC5B,+FAA+F;IAC/F,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,+CAA+C;IAC/C,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,0EAA0E;IAC1E,MAAM,EAAE,MAAM,CAAA;IACd,iEAAiE;IACjE,UAAU,EAAE,MAAM,CAAA;CACnB,CAAA"}
@@ -0,0 +1,2 @@
1
+ export * from "./declarations/src/index.js";
2
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibml4eGllLWNtcy1hdXRoLTJmYS5janMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4vZGVjbGFyYXRpb25zL3NyYy9pbmRleC5kLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0=
@@ -0,0 +1,122 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var node_crypto = require('node:crypto');
6
+
7
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
8
+
9
+ /** RFC 4648 base32 encode (no padding). */
10
+ function base32Encode(buffer) {
11
+ let bits = 0;
12
+ let value = 0;
13
+ let output = '';
14
+ for (const byte of buffer) {
15
+ value = value << 8 | byte;
16
+ bits += 8;
17
+ while (bits >= 5) {
18
+ output += ALPHABET[value >>> bits - 5 & 31];
19
+ bits -= 5;
20
+ }
21
+ }
22
+ if (bits > 0) output += ALPHABET[value << 5 - bits & 31];
23
+ return output;
24
+ }
25
+
26
+ /** RFC 4648 base32 decode. Ignores casing, spaces and `=` padding. */
27
+ function base32Decode(input) {
28
+ const clean = input.replace(/=+$/g, '').replace(/\s/g, '').toUpperCase();
29
+ let bits = 0;
30
+ let value = 0;
31
+ const bytes = [];
32
+ for (const char of clean) {
33
+ const idx = ALPHABET.indexOf(char);
34
+ if (idx === -1) throw new Error(`Invalid base32 character: ${char}`);
35
+ value = value << 5 | idx;
36
+ bits += 5;
37
+ if (bits >= 8) {
38
+ bytes.push(value >>> bits - 8 & 0xff);
39
+ bits -= 8;
40
+ }
41
+ }
42
+ return Buffer.from(bytes);
43
+ }
44
+
45
+ function hotp(secret, counter, digits) {
46
+ const buf = Buffer.alloc(8);
47
+ // Write the 64-bit counter big-endian (high word is 0 for any realistic time).
48
+ buf.writeUInt32BE(Math.floor(counter / 0x100000000), 0);
49
+ buf.writeUInt32BE(counter >>> 0, 4);
50
+ const hmac = node_crypto.createHmac('sha1', secret).update(buf).digest();
51
+ const offset = hmac[hmac.length - 1] & 0xf;
52
+ const code = (hmac[offset] & 0x7f) << 24 | (hmac[offset + 1] & 0xff) << 16 | (hmac[offset + 2] & 0xff) << 8 | hmac[offset + 3] & 0xff;
53
+ return (code % 10 ** digits).toString().padStart(digits, '0');
54
+ }
55
+
56
+ /** Time-based one-time-password (TOTP, RFC 6238) provider for authenticator-app 2FA. */
57
+ class TwoFactor {
58
+ constructor(config = {}) {
59
+ var _config$issuer, _config$digits, _config$period, _config$window;
60
+ this.issuer = (_config$issuer = config.issuer) !== null && _config$issuer !== void 0 ? _config$issuer : 'Nixxie CMS';
61
+ this.digits = (_config$digits = config.digits) !== null && _config$digits !== void 0 ? _config$digits : 6;
62
+ this.period = (_config$period = config.period) !== null && _config$period !== void 0 ? _config$period : 30;
63
+ this.window = (_config$window = config.window) !== null && _config$window !== void 0 ? _config$window : 1;
64
+ }
65
+
66
+ /** Create a new shared secret + otpauth URL for enrolment. `account` is usually the user's email. */
67
+ generateSecret(account) {
68
+ const secret = base32Encode(node_crypto.randomBytes(20));
69
+ const label = encodeURIComponent(`${this.issuer}:${account}`);
70
+ const params = new URLSearchParams({
71
+ secret,
72
+ issuer: this.issuer,
73
+ algorithm: 'SHA1',
74
+ digits: String(this.digits),
75
+ period: String(this.period)
76
+ });
77
+ return {
78
+ secret,
79
+ otpauthUrl: `otpauth://totp/${label}?${params}`
80
+ };
81
+ }
82
+
83
+ /** Compute the current TOTP code for a secret (mainly useful in tests). */
84
+ generate(secret, atMs = Date.now()) {
85
+ const counter = Math.floor(atMs / 1000 / this.period);
86
+ return hotp(base32Decode(secret), counter, this.digits);
87
+ }
88
+
89
+ /** Verify a user-supplied token against the secret, tolerating `window` steps of drift. */
90
+ verify(token, secret, atMs = Date.now()) {
91
+ const normalized = token.replace(/\s/g, '');
92
+ if (normalized.length !== this.digits) return false;
93
+ const key = base32Decode(secret);
94
+ const counter = Math.floor(atMs / 1000 / this.period);
95
+ for (let errorWindow = -this.window; errorWindow <= this.window; errorWindow++) {
96
+ const candidate = hotp(key, counter + errorWindow, this.digits);
97
+ if (candidate.length === normalized.length && node_crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalized))) {
98
+ return true;
99
+ }
100
+ }
101
+ return false;
102
+ }
103
+
104
+ /** Generate single-use recovery codes to store (hashed) alongside the secret. */
105
+ generateBackupCodes(count = 10) {
106
+ return Array.from({
107
+ length: count
108
+ }, () => {
109
+ const n = node_crypto.randomInt(0, 100000000);
110
+ const s = n.toString().padStart(8, '0');
111
+ return `${s.slice(0, 4)}-${s.slice(4)}`;
112
+ });
113
+ }
114
+ }
115
+ function createTwoFactor(config) {
116
+ return new TwoFactor(config);
117
+ }
118
+
119
+ exports.TwoFactor = TwoFactor;
120
+ exports.base32Decode = base32Decode;
121
+ exports.base32Encode = base32Encode;
122
+ exports.createTwoFactor = createTwoFactor;
@@ -0,0 +1,115 @@
1
+ import { randomBytes, timingSafeEqual, randomInt, createHmac } from 'node:crypto';
2
+
3
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
4
+
5
+ /** RFC 4648 base32 encode (no padding). */
6
+ function base32Encode(buffer) {
7
+ let bits = 0;
8
+ let value = 0;
9
+ let output = '';
10
+ for (const byte of buffer) {
11
+ value = value << 8 | byte;
12
+ bits += 8;
13
+ while (bits >= 5) {
14
+ output += ALPHABET[value >>> bits - 5 & 31];
15
+ bits -= 5;
16
+ }
17
+ }
18
+ if (bits > 0) output += ALPHABET[value << 5 - bits & 31];
19
+ return output;
20
+ }
21
+
22
+ /** RFC 4648 base32 decode. Ignores casing, spaces and `=` padding. */
23
+ function base32Decode(input) {
24
+ const clean = input.replace(/=+$/g, '').replace(/\s/g, '').toUpperCase();
25
+ let bits = 0;
26
+ let value = 0;
27
+ const bytes = [];
28
+ for (const char of clean) {
29
+ const idx = ALPHABET.indexOf(char);
30
+ if (idx === -1) throw new Error(`Invalid base32 character: ${char}`);
31
+ value = value << 5 | idx;
32
+ bits += 5;
33
+ if (bits >= 8) {
34
+ bytes.push(value >>> bits - 8 & 0xff);
35
+ bits -= 8;
36
+ }
37
+ }
38
+ return Buffer.from(bytes);
39
+ }
40
+
41
+ function hotp(secret, counter, digits) {
42
+ const buf = Buffer.alloc(8);
43
+ // Write the 64-bit counter big-endian (high word is 0 for any realistic time).
44
+ buf.writeUInt32BE(Math.floor(counter / 0x100000000), 0);
45
+ buf.writeUInt32BE(counter >>> 0, 4);
46
+ const hmac = createHmac('sha1', secret).update(buf).digest();
47
+ const offset = hmac[hmac.length - 1] & 0xf;
48
+ const code = (hmac[offset] & 0x7f) << 24 | (hmac[offset + 1] & 0xff) << 16 | (hmac[offset + 2] & 0xff) << 8 | hmac[offset + 3] & 0xff;
49
+ return (code % 10 ** digits).toString().padStart(digits, '0');
50
+ }
51
+
52
+ /** Time-based one-time-password (TOTP, RFC 6238) provider for authenticator-app 2FA. */
53
+ class TwoFactor {
54
+ constructor(config = {}) {
55
+ var _config$issuer, _config$digits, _config$period, _config$window;
56
+ this.issuer = (_config$issuer = config.issuer) !== null && _config$issuer !== void 0 ? _config$issuer : 'Nixxie CMS';
57
+ this.digits = (_config$digits = config.digits) !== null && _config$digits !== void 0 ? _config$digits : 6;
58
+ this.period = (_config$period = config.period) !== null && _config$period !== void 0 ? _config$period : 30;
59
+ this.window = (_config$window = config.window) !== null && _config$window !== void 0 ? _config$window : 1;
60
+ }
61
+
62
+ /** Create a new shared secret + otpauth URL for enrolment. `account` is usually the user's email. */
63
+ generateSecret(account) {
64
+ const secret = base32Encode(randomBytes(20));
65
+ const label = encodeURIComponent(`${this.issuer}:${account}`);
66
+ const params = new URLSearchParams({
67
+ secret,
68
+ issuer: this.issuer,
69
+ algorithm: 'SHA1',
70
+ digits: String(this.digits),
71
+ period: String(this.period)
72
+ });
73
+ return {
74
+ secret,
75
+ otpauthUrl: `otpauth://totp/${label}?${params}`
76
+ };
77
+ }
78
+
79
+ /** Compute the current TOTP code for a secret (mainly useful in tests). */
80
+ generate(secret, atMs = Date.now()) {
81
+ const counter = Math.floor(atMs / 1000 / this.period);
82
+ return hotp(base32Decode(secret), counter, this.digits);
83
+ }
84
+
85
+ /** Verify a user-supplied token against the secret, tolerating `window` steps of drift. */
86
+ verify(token, secret, atMs = Date.now()) {
87
+ const normalized = token.replace(/\s/g, '');
88
+ if (normalized.length !== this.digits) return false;
89
+ const key = base32Decode(secret);
90
+ const counter = Math.floor(atMs / 1000 / this.period);
91
+ for (let errorWindow = -this.window; errorWindow <= this.window; errorWindow++) {
92
+ const candidate = hotp(key, counter + errorWindow, this.digits);
93
+ if (candidate.length === normalized.length && timingSafeEqual(Buffer.from(candidate), Buffer.from(normalized))) {
94
+ return true;
95
+ }
96
+ }
97
+ return false;
98
+ }
99
+
100
+ /** Generate single-use recovery codes to store (hashed) alongside the secret. */
101
+ generateBackupCodes(count = 10) {
102
+ return Array.from({
103
+ length: count
104
+ }, () => {
105
+ const n = randomInt(0, 100000000);
106
+ const s = n.toString().padStart(8, '0');
107
+ return `${s.slice(0, 4)}-${s.slice(4)}`;
108
+ });
109
+ }
110
+ }
111
+ function createTwoFactor(config) {
112
+ return new TwoFactor(config);
113
+ }
114
+
115
+ export { TwoFactor, base32Decode, base32Encode, createTwoFactor };
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@nixxie-cms/auth-2fa",
3
+ "version": "1.0.1",
4
+ "license": "MIT",
5
+ "main": "dist/nixxie-cms-auth-2fa.cjs.js",
6
+ "module": "dist/nixxie-cms-auth-2fa.esm.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/nixxie-cms-auth-2fa.cjs.js",
10
+ "module": "./dist/nixxie-cms-auth-2fa.esm.js",
11
+ "default": "./dist/nixxie-cms-auth-2fa.cjs.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "dependencies": {
16
+ "@babel/runtime": "^7.24.7"
17
+ },
18
+ "devDependencies": {
19
+ "@nixxie-cms/core": "^1.0.1"
20
+ },
21
+ "peerDependencies": {
22
+ "@nixxie-cms/core": "^1.0.1"
23
+ },
24
+ "preconstruct": {
25
+ "entrypoints": [
26
+ "index.ts"
27
+ ]
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/nixxiecms/nixxie/tree/main/packages/auth-2fa"
32
+ }
33
+ }
package/src/base32.ts ADDED
@@ -0,0 +1,37 @@
1
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
2
+
3
+ /** RFC 4648 base32 encode (no padding). */
4
+ export function base32Encode(buffer: Buffer): string {
5
+ let bits = 0
6
+ let value = 0
7
+ let output = ''
8
+ for (const byte of buffer) {
9
+ value = (value << 8) | byte
10
+ bits += 8
11
+ while (bits >= 5) {
12
+ output += ALPHABET[(value >>> (bits - 5)) & 31]
13
+ bits -= 5
14
+ }
15
+ }
16
+ if (bits > 0) output += ALPHABET[(value << (5 - bits)) & 31]
17
+ return output
18
+ }
19
+
20
+ /** RFC 4648 base32 decode. Ignores casing, spaces and `=` padding. */
21
+ export function base32Decode(input: string): Buffer {
22
+ const clean = input.replace(/=+$/g, '').replace(/\s/g, '').toUpperCase()
23
+ let bits = 0
24
+ let value = 0
25
+ const bytes: number[] = []
26
+ for (const char of clean) {
27
+ const idx = ALPHABET.indexOf(char)
28
+ if (idx === -1) throw new Error(`Invalid base32 character: ${char}`)
29
+ value = (value << 5) | idx
30
+ bits += 5
31
+ if (bits >= 8) {
32
+ bytes.push((value >>> (bits - 8)) & 0xff)
33
+ bits -= 8
34
+ }
35
+ }
36
+ return Buffer.from(bytes)
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,87 @@
1
+ import { createHmac, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'
2
+ import { base32Decode, base32Encode } from './base32'
3
+ import type { GeneratedSecret, TwoFactorConfig } from './types'
4
+
5
+ function hotp(secret: Buffer, counter: number, digits: number): string {
6
+ const buf = Buffer.alloc(8)
7
+ // Write the 64-bit counter big-endian (high word is 0 for any realistic time).
8
+ buf.writeUInt32BE(Math.floor(counter / 0x100000000), 0)
9
+ buf.writeUInt32BE(counter >>> 0, 4)
10
+ const hmac = createHmac('sha1', secret).update(buf).digest()
11
+ const offset = hmac[hmac.length - 1] & 0xf
12
+ const code =
13
+ ((hmac[offset] & 0x7f) << 24) |
14
+ ((hmac[offset + 1] & 0xff) << 16) |
15
+ ((hmac[offset + 2] & 0xff) << 8) |
16
+ (hmac[offset + 3] & 0xff)
17
+ return (code % 10 ** digits).toString().padStart(digits, '0')
18
+ }
19
+
20
+ /** Time-based one-time-password (TOTP, RFC 6238) provider for authenticator-app 2FA. */
21
+ export class TwoFactor {
22
+ private issuer: string
23
+ private digits: number
24
+ private period: number
25
+ private window: number
26
+
27
+ constructor(config: TwoFactorConfig = {}) {
28
+ this.issuer = config.issuer ?? 'Nixxie CMS'
29
+ this.digits = config.digits ?? 6
30
+ this.period = config.period ?? 30
31
+ this.window = config.window ?? 1
32
+ }
33
+
34
+ /** Create a new shared secret + otpauth URL for enrolment. `account` is usually the user's email. */
35
+ generateSecret(account: string): GeneratedSecret {
36
+ const secret = base32Encode(randomBytes(20))
37
+ const label = encodeURIComponent(`${this.issuer}:${account}`)
38
+ const params = new URLSearchParams({
39
+ secret,
40
+ issuer: this.issuer,
41
+ algorithm: 'SHA1',
42
+ digits: String(this.digits),
43
+ period: String(this.period),
44
+ })
45
+ return { secret, otpauthUrl: `otpauth://totp/${label}?${params}` }
46
+ }
47
+
48
+ /** Compute the current TOTP code for a secret (mainly useful in tests). */
49
+ generate(secret: string, atMs: number = Date.now()): string {
50
+ const counter = Math.floor(atMs / 1000 / this.period)
51
+ return hotp(base32Decode(secret), counter, this.digits)
52
+ }
53
+
54
+ /** Verify a user-supplied token against the secret, tolerating `window` steps of drift. */
55
+ verify(token: string, secret: string, atMs: number = Date.now()): boolean {
56
+ const normalized = token.replace(/\s/g, '')
57
+ if (normalized.length !== this.digits) return false
58
+ const key = base32Decode(secret)
59
+ const counter = Math.floor(atMs / 1000 / this.period)
60
+ for (let errorWindow = -this.window; errorWindow <= this.window; errorWindow++) {
61
+ const candidate = hotp(key, counter + errorWindow, this.digits)
62
+ if (
63
+ candidate.length === normalized.length &&
64
+ timingSafeEqual(Buffer.from(candidate), Buffer.from(normalized))
65
+ ) {
66
+ return true
67
+ }
68
+ }
69
+ return false
70
+ }
71
+
72
+ /** Generate single-use recovery codes to store (hashed) alongside the secret. */
73
+ generateBackupCodes(count = 10): string[] {
74
+ return Array.from({ length: count }, () => {
75
+ const n = randomInt(0, 1_0000_0000)
76
+ const s = n.toString().padStart(8, '0')
77
+ return `${s.slice(0, 4)}-${s.slice(4)}`
78
+ })
79
+ }
80
+ }
81
+
82
+ export function createTwoFactor(config?: TwoFactorConfig): TwoFactor {
83
+ return new TwoFactor(config)
84
+ }
85
+
86
+ export { base32Encode, base32Decode } from './base32'
87
+ export type { TwoFactorConfig, GeneratedSecret } from './types'
package/src/types.ts ADDED
@@ -0,0 +1,20 @@
1
+ export type TwoFactorConfig = {
2
+ /** Label shown in the authenticator app, usually your app/brand name. Default: 'Nixxie CMS' */
3
+ issuer?: string
4
+ /** Number of digits in the code. Default: 6 */
5
+ digits?: number
6
+ /** Time step in seconds. Default: 30 */
7
+ period?: number
8
+ /**
9
+ * How many time steps before/after now are accepted, to tolerate clock drift. Default: 1
10
+ * (i.e. the previous, current and next codes are valid).
11
+ */
12
+ window?: number
13
+ }
14
+
15
+ export type GeneratedSecret = {
16
+ /** Base32-encoded shared secret to store (encrypted) against the user. */
17
+ secret: string
18
+ /** otpauth:// URI to render as a QR code in the enrolment UI. */
19
+ otpauthUrl: string
20
+ }