mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-19 23:06:49 +00:00
feat: RBAC, atomic deployments, fleet backups, and licensing (Pro) (#185)
* feat: add RBAC viewer accounts, atomic deployments, and fleet-wide backups (Pro) Introduces three Pro-tier features: - RBAC: Multi-user system with admin/viewer roles, user management UI, automatic migration from single-admin credentials, viewer restrictions across the entire UI (read-only editor, hidden action buttons) - Atomic Deployments: Pre-deploy file backup to .sencho-backup/, automatic rollback on health probe failure, manual rollback button, health probes added to stack updates, webhook-triggered deploys use atomic rollback - Fleet-Wide Backups: Point-in-time snapshots of compose files across all nodes (local + remote), stored centrally in SQLite, per-stack restore with optional redeploy, graceful handling of offline nodes * fix(settings): use correct ProGate prop name in UsersSection * fix(settings): remove unused isPro prop from UsersSection * fix(auth): fetch user info after login and setup so isAdmin is set correctly * feat(pricing): revise pricing strategy and enforce variant-based seat limits Raise Personal Pro from $49/yr to $69/yr with 3 viewer seats (up from 1). Add $15/mo billing option for Team Pro. Mark lifetime pricing as a 90-day early-adopter offer. Store Lemon Squeezy variant_name on activation/validation and enforce seat limits server-side per variant. * feat(licensing): add Lemon Squeezy checkout, webhook, and billing portal integration Server-side checkout URL generation (POST /api/checkout) with admin email pre-fill and instance_id custom data. HMAC-SHA256 verified webhook endpoint (POST /api/webhooks/lemonsqueezy) handling order, subscription, and payment lifecycle events for automatic license activation. Customer billing portal link stored from webhook events and exposed via GET /api/billing/portal. In-app checkout buttons in Settings with manual license key fallback. * fix(licensing): exempt Lemon Squeezy webhook from auth middleware The catch-all auth middleware on /api/* was blocking the public webhook endpoint. Added /webhooks/lemonsqueezy to the exemption list alongside /auth/* and /webhooks/:id/trigger. * feat(pricing): update pricing to final live rates Personal Pro: $7.99/month, $69.99/year, $249 lifetime. Team Pro: $49.99/month, $499.99/year, $1,499 lifetime. Added personal_monthly checkout variant across backend, frontend, and website. * refactor(licensing): remove server-side checkout/webhook for self-hosted model Sencho is self-hosted — each user runs their own instance, so there is no central server to receive webhooks or hold the store API key. Replaced in-app checkout buttons with a "View Pricing" redirect to sencho.io and kept manual license key activation as the primary flow. - Delete LemonSqueezyService (checkout, webhook, HMAC verification) - Remove POST /api/checkout, GET /api/billing/portal, POST /api/webhooks/lemonsqueezy - Remove raw body parser and auth exemption for webhook route - Remove all LEMONSQUEEZY_* env vars from .env.example - Replace checkout buttons in SettingsModal with single "View Pricing" button - Simplify LicenseContext checkout to open sencho.io pricing page - Update licensing docs to reflect website-based purchase flow * chore: normalize em-dashes to hyphens across codebase (linter) * chore: remove accidentally tracked directories from index
This commit is contained in:
@@ -74,7 +74,7 @@ describe('authMiddleware', () => {
|
||||
const res = await request(app)
|
||||
.get('/api/stacks')
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
// Will succeed (200) or fail with a docker/fs error (500) — but NOT 401
|
||||
// Will succeed (200) or fail with a docker/fs error (500) - but NOT 401
|
||||
expect(res.status).not.toBe(401);
|
||||
});
|
||||
|
||||
@@ -96,7 +96,7 @@ describe('authMiddleware', () => {
|
||||
// ─── Protected endpoint: console-token ───────────────────────────────────────
|
||||
|
||||
describe('POST /api/system/console-token', () => {
|
||||
it('returns 401 without authentication (was a security bug — C1 fix)', async () => {
|
||||
it('returns 401 without authentication (was a security bug - C1 fix)', async () => {
|
||||
const res = await request(app).post('/api/system/console-token');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
@@ -33,7 +33,7 @@ describe('GET /api/health', () => {
|
||||
});
|
||||
|
||||
it('does not require an auth token', async () => {
|
||||
// No cookie, no Authorization header — must still return 200
|
||||
// No cookie, no Authorization header - must still return 200
|
||||
const res = await request(app).get('/api/health');
|
||||
expect(res.status).not.toBe(401);
|
||||
expect(res.status).not.toBe(403);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Test DB helper — creates a temporary SQLite database, seeds it with a known
|
||||
* Test DB helper - creates a temporary SQLite database, seeds it with a known
|
||||
* admin credential, and sets process.env so DatabaseService uses it.
|
||||
*
|
||||
* Call this at the top of every test file *before* importing the app,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Tests for node management API — focusing on api_url validation (SSRF fix C2).
|
||||
* Tests for node management API - focusing on api_url validation (SSRF fix C2).
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import request from 'supertest';
|
||||
@@ -21,7 +21,7 @@ afterAll(() => {
|
||||
cleanupTestDb(tmpDir);
|
||||
});
|
||||
|
||||
describe('POST /api/nodes — api_url SSRF validation (C2 fix)', () => {
|
||||
describe('POST /api/nodes - api_url SSRF validation (C2 fix)', () => {
|
||||
it('rejects localhost api_url', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/nodes')
|
||||
@@ -66,7 +66,7 @@ describe('POST /api/nodes — api_url SSRF validation (C2 fix)', () => {
|
||||
api_url: 'http://192.168.1.50:3000',
|
||||
api_token: 'sometoken',
|
||||
});
|
||||
// Should succeed (201 or 200) — not a validation error
|
||||
// Should succeed (201 or 200) - not a validation error
|
||||
expect(res.status).not.toBe(400);
|
||||
});
|
||||
|
||||
|
||||
+59
-46
@@ -67,8 +67,8 @@ const getCookieOptions = (req: Request) => ({
|
||||
// Middleware
|
||||
|
||||
// Security headers (X-Frame-Options, X-Content-Type-Options, etc.)
|
||||
// crossOriginEmbedderPolicy: disabled — Monaco editor workers lack COEP headers.
|
||||
// hsts: disabled — HSTS must only be set when the app is served over HTTPS.
|
||||
// crossOriginEmbedderPolicy: disabled - Monaco editor workers lack COEP headers.
|
||||
// hsts: disabled - HSTS must only be set when the app is served over HTTPS.
|
||||
// Enabling it over HTTP permanently breaks browser access for 1 year.
|
||||
// contentSecurityPolicy.upgradeInsecureRequests: explicitly set to null.
|
||||
// Helmet 8 merges custom directives with its defaults, which include this
|
||||
@@ -114,7 +114,7 @@ app.use(helmet({
|
||||
},
|
||||
}));
|
||||
|
||||
// CORS — in production restrict to the configured frontend origin.
|
||||
// CORS - in production restrict to the configured frontend origin.
|
||||
// In development, mirror the request origin so Vite's dev server works.
|
||||
const corsOrigin = process.env.NODE_ENV === 'production' && process.env.FRONTEND_URL
|
||||
? process.env.FRONTEND_URL
|
||||
@@ -124,6 +124,7 @@ app.use(cors({
|
||||
origin: corsOrigin,
|
||||
credentials: true,
|
||||
}));
|
||||
|
||||
// Conditionally parse JSON bodies. Remote proxy requests must NOT have their body
|
||||
// consumed here: express.json() drains the IncomingMessage stream into req.body
|
||||
// and http-proxy then pipes an already-ended stream to the remote server.
|
||||
@@ -239,7 +240,7 @@ const authMiddleware = async (req: Request, res: Response, next: NextFunction):
|
||||
}
|
||||
};
|
||||
|
||||
// Rate limiter for auth endpoints — prevents brute-force attacks.
|
||||
// Rate limiter for auth endpoints - prevents brute-force attacks.
|
||||
// Production: 5 attempts per 15-minute window per IP.
|
||||
// Development: 100 attempts (so E2E tests and local tooling are not blocked).
|
||||
const authRateLimiter = rateLimit({
|
||||
@@ -360,7 +361,7 @@ app.post('/api/auth/login', authRateLimiter, async (req: Request, res: Response)
|
||||
}
|
||||
});
|
||||
|
||||
// Update password endpoint — any authenticated user can change their own password
|
||||
// Update password endpoint - any authenticated user can change their own password
|
||||
app.put('/api/auth/password', authMiddleware, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { oldPassword, newPassword } = req.body;
|
||||
@@ -788,14 +789,14 @@ async function captureLocalNodeFiles(node: Node): Promise<SnapshotNodeData> {
|
||||
const composeContent = await fsService.getStackContent(stackName);
|
||||
files.push({ filename: 'compose.yaml', content: composeContent });
|
||||
} catch {
|
||||
// Stack has no compose file — skip
|
||||
// Stack has no compose file - skip
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const envContent = await fsService.getEnvContent(stackName);
|
||||
files.push({ filename: '.env', content: envContent });
|
||||
} catch {
|
||||
// No .env file — that's fine
|
||||
// No .env file - that's fine
|
||||
}
|
||||
stacks.push({ stackName, files });
|
||||
}
|
||||
@@ -844,7 +845,7 @@ async function captureRemoteNodeFiles(node: Node): Promise<SnapshotNodeData> {
|
||||
files.push({ filename: '.env', content });
|
||||
}
|
||||
} catch {
|
||||
// No .env — skip
|
||||
// No .env - skip
|
||||
}
|
||||
if (files.length > 0) {
|
||||
stacks.push({ stackName, files });
|
||||
@@ -1029,7 +1030,7 @@ app.post('/api/fleet/snapshots/:id/restore', async (req: Request, res: Response)
|
||||
try {
|
||||
await fsService.backupStackFiles(stackName);
|
||||
} catch {
|
||||
// Stack may not exist yet — that's ok
|
||||
// Stack may not exist yet - that's ok
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
@@ -1206,7 +1207,7 @@ app.get('/api/webhooks/:id/history', authMiddleware, async (req: Request, res: R
|
||||
}
|
||||
});
|
||||
|
||||
// Webhook trigger — public endpoint, authenticated via HMAC signature
|
||||
// Webhook trigger - public endpoint, authenticated via HMAC signature
|
||||
app.post('/api/webhooks/:id/trigger', async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const id = parseInt(req.params.id as string, 10);
|
||||
@@ -1218,7 +1219,7 @@ app.post('/api/webhooks/:id/trigger', async (req: Request, res: Response): Promi
|
||||
return;
|
||||
}
|
||||
|
||||
// Pro gate — trigger only works with an active Pro license
|
||||
// Pro gate - trigger only works with an active Pro license
|
||||
if (LicenseService.getInstance().getTier() !== 'pro') {
|
||||
res.status(403).json({ error: 'This feature requires Sencho Pro.', code: 'PRO_REQUIRED' });
|
||||
return;
|
||||
@@ -1242,7 +1243,7 @@ app.post('/api/webhooks/:id/trigger', async (req: Request, res: Response): Promi
|
||||
const action = req.body?.action || webhook.action;
|
||||
const triggerSource = req.headers['user-agent'] || req.ip || null;
|
||||
|
||||
// Execute asynchronously — return 202 immediately
|
||||
// Execute asynchronously - return 202 immediately
|
||||
res.status(202).json({ message: 'Webhook accepted', action });
|
||||
|
||||
const atomic = LicenseService.getInstance().getTier() === 'pro';
|
||||
@@ -1298,6 +1299,18 @@ app.post('/api/users', authMiddleware, async (req: Request, res: Response): Prom
|
||||
return;
|
||||
}
|
||||
|
||||
// Enforce seat limits based on license variant
|
||||
const seatLimits = LicenseService.getInstance().getSeatLimits();
|
||||
if (role === 'admin' && seatLimits.maxAdmins !== null && db.getAdminCount() >= seatLimits.maxAdmins) {
|
||||
res.status(403).json({ error: `Your license allows a maximum of ${seatLimits.maxAdmins} admin account${seatLimits.maxAdmins === 1 ? '' : 's'}. Upgrade to Team Pro for unlimited accounts.` });
|
||||
return;
|
||||
}
|
||||
if (role === 'viewer' && seatLimits.maxViewers !== null && db.getViewerCount() >= seatLimits.maxViewers) {
|
||||
res.status(403).json({ error: `Your license allows a maximum of ${seatLimits.maxViewers} viewer account${seatLimits.maxViewers === 1 ? '' : 's'}. Upgrade to Team Pro for unlimited accounts.` });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const id = db.addUser({ username, password_hash: passwordHash, role });
|
||||
res.status(201).json({ id, username, role });
|
||||
@@ -1451,7 +1464,7 @@ const remoteNodeProxy = createProxyMiddleware<Request, Response>({
|
||||
// Mark every response forwarded from a remote node with a sentinel header.
|
||||
// The frontend (apiFetch / fetchForNode) checks this before firing the
|
||||
// global 'sencho-unauthorized' event: a 401 from a remote means the stored
|
||||
// api_token for that node is invalid — not that the user's own session
|
||||
// api_token for that node is invalid - not that the user's own session
|
||||
// expired. Without this distinction, any node with a bad token causes an
|
||||
// immediate logout loop.
|
||||
proxyRes.headers['x-sencho-proxy'] = '1';
|
||||
@@ -1854,7 +1867,7 @@ async function resolveAllEnvFilePaths(nodeId: number, stackName: string): Promis
|
||||
await fsService.access(f);
|
||||
existing.push(f);
|
||||
} catch {
|
||||
// File does not exist — skip
|
||||
// File does not exist - skip
|
||||
}
|
||||
}
|
||||
return existing;
|
||||
@@ -2208,7 +2221,7 @@ app.get('/api/stats', async (req: Request, res: Response) => {
|
||||
// A container is "managed" if Docker started it from within COMPOSE_DIR.
|
||||
// We use com.docker.compose.project.working_dir rather than project name because
|
||||
// stacks launched from the COMPOSE_DIR root (not a subdirectory) all share the
|
||||
// project name of the root folder — causing false "external" classification.
|
||||
// project name of the root folder - causing false "external" classification.
|
||||
const isManagedByComposeDir = (c: any): boolean => {
|
||||
const workingDir: string | undefined = c.Labels?.['com.docker.compose.project.working_dir'];
|
||||
if (!workingDir) return false;
|
||||
@@ -2516,16 +2529,16 @@ const ALLOWED_SETTING_KEYS = new Set([
|
||||
// Zod schema for bulk PATCH - all keys optional, present keys fully validated
|
||||
import { z } from 'zod';
|
||||
const SettingsPatchSchema = z.object({
|
||||
host_cpu_limit: z.coerce.number().int().min(1).max(100).transform(String),
|
||||
host_ram_limit: z.coerce.number().int().min(1).max(100).transform(String),
|
||||
host_disk_limit: z.coerce.number().int().min(1).max(100).transform(String),
|
||||
docker_janitor_gb: z.coerce.number().min(0).transform(String),
|
||||
global_crash: z.enum(['0', '1']),
|
||||
global_logs_refresh: z.enum(['1', '3', '5', '10']),
|
||||
developer_mode: z.enum(['0', '1']),
|
||||
template_registry_url: z.string().max(2048).refine(v => v === '' || /^https?:\/\/.+/.test(v), { message: 'Must be a valid URL or empty' }),
|
||||
host_cpu_limit: z.coerce.number().int().min(1).max(100).transform(String),
|
||||
host_ram_limit: z.coerce.number().int().min(1).max(100).transform(String),
|
||||
host_disk_limit: z.coerce.number().int().min(1).max(100).transform(String),
|
||||
docker_janitor_gb: z.coerce.number().min(0).transform(String),
|
||||
global_crash: z.enum(['0', '1']),
|
||||
global_logs_refresh: z.enum(['1', '3', '5', '10']),
|
||||
developer_mode: z.enum(['0', '1']),
|
||||
template_registry_url: z.string().max(2048).refine(v => v === '' || /^https?:\/\/.+/.test(v), { message: 'Must be a valid URL or empty' }),
|
||||
metrics_retention_hours: z.coerce.number().int().min(1).max(8760).transform(String),
|
||||
log_retention_days: z.coerce.number().int().min(1).max(365).transform(String),
|
||||
log_retention_days: z.coerce.number().int().min(1).max(365).transform(String),
|
||||
}).partial();
|
||||
|
||||
app.get('/api/settings', async (req: Request, res: Response) => {
|
||||
@@ -2953,28 +2966,28 @@ app.post('/api/templates/deploy', async (req: Request, res: Response) => {
|
||||
// =========================
|
||||
|
||||
app.get('/api/image-updates', authMiddleware, (_req: Request, res: Response) => {
|
||||
try {
|
||||
const updates = DatabaseService.getInstance().getStackUpdateStatus();
|
||||
res.json(updates);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch image update status:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch image update status' });
|
||||
}
|
||||
try {
|
||||
const updates = DatabaseService.getInstance().getStackUpdateStatus();
|
||||
res.json(updates);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch image update status:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch image update status' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/image-updates/refresh', authMiddleware, (_req: Request, res: Response) => {
|
||||
if (!requireAdmin(_req, res)) return;
|
||||
try {
|
||||
const triggered = ImageUpdateService.getInstance().triggerManualRefresh();
|
||||
if (!triggered) {
|
||||
res.status(429).json({ error: 'Rate limited. Please wait at least 10 minutes between manual refreshes.' });
|
||||
return;
|
||||
}
|
||||
res.json({ success: true, message: 'Image update check started in background.' });
|
||||
} catch (error) {
|
||||
console.error('Failed to trigger image update refresh:', error);
|
||||
res.status(500).json({ error: 'Failed to trigger refresh' });
|
||||
if (!requireAdmin(_req, res)) return;
|
||||
try {
|
||||
const triggered = ImageUpdateService.getInstance().triggerManualRefresh();
|
||||
if (!triggered) {
|
||||
res.status(429).json({ error: 'Rate limited. Please wait at least 10 minutes between manual refreshes.' });
|
||||
return;
|
||||
}
|
||||
res.json({ success: true, message: 'Image update check started in background.' });
|
||||
} catch (error) {
|
||||
console.error('Failed to trigger image update refresh:', error);
|
||||
res.status(500).json({ error: 'Failed to trigger refresh' });
|
||||
}
|
||||
});
|
||||
|
||||
// =========================
|
||||
@@ -3156,11 +3169,11 @@ if (require.main === module) {
|
||||
// Exports used by tests (supertest requires the http.Server instance).
|
||||
export { app, server };
|
||||
|
||||
// Graceful shutdown — allows in-flight requests to finish, then cleanly stops
|
||||
// Graceful shutdown - allows in-flight requests to finish, then cleanly stops
|
||||
// background services and closes the SQLite connection before the process exits.
|
||||
// Docker sends SIGTERM when the container stops; Ctrl-C sends SIGINT in dev.
|
||||
const gracefulShutdown = (signal: string) => {
|
||||
console.log(`[Shutdown] ${signal} received — shutting down gracefully…`);
|
||||
console.log(`[Shutdown] ${signal} received - shutting down gracefully…`);
|
||||
|
||||
server.close(() => {
|
||||
console.log('[Shutdown] HTTP server closed');
|
||||
@@ -3168,13 +3181,13 @@ const gracefulShutdown = (signal: string) => {
|
||||
try { MonitorService.getInstance().stop(); } catch { /* already stopped */ }
|
||||
try { ImageUpdateService.getInstance().stop(); } catch { /* already stopped */ }
|
||||
try { DatabaseService.getInstance().getDb().close(); } catch { /* already closed */ }
|
||||
console.log('[Shutdown] Done — exiting');
|
||||
console.log('[Shutdown] Done - exiting');
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
// Force-exit after 10 s if connections refuse to drain
|
||||
setTimeout(() => {
|
||||
console.error('[Shutdown] Timed out waiting for connections — forcing exit');
|
||||
console.error('[Shutdown] Timed out waiting for connections - forcing exit');
|
||||
process.exit(1);
|
||||
}, 10_000).unref();
|
||||
};
|
||||
|
||||
@@ -134,7 +134,7 @@ export class ComposeService {
|
||||
} catch (deployError) {
|
||||
// Atomic: auto-rollback on failure
|
||||
if (atomic) {
|
||||
sendOutput('\n=== Deployment failed — rolling back to previous version ===\n');
|
||||
sendOutput('\n=== Deployment failed - rolling back to previous version ===\n');
|
||||
try {
|
||||
const fsSvc = FileSystemService.getInstance(this.nodeId);
|
||||
await fsSvc.restoreStackFiles(stackName);
|
||||
@@ -142,7 +142,7 @@ export class ComposeService {
|
||||
sendOutput('=== Rolled back successfully ===\n');
|
||||
} catch (rollbackError) {
|
||||
console.error(`Rollback failed for ${stackName}:`, rollbackError);
|
||||
sendOutput('=== Rollback failed — manual intervention may be required ===\n');
|
||||
sendOutput('=== Rollback failed - manual intervention may be required ===\n');
|
||||
}
|
||||
}
|
||||
throw deployError;
|
||||
@@ -322,7 +322,7 @@ export class ComposeService {
|
||||
} catch (updateError) {
|
||||
// Atomic: auto-rollback on failure
|
||||
if (atomic) {
|
||||
sendOutput('\n=== Update failed — rolling back to previous version ===\n');
|
||||
sendOutput('\n=== Update failed - rolling back to previous version ===\n');
|
||||
try {
|
||||
const fsSvc = FileSystemService.getInstance(this.nodeId);
|
||||
await fsSvc.restoreStackFiles(stackName);
|
||||
@@ -330,7 +330,7 @@ export class ComposeService {
|
||||
sendOutput('=== Rolled back successfully ===\n');
|
||||
} catch (rollbackError) {
|
||||
console.error(`Rollback failed for ${stackName}:`, rollbackError);
|
||||
sendOutput('=== Rollback failed — manual intervention may be required ===\n');
|
||||
sendOutput('=== Rollback failed - manual intervention may be required ===\n');
|
||||
}
|
||||
}
|
||||
throw updateError;
|
||||
|
||||
@@ -722,6 +722,11 @@ export class DatabaseService {
|
||||
return (this.db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number })?.count || 0;
|
||||
}
|
||||
|
||||
public getViewerCount(): number {
|
||||
return (this.db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'viewer'").get() as { count: number })?.count || 0;
|
||||
}
|
||||
|
||||
|
||||
// --- Fleet Snapshots ---
|
||||
|
||||
public createSnapshot(description: string, createdBy: string, nodeCount: number, stackCount: number, skippedNodes: string): number {
|
||||
|
||||
@@ -5,17 +5,32 @@ import { DatabaseService } from './DatabaseService';
|
||||
export type LicenseTier = 'community' | 'pro';
|
||||
export type LicenseStatus = 'community' | 'trial' | 'active' | 'expired' | 'disabled';
|
||||
|
||||
export type LicenseVariant = 'personal' | 'team' | null;
|
||||
|
||||
export interface LicenseInfo {
|
||||
tier: LicenseTier;
|
||||
status: LicenseStatus;
|
||||
variant: LicenseVariant;
|
||||
customerName: string | null;
|
||||
productName: string | null;
|
||||
maskedKey: string | null;
|
||||
validUntil: string | null;
|
||||
trialDaysRemaining: number | null;
|
||||
instanceId: string;
|
||||
portalUrl: string | null;
|
||||
}
|
||||
|
||||
/** Seat limits per variant. null = unlimited. */
|
||||
export interface SeatLimits {
|
||||
maxAdmins: number | null;
|
||||
maxViewers: number | null;
|
||||
}
|
||||
|
||||
const SEAT_LIMITS: Record<string, SeatLimits> = {
|
||||
personal: { maxAdmins: 1, maxViewers: 3 },
|
||||
team: { maxAdmins: null, maxViewers: null },
|
||||
};
|
||||
|
||||
interface LemonSqueezyActivationResponse {
|
||||
activated: boolean;
|
||||
error?: string;
|
||||
@@ -82,7 +97,7 @@ export class LicenseService {
|
||||
private static instance: LicenseService;
|
||||
private validationTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
private constructor() {}
|
||||
private constructor() { }
|
||||
|
||||
public static getInstance(): LicenseService {
|
||||
if (!LicenseService.instance) {
|
||||
@@ -118,7 +133,7 @@ export class LicenseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current license tier. Synchronous — reads from cached DB state only.
|
||||
* Returns the current license tier. Synchronous - reads from cached DB state only.
|
||||
*/
|
||||
public getTier(): LicenseTier {
|
||||
const db = DatabaseService.getInstance();
|
||||
@@ -132,7 +147,7 @@ export class LicenseService {
|
||||
if (validUntil && new Date(validUntil) > new Date()) {
|
||||
return 'pro';
|
||||
}
|
||||
// Trial expired — update status
|
||||
// Trial expired - update status
|
||||
db.setSystemState('license_status', 'community');
|
||||
return 'community';
|
||||
}
|
||||
@@ -162,6 +177,31 @@ export class LicenseService {
|
||||
return 'community';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the license variant (personal or team) from stored metadata.
|
||||
* Trial licenses default to "team" so users can explore all features.
|
||||
*/
|
||||
public getVariant(): LicenseVariant {
|
||||
const db = DatabaseService.getInstance();
|
||||
const status = db.getSystemState('license_status');
|
||||
if (status === 'trial') return 'team';
|
||||
const variantName = db.getSystemState('license_variant_name');
|
||||
if (!variantName) return null;
|
||||
const lower = variantName.toLowerCase();
|
||||
if (lower.includes('team')) return 'team';
|
||||
if (lower.includes('personal')) return 'personal';
|
||||
return 'personal'; // default activated licenses to personal
|
||||
}
|
||||
|
||||
/**
|
||||
* Get seat limits for the current license variant.
|
||||
*/
|
||||
public getSeatLimits(): SeatLimits {
|
||||
const variant = this.getVariant();
|
||||
if (!variant) return { maxAdmins: 1, maxViewers: 0 }; // community
|
||||
return SEAT_LIMITS[variant] || SEAT_LIMITS.personal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get full license information for the API response.
|
||||
*/
|
||||
@@ -181,12 +221,14 @@ export class LicenseService {
|
||||
return {
|
||||
tier: this.getTier(),
|
||||
status,
|
||||
variant: this.getVariant(),
|
||||
customerName: db.getSystemState('license_customer_name'),
|
||||
productName: db.getSystemState('license_product_name'),
|
||||
maskedKey: key ? `****-****-****-${key.slice(-4)}` : null,
|
||||
validUntil,
|
||||
trialDaysRemaining,
|
||||
instanceId,
|
||||
portalUrl: db.getSystemState('customer_portal_url') || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -221,7 +263,7 @@ export class LicenseService {
|
||||
if (data.license_key?.expires_at) {
|
||||
db.setSystemState('license_valid_until', data.license_key.expires_at);
|
||||
} else {
|
||||
// Lifetime license — no expiry
|
||||
// Lifetime license - no expiry
|
||||
db.setSystemState('license_valid_until', '');
|
||||
}
|
||||
|
||||
@@ -231,6 +273,9 @@ export class LicenseService {
|
||||
if (data.meta?.product_name) {
|
||||
db.setSystemState('license_product_name', data.meta.product_name);
|
||||
}
|
||||
if (data.meta?.variant_name) {
|
||||
db.setSystemState('license_variant_name', data.meta.variant_name);
|
||||
}
|
||||
|
||||
console.log('[License] Activated successfully.');
|
||||
return { success: true };
|
||||
@@ -278,6 +323,13 @@ export class LicenseService {
|
||||
'license_last_validated',
|
||||
'license_customer_name',
|
||||
'license_product_name',
|
||||
'license_variant_name',
|
||||
'subscription_id',
|
||||
'customer_id',
|
||||
'customer_portal_url',
|
||||
'update_payment_url',
|
||||
'order_id',
|
||||
'receipt_url',
|
||||
];
|
||||
for (const key of keysToRemove) {
|
||||
db.setSystemState(key, '');
|
||||
@@ -345,11 +397,14 @@ export class LicenseService {
|
||||
if (data.meta?.product_name) {
|
||||
db.setSystemState('license_product_name', data.meta.product_name);
|
||||
}
|
||||
if (data.meta?.variant_name) {
|
||||
db.setSystemState('license_variant_name', data.meta.variant_name);
|
||||
}
|
||||
|
||||
console.log('[License] Validation successful.');
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
// Network failure — don't change status, just log
|
||||
// Network failure - don't change status, just log
|
||||
console.warn('[License] Validation network error (keeping current status):', (err as Error).message);
|
||||
return { success: false, error: 'Unable to reach license server' };
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export const isValidStackName = (name: string): boolean =>
|
||||
/**
|
||||
* Validates that a remote node API URL is a safe, well-formed HTTP/HTTPS URL.
|
||||
* Rejects loopback addresses to prevent SSRF against local services.
|
||||
* Private/LAN IPs are allowed — users legitimately point Sencho at nodes on their LAN.
|
||||
* Private/LAN IPs are allowed - users legitimately point Sencho at nodes on their LAN.
|
||||
*/
|
||||
export function isValidRemoteUrl(
|
||||
raw: string,
|
||||
@@ -32,7 +32,7 @@ export function isValidRemoteUrl(
|
||||
if (loopback.test(url.hostname)) {
|
||||
return {
|
||||
valid: false,
|
||||
reason: 'API URL cannot point to localhost or loopback — use the actual host address',
|
||||
reason: 'API URL cannot point to localhost or loopback - use the actual host address',
|
||||
};
|
||||
}
|
||||
return { valid: true, url };
|
||||
|
||||
Reference in New Issue
Block a user