Yashraj
📎 1 file 9,370 chars
📄
pasted-code-1795036351047.txt
txt 322 lines
▶
# PROJECT: DIGITAL STORE – Advanced Secure Digital Store Bot

You are a senior full-stack developer, software architect, cybersecurity engineer, and automation specialist.

Your task is to design and develop a complete, production-ready digital store bot named **DIGITAL STORE**.

The bot must be modern, reliable, scalable, user-friendly, and extremely secure. Security must be implemented throughout the entire system, not just at login.

## 1. Main Objective

Build a fully functional digital store bot that allows users to:
- Browse digital products and services.
- View product details, pricing, and availability.
- Purchase digital products.
- Make secure payments.
- Receive their purchased products automatically.
- View order history and transaction details.
- Contact store support.
- Track order and payment status.

The system must include a powerful administrator dashboard for complete store management.

## 2. Security – Highest Priority

Security is mandatory for EVERY feature and operation.

Implement the following:

### Authentication & Access Control
- Secure administrator authentication.
- Role-Based Access Control (RBAC).
- Separate permissions for Owner, Admin, Moderator, Support Staff, and Customer.
- Multi-factor authentication (MFA/2FA) for administrators.
- Secure session management.
- Automatic session expiration.
- Login attempt limits.
- Brute-force protection.
- Secure password hashing using Argon2id or an equivalent modern algorithm.
- Secure password reset functionality.

### Bot Security
- Prevent unauthorized command execution.
- Validate every command and interaction.
- Restrict sensitive commands to authorized roles.
- Prevent command injection.
- Prevent privilege escalation.
- Protect against malicious users and automated abuse.
- Implement rate limiting and cooldowns.
- Validate all user inputs.
- Prevent unauthorized access to bot configuration.
- Never expose API keys, tokens, passwords, or internal credentials.

### Payment & Transaction Security
- Use trusted payment gateways.
- Verify payment status directly through the payment provider.
- Never trust screenshots or user-submitted payment confirmations.
- Verify payment webhook signatures.
- Prevent duplicate transactions.
- Prevent double delivery.
- Implement idempotency for payment and order operations.
- Maintain complete transaction logs.
- Never mark an order as paid without verified payment confirmation.

### Database Security
- Use secure database connections.
- Encrypt sensitive information.
- Use parameterized queries and ORM protections.
- Prevent SQL injection.
- Implement database access permissions.
- Perform automated backups.
- Support database restoration.
- Never store raw passwords or payment credentials.

### Additional Protection
- HTTPS/TLS wherever applicable.
- CSRF protection for web dashboards.
- XSS protection.
- SSRF protection.
- Secure file uploads.
- Malware and suspicious-file validation.
- API authentication and authorization.
- Audit logs for sensitive actions.
- IP-based abuse detection where appropriate.
- Secrets stored in environment variables or a secure secrets manager.
- Secure error handling without leaking internal information.

## 3. Customer Features

Create a professional customer experience with:

- Main store menu.
- Product categories.
- Product search.
- Product descriptions and images.
- Product pricing.
- Stock and availability indicators.
- Shopping cart.
- Secure checkout.
- Order confirmation.
- Automatic product delivery.
- Purchase history.
- Transaction history.
- Order tracking.
- Refund request system.
- Customer support.
- Notifications.
- User account management.

## 4. Administrator Features

Create a complete administrative management system.

Administrators should be able to:

- Add, edit, and delete products.
- Create and manage product categories.
- Update product prices.
- Manage digital product inventory.
- Manage orders.
- Approve or reject eligible refund requests.
- View transactions.
- Manage customers.
- Ban or suspend abusive accounts.
- Create discount codes.
- Configure promotions.
- Manage staff and permissions.
- View revenue and sales statistics.
- Monitor suspicious activity.
- View security logs.
- Configure payment gateways.
- Configure automatic delivery.
- Manage store settings.

Every sensitive administrative action must require appropriate permissions and be recorded in an immutable or tamper-evident audit log.

