Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and back-channel logout; clients are the linked products (Connect). Sign-in steps (password, sign-up, email check, 2FA and its setup, privacy notice, news question, password reset) survive to the product. Account page and admin API, church profile, export and deletion fan-out, Hub v2 client, jobs. End-to-end tests with a test product on openid-client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* The admin audit log, the per-person sign-in log and the access log. Logging never breaks the
|
||||
* action it records.
|
||||
*/
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export function clientIp(req: Request | undefined): string | null {
|
||||
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
|
||||
}
|
||||
|
||||
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
|
||||
try {
|
||||
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
|
||||
} catch (e) {
|
||||
console.error('[audit]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
export type LoginEventType =
|
||||
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
|
||||
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created';
|
||||
|
||||
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
|
||||
try {
|
||||
await ctx.db.loginEvent.create({
|
||||
data: {
|
||||
accountId,
|
||||
type,
|
||||
clientId: extra.clientId ?? null,
|
||||
ip: clientIp(req),
|
||||
userAgent: req?.get('user-agent')?.slice(0, 300) ?? null,
|
||||
detail: (extra.detail ?? undefined) as never,
|
||||
createdAt: ctx.now(),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[login-event]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function accessLog(ctx: Ctx, actorId: string, targetId: string, action: 'view' | 'export', req?: Request) {
|
||||
try {
|
||||
await ctx.db.accessLog.create({ data: { actorId, targetId, action, ip: clientIp(req), createdAt: ctx.now() } });
|
||||
} catch (e) {
|
||||
console.error('[access-log]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
|
||||
* tests pass their own with `loadConfig({...})`.
|
||||
*/
|
||||
export type Config = {
|
||||
/** The public address, e.g. https://accounts.hopefamily.co.za (no trailing slash). */
|
||||
publicUrl: string;
|
||||
port: number;
|
||||
/** Encrypts secrets at rest and signs cookies. Generated on the server, never sent anywhere. */
|
||||
secret: string;
|
||||
production: boolean;
|
||||
/** Behind nginx/frp: trust X-Forwarded-* (as Events' TRUST_PROXY). */
|
||||
trustProxy: boolean;
|
||||
hubUrl: string;
|
||||
hubLicenceKey: string | null;
|
||||
hubPublicKey: string | null;
|
||||
hubAdminName: string | null;
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
|
||||
/** Local testing only: linked products on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
jobsEnabled: boolean;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
|
||||
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||
const publicUrl = String(env.ACCOUNTS_URL || env.PUBLIC_URL || 'http://localhost:3200').replace(/\/+$/, '');
|
||||
const production = env.NODE_ENV === 'production';
|
||||
const secret = env.ACCOUNTS_SECRET || '';
|
||||
if (production && secret.length < 32) throw new Error('ACCOUNTS_SECRET must be set (at least 32 characters) in production.');
|
||||
return {
|
||||
publicUrl,
|
||||
port: Number(env.PORT || 5200),
|
||||
secret: secret || 'development-only-secret-change-me-0123456789',
|
||||
production,
|
||||
trustProxy: bool(env.TRUST_PROXY, production),
|
||||
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
|
||||
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
|
||||
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
|
||||
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
|
||||
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim() || null,
|
||||
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||
smtp: env.SMTP_HOST
|
||||
? { host: env.SMTP_HOST, port: Number(env.SMTP_PORT || 587), user: env.SMTP_USER || '', pass: env.SMTP_PASS || '', from: env.SMTP_FROM || env.SMTP_USER || '', secure: bool(env.SMTP_SECURE, Number(env.SMTP_PORT) === 465) }
|
||||
: null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Secrets at rest (AES-256-GCM, as Events' utils/encryption.js), tokens and codes.
|
||||
* The key comes from ACCOUNTS_SECRET; encrypted values start with "enc:".
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const SENTINEL = 'enc:';
|
||||
|
||||
export class Secrets {
|
||||
private readonly key: Buffer;
|
||||
|
||||
constructor(secret: string) {
|
||||
this.key = crypto.scryptSync(secret, 'crosscode-accounts-aes256gcm-v1', 32);
|
||||
}
|
||||
|
||||
encrypt(plain: string): string {
|
||||
if (plain.startsWith(SENTINEL)) return plain;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
|
||||
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
|
||||
}
|
||||
|
||||
/** Throws if the value was changed or encrypted with another key. */
|
||||
decrypt(value: string): string {
|
||||
if (!value.startsWith(SENTINEL)) return value;
|
||||
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
|
||||
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
|
||||
/** Keys for signing cookies (oidc-provider and our own), derived so they're stable per install. */
|
||||
cookieKeys(): string[] {
|
||||
return [crypto.createHmac('sha256', this.key).update('cookies-v1').digest('base64url')];
|
||||
}
|
||||
}
|
||||
|
||||
/** A random token for a link sent by email (32 bytes, base64url). */
|
||||
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
/** A 6-digit code sent by email or WhatsApp. */
|
||||
export const randomCode = () => String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
|
||||
|
||||
/** What's stored for a token or code: only its SHA-256. */
|
||||
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
|
||||
|
||||
export function safeEqual(a: string, b: string): boolean {
|
||||
const x = Buffer.from(a);
|
||||
const y = Buffer.from(b);
|
||||
return x.length === y.length && crypto.timingSafeEqual(x, y);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Email (SMTP, from the admin's settings or the server's .env) and WhatsApp (WAWP, as Cross
|
||||
* Events). In tests a `MemoryMessenger` keeps what would have been sent.
|
||||
*/
|
||||
import nodemailer from 'nodemailer';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export type Email = { to: string; subject: string; text: string };
|
||||
export type WhatsApp = { to: string; text: string };
|
||||
|
||||
export interface Messenger {
|
||||
email(msg: Email): Promise<void>;
|
||||
whatsapp(msg: WhatsApp): Promise<void>;
|
||||
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
|
||||
whatsappReady(): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */
|
||||
export function waNumber(raw: string): string | null {
|
||||
let d = String(raw || '').replace(/\D/g, '');
|
||||
if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`;
|
||||
return d.length >= 10 && d.length <= 15 ? d : null;
|
||||
}
|
||||
|
||||
export class LiveMessenger implements Messenger {
|
||||
constructor(private readonly ctx: Pick<Ctx, 'settings' | 'config'>) {}
|
||||
|
||||
private async smtp() {
|
||||
const s = this.ctx.settings;
|
||||
const host = (await s.get('smtp_host')) || this.ctx.config.smtp?.host;
|
||||
if (!host) return null;
|
||||
const port = Number((await s.get('smtp_port')) || this.ctx.config.smtp?.port || 587);
|
||||
return {
|
||||
transport: nodemailer.createTransport({
|
||||
host,
|
||||
port,
|
||||
secure: (await s.get('smtp_secure')) === 'true' || (this.ctx.config.smtp?.secure ?? port === 465),
|
||||
auth: { user: (await s.get('smtp_user')) || this.ctx.config.smtp?.user || '', pass: (await s.get('smtp_pass')) || this.ctx.config.smtp?.pass || '' },
|
||||
}),
|
||||
from: (await s.get('smtp_from')) || this.ctx.config.smtp?.from || '',
|
||||
};
|
||||
}
|
||||
|
||||
async email(msg: Email): Promise<void> {
|
||||
const smtp = await this.smtp();
|
||||
if (!smtp) {
|
||||
if (this.ctx.config.production) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).');
|
||||
console.log(`[email] (no SMTP) to ${msg.to}: ${msg.subject}\n${msg.text}`);
|
||||
return;
|
||||
}
|
||||
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
}
|
||||
|
||||
async whatsappReady(): Promise<boolean> {
|
||||
return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id')));
|
||||
}
|
||||
|
||||
async whatsapp(msg: WhatsApp): Promise<void> {
|
||||
const token = await this.ctx.settings.get('wawp_access_token');
|
||||
const instance = await this.ctx.settings.get('wawp_instance_id');
|
||||
const number = waNumber(msg.to);
|
||||
if (!token || !instance) throw new Error('WhatsApp isn\'t set up.');
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: token, instance_id: instance, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
}
|
||||
}
|
||||
|
||||
export class MemoryMessenger implements Messenger {
|
||||
emails: Email[] = [];
|
||||
whatsapps: WhatsApp[] = [];
|
||||
whatsappOn = false;
|
||||
async email(msg: Email) { this.emails.push(msg); }
|
||||
async whatsapp(msg: WhatsApp) { this.whatsapps.push(msg); }
|
||||
async whatsappReady() { return this.whatsappOn; }
|
||||
/** The last 6-digit code sent to `to` (tests). */
|
||||
lastCode(to: string): string | null {
|
||||
const all = [...this.emails.filter((e) => e.to === to).map((e) => e.text), ...this.whatsapps.filter((w) => w.to === to).map((w) => w.text)];
|
||||
const m = /\b(\d{6})\b/.exec(all[all.length - 1] ?? '');
|
||||
return m ? m[1]! : null;
|
||||
}
|
||||
/** The last link sent to `to` (tests). */
|
||||
lastLink(to: string): string | null {
|
||||
const e = this.emails.filter((x) => x.to === to).at(-1);
|
||||
const m = /(https?:\/\/\S+)/.exec(e?.text ?? '');
|
||||
return m ? m[1]! : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Passwords: Argon2id with Events' parameters. bcrypt hashes (imported from Cross Events, whose
|
||||
* older accounts still have them) verify too, and `needsRehash` tells the caller to store a new
|
||||
* Argon2id hash after a successful sign-in, as Events does.
|
||||
*/
|
||||
import argon2 from '@node-rs/argon2';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const OPTIONS = { algorithm: 2 as const /* Argon2id */, memoryCost: 19456, timeCost: 2, parallelism: 1 };
|
||||
const PREFIX = `$argon2id$v=19$m=${OPTIONS.memoryCost},t=${OPTIONS.timeCost},p=${OPTIONS.parallelism}$`;
|
||||
|
||||
export const MIN_PASSWORD_LENGTH = 8;
|
||||
export const MAX_PASSWORD_LENGTH = 200;
|
||||
|
||||
export function hashPassword(password: string): Promise<string> {
|
||||
return argon2.hash(password, OPTIONS);
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hash: string | null | undefined): Promise<boolean> {
|
||||
if (!hash) return false;
|
||||
try {
|
||||
if (hash.startsWith('$argon2')) return await argon2.verify(hash, password);
|
||||
if (/^\$2[aby]\$/.test(hash)) return await bcrypt.compare(password, hash);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export const needsRehash = (hash: string) => !hash.startsWith(PREFIX);
|
||||
|
||||
/** A hash to compare against when there's no account, so a missing account takes as long. */
|
||||
let dummy: Promise<string> | null = null;
|
||||
export function dummyHash(): Promise<string> {
|
||||
if (!dummy) dummy = hashPassword('no-such-account-placeholder');
|
||||
return dummy;
|
||||
}
|
||||
|
||||
export function passwordProblem(password: unknown): string | null {
|
||||
if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`;
|
||||
if (password.length > MAX_PASSWORD_LENGTH) return 'That password is too long.';
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Recovery codes: 10 single-use codes each time 2FA is turned on, shown once ("abcd-efgh-jkmn").
|
||||
* Only their hashes are kept. Letters that are easy to mix up are left out.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { hashToken } from './crypto.js';
|
||||
|
||||
const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
|
||||
export const RECOVERY_CODE_COUNT = 10;
|
||||
|
||||
function one(): string {
|
||||
const chars = Array.from({ length: 12 }, () => ALPHABET[crypto.randomInt(0, ALPHABET.length)]);
|
||||
return `${chars.slice(0, 4).join('')}-${chars.slice(4, 8).join('')}-${chars.slice(8).join('')}`;
|
||||
}
|
||||
|
||||
export function newRecoveryCodes(): { codes: string[]; hashes: string[] } {
|
||||
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, one);
|
||||
return { codes, hashes: codes.map(hashRecoveryCode) };
|
||||
}
|
||||
|
||||
/** As typed: case and dashes or spaces don't matter. */
|
||||
export function normaliseRecoveryCode(input: unknown): string {
|
||||
const clean = String(input ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
return clean.length === 12 ? `${clean.slice(0, 4)}-${clean.slice(4, 8)}-${clean.slice(8)}` : clean;
|
||||
}
|
||||
|
||||
export const hashRecoveryCode = (code: string) => hashToken(normaliseRecoveryCode(code));
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Site settings in `AppSetting` (key → string). Secret ones are encrypted at rest. A short cache
|
||||
* keeps sign-in pages from reading the table on every request.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** Encrypted at rest; never sent to the browser. */
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
|
||||
|
||||
/** The settings an admin may read and change through the generic settings API. */
|
||||
export const ADMIN_SETTINGS = new Set([
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
|
||||
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
|
||||
'wawp_access_token', 'wawp_instance_id',
|
||||
]);
|
||||
|
||||
const TTL_MS = 30_000;
|
||||
|
||||
export class Settings {
|
||||
private cache = new Map<string, { value: string | null; at: number }>();
|
||||
|
||||
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
const hit = this.cache.get(key);
|
||||
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
||||
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
|
||||
let value = row?.value ?? null;
|
||||
if (value !== null && SECRET_SETTINGS.has(key)) {
|
||||
try {
|
||||
value = this.ctx.secrets.decrypt(value);
|
||||
} catch {
|
||||
value = null;
|
||||
}
|
||||
}
|
||||
this.cache.set(key, { value, at: Date.now() });
|
||||
return value;
|
||||
}
|
||||
|
||||
async bool(key: string, fallback: boolean): Promise<boolean> {
|
||||
const v = await this.get(key);
|
||||
return v === null || v === '' ? fallback : v === 'true';
|
||||
}
|
||||
|
||||
async json<T>(key: string, fallback: T): Promise<T> {
|
||||
const v = await this.get(key);
|
||||
if (!v) return fallback;
|
||||
try {
|
||||
return JSON.parse(v) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
|
||||
else {
|
||||
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
|
||||
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
|
||||
}
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
async setMany(values: Record<string, string | null>): Promise<void> {
|
||||
for (const [k, v] of Object.entries(values)) await this.set(k, v);
|
||||
}
|
||||
|
||||
forget(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Authenticator-app codes (RFC 6238: SHA-1, 6 digits, 30 seconds), as Cross Events 2.3 and the Hub,
|
||||
* so secrets moved from Events keep working. `matchStep` returns the step a code belongs to, so a
|
||||
* code that was used once is refused the second time.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
export const STEP = 30;
|
||||
|
||||
export function base32Encode(buf: Uint8Array): string {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let out = '';
|
||||
for (const byte of buf) {
|
||||
value = (value << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
out += BASE32[(value >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
|
||||
return out;
|
||||
}
|
||||
|
||||
export function base32Decode(str: string): Buffer {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
const out: number[] = [];
|
||||
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
|
||||
const idx = BASE32.indexOf(ch);
|
||||
if (idx === -1) continue;
|
||||
value = (value << 5) | idx;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
out.push((value >>> (bits - 8)) & 255);
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
return Buffer.from(out);
|
||||
}
|
||||
|
||||
export const generateSecret = () => base32Encode(crypto.randomBytes(20));
|
||||
|
||||
export function codeAt(secret: string, counter: number): string {
|
||||
const buf = Buffer.alloc(8);
|
||||
buf.writeBigUInt64BE(BigInt(counter));
|
||||
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
|
||||
const offset = hmac[hmac.length - 1]! & 0xf;
|
||||
const num = ((hmac[offset]! & 0x7f) << 24) | (hmac[offset + 1]! << 16) | (hmac[offset + 2]! << 8) | hmac[offset + 3]!;
|
||||
return String(num % 1_000_000).padStart(6, '0');
|
||||
}
|
||||
|
||||
/** The step `code` is right for (now, or one either side for clock drift), or null. Steps up to `afterStep` were used. */
|
||||
export function matchStep(secret: string, code: unknown, { now = Date.now(), afterStep = -1 } = {}): number | null {
|
||||
const clean = String(code ?? '').replace(/\D/g, '');
|
||||
if (clean.length !== 6) return null;
|
||||
const counter = Math.floor(now / 1000 / STEP);
|
||||
for (const c of [counter - 1, counter, counter + 1]) {
|
||||
if (c <= afterStep) continue;
|
||||
if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The otpauth:// link an authenticator app scans as a QR code. */
|
||||
export function otpauthUrl(secret: string, account: string, issuer: string): string {
|
||||
const label = `${issuer}:${account}`;
|
||||
return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
|
||||
}
|
||||
Reference in New Issue
Block a user