|
| 1 | +import { randomBytes } from 'node:crypto' |
| 2 | + |
| 3 | +import { authAccounts, authSessions, authUsers, generateId } from '@afilmory/db' |
| 4 | +import { env } from '@afilmory/env' |
| 5 | +import { eq } from 'drizzle-orm' |
| 6 | + |
| 7 | +import { createConfiguredApp } from '../app.factory' |
| 8 | +import { DbAccessor, PgPoolProvider } from '../database/database.provider' |
| 9 | +import { logger } from '../helpers/logger.helper' |
| 10 | +import { AuthProvider } from '../modules/auth/auth.provider' |
| 11 | +import { RedisProvider } from '../redis/redis.provider' |
| 12 | + |
| 13 | +const RESET_FLAG = '--reset-superadmin-password' |
| 14 | +const PASSWORD_FLAG = '--password' |
| 15 | +const EMAIL_FLAG = '--email' |
| 16 | + |
| 17 | +export interface ResetCliOptions { |
| 18 | + password?: string |
| 19 | + email?: string |
| 20 | +} |
| 21 | + |
| 22 | +export function parseResetCliArgs(args: readonly string[]): ResetCliOptions | null { |
| 23 | + const hasResetFlag = args.some((arg) => arg === RESET_FLAG || arg.startsWith(`${RESET_FLAG}=`)) |
| 24 | + if (!hasResetFlag) { |
| 25 | + return null |
| 26 | + } |
| 27 | + |
| 28 | + let password: string | undefined |
| 29 | + let email: string | undefined |
| 30 | + |
| 31 | + for (let index = 0; index < args.length; index++) { |
| 32 | + const arg = args[index] |
| 33 | + if (!arg || arg === '--') { |
| 34 | + continue |
| 35 | + } |
| 36 | + |
| 37 | + if (arg === RESET_FLAG) { |
| 38 | + continue |
| 39 | + } |
| 40 | + |
| 41 | + if (arg.startsWith(`${RESET_FLAG}=`)) { |
| 42 | + const inline = arg.slice(RESET_FLAG.length + 1).trim() |
| 43 | + if (inline.length > 0) { |
| 44 | + password = inline |
| 45 | + } |
| 46 | + continue |
| 47 | + } |
| 48 | + |
| 49 | + if (arg === PASSWORD_FLAG) { |
| 50 | + const value = args[index + 1] |
| 51 | + if (!value || value.startsWith('--')) { |
| 52 | + throw new Error('Missing value for --password') |
| 53 | + } |
| 54 | + password = value |
| 55 | + index++ |
| 56 | + continue |
| 57 | + } |
| 58 | + |
| 59 | + if (arg.startsWith(`${PASSWORD_FLAG}=`)) { |
| 60 | + const value = arg.slice(PASSWORD_FLAG.length + 1).trim() |
| 61 | + if (value.length === 0) { |
| 62 | + throw new Error('Missing value for --password') |
| 63 | + } |
| 64 | + password = value |
| 65 | + continue |
| 66 | + } |
| 67 | + |
| 68 | + if (arg === EMAIL_FLAG) { |
| 69 | + const value = args[index + 1] |
| 70 | + if (!value || value.startsWith('--')) { |
| 71 | + throw new Error('Missing value for --email') |
| 72 | + } |
| 73 | + email = value |
| 74 | + index++ |
| 75 | + continue |
| 76 | + } |
| 77 | + |
| 78 | + if (arg.startsWith(`${EMAIL_FLAG}=`)) { |
| 79 | + const value = arg.slice(EMAIL_FLAG.length + 1).trim() |
| 80 | + if (value.length === 0) { |
| 81 | + throw new Error('Missing value for --email') |
| 82 | + } |
| 83 | + email = value |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return { password, email } |
| 88 | +} |
| 89 | + |
| 90 | +function generateRandomPassword(): string { |
| 91 | + return randomBytes(16).toString('base64url') |
| 92 | +} |
| 93 | + |
| 94 | +export async function handleResetSuperAdminPassword(options: ResetCliOptions): Promise<void> { |
| 95 | + const app = await createConfiguredApp({ |
| 96 | + globalPrefix: '/api', |
| 97 | + }) |
| 98 | + |
| 99 | + const container = app.getContainer() |
| 100 | + const poolProvider = container.resolve(PgPoolProvider) |
| 101 | + const redisProvider = container.resolve(RedisProvider) |
| 102 | + const authProvider = container.resolve(AuthProvider) |
| 103 | + const dbAccessor = container.resolve(DbAccessor) |
| 104 | + |
| 105 | + try { |
| 106 | + const auth = authProvider.getAuth() |
| 107 | + const context = await auth.$context |
| 108 | + const rawPassword = options.password ?? generateRandomPassword() |
| 109 | + const { minPasswordLength, maxPasswordLength } = context.password.config |
| 110 | + |
| 111 | + if (rawPassword.length < minPasswordLength || rawPassword.length > maxPasswordLength) { |
| 112 | + throw new Error(`Password must be between ${minPasswordLength} and ${maxPasswordLength} characters.`) |
| 113 | + } |
| 114 | + |
| 115 | + const hashedPassword = await context.password.hash(rawPassword) |
| 116 | + const db = dbAccessor.get() |
| 117 | + |
| 118 | + const targetEmail = options.email ?? env.DEFAULT_SUPERADMIN_EMAIL |
| 119 | + const now = new Date().toISOString() |
| 120 | + let resolvedEmail = targetEmail |
| 121 | + let revokedSessionsCount = 0 |
| 122 | + let credentialAccountCreated = false |
| 123 | + |
| 124 | + await db.transaction(async (tx) => { |
| 125 | + let superAdmin = await tx.query.authUsers.findFirst({ |
| 126 | + where: (users, { eq }) => eq(users.email, targetEmail), |
| 127 | + }) |
| 128 | + |
| 129 | + if (!superAdmin) { |
| 130 | + superAdmin = await tx.query.authUsers.findFirst({ |
| 131 | + where: (users, { eq }) => eq(users.role, 'superadmin'), |
| 132 | + }) |
| 133 | + } |
| 134 | + |
| 135 | + if (!superAdmin) { |
| 136 | + const message = options.email |
| 137 | + ? `No superadmin account found for email "${options.email}"` |
| 138 | + : 'No superadmin account found' |
| 139 | + throw new Error(message) |
| 140 | + } |
| 141 | + |
| 142 | + resolvedEmail = superAdmin.email |
| 143 | + |
| 144 | + const credentialAccount = await tx.query.authAccounts.findFirst({ |
| 145 | + where: (accounts, { eq, and }) => |
| 146 | + and(eq(accounts.userId, superAdmin.id), eq(accounts.providerId, 'credential')), |
| 147 | + }) |
| 148 | + |
| 149 | + if (credentialAccount) { |
| 150 | + await tx |
| 151 | + .update(authAccounts) |
| 152 | + .set({ password: hashedPassword, updatedAt: now }) |
| 153 | + .where(eq(authAccounts.id, credentialAccount.id)) |
| 154 | + } else { |
| 155 | + credentialAccountCreated = true |
| 156 | + await tx.insert(authAccounts).values({ |
| 157 | + id: generateId(), |
| 158 | + accountId: superAdmin.id, |
| 159 | + providerId: 'credential', |
| 160 | + userId: superAdmin.id, |
| 161 | + password: hashedPassword, |
| 162 | + createdAt: now, |
| 163 | + updatedAt: now, |
| 164 | + }) |
| 165 | + } |
| 166 | + |
| 167 | + await tx.update(authUsers).set({ updatedAt: now }).where(eq(authUsers.id, superAdmin.id)) |
| 168 | + |
| 169 | + const deletedSessions = await tx |
| 170 | + .delete(authSessions) |
| 171 | + .where(eq(authSessions.userId, superAdmin.id)) |
| 172 | + .returning({ id: authSessions.id }) |
| 173 | + |
| 174 | + revokedSessionsCount = deletedSessions.length |
| 175 | + }) |
| 176 | + |
| 177 | + logger.info( |
| 178 | + `Superadmin password reset for ${resolvedEmail}. ${credentialAccountCreated ? 'Credential account created.' : 'Credential account updated.'} Revoked ${revokedSessionsCount} sessions.`, |
| 179 | + ) |
| 180 | + |
| 181 | + process.stdout.write(`Superadmin credentials reset\n email: ${resolvedEmail}\n password: ${rawPassword}\n`) |
| 182 | + } finally { |
| 183 | + await app.close('cli') |
| 184 | + |
| 185 | + try { |
| 186 | + const pool = poolProvider.getPool() |
| 187 | + await pool.end() |
| 188 | + } catch (error) { |
| 189 | + logger.warn(`Failed to close PostgreSQL pool cleanly: ${String(error)}`) |
| 190 | + } |
| 191 | + |
| 192 | + try { |
| 193 | + const redis = redisProvider.getClient() |
| 194 | + redis.disconnect() |
| 195 | + } catch (error) { |
| 196 | + logger.warn(`Failed to disconnect Redis client cleanly: ${String(error)}`) |
| 197 | + } |
| 198 | + } |
| 199 | +} |
0 commit comments