Add initial shared code packages
This commit is contained in:
commit
838a97d344
54 files changed
+6265
No files matched your search
@@ -0,0 +1,153 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const PASSWORD_ITERATIONS = 100000;
|
||||
const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
|
||||
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,
|
||||
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 created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
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');
|
||||
}
|
||||
|
||||
/** 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))');
|
||||
}
|
||||
}
|
||||
|
||||
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, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, 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, 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.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 pruneExpiredSessions() {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE expires_at < now()');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user