20 lines
1.2 KiB
TypeScript
20 lines
1.2 KiB
TypeScript
import { transaction } from './db';
|
|
import { authId, matchingStep, type AuthConfig } from './auth';
|
|
// A database row serializes all login attempts across workers and restarts.
|
|
export async function consumeCode(config: AuthConfig, code: string): Promise<'ok'|'invalid'|'limited'> {
|
|
return transaction(async client => {
|
|
const id = authId(config);
|
|
await client.query('INSERT INTO auth_login_state(id) VALUES($1) ON CONFLICT DO NOTHING',[id]);
|
|
const {rows:[state]} = await client.query('SELECT *, extract(epoch FROM clock_timestamp()) * 1000 AS now_ms FROM auth_login_state WHERE id=$1 FOR UPDATE',[id]);
|
|
const now = Number(state.now_ms);
|
|
const expired = now - new Date(state.window_start).getTime() >= 300000;
|
|
const attempts = expired ? 0 : state.attempts;
|
|
if (attempts >= 20) return 'limited';
|
|
await client.query('UPDATE auth_login_state SET attempts=$2, window_start=CASE WHEN $3 THEN clock_timestamp() ELSE window_start END WHERE id=$1',[id,attempts+1,expired]);
|
|
const step = matchingStep(config.secret,code,now);
|
|
if (step === null || step <= Number(state.last_step)) return 'invalid';
|
|
await client.query('UPDATE auth_login_state SET last_step=$2 WHERE id=$1',[id,step]);
|
|
return 'ok';
|
|
});
|
|
}
|