Skip to content
Back to search

lastsaas

SaaS boilerplate/starter-kit in Go+React with Stripe integration, multi-tenant support, comprehensive features and AI-agent ready

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/metavert-io--lastsaas/badge.svg)](/listings/metavert-io--lastsaas)

HTML

<a href="/listings/metavert-io--lastsaas"><img src="/api/listings/metavert-io--lastsaas/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. Clone the repository

git clone https://github.com/metavert-io/lastsaas.git
cd lastsaas

2. Run the setup script

./scripts/setup.sh

This will prompt you for: - **Database name** — the project identity (two projects sharing a name share the same user base) - **MongoDB URI** — your Atlas connection string or `mongodb://localhost:27017` - **JWT secrets** — auto-generated - **Google OAuth credentials** — optional, press Enter to skip - **Resend API key** — optional, press Enter to skip - **App name and email settings**

It writes a `.env` file and copies the config template.

3. Start the backend

set -a && source .env && set +a
cd backend
go run ./cmd/server

The server starts on `http://localhost:4290`.

4. Start the frontend

In a separate terminal:

set -a && source .env && set +a
cd frontend
npm install
npm run dev

The frontend starts on `http://localhost:4280`.

5. Initialize the system

Run the CLI setup to create the root tenant and admin account:

cd backend
go run ./cmd/lastsaas setup

