otp-toolkit
Version:
Secure, pluggable OTP generation and validation toolkit for Node.js (TypeScript ready).
43 lines (35 loc) • 1.13 kB
text/typescript
import { OtpRecord, OtpStore } from "./types";
export class InMemoryOtpStore implements OtpStore {
private map = new Map<string, OtpRecord>();
private interval: NodeJS.Timeout;
constructor(private sweepMs: number = 60_000) {
// Periodic cleanup of expired/consumed records
this.interval = setInterval(() => {
const now = Date.now();
for (const [id, rec] of this.map.entries()) {
if (rec.consumed || rec.expiresAt <= now) this.map.delete(id);
}
}, this.sweepMs).unref?.();
}
async save(record: OtpRecord): Promise<void> {
this.map.set(record.id, record);
}
async get(id: string): Promise<OtpRecord | undefined> {
return this.map.get(id);
}
async consume(id: string): Promise<void> {
const rec = this.map.get(id);
if (rec) {
rec.consumed = true;
this.map.set(id, rec);
}
}
async delete(id: string): Promise<void> {
this.map.delete(id);
}
async cleanup(now: number = Date.now()): Promise<void> {
for (const [id, rec] of this.map.entries()) {
if (rec.consumed || rec.expiresAt <= now) this.map.delete(id);
}
}
}