Skip to content
yanstd888Public

About

Self-hosted AI marketplace, token billing engine & OpenAI-compatible Go API gateway with atomic PostgreSQL ledger, escrow commerce, and Stripe/DOKU/QRIS payments.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

32 stars

Watchers

3 watching

Forks

Repository files navigation

Node2Mint — AI Sell Modern

🪙 Node2Mint — AI Sell Modern

Node2Mint - Self-Hosted Digital Marketplace, Token Billing Engine & OpenAI API Gateway

Self-hosted AI marketplace, token billing engine, and OpenAI-compatible API gateway with atomic ledger balances, provider failover, and affiliate distribution.

A production-ready full-stack platform built with Next.js 15, Go 1.22, PostgreSQL 16, Redis 7, and Caddy 2 for selling digital products, token packs, and routing AI model access.

License MIT Go 1.22+ Next.js 15 PostgreSQL 16 Redis 7 Docker Compose

OpenAI Compatible Payments AICLUB Ecosystem Sponsor Yanstd

Why Node2Mint · Features · Architecture · Quick Start · API Reference · Configuration · Deployment · Security · Bahasa Indonesia


⚡ Why Node2Mint?

Running an AI model reselling service or token marketplace requires strict ledger safety. Distributed billing systems frequently suffer from race conditions, double-spending, and upstream provider outages. Node2Mint solves these engineering challenges by combining a high-concurrency Go 1.22 API gateway with an atomic PostgreSQL 16 transaction model:

  • 🔒 Atomic Money & Token Balances: All balance debits and credits use row-level database locking (SELECT FOR UPDATE) within strict transaction boundaries—eliminating negative-balance race conditions.
  • 🔄 Automated Provider Failover: Outbound AI chat completions automatically route through active upstream providers (OpenAI, Anthropic, custom endpoints) with health checks and circuit breaker fallback.
  • 🔑 Hashed Credentials (Zero Plaintext): User API keys are stored exclusively as SHA-256 hashes. Full keys are displayed only once upon creation and never stored in plaintext.
  • 💳 Multi-Channel Global & Local Payments: Native support for card/e-wallet gateways (Stripe, DOKU), manual QRIS / Bank Transfers with admin verification workflows, and optional TRC-20 USDT crypto settlement.
  • 🚀 Built-In Growth & Affiliate Engine: Native referral system (bonus token grants for inviters and invitees) and automated affiliate wallet commissions on completed marketplace orders.
  • 🖥️ 50+ Production Web Templates Included: Complete responsive UI across customer marketplace, seller dashboard, interactive AI playground/chat, and administrative consoles.

How Node2Mint Compares (LLM Gateway & Marketplace Matrix)

Capability Node2Mint LiteLLM / One-API OpenRouter (Cloud)
OpenAI-Compatible Gateway (/v1/chat/completions) ✅ Yes ✅ Yes ✅ Yes
Upstream Health Checks & Circuit Breaker Failover ✅ Yes ✅ Yes ✅ Yes
Row-Locked Atomic Ledger (SELECT FOR UPDATE) ✅ Yes ⚠️ Varies ✅ Yes
Multi-Vendor Digital Marketplace & Escrow Wallet ✅ Yes (Built-in) ❌ No ❌ No
Affiliate Commission & Referral Quota Engine ✅ Yes (Built-in) ❌ No ❌ No
Stripe, DOKU, QRIS & TRC-20 USDT Payments ✅ Yes (Native) ❌ External Plugin ❌ Stripe/Crypto Only
100% Self-Hosted & Full Source Ownership ✅ MIT License ✅ Open Source ❌ Proprietary SaaS

🧩 Features & Core Modules

🔀 API Gateway & Token Billing

  • OpenAI-Compatible /v1/chat/completions: Serves upstream models to client apps, SDKs, Cursor, and Cline using standardized schema headers.
  • Dynamic Token Metering: Deducts user balances based on exact model input/output rates, including cached prompt discount calculations.
  • Fixed-Window Rate Limiting: Per-IP and per-account request throttling enforced via Redis 7.
  • Telegram Notification Gateway: Real-time alerts via Telegram Bot API for order placements, dispute escalations, and group membership verification.

🛒 Marketplace & Escrow Commerce

  • Storefront & Product Catalog: Sell digital prompts, fine-tuned models, datasets, software tools, and subscription access packs.
  • Escrow Settlement: Buyer funds are safely held in platform escrow until manual or automated confirmation releases payout to the seller's store wallet.
  • Order Cancellation & Refunds: Safe rollback paths with immutable, atomic transaction log entries for every money movement.
  • Seller Store Management: Product publishing, GMV/sales analytics, dispute handling, and withdrawal requests.

🤝 Affiliate & Referral Program

  • Referral Rewards: Automatic token quota grants for new signups and referral code owners.
  • Affiliate Commission: Configurable percentage payouts deposited directly into affiliator wallets upon order settlement.
  • Anti-Fraud Controls: IP hashing, Cloudflare Turnstile, and duplicate signup checks protect referral distributions.