This creates the root tenant (your admin organization) and the owner account. You can now log in at `http://localhost:4280`.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 906 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # LastSaaS
  2. [![CI](https://github.com/metavert-io/lastsaas/actions/workflows/ci.yml/badge.svg)](https://github.com/metavert-io/lastsaas/actions/workflows/ci.yml)
  3. [![codecov](https://codecov.io/gh/metavert-io/lastsaas/branch/master/graph/badge.svg)](https://codecov.io/gh/metavert-io/lastsaas)
  4. [![Go Report Card](https://goreportcard.com/badge/github.com/metavert-io/lastsaas)](https://goreportcard.com/report/github.com/metavert-io/lastsaas)
  5. **The last SaaS boilerplate you'll ever need.**
  6. LastSaaS is a complete, production-ready SaaS foundation built entirely through conversation with [Claude Code](https://claude.ai/claude-code). It gives you multi-tenant account management, authentication, role-based access control, white-label branding, Stripe billing, API keys, outgoing webhooks, a full admin interface, system health monitoring, credit-based usage tracking, and product analytics with telemetry — everything you need to launch a SaaS business, ready to customize for your specific product.
  7. The bottleneck for building software isn't engineering capacity anymore — it's imagination. LastSaaS proves it: a single person with a clear vision and an AI agent can stand up what used to require a team and months of work. And because it was built with [Claude Code](https://claude.ai/claude-code), the codebase is fork-ready for agentic engineering — point an AI agent at it and keep building your product through conversation.
  8. **[Project Page](https://metavert.io/lastsaas)**
  9. ---
  10. ## Why LastSaaS Exists
  11. Every SaaS product needs the same boring foundation: user accounts, teams, roles, authentication, admin dashboards, billing, usage limits, branding, webhooks, API keys. Historically, building that foundation meant weeks of plumbing before you could write a single line of your actual product.
  12. LastSaaS eliminates that. Fork it, point an AI agent at it, and start building your product on top of a foundation that already handles:
  13. - Multi-tenant isolation with role-based access
  14. - JWT authentication with refresh token rotation
  15. - Google, GitHub, and Microsoft OAuth integration
  16. - Magic link passwordless authentication
  17. - MFA/TOTP with recovery codes
  18. - Email verification and password resets
  19. - Team invitations and member management
  20. - Stripe billing with subscriptions, per-seat pricing, trials, and credit bundles
  21. - Plan entitlements and billing enforcement middleware
  22. - White-label branding with custom themes, logos, landing pages, and custom pages
  23. - API key authentication (admin and user scopes)
  24. - Outgoing webhooks with 19 event types and HMAC-SHA256 signing
  25. - Credit-based usage tracking (subscription + purchased buckets)
  26. - Promotion codes and coupon management via Stripe
  27. - Product analytics dashboard (conversion funnel, KPIs, retention cohorts, engagement metrics)
  28. - Telemetry event system with Go SDK and REST API for custom event tracking
  29. - A full admin interface for managing everything
  30. - Built-in API documentation (HTML and Markdown)
  31. - Real-time system health monitoring
  32. - Financial metrics dashboard (revenue, ARR, DAU, MAU)
  33. - MCP (Model Context Protocol) server for AI-powered admin access
  34. - CLI tools for server administration
  35. - Auto-versioning with database migrations
  36. - Production deployment on Fly.io
  37. This is open-source infrastructure for the agentic era of software — where the person with the idea is also the person who ships it. The codebase follows consistent patterns that AI agents navigate fluently, so you can keep evolving it the same way it was built.
  38. ---
  39. ## How It Compares
  40. If you're evaluating SaaS boilerplates, you've probably looked at ShipFast, Supastarter, MakerKit, SaaS Pegasus, and Gravity. Here's why technical founders choose LastSaaS instead.
  41. **Free and open-source.** ShipFast costs $169, MakerKit runs $199–599, Supastarter starts at $299, SaaS Pegasus charges $249/year, and Gravity is under $1K. LastSaaS is MIT-licensed — fork it, ship it, never pay a license fee. You own the code completely.
  42. **Go backend, not another Next.js project.** ShipFast, Supastarter, MakerKit, and Gravity are all JavaScript/TypeScript stacks. SaaS Pegasus uses Django. LastSaaS pairs a Go backend with a React + TypeScript frontend — giving you compiled-binary deployment, low memory footprint (a 14MB Alpine container), and the concurrency model that Go is known for. If your SaaS will handle real traffic or you want a backend that isn't a Node.js monolith, this matters.
  43. **Genuine multi-tenancy.** ShipFast has no multi-tenancy at all. SaaS Pegasus and Gravity offer basic team features but not true tenant isolation. LastSaaS gives you full multi-tenant architecture: tenant-scoped data isolation, three-tier RBAC (owner/admin/user), team invitations, ownership transfer, per-tenant activity logs, and per-tenant billing. This is the difference between "users can collaborate" and "each customer gets their own isolated workspace."
  44. **White-label branding built in.** Most boilerplates give you a theme toggle at best. LastSaaS includes a full white-label system: custom app name, logo, colors, fonts, landing page, custom pages, CSS injection, favicon, configurable navigation with entitlement gating, and auth page customization. If you're building a platform where customers see your brand (not yours-plus-a-framework), this saves weeks.
  45. **Outgoing webhooks, not just Stripe webhooks.** None of the alternatives — ShipFast, Supastarter, MakerKit, SaaS Pegasus, or Gravity — include an outgoing webhook system. LastSaaS ships with 19 event types across billing, team lifecycle, user lifecycle, credits, and security events, with HMAC-SHA256 signing, delivery tracking, and test events. Your customers can integrate with your platform from day one.
  46. **API keys with scoped access.** ShipFast, Supastarter, and MakerKit don't include API key management. LastSaaS provides `lsk_`-prefixed API keys with admin and user authority scopes, SHA-256 hashed storage, and last-used tracking — ready for your customers to build integrations.
  47. **Health monitoring and financial dashboards.** No competing boilerplate includes system health monitoring. LastSaaS collects CPU, memory, disk, HTTP, and MongoDB metrics every 60 seconds across all nodes, with 8 real-time charts, threshold alerting, and 30-day retention. The financial dashboard gives you revenue, ARR, DAU, and MAU time-series out of the box.
  48. **Product analytics with telemetry.** No competing boilerplate includes product analytics. LastSaaS auto-instruments the customer journey — visitor → signup → plan page → checkout → paid conversion → upgrade — and visualizes it as a conversion funnel. The PM dashboard includes SaaS KPIs (MRR, ARR, ARPU, LTV, churn rate, trial conversion), retention cohort analysis, engagement metrics (DAU/WAU/MAU for paying subscribers), and a custom event explorer. A Go SDK and REST API let you track your own events with zero configuration.
  49. **MCP server for AI-native operations.** This is unique to LastSaaS. A built-in Model Context Protocol server with 32 read-only tools lets you connect Claude (or any MCP-compatible AI) directly to your running application. Query your ARR trend, investigate error spikes, audit API keys, or review system health — all in natural language. No other SaaS boilerplate offers agentic admin access.
  50. **Built for AI-assisted development.** LastSaaS was built entirely through conversation with Claude Code, and the codebase is designed to keep being built that way. Consistent patterns, clear naming, and a structure AI agents navigate fluently. Fork it, point an agent at it, describe your product, and keep going. The competing boilerplates were built for manual development — LastSaaS is built for the way software is made now.
  51. | | LastSaaS | ShipFast | Supastarter | MakerKit | Pegasus | Gravity |
  52. |---|---|---|---|---|---|---|
  53. | **Price** | **Free (MIT)** | $169 | $299+ | $199–599 | $249/yr | <$1K |
  54. | **Stack** | Go + React | Next.js | Next.js / Nuxt | Next.js | Django | Node + React |
  55. | **Multi-Tenancy** | Full RBAC | — | ✓ | ✓ | Teams only | Teams only |
  56. | **White-Label** | Full | — | Partial | Partial | — | — |
  57. | **Webhooks** | 19 events | — | — | — | — | — |
  58. | **API Keys** | Scoped | — | — | — | Basic | — |
  59. | **Health Monitoring** | 8 charts | — | — | — | — | — |
  60. | **Product Analytics** | 5-tab PM dashboard | — | — | — | — | — |
  61. | **Credit System** | Dual buckets | — | — | Basic | — | — |
  62. | **MCP Server** | 26 tools | — | — | — | — | — |
  63. | **Admin Dashboard** | Full | — | ✓ | ✓ | ✓ | Basic |
  64. | **Stripe Billing** | Full | ✓ | ✓ | ✓ | ✓ | ✓ |
  65. ---
  66. ## Features
  67. ### Authentication & Identity
  68. - Email/password registration with bcrypt hashing
  69. - Email verification via [Resend](https://resend.com)
  70. - Google, GitHub, and Microsoft OAuth with automatic account linking
  71. - Magic link passwordless login via email
  72. - MFA/TOTP two-factor authentication with setup wizard
  73. - Recovery codes for MFA backup access
  74. - JWT access tokens (30min) + refresh tokens (7 days) with rotation
  75. - Account lockout after failed login attempts
  76. - Password reset flow with secure tokens
  77. - Password strength enforcement
  78. - Session management — list active sessions, revoke individual or all sessions
  79. - Session revocation on password change
  80. ### Multi-Tenancy
  81. - Root tenant (system admin) + customer tenants
  82. - Users belong to tenants via memberships
  83. - Roles: **owner**, **admin**, **user** with hierarchical permissions
  84. - Team invitations with email notifications
  85. - Ownership transfer between members
  86. - Per-tenant activity log
  87. - Tenant settings self-service
  88. ### Billing & Credits (Stripe)
  89. - **Subscription plans** with monthly and annual billing (configurable annual discount %)
  90. - **Pricing models**: flat-rate or per-seat (with included seats, min/max seat limits)
  91. - **Free trials** with configurable trial days per plan and trial abuse prevention
  92. - **Credit bundles** for one-time purchases
  93. - **Dual credit buckets**: subscription credits (reset or accrue) + purchased credits
  94. - **Stripe Checkout** (redirect-based) for payment collection
  95. - **Stripe Billing Portal** for customer self-service (payment methods, invoices)
  96. - **Multi-currency support** with configurable default currency
  97. - **Stripe Tax** automatic tax calculation
  98. - **Promotion codes and coupons** — create and manage via admin UI, linked to Stripe
  99. - **Invoice generation** — sequential invoice numbers, PDF download, tax breakdown
  100. - **Transaction history** — per-tenant and admin-wide with search and filtering
  101. - **Financial metrics** — revenue, ARR, DAU, MAU time-series with charting
  102. - **Billing enforcement middleware** — blocks expired subscriptions from paid features
  103. - **Entitlement middleware** — gate features based on plan (boolean and numeric entitlements)
  104. - **Billing waiver** for special accounts (root tenant, demo accounts)
  105. - **Admin subscription management** — cancel, modify, reassign plans
  106. - **Refund and dispute handling** — webhook handlers for `charge.refunded`, `charge.dispute.created`, `charge.dispute.closed`
  107. ### White-Label Branding
  108. - Custom app name, tagline, and logo (text, image, or both modes)
  109. - Theme colors (primary, accent, background, surface, text) with auto-generated shade palettes
  110. - Custom fonts (body and heading)
  111. - Custom landing page with configurable HTML
  112. - Custom pages served at `/p/{slug}` with SEO metadata
  113. - Custom CSS injection
  114. - Custom head HTML injection (analytics, meta tags)
  115. - Favicon upload
  116. - Media library for image/asset management
  117. - Configurable navigation sidebar with entitlement-gated items
  118. - Auth page customization (login/signup headings and subtext)
  119. - Dashboard HTML customization
  120. - Open Graph image support
  121. ### API Keys
  122. - Create API keys with `lsk_` prefix
  123. - Two authority levels: **admin** (auto-resolves root tenant) and **user** (requires X-Tenant-ID)
  124. - SHA-256 hashed storage — raw key shown only at creation
  125. - Last-used timestamp tracking
  126. - Admin UI for key management
  127. - Supports both JWT and API key authentication on all endpoints
  128. ### Outgoing Webhooks
  129. - 19 event types across 5 tiers:
  130. - **Billing**: subscription.activated, subscription.canceled, payment.received, payment.failed
  131. - **Team lifecycle**: member.invited, member.joined, member.removed, member.role_changed, ownership.transferred
  132. - **User lifecycle**: user.registered, user.verified, user.deactivated
  133. - **Credits & billing**: credits.purchased, plan.changed, tenant.created, tenant.deactivated
  134. - **Audit & security**: user.deleted, tenant.deleted, api_key.created, api_key.revoked
  135. - HMAC-SHA256 payload signing with `whsec_`-prefixed secrets
  136. - Delivery tracking with response codes, response bodies, and duration
  137. - Test event delivery
  138. - Secret regeneration
  139. - Event type filtering per webhook
  140. ### Admin Interface
  141. - **Dashboard** with user/tenant counts, health overview, and business metrics
  142. - **User management** — list, search, view profiles, edit, suspend, impersonate, delete with ownership preflight
  143. - **Tenant management** — list, view, edit, plan assignment, status control, subscription management
  144. - **Financial overview** — transaction history across all tenants, revenue/ARR/DAU/MAU charts
  145. - **Product analytics** — conversion funnel, SaaS KPIs, retention cohorts, engagement metrics, custom event explorer
  146. - **Plan management** — create, edit, archive, entitlements, per-seat configuration, trial days
  147. - **Credit bundle management** — create, edit, sort, activate/deactivate
  148. - **Promotions** — create and manage Stripe promotion codes and coupons
  149. - **Branding editor** — theme colors, logos, fonts, landing page, custom pages, CSS, navigation
  150. - **API key management** — create, view, revoke
  151. - **Webhook management** — create, edit, delete, test, view delivery history
  152. - **Announcements** — publish system-wide announcements
  153. - **System log viewer** with severity filtering, search, and user filtering
  154. - **Configuration variable editor** (strings, numbers, enums, templates)
  155. - **In-app messaging** — send messages to individual users
  156. - **Root members** — manage the admin team with invitations and role changes
  157. - **CSV export** for users and tenants
  158. - **Admin impersonation** — log in as any user for debugging
  159. - **System health monitoring** (see below)
  160. - **Integration health checks** — MongoDB, Stripe, Resend, Google OAuth status
  161. - Three-tier admin access: **user** (read-only), **admin** (read-write), **owner** (destructive operations)
  162. ### System Health Monitoring
  163. - Automatic node registration with heartbeat (30s interval)
  164. - Metrics collection every 60s: CPU, memory, disk, network, HTTP request stats, MongoDB stats, Go runtime
  165. - HTTP metrics middleware with percentile latency tracking (p50/p95/p99)
  166. - Threshold-based alerting (configurable warning/critical levels)
  167. - 30-day automatic data retention via MongoDB TTL indexes
  168. - Real-time dashboard with 8 time-series charts (Recharts)
  169. - Aggregate, all-nodes overlay, and single-node filter modes
  170. - Time range selection: 1h, 6h, 24h, 7d, 30d
  171. - Integration health panel (MongoDB, Stripe, Resend, Google OAuth connectivity)
  172. ### Product Analytics & Telemetry
  173. - **Conversion funnel** — Visitors → Signups → Plan Page Views → Checkouts → Paid Conversions → Upgrades, with conversion rates at each step
  174. - **SaaS KPIs** — MRR, ARR, ARPU, LTV, churn rate, trial-to-paid conversion rate, median time to first purchase, active subscriber count
  175. - **Retention cohorts** — weekly or monthly cohort retention table with color-coded heatmap (tracks `lastLoginAt` over time)
  176. - **Engagement metrics** — DAU/WAU/MAU for paying subscribers, average sessions per user, top features by usage, credit consumption trend
  177. - **Custom event explorer** — browse all event types, view trend charts, filter by name and time range
  178. - **Telemetry Go SDK** — `telemetry.Track()` / `TrackBatch()` / `TrackPageView()` / `TrackCheckoutStarted()` / `TrackLogin()` for direct in-process event recording (no HTTP overhead)
  179. - **Telemetry REST API** — `POST /telemetry/track` (anonymous, rate-limited) for page views; `POST /telemetry/events` and `/telemetry/events/batch` (authenticated) for custom events
  180. - **Auto-instrumentation** — registration, email verification, login, checkout, subscription activation/cancellation, and plan changes are tracked automatically
  181. - **365-day retention** — telemetry events auto-expire via MongoDB TTL index
  182. - **Rate limiting** — 60 req/min per IP for anonymous tracking, 120 req/min per user for authenticated events
  183. ### User Self-Service
  184. - Profile editing (display name, email)
  185. - Theme preference (light/dark)
  186. - Password management
  187. - MFA setup and management
  188. - Session viewer with remote revocation
  189. - Account deletion with data cleanup
  190. - Data export (GDPR-friendly)
  191. - Billing management (plan selection, credit purchases, invoice history, PDF download)
  192. - Onboarding flow
  193. ### Built-in API Documentation
  194. - Interactive HTML API reference at `/api/docs` with expandable endpoint details
  195. - Markdown API reference at `/api/docs/markdown` for integration in external docs
  196. - Comprehensive webhook event reference with payload descriptions
  197. - Auto-versioned from the VERSION file
  198. ### CLI Administration
  199. - `lastsaas setup` — Initialize the system (create root tenant + owner)
  200. - `lastsaas start` / `stop` / `restart` — Server process management
  201. - `lastsaas change-password` — Reset any user's password
  202. - `lastsaas send-message` — Send system messages to users
  203. - `lastsaas transfer-root-owner` — Transfer root tenant ownership
  204. - `lastsaas config list|get|set` — Manage configuration variables
  205. - `lastsaas version` — Show binary and database versions
  206. - `lastsaas status` — Check system health
  207. - `lastsaas mcp` — Start the MCP server (see [MCP Server](#mcp-server-ai-admin-access) below)
  208. ### MCP Server (AI Admin Access)
  209. A built-in [Model Context Protocol](https://modelcontextprotocol.io) server gives AI assistants like Claude read-only access to your admin data — dashboards, users, tenants, financials, logs, health, and more. Useful for asking questions like "what's our ARR trend?" or "show me critical logs from the last hour" in natural language.
  210. - **32 read-only tools** across 14 categories — no write operations, safe by design
  211. - **2 resources** — `lastsaas://dashboard` and `lastsaas://health` for automatic context
  212. - **API key authentication** — requires a root-tenant API key, same auth as the admin API
  213. - **Stdio transport** — runs locally, compatible with Claude Desktop and Claude Code
  214. **Tool categories:**
  215. - **About** — software version and environment
  216. - **Dashboard** — user/tenant counts, health overview
  217. - **Tenants** — list with filtering, detailed view with members
  218. - **Users** — list with search, detailed view with auth methods and memberships
  219. - **Financial** — transaction history, revenue/ARR/DAU/MAU time-series metrics
  220. - **Logs** — full-text search with severity/category/date filters, severity counts
  221. - **Health** — current system metrics, time-series health data, node list, integration status
  222. - **Config** — list and inspect runtime configuration variables
  223. - **Plans** — plan details, entitlement keys, credit bundles
  224. - **Announcements** — list published and draft announcements
  225. - **Promotions** — Stripe promotion codes with coupon details
  226. - **Security** — API key inventory (previews only), root tenant members
  227. - **Webhooks** — webhook configs, event type reference, delivery history
  228. ### Security
  229. - Security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy)
  230. - Rate limiting on authentication endpoints
  231. - Request body size limits
  232. - NoSQL injection protection (regex input escaping)
  233. - XSS protection via DOMPurify for injected HTML
  234. - Trusted proxy IP resolution (Fly-Client-IP)
  235. - Webhook signature verification (Stripe inbound, HMAC-SHA256 outbound)
  236. - Idempotent webhook processing via unique event ID index
  237. - System log injection detection with automatic critical alerts
  238. - Refresh token rotation with family-based revocation
  239. ### Production Ready
  240. - Dockerized multi-stage build (Go + Node + Alpine)
  241. - Fly.io deployment with auto-stop/auto-start machines
  242. - SPA serving from the Go binary (no separate web server needed)
  243. - CORS, security headers, rate limiting
  244. - Graceful shutdown with connection draining
  245. - Auto-versioning with database migration on startup
  246. - Version notification messages to admin users after upgrades
  247. ---
  248. ## Tech Stack
  249. | Layer | Technology |
  250. |-------|-----------|
  251. | Backend | Go 1.25, gorilla/mux |
  252. | Frontend | React 19, TypeScript, Vite 7, Tailwind CSS 4 |
  253. | Database | MongoDB (Atlas or local) |
  254. | Auth | JWT (access + refresh), bcrypt, Google/GitHub/Microsoft OAuth, Magic Links, TOTP MFA |
  255. | Billing | Stripe (stripe-go v82) — Checkout, Billing Portal, Webhooks, Tax |
  256. | Email | Resend |
  257. | Charts | Recharts |
  258. | Metrics | gopsutil v4 |
  259. | PDF | gofpdf (invoice generation) |
  260. | Security | DOMPurify (frontend), HMAC-SHA256 (webhooks) |
  261. | Deployment | Docker, Fly.io |
  262. ---
  263. ## Prerequisites
  264. - **Go 1.25+** — [install](https://go.dev/doc/install)
  265. - **Node.js 22+** — [install](https://nodejs.org)
  266. - **MongoDB** — either:
  267. - [MongoDB Atlas](https://www.mongodb.com/atlas) (free M0 tier works fine)
  268. - Local MongoDB Community Edition
  269. - **Git**
  270. ### Optional
  271. - [Resend](https://resend.com) API key — for email verification, password resets, and invitations
  272. - Google OAuth credentials — for Google sign-in
  273. - GitHub OAuth credentials — for GitHub sign-in
  274. - Microsoft OAuth credentials — for Microsoft sign-in
  275. - [Stripe](https://stripe.com) account — for billing (subscriptions, credit purchases, invoices)
  276. - [Fly.io](https://fly.io) account — for production deployment
  277. ---
  278. ## Quick Start
  279. ### 1. Clone the repository
  280. ```bash
  281. git clone https://github.com/metavert-io/lastsaas.git
  282. cd lastsaas
  283. ```
  284. ### 2. Run the setup script
  285. ```bash
  286. ./scripts/setup.sh
  287. ```
  288. This will prompt you for:
  289. - **Database name** — the project identity (two projects sharing a name share the same user base)
  290. - **MongoDB URI** — your Atlas connection string or `mongodb://localhost:27017`
  291. - **JWT secrets** — auto-generated
  292. - **Google OAuth credentials** — optional, press Enter to skip
  293. - **Resend API key** — optional, press Enter to skip
  294. - **App name and email settings**
  295. It writes a `.env` file and copies the config template.
  296. ### 3. Start the backend
  297. ```bash
  298. set -a && source .env && set +a
  299. cd backend
  300. go run ./cmd/server
  301. ```
  302. The server starts on `http://localhost:4290`.
  303. ### 4. Start the frontend
  304. In a separate terminal:
  305. ```bash
  306. set -a && source .env && set +a
  307. cd frontend
  308. npm install
  309. npm run dev
  310. ```
  311. The frontend starts on `http://localhost:4280`.
  312. ### 5. Initialize the system
  313. Run the CLI setup to create the root tenant and admin account:
  314. ```bash
  315. cd backend
  316. go run ./cmd/lastsaas setup
  317. ```
  318. This creates the root tenant (your admin organization) and the owner account. You can now log in at `http://localhost:4280`.
  319. ---
  320. ## Setting Up Stripe Billing
  321. Stripe integration is optional but required for paid subscriptions, credit bundle purchases, and invoice generation. If you skip this section, LastSaaS works as a free-tier-only platform.
  322. ### 1. Create a Stripe account
  323. Sign up at [stripe.com](https://stripe.com) and complete onboarding. You can use **test mode** during development.
  324. ### 2. Get your API keys
  325. Go to **Stripe Dashboard → Developers → API keys** and copy:
  326. - **Publishable key** (starts with `pk_test_` or `pk_live_`)
  327. - **Secret key** (starts with `sk_test_` or `sk_live_`)
  328. ### 3. Create a webhook endpoint
  329. Go to **Stripe Dashboard → Developers → Webhooks → Add endpoint**:
  330. - **Endpoint URL**: `https://your-domain.com/api/billing/webhook`
  331. - For local development with the Stripe CLI: `stripe listen --forward-to localhost:4290/api/billing/webhook`
  332. - **Events to subscribe to** — select these 8 events:
  333. - `checkout.session.completed`
  334. - `invoice.paid`
  335. - `invoice.payment_failed`
  336. - `customer.subscription.updated`
  337. - `customer.subscription.deleted`
  338. - `charge.refunded`
  339. - `charge.dispute.created`
  340. - `charge.dispute.closed`
  341. After creating the endpoint, copy the **Signing secret** (starts with `whsec_`).
  342. ### 4. Set environment variables
  343. Add these to your `.env` file:
  344. ```bash
  345. STRIPE_SECRET_KEY=sk_test_...
  346. STRIPE_PUBLISHABLE_KEY=pk_test_...
  347. STRIPE_WEBHOOK_SECRET=whsec_...
  348. ```
  349. ### 5. Create plans in the admin UI
  350. Once the backend is running with Stripe configured:
  351. 1. Log in as the root tenant owner
  352. 2. Go to **Admin → Plans** and create your subscription plans
  353. 3. Set pricing, billing intervals, trial days, entitlements, and credit allocations
  354. 4. Optionally create **credit bundles** under Admin → Credit Bundles
  355. 5. Optionally create **promotion codes** under Admin → Promotions
  356. Stripe Products and Prices are created automatically when customers check out — you don't need to configure anything in the Stripe Dashboard beyond the API keys and webhook.
  357. ### 6. Go live
  358. When you're ready for production:
  359. 1. Switch to **live mode** in the Stripe Dashboard
  360. 2. Create a new webhook endpoint with your production URL and the same 8 events
  361. 3. Update your production environment variables with the live keys and webhook secret
  362. ---
  363. ## Configuration
  364. Config files live in `backend/config/`:
  365. - `dev.example.yaml` / `prod.example.yaml` — committed templates
  366. - `dev.yaml` / `prod.yaml` — your actual configs (gitignored)
  367. Set `LASTSAAS_ENV=dev` or `LASTSAAS_ENV=prod` to select which config to load. Defaults to `dev`.
  368. Secrets are referenced as `${ENV_VAR}` in YAML and expanded from environment variables at load time. Default values use `${VAR:default}` syntax.
  369. ### Environment Variables
  370. | Variable | Required | Description |
  371. |----------|----------|------------|
  372. | `DATABASE_NAME` | Yes | Project identity — shared name = shared user base |
  373. | `MONGODB_URI` | Yes | MongoDB connection string |
  374. | `JWT_ACCESS_SECRET` | Yes | Secret for signing access tokens |
  375. | `JWT_REFRESH_SECRET` | Yes | Secret for signing refresh tokens |
  376. | `FRONTEND_URL` | Yes | Frontend URL for CORS and email links |
  377. | `APP_NAME` | Yes | Your application name (used in emails, UI) |
  378. | `STRIPE_SECRET_KEY` | No | Stripe secret API key |
  379. | `STRIPE_PUBLISHABLE_KEY` | No | Stripe publishable key (sent to frontend) |
  380. | `STRIPE_WEBHOOK_SECRET` | No | Stripe webhook signing secret |
  381. | `GOOGLE_CLIENT_ID` | No | Google OAuth client ID |
  382. | `GOOGLE_CLIENT_SECRET` | No | Google OAuth secret |
  383. | `GOOGLE_REDIRECT_URL` | No | Google OAuth redirect URL |
  384. | `RESEND_API_KEY` | No | Resend email service API key |
  385. | `FROM_EMAIL` | No | Sender email address (default: noreply@yourdomain.com) |
  386. | `FROM_NAME` | No | Sender name (default: LastSaaS) |
  387. ---
  388. ## Project Structure
  389. ```
  390. lastsaas/
  391. backend/
  392. cmd/
  393. server/main.go Entry point (HTTP server, route wiring)
  394. lastsaas/main.go CLI administration tool + MCP server
  395. config/ YAML config files
  396. internal/
  397. api/handlers/ HTTP handlers (auth, admin, tenant, billing, branding, webhooks, etc.)
  398. apicounter/ API call counters for integration health
  399. auth/ JWT, password hashing, Google/GitHub/Microsoft OAuth, TOTP MFA
  400. config/ Config loader with env variable expansion
  401. configstore/ Runtime configuration (DB-backed, cached)
  402. db/ MongoDB connection, collections, indexes
  403. email/ Resend email service with templates
  404. events/ Internal event emitter (drives webhook deliveries)
  405. health/ System health monitoring service
  406. middleware/ Auth, tenant, RBAC, rate limiting, metrics, security, billing enforcement
  407. models/ All data models
  408. planstore/ Plan seeding
  409. stripe/ Stripe service (Checkout, Billing Portal, Customers, Prices, Subscriptions)
  410. syslog/ System logging service with injection detection
  411. telemetry/ Telemetry event collection, Go SDK, and PM analytics queries
  412. version/ Version management and auto-migration
  413. frontend/
  414. src/
  415. api/client.ts Axios API client with token refresh
  416. components/ Layout, AdminLayout, BrandingThemeInjector, shared components
  417. contexts/ Auth, Tenant, and Branding React contexts
  418. pages/
  419. admin/ Admin interface (dashboard, users, tenants, plans, billing, branding, etc.)
  420. admin/health/ Health monitoring components and charts
  421. app/ Customer-facing pages (dashboard, billing, team, settings, activity)
  422. app/settings/ User settings tabs (profile, security, MFA, sessions, billing)
  423. auth/ Login, signup, MFA challenge, magic link, verification, password reset
  424. public/ Landing page and custom pages
  425. types/index.ts TypeScript type definitions
  426. scripts/
  427. setup.sh Interactive setup script
  428. Dockerfile Multi-stage production build
  429. fly.toml Fly.io deployment config
  430. VERSION Current version number
  431. ```
  432. ---
  433. ## API Documentation
  434. LastSaaS includes built-in, self-hosted API documentation:
  435. - **Interactive HTML reference**: `GET /api/docs` — expandable endpoint cards with request/response examples
  436. - **Markdown reference**: `GET /api/docs/markdown` — for embedding in external documentation
  437. The documentation is generated from code and always matches the running version. It covers all endpoints, parameters, request/response formats, and all 19 webhook event types with payload descriptions.
  438. ---
  439. ## MCP Server Setup
  440. The MCP server lets AI assistants query your admin data in natural language. It proxies read-only requests to the LastSaaS admin API using an API key.
  441. ### Prerequisites
  442. 1. A running LastSaaS instance (local or deployed)
  443. 2. A root-tenant API key — create one in **Admin → API Keys** with **admin** authority
  444. ### Usage with Claude Desktop
  445. Add to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
  446. ```json
  447. {
  448. "mcpServers": {
  449. "lastsaas": {
  450. "command": "/path/to/lastsaas",
  451. "args": ["mcp"],
  452. "env": {
  453. "LASTSAAS_URL": "https://your-app.fly.dev",
  454. "LASTSAAS_API_KEY": "lsk_your_api_key_here"
  455. }
  456. }
  457. }
  458. }
  459. ```
  460. ### Usage with Claude Code
  461. Add to your project's `.mcp.json`:
  462. ```json
  463. {
  464. "mcpServers": {
  465. "lastsaas": {
  466. "command": "/path/to/lastsaas",
  467. "args": ["mcp"],
  468. "env": {
  469. "LASTSAAS_URL": "https://your-app.fly.dev",
  470. "LASTSAAS_API_KEY": "lsk_your_api_key_here"
  471. }
  472. }
  473. }
  474. }
  475. ```
  476. ### Build the CLI binary
  477. ```bash
  478. cd backend
  479. go build -o lastsaas ./cmd/lastsaas
  480. ```
  481. ### Environment Variables
  482. | Variable | Required | Description |
  483. |----------|----------|-------------|
  484. | `LASTSAAS_URL` | Yes | Base URL of the LastSaaS instance (e.g. `http://localhost:4290` or `https://your-app.fly.dev`) |
  485. | `LASTSAAS_API_KEY` | Yes | Root-tenant API key with admin authority (starts with `lsk_`) |
  486. ### Available Tools (26)
  487. | Tool | Description |
  488. |------|-------------|
  489. | `get_about` | Software version and environment |
  490. | `dashboard_stats` | User/tenant counts and health overview |
  491. | `list_tenants` | Paginated tenant list with search and filters |
  492. | `get_tenant` | Detailed tenant with plan, billing, and members |
  493. | `list_users` | Paginated user list with search and filters |
  494. | `get_user` | Detailed user with auth methods and memberships |
  495. | `list_transactions` | Financial transactions with search and filters |
  496. | `get_financial_metrics` | Revenue, ARR, DAU, MAU time-series |
  497. | `search_logs` | Full-text log search with severity/category/date filters |
  498. | `get_log_severity_counts` | Log counts by severity level |
  499. | `get_system_health` | Current CPU, memory, disk, HTTP stats |
  500. | `get_health_metrics` | Time-series health data (per-node or aggregate) |
  501. | `list_nodes` | Server nodes with status and version |
  502. | `get_integrations` | Third-party integration health |
  503. | `list_config` | All runtime configuration variables |
  504. | `get_config` | Single config variable details |
  505. | `list_plans` | Subscription plans with pricing and entitlements |
  506. | `get_plan` | Detailed plan info |
  507. | `list_entitlement_keys` | Entitlement key catalog |
  508. | `list_credit_bundles` | Credit bundle pricing |
  509. | `list_announcements` | Published and draft announcements |
  510. | `list_promotions` | Stripe promotion codes and coupons |
  511. | `list_api_keys` | API key inventory (previews only) |
  512. | `list_root_members` | Admin team and pending invitations |
  513. | `list_webhooks` | Outbound webhook configurations |
  514. | `list_webhook_event_types` | Available webhook event types |
  515. | `get_webhook` | Webhook detail with delivery history |
  516. ### MCP Examples
  517. These examples show how the MCP tools work in practice. Each example lists the user prompt and the exact tool calls that execute behind the scenes.
  518. #### Example 1: Check Business Overview
  519. **Prompt:** "How's my SaaS doing today?"
  520. **Tool calls:**
  521. 1. `dashboard_stats` — returns a snapshot:
  522. ```
  523. Users: 1,284 (12 new today)
  524. Tenants: 89 (3 new this week)
  525. Health: All systems healthy
  526. Active alerts: 0
  527. ```
  528. #### Example 2: Investigate Revenue Trend
  529. **Prompt:** "Show me our revenue trend for the last 30 days"
  530. **Tool calls:**
  531. 1. `get_financial_metrics` — queries time-series data:
  532. ```json
  533. { "range": "30d", "metric": "revenue" }
  534. ```
  535. Returns daily revenue data points (values in cents) for charting, e.g.:
  536. ```
  537. 2026-01-27: $1,250.00
  538. 2026-01-28: $890.00
  539. ...
  540. 2026-02-25: $2,100.00
  541. ```
  542. 2. `get_financial_metrics` — follow up with ARR:
  543. ```json
  544. { "range": "30d", "metric": "arr" }
  545. ```
  546. #### Example 3: Find a Specific Tenant
  547. **Prompt:** "Look up the Acme Corp tenant and show me their details"
  548. **Tool calls:**
  549. 1. `list_tenants` — searches by name:
  550. ```json
  551. { "search": "Acme Corp" }
  552. ```
  553. Returns matching tenants with IDs, plan names, and billing status.
  554. 2. `get_tenant` — fetches full details using the tenant ID:
  555. ```json
  556. { "id": "6789abc..." }
  557. ```
  558. Returns plan info, billing status, credit balances, subscription dates, and a full member list with roles.
  559. #### Example 4: Search for Critical Errors
  560. **Prompt:** "Were there any critical errors in the last hour?"
  561. **Tool calls:**
  562. 1. `search_logs` — filters by severity and time:
  563. ```json
  564. {
  565. "severity": "critical",
  566. "fromDate": "2026-02-26T14:00:00Z",
  567. "perPage": "50"
  568. }
  569. ```
  570. Returns log entries with timestamps, categories, messages, and metadata. For example:
  571. ```
  572. [critical] 14:23:05 billing — Stripe webhook signature verification failed
  573. [critical] 14:31:12 security — Log injection pattern detected in user input
  574. ```
  575. 2. `get_log_severity_counts` — provides overall distribution:
  576. ```
  577. critical: 2, high: 15, medium: 89, low: 342, debug: 1,204
  578. ```
  579. #### Example 5: Monitor System Health
  580. **Prompt:** "How's the system health? Are all integrations working?"
  581. **Tool calls:**
  582. 1. `get_system_health` — returns current metrics:
  583. ```
  584. CPU: 12.3%
  585. Memory: 245 MB / 512 MB (47.8%)
  586. Disk: 1.2 GB / 8 GB (15.0%)
  587. HTTP: 1,234 requests (p95 latency: 45ms)
  588. MongoDB: 12 active connections
  589. ```
  590. 2. `get_integrations` — checks third-party connectivity:
  591. ```
  592. MongoDB: healthy (3ms response)
  593. Stripe: healthy (120ms response, 89 calls/24h)
  594. Resend: healthy (95ms response, 12 calls/24h)
  595. Google OAuth: healthy
  596. ```
  597. #### Example 6: Audit API Key Usage
  598. **Prompt:** "Show me all active API keys and when they were last used"
  599. **Tool calls:**
  600. 1. `list_api_keys` — returns inventory (full keys are never exposed):
  601. ```
  602. "Production Automation" (admin) — lsk_...a3f2 — last used: 2 hours ago
  603. "CI/CD Pipeline" (admin) — lsk_...b7e1 — last used: 15 minutes ago
  604. "Customer Integration" (user) — lsk_...c9d4 — last used: 3 days ago
  605. "Old Test Key" (admin) — lsk_...d1e5 — last used: never
  606. ```
  607. #### Example 7: Review Subscription Plans
  608. **Prompt:** "What plans do we offer and how many subscribers does each have?"
  609. **Tool calls:**
  610. 1. `list_plans` — returns all plans with pricing and subscriber counts:
  611. ```
  612. Starter: $9/mo ($86/yr) — 45 subscribers — 5 seat limit
  613. Pro: $29/mo ($278/yr) — 31 subscribers — 25 seat limit, per-seat pricing
  614. Enterprise: $99/mo ($950/yr) — 8 subscribers — unlimited seats
  615. ```
  616. 2. `list_credit_bundles` — shows available credit purchases:
  617. ```
  618. Small Pack: 100 credits — $5.00 — active
  619. Medium Pack: 500 credits — $20.00 — active
  620. Large Pack: 2000 credits — $60.00 — active
  621. ```
  622. #### Example 8: Check Webhook Delivery
  623. **Prompt:** "Are our webhooks delivering successfully? Show me the recent history for the production webhook"
  624. **Tool calls:**
  625. 1. `list_webhooks` — shows all configured webhooks:
  626. ```
  627. "Production" — https://api.example.com/webhooks — 12 events — active
  628. "Staging" — https://staging.example.com/hooks — 5 events — active
  629. ```
  630. 2. `get_webhook` — fetches delivery history for the production webhook:
  631. ```json
  632. { "id": "abc123..." }
  633. ```
  634. Returns recent delivery attempts with status codes, response times, and any failures:
  635. ```
  636. 2026-02-26 14:30:01 — subscription.activated — 200 OK (120ms)
  637. 2026-02-26 14:15:22 — payment.received — 200 OK (95ms)
  638. 2026-02-26 13:45:10 — member.joined — 500 Error (340ms)
  639. ```
  640. #### Example 9: User Lookup and Membership
  641. **Prompt:** "Find the user with email alice@example.com and show me their tenant memberships"
  642. **Tool calls:**
  643. 1. `list_users` — searches by email:
  644. ```json
  645. { "search": "alice@example.com" }
  646. ```
  647. Returns the matching user with ID, verification status, and last login.
  648. 2. `get_user` — fetches full details:
  649. ```json
  650. { "id": "def456..." }
  651. ```
  652. Returns:
  653. ```
  654. Email: alice@example.com (verified)
  655. Auth: password + Google OAuth
  656. MFA: TOTP enabled
  657. Memberships:
  658. — Acme Corp (owner) — joined 2026-01-15
  659. — Side Project Inc (admin) — joined 2026-02-10
  660. Last login: 2 hours ago
  661. ```
  662. #### Example 10: Health Metrics Deep Dive
  663. **Prompt:** "Show me the CPU and memory trends across all nodes for the last 24 hours"
  664. **Tool calls:**
  665. 1. `list_nodes` — identifies all server nodes:
  666. ```
  667. node-1 (v1.0.0) — healthy — last seen: 30s ago
  668. node-2 (v1.0.0) — healthy — last seen: 28s ago
  669. ```
  670. 2. `get_health_metrics` — fetches aggregate time-series data:
  671. ```json
  672. { "range": "24h" }
  673. ```
  674. Returns data points every 60 seconds with CPU %, memory %, disk %, HTTP request counts, and latency percentiles — ready for charting.
  675. 3. `get_health_metrics` — optionally drill into a specific node:
  676. ```json
  677. { "node": "node-1", "range": "24h" }
  678. ```
  679. ---
  680. ## Deployment
  681. ### Fly.io
  682. LastSaaS includes a Dockerfile and Fly.io configuration for production deployment.
  683. ```bash
  684. # Install flyctl if needed
  685. curl -L https://fly.io/install.sh | sh
  686. # Create the app (first time only)
  687. flyctl apps create your-app-name --org your-org
  688. # Set production secrets
  689. flyctl secrets set \
  690. DATABASE_NAME="your-db-name" \
  691. MONGODB_URI="mongodb+srv://..." \
  692. JWT_ACCESS_SECRET="$(openssl rand -hex 32)" \
  693. JWT_REFRESH_SECRET="$(openssl rand -hex 32)" \
  694. FRONTEND_URL="https://your-app-name.fly.dev" \
  695. APP_NAME="YourApp" \
  696. STRIPE_SECRET_KEY="sk_live_..." \
  697. STRIPE_PUBLISHABLE_KEY="pk_live_..." \
  698. STRIPE_WEBHOOK_SECRET="whsec_..."
  699. # Deploy
  700. flyctl deploy
  701. ```
  702. The Dockerfile builds both the Go backend and React frontend into a single ~14MB Alpine container. The Go binary serves the frontend SPA directly — no nginx or separate web server required.
  703. ### Other Platforms
  704. The Docker image works anywhere containers run. The only external dependency is MongoDB. Set the environment variables listed above and expose port 8080.
  705. ---
  706. ## Fork It and Keep Building with AI
  707. LastSaaS was built entirely through conversation with [Claude Code](https://claude.ai/claude-code) — every feature, every handler, every component was described in natural language and implemented by an AI agent. But the real point isn't that it *was* built this way — it's that it's designed to *keep* being built this way.
  708. The codebase follows consistent patterns, uses clear naming, and maintains a structure that AI agents navigate fluently. Fork it, point Claude Code at it, and start describing your product. The agent already understands the patterns — authentication, tenancy, billing, middleware, events — and builds on top of them naturally. You're not starting from scratch; you're continuing a conversation.
  709. Here's what's already wired up for you:
  710. 1. **Add your product's data models** in `backend/internal/models/`
  711. 2. **Add API handlers** in `backend/internal/api/handlers/`
  712. 3. **Wire routes** in `backend/cmd/server/main.go`
  713. 4. **Add frontend pages** in `frontend/src/pages/`
  714. 5. **Use the tenant context** — every authenticated request carries the user's tenant, so your product logic gets multi-tenancy for free
  715. 6. **Use the credit system** — check and deduct credits for usage-based features
  716. 7. **Use entitlements** — gate features with `middleware.RequireEntitlement(db, "feature_name")` and `middleware.RequireActiveBilling()`
  717. 8. **Use the config store** — add runtime-configurable settings without redeployment
  718. 9. **Use the event emitter** — emit events from your handlers and they'll automatically be delivered to configured webhooks
  719. 10. **Use API keys** — your endpoints automatically support both JWT and API key authentication
  720. 11. **Use the branding system** — your UI inherits the white-label theme automatically via the BrandingContext
  721. 12. **Use the telemetry system** — track custom events with `telemetry.Track()` in Go or `POST /telemetry/events` from external clients, and they'll automatically appear in the PM dashboard
  722. ---
  723. ## Privacy Policy
  724. LastSaaS is self-hosted software — you control your database, your hosting, and your data. The MCP server connects to your LastSaaS instance via the HTTP API using read-only tools — no data is transmitted to Metavert LLC or any third party.
  725. For the full privacy policy, see: https://www.metavert.io/lastsaas-privacy-policy
  726. ---
  727. ## License
  728. [MIT](LICENSE) - Copyright 2026 Metavert LLC

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.