Skip to content
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

feat: add otp utils #37

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,27 @@
"require": "./dist/crypto.web.cjs",
"import": "./dist/crypto.web.mjs",
"types": "./dist/crypto.web.d.ts"
},
"./otp": {
"browser": "./dist/otp.mjs",
"bun": "./dist/otp.mjs",
"deno": "./dist/otp.mjs",
"edge-light": "./dist/otp.mjs",
"edge-routine": "./dist/otp.mjs",
"lagon": "./dist/otp.mjs",
"netlify": "./dist/otp.mjs",
"react-native": "./dist/otp.mjs",
"wintercg": "./dist/otp.mjs",
"worker": "./dist/otp.mjs",
"workerd": "./dist/otp.mjs",
"node": {
"require": "./dist/otp.cjs",
"import": "./dist/otp.mjs",
"types": "./dist/otp.d.ts"
},
"require": "./dist/otp.cjs",
"import": "./dist/otp.mjs",
"types": "./dist/otp.d.ts"
}
},
"main": "./dist/crypto.node.cjs",
Expand Down Expand Up @@ -56,5 +77,10 @@
"unbuild": "^1.2.1",
"vitest": "^0.34.5"
},
"packageManager": "[email protected]"
}
"packageManager": "[email protected]",
"unbuild": {
"externals": [
"uncrypto"
]
}
}
150 changes: 150 additions & 0 deletions src/otp/base32.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*!
* base-32.js
* Copyright(c) 2024 Reaper
* MIT Licensed
*/

// Simple implementation based of RFC 4648 for base32 encoding and decoding

const pad = "=";
const base32alphaMap = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might try to compress it using an array.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doable, though the reference and number of operation would remain similar during encode, saves a bit more during decode so I've pushed the changes

0: "A",
1: "B",
2: "C",
3: "D",
4: "E",
5: "F",
6: "G",
7: "H",
8: "I",
9: "J",
10: "K",
11: "L",
12: "M",
13: "N",
14: "O",
15: "P",
16: "Q",
17: "R",
18: "S",
19: "T",
20: "U",
21: "V",
22: "W",
23: "X",
24: "Y",
25: "Z",
26: "2",
27: "3",
28: "4",
29: "5",
30: "6",
31: "7",
};

const base32alphaMapDecode = Object.fromEntries(
Object.entries(base32alphaMap).map(([k, v]) => [v, k])
);

export const encode = (str: string) => {
const splits = str.split("");

if (!splits.length) {
return "";
}

let binaryGroup = [];
let bitText = "";

splits.forEach((c) => {
bitText += toBinary(c);

if (bitText.length == 40) {
binaryGroup.push(bitText);
bitText = "";
}
});

if (bitText.length > 0) {
binaryGroup.push(bitText);
bitText = "";
}

return binaryGroup
.map((x) => {
let fiveBitGrouping = [];
let lex = "";
let bitOn = x;

bitOn.split("").forEach((d) => {
lex += d;
if (lex.length == 5) {
fiveBitGrouping.push(lex);
lex = "";
}
});

if (lex.length > 0) {
fiveBitGrouping.push(lex.padEnd(5, "0"));
lex = "";
}

let paddedArray = Array.from(fiveBitGrouping);
paddedArray.length = 8;
paddedArray = paddedArray.fill("-1", fiveBitGrouping.length, 8);

return paddedArray
.map((f) => {
if (f == "-1") {
return pad;
}
const key = parseInt(f, 2).toString(
10
) as unknown as keyof typeof base32alphaMap;
return base32alphaMap[key];
})
.join("");
})
.join("");
};

export const decode = (str: string) => {
const overallBinary = str
.split("")
.map((x) => {
if (x === pad) {
return "00000";
}
const d = base32alphaMapDecode[x];
const binary = parseInt(d, 10).toString(2);
return binary.padStart(5, "0");
})
.join("");

const characterBitGrouping = chunk(overallBinary.split(""), 8);
return characterBitGrouping
.map((x) => {
const binaryL = x.join("");
const str = String.fromCharCode(+parseInt(binaryL, 2).toString(10));
return str.replace("\x00", "");
})
.join("");

return "";
};

const toBinary = (char: string, padLimit = 8) => {
const binary = String(char).charCodeAt(0).toString(2);
return binary.padStart(padLimit, "0");
};

const chunk = <T>(
arr: Array<T>,
chunkSize = 1,
cache: Array<Array<T>> = []
) => {
const tmp = [...arr];
if (chunkSize <= 0) return cache;
while (tmp.length) cache.push(tmp.splice(0, chunkSize));
return cache;
};
5 changes: 5 additions & 0 deletions src/otp/endian.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function bigEndian64(hash: bigint) {
const buf = Buffer.allocUnsafe(64 / 8);
buf.writeBigInt64BE(hash, 0);
return buf;
}
37 changes: 37 additions & 0 deletions src/otp/hmac.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import subtle from "uncrypto";

const algoMap = {
sha1: "SHA-1",
sha256: "SHA-256",
sha512: "SHA-512",
};

export type AlgoEnum = "sha1" | "sha256" | "sha512";

export async function createHmac(
algorithm: AlgoEnum,
secret: string,
data: Buffer
) {
// let enc
// if (TextEncoder.constructor.length == 1) {
// // @ts-ignore
// enc = new TextEncoder('utf-8')
// } else {
// enc = new TextEncoder()
// }

const key = await subtle.importKey(
"raw", // raw format of the key - should be Uint8Array
secret,
{
// algorithm details
name: "HMAC",
hash: { name: algoMap[algorithm] },
},
false, // export = false
["sign", "verify"] // what this key can do
);
const signature = await subtle.sign("HMAC", key, data);
return Buffer.from(signature);
}
84 changes: 84 additions & 0 deletions src/otp/otp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { getRandomValues } from "uncrypto";

import { decode, encode } from "./base32.js";
import { AlgoEnum, createHmac } from "./hmac.js";
import { bigEndian64 } from "./endian";

interface TOTPURLOptions {
company: string;
email: string;
}

const { floor } = Math;

/**
* @param {string} secret - the secret to be used, needs to be a base32 encoded string
* @param {number} when - point of time in seconds (default: Date.now()/1000)
* @param {object} [options]
* @param {number} [options.period] in seconds (eg: 30 => 30 seconds)
* @param {import("./hmac.js").AlgoEnum} [options.algorithm] (default: sha512)
* @returns {Promise<string>}
*/
export async function totp(
secret: string,
when = floor(Date.now() / 1000),
options = {}
) {
const _options = Object.assign(
{
period: 30,
algorithm: "sha512" as AlgoEnum,
},
options
);
const now = floor(when / _options.period);
const key = decode(secret);
const buff = bigEndian64(BigInt(now));
const hmac = await createHmac(_options.algorithm, key, buff);
const offset = hmac[hmac.length - 1] & 0xf;
const truncatedHash = hmac.subarray(offset, offset + 4);
const otp = (
(truncatedHash.readInt32BE() & 0x7f_ff_ff_ff) %
1_000_000
).toString(10);
return otp.length < 6 ? `${otp}`.padStart(6, "0") : otp;
}

/**
* @param {string} secret - the secret to be used, needs to be a base32 encoded string
* @param {string} totpToken - the totp token
* @param {object} [options]
* @param {number} [options.period] in seconds (eg: 30 => 30 seconds)
* @param {import("./hmac.js").AlgoEnum} [options.algorithm] (default: sha512)
* @returns {Promise<boolean>}
*/
export async function isTOTPValid(
secret: string,
totpToken: string,
options = {}
) {
const _options = Object.assign({ period: 30, algorithm: "sha512" }, options);
for (let index = -2; index < 3; index += 1) {
const fromSys = await totp(secret, Date.now() / 1000 + index, _options);
const valid = fromSys === totpToken;
if (valid) return true;
}
return false;
}

export function generateTOTPURL(secret: string, options: TOTPURLOptions) {
const parameters = new URLSearchParams();
parameters.append("secret", secret);
parameters.append("issuer", options.company);
parameters.append("digits", "6");
const url = `otpauth://totp/${options.company}:${
options.email
}?${parameters.toString()}`;
return new URL(url).toString();
}

export function generateTOTPSecret(num = 32) {
const array = new Uint32Array(num);
const vals = getRandomValues(array);
return encode(Buffer.from(vals).toString("ascii"));
}
27 changes: 27 additions & 0 deletions test/otp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { expect, it, describe } from "vitest";
import { generateTOTPSecret, isTOTPValid, totp } from "../src/otp/otp";

describe("uncrypto:otp", () => {
it("will generate 2 different secrets", () => {
const secret = generateTOTPSecret();
const secret2 = generateTOTPSecret();
expect(secret).not.eq(secret2);
});

it("dynamic isValid", async () => {
const secret = generateTOTPSecret();
const period = 60;
const opts = {
period: period,
};
const otp = await totp(secret, undefined, opts);
expect(await isTOTPValid(secret, otp, opts)).is.true;
});

it("static is valid", async () => {
const secret = "JFLVYRQGJ5ZFOLSYO5HVOWIZGAYHOCTEGNLE2JYMNAMTCET3A5VQ====";
const d = 1704875845134;
const otp = await totp(secret, d / 1000);
expect(otp).is.eq("" + 881718);
});
});