Star 历史趋势
数据来源: GitHub API · 生成自 Stargazers.cn
README.md
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)

CapabilityNode2MintLiteLLM / One-APIOpenRouter (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:

RoleEmailPasswordPre-seeded Balance
Adminadmin@test.localTest1234!50,000 IDR
Sellerseller@test.localTest1234!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:

MethodEndpointAuthDescription
POST/v1/chat/completionsBearer API KeyOpenAI-compatible chat completions with failover
POST/api/auth/registerPublic / TurnstileUser registration with signup token grants
POST/api/auth/loginPublic / TurnstileUser authentication returning JWT token
GET/api/dashboardJWTUser profile, quotas, and wallet balance
GET/api/keysJWTList active API keys (prefix only)
POST/api/keysJWTGenerate new API key (raw secret shown once)
DELETE/api/keys/{id}JWTRevoke existing API key
GET/api/market/productsPublicList published digital goods and access packs
POST/api/market/ordersJWTPlace marketplace order with atomic balance escrow
POST/api/market/orders/{id}/confirmJWTBuyer release of escrow to seller store wallet
GET/api/packagesPublicAvailable token top-up and signup packages
POST/api/payment/checkoutJWTCreate payment invoice (Stripe, DOKU, QRIS)
GET/api/admin/summaryAdminHigh-level platform GMV and user analytics
POST/api/admin/withdrawal/{id}/decideAdminApprove 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)

VariableDescriptionDefault
DATABASE_URLPostgreSQL connection stringpostgresql://aiuser:***@localhost:5432/aisell
REDIS_ADDRRedis host and portlocalhost:6379
JWT_SECRET32+ character random string for auth tokensCHANGE_ME_RANDOM_SECRET
SECRET_KEY32+ character random string for data encryptionCHANGE_ME_ENCRYPTION_KEY
PORTHTTP listener port8080
RATE_LIMIT_DISABLEDisable rate limiter (local dev only)false
STRIPE_SECRET_KEYOptional Stripe API secret key(empty)
DOKU_SANDBOXToggle DOKU payment simulatortrue
TELEGRAM_BOT_TOKENOptional bot token for group membership gate(empty)

Frontend (web/.env.local)

VariableDescriptionDefault
NEXT_PUBLIC_API_URLGateway API URLhttp://localhost:8080
NEXT_PUBLIC_DEFAULT_LOCALEDefault language (id or en)id
NEXT_PUBLIC_SITE_NAMEBranding titleNode2Mint

🚢 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 / ResourcePurpose
LICENSEMIT Open Source License terms
CONTRIBUTING.mdBranching guidelines, coding standards, and PR workflows
SECURITY.mdVulnerability disclosure policy and reporting contacts
CODE_OF_CONDUCT.mdContributor Covenant v2.1 community standards
Design SystemFrontend 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

Related open source

  • 9RouterX — self-hosted single-binary AI router & LLM gateway by the same team.

🤝 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.
affiliate-systemai-gatewayai-marketplaceapi-gatewaydigital-marketplacesdokuescrowfullstackgolangllm-gatewaymarketplacenextjs15openai-apiopenai-compatiblepostgresqlqrisredisself-hostedstripetoken-billing

语言 Languages

TypeScript46.7%
Go43.1%
Shell4.0%
PLpgSQL3.7%
JavaScript1.2%
Python1.2%
Dockerfile0.0%
Batchfile0.0%

提交活跃度 Commit Activity

代码提交热力图
过去 52 周的开发活跃度
7
Total Commits
峰值: 5次/周
Less
More

核心贡献者 Contributors