## 5. Automatic Digital Product Delivery

The system must support automatic delivery of digital products after verified payment.

Supported product types:
- License keys.
- Activation codes.
- Digital files.
- Software downloads.
- Gift cards.
- Subscription details.
- Custom digital content.

Requirements:
- Secure inventory management.
- Unique product allocation.
- No duplicate delivery.
- Delivery status tracking.
- Retry mechanism for failed deliveries.
- Secure download links with expiration.
- Delivery logs.
- Protection against unauthorized downloads.

## 6. Payment System

Design a modular payment system that can support suitable payment providers.

For India, consider:
- Razorpay.
- Cashfree.
- UPI through supported payment providers.

Requirements:
- Secure checkout.
- Payment verification.
- Webhook verification.
- Automatic order status updates.
- Refund management.
- Transaction receipts.
- Payment failure handling.

Do not implement fake payment verification or insecure manual payment shortcuts.

## 7. Dashboard & Analytics

Build a modern, responsive dashboard.

Include:
- Total revenue.
- Today's sales.
- Total orders.
- Pending orders.
- Completed orders.
- Failed transactions.
- Total customers.
- Best-selling products.
- Recent activities.
- Security alerts.
- Sales analytics and charts.

## 8. Technical Architecture

Choose a reliable, maintainable technology stack.

Suggested stack:
- Backend: Python FastAPI or Node.js.
- Frontend: React / Next.js.
- Database: PostgreSQL.
- Cache and queues: Redis.
- ORM: SQLAlchemy or Prisma.
- Authentication: Secure session-based authentication or appropriately implemented token authentication.
- Deployment: Docker.
- Reverse proxy: Nginx.

Use modular architecture with separate services for:
- Authentication.
- Customers.
- Products.
- Orders.
- Payments.
- Digital delivery.
- Notifications.
- Administration.
- Security monitoring.

## 9. Reliability & Performance

- Handle concurrent purchases safely.
- Prevent race conditions.
- Use database transactions.
- Implement proper error handling.
- Add structured logging.
- Implement health checks.
- Support graceful shutdown.
- Use background jobs for long-running tasks.
- Add automated tests.
- Make the system scalable.

## 10. Testing & Security Auditing

Before considering the project complete, perform:

- Authentication testing.
- Authorization testing.
- API security testing.
- SQL injection testing.
- XSS testing.
- CSRF testing.
- Payment manipulation testing.
- Duplicate purchase testing.
- Double-delivery testing.
- Rate-limit testing.
- Session security testing.
- File upload security testing.
- Database backup and recovery testing.

Fix all critical and high-severity vulnerabilities before deployment.

## 11. UI/UX Design

Brand name: **DIGITAL STORE**

Design requirements:
- Professional digital-commerce appearance.
- Modern dark-themed interface.
- Clean navigation.
- Responsive desktop and mobile layouts.
- Smooth animations.
- Clear buttons and notifications.
- Consistent branding.
- Professional product cards.
- Modern admin dashboard.

Do not create a generic-looking unfinished interface.

## 12. Development Rules

IMPORTANT:

1. Build a genuinely working application, not just a UI prototype.
2. Do not leave placeholder buttons or fake functionality.
3. Do not hardcode API keys, passwords, or secrets.
4. Do not skip security checks for convenience.
5. Do not expose internal errors to customers.
6. Do not trust client-side validation alone.
7. Implement server-side validation for every sensitive operation.
8. Create database migrations.
9. Provide an example environment configuration without real secrets.
10. Include installation and deployment documentation.
11. Include a complete README.
12. Include automated tests.
13. Explain how to configure payment gateways.
14. Include secure backup and recovery instructions.

## 13. Final Deliverables

Deliver a complete project containing:

- Fully functional DIGITAL STORE bot.
- Complete source code.
- Backend and frontend.
- Database schema and migrations.
- Admin dashboard.
- Secure authentication.
- Payment integration.
- Automatic digital product delivery.
- Security and audit logging.
- Automated tests.
- Docker configuration.
- Environment configuration template.
- Installation guide.
- Deployment guide.
- README documentation.

## FINAL INSTRUCTION

Work as a professional development team.

First analyze the requirements, create the architecture, and establish a security plan. Then develop the application module by module.

Test every major feature before moving forward.

Do not claim a feature is complete until it has been implemented and tested.

**The highest priority is security, followed by reliability, correct functionality, and user experience.**

The final result must be a real, production-ready digital commerce platform named DIGITAL STORE.
Kodari AI
KodariWed at 9:18 pm 4
DigitalStoreBot
A comprehensive Discord bot for digital product sales with secure admin dashboard. Features include product catalog browsing, categorized listings, shopping cart, verified payment processing through Razorpay/Cashfree, automatic digital product delivery, order tracking, and refund management. Implements RBAC with MFA for staff, rate limiting, audit logging, and secure session handling. Includes customer support tickets, purchase history, transaction logs, and real-time notifications. Admin panel manages inventory, pricing, discounts, staff permissions, and sales analytics with revenue statistics and security monitoring.

I’ll build the store around verified Razorpay payments, encrypted inventory, transactional allocation, and Discord-based access controls. I’ll also identify any requirements that aren’t implemented or independently security-audited rather than presenting them as production-ready.

Built an initial DIGITAL STORE bot with Razorpay payment verification, encrypted inventory, private order delivery, refund requests, and owner-only inventory commands.

This is not production-ready or the complete platform requested. The dashboard, full RBAC/MFA, automated refunds, file delivery, backups, and several other features remain unimplemented. The included tests were not run, and no security audit was performed.

Configure the Razorpay webhook at https://0hfw6vs2.kodaribots.com/webhooks/razorpay. Setup and limitations are documented in README.md.

Kodari can make mistakes. Review important code before using.
Files
tests
.gitignore
bot.py
Dockerfile
README.md
requirements.txt
store.py
Code
7 481
bot.py
import asyncio
import logging
import os
import time

import aiohttp
from aiohttp import web
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv

from store import Store, verify_signature

load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s %(message)s')
log = logging.getLogger('digital-store')

required = ('DISCORD_TOKEN', 'OWNER_IDS', 'RAZORPAY_KEY_ID', 'RAZORPAY_KEY_SECRET', 'RAZORPAY_WEBHOOK_SECRET', 'INVENTORY_ENCRYPTION_KEY')
if any(not os.getenv(name) or os.getenv(name) == 'your_discord_bot_token_here' for name in required):
    raise RuntimeError('Set all required environment variables before starting.')
owners = {int(value.strip()) for value in os.environ['OWNER_IDS'].split(',') if value.strip()}
store = Store(os.getenv('DATABASE_PATH', 'store.db'), os.environ['INVENTORY_ENCRYPTION_KEY'])


class StoreBot(commands.Bot):
    async def setup_hook(self):
        self.http_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=15), auth=aiohttp.BasicAuth(os.environ['RAZORPAY_KEY_ID'], os.environ['RAZORPAY_KEY_SECRET']))
        app = web.Application(client_max_size=128 * 1024)
        app.router.add_post('/webhooks/razorpay', webhook)
        app.router.add_get('/health', lambda request: web.Response(text='ok'))
        self.runner = web.AppRunner(app, access_log=None)
        await self.runner.setup()
        await web.TCPSite(self.runner, '0.0.0.0', int(os.getenv('SERVER_PORT', '8080'))).start()
        await self.tree.sync()

    async def close(self):
        await self.runner.cleanup()
        await self.http_session.close()
        store.db.close()
        await super().close()


bot = StoreBot(command_prefix='!', intents=discord.Intents.default())


@bot.event
async def on_ready():
    log.info('Connected as %s', bot.user)
    print('KODARI_READY', flush=True)


