refactor: add input length guards for add/edit/import flows

This commit is contained in:
Xiaolan Bot
2026-02-22 11:07:42 +08:00
parent 276bb5fc83
commit 095e88cad3

View File

@@ -252,6 +252,9 @@ EDITABLE_SUB_FIELDS = {
'renewal_type': 'renewal_type',
'notes': 'notes'
}
MAX_NAME_LEN = 128
MAX_CATEGORY_LEN = 64
MAX_NOTES_LEN = 1000
def _build_category_callback_data(category_id: int) -> str:
@@ -553,12 +556,18 @@ async def import_upload_received(update: Update, context: CallbackContext):
if renewal_type not in valid_renewal_types:
raise ValueError(f"无效续费类型: {renewal_type}")
notes = str(row['notes']).strip() if pd.notna(row['notes']) else None
if notes and len(notes) > MAX_NOTES_LEN:
raise ValueError(f"备注过长(>{MAX_NOTES_LEN}")
name = str(row['name']).strip()
category = str(row['category']).strip()
if not name:
raise ValueError("名称不能为空")
if not category:
raise ValueError("类别不能为空")
if len(name) > MAX_NAME_LEN:
raise ValueError(f"名称过长(>{MAX_NAME_LEN}")
if len(category) > MAX_CATEGORY_LEN:
raise ValueError(f"类别过长(>{MAX_CATEGORY_LEN}")
records.append((
user_id, name, cost, currency, category,
next_due, frequency_unit, frequency_value, renewal_type, notes
@@ -601,6 +610,9 @@ async def add_name_received(update: Update, context: CallbackContext):
if not name:
await update.message.reply_text("订阅名称不能为空。")
return ADD_NAME
if len(name) > MAX_NAME_LEN:
await update.message.reply_text(f"订阅名称过长,请控制在 {MAX_NAME_LEN} 个字符以内。")
return ADD_NAME
context.user_data['new_sub_data']['name'] = name
await update.message.reply_text("第二步:请输入订阅 *费用*", parse_mode='MarkdownV2')
return ADD_COST
@@ -634,6 +646,9 @@ async def add_category_received(update: Update, context: CallbackContext):
if not category_name:
await update.message.reply_text("类别不能为空。")
return ADD_CATEGORY
if len(category_name) > MAX_CATEGORY_LEN:
await update.message.reply_text(f"类别名称过长,请控制在 {MAX_CATEGORY_LEN} 个字符以内。")
return ADD_CATEGORY
context.user_data['new_sub_data']['category'] = category_name
with get_db_connection() as conn:
cursor = conn.cursor()
@@ -701,6 +716,9 @@ async def add_notes_received(update: Update, context: CallbackContext):
await update.message.reply_text("发生错误,请重试。")
return ConversationHandler.END
note = update.message.text.strip()
if len(note) > MAX_NOTES_LEN:
await update.message.reply_text(f"备注过长,请控制在 {MAX_NOTES_LEN} 个字符以内。")
return ADD_NOTES
sub_data['notes'] = note if note else None
save_subscription(update.effective_user.id, sub_data)
await update.message.reply_text(text=f"✅ 订阅 '{escape_markdown(sub_data.get('name', ''), version=2)}' 已添加!",
@@ -1170,6 +1188,10 @@ async def edit_new_value_received(update: Update, context: CallbackContext):
if message_to_reply:
await message_to_reply.reply_text("类别不能为空。")
validation_failed = True
elif len(new_value) > MAX_CATEGORY_LEN:
if message_to_reply:
await message_to_reply.reply_text(f"类别名称过长,请控制在 {MAX_CATEGORY_LEN} 个字符以内。")
validation_failed = True
else:
with get_db_connection() as conn:
cursor = conn.cursor()