@crpdo/time
Version:
Provides methods for performing time-based operations including token verification, hash generation, and NTP calculations. It primarily deals with time-based one-time password (TOTP) functions
77 lines (71 loc) • 2.25 kB
JavaScript
const Time = require('../lib/time')
describe('Time', () => {
describe('#code()', () => {
it('should generate a TOTP given a secret and a time', () => {
const secret = 'my_secret'
const totpGap = 10
const now = Date.now()
const totp = Time.code(secret, totpGap, now)
expect(totp).to.be.a('string')
})
})
describe('#hash()', () => {
it('should generate a hashed time-based code', () => {
const secret = 'my_secret'
const totpGap = 10
const now = Date.now()
const hash = Time.hash(secret, totpGap, now)
expect(hash).to.be.a('string')
})
})
describe('#verify()', () => {
it('should verify a token', () => {
const secret = 'my_secret'
const token = Time.code(secret)
const result = Time.verify(token, secret)
expect(result).to.be.true
})
it('should verify a hashed token', () => {
const secret = 'my_secret'
const token = Time.hash(secret)
const result = Time.verify(token, secret, { hashed: true })
expect(result).to.be.true
})
it('should not verify an invalid token', () => {
const now = Date.now()
const totpGap = 30
const hashed = true
const secret = 'my_secret'
const token = Time.hash(secret, { totpGap, now })
const result = Time.verify(token, secret, { now: now + 1000000, hashed })
expect(result).to.be.false
})
})
describe('#ntp()', () => {
it('should calculate NTP', () => {
const t0 = 1
const t1 = 2
const t2 = 3
const t3 = 4
const ntp = Time.ntp(t0, t1, t2, t3)
expect(ntp).to.be.an('object')
expect(ntp).to.have.property('rtt')
expect(ntp).to.have.property('offset')
expect(ntp).to.have.property('delay')
})
})
describe('#sync()', () => {
it('should calculate average NTP', () => {
const results = [
{ rtt: 1, offset: 2, delay: 3 },
{ rtt: 2, offset: 3, delay: 4 },
{ rtt: 3, offset: 4, delay: 5 },
]
const sync = Time.sync(results)
expect(sync).to.be.an('object')
expect(sync).to.have.property('rtt')
expect(sync).to.have.property('offset')
expect(sync).to.have.property('delay')
})
})
})