Vendor SharedCode locally
This commit is contained in:
1 parent
a8c51b8484
commit
6eb8f4ad60
88 files changed
+9708
-275
No files matched your search
@@ -0,0 +1,20 @@
|
||||
# `@gabriel20xx/node-backend`
|
||||
|
||||
Shared Node.js backend infrastructure for services that use PostgreSQL:
|
||||
|
||||
- validated `DATABASE_URL` and pool settings;
|
||||
- one pool owner with startup retry, transient query retry, transactions, and shutdown;
|
||||
- PBKDF2 password hashing and secure session-token helpers;
|
||||
- short-lived, one-time admin reset codes printed to the server console;
|
||||
- common account/session persistence;
|
||||
- transaction-locked ordered migrations.
|
||||
|
||||
The package does not depend on Express. Each service keeps its own routes,
|
||||
cookies, roles, validation policy, and domain repositories. Existing
|
||||
`MediaShared` code can be migrated into this package incrementally; keep the
|
||||
legacy package as a compatibility layer until every consumer has moved.
|
||||
|
||||
Pass a service-specific `tableName` to `runMigrations` when multiple services
|
||||
share one PostgreSQL database, so their migration histories cannot collide.
|
||||
|
||||
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `SharedCode`.
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@gabriel20xx/node-backend",
|
||||
"version": "0.1.1",
|
||||
"description": "Shared PostgreSQL, configuration, migration, and authentication primitives for Node.js services.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"src",
|
||||
"test",
|
||||
"README.md"
|
||||
],
|
||||
"exports": {
|
||||
".": "./src/index.js",
|
||||
"./config": "./src/config.js",
|
||||
"./db": "./src/db.js",
|
||||
"./auth": "./src/auth.js",
|
||||
"./migrate": "./src/migrate.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"pg": "^8.17.2"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const PASSWORD_ITERATIONS = 100000;
|
||||
const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
|
||||
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
|
||||
|
||||
export function normalizeRole(value) {
|
||||
const normalized = String(value ?? '').trim().toLowerCase();
|
||||
return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN ? normalized : USER_ROLES.USER;
|
||||
}
|
||||
|
||||
export function canManageUsers(role) {
|
||||
const normalized = normalizeRole(role);
|
||||
return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN;
|
||||
}
|
||||
|
||||
export function canAssignRole(actorRole, targetRole) {
|
||||
return normalizeRole(actorRole) === USER_ROLES.SUPERADMIN && normalizeRole(targetRole) !== USER_ROLES.SUPERADMIN;
|
||||
}
|
||||
|
||||
export const AUTH_SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
UPDATE auth_users SET role = 'superadmin'
|
||||
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
|
||||
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
||||
`;
|
||||
|
||||
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
||||
if (typeof password !== 'string' || password.length < 8) {
|
||||
throw new Error('Password must be at least 8 characters');
|
||||
}
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||
return `${salt}:${hash.toString('hex')}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(password, stored) {
|
||||
try {
|
||||
const [salt, expected] = String(stored).split(':');
|
||||
if (!salt || !expected) return false;
|
||||
const actual = crypto.pbkdf2Sync(
|
||||
String(password),
|
||||
salt,
|
||||
PASSWORD_ITERATIONS,
|
||||
PASSWORD_KEY_LENGTH,
|
||||
PASSWORD_DIGEST
|
||||
);
|
||||
const expectedBytes = Buffer.from(expected, 'hex');
|
||||
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function createSessionToken() {
|
||||
const token = crypto.randomBytes(32).toString('base64url');
|
||||
return { token, tokenHash: hashToken(token) };
|
||||
}
|
||||
|
||||
export function hashToken(token) {
|
||||
return crypto.createHash('sha256').update(String(token)).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and validates the short-lived, one-time code used by the public
|
||||
* "reset admin account" flow. Account deletion stays with the application
|
||||
* because its account table and session policy may differ.
|
||||
*/
|
||||
export class ResetManager {
|
||||
constructor({ ttlMs = RESET_CODE_TTL_MS, log = console.log } = {}) {
|
||||
this.ttlMs = ttlMs;
|
||||
this.log = log;
|
||||
this.code = null;
|
||||
this.expiresAt = 0;
|
||||
}
|
||||
|
||||
request() {
|
||||
this.code = crypto.randomBytes(4).toString('hex').toUpperCase();
|
||||
this.expiresAt = Date.now() + this.ttlMs;
|
||||
this.log(
|
||||
`\n${'='.repeat(50)}\nADMIN RESET CODE: ${this.code}\nExpires in 5 minutes. Enter it on the login page.\n${'='.repeat(50)}\n`,
|
||||
);
|
||||
return this.code;
|
||||
}
|
||||
|
||||
confirm(candidate) {
|
||||
if (!this.code) return false;
|
||||
if (Date.now() > this.expiresAt) {
|
||||
this.code = null;
|
||||
this.expiresAt = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalized = String(candidate ?? '').trim().toUpperCase();
|
||||
const expected = Buffer.from(this.code);
|
||||
const actual = Buffer.from(normalized);
|
||||
const valid = expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||
if (!valid) return false;
|
||||
|
||||
this.code = null;
|
||||
this.expiresAt = 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Persistence-only auth store; cookies, roles, and HTTP policy stay in the app. */
|
||||
export class AuthStore {
|
||||
constructor(database, { singleUser = true } = {}) {
|
||||
if (!database || typeof database.query !== 'function') {
|
||||
throw new TypeError('AuthStore requires a Database-like query object');
|
||||
}
|
||||
this.database = database;
|
||||
this.singleUser = singleUser;
|
||||
}
|
||||
|
||||
async ensureSchema() {
|
||||
await this.database.query(AUTH_SCHEMA);
|
||||
if (this.singleUser) {
|
||||
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
|
||||
} else {
|
||||
await this.database.query('DROP INDEX IF EXISTS auth_users_singleton_idx');
|
||||
}
|
||||
}
|
||||
|
||||
async countUsers() {
|
||||
const result = await this.database.query('SELECT count(*)::int AS count FROM auth_users');
|
||||
return result.rows[0].count;
|
||||
}
|
||||
|
||||
async createUser(username, email, passwordHash) {
|
||||
try {
|
||||
const result = await this.database.query(
|
||||
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3,
|
||||
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
|
||||
now())
|
||||
RETURNING id, username, email, password_hash, role, created_at, updated_at`,
|
||||
[username, email, passwordHash]
|
||||
);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
if (error?.code === '23505') {
|
||||
const duplicate = new Error('auth user already exists');
|
||||
duplicate.code = 'AUTH_USER_EXISTS';
|
||||
throw duplicate;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async findByIdentifier(identifier) {
|
||||
const result = await this.database.query(
|
||||
`SELECT id, username, email, password_hash, role, created_at, updated_at
|
||||
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`,
|
||||
[identifier]
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async updateCredentials(id, username, email, passwordHash) {
|
||||
await this.database.query(
|
||||
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||
WHERE id = $4`,
|
||||
[username, email, passwordHash, id]
|
||||
);
|
||||
}
|
||||
|
||||
async createSession(userId, tokenHash, expiresAt) {
|
||||
await this.database.query(
|
||||
'INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
|
||||
[userId, tokenHash, expiresAt]
|
||||
);
|
||||
}
|
||||
|
||||
async findSessionUser(tokenHash) {
|
||||
const result = await this.database.query(
|
||||
`SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at
|
||||
FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()`,
|
||||
[tokenHash]
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async deleteSession(tokenHash) {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE token_hash = $1', [tokenHash]);
|
||||
}
|
||||
|
||||
async deleteSessionsForUser(userId) {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE user_id = $1', [userId]);
|
||||
}
|
||||
|
||||
async listUsers() {
|
||||
const result = await this.database.query(
|
||||
'SELECT id, username, email, role, created_at, updated_at FROM auth_users ORDER BY created_at, id',
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
|
||||
try {
|
||||
const result = await this.database.query(
|
||||
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3, $4, now())
|
||||
RETURNING id, username, email, role, created_at, updated_at`,
|
||||
[username, email, passwordHash, normalizeRole(role)],
|
||||
);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
if (error?.code === '23505') {
|
||||
const duplicate = new Error('auth user already exists');
|
||||
duplicate.code = 'AUTH_USER_EXISTS';
|
||||
throw duplicate;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async updateUser(id, { username, email, passwordHash, role } = {}) {
|
||||
const fields = [];
|
||||
const values = [];
|
||||
const add = (sql, value) => { fields.push(sql); values.push(value); };
|
||||
if (username !== undefined) add(`username = $${values.length + 1}`, username);
|
||||
if (email !== undefined) add(`email = $${values.length + 1}`, email);
|
||||
if (passwordHash !== undefined) add(`password_hash = $${values.length + 1}`, passwordHash);
|
||||
if (role !== undefined) add(`role = $${values.length + 1}`, normalizeRole(role));
|
||||
if (fields.length === 0) return;
|
||||
values.push(id);
|
||||
await this.database.query(
|
||||
`UPDATE auth_users SET ${fields.join(', ')}, updated_at = now() WHERE id = $${values.length}`,
|
||||
values,
|
||||
);
|
||||
}
|
||||
|
||||
async deleteUser(id) {
|
||||
await this.database.query('DELETE FROM auth_users WHERE id = $1', [id]);
|
||||
}
|
||||
|
||||
async deleteAllUsers() {
|
||||
await this.database.query('DELETE FROM auth_users');
|
||||
}
|
||||
|
||||
async getTotpState(userId) {
|
||||
const result = await this.database.query(
|
||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1',
|
||||
[userId],
|
||||
);
|
||||
return result.rows[0] || { secret: '', enabled: false };
|
||||
}
|
||||
|
||||
async setTotpSecret(userId, secret) {
|
||||
await this.database.query(
|
||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2',
|
||||
[secret, userId],
|
||||
);
|
||||
}
|
||||
|
||||
async enableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''",
|
||||
[userId],
|
||||
);
|
||||
}
|
||||
|
||||
async disableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
|
||||
[userId],
|
||||
);
|
||||
}
|
||||
|
||||
async pruneExpiredSessions() {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE expires_at < now()');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
const DEFAULTS = Object.freeze({
|
||||
max: 20,
|
||||
min: 0,
|
||||
connectionTimeoutMillis: 5000,
|
||||
idleTimeoutMillis: 30000,
|
||||
queryTimeout: 15000,
|
||||
});
|
||||
|
||||
function positiveInt(value, fallback, minimum = 0) {
|
||||
const parsed = Number.parseInt(String(value ?? ''), 10);
|
||||
return Number.isInteger(parsed) && parsed >= minimum ? parsed : fallback;
|
||||
}
|
||||
|
||||
/** Return DATABASE_URL or throw an actionable startup error. */
|
||||
export function databaseUrlFromEnv(env = process.env) {
|
||||
const url = String(env.DATABASE_URL || '').trim();
|
||||
if (!url) {
|
||||
const error = new Error('DATABASE_URL is required');
|
||||
error.code = 'DB_NOT_CONFIGURED';
|
||||
throw error;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/** Build a pg.Pool-compatible configuration from environment variables. */
|
||||
export function databaseConfigFromEnv(env = process.env) {
|
||||
const max = positiveInt(env.DATABASE_MAX_CONNS, DEFAULTS.max, 1);
|
||||
const min = positiveInt(env.DATABASE_MIN_CONNS, DEFAULTS.min, 0);
|
||||
if (min > max) {
|
||||
throw new Error('DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS');
|
||||
}
|
||||
|
||||
return {
|
||||
connectionString: databaseUrlFromEnv(env),
|
||||
max,
|
||||
min,
|
||||
connectionTimeoutMillis: positiveInt(
|
||||
env.DATABASE_CONNECT_TIMEOUT_MS,
|
||||
DEFAULTS.connectionTimeoutMillis,
|
||||
1
|
||||
),
|
||||
idleTimeoutMillis: positiveInt(
|
||||
env.DATABASE_IDLE_TIMEOUT_MS,
|
||||
DEFAULTS.idleTimeoutMillis,
|
||||
0
|
||||
),
|
||||
query_timeout: positiveInt(env.DATABASE_QUERY_TIMEOUT_MS, DEFAULTS.queryTimeout, 1),
|
||||
ssl:
|
||||
/^(true|require|1)$/i.test(String(env.DATABASE_SSL || ''))
|
||||
? { rejectUnauthorized: !/^(true|1)$/i.test(String(env.DATABASE_SSL_ALLOW_INVALID || '')) }
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export { DEFAULTS as DATABASE_DEFAULTS };
|
||||
@@ -0,0 +1,92 @@
|
||||
import pg from 'pg';
|
||||
import { databaseConfigFromEnv } from './config.js';
|
||||
|
||||
const { Pool } = pg;
|
||||
|
||||
const TRANSIENT_CODES = new Set(['ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
|
||||
const TRANSIENT_MESSAGE = /connection terminated|connection reset|econnreset|epipe|server closed the connection/i;
|
||||
|
||||
export function isTransientConnectionError(error) {
|
||||
return Boolean(
|
||||
error &&
|
||||
(TRANSIENT_CODES.has(error.code) || TRANSIENT_MESSAGE.test(String(error.message || '')))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one pg pool and exposes bounded startup, retry, transaction, and
|
||||
* shutdown behavior. Domain repositories should depend on this abstraction
|
||||
* instead of creating independent pools.
|
||||
*/
|
||||
export class Database {
|
||||
constructor(options = {}) {
|
||||
const { pool, ...poolOptions } = options;
|
||||
this.pool = pool || new Pool(poolOptions);
|
||||
this.ownsPool = !pool;
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
static fromEnv(env = process.env) {
|
||||
return new Database(databaseConfigFromEnv(env));
|
||||
}
|
||||
|
||||
async connect({ retries = 10, retryDelayMs = 2000 } = {}) {
|
||||
if (this.ready) return this;
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= Math.max(1, retries); attempt += 1) {
|
||||
try {
|
||||
await this.pool.query('SELECT 1');
|
||||
this.ready = true;
|
||||
return this;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt >= retries || !isTransientConnectionError(error)) throw error;
|
||||
const delay = Math.min(Math.max(100, retryDelayMs) * 2 ** (attempt - 1), 30000);
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
async query(text, values = []) {
|
||||
await this.connect();
|
||||
try {
|
||||
return await this.pool.query(text, values);
|
||||
} catch (error) {
|
||||
if (!isTransientConnectionError(error)) throw error;
|
||||
return this.pool.query(text, values);
|
||||
}
|
||||
}
|
||||
|
||||
async transaction(callback) {
|
||||
if (typeof callback !== 'function') throw new TypeError('transaction callback is required');
|
||||
await this.connect();
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await callback(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
await client.query('ROLLBACK');
|
||||
} catch {
|
||||
// Preserve the original application error.
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (!this.pool || !this.ownsPool) return;
|
||||
await this.pool.end();
|
||||
this.ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function createDatabaseFromEnv(env = process.env) {
|
||||
return Database.fromEnv(env);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
export {
|
||||
databaseConfigFromEnv,
|
||||
databaseUrlFromEnv,
|
||||
DATABASE_DEFAULTS,
|
||||
} from './config.js';
|
||||
export {
|
||||
Database,
|
||||
createDatabaseFromEnv,
|
||||
isTransientConnectionError,
|
||||
} from './db.js';
|
||||
export {
|
||||
AUTH_SCHEMA,
|
||||
AuthStore,
|
||||
RESET_CODE_TTL_MS,
|
||||
ResetManager,
|
||||
createSessionToken,
|
||||
hashPassword,
|
||||
hashToken,
|
||||
USER_ROLES,
|
||||
canAssignRole,
|
||||
canManageUsers,
|
||||
normalizeRole,
|
||||
verifyPassword,
|
||||
} from './auth.js';
|
||||
export {
|
||||
TOTP_DIGITS,
|
||||
TOTP_PERIOD_SECONDS,
|
||||
TOTP_WINDOW,
|
||||
generateTotpSecret,
|
||||
totpProvisioningUri,
|
||||
verifyTotp,
|
||||
} from './totp.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Apply ordered SQL migrations using the shared Database transaction wrapper.
|
||||
* Each migration is { id: string, up: async (client) => void }.
|
||||
*/
|
||||
export async function runMigrations(
|
||||
database,
|
||||
migrations,
|
||||
{ lockKey = 70420320, tableName = 'schema_migrations' } = {}
|
||||
) {
|
||||
if (!database || typeof database.transaction !== 'function') {
|
||||
throw new TypeError('runMigrations requires a Database-like transaction object');
|
||||
}
|
||||
if (!Array.isArray(migrations)) throw new TypeError('migrations must be an array');
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tableName)) {
|
||||
throw new TypeError('migration tableName must be a simple SQL identifier');
|
||||
}
|
||||
const table = `"${tableName}"`;
|
||||
|
||||
const ordered = [...migrations].sort((left, right) => String(left.id).localeCompare(String(right.id)));
|
||||
await database.transaction(async client => {
|
||||
await client.query('SELECT pg_advisory_xact_lock($1)', [lockKey]);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS ${table} (
|
||||
id TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
`);
|
||||
|
||||
for (const migration of ordered) {
|
||||
if (!migration?.id || typeof migration.up !== 'function') {
|
||||
throw new TypeError('each migration requires an id and up(client) function');
|
||||
}
|
||||
const existing = await client.query(
|
||||
`SELECT 1 FROM ${table} WHERE id = $1`,
|
||||
[migration.id]
|
||||
);
|
||||
if (existing.rowCount > 0) continue;
|
||||
await migration.up(client);
|
||||
await client.query(`INSERT INTO ${table} (id) VALUES ($1)`, [migration.id]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
export const TOTP_PERIOD_SECONDS = 30;
|
||||
export const TOTP_DIGITS = 6;
|
||||
export const TOTP_WINDOW = 1;
|
||||
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
|
||||
export function generateTotpSecret() {
|
||||
return encodeBase32(crypto.randomBytes(20));
|
||||
}
|
||||
|
||||
export function totpProvisioningUri(issuer, account, secret) {
|
||||
const normalizedIssuer = String(issuer ?? '').trim();
|
||||
const normalizedAccount = String(account ?? '').trim();
|
||||
const label = normalizedIssuer ? `${normalizedIssuer}:${normalizedAccount}` : normalizedAccount;
|
||||
const params = new URLSearchParams({
|
||||
secret: normalizeSecret(secret),
|
||||
algorithm: 'SHA1',
|
||||
digits: String(TOTP_DIGITS),
|
||||
period: String(TOTP_PERIOD_SECONDS),
|
||||
});
|
||||
if (normalizedIssuer) params.set('issuer', normalizedIssuer);
|
||||
return `otpauth://totp/${encodeURIComponent(label)}?${params.toString()}`;
|
||||
}
|
||||
|
||||
export function verifyTotp(secret, token, now = Date.now()) {
|
||||
const normalizedSecret = normalizeSecret(secret);
|
||||
const normalizedToken = normalizeToken(token);
|
||||
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false;
|
||||
|
||||
let key;
|
||||
try {
|
||||
key = decodeBase32(normalizedSecret);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (key.length === 0) return false;
|
||||
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
|
||||
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) {
|
||||
if (period + offset < 0) continue;
|
||||
const counter = Buffer.alloc(8);
|
||||
counter.writeBigUInt64BE(BigInt(period + offset));
|
||||
const digest = crypto.createHmac('sha1', key).update(counter).digest();
|
||||
const index = digest[digest.length - 1] & 0x0f;
|
||||
const value = ((digest[index] & 0x7f) << 24)
|
||||
| (digest[index + 1] << 16)
|
||||
| (digest[index + 2] << 8)
|
||||
| digest[index + 3];
|
||||
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
|
||||
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function normalizeSecret(value) {
|
||||
return String(value ?? '').trim().toUpperCase().replaceAll(' ', '').replaceAll('=', '');
|
||||
}
|
||||
|
||||
function normalizeToken(value) {
|
||||
const token = String(value ?? '').trim();
|
||||
return /^\d{6}$/.test(token) ? token : '';
|
||||
}
|
||||
|
||||
function encodeBase32(buffer) {
|
||||
let output = '';
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
for (const byte of buffer) {
|
||||
value = (value << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
|
||||
return output;
|
||||
}
|
||||
|
||||
function decodeBase32(value) {
|
||||
let bits = 0;
|
||||
let buffer = 0;
|
||||
const output = [];
|
||||
for (const character of value) {
|
||||
const index = BASE32_ALPHABET.indexOf(character);
|
||||
if (index < 0) throw new Error('invalid base32 secret');
|
||||
buffer = (buffer << 5) | index;
|
||||
bits += 5;
|
||||
while (bits >= 8) {
|
||||
bits -= 8;
|
||||
output.push((buffer >>> bits) & 255);
|
||||
}
|
||||
buffer &= bits === 0 ? 0 : (1 << bits) - 1;
|
||||
}
|
||||
return Buffer.from(output);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
ResetManager,
|
||||
createSessionToken,
|
||||
hashPassword,
|
||||
hashToken,
|
||||
verifyPassword,
|
||||
} from '../src/auth.js';
|
||||
import { totpProvisioningUri, verifyTotp } from '../src/totp.js';
|
||||
|
||||
test('reset codes are printed, case-insensitive, expiring, and one-time', () => {
|
||||
const messages = [];
|
||||
const manager = new ResetManager({ log: (message) => messages.push(message) });
|
||||
const code = manager.request();
|
||||
|
||||
assert.equal(code.length, 8);
|
||||
assert.equal(messages.length, 1);
|
||||
assert.match(messages[0], new RegExp(`ADMIN RESET CODE: ${code}`));
|
||||
assert.equal(manager.confirm(` ${code.toLowerCase()} `), true);
|
||||
assert.equal(manager.confirm(code), false);
|
||||
});
|
||||
|
||||
test('expired reset codes are rejected', () => {
|
||||
const manager = new ResetManager({ ttlMs: -1, log: () => {} });
|
||||
const code = manager.request();
|
||||
assert.equal(manager.confirm(code), false);
|
||||
});
|
||||
|
||||
test('password hashes verify and reject a different password', () => {
|
||||
const hash = hashPassword('correct horse battery staple');
|
||||
assert.equal(verifyPassword('correct horse battery staple', hash), true);
|
||||
assert.equal(verifyPassword('wrong password', hash), false);
|
||||
});
|
||||
|
||||
test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
|
||||
const secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
|
||||
const vectors = [
|
||||
[59, '287082'],
|
||||
[1111111109, '081804'],
|
||||
[1111111111, '050471'],
|
||||
[1234567890, '005924'],
|
||||
[2000000000, '279037'],
|
||||
];
|
||||
for (const [seconds, code] of vectors) {
|
||||
assert.equal(verifyTotp(secret, code, seconds * 1000), true);
|
||||
}
|
||||
assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//);
|
||||
});
|
||||
|
||||
test('session token hashes are not the raw token', () => {
|
||||
const { token, tokenHash } = createSessionToken();
|
||||
assert.notEqual(token, tokenHash);
|
||||
assert.equal(hashToken(token), tokenHash);
|
||||
});
|
||||
Reference in new issue
Block a user