totp/src/OTPOutput.tsx

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-04-07 00:13:19 -04:00
import React from 'react';
import {HashAlgorithms, HOTP, HOTPOptions} from '@otplib/core';
import {createDigest} from '@otplib/plugin-crypto-js';
2024-04-07 01:04:16 -04:00
import classNames from 'classnames';
2024-04-07 03:03:48 -04:00
import CopyButton from './CopyButton.tsx';
2024-04-07 00:13:19 -04:00
const ALGORITHMS = {
sha1: HashAlgorithms.SHA1,
sha256: HashAlgorithms.SHA256,
sha512: HashAlgorithms.SHA512,
};
export type HashAlgorithm = keyof typeof ALGORITHMS;
2024-04-07 01:04:16 -04:00
function OTPCode({code, delta}: { code: string; delta: number }) {
return <div className={classNames('totp-code', {
'totp-older': delta < 0,
'totp-newer': delta > 0,
'totp-current': delta === 0,
'totp-far': Math.abs(delta) > 5,
2024-04-07 02:04:25 -04:00
'totp-near-first': delta === -5,
'totp-near-last': delta === 5,
2024-04-07 01:04:16 -04:00
})}>
2024-04-07 00:13:19 -04:00
{code}
2024-04-07 03:03:48 -04:00
<CopyButton text={code}/>
2024-04-07 00:13:19 -04:00
</div>;
}
export default function OTPOutput({secret, offset, algorithm, digits}: {
secret: string;
offset: number;
algorithm: HashAlgorithm;
digits: number;
}) {
2024-04-07 01:04:16 -04:00
const otp = React.useMemo(() => new HOTP<HOTPOptions>({
2024-04-07 00:13:19 -04:00
createDigest,
digits,
algorithm: ALGORITHMS[algorithm],
}), [digits, algorithm]);
return <div className="totp-output">
{[...Array(21).keys()].map((i) => {
2024-04-07 01:04:16 -04:00
const delta = i - 10;
const current = offset + delta;
return <OTPCode key={current} code={otp.generate(secret, current)} delta={delta}/>;
2024-04-07 00:13:19 -04:00
})}
</div>;
}