async def razorpay(method, path, data=None):
    async with bot.http_session.request(method, 'https://api.razorpay.com/v1/' + path, json=data, allow_redirects=False) as response:
        if response.status >= 400:
            log.error('Razorpay returned HTTP %s for %s', response.status, path.split('/')[0])
            raise RuntimeError('Payment provider request failed.')
        return await response.json()


async def webhook(request):
    body = await request.read()
    if not verify_signature(os.environ['RAZORPAY_WEBHOOK_SECRET'], body, request.headers.get('X-Razorpay-Signature')):
        return web.Response(status=401)
    try:
        payload = await request.json()
        if payload.get('event') != 'payment_link.paid':
            return web.Response(status=200)
        entity = payload['payload']['payment_link']['entity']
        link_id = entity['id']
        link = await razorpay('GET', 'payment_links/' + link_id)
        if link['status'] != 'paid' or link['amount_paid'] != link['amount']:
            return web.Response(status=409)
        payments = link.get('payments') or []
        if len(payments) != 1:
            log.warning('Payment link %s requires manual review: unexpected payment count', link_id)
            return web.Response(status=409)
        payment = await razorpay('GET', 'payments/' + payments[0]['payment_id'])
        if payment['status'] != 'captured' or payment['amount'] != link['amount'] or payment['currency'] != link['currency']:
            return web.Response(status=409)
        order_id = link['reference_id']
        newly_paid = store.confirm_payment(order_id, link_id, link['amount'], link['currency'], payment['id'])
        if newly_paid:
            row = store.db.execute('SELECT user_id FROM orders WHERE id=?', (order_id,)).fetchone()
            try:
                user = await bot.fetch_user(row['user_id'])
                await user.send(f'Your DIGITAL STORE order `{order_id}` is paid. Use `/delivery order_id:{order_id}` to retrieve your item privately.')
            except discord.HTTPException:
                log.warning('Could not notify customer for order %s', order_id)
        return web.Response(status=200)
    except (KeyError, ValueError, TypeError):
        log.warning('Rejected invalid payment webhook')
        return web.Response(status=400)
    except Exception:
        log.exception('Webhook processing failed')
        return web.Response(status=500)


def owner_only():
    async def predicate(interaction):
        return interaction.user.id in owners
    return app_commands.check(predicate)


@bot.tree.command(description='Browse or search DIGITAL STORE products')
@app_commands.checks.cooldown(3, 10.0, key=lambda i: i.user.id)
async def shop(interaction: discord.Interaction, search: str = ''):
    products = store.products(search[:100])
    embed = discord.Embed(title='DIGITAL STORE', description='Browse products and use /buy to check out.', color=0x8b5cf6)
    for p in products:
        embed.add_field(name=f"#{p['id']} · {p['name']} · ₹{p['price']/100:.2f}", value=f"{p['category']} · {p['stock']} available\n{p['description']}", inline=False)
    if not products:
        embed.description = 'No products found.'
    await interaction.response.send_message(embed=embed, ephemeral=True)


@bot.tree.command(description='Purchase one product securely through Razorpay')
@app_commands.checks.cooldown(1, 20.0, key=lambda i: i.user.id)
async def buy(interaction: discord.Interaction, product_id: int):
    await interaction.response.defer(ephemeral=True, thinking=True)
    try:
        order = store.create_order(interaction.user.id, product_id)
    except ValueError as exc:
        await interaction.followup.send(str(exc), ephemeral=True)
        return
    try:
        link = await razorpay('POST', 'payment_links', {'amount': order['amount'], 'currency': 'INR', 'accept_partial': False, 'reference_id': order['id'], 'description': 'DIGITAL STORE order ' + order['id'], 'expire_by': int(time.time()) + 3600, 'reminder_enable': False})
        store.attach_link(order['id'], link['id'], link['short_url'])
    except Exception:
        # A timed-out provider request may still have created a payable link; retain the reservation for reconciliation.
        log.exception('Payment-link creation uncertain for order %s', order['id'])
        await interaction.followup.send(f'Checkout could not be completed. Contact support with order `{order["id"]}`.', ephemeral=True)
        return
    await interaction.followup.send(f'Order `{order["id"]}`: [Pay securely with Razorpay]({link["short_url"]}). Use /orders to track it.', ephemeral=True)