🎨 Frontend & UI/UX (Next.js 15)

  • Dual-Mode Shell: Customer portal with sleek dark-mode aesthetics paired with a high-contrast amber administrative shell.
  • Multilingual (i18n): Built-in English (`en`) and Bahasa Indonesia (`id`) localization dictionaries.
  • Client-Side Image Optimization: Browser canvas WebP image compression (<256 KB) prior to server upload.

🏗️ System Architecture

                Client (Web / Mobile / CLI / OpenAI SDK)
                           │
                           ▼
                  Caddy 2 Reverse Proxy
                 (HTTPS / TLS Termination)
                ┌──────────┴──────────┐
                ▼                     ▼
       Next.js 15 Frontend       Go API Gateway
       (Port 3000 / SSR)        (Port 8080 / REST)
                                      │
            ┌─────────────────────────┼─────────────────────────┐
            ▼                         ▼                         ▼
      PostgreSQL 16                Redis 7               Upstream AI APIs
   (Ledger / Orders / Auth)     (Rate Limiting)       (OpenAI / Anthropic / Custom)

Directory Structure

node2mint/
├── gateway/                  # Go backend gateway (Chi router, pgxpool, redis)
│   ├── cmd/gateway/          # Application entrypoint
│   ├── internal/
│   │   ├── auth/             # JWT Bearer tokens, password hashing
│   │   ├── billing/          # Atomic charges, balance validation
│   │   ├── handler/          # HTTP controllers (admin, market, tokens, chat)
│   │   ├── provider/         # Upstream AI model client & failover
│   │   ├── rate/             # Redis-backed fixed-window rate limiter
│   │   └── store/            # PostgreSQL queries and migrations
│   ├── sql/                  # Schema definitions and base seed
│   └── .env.example          # Backend environment template
├── web/                      # Next.js 15 frontend (Tailwind CSS, shadcn/ui)
│   ├── app/                  # App router (marketplace, dashboard, admin, auth)
│   ├── components/           # Reusable UI components & layout shells
│   ├── lib/                  # API clients, auth context, i18n dictionaries
│   └── .env.example          # Frontend environment template
├── deploy/                   # Production deployment configurations
│   ├── docker-compose.prod.yml
│   ├── Caddyfile
│   └── site-allowlist.env.example
├── docs/                     # Design system and architecture documentation
├── docker-compose.yml        # Development stack orchestration
└── smoke-test.sh             # End-to-end billing and order regression check

🚀 Quick Start

1. Prerequisites

  • Docker Engine & Docker Compose v2+
  • Go 1.22+ (for local backend development)
  • Node.js 18+ (for local frontend development)

2. Clone the Repository

