import { createRequire } from 'node:module' import type { AuditRecord, AuthRepository, InvitationRecord, SessionRecord, UserRecord, } from './auth.js' interface QueryResult { rows: Record[] rowCount: number | null } interface PgClient { query(text: string, values?: unknown[]): Promise release(): void } interface PgPool { query(text: string, values?: unknown[]): Promise connect(): Promise end(): Promise } interface PgPoolConstructor { new (options: { connectionString: string; max?: number }): PgPool } const runtimeRequire = createRequire(import.meta.url) const { Pool } = runtimeRequire('pg') as { Pool: PgPoolConstructor } export class PostgresAuthRepository implements AuthRepository { readonly pool: PgPool constructor(databaseUrl: string) { this.pool = new Pool({ connectionString: databaseUrl, max: 10 }) } async findUserByAccount(account: string) { const result = await this.pool.query('SELECT * FROM users WHERE account = $1 LIMIT 1', [account]) return result.rows[0] ? userFromRow(result.rows[0]) : undefined } async findUserById(id: string) { const result = await this.pool.query('SELECT * FROM users WHERE id = $1 LIMIT 1', [id]) return result.rows[0] ? userFromRow(result.rows[0]) : undefined } async listUsers() { const result = await this.pool.query('SELECT * FROM users ORDER BY created_at DESC') return result.rows.map(userFromRow) } async createUser(user: UserRecord) { await this.pool.query( `INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at, last_login_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [user.id, user.account, user.accountKind, user.passwordHash, user.displayName, user.role, user.status, user.createdAt, user.updatedAt, user.lastLoginAt ?? null], ) } async createInvitedUser(user: UserRecord, invitationId: string, at: string) { const client = await this.pool.connect() try { await client.query('BEGIN') const invitationResult = await client.query( `SELECT * FROM invitation_codes WHERE id = $1 AND disabled_at IS NULL AND used_count < max_uses AND (expires_at IS NULL OR expires_at > $2) FOR UPDATE`, [invitationId, at], ) if (!invitationResult.rows[0]) { await client.query('ROLLBACK') return false } await client.query( `INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at, last_login_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [user.id, user.account, user.accountKind, user.passwordHash, user.displayName, user.role, user.status, user.createdAt, user.updatedAt, user.lastLoginAt ?? null], ) await client.query( 'INSERT INTO invitation_redemptions (invitation_id, user_id, redeemed_at) VALUES ($1, $2, $3)', [invitationId, user.id, at], ) await client.query('UPDATE invitation_codes SET used_count = used_count + 1 WHERE id = $1', [invitationId]) await client.query('COMMIT') return true } catch (error) { await client.query('ROLLBACK') if (isUniqueViolation(error)) return false throw error } finally { client.release() } } async updateLastLogin(userId: string, at: string) { await this.pool.query('UPDATE users SET last_login_at = $2, updated_at = $2 WHERE id = $1', [userId, at]) } async findInvitationByHash(codeHash: string) { const result = await this.pool.query('SELECT * FROM invitation_codes WHERE code_hash = $1 LIMIT 1', [codeHash]) return result.rows[0] ? invitationFromRow(result.rows[0]) : undefined } async createInvitation(invitation: InvitationRecord) { await this.pool.query( `INSERT INTO invitation_codes (id, code_hash, code_prefix, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [invitation.id, invitation.codeHash, invitation.codePrefix, invitation.label, invitation.maxUses, invitation.usedCount, invitation.expiresAt ?? null, invitation.disabledAt ?? null, invitation.createdBy, invitation.createdAt], ) } async listInvitations() { const result = await this.pool.query('SELECT * FROM invitation_codes ORDER BY created_at DESC') return result.rows.map(invitationFromRow) } async revokeInvitation(invitationId: string, at: string) { const result = await this.pool.query( 'UPDATE invitation_codes SET disabled_at = $2 WHERE id = $1 AND disabled_at IS NULL', [invitationId, at], ) return result.rowCount === 1 } async createSession(session: SessionRecord) { await this.pool.query( `INSERT INTO auth_sessions (id, token_hash, user_id, expires_at, revoked_at, created_at, last_seen_at, user_agent, ip_address) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, [session.id, session.tokenHash, session.userId, session.expiresAt, session.revokedAt ?? null, session.createdAt, session.lastSeenAt, session.userAgent ?? null, session.ipAddress ?? null], ) } async findSessionByHash(tokenHash: string) { const result = await this.pool.query('SELECT * FROM auth_sessions WHERE token_hash = $1 LIMIT 1', [tokenHash]) return result.rows[0] ? sessionFromRow(result.rows[0]) : undefined } async revokeSession(sessionId: string, at: string) { await this.pool.query('UPDATE auth_sessions SET revoked_at = $2, last_seen_at = $2 WHERE id = $1', [sessionId, at]) } async createAudit(record: AuditRecord) { await this.pool.query( `INSERT INTO auth_audit_log (actor_user_id, event_type, target_type, target_id, ip_address, user_agent, details, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)`, [record.actorUserId ?? null, record.eventType, record.targetType ?? null, record.targetId ?? null, record.ipAddress ?? null, record.userAgent ?? null, JSON.stringify(record.details), record.createdAt], ) } async listAudit(limit: number) { const result = await this.pool.query('SELECT * FROM auth_audit_log ORDER BY created_at DESC LIMIT $1', [limit]) return result.rows.map(auditFromRow) } async close() { await this.pool.end() } } function userFromRow(row: Record): UserRecord { return { id: String(row.id), account: String(row.account), accountKind: row.account_kind as UserRecord['accountKind'], passwordHash: String(row.password_hash), displayName: String(row.display_name), role: row.role as UserRecord['role'], status: row.status as UserRecord['status'], createdAt: new Date(String(row.created_at)).toISOString(), updatedAt: new Date(String(row.updated_at)).toISOString(), ...(row.last_login_at ? { lastLoginAt: new Date(String(row.last_login_at)).toISOString() } : {}), } } function invitationFromRow(row: Record): InvitationRecord { return { id: String(row.id), codeHash: String(row.code_hash), codePrefix: String(row.code_prefix), label: String(row.label), maxUses: Number(row.max_uses), usedCount: Number(row.used_count), ...(row.expires_at ? { expiresAt: new Date(String(row.expires_at)).toISOString() } : {}), ...(row.disabled_at ? { disabledAt: new Date(String(row.disabled_at)).toISOString() } : {}), createdBy: String(row.created_by), createdAt: new Date(String(row.created_at)).toISOString(), } } function sessionFromRow(row: Record): SessionRecord { return { id: String(row.id), tokenHash: String(row.token_hash), userId: String(row.user_id), expiresAt: new Date(String(row.expires_at)).toISOString(), ...(row.revoked_at ? { revokedAt: new Date(String(row.revoked_at)).toISOString() } : {}), createdAt: new Date(String(row.created_at)).toISOString(), lastSeenAt: new Date(String(row.last_seen_at)).toISOString(), ...(row.user_agent ? { userAgent: String(row.user_agent) } : {}), ...(row.ip_address ? { ipAddress: String(row.ip_address) } : {}), } } function auditFromRow(row: Record): AuditRecord { return { id: String(row.id), ...(row.actor_user_id ? { actorUserId: String(row.actor_user_id) } : {}), eventType: String(row.event_type), ...(row.target_type ? { targetType: String(row.target_type) } : {}), ...(row.target_id ? { targetId: String(row.target_id) } : {}), ...(row.ip_address ? { ipAddress: String(row.ip_address) } : {}), ...(row.user_agent ? { userAgent: String(row.user_agent) } : {}), details: (row.details || {}) as Record, createdAt: new Date(String(row.created_at)).toISOString(), } } function isUniqueViolation(error: unknown): boolean { return Boolean(error && typeof error === 'object' && 'code' in error && error.code === '23505') }