Spaces:
Build error
Build error
File size: 11,389 Bytes
0bfe2e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
// import { UserDataSchema, UserData, DB } from '../db';
import { UserDataSchema, UserData } from './schemas';
import { TransactionQueue } from './queue';
import { DB } from './db';
import {
decryptString,
deriveKey,
encryptString,
generateUUID,
getTextHash,
maskSensitiveInfo,
createLogger,
constants,
Env,
verifyHash,
validateConfig,
formatZodError,
} from '../utils';
const APIError = constants.APIError;
const logger = createLogger('users');
const db = DB.getInstance();
const txQueue = TransactionQueue.getInstance();
export class UserRepository {
static async createUser(
config: UserData,
password: string
): Promise<{ uuid: string; encryptedPassword: string }> {
return txQueue.enqueue(async () => {
if (password.length < 6) {
return Promise.reject(
new APIError(constants.ErrorCode.USER_NEW_PASSWORD_TOO_SHORT)
);
}
let validatedConfig: UserData;
if (Env.ADDON_PASSWORD && config.addonPassword !== Env.ADDON_PASSWORD) {
return Promise.reject(
new APIError(constants.ErrorCode.USER_INVALID_PASSWORD)
);
}
config.trusted = false;
try {
// don't skip errors, but don't decrypt credentials
// as we need to store the encrypted version
validatedConfig = await validateConfig(config, false, false);
} catch (error: any) {
logger.error(`Invalid config for new user: ${error.message}`);
return Promise.reject(
new APIError(
constants.ErrorCode.USER_INVALID_CONFIG,
undefined,
error.message
)
);
}
const uuid = await this.generateUUID();
const { encryptedConfig, salt: configSalt } = await this.encryptConfig(
validatedConfig,
password
);
const hashedPassword = await getTextHash(password);
const { success, data } = encryptString(password);
if (success === false) {
return Promise.reject(constants.ErrorCode.USER_ERROR);
}
const encryptedPassword = data;
let tx;
let committed = false;
try {
tx = await db.begin();
await tx.execute(
'INSERT INTO users (uuid, password_hash, config, config_salt) VALUES (?, ?, ?, ?)',
[uuid, hashedPassword, encryptedConfig, configSalt]
);
await tx.commit();
committed = true;
logger.info(`Created a new user with UUID: ${uuid}`);
return { uuid, encryptedPassword };
} catch (error) {
logger.error(
`Failed to create user: ${error instanceof Error ? error.message : String(error)}`
);
if (error instanceof APIError) {
throw error;
}
throw new APIError(constants.ErrorCode.INTERNAL_SERVER_ERROR);
} finally {
if (tx && !committed) {
await tx.rollback();
}
}
});
}
static async checkUserExists(uuid: string): Promise<boolean> {
try {
const result = await db.query('SELECT uuid FROM users WHERE uuid = ?', [
uuid,
]);
return result.length > 0;
} catch (error) {
logger.error(`Error checking user existence: ${error}`);
return Promise.reject(constants.ErrorCode.USER_ERROR);
}
}
// with stremio auth, we are given the encrypted password
// with api use, we are given the password
// GET /user should also return
static async getUser(
uuid: string,
password: string
): Promise<UserData | null> {
try {
const result = await db.query(
'SELECT config, config_salt, password_hash FROM users WHERE uuid = ?',
[uuid]
);
if (!result.length || !result[0].config) {
return Promise.reject(new APIError(constants.ErrorCode.USER_NOT_FOUND));
}
await db.execute(
'UPDATE users SET accessed_at = CURRENT_TIMESTAMP WHERE uuid = ?',
[uuid]
);
const isValid = await this.verifyUserPassword(
password,
result[0].password_hash
);
if (!isValid) {
return Promise.reject(
new APIError(constants.ErrorCode.USER_INVALID_PASSWORD)
);
}
const decryptedConfig = await this.decryptConfig(
result[0].config,
password,
result[0].config_salt
);
// try {
// // skip errors, and dont decrypt credentials either, as this would make
// // encryption pointless
// validatedConfig = await validateConfig(decryptedConfig, true, false);
// } catch (error: any) {
// return Promise.reject(
// new APIError(
// constants.ErrorCode.USER_INVALID_CONFIG,
// undefined,
// error.message
// )
// );
// }
// const {
// success,
// data: validatedConfig,
// error,
// } = UserDataSchema.safeParse(decryptedConfig);
// if (!success) {
// return Promise.reject(
// new APIError(
// constants.ErrorCode.USER_INVALID_CONFIG,
// undefined,
// formatZodError(error)
// )
// );
// }
decryptedConfig.trusted =
Env.TRUSTED_UUIDS?.split(',').some((u) => new RegExp(u).test(uuid)) ??
false;
logger.info(`Retrieved configuration for user ${uuid}`);
return decryptedConfig;
} catch (error) {
logger.error(
`Error retrieving user ${uuid}: ${error instanceof Error ? error.message : String(error)}`
);
return Promise.reject(
new APIError(constants.ErrorCode.INTERNAL_SERVER_ERROR)
);
}
}
static async updateUser(
uuid: string,
password: string,
config: UserData
): Promise<void> {
return txQueue.enqueue(async () => {
let tx;
let committed = false;
try {
tx = await db.begin();
const currentUser = await tx.execute(
'SELECT config_salt, password_hash FROM users WHERE uuid = ?',
[uuid]
);
if (!currentUser.rows.length) {
throw new APIError(constants.ErrorCode.USER_NOT_FOUND);
}
if (Env.ADDON_PASSWORD && config.addonPassword !== Env.ADDON_PASSWORD) {
throw new APIError(
constants.ErrorCode.USER_INVALID_PASSWORD,
undefined,
'Invalid password'
);
}
let validatedConfig: UserData;
try {
validatedConfig = await validateConfig(config, false, false);
} catch (error: any) {
throw new APIError(
constants.ErrorCode.USER_INVALID_CONFIG,
undefined,
error.message
);
}
const storedHash = currentUser.rows[0].password_hash;
const isValid = await this.verifyUserPassword(password, storedHash);
if (!isValid) {
throw new APIError(constants.ErrorCode.USER_INVALID_PASSWORD);
}
const { encryptedConfig } = await this.encryptConfig(
validatedConfig,
password,
currentUser.rows[0].config_salt
);
await tx.execute(
'UPDATE users SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE uuid = ?',
[encryptedConfig, uuid]
);
await tx.commit();
committed = true;
logger.info(`Updated user ${uuid} with an updated configuration`);
} catch (error) {
logger.error(
`Failed to update user ${uuid}: ${error instanceof Error ? error.message : String(error)}`
);
if (error instanceof APIError) {
throw error;
}
throw new APIError(constants.ErrorCode.INTERNAL_SERVER_ERROR);
} finally {
if (tx && !committed) {
await tx.rollback();
}
}
});
}
static async getUserCount(): Promise<number> {
try {
const result = await db.query('SELECT * FROM users');
return result.length;
} catch (error) {
logger.error(`Error getting user count: ${error}`);
return Promise.reject(new APIError(constants.ErrorCode.USER_ERROR));
}
}
static async deleteUser(uuid: string): Promise<void> {
return txQueue.enqueue(async () => {
let tx;
let committed = false;
try {
tx = await db.begin();
const result = await tx.execute('DELETE FROM users WHERE uuid = ?', [
uuid,
]);
if (result.rowCount === 0) {
throw new APIError(constants.ErrorCode.USER_NOT_FOUND);
}
await tx.commit();
committed = true;
logger.info(`Deleted user ${uuid}`);
} catch (error) {
logger.error(
`Failed to delete user ${uuid}: ${error instanceof Error ? error.message : String(error)}`
);
if (error instanceof APIError) {
throw error;
}
throw new APIError(constants.ErrorCode.INTERNAL_SERVER_ERROR);
} finally {
if (tx && !committed) {
await tx.rollback();
}
}
});
}
static async pruneUsers(maxDays: number = 30): Promise<number> {
if (maxDays < 0) {
return 0;
}
try {
const query =
db.getDialect() === 'postgres'
? `DELETE FROM users WHERE accessed_at < NOW() - INTERVAL '${maxDays} days'`
: `DELETE FROM users WHERE accessed_at < datetime('now', '-' || ${maxDays} || ' days')`;
const result = await db.execute(query);
const deletedCount = result.changes || result.rowCount || 0;
logger.info(`Pruned ${deletedCount} users older than ${maxDays} days`);
return deletedCount;
} catch (error) {
logger.error('Failed to prune users:', error);
return Promise.reject(new APIError(constants.ErrorCode.USER_ERROR));
}
}
private static async verifyUserPassword(
password: string,
storedHash: string
): Promise<boolean> {
return verifyHash(password, storedHash);
}
private static async encryptConfig(
config: UserData,
password: string,
salt?: string
): Promise<{
encryptedConfig: string;
salt: string;
}> {
const { key, salt: saltUsed } = await deriveKey(
`${password}:${Env.SECRET_KEY}`,
salt
);
const configString = JSON.stringify(config);
const { success, data, error } = encryptString(configString, key);
if (!success) {
return Promise.reject(new APIError(constants.ErrorCode.USER_ERROR));
}
return { encryptedConfig: data, salt: saltUsed };
}
private static async decryptConfig(
encryptedConfig: string,
password: string,
salt: string
): Promise<UserData> {
const { key } = await deriveKey(`${password}:${Env.SECRET_KEY}`, salt);
const {
success,
data: decryptedString,
error,
} = decryptString(encryptedConfig, key);
if (!success || !decryptedString) {
return Promise.reject(new APIError(constants.ErrorCode.USER_ERROR));
}
return JSON.parse(decryptedString);
}
private static async generateUUID(count: number = 1): Promise<string> {
if (count > 10) {
return Promise.reject(new APIError(constants.ErrorCode.USER_ERROR));
}
const uuid = generateUUID();
const existingUser = await this.checkUserExists(uuid);
if (existingUser) {
return this.generateUUID(count + 1);
}
return uuid;
}
}
|