git clone [https://github.com/yanstd888/node2mint.git](https://github.com/yanstd888/node2mint.git)
cd node2mint

3. Configure Environments

cp gateway/.env.example gateway/.env
cp web/.env.example web/.env.local
cp -r gateway/.secrets.example gateway/.secrets

💡 The example templates contain pre-configured dev credentials. For production, generate unique 32+ character secrets (JWT_SECRET, SECRET_KEY).

4. Run Development Stack

Start backend services (PostgreSQL 16, Redis 7, Go Gateway, Uptime Kuma):

docker compose up -d --build

Verify all containers are healthy:

docker compose ps
curl http://localhost:8080/healthz   # Returns "ok"

Start Next.js 15 frontend (in a separate terminal):

cd web
npm install
npm run dev

Access the local services:

  • 🌐 Web Marketplace & App: http://localhost:3000
  • ⚡ API Gateway: http://localhost:8080
  • 📊 Uptime Kuma Health Dashboard: http://localhost:3001

Default Seed Accounts (Local Development Only)

The local compose setup automatically mounts gateway/sql/99-local-dev-seed.sql with two test accounts:

Role Email Password Pre-seeded Balance
Admin admin@test.local Test1234! 50,000 IDR
Seller seller@test.local Test1234! 10,000 IDR (Demo Store with 13 products)

(Seed accounts are strictly excluded in production deployments).

5. Automated End-to-End Verification

Run the money and order validation regression smoke test:

bash smoke-test.sh

🔌 API Reference

The Go gateway exposes REST endpoints alongside OpenAI-compatible completions:

Method Endpoint Auth Description
POST /v1/chat/completions Bearer API Key OpenAI-compatible chat completions with failover
POST /api/auth/register Public / Turnstile User registration with signup token grants
POST /api/auth/login Public / Turnstile User authentication returning JWT token
GET /api/dashboard JWT User profile, quotas, and wallet balance
GET /api/keys JWT List active API keys (prefix only)
POST /api/keys JWT Generate new API key (raw secret shown once)
DELETE /api/keys/{id} JWT Revoke existing API key
GET /api/market/products Public List published digital goods and access packs
POST /api/market/orders JWT Place marketplace order with atomic balance escrow
POST /api/market/orders/{id}/confirm JWT Buyer release of escrow to seller store wallet
GET /api/packages Public Available token top-up and signup packages
POST /api/payment/checkout JWT Create payment invoice (Stripe, DOKU, QRIS)
GET /api/admin/summary Admin High-level platform GMV and user analytics
POST /api/admin/withdrawal/{id}/decide Admin Approve or reject seller withdrawal with audit log

⚙️ Configuration

Neutral configuration templates are provided in .env.example files. Never commit .env or .env.local files to version control.

Gateway (gateway/.env)

Variable Description Default
DATABASE_URL PostgreSQL connection string postgresql://aiuser:***@localhost:5432/aisell
REDIS_ADDR Redis host and port localhost:6379
JWT_SECRET 32+ character random string for auth tokens CHANGE_ME_RANDOM_SECRET
SECRET_KEY 32+ character random string for data encryption CHANGE_ME_ENCRYPTION_KEY
PORT HTTP listener port 8080
RATE_LIMIT_DISABLE Disable rate limiter (local dev only) false
STRIPE_SECRET_KEY Optional Stripe API secret key (empty)
DOKU_SANDBOX Toggle DOKU payment simulator true
TELEGRAM_BOT_TOKEN Optional bot token for group membership gate (empty)

Frontend (web/.env.local)

Variable Description Default
NEXT_PUBLIC_API_URL Gateway API URL http://localhost:8080
NEXT_PUBLIC_DEFAULT_LOCALE Default language (id or en) id
NEXT_PUBLIC_SITE_NAME Branding title Node2Mint

🚢 Deployment

Docker Compose (Production)

For production environments, mount secrets via Docker secrets or protected environment files:

cd deploy
cp site-allowlist.env.example site-allowlist.env
docker compose --env-file site-allowlist.env -f docker-compose.prod.yml up -d

Cloudflare Tunnel Setup

To expose Node2Mint securely without opening public inbound firewall ports:

cloudflared tunnel run --protocol http2 --token YOUR_CLOUDFLARE_TUNNEL_TOKEN

🛡️ Safety and Security

  • Zero Plaintext Secrets in Repository: No production keys, database passwords, or operational secrets are stored in Git.
  • Hashed API Keys: Gateway API keys are hashed with SHA-256 before insertion. Only the prefix (e.g., n2m_live_...) is queryable by users.
  • Race Condition Prevention: Balances, order stock, and withdrawal flows run in isolated transactions with SELECT ... FOR UPDATE row locks.
  • Bot & Abuse Mitigation: Optional Cloudflare Turnstile verification guards public registration and authentication endpoints.
  • Structured Audit Logs: Every administrative balance adjustment, top-up approval, escrow release, and withdrawal records an immutable audit log row with actor ID, IP address, and timestamp.

Pre-Commit & CI Verification

Run local checks before staging any pull request:

# Go gateway verification
cd gateway
go vet ./...
go test ./...

# Frontend type checking and build
cd ../web
npx tsc --noEmit --pretty false
npm run build

# Git cleanliness check
git diff --check

🇮🇩 Bahasa Indonesia — Ringkasan Node2Mint

Node2Mint adalah platform full-stack open-source (Next.js 15 + Go 1.22 + PostgreSQL 16 + Redis 7) yang menggabungkan Marketplace Produk Digital AI, Token Billing Engine, dan OpenAI-Compatible API Gateway.

Dirancang khusus untuk menjawab kebutuhan ekosistem bisnis digital modern (baik global maupun Indonesia):

  • Keamanan Saldo Anti-Minus (Atomic Ledger): Menggunakan row-level locking (SELECT FOR UPDATE) di PostgreSQL untuk mencegah race condition atau double-spending saat ribuan request API berjalan bersamaan.
  • Dukungan Pembayaran Lokal & Global: Mendukung integrasi DOKU, QRIS, Transfer Bank Manual, Stripe, hingga USDT (TRC-20) serta sistem rekber (Escrow) otomatis untuk melindungi pembeli dan penjual di marketplace.
  • Kompatibel Penuh dengan Ekosistem OpenAI: Endpoint /v1/chat/completions dilengkapi automatic provider failover dan circuit breaker, siap dihubungkan ke aplikasi AI, bot, maupun IDE seperti Cursor dan Cline.

📚 Documentation & Ecosystem

Document / Resource Purpose
LICENSE MIT Open Source License terms
CONTRIBUTING.md Branching guidelines, coding standards, and PR workflows
SECURITY.md Vulnerability disclosure policy and reporting contacts
CODE_OF_CONDUCT.md Contributor Covenant v2.1 community standards
Design System Frontend component specs, color palette, and layout rules
AICLUB Indonesia (aiclub.ai.id) Official AI tools directory, free .ai.id subdomains, and community hub
Toko AICLUB (toko.aiclub.ai.id) Live digital product & application marketplace

🤝 Contributing & License

Contributions, bug reports, and pull requests are welcome! Please ensure changes include a minimal reproducible check or automated unit test where applicable. Read CONTRIBUTING.md for details.

This project is licensed under the MIT License — Built and maintained by Yanstd (@yanstd888).

About

Self-hosted AI marketplace, token billing engine & OpenAI-compatible Go API gateway with atomic PostgreSQL ledger, escrow commerce, and Stripe/DOKU/QRIS payments.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

32 stars

Watchers

3 watching

Forks

Releases

Packages

Contributors

Languages