Skip to content

Commit

Permalink
Removing all crypto imports and relying on runtime support(node/v8)
Browse files Browse the repository at this point in the history
  • Loading branch information
ganesh47 committed Mar 23, 2023
1 parent ff9ae6f commit 122ebfe
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "totp-basic",
"version": "0.0.8",
"version": "0.0.9",
"description": "A Basic TOTP (Time-based One-time Password Algorithm) implementation in TypeScript for use with cloudflare-workers",
"type": "module",
"main": "index.js",
Expand Down
6 changes: 2 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const { subtle } = require('crypto').webcrypto;

export const generateTOTP = async (secret: string): Promise<string> => {
const time = Math.floor(Date.now() / 1000); // get the current time in seconds
const timeWindow = 30; // time window in seconds
Expand All @@ -9,14 +7,14 @@ export const generateTOTP = async (secret: string): Promise<string> => {
counter[6] = (timeStep >> 8) & 0xff;
counter[5] = (timeStep >> 16) & 0xff;
counter[4] = (timeStep >> 24) & 0xff;
const hmacKey = await subtle.importKey(
const hmacKey = await crypto.subtle.importKey(
'raw', // format of the secret key
new TextEncoder().encode(secret), // the secret key as a byte array
{ name: 'HMAC', hash: { name: 'SHA-1' } }, // algorithm to use for HMAC
false, // not extractable
['sign'] // only need the key for signing
);
const hmacResult = await subtle.sign(
const hmacResult = await crypto.subtle.sign(
'HMAC', // HMAC algorithm
hmacKey,
counter // the counter as data to sign
Expand Down
9 changes: 9 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import {describe, it, expect} from "vitest";
import {verifyTOTP, generateTOTP} from "../src";
// @ts-ignore

describe("TOTP generation should work by specs", async () => {
it("should generate a valid OTP", async () => {
try {
if(global.crypto === undefined)
{ // @ts-ignore
global.crypto = await import('node:crypto');
}
} catch (err) {
console.error('crypto support is disabled in your test-runtime!');
}
const secret = 'mysecret';
const otp = await generateTOTP(secret);
expect(otp).toMatch(/^\d{6}$/); // OTP should be a 6-digit string
Expand Down
10 changes: 8 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
{
"compilerOptions": {
"moduleResolution": "node",
"module": "esnext",
"target": "es2018",
"module": "es2020",
"target": "es2020",
"declaration": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true
},
"exclude": [
"node_modules",
"dist"
],
"types": [
"node",
"crypto-browserify",
]
}

0 comments on commit 122ebfe

Please sign in to comment.