@bot.tree.command(description='View your recent orders and payment status')
async def orders(interaction: discord.Interaction):
    rows = store.db.execute('SELECT id,amount,status,created FROM orders WHERE user_id=? ORDER BY created DESC LIMIT 15', (interaction.user.id,)).fetchall()
    text = '\n'.join(f"`{r['id']}` · ₹{r['amount']/100:.2f} · {r['status']}" for r in rows) or 'No orders yet.'
    await interaction.response.send_message(text, ephemeral=True)


@bot.tree.command(description='Retrieve your paid digital item privately')
@app_commands.checks.cooldown(3, 10.0, key=lambda i: i.user.id)
async def delivery(interaction: discord.Interaction, order_id: str):
    content = store.get_delivery(interaction.user.id, order_id)
    await interaction.response.send_message(content if content else 'No paid delivery found for this order.', ephemeral=True, allowed_mentions=discord.AllowedMentions.none())


@bot.tree.command(description='Request review of a paid order refund')
@app_commands.checks.cooldown(2, 60.0, key=lambda i: i.user.id)
async def refund_request(interaction: discord.Interaction, order_id: str, reason: str):
    try:
        store.request_refund(interaction.user.id, order_id, reason)
        await interaction.response.send_message('Refund request recorded for staff review; this does not issue a refund.', ephemeral=True)
    except ValueError as exc:
        await interaction.response.send_message(str(exc), ephemeral=True)


@bot.tree.command(description='Get help with DIGITAL STORE')
async def store_help(interaction: discord.Interaction):
    await interaction.response.send_message('Use /shop to browse, /buy to check out, /orders to track purchases, /delivery to retrieve an item, and /refund_request to request a review. Contact the server staff for support.', ephemeral=True)


@bot.tree.command(description='Owner: create a product; price is in paise')
@owner_only()
async def product_add(interaction: discord.Interaction, name: str, category: str, description: str, price_paise: int):
    try:
        product_id = store.add_product(interaction.user.id, name, category, description, price_paise)
        await interaction.response.send_message(f'Created product #{product_id}.', ephemeral=True)
    except ValueError as exc:
        await interaction.response.send_message(str(exc), ephemeral=True)


@bot.tree.command(description='Owner: add one private inventory item through a modal')
@owner_only()
async def stock_add(interaction: discord.Interaction, product_id: int):
    class StockModal(discord.ui.Modal, title='Add digital inventory'):
        content = discord.ui.TextInput(label='Secret item content', style=discord.TextStyle.paragraph, max_length=1500)

        async def on_submit(self, modal_interaction: discord.Interaction):
            if modal_interaction.user.id not in owners:
                await modal_interaction.response.send_message('Not authorized.', ephemeral=True)
                return
            try:
                store.add_stock(modal_interaction.user.id, product_id, str(self.content))
                await modal_interaction.response.send_message('Inventory item encrypted and added.', ephemeral=True)
            except ValueError as exc:
                await modal_interaction.response.send_message(str(exc), ephemeral=True)
    await interaction.response.send_modal(StockModal())


@bot.tree.command(description='Owner: view recent refund requests')
@owner_only()
async def refund_queue(interaction: discord.Interaction):
    rows = store.db.execute("SELECT id,order_id,reason FROM refunds WHERE status='requested' ORDER BY created LIMIT 10").fetchall()
    text = '\n'.join(f"#{r['id']} · `{r['order_id']}` · {r['reason'][:120]}" for r in rows) or 'No open requests.'
    await interaction.response.send_message(text, ephemeral=True, allowed_mentions=discord.AllowedMentions.none())