refactor: remove the billing tier model (P0.1)
The community edition has no monetization (ADR-0001). Remove the tier model (packages/shared/src/tiers.ts), the requireTier middleware and every tier gate, GET/PATCH /api/tier and the trial start, and the Stripe integration, which depends on the tier model. Personal features a tier used to limit are open to everyone: unlimited workspaces and connectors, every embedding provider including LiteLLM, per-workspace costs, Approvals. The workspace session cap is one constant (100). Team and enterprise surfaces are hidden instead of unlocked (team dock zone, Settings Team/Enterprise/Plan tabs, workspace Team tab); cloud sync reports unavailable, as it did for free users. The sidecar ignores the tier keys in config.json but does not delete them: both editions may still share ~/.waggle. Web billing UI is deleted: plan cards, upgrade and trial modals, payment success route, the KVARK sales block, tier 403 handling.
This commit is contained in:
@@ -11,18 +11,16 @@
|
||||
* `{ kind:'none', fallback:true }` so the frontend falls back to Tier 0.
|
||||
*/
|
||||
|
||||
import type { InterpretResult, ResolvedAction, Tier } from '@waggle/shared';
|
||||
import type { InterpretResult, ResolvedAction } from '@waggle/shared';
|
||||
import {
|
||||
buildActionCatalog,
|
||||
validateAndBuildAction,
|
||||
checkTier,
|
||||
type RegistryContext,
|
||||
} from './command-registry.js';
|
||||
|
||||
export interface InterpretDeps {
|
||||
text: string;
|
||||
workspaceId?: string;
|
||||
currentTier: Tier;
|
||||
workspaces: ReadonlyArray<{ id: string; name: string }>;
|
||||
/** The workspace "now" block (awareness + recent sessions + pending). */
|
||||
memoryContext: string;
|
||||
@@ -93,21 +91,6 @@ function buildValidStep(
|
||||
return validateAndBuildAction(actionId, params, ctx);
|
||||
}
|
||||
|
||||
/** Apply the tier gate to a resolved single action. */
|
||||
function finalizeAction(action: ResolvedAction, currentTier: Tier): InterpretResult {
|
||||
const tier = checkTier(action.id, currentTier);
|
||||
if (tier.gated && tier.requiredTier) {
|
||||
return {
|
||||
kind: 'tier_gated',
|
||||
capability: action.label,
|
||||
requiredTier: tier.requiredTier,
|
||||
actualTier: currentTier,
|
||||
message: `${action.label} requires the ${tier.requiredTier} tier.`,
|
||||
};
|
||||
}
|
||||
return { kind: 'action', action };
|
||||
}
|
||||
|
||||
export async function interpretCommand(deps: InterpretDeps): Promise<InterpretResult> {
|
||||
const ctx: RegistryContext = { workspaceId: deps.workspaceId, workspaces: deps.workspaces };
|
||||
|
||||
@@ -136,7 +119,7 @@ export async function interpretCommand(deps: InterpretDeps): Promise<InterpretRe
|
||||
if (!action) {
|
||||
return { kind: 'none', fallback: true, message: "I couldn't map that to an action I can run." };
|
||||
}
|
||||
return finalizeAction(action, deps.currentTier);
|
||||
return { kind: 'action', action };
|
||||
}
|
||||
|
||||
case 'plan': {
|
||||
@@ -144,7 +127,7 @@ export async function interpretCommand(deps: InterpretDeps): Promise<InterpretRe
|
||||
// a true multi-step plan downgrades to clarify (fast-follow executes it).
|
||||
const rawSteps = Array.isArray(parsed.steps) ? parsed.steps : [];
|
||||
const steps = rawSteps.map((s) => buildValidStep(s, ctx)).filter((s): s is ResolvedAction => s !== null);
|
||||
if (steps.length === 1) return finalizeAction(steps[0], deps.currentTier);
|
||||
if (steps.length === 1) return { kind: 'action', action: steps[0] };
|
||||
if (steps.length > 1) {
|
||||
const labels = steps.map((s) => s.label).join(' → ');
|
||||
return {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* The core safety property: the LLM resolver returns only an action `id` +
|
||||
* `params`. THIS module — never the model — maps the id onto an executable
|
||||
* shape (a navigation target or a server-derived endpoint), validates params,
|
||||
* and stamps `sideEffect` / `riskLevel` / `requiredTier`. An unknown id, or
|
||||
* and stamps `sideEffect` / `riskLevel`. An unknown id, or
|
||||
* params that fail validation, resolve to `null` (→ the caller returns `none`).
|
||||
*
|
||||
* No new execution layer: navigation reuses the CommandResult `onNavigate`
|
||||
@@ -15,9 +15,6 @@
|
||||
|
||||
import {
|
||||
MCP_CATALOG,
|
||||
assertTierCapability,
|
||||
TierError,
|
||||
type Tier,
|
||||
type RiskLevel,
|
||||
type ResolvedAction,
|
||||
} from '@waggle/shared';
|
||||
@@ -88,7 +85,6 @@ interface ActionDescriptor {
|
||||
params: Record<string, ParamSpec>;
|
||||
sideEffect: boolean;
|
||||
riskLevel: RiskLevel;
|
||||
requiredTier?: Tier;
|
||||
/** Build the executable shape, or return null when params are invalid. */
|
||||
build: (
|
||||
params: Record<string, unknown>,
|
||||
@@ -219,32 +215,14 @@ export function validateAndBuildAction(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier gate for a resolved action, reusing the canonical `assertTierCapability`.
|
||||
* Returns `{ gated: true, requiredTier }` when the current tier is below the
|
||||
* action's `requiredTier`.
|
||||
*/
|
||||
export function checkTier(actionId: string, currentTier: Tier): { gated: boolean; requiredTier?: Tier } {
|
||||
const descriptor = BY_ID.get(actionId);
|
||||
if (!descriptor?.requiredTier) return { gated: false };
|
||||
try {
|
||||
assertTierCapability(currentTier, descriptor.requiredTier);
|
||||
return { gated: false };
|
||||
} catch (e) {
|
||||
if (e instanceof TierError) return { gated: true, requiredTier: descriptor.requiredTier };
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Render the registry + nav/MCP catalogs as the system-prompt action catalog. */
|
||||
export function buildActionCatalog(): string {
|
||||
const actions = ACTION_REGISTRY.map((d) => {
|
||||
const params = Object.entries(d.params)
|
||||
.map(([k, s]) => `${k}${s.required ? '' : '?'}: ${s.description}${s.enum ? ` (one of: ${s.enum.join(', ')})` : ''}`)
|
||||
.join('; ');
|
||||
const tier = d.requiredTier ? ` [requires ${d.requiredTier}]` : '';
|
||||
const eff = d.sideEffect ? ' [side-effect → approval]' : '';
|
||||
return `- ${d.id}${tier}${eff}: ${d.description}\n params: ${params || '(none)'}`;
|
||||
return `- ${d.id}${eff}: ${d.description}\n params: ${params || '(none)'}`;
|
||||
}).join('\n');
|
||||
|
||||
const navList = NAV_TARGETS.map((t) => `- ${t.id} (${t.label}) — ${t.hints}`).join('\n');
|
||||
|
||||
@@ -69,8 +69,7 @@ import {
|
||||
} from '@waggle/agent';
|
||||
import { PluginRuntimeManager, getStarterSkillsDir, validatePluginManifest } from '@waggle/sdk';
|
||||
import { MarketplaceDB, MarketplaceSync, seedMcpServers, seedNewSources } from '@waggle/marketplace';
|
||||
import { parseTier, type RiskLevel } from '@waggle/shared';
|
||||
import { readTierFromDataDir } from '../middleware/assert-tier.js';
|
||||
import type { RiskLevel } from '@waggle/shared';
|
||||
import { runConnectorFetch } from './connector-harvest.js';
|
||||
import { writeAutoSyncSummaryFrame } from './harvest-autosync-frame.js';
|
||||
import { runLoopTick } from './loop-executor.js';
|
||||
@@ -163,7 +162,6 @@ import { waggleSignalRoutes } from './routes/waggle-signals.js';
|
||||
import { providerRoutes } from './routes/providers.js';
|
||||
import { profileRoutes } from './routes/profile.js';
|
||||
import { telemetryRoutes } from './routes/telemetry.js';
|
||||
import { stripeRoutes } from '../stripe/index.js';
|
||||
import { agentGroupRoutes } from './routes/agent-groups.js';
|
||||
import { localJobRoutes } from './routes/jobs.js';
|
||||
import { agentEntityRoutes } from './routes/agents.js';
|
||||
@@ -196,8 +194,7 @@ import {
|
||||
type ProactiveMessage,
|
||||
} from './proactive-handlers.js';
|
||||
import { generateMonthlyAssessment, saveAssessmentToMind } from './monthly-assessment.js';
|
||||
import { WorkspaceSessionManager } from './workspace-sessions.js';
|
||||
import { maxWorkspaceSessionsForTier } from './tier-session-cap.js';
|
||||
import { MAX_WORKSPACE_SESSIONS, WorkspaceSessionManager } from './workspace-sessions.js';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { LocalJobStore } from './job-store.js';
|
||||
import { AgentRunRegistry } from './agent-run-registry.js';
|
||||
@@ -213,8 +210,6 @@ export interface LocalConfig {
|
||||
instanceId?: string;
|
||||
/** Governed CLI execution — allowlist of program names the agent may run. */
|
||||
cli?: { allowlist?: string[] };
|
||||
/** Active subscription tier, when known (drives session/feature caps). */
|
||||
tier?: string;
|
||||
/** True only when startService owns the LiteLLM child lifecycle. */
|
||||
manageLiteLLM?: boolean;
|
||||
/** Stable child-process port, retained even while requests use a fallback proxy. */
|
||||
@@ -495,9 +490,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
&& rawDesktopBootstrapToken.length <= 200
|
||||
? rawDesktopBootstrapToken
|
||||
: null;
|
||||
const resolvedTier = parseTier(String(fullConfig.tier ?? '')) ?? readTierFromDataDir(fullConfig.dataDir);
|
||||
fullConfig.tier = resolvedTier;
|
||||
|
||||
const server = Fastify({ logger: false });
|
||||
const localJobStore = new LocalJobStore();
|
||||
server.decorate('localJobStore', localJobStore);
|
||||
@@ -1289,9 +1281,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
|
||||
// ── Workspace Session Manager ────────────────────────────────────
|
||||
// Manages concurrent workspace sessions with independent minds, orchestrators,
|
||||
// and tools. Cap is tied to the active tier at startup and when the tier changes.
|
||||
const sessionManager = new WorkspaceSessionManager(3);
|
||||
sessionManager.setMaxSessions(maxWorkspaceSessionsForTier(resolvedTier));
|
||||
// and tools.
|
||||
const sessionManager = new WorkspaceSessionManager(MAX_WORKSPACE_SESSIONS);
|
||||
server.decorate('sessionManager', sessionManager);
|
||||
|
||||
/**
|
||||
@@ -2893,7 +2884,6 @@ Return ONLY the improved system prompt text. No commentary, no markdown fences,
|
||||
await server.register(telemetryRoutes);
|
||||
await server.register(agentGroupRoutes);
|
||||
await server.register(localJobRoutes);
|
||||
await server.register(stripeRoutes);
|
||||
await server.register(harvestRoutes);
|
||||
await server.register(wikiRoutes);
|
||||
await server.register(identityRoutes);
|
||||
|
||||
@@ -40,10 +40,6 @@ import { assertSafeSegment, authHeaders, clampStr, clampStrArray } from './valid
|
||||
* spawn's {workspaceId, sessionId} in an in-process map keyed by agent id, and
|
||||
* liveStatus/pause act only on that recorded session. Entries are lost on
|
||||
* restart (the stored status then applies) — acceptable for one-shot C23 runs.
|
||||
*
|
||||
* Tier gating: agent creation is deliberately UNGATED — CLAUDE.md §1 moat
|
||||
* strategy: "Agents are free (they generate memory)", matching the executor
|
||||
* (`POST /api/fleet/spawn` is free for all tiers).
|
||||
*/
|
||||
|
||||
const AGENT_TYPES: readonly AgentType[] = ['personal', 'workspace', 'team', 'autonomous'];
|
||||
@@ -187,9 +183,7 @@ export const agentEntityRoutes: FastifyPluginAsync = async (server) => {
|
||||
return { agents, count: agents.length };
|
||||
});
|
||||
|
||||
// POST /api/agents — create. NOT tier-gated: CLAUDE.md §1 moat strategy says
|
||||
// "Agents are free (they generate memory)" and the executor (fleet spawn) is
|
||||
// free for all tiers — a tier gate here would be an incoherent surface.
|
||||
// POST /api/agents — create.
|
||||
// Blueprint hard gate: goal, model, memoryScopes and autonomyLevel are
|
||||
// required so the stored record is the full effective surface ("no hidden
|
||||
// tool/memory access").
|
||||
|
||||
@@ -34,7 +34,6 @@ import { loadSkills } from '@waggle/agent';
|
||||
import { buildWorkspaceNowBlock, formatWorkspaceNowPrompt } from './workspace-context.js';
|
||||
import { searchSessions } from './session-utils.js';
|
||||
import { interpretCommand } from '../command-interpret.js';
|
||||
import { readTierFromRequest } from '../../middleware/assert-tier.js';
|
||||
|
||||
/**
|
||||
* Memoized `loadSkills()` — the federated `/search` hot path runs per keystroke,
|
||||
@@ -342,7 +341,6 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
|
||||
const result = await interpretCommand({
|
||||
text,
|
||||
workspaceId,
|
||||
currentTier: readTierFromRequest(request),
|
||||
workspaces,
|
||||
memoryContext,
|
||||
llm,
|
||||
|
||||
@@ -1,30 +1,8 @@
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { ConnectorHealth } from '@waggle/shared';
|
||||
import { getCapabilities, parseTier, type Tier } from '@waggle/shared';
|
||||
import type { RecordAuditInput } from '@waggle/core';
|
||||
import { JiraConnector, SalesforceConnector } from '@waggle/agent';
|
||||
|
||||
/**
|
||||
* Tier cap for connecting connectors. All current tiers (Solo + Team) have an
|
||||
* unlimited connectorLimit (-1); the gate is retained for any future finite cap.
|
||||
* Re-connecting an already-connected connector (token refresh) does NOT
|
||||
* count against the cap. Returns the 403 payload data if the cap is exceeded,
|
||||
* else null. Pure (no IO) so it is unit-testable.
|
||||
*/
|
||||
export function connectorCapExceeded(
|
||||
tier: Tier,
|
||||
connectedIds: string[],
|
||||
id: string,
|
||||
): { limit: number; current: number } | null {
|
||||
const limit = getCapabilities(tier).connectorLimit;
|
||||
if (limit <= 0) return null; // unlimited
|
||||
if (connectedIds.includes(id)) return null; // already connected — token refresh
|
||||
if (connectedIds.length >= limit) return { limit, current: connectedIds.length };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Vault sub-key holding the C16 manual-sync stamp. Matches the
|
||||
* `connector:{id}:*` prefix so disconnect/revoke auto-clean it. */
|
||||
const lastSyncKey = (id: string) => `connector:${id}:lastSync`;
|
||||
@@ -171,32 +149,6 @@ export async function connectorRoutes(fastify: FastifyInstance) {
|
||||
}
|
||||
}
|
||||
|
||||
// Tier cap — connectors are unlimited on all current tiers (Solo + Team);
|
||||
// gate retained for any future finite cap. Count REAL credentialed
|
||||
// connections (getDefinitions status==='connected' excludes the always-on
|
||||
// mock channels). Marker `error:'TIER_INSUFFICIENT'` so the adapter's tier
|
||||
// event + the install store's tier classification light up. Fail-open if the
|
||||
// tier read throws (matches the workspace-limit gate).
|
||||
try {
|
||||
const configPath = join(fastify.localConfig.dataDir, 'config.json');
|
||||
const tierRaw = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')).tier : '';
|
||||
const tier = parseTier(String(tierRaw ?? '')) ?? 'FREE';
|
||||
const connectedIds = registry
|
||||
? registry.getDefinitions().filter(d => d.status === 'connected').map(d => d.id)
|
||||
: [];
|
||||
const cap = connectorCapExceeded(tier, connectedIds, id);
|
||||
if (cap) {
|
||||
return reply.code(403).send({
|
||||
error: 'TIER_INSUFFICIENT',
|
||||
required: 'TEAMS',
|
||||
actual: tier,
|
||||
message: `Connector limit reached for ${tier} (${cap.limit} max). Upgrade to connect more.`,
|
||||
limit: cap.limit,
|
||||
current: cap.current,
|
||||
});
|
||||
}
|
||||
} catch { /* tier read failed — allow the connect (fail-open) */ }
|
||||
|
||||
const connector = registry?.get(id);
|
||||
const authType = connector?.authType ?? 'bearer';
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
|
||||
// ── Types (inline to avoid cross-package resolution issues in worktrees) ──
|
||||
|
||||
@@ -95,9 +94,8 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
|
||||
}
|
||||
|
||||
// GET /api/cost/summary — total tokens, estimated cost, daily breakdown.
|
||||
// Intentionally FREE for all tiers (P22): it powers the personal Telemetry
|
||||
// dev-mode cost/budget view. The TEAM cost-visibility surface is the separate
|
||||
// /api/cost/by-workspace + /api/costs alias (both requireTier('TEAMS')).
|
||||
// Powers the Telemetry cost/budget view; /api/cost/by-workspace adds the
|
||||
// per-workspace breakdown and /api/costs is an alias of this route.
|
||||
server.get<{
|
||||
Querystring: { days?: string };
|
||||
}>('/api/cost/summary', async (request) => {
|
||||
@@ -220,7 +218,7 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
|
||||
});
|
||||
|
||||
// GET /api/cost/by-workspace — per-workspace token usage breakdown
|
||||
server.get('/api/cost/by-workspace', { preHandler: [requireTier('TEAMS')] }, async () => {
|
||||
server.get('/api/cost/by-workspace', async () => {
|
||||
const entries = getEntries();
|
||||
const workspaces = server.workspaceManager.list();
|
||||
|
||||
@@ -281,8 +279,7 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
|
||||
|
||||
// D2: Alias /api/costs → /api/cost/summary for API discoverability
|
||||
// Use internal routing instead of 302 redirect so clients get a direct 200 response
|
||||
// Cost visibility is a Team feature — gated identically to /api/cost/by-workspace.
|
||||
server.get('/api/costs', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
server.get('/api/costs', async (request, reply) => {
|
||||
const days = (request.query as Record<string, string>)?.days;
|
||||
const url = days ? `/api/cost/summary?days=${days}` : '/api/cost/summary';
|
||||
const response = await server.inject({ method: 'GET', url, headers: request.headers });
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* The read side (`GET /api/embedding/status`) and reprobe
|
||||
* (`POST /api/embedding/reprobe`) live inline in local/index.ts, where they have
|
||||
* closure access to the boot-time embedding config. This plugin owns
|
||||
* `POST /api/embedding/provider`: validate → tier-gate → persist the choice.
|
||||
* `POST /api/embedding/provider`: validate → persist the choice. Every provider is
|
||||
* selectable (ADR-0001).
|
||||
*
|
||||
* Hot-swap note: the live embedder is created once at boot and threaded BY
|
||||
* REFERENCE into the Orchestrator, mind search, and the vector-backfill path.
|
||||
@@ -19,8 +20,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { WaggleConfig, getMinimumTierForProvider, type EmbeddingProviderType } from '@waggle/core';
|
||||
import { TIER_CAPABILITIES, parseTier, getEffectiveTier, type Tier } from '@waggle/shared';
|
||||
import { WaggleConfig } from '@waggle/core';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
|
||||
/**
|
||||
@@ -35,19 +35,6 @@ const setProviderSchema = z.object({
|
||||
provider: z.enum(SELECTABLE_PROVIDERS),
|
||||
});
|
||||
|
||||
/** Effective tier from config.json (mirrors settings.ts readTierConfig + trial resolution). */
|
||||
function readEffectiveTier(dataDir: string): Tier {
|
||||
try {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier ?? '')) ?? 'FREE';
|
||||
return getEffectiveTier(parsed, raw.trialStartedAt ?? null);
|
||||
}
|
||||
} catch { /* fall through to FREE */ }
|
||||
return 'FREE';
|
||||
}
|
||||
|
||||
/** True when EMBEDDING_PROVIDER env var is set — it wins over the persisted choice. */
|
||||
function envOverrideProvider(): string | null {
|
||||
const v = process.env.EMBEDDING_PROVIDER?.trim();
|
||||
@@ -103,22 +90,6 @@ export const embeddingRoutes: FastifyPluginAsync = async (server) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Tier gate — 'auto' is always allowed; an explicit provider must be in
|
||||
// the tier's allowed set (TIER_CAPABILITIES.embeddingProviders).
|
||||
if (provider !== 'auto') {
|
||||
const tier = readEffectiveTier(server.localConfig.dataDir);
|
||||
const allowed = TIER_CAPABILITIES[tier].embeddingProviders as readonly string[];
|
||||
if (!allowed.includes(provider)) {
|
||||
const requiredTier = getMinimumTierForProvider(provider as EmbeddingProviderType);
|
||||
return reply.status(403).send({
|
||||
error: 'TIER_REQUIRED',
|
||||
message: `The "${provider}" embedding provider requires the ${requiredTier} tier or higher (current: ${tier}).`,
|
||||
requiredTier,
|
||||
currentTier: tier,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Persist (setEmbeddingProvider does not save on its own).
|
||||
const config = new WaggleConfig(server.localConfig.dataDir);
|
||||
config.setEmbeddingProvider(provider);
|
||||
|
||||
@@ -4,13 +4,11 @@
|
||||
*/
|
||||
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { parseTier, type GoalAncestry } from '@waggle/shared';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
import type { GoalAncestry } from '@waggle/shared';
|
||||
import { runAgentLoop, isEnabled, detectTaskShape, listPersonas } from '@waggle/agent';
|
||||
import { emitWaggleSignal } from './waggle-signals.js';
|
||||
import { persistMessage } from './chat-persistence.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
import { maxWorkspaceSessionsForTier } from '../tier-session-cap.js';
|
||||
import { spawnIsolatedFleetRun } from '../fleet-run-executor.js';
|
||||
import { resolveUsableModel } from '../model-availability.js';
|
||||
|
||||
@@ -58,15 +56,12 @@ export async function fleetRoutes(fastify: FastifyInstance) {
|
||||
};
|
||||
});
|
||||
|
||||
// Tier-based maxSessions: FREE=10, TEAMS=25, ENTERPRISE/TRIAL=100
|
||||
const tierRaw = fastify.localConfig?.tier ?? '';
|
||||
const tier = parseTier(String(tierRaw)) ?? 'FREE';
|
||||
const maxSessions = maxWorkspaceSessionsForTier(tier);
|
||||
const maxSessions = sessionManager.getMaxSessions();
|
||||
|
||||
return { sessions, count: sessions.length, maxSessions };
|
||||
});
|
||||
|
||||
// POST /api/fleet/spawn — spawn a new agent session (free for all tiers — agents generate memory)
|
||||
// POST /api/fleet/spawn — spawn a new agent session
|
||||
//
|
||||
// FR #15 Phase A: properly create the workspace session via getOrCreate so
|
||||
// Room/Mission Control register it as live, and emit an `agent:spawned`
|
||||
|
||||
@@ -18,7 +18,6 @@ import { validateSkillMd } from '@waggle/sdk';
|
||||
import { safeFetch, assertUrlAllowed, scanForInjection } from '@waggle/agent';
|
||||
import { getKvarkConfig } from '../../kvark/kvark-config.js';
|
||||
import { emitNotification } from './notifications.js';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
import { loadMcpConfig, removeMcpServerEntry } from '../mcp-config.js';
|
||||
import { enqueueHeldAction } from '../held-action-executor.js';
|
||||
import { isMarketplaceBackgroundSyncDisabled } from '../marketplace-background-sync.js';
|
||||
@@ -187,7 +186,7 @@ export async function marketplaceRoutes(fastify: FastifyInstance) {
|
||||
// Returns enterprise packs that require KVARK. Only populated when
|
||||
// KVARK credentials are configured in the vault.
|
||||
|
||||
fastify.get('/api/marketplace/enterprise-packs', { preHandler: [requireTier('ENTERPRISE')] }, async (request, reply) => {
|
||||
fastify.get('/api/marketplace/enterprise-packs', async (request, reply) => {
|
||||
const vault = fastify.vault;
|
||||
const kvarkConfigured = vault ? getKvarkConfig(vault) !== null : false;
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { WaggleConfig } from '@waggle/core';
|
||||
import { type Tier, TIERS, TIER_CAPABILITIES, parseTier, getCapabilities, getEffectiveTier, trialDaysRemaining } from '@waggle/shared';
|
||||
import type { AutonomyLevel } from '@waggle/agent';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
import { probeProviderKey, validateKeyFormat } from '../llm-key-probe.js';
|
||||
import { resolveExplicitRoutableModel, resolveUsableModel } from '../model-availability.js';
|
||||
import { maxWorkspaceSessionsForTier } from '../tier-session-cap.js';
|
||||
import { applyProviderKeyToEnv } from '../provider-env.js';
|
||||
import { refreshManagedLiteLLM, type LiteLLMRefreshResult } from '../litellm-runtime-config.js';
|
||||
|
||||
@@ -44,11 +41,6 @@ function maskApiKey(key: string): string {
|
||||
return key.slice(0, 7) + '...' + key.slice(-4);
|
||||
}
|
||||
|
||||
function applyRuntimeTier(server: FastifyInstance, tier: Tier): void {
|
||||
server.localConfig.tier = tier;
|
||||
server.sessionManager?.setMaxSessions(maxWorkspaceSessionsForTier(tier));
|
||||
}
|
||||
|
||||
export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
// GET /api/settings — read config (keys from vault, metadata from vault+config)
|
||||
server.get('/api/settings', async () => {
|
||||
@@ -445,162 +437,23 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
return updated;
|
||||
});
|
||||
|
||||
// ── Tier detection ───────────────────────────────────────────────────
|
||||
// Tier is read from config.json → tier field (defaults to FREE).
|
||||
// Canonical values: TRIAL | FREE | TEAMS | ENTERPRISE (@waggle/shared
|
||||
// tiers.ts). Legacy names (PRO/BASIC/lowercase) auto-migrate via parseTier().
|
||||
// The Stripe webhook (packages/server/src/stripe/webhook.ts) writes this field.
|
||||
|
||||
function readTierConfig(dataDir: string): { tier: Tier; trialStartedAt: string | null } {
|
||||
try {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier ?? ''));
|
||||
if (parsed) return { tier: parsed, trialStartedAt: raw.trialStartedAt ?? null };
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return { tier: 'FREE', trialStartedAt: null };
|
||||
}
|
||||
|
||||
// GET /api/tier — authoritative tier source for frontend
|
||||
server.get('/api/tier', async () => {
|
||||
const { tier: rawTier, trialStartedAt } = readTierConfig(server.localConfig.dataDir);
|
||||
const tier = getEffectiveTier(rawTier, trialStartedAt);
|
||||
const caps = getCapabilities(tier);
|
||||
const daysRemaining = trialDaysRemaining(trialStartedAt);
|
||||
// Usage counts for limit display
|
||||
const workspaceCount = server.workspaceManager?.list().length ?? 0;
|
||||
return {
|
||||
tier,
|
||||
rawTier,
|
||||
trialStartedAt,
|
||||
trialDaysRemaining: daysRemaining,
|
||||
trialExpired: rawTier === 'TRIAL' && tier === 'FREE',
|
||||
capabilities: caps,
|
||||
teamsServerUrl: process.env.DATABASE_URL
|
||||
? `http://127.0.0.1:${process.env.TEAMS_SERVER_PORT ?? '3101'}`
|
||||
: null,
|
||||
teamsServerAvailable: !!process.env.DATABASE_URL,
|
||||
usage: {
|
||||
workspaceCount,
|
||||
},
|
||||
// Legacy shape — kept for backward compatibility with existing frontend
|
||||
limits: {
|
||||
maxWorkspaces: caps.workspaceLimit,
|
||||
maxSessions: tier === 'FREE' ? 10 : 25,
|
||||
maxMembers: caps.teamMembersLimit,
|
||||
features: {
|
||||
teams: caps.sharedWorkspaces,
|
||||
marketplace: true,
|
||||
budgetControls: caps.adminPanel,
|
||||
kvark: tier === 'ENTERPRISE',
|
||||
governance: tier === 'ENTERPRISE',
|
||||
customModels: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// PATCH /api/tier — change tier (testing/dev — will be replaced by Stripe webhook)
|
||||
server.patch<{
|
||||
Body: { tier: string };
|
||||
}>('/api/tier', async (request, reply) => {
|
||||
// AV-3: this dev/test-only override must NOT be a production privilege-escalation
|
||||
// path. Under the loopback-trust model any local page/extension could PATCH a paid
|
||||
// tier for free (no payment, no auth). Fail closed — disabled unless explicitly
|
||||
// enabled for dev/testing. Legit tier changes flow through Stripe (sync/webhook)
|
||||
// and POST /api/tier/start-trial.
|
||||
if (process.env.WAGGLE_ALLOW_TIER_OVERRIDE !== '1') {
|
||||
return reply.status(403).send({ error: 'Tier override disabled', code: 'TIER_OVERRIDE_DISABLED' });
|
||||
}
|
||||
const { tier: tierRaw } = request.body ?? {};
|
||||
const parsed = parseTier(String(tierRaw ?? ''));
|
||||
if (!parsed) {
|
||||
return reply.status(400).send({ error: `Invalid tier. Must be one of: ${TIERS.join(', ')}` });
|
||||
}
|
||||
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try {
|
||||
if (fs.existsSync(configPath)) {
|
||||
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch { /* fresh */ }
|
||||
|
||||
raw.tier = parsed;
|
||||
fs.writeFileSync(configPath, JSON.stringify(raw, null, 2), 'utf-8');
|
||||
applyRuntimeTier(server, parsed);
|
||||
|
||||
return { tier: parsed, capabilities: getCapabilities(parsed), updated: true };
|
||||
});
|
||||
|
||||
// POST /api/tier/start-trial — atomic trial start.
|
||||
//
|
||||
// Sets `tier='TRIAL'` + `trialStartedAt=now` in a single write. Idempotent
|
||||
// by design: if `trialStartedAt` is already set, returns 409 with the
|
||||
// current tier state — a user gets exactly one 15-day trial. The previous
|
||||
// path (client-side `adapter.updateSettings({ tier: 'TRIAL', trialStartedAt })`)
|
||||
// was doubly broken: `updateSettings` didn't exist on the adapter, and
|
||||
// `PATCH /api/tier` ignores `trialStartedAt`, so trials silently never
|
||||
// started. See UpgradeModal `onStartTrial` and OnboardingWizard completion.
|
||||
server.post('/api/tier/start-trial', async (_request, reply) => {
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try {
|
||||
if (fs.existsSync(configPath)) {
|
||||
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch { /* fresh */ }
|
||||
|
||||
if (typeof raw.trialStartedAt === 'string' && raw.trialStartedAt.length > 0) {
|
||||
const existingTier = parseTier(String(raw.tier ?? '')) ?? 'FREE';
|
||||
const effective = getEffectiveTier(existingTier, raw.trialStartedAt);
|
||||
return reply.status(409).send({
|
||||
error: 'TRIAL_ALREADY_STARTED',
|
||||
message: 'A trial has already been started for this installation.',
|
||||
tier: effective,
|
||||
rawTier: existingTier,
|
||||
trialStartedAt: raw.trialStartedAt,
|
||||
trialDaysRemaining: trialDaysRemaining(raw.trialStartedAt),
|
||||
trialExpired: existingTier === 'TRIAL' && effective === 'FREE',
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
raw.tier = 'TRIAL';
|
||||
raw.trialStartedAt = now;
|
||||
fs.writeFileSync(configPath, JSON.stringify(raw, null, 2), 'utf-8');
|
||||
applyRuntimeTier(server, 'TRIAL');
|
||||
|
||||
return {
|
||||
tier: 'TRIAL' as Tier,
|
||||
rawTier: 'TRIAL' as Tier,
|
||||
trialStartedAt: now,
|
||||
trialDaysRemaining: trialDaysRemaining(now),
|
||||
trialExpired: false,
|
||||
capabilities: getCapabilities('TRIAL'),
|
||||
};
|
||||
});
|
||||
|
||||
// ── Cloud Sync ────────────────────────────────────────────────────
|
||||
|
||||
server.get('/api/cloud-sync', async () => {
|
||||
const { tier } = readTierConfig(server.localConfig.dataDir);
|
||||
const caps = getCapabilities(tier);
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try { if (fs.existsSync(configPath)) raw = JSON.parse(fs.readFileSync(configPath, 'utf-8')); } catch { /* */ }
|
||||
return {
|
||||
available: caps.cloudSync,
|
||||
// Cloud sync runs through the team server, which the community edition
|
||||
// does not ship (ADR-0003).
|
||||
available: false,
|
||||
enabled: raw.cloudSyncEnabled === true,
|
||||
tier,
|
||||
teamServerUrl: (raw.teamServer as Record<string, unknown>)?.url ?? null,
|
||||
connected: !!((raw.teamServer as Record<string, unknown>)?.token),
|
||||
};
|
||||
});
|
||||
|
||||
server.post<{ Body: { enabled: boolean } }>('/api/cloud-sync/toggle', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
server.post<{ Body: { enabled: boolean } }>('/api/cloud-sync/toggle', async (request, reply) => {
|
||||
const { enabled } = request.body ?? {};
|
||||
if (typeof enabled !== 'boolean') return reply.code(400).send({ error: 'enabled must be a boolean' });
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
@@ -613,7 +466,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
|
||||
// ── Admin Overview ────────────────────────────────────────────────
|
||||
|
||||
server.get('/api/admin/overview', { preHandler: [requireTier('TEAMS')] }, async () => {
|
||||
server.get('/api/admin/overview', async () => {
|
||||
const workspaces = server.workspaceManager?.list() ?? [];
|
||||
return {
|
||||
usage: { totalInputTokens: 0, totalOutputTokens: 0 },
|
||||
@@ -635,7 +488,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
// GET /api/admin/audit-export — download audit log as JSON or CSV
|
||||
server.get<{
|
||||
Querystring: { from?: string; to?: string; format?: 'json' | 'csv' };
|
||||
}>('/api/admin/audit-export', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
}>('/api/admin/audit-export', async (request, reply) => {
|
||||
const { from, to, format = 'json' } = request.query;
|
||||
const auditStore = server.auditStore;
|
||||
if (!auditStore?.getAll) {
|
||||
|
||||
@@ -15,7 +15,6 @@ import { WaggleConfig } from '@waggle/core';
|
||||
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
|
||||
import { emitNotification } from './notifications.js';
|
||||
import { emitAuditEvent } from './events.js';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
|
||||
// ── Local team DB ────────────────────────────────────────────────────
|
||||
|
||||
@@ -140,7 +139,7 @@ export async function teamRoutes(fastify: FastifyInstance) {
|
||||
* POST /api/team/connect
|
||||
* Connect to a team server by validating the token against the server's health endpoint.
|
||||
*/
|
||||
fastify.post('/api/team/connect', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
fastify.post('/api/team/connect', async (request, reply) => {
|
||||
const { serverUrl, token } = request.body as { serverUrl: string; token: string };
|
||||
|
||||
if (!serverUrl || !token) {
|
||||
@@ -454,7 +453,7 @@ export async function teamRoutes(fastify: FastifyInstance) {
|
||||
}
|
||||
|
||||
// GET /api/team/governance/permissions — get effective permissions for current user
|
||||
fastify.get('/api/team/governance/permissions', { preHandler: [requireTier('ENTERPRISE')] }, async (request, reply) => {
|
||||
fastify.get('/api/team/governance/permissions', async (request, reply) => {
|
||||
const { workspaceId } = request.query as { workspaceId?: string };
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
|
||||
@@ -5,7 +5,6 @@ import Database from 'better-sqlite3';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { MindDB, WaggleConfig, createFileStore, reconcileFtsIndex } from '@waggle/core';
|
||||
import { parseTier, getCapabilities } from '@waggle/shared';
|
||||
import { assertSafeSegment } from './validate.js';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
import { getBoundTeamServer } from '../team-server-binding.js';
|
||||
@@ -331,25 +330,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
|
||||
}>('/api/workspaces', { preHandler: validateBody(createWorkspaceSchema) }, async (request, reply) => {
|
||||
const { name, group, icon, model, personaId, directory, tone, teamId, teamServerUrl, teamRole, teamUserId, storageType, storagePath, storageConfig } = request.body;
|
||||
|
||||
// Tier limit enforcement: check workspaceLimit from @waggle/shared
|
||||
try {
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
const tierRaw = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf-8')).tier : '';
|
||||
const tier = parseTier(String(tierRaw ?? '')) ?? 'FREE';
|
||||
const caps = getCapabilities(tier);
|
||||
if (caps.workspaceLimit > 0) {
|
||||
const currentCount = server.workspaceManager.list().length;
|
||||
if (currentCount >= caps.workspaceLimit) {
|
||||
return reply.status(403).send({
|
||||
error: `Workspace limit reached for ${tier} tier (${caps.workspaceLimit} max). Upgrade to create more.`,
|
||||
tier,
|
||||
limit: caps.workspaceLimit,
|
||||
current: currentCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch { /* tier check failed — allow creation */ }
|
||||
|
||||
// BUG-R3-03: Validate model ID if provided
|
||||
if (model && !isValidModelId(model)) {
|
||||
return reply.status(400).send({
|
||||
|
||||
@@ -237,25 +237,12 @@ export class SessionTimeoutTracker {
|
||||
|
||||
/**
|
||||
* Routes exempt from bearer token authentication.
|
||||
*
|
||||
* `/api/stripe/webhook` is a tokenless POST from Stripe's servers — it can never
|
||||
* carry our per-process session bearer, so in a hosted (0.0.0.0) deploy it would
|
||||
* 401 before the handler and subscription-lifecycle events
|
||||
* (customer.subscription.deleted/updated) would never process — cancelled subs
|
||||
* would never downgrade to FREE. It is independently authenticated by Stripe
|
||||
* *signature verification* inside the handler (stripe.webhooks.constructEvent
|
||||
* rejects any body not signed with STRIPE_WEBHOOK_SECRET before the handler
|
||||
* trusts it), so exempting it from the bearer gate does not widen the trust
|
||||
* boundary. Desktop (loopback) mode is unaffected — Stripe can't reach a
|
||||
* loopback bind. The path string matches the route registered in
|
||||
* stripe/webhook.ts (`POST /api/stripe/webhook`, no prefix).
|
||||
*/
|
||||
const AUTH_EXEMPT_PATHS = [
|
||||
'/health',
|
||||
'/api/auth/session-token',
|
||||
'/api/browser-ext/session-token',
|
||||
'/api/browser-ext/pair',
|
||||
'/api/stripe/webhook',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -738,8 +725,8 @@ async function securityMiddlewarePlugin(
|
||||
// ── Bearer token authentication (SEC-011 + D1) ──
|
||||
// D1: localhost is NO LONGER trusted by default. Waggle is a desktop app that
|
||||
// coexists with browsers/extensions/other local apps, so "any loopback caller is
|
||||
// trusted" let any of them drive the authenticated API (e.g. the PATCH /api/tier
|
||||
// free upgrade). The Tauri webview obtains the token from the auth-exempt,
|
||||
// trusted" let any of them drive the authenticated API (e.g. change settings or
|
||||
// provider keys). The Tauri webview obtains the token from the auth-exempt,
|
||||
// same-origin-gated /api/auth/session-token bootstrap and sends it as a Bearer.
|
||||
// Set WAGGLE_TRUST_LOCALHOST=1 to restore legacy loopback trust (emergency escape).
|
||||
if (sessionToken) {
|
||||
|
||||
@@ -10,7 +10,6 @@ import type { LlmHealthStatus } from './index.js';
|
||||
import { startLiteLLM, stopLiteLLM, type LiteLLMStatus } from './lifecycle.js';
|
||||
import { createLogger } from './logger.js';
|
||||
import { resolveBindHost } from './net-config.js';
|
||||
import { readTierFromDataDir } from '../middleware/assert-tier.js';
|
||||
import { listOllamaChatModelIds } from './model-availability.js';
|
||||
import {
|
||||
readEraseMarker,
|
||||
@@ -245,9 +244,9 @@ export async function startService(options?: ServiceOptions): Promise<ServiceRes
|
||||
}
|
||||
|
||||
// D11: ONE startup line answering "which state am I running against?" —
|
||||
// resolved dataDir + effective tier. Logged after wipe/migration so it
|
||||
// reflects the directory the server will actually serve.
|
||||
log.info(`Data dir: ${dataDir} · tier: ${readTierFromDataDir(dataDir)}`);
|
||||
// the resolved dataDir. Logged after wipe/migration so it reflects the
|
||||
// directory the server will actually serve.
|
||||
log.info(`Data dir: ${dataDir}`);
|
||||
|
||||
// 3. Ensure personal.mind exists
|
||||
const personalPath = path.join(dataDir, 'personal.mind');
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Tier } from '@waggle/shared';
|
||||
|
||||
export function maxWorkspaceSessionsForTier(tier: Tier): number {
|
||||
if (tier === 'FREE') return 10;
|
||||
if (tier === 'TEAMS') return 25;
|
||||
return 100;
|
||||
}
|
||||
@@ -8,12 +8,15 @@
|
||||
* state (the "Option Y" fix from docs/plans/phase-a-the-room.md §9).
|
||||
*
|
||||
* Max concurrent sessions configurable (default: 3) to prevent resource exhaustion.
|
||||
* Tier-gate via setMaxSessions() at startup once the user's subscription is known.
|
||||
* The sidecar starts the manager with MAX_WORKSPACE_SESSIONS.
|
||||
*/
|
||||
|
||||
import type { MindDB } from '@waggle/core';
|
||||
import type { ToolDefinition, Orchestrator } from '@waggle/agent';
|
||||
|
||||
/** Concurrent workspace sessions the sidecar allows. */
|
||||
export const MAX_WORKSPACE_SESSIONS = 100;
|
||||
|
||||
export interface WorkspaceSession {
|
||||
workspaceId: string;
|
||||
mind: MindDB;
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* Tier enforcement middleware for Fastify routes.
|
||||
*
|
||||
* Usage:
|
||||
* server.post('/api/team/connect', { preHandler: [requireTier('TEAMS')] }, handler)
|
||||
*
|
||||
* Reads the current tier from config.json (same source as GET /api/tier).
|
||||
* Returns 403 with structured error when tier is insufficient.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { type Tier, assertTierCapability, TierError, parseTier, getEffectiveTier } from '@waggle/shared';
|
||||
|
||||
/**
|
||||
* Read the effective tier for a data directory.
|
||||
* Uses the same config.json source as the GET /api/tier route in settings.ts.
|
||||
* Also consumed by startService's D11 startup log line (no request in scope there).
|
||||
*/
|
||||
export function readTierFromDataDir(dataDir: string | undefined): Tier {
|
||||
try {
|
||||
if (!dataDir) return 'FREE';
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier ?? ''));
|
||||
if (parsed) return getEffectiveTier(parsed, raw.trialStartedAt ?? null);
|
||||
}
|
||||
} catch { /* unreadable config → fail closed to FREE */ }
|
||||
return 'FREE';
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the current tier from the server's data directory.
|
||||
*/
|
||||
export function readTierFromRequest(request: FastifyRequest): Tier {
|
||||
return readTierFromDataDir(request.server.localConfig?.dataDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fastify preHandler that enforces a minimum tier.
|
||||
* Returns 403 TIER_INSUFFICIENT if the current tier is below the required level.
|
||||
*/
|
||||
export function requireTier(minimumTier: Tier) {
|
||||
return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {
|
||||
const userTier = readTierFromRequest(request);
|
||||
try {
|
||||
assertTierCapability(userTier, minimumTier);
|
||||
} catch (e) {
|
||||
if (e instanceof TierError) {
|
||||
return void reply.code(403).send({
|
||||
error: 'TIER_INSUFFICIENT',
|
||||
message: `This feature requires the ${e.required} tier. You are on ${e.actual}.`,
|
||||
required: e.required,
|
||||
actual: e.actual,
|
||||
upgradeUrl: 'https://waggle-os.ai/upgrade',
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* Stripe Checkout — creates a checkout session for tier upgrades.
|
||||
*
|
||||
* POST /api/stripe/create-checkout-session
|
||||
* Body: { tier: 'TEAMS', billingPeriod?: 'monthly' | 'annual' }
|
||||
* Returns: { url: string }
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { Tier } from '@waggle/shared';
|
||||
import { getStripe, priceIdForTier } from './index.js';
|
||||
import { validateBody } from '../validate-body.js';
|
||||
|
||||
/** POST /api/stripe/create-checkout-session body — a billing action. `tier` is
|
||||
* shape-validated here (required string); the TEAMS-only business rule stays in
|
||||
* the handler so it can return the specific INVALID_TIER envelope. */
|
||||
const createCheckoutSchema = z.object({
|
||||
tier: z.string().min(1),
|
||||
billingPeriod: z.enum(['monthly', 'annual']).optional(),
|
||||
});
|
||||
|
||||
export const checkoutRoutes: FastifyPluginAsync = async (server) => {
|
||||
server.post<{
|
||||
Body: { tier: string; billingPeriod?: 'monthly' | 'annual' };
|
||||
}>('/api/stripe/create-checkout-session', { preHandler: validateBody(createCheckoutSchema) }, async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED', message: 'Stripe is not configured. Set STRIPE_SECRET_KEY.' });
|
||||
}
|
||||
|
||||
const { tier, billingPeriod } = request.body ?? {};
|
||||
|
||||
// TEAMS is the only paid tier with a Stripe price (PRO removed — Solo is free).
|
||||
if (tier !== 'TEAMS') {
|
||||
return reply.code(400).send({ error: 'INVALID_TIER', message: 'Only the Team tier supports Stripe checkout.' });
|
||||
}
|
||||
|
||||
const priceId = priceIdForTier(tier as Tier, billingPeriod);
|
||||
if (!priceId) {
|
||||
return reply.code(400).send({ error: 'NO_PRICE_CONFIGURED', message: `No Stripe price configured for ${tier} (${billingPeriod ?? 'monthly'}).` });
|
||||
}
|
||||
|
||||
try {
|
||||
const origin = request.headers['origin']
|
||||
?? process.env['APP_URL']
|
||||
?? 'http://localhost:1420';
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
success_url: `${origin}/payment-success?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: `${origin}/payment-cancelled`,
|
||||
allow_promotion_codes: true,
|
||||
metadata: {
|
||||
tier,
|
||||
billingPeriod: billingPeriod ?? 'monthly',
|
||||
},
|
||||
});
|
||||
|
||||
return { url: session.url };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Stripe session creation failed';
|
||||
return reply.code(502).send({ error: 'STRIPE_ERROR', message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,140 +0,0 @@
|
||||
/**
|
||||
* Stripe integration — checkout, webhook, and customer portal.
|
||||
*
|
||||
* All Stripe functionality is gated behind STRIPE_SECRET_KEY env var.
|
||||
* When not set, all /api/stripe/* routes return 503 STRIPE_NOT_CONFIGURED.
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import Stripe from 'stripe';
|
||||
import { type Tier, TIER_CAPABILITIES } from '@waggle/shared';
|
||||
|
||||
export { checkoutRoutes } from './checkout.js';
|
||||
export { webhookRoutes } from './webhook.js';
|
||||
export { portalRoutes } from './portal.js';
|
||||
export { syncRoutes } from './sync.js';
|
||||
|
||||
// ── Stripe SDK singleton ─────────────────────────────────────────────
|
||||
|
||||
let stripeInstance: Stripe | null = null;
|
||||
let stripeSecretKey: string | null = null;
|
||||
|
||||
/**
|
||||
* Get the Stripe SDK instance (lazy-initialized).
|
||||
* Returns null if STRIPE_SECRET_KEY is not set.
|
||||
*/
|
||||
export function getStripe(): Stripe | null {
|
||||
const secretKey = process.env['STRIPE_SECRET_KEY'] ?? null;
|
||||
if (secretKey === stripeSecretKey) return stripeInstance;
|
||||
|
||||
stripeSecretKey = secretKey;
|
||||
stripeInstance = secretKey
|
||||
? new Stripe(secretKey, { apiVersion: '2026-03-25.dahlia' })
|
||||
: null;
|
||||
|
||||
return stripeInstance;
|
||||
}
|
||||
|
||||
// ── Tier ↔ Price ID mapping ──────────────────────────────────────────
|
||||
|
||||
/** Collect non-empty env values for the given keys, preserving order. */
|
||||
function readPriceEnvs(...keys: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const k of keys) {
|
||||
const v = process.env[k];
|
||||
if (v) out.push(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a Stripe price ID back to a canonical Tier.
|
||||
*
|
||||
* Supports two env-var contracts that can coexist:
|
||||
* - **New 4-var contract** (matches `apps/www` Next.js port):
|
||||
* STRIPE_PRICE_PRO_MONTHLY / STRIPE_PRICE_PRO_ANNUAL
|
||||
* STRIPE_PRICE_TEAMS_MONTHLY / STRIPE_PRICE_TEAMS_ANNUAL
|
||||
* - **Legacy single-var contract** (older desktop sidecar env):
|
||||
* STRIPE_PRICE_PRO / STRIPE_PRICE_TEAMS
|
||||
* STRIPE_PRICE_BASIC (oldest alias)
|
||||
*
|
||||
* New contract is checked first; legacy vars act as additional fallbacks.
|
||||
* Resolution is synchronous and offline-safe — no Stripe API round-trip.
|
||||
*
|
||||
* PRO removed (Solo/Team collapse): the legacy PRO/BASIC price vars are still
|
||||
* READ, but now resolve to `'FREE'` so a legacy PRO subscriber lands on Solo
|
||||
* (never null, never locked out). Only TEAMS mints a paid tier.
|
||||
*/
|
||||
export function tierFromPriceId(priceId: string): Tier | null {
|
||||
const proPrices = readPriceEnvs(
|
||||
'STRIPE_PRICE_PRO_MONTHLY',
|
||||
'STRIPE_PRICE_PRO_ANNUAL',
|
||||
'STRIPE_PRICE_PRO',
|
||||
'STRIPE_PRICE_BASIC',
|
||||
);
|
||||
const teamsPrices = readPriceEnvs(
|
||||
'STRIPE_PRICE_TEAMS_MONTHLY',
|
||||
'STRIPE_PRICE_TEAMS_ANNUAL',
|
||||
'STRIPE_PRICE_TEAMS',
|
||||
);
|
||||
|
||||
if (proPrices.includes(priceId)) return 'FREE';
|
||||
if (teamsPrices.includes(priceId)) return 'TEAMS';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Resolve the Stripe price ID for a (tier, billingPeriod). Prefers the 4-var
|
||||
* period-specific contract, falls back to legacy single-var, then TIER_CAPABILITIES. */
|
||||
export function priceIdForTier(tier: Tier, billingPeriod: 'monthly' | 'annual' = 'monthly'): string | null {
|
||||
const period = billingPeriod === 'annual' ? 'ANNUAL' : 'MONTHLY';
|
||||
// The period-specific 4-var price is always preferred. TEAMS is the only
|
||||
// paid tier post-PRO-removal, so it is the only tier with a checkout price.
|
||||
const periodSpecific = tier === 'TEAMS'
|
||||
? process.env[`STRIPE_PRICE_TEAMS_${period}`]
|
||||
: undefined;
|
||||
if (periodSpecific) return periodSpecific;
|
||||
// F9 fail-closed: for ANNUAL, never fall back to a monthly-priced var. The legacy
|
||||
// single-var (STRIPE_PRICE_PRO/TEAMS/BASIC) and the TIER_CAPABILITIES default are
|
||||
// all monthly prices; charging one for an annual selection — while the UI shows the
|
||||
// annual price — is a billing lie. Returning null yields an honest 400
|
||||
// NO_PRICE_CONFIGURED (checkout.ts:30) instead of a wrong charge.
|
||||
if (billingPeriod === 'annual') return null;
|
||||
const candidates = tier === 'TEAMS'
|
||||
? [process.env.STRIPE_PRICE_TEAMS]
|
||||
: [];
|
||||
for (const c of candidates) if (c) return c;
|
||||
return TIER_CAPABILITIES[tier]?.stripePriceId ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/stripe/status → { configured } — a secret-free probe of whether Stripe
|
||||
* checkout is wired (STRIPE_SECRET_KEY present + stripe SDK loadable). Lets the
|
||||
* billing UI render the F8 honest "not configured" disabled state BEFORE a click,
|
||||
* instead of only surfacing the 503 after the user tries to subscribe.
|
||||
*/
|
||||
export const statusRoutes: FastifyPluginAsync = async (server) => {
|
||||
server.get('/api/stripe/status', async () => ({ configured: !!getStripe() }));
|
||||
};
|
||||
|
||||
// ── Combined route registration ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register all Stripe routes on a Fastify server.
|
||||
* Safe to call even when Stripe is not configured — routes will return 503.
|
||||
*/
|
||||
export const stripeRoutes: FastifyPluginAsync = async (server) => {
|
||||
// Webhook needs its own content type parser, so register in isolated context
|
||||
await server.register(async (webhookScope) => {
|
||||
const { webhookRoutes } = await import('./webhook.js');
|
||||
await webhookScope.register(webhookRoutes);
|
||||
});
|
||||
|
||||
// Checkout, portal, sync, and the config-status probe use standard JSON parsing
|
||||
const { checkoutRoutes } = await import('./checkout.js');
|
||||
const { portalRoutes } = await import('./portal.js');
|
||||
const { syncRoutes } = await import('./sync.js');
|
||||
await server.register(checkoutRoutes);
|
||||
await server.register(portalRoutes);
|
||||
await server.register(syncRoutes);
|
||||
await server.register(statusRoutes);
|
||||
};
|
||||
@@ -1,54 +0,0 @@
|
||||
/**
|
||||
* Stripe Customer Portal — lets paid users manage their subscription.
|
||||
*
|
||||
* POST /api/stripe/create-portal-session
|
||||
* Returns: { url: string }
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { requireTier } from '../middleware/assert-tier.js';
|
||||
import { getStripe } from './index.js';
|
||||
|
||||
export const portalRoutes: FastifyPluginAsync = async (server) => {
|
||||
// Ungated to any authenticated user (requireTier('FREE') is a no-op floor): a
|
||||
// legacy PRO subscriber (now Solo/FREE) must still reach the portal to self-cancel.
|
||||
// Non-subscribers are handled by the route's own NO_STRIPE_CUSTOMER 400 below.
|
||||
server.post('/api/stripe/create-portal-session', { preHandler: [requireTier('FREE')] }, async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED' });
|
||||
}
|
||||
|
||||
// Read stripe_customer_id from config.json
|
||||
const dataDir = server.localConfig?.dataDir;
|
||||
let customerId: string | null = null;
|
||||
try {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
customerId = raw.stripe_customer_id ?? null;
|
||||
}
|
||||
} catch { /* no config */ }
|
||||
|
||||
if (!customerId) {
|
||||
return reply.code(400).send({ error: 'NO_STRIPE_CUSTOMER', message: 'No Stripe customer found. Complete a checkout first.' });
|
||||
}
|
||||
|
||||
try {
|
||||
const origin = request.headers['origin']
|
||||
?? process.env['APP_URL']
|
||||
?? 'http://localhost:1420';
|
||||
|
||||
const session = await stripe.billingPortal.sessions.create({
|
||||
customer: customerId,
|
||||
return_url: `${origin}/settings`,
|
||||
});
|
||||
return { url: session.url };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Portal session creation failed';
|
||||
return reply.code(502).send({ error: 'STRIPE_ERROR', message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,90 +0,0 @@
|
||||
/**
|
||||
* Stripe Sync — poll-based tier synchronization for desktop apps.
|
||||
*
|
||||
* POST /api/stripe/sync
|
||||
* Body: { sessionId: string }
|
||||
* Returns: { tier: string, customerId: string }
|
||||
*
|
||||
* Desktop apps behind NAT cannot receive webhooks reliably.
|
||||
* The frontend calls this endpoint after Stripe checkout redirect
|
||||
* to confirm payment and update the local tier.
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { type Tier, parseTier } from '@waggle/shared';
|
||||
import { getStripe, tierFromPriceId } from './index.js';
|
||||
import { updateUserTier } from './webhook.js';
|
||||
|
||||
export const syncRoutes: FastifyPluginAsync = async (server) => {
|
||||
server.post<{
|
||||
Body: { sessionId: string };
|
||||
}>('/api/stripe/sync', async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED' });
|
||||
}
|
||||
|
||||
const { sessionId } = request.body ?? {};
|
||||
if (!sessionId || typeof sessionId !== 'string') {
|
||||
return reply.code(400).send({ error: 'MISSING_SESSION_ID', message: 'sessionId is required.' });
|
||||
}
|
||||
|
||||
const dataDir = server.localConfig?.dataDir;
|
||||
if (!dataDir) {
|
||||
return reply.code(500).send({ error: 'SERVER_MISCONFIGURED' });
|
||||
}
|
||||
|
||||
try {
|
||||
const session = await stripe.checkout.sessions.retrieve(sessionId, {
|
||||
expand: ['subscription'],
|
||||
});
|
||||
|
||||
// Payment gate: never grant a paid tier from an unpaid session.
|
||||
// metadata.tier is set at session creation (before payment), so an
|
||||
// unpaid sessionId would otherwise grant a free paid tier. 'no_payment_required'
|
||||
// covers 100%-off promo codes enabled via allow_promotion_codes.
|
||||
const paid = session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
|
||||
if (session.status !== 'complete' || !paid) {
|
||||
return reply.code(402).send({ error: 'PAYMENT_NOT_COMPLETED', message: 'Checkout session is not paid yet.' });
|
||||
}
|
||||
|
||||
const customerId = typeof session.customer === 'string'
|
||||
? session.customer
|
||||
: undefined;
|
||||
|
||||
// Resolve tier from subscription price or session metadata
|
||||
let tier: Tier | null = null;
|
||||
|
||||
// Try subscription price first (most reliable)
|
||||
const subscription = session.subscription;
|
||||
if (subscription && typeof subscription === 'object' && 'items' in subscription) {
|
||||
const sub = subscription as { items?: { data?: Array<{ price?: { id?: string } }> } };
|
||||
const priceId = sub.items?.data?.[0]?.price?.id;
|
||||
if (priceId) {
|
||||
tier = tierFromPriceId(priceId);
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to session metadata
|
||||
if (!tier) {
|
||||
const tierRaw = session.metadata?.tier;
|
||||
if (tierRaw) {
|
||||
tier = parseTier(tierRaw);
|
||||
}
|
||||
}
|
||||
|
||||
if (!tier) {
|
||||
return reply.code(400).send({ error: 'TIER_NOT_RESOLVED', message: 'Could not determine tier from checkout session.' });
|
||||
}
|
||||
|
||||
updateUserTier(dataDir, tier, customerId);
|
||||
server.log.info({ event: 'stripe_sync', tier, customerId });
|
||||
|
||||
return { tier, customerId: customerId ?? null };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Stripe sync failed';
|
||||
server.log.error({ event: 'stripe_sync_error', error: message });
|
||||
return reply.code(502).send({ error: 'STRIPE_ERROR', message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,189 +0,0 @@
|
||||
/**
|
||||
* Stripe Webhook — handles subscription lifecycle events.
|
||||
*
|
||||
* POST /api/stripe/webhook
|
||||
* Validates stripe-signature header, updates tier in config.json.
|
||||
*
|
||||
* CRITICAL: This route needs raw body for signature validation.
|
||||
* Fastify's addContentTypeParser is used to capture raw bytes.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { type Tier, parseTier, getCapabilities } from '@waggle/shared';
|
||||
import { getStripe, tierFromPriceId } from './index.js';
|
||||
|
||||
/**
|
||||
* Atomically write JSON to disk: write to a unique temp file in the same
|
||||
* directory, then rename over the target. rename(2) is atomic on the same
|
||||
* volume, so a crash mid-write leaves the previous complete file intact
|
||||
* instead of a torn/partial one. A module-scoped counter (not a timestamp)
|
||||
* keeps the temp name unique even within the same millisecond.
|
||||
*/
|
||||
let __tmpSeq = 0;
|
||||
function atomicWriteJson(filePath: string, data: unknown): void {
|
||||
const tmp = `${filePath}.${process.pid}.${__tmpSeq++}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8');
|
||||
const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
try {
|
||||
for (let attempt = 1; attempt <= 4; attempt++) {
|
||||
try {
|
||||
fs.renameSync(tmp, filePath);
|
||||
return;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
const transient = code === 'EPERM' || code === 'EACCES' || code === 'EBUSY';
|
||||
if (!transient || attempt === 4) throw error;
|
||||
// Windows antivirus and indexers can briefly hold an exclusive handle.
|
||||
Atomics.wait(waitBuffer, 0, 0, 25 * attempt);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* R1-011: serialize the webhook critical section. atomicWriteJson prevents torn
|
||||
* files, but two concurrent deliveries of the SAME event (a real Stripe retry
|
||||
* scenario) could both read .stripe-processed-events.json before either wrote,
|
||||
* both pass the idempotency check, and both run updateUserTier — a TOCTOU race
|
||||
* that can write contradictory tiers. This module-scoped promise queue makes the
|
||||
* read-check-process-write sequence mutually exclusive; one failure never wedges
|
||||
* the queue (the tail swallows rejections).
|
||||
*/
|
||||
let __webhookTail: Promise<void> = Promise.resolve();
|
||||
function serializeWebhook<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const result = __webhookTail.then(() => fn());
|
||||
__webhookTail = result.then(() => undefined, () => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's tier (and optionally Stripe customer ID) in config.json.
|
||||
* This is the same storage used by readTierFromRequest() in the tier middleware
|
||||
* and by the portal route to read stripe_customer_id.
|
||||
*/
|
||||
function updateUserTier(dataDir: string, tier: Tier, customerId?: string): void {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try {
|
||||
if (fs.existsSync(configPath)) {
|
||||
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch { /* fresh config */ }
|
||||
const updated = { ...raw, tier, ...(customerId ? { stripe_customer_id: customerId } : {}) };
|
||||
atomicWriteJson(configPath, updated);
|
||||
}
|
||||
|
||||
export const webhookRoutes: FastifyPluginAsync = async (server) => {
|
||||
// Register raw body parser for this route only
|
||||
server.addContentTypeParser(
|
||||
'application/json',
|
||||
{ parseAs: 'buffer' },
|
||||
(_req, body, done) => {
|
||||
done(null, body);
|
||||
},
|
||||
);
|
||||
|
||||
server.post('/api/stripe/webhook', async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
const webhookSecret = process.env['STRIPE_WEBHOOK_SECRET'];
|
||||
if (!stripe || !webhookSecret) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED' });
|
||||
}
|
||||
|
||||
const signature = request.headers['stripe-signature'];
|
||||
if (!signature) {
|
||||
return reply.code(400).send({ error: 'MISSING_SIGNATURE' });
|
||||
}
|
||||
|
||||
let event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(
|
||||
request.body as Buffer,
|
||||
signature as string,
|
||||
webhookSecret,
|
||||
);
|
||||
} catch {
|
||||
return reply.code(400).send({ error: 'INVALID_SIGNATURE' });
|
||||
}
|
||||
|
||||
const dataDir = server.localConfig?.dataDir;
|
||||
if (!dataDir) {
|
||||
return reply.code(500).send({ error: 'SERVER_MISCONFIGURED' });
|
||||
}
|
||||
|
||||
// R1-011: run idempotency-check + processing + processed-write as ONE
|
||||
// serialized critical section so concurrent retries of the same event cannot
|
||||
// both slip past the dedup check and double-process a tier change.
|
||||
const processedPath = path.join(dataDir, '.stripe-processed-events.json');
|
||||
const outcome = await serializeWebhook<'duplicate' | 'processed'>(async () => {
|
||||
let processedIds: string[] = [];
|
||||
try { processedIds = JSON.parse(fs.readFileSync(processedPath, 'utf-8')); } catch { /* first run */ }
|
||||
if (processedIds.includes(event.id)) {
|
||||
server.log.info({ event: 'webhook_duplicate_skipped', eventId: event.id });
|
||||
return 'duplicate';
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object as { payment_status?: string; metadata?: Record<string, string>; customer?: string };
|
||||
// R1-002 (webhook path): checkout.session.completed also fires for
|
||||
// UNPAID sessions (async/delayed payment methods, incomplete
|
||||
// checkouts). Only grant a tier once payment has actually settled —
|
||||
// same gate as the /api/stripe/sync path (sync.ts). 'paid' covers
|
||||
// normal purchases; 'no_payment_required' covers 100%-off coupons.
|
||||
const paid = session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
|
||||
const tierRaw = session.metadata?.tier;
|
||||
if (paid && tierRaw) {
|
||||
const parsed = parseTier(tierRaw);
|
||||
if (parsed) {
|
||||
const customerId = typeof session.customer === 'string' ? session.customer : undefined;
|
||||
updateUserTier(dataDir, parsed, customerId);
|
||||
server.log.info({ event: 'checkout_completed', tier: parsed, customerId });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object as { customer?: string; items?: { data?: Array<{ price?: { id?: string } }> } };
|
||||
const priceId = subscription.items?.data?.[0]?.price?.id;
|
||||
if (priceId) {
|
||||
const newTier = tierFromPriceId(priceId);
|
||||
if (newTier) {
|
||||
const customerId = typeof subscription.customer === 'string' ? subscription.customer : undefined;
|
||||
updateUserTier(dataDir, newTier, customerId);
|
||||
server.log.info({ event: 'subscription_updated', tier: newTier, customerId });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.deleted': {
|
||||
updateUserTier(dataDir, 'FREE');
|
||||
server.log.info({ event: 'subscription_cancelled' });
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// Unknown event types are silently acknowledged
|
||||
break;
|
||||
}
|
||||
|
||||
// Mark event as processed (keep last 500 IDs to avoid unbounded growth)
|
||||
processedIds.push(event.id);
|
||||
if (processedIds.length > 500) processedIds.splice(0, processedIds.length - 500);
|
||||
try { atomicWriteJson(processedPath, processedIds); } catch { /* best effort */ }
|
||||
return 'processed';
|
||||
});
|
||||
|
||||
if (outcome === 'duplicate') return reply.send({ received: true, duplicate: true });
|
||||
return { received: true };
|
||||
});
|
||||
};
|
||||
|
||||
export { updateUserTier };
|
||||
@@ -1,19 +1,16 @@
|
||||
/**
|
||||
* D11 (UX-Refactor P4) — dataDir resolution + startup tier read.
|
||||
* D11 (UX-Refactor P4) — dataDir resolution.
|
||||
*
|
||||
* - resolveDataDir: explicit option > WAGGLE_DATA_DIR env > ~/.waggle. Before
|
||||
* D11, startService ignored the env var while local/index.ts, the
|
||||
* marketplace installer, and memory-mcp honored it — a custom install split
|
||||
* its state across two directories.
|
||||
* - readTierFromDataDir: the startup log line's tier source — same
|
||||
* config.json contract as GET /api/tier, fails closed to FREE.
|
||||
*/
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { startService, resolveDataDir } from '../src/local/service.js';
|
||||
import { readTierFromDataDir } from '../src/middleware/assert-tier.js';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
|
||||
function makeTmpDir(): string {
|
||||
@@ -85,47 +82,9 @@ describe('startService honors WAGGLE_DATA_DIR (D11 integration)', () => {
|
||||
.map((c) => String(c[0]))
|
||||
.find((m) => m.includes('[waggle:service] Data dir:'));
|
||||
expect(dataDirLine).toContain(envDir);
|
||||
expect(dataDirLine).toMatch(/· tier: (TRIAL|FREE|TEAMS|ENTERPRISE)$/);
|
||||
expect(dataDirLine?.endsWith(`Data dir: ${envDir}`)).toBe(true);
|
||||
} finally {
|
||||
logSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('readTierFromDataDir (D11 startup log tier source)', () => {
|
||||
let tmp: string;
|
||||
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
|
||||
|
||||
function writeConfig(obj: Record<string, unknown>): string {
|
||||
tmp = makeTmpDir();
|
||||
fs.writeFileSync(path.join(tmp, 'config.json'), JSON.stringify(obj));
|
||||
return tmp;
|
||||
}
|
||||
|
||||
it('reads a canonical tier', () => {
|
||||
expect(readTierFromDataDir(writeConfig({ tier: 'TEAMS' }))).toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('migrates legacy names (solo/basic/pro all → FREE after the Solo/Team collapse)', () => {
|
||||
expect(readTierFromDataDir(writeConfig({ tier: 'solo' }))).toBe('FREE');
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
expect(readTierFromDataDir(writeConfig({ tier: 'basic' }))).toBe('FREE');
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
expect(readTierFromDataDir(writeConfig({ tier: 'pro' }))).toBe('FREE');
|
||||
});
|
||||
|
||||
it('TRIAL downgrades to FREE when expired (effective tier, not raw)', () => {
|
||||
const expired = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
expect(readTierFromDataDir(writeConfig({ tier: 'TRIAL', trialStartedAt: expired }))).toBe('FREE');
|
||||
});
|
||||
|
||||
it('fails closed to FREE on missing dir, missing config, malformed JSON, unknown tier', () => {
|
||||
expect(readTierFromDataDir(undefined)).toBe('FREE');
|
||||
expect(readTierFromDataDir(path.join(os.tmpdir(), 'waggle-d11-nonexistent'))).toBe('FREE');
|
||||
tmp = makeTmpDir();
|
||||
fs.writeFileSync(path.join(tmp, 'config.json'), '{not json');
|
||||
expect(readTierFromDataDir(tmp)).toBe('FREE');
|
||||
fs.writeFileSync(path.join(tmp, 'config.json'), JSON.stringify({ tier: 'PLATINUM' }));
|
||||
expect(readTierFromDataDir(tmp)).toBe('FREE');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Embedding routing API tests (steal #10) —
|
||||
* GET /api/embedding/status (enriched: configuredProvider + envOverride)
|
||||
* POST /api/embedding/provider (validate → tier-gate → persist → restartRequired)
|
||||
* POST /api/embedding/provider (validate → persist → restartRequired)
|
||||
*
|
||||
* Note: vitest.setup.ts pins EMBEDDING_PROVIDER='mock' for the whole suite, so the
|
||||
* env-override branch would otherwise 409 every write. We clear it per-test to
|
||||
@@ -28,7 +28,6 @@ describe('Embedding routing API', () => {
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-embrouting-test-'));
|
||||
// No `tier` field → effective tier resolves to FREE (litellm gated off).
|
||||
fs.writeFileSync(path.join(tmpDir, 'config.json'), JSON.stringify({}));
|
||||
fs.mkdirSync(path.join(tmpDir, 'skills'), { recursive: true });
|
||||
fs.writeFileSync(path.join(tmpDir, 'skills', '.starter-installed'), 'test');
|
||||
@@ -86,19 +85,16 @@ describe('Embedding routing API', () => {
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('POST /api/embedding/provider tier-gates litellm on FREE with 403', async () => {
|
||||
it('POST /api/embedding/provider accepts litellm (every provider is selectable)', async () => {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/embedding/provider',
|
||||
payload: { provider: 'litellm' },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.error).toBe('TIER_REQUIRED');
|
||||
expect(body.requiredTier).toBeDefined();
|
||||
expect(body.currentTier).toBe('FREE');
|
||||
// Rejected write must not have persisted.
|
||||
expect(readConfig().embedding).toBeUndefined();
|
||||
expect(body.configuredProvider).toBe('litellm');
|
||||
expect((readConfig().embedding as { provider?: string }).provider).toBe('litellm');
|
||||
});
|
||||
|
||||
it('POST /api/embedding/provider persists "auto" (no restart required)', async () => {
|
||||
@@ -114,11 +110,11 @@ describe('Embedding routing API', () => {
|
||||
expect((readConfig().embedding as { provider?: string }).provider).toBe('auto');
|
||||
});
|
||||
|
||||
it('POST /api/embedding/provider persists a tier-allowed provider with restartRequired', async () => {
|
||||
it('POST /api/embedding/provider persists an explicit provider with restartRequired', async () => {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/embedding/provider',
|
||||
payload: { provider: 'inprocess' }, // FREE allows inprocess
|
||||
payload: { provider: 'inprocess' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
|
||||
@@ -53,6 +53,7 @@ describe('Fleet Routes', () => {
|
||||
it('returns empty array when session manager has no active sessions', async () => {
|
||||
const mockManager = {
|
||||
getActive: () => [],
|
||||
getMaxSessions: () => 100,
|
||||
};
|
||||
server = createTestServer(mockManager);
|
||||
const res = await server.inject({ method: 'GET', url: '/api/fleet' });
|
||||
@@ -61,7 +62,7 @@ describe('Fleet Routes', () => {
|
||||
const body = res.json();
|
||||
expect(body.sessions).toEqual([]);
|
||||
expect(body.count).toBe(0);
|
||||
expect(body.maxSessions).toBe(10); // FREE (Solo) session cap — raised from 3 in the 2026-07-05 Solo-vs-Team migration
|
||||
expect(body.maxSessions).toBe(100); // reported from the session manager
|
||||
});
|
||||
|
||||
it('returns agent status when sessions exist', async () => {
|
||||
@@ -83,6 +84,7 @@ describe('Fleet Routes', () => {
|
||||
lastActivity: now - 60000,
|
||||
},
|
||||
],
|
||||
getMaxSessions: () => 100,
|
||||
};
|
||||
server = createTestServer(mockManager);
|
||||
const res = await server.inject({ method: 'GET', url: '/api/fleet' });
|
||||
@@ -90,7 +92,7 @@ describe('Fleet Routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.count).toBe(2);
|
||||
expect(body.maxSessions).toBe(10); // FREE (Solo) session cap — raised from 3 in the 2026-07-05 Solo-vs-Team migration
|
||||
expect(body.maxSessions).toBe(100); // reported from the session manager
|
||||
expect(body.sessions).toHaveLength(2);
|
||||
|
||||
// First session
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* Connector tier cap (review LOW #1, founder-requested enforcement). After the
|
||||
* Solo/Team collapse EVERY tier has an unlimited connectorLimit (-1), so
|
||||
* connectorCapExceeded never caps a real tier. These tests pin that unlimited
|
||||
* contract; re-connecting an already-connected connector (token refresh) is a
|
||||
* no-op regardless.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getCapabilities } from '@waggle/shared';
|
||||
import { connectorCapExceeded } from '../../src/local/routes/connectors.js';
|
||||
|
||||
describe('connectorCapExceeded', () => {
|
||||
it('FREE (Solo) is unlimited (-1) — never capped', () => {
|
||||
expect(getCapabilities('FREE').connectorLimit).toBe(-1);
|
||||
const many = Array.from({ length: 50 }, (_, i) => `c${i}`);
|
||||
expect(connectorCapExceeded('FREE', many, 'new-one')).toBeNull();
|
||||
});
|
||||
|
||||
it('FREE re-connecting an already-connected connector → allowed (token refresh)', () => {
|
||||
const many = Array.from({ length: 50 }, (_, i) => `c${i}`);
|
||||
expect(connectorCapExceeded('FREE', many, 'c0')).toBeNull();
|
||||
});
|
||||
|
||||
it('TEAMS is unlimited — never capped', () => {
|
||||
const many = Array.from({ length: 50 }, (_, i) => `c${i}`);
|
||||
expect(connectorCapExceeded('TEAMS', many, 'new-one')).toBeNull();
|
||||
});
|
||||
|
||||
it('TRIAL is unlimited — never capped', () => {
|
||||
const many = Array.from({ length: 50 }, (_, i) => `c${i}`);
|
||||
expect(connectorCapExceeded('TRIAL', many, 'new-one')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,369 +0,0 @@
|
||||
/**
|
||||
* POST /api/tier/start-trial — atomic trial start.
|
||||
*
|
||||
* Pins the contract used by Desktop's UpgradeModal `onStartTrial` and the
|
||||
* onboarding-complete handler. The previous path silently failed for two
|
||||
* reasons (missing `adapter.updateSettings`, server `PATCH /api/tier`
|
||||
* ignoring `trialStartedAt`); this route + these tests guard against either
|
||||
* regression.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildLocalServer } from '../src/local/index.js';
|
||||
import { authInject } from './test-utils.js';
|
||||
|
||||
function readConfig(dataDir: string): Record<string, unknown> {
|
||||
const p = path.join(dataDir, 'config.json');
|
||||
if (!fs.existsSync(p)) return {};
|
||||
return JSON.parse(fs.readFileSync(p, 'utf-8')) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function writeConfig(dataDir: string, value: Record<string, unknown>): void {
|
||||
fs.writeFileSync(path.join(dataDir, 'config.json'), JSON.stringify(value), 'utf-8');
|
||||
}
|
||||
|
||||
describe('POST /api/tier/start-trial', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-start-trial-'));
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server.close();
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* EBUSY on win32 */ }
|
||||
});
|
||||
|
||||
it('starts a fresh trial — writes tier=TRIAL + trialStartedAt and returns 200', async () => {
|
||||
const before = Date.now();
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'POST',
|
||||
url: '/api/tier/start-trial',
|
||||
}));
|
||||
const after = Date.now();
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as {
|
||||
tier: string; rawTier: string; trialStartedAt: string;
|
||||
trialDaysRemaining: number; trialExpired: boolean;
|
||||
capabilities: Record<string, unknown>;
|
||||
};
|
||||
expect(body.tier).toBe('TRIAL');
|
||||
expect(body.rawTier).toBe('TRIAL');
|
||||
expect(body.trialExpired).toBe(false);
|
||||
// Fresh trial is 15 days; Math.ceil floor is 15.
|
||||
expect(body.trialDaysRemaining).toBe(15);
|
||||
|
||||
// trialStartedAt must be a valid ISO timestamp within the request window.
|
||||
const t = new Date(body.trialStartedAt).getTime();
|
||||
expect(t).toBeGreaterThanOrEqual(before);
|
||||
expect(t).toBeLessThanOrEqual(after);
|
||||
|
||||
// Server-side persistence — guards against the original PATCH /api/tier
|
||||
// bug where `trialStartedAt` was never written.
|
||||
const persisted = readConfig(tmpDir);
|
||||
expect(persisted.tier).toBe('TRIAL');
|
||||
expect(persisted.trialStartedAt).toBe(body.trialStartedAt);
|
||||
expect(server.localConfig.tier).toBe('TRIAL');
|
||||
expect(server.sessionManager.getMaxSessions()).toBe(100);
|
||||
});
|
||||
|
||||
it('returns 409 TRIAL_ALREADY_STARTED if a trial timestamp is already on disk', async () => {
|
||||
const earlier = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(); // 5 days ago
|
||||
writeConfig(tmpDir, { tier: 'TRIAL', trialStartedAt: earlier });
|
||||
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'POST',
|
||||
url: '/api/tier/start-trial',
|
||||
}));
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = res.json() as {
|
||||
error: string; tier: string; trialStartedAt: string; trialDaysRemaining: number;
|
||||
};
|
||||
expect(body.error).toBe('TRIAL_ALREADY_STARTED');
|
||||
expect(body.trialStartedAt).toBe(earlier);
|
||||
// 5 days in → ~10 days remaining.
|
||||
expect(body.trialDaysRemaining).toBe(10);
|
||||
|
||||
// Crucially: the timestamp on disk must NOT have been overwritten.
|
||||
const persisted = readConfig(tmpDir);
|
||||
expect(persisted.trialStartedAt).toBe(earlier);
|
||||
});
|
||||
|
||||
it('returns 409 for an expired trial (no silent restart) and reports trialExpired=true', async () => {
|
||||
// 16 days ago — past the 15-day trial window.
|
||||
const long_ago = new Date(Date.now() - 16 * 24 * 60 * 60 * 1000).toISOString();
|
||||
writeConfig(tmpDir, { tier: 'TRIAL', trialStartedAt: long_ago });
|
||||
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'POST',
|
||||
url: '/api/tier/start-trial',
|
||||
}));
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = res.json() as { error: string; tier: string; trialExpired: boolean };
|
||||
expect(body.error).toBe('TRIAL_ALREADY_STARTED');
|
||||
// Effective tier downgraded to FREE; rawTier still TRIAL; trialExpired flag set.
|
||||
expect(body.tier).toBe('FREE');
|
||||
expect(body.trialExpired).toBe(true);
|
||||
|
||||
// Disk untouched.
|
||||
const persisted = readConfig(tmpDir);
|
||||
expect(persisted.trialStartedAt).toBe(long_ago);
|
||||
expect(persisted.tier).toBe('TRIAL');
|
||||
});
|
||||
|
||||
it('does not overwrite an existing paid tier — 409 still fires when trialStartedAt is set on a TEAMS tier', async () => {
|
||||
// Edge case: a TEAMS user who happens to have an old trial timestamp from
|
||||
// before they upgraded. We must not downgrade them by re-applying TRIAL.
|
||||
const old = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
writeConfig(tmpDir, { tier: 'TEAMS', trialStartedAt: old });
|
||||
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'POST',
|
||||
url: '/api/tier/start-trial',
|
||||
}));
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
// Disk must keep TEAMS.
|
||||
const persisted = readConfig(tmpDir);
|
||||
expect(persisted.tier).toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('applies a persisted paid tier to the runtime session cap on startup', async () => {
|
||||
await server.close();
|
||||
writeConfig(tmpDir, { tier: 'TEAMS' });
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
|
||||
expect(server.localConfig.tier).toBe('TEAMS');
|
||||
expect(server.sessionManager.getMaxSessions()).toBe(25);
|
||||
});
|
||||
});
|
||||
|
||||
// ── AV-3 — PATCH /api/tier is a dev-only override, disabled in production ──
|
||||
// Under the loopback-trust model this route was an unauthenticated free-upgrade
|
||||
// path. It now fails closed unless WAGGLE_ALLOW_TIER_OVERRIDE=1.
|
||||
describe('PATCH /api/tier override gate (AV-3)', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-tier-gate-'));
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
});
|
||||
afterEach(async () => {
|
||||
delete process.env.WAGGLE_ALLOW_TIER_OVERRIDE;
|
||||
await server.close();
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* EBUSY on win32 */ }
|
||||
});
|
||||
|
||||
it('rejects PATCH /api/tier by default (override disabled) — no free upgrade', async () => {
|
||||
delete process.env.WAGGLE_ALLOW_TIER_OVERRIDE;
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'PATCH', url: '/api/tier', payload: { tier: 'TEAMS' },
|
||||
}));
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json().code).toBe('TIER_OVERRIDE_DISABLED');
|
||||
expect(readConfig(tmpDir).tier).not.toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('allows PATCH /api/tier when WAGGLE_ALLOW_TIER_OVERRIDE=1 (dev/test)', async () => {
|
||||
process.env.WAGGLE_ALLOW_TIER_OVERRIDE = '1';
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'PATCH', url: '/api/tier', payload: { tier: 'TEAMS' },
|
||||
}));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(readConfig(tmpDir).tier).toBe('TEAMS');
|
||||
expect(server.localConfig.tier).toBe('TEAMS');
|
||||
expect(server.sessionManager.getMaxSessions()).toBe(25);
|
||||
});
|
||||
});
|
||||
|
||||
// ── D1 — loopback now requires a token; the webview bootstraps it ──────────
|
||||
describe('D1 loopback auth + session-token bootstrap', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
const originalHost = process.env.WAGGLE_HOST;
|
||||
const originalInstanceId = process.env.WAGGLE_INSTANCE_ID;
|
||||
const originalDesktopBootstrap = process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN;
|
||||
const desktopBootstrap = 'desktop-bootstrap-test-1234567890';
|
||||
|
||||
beforeEach(async () => {
|
||||
// Exercise the SECURE D1 default (the suite setup defaults trust ON).
|
||||
process.env.WAGGLE_TRUST_LOCALHOST = '0';
|
||||
process.env.WAGGLE_INSTANCE_ID = 'desktop-instance-test';
|
||||
process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN = desktopBootstrap;
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-d1-'));
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await server.close();
|
||||
process.env.WAGGLE_TRUST_LOCALHOST = '1';
|
||||
if (originalHost === undefined) delete process.env.WAGGLE_HOST;
|
||||
else process.env.WAGGLE_HOST = originalHost;
|
||||
if (originalInstanceId === undefined) delete process.env.WAGGLE_INSTANCE_ID;
|
||||
else process.env.WAGGLE_INSTANCE_ID = originalInstanceId;
|
||||
if (originalDesktopBootstrap === undefined) delete process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN;
|
||||
else process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN = originalDesktopBootstrap;
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* EBUSY on win32 */ }
|
||||
});
|
||||
|
||||
it('serves the session token only with the per-launch desktop bootstrap credential', async () => {
|
||||
const res = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: { 'x-waggle-desktop-bootstrap': desktopBootstrap },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
const token = res.json().token as string;
|
||||
expect(typeof token).toBe('string');
|
||||
expect(token.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('scrubs the launch credential before child processes can inherit it', () => {
|
||||
expect(process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects a browser-reachable Tauri origin without the IPC-only bootstrap credential', async () => {
|
||||
const missing = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: { origin: 'http://tauri.localhost' },
|
||||
});
|
||||
expect(missing.statusCode).toBe(403);
|
||||
expect(missing.json().code).toBe('DESKTOP_BOOTSTRAP_REQUIRED');
|
||||
|
||||
const wrong = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: {
|
||||
origin: 'http://tauri.localhost',
|
||||
'x-waggle-desktop-bootstrap': 'wrong-bootstrap-token-1234567890',
|
||||
},
|
||||
});
|
||||
expect(wrong.statusCode).toBe(403);
|
||||
expect(wrong.json().code).toBe('DESKTOP_BOOTSTRAP_REQUIRED');
|
||||
});
|
||||
|
||||
it('binds browser-mode bootstrap to the exact request authority', async () => {
|
||||
await server.close();
|
||||
delete process.env.WAGGLE_INSTANCE_ID;
|
||||
delete process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN;
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
|
||||
const crossLoopback = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: {
|
||||
host: '127.0.0.1:3333',
|
||||
origin: 'http://127.0.0.1:5174',
|
||||
},
|
||||
});
|
||||
expect(crossLoopback.statusCode).toBe(403);
|
||||
|
||||
const sameOrigin = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: {
|
||||
host: '127.0.0.1:3333',
|
||||
origin: 'http://127.0.0.1:3333',
|
||||
},
|
||||
});
|
||||
expect(sameOrigin.statusCode).toBe(200);
|
||||
|
||||
for (const headers of [
|
||||
{
|
||||
host: '127.0.0.1:3333',
|
||||
origin: 'http://127.0.0.1:3333',
|
||||
'sec-fetch-site': 'none',
|
||||
},
|
||||
{
|
||||
host: '127.0.0.1:3333',
|
||||
referer: 'http://127.0.0.1:3333/app',
|
||||
'sec-fetch-site': 'none',
|
||||
},
|
||||
]) {
|
||||
const inconsistent = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers,
|
||||
});
|
||||
expect(inconsistent.statusCode).toBe(403);
|
||||
expect(inconsistent.json().code).toBe('SESSION_BOOTSTRAP_ORIGIN_MISMATCH');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects originless top-level and MV3 requests at the browser-mode process-token bootstrap', async () => {
|
||||
await server.close();
|
||||
delete process.env.WAGGLE_INSTANCE_ID;
|
||||
delete process.env.WAGGLE_DESKTOP_BOOTSTRAP_TOKEN;
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
|
||||
for (const headers of [
|
||||
{ host: '127.0.0.1:3333', 'sec-fetch-site': 'none' },
|
||||
{
|
||||
host: '127.0.0.1:3333',
|
||||
'sec-fetch-site': 'none',
|
||||
'x-waggle-extension-id': 'abcdefghijklmnopabcdefghijklmnop',
|
||||
},
|
||||
]) {
|
||||
const res = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers,
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json().code).toBe('SESSION_BOOTSTRAP_ORIGIN_MISMATCH');
|
||||
}
|
||||
|
||||
const sameOriginFetch = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: {
|
||||
host: '127.0.0.1:3333',
|
||||
'sec-fetch-site': 'same-origin',
|
||||
},
|
||||
});
|
||||
expect(sameOriginFetch.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('does not expose the process bearer when the sidecar is non-loopback-bound', async () => {
|
||||
await server.close();
|
||||
process.env.WAGGLE_HOST = '0.0.0.0';
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
|
||||
const res = await server.inject({ method: 'GET', url: '/api/auth/session-token' });
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json().code).toBe('SESSION_BOOTSTRAP_LOOPBACK_ONLY');
|
||||
});
|
||||
|
||||
it('requires a bearer token on a normal route (loopback no longer trusted)', async () => {
|
||||
const res = await server.inject({ method: 'GET', url: '/api/tier' });
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('accepts a normal route when the bootstrapped token is presented', async () => {
|
||||
const token = (await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/auth/session-token',
|
||||
headers: { 'x-waggle-desktop-bootstrap': desktopBootstrap },
|
||||
})).json().token as string;
|
||||
const res = await server.inject({
|
||||
method: 'GET', url: '/api/tier',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -1,160 +0,0 @@
|
||||
/**
|
||||
* Stripe Checkout — billingPeriod-aware price resolution (FINDING R1-003).
|
||||
*
|
||||
* The checkout route must honour the requested billingPeriod when picking the
|
||||
* Stripe price: 'annual' resolves the annual price, 'monthly' (and omitted)
|
||||
* resolves the monthly price with a legacy single-var fallback. ANNUAL fails
|
||||
* closed (F9): it never falls back to a monthly-priced var, returning
|
||||
* NO_PRICE_CONFIGURED rather than silently charging the monthly price.
|
||||
*
|
||||
* We mock getStripe (mirroring webhook.test.ts's getStripe / process.env
|
||||
* mocking style) with a fake Stripe whose checkout.sessions.create records the
|
||||
* price it was handed, and keep the REAL priceIdForTier so the env-driven
|
||||
* resolution logic is exercised end-to-end. Price env vars are cleared between
|
||||
* cases so tests stay order-independent.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
|
||||
// Records the price passed to the most recent sessions.create call.
|
||||
let lastPriceArg: string | null = null;
|
||||
|
||||
// Fake Stripe — only the surface checkout.ts touches.
|
||||
const fakeStripe = {
|
||||
checkout: {
|
||||
sessions: {
|
||||
create: vi.fn(async (params: { line_items: Array<{ price: string }> }) => {
|
||||
lastPriceArg = params.line_items[0]?.price ?? null;
|
||||
return { url: 'https://checkout.stripe.test/session_123' };
|
||||
}),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Mock the stripe barrel: override getStripe, keep the real priceIdForTier so
|
||||
// the env-var resolution contract is genuinely under test.
|
||||
vi.mock('../../src/stripe/index.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/stripe/index.js')>();
|
||||
return {
|
||||
...actual,
|
||||
getStripe: () => fakeStripe,
|
||||
};
|
||||
});
|
||||
|
||||
import { checkoutRoutes } from '../../src/stripe/checkout.js';
|
||||
|
||||
const PRICE_ENV_KEYS = [
|
||||
'STRIPE_PRICE_BASIC',
|
||||
'STRIPE_PRICE_PRO',
|
||||
'STRIPE_PRICE_PRO_MONTHLY',
|
||||
'STRIPE_PRICE_PRO_ANNUAL',
|
||||
'STRIPE_PRICE_TEAMS',
|
||||
'STRIPE_PRICE_TEAMS_MONTHLY',
|
||||
'STRIPE_PRICE_TEAMS_ANNUAL',
|
||||
] as const;
|
||||
|
||||
describe('Stripe Checkout — billingPeriod-aware price resolution', () => {
|
||||
let server: FastifyInstance;
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const k of PRICE_ENV_KEYS) delete process.env[k];
|
||||
lastPriceArg = null;
|
||||
fakeStripe.checkout.sessions.create.mockClear();
|
||||
|
||||
server = Fastify();
|
||||
await server.register(checkoutRoutes);
|
||||
await server.ready();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
for (const k of PRICE_ENV_KEYS) delete process.env[k];
|
||||
await server.close();
|
||||
});
|
||||
|
||||
async function postCheckout(body: Record<string, unknown>) {
|
||||
return server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/create-checkout-session',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
payload: body,
|
||||
});
|
||||
}
|
||||
|
||||
it('annual billingPeriod uses the annual price (price_pa)', async () => {
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_pm';
|
||||
process.env['STRIPE_PRICE_TEAMS_ANNUAL'] = 'price_pa';
|
||||
|
||||
const res = await postCheckout({ tier: 'TEAMS', billingPeriod: 'annual' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().url).toBe('https://checkout.stripe.test/session_123');
|
||||
expect(fakeStripe.checkout.sessions.create).toHaveBeenCalledOnce();
|
||||
expect(lastPriceArg).toBe('price_pa');
|
||||
});
|
||||
|
||||
it('monthly billingPeriod uses the monthly price (price_pm)', async () => {
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_pm';
|
||||
process.env['STRIPE_PRICE_TEAMS_ANNUAL'] = 'price_pa';
|
||||
|
||||
const res = await postCheckout({ tier: 'TEAMS', billingPeriod: 'monthly' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(lastPriceArg).toBe('price_pm');
|
||||
});
|
||||
|
||||
it('omitted billingPeriod defaults to the monthly price (price_pm)', async () => {
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_pm';
|
||||
process.env['STRIPE_PRICE_TEAMS_ANNUAL'] = 'price_pa';
|
||||
|
||||
const res = await postCheckout({ tier: 'TEAMS' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(lastPriceArg).toBe('price_pm');
|
||||
});
|
||||
|
||||
it('monthly falls back to the legacy single-var price when no 4-var contract is set', async () => {
|
||||
process.env['STRIPE_PRICE_TEAMS'] = 'price_legacy';
|
||||
|
||||
const res = await postCheckout({ tier: 'TEAMS', billingPeriod: 'monthly' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(lastPriceArg).toBe('price_legacy');
|
||||
});
|
||||
|
||||
it('annual FAILS CLOSED when only a (monthly) legacy single-var is set — never silently charges monthly (F9)', async () => {
|
||||
// The legacy STRIPE_PRICE_TEAMS is a monthly price; an annual selection must not
|
||||
// resolve to it (would charge monthly while the UI shows the annual price).
|
||||
process.env['STRIPE_PRICE_TEAMS'] = 'price_legacy';
|
||||
|
||||
const res = await postCheckout({ tier: 'TEAMS', billingPeriod: 'annual' });
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe('NO_PRICE_CONFIGURED');
|
||||
expect(fakeStripe.checkout.sessions.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 NO_PRICE_CONFIGURED for an annual selection when nothing is configured', async () => {
|
||||
// The monthly path can fall back to the legacy single-var / TIER_CAPABILITIES
|
||||
// default (STRIPE_PRICE_TEAMS is present in .env at module load), so the
|
||||
// deterministic "no price" case is the annual one: annual fails closed (F9)
|
||||
// and never falls back, so with nothing configured it returns null → 400.
|
||||
const res = await postCheckout({ tier: 'TEAMS', billingPeriod: 'annual' });
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe('NO_PRICE_CONFIGURED');
|
||||
expect(fakeStripe.checkout.sessions.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a non-TEAMS tier (legacy PRO) with 400 INVALID_TIER — TEAMS is the only paid checkout (PRO removed)', async () => {
|
||||
// Even with a price configured, a PRO checkout must be refused before price
|
||||
// resolution — Solo is free, Team is the only Stripe tier.
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_pm';
|
||||
|
||||
const res = await postCheckout({ tier: 'PRO', billingPeriod: 'monthly' });
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe('INVALID_TIER');
|
||||
expect(fakeStripe.checkout.sessions.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,291 +0,0 @@
|
||||
/**
|
||||
* H-33 Stripe smoke — programmatic end-to-end.
|
||||
*
|
||||
* Covers every item in `docs/OPS/stripe-smoke.md` without needing the
|
||||
* `stripe listen` / long-lived-sidecar dance:
|
||||
*
|
||||
* 1. `checkout.session.completed` → tier updated + customer ID stored
|
||||
* 2. `customer.subscription.updated` → tier reflects new price
|
||||
* 3. `customer.subscription.deleted` → tier reverts to FREE
|
||||
* 4. Duplicate event → .stripe-processed-events.json dedup
|
||||
* 5. `/api/stripe/create-checkout-session` returns a real Stripe Checkout URL
|
||||
* 6. `/api/stripe/create-portal-session` returns a real Stripe portal URL
|
||||
* 7. Signature validation → invalid sig → 400 INVALID_SIGNATURE
|
||||
*
|
||||
* Signs events using `Stripe.webhooks.generateTestHeaderString` so we exercise
|
||||
* the real signature-validation path without running `stripe listen`.
|
||||
*
|
||||
* ## How to run
|
||||
*
|
||||
* ```sh
|
||||
* STRIPE_SECRET_KEY=sk_test_... \
|
||||
* STRIPE_PRICE_TEAMS=price_... \
|
||||
* WAGGLE_STRIPE_SMOKE=1 \
|
||||
* npx vitest run packages/server/tests/stripe/smoke-e2e.test.ts
|
||||
* ```
|
||||
*
|
||||
* Without `WAGGLE_STRIPE_SMOKE=1` the suite self-skips so CI stays green on
|
||||
* dev machines that don't have a Stripe sandbox wired up.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
|
||||
// ── Gate: self-skip when the smoke env isn't configured ────────
|
||||
|
||||
const ENABLED = process.env.WAGGLE_STRIPE_SMOKE === '1' || process.env.WAGGLE_STRIPE_SMOKE === 'true';
|
||||
const STRIPE_KEY = process.env.STRIPE_SECRET_KEY ?? '';
|
||||
const PRICE_TEAMS = process.env.STRIPE_PRICE_TEAMS ?? '';
|
||||
|
||||
// Generate a webhook secret fresh for this run — the sidecar would read
|
||||
// whsec_... from `stripe listen`, but since we sign events ourselves the
|
||||
// only requirement is that both sides share the same secret.
|
||||
const WEBHOOK_SECRET = `whsec_${'smoke'.padEnd(32, '0')}`;
|
||||
process.env.STRIPE_WEBHOOK_SECRET = WEBHOOK_SECRET;
|
||||
|
||||
const SHOULD_RUN =
|
||||
ENABLED &&
|
||||
STRIPE_KEY.startsWith('sk_test_') &&
|
||||
PRICE_TEAMS.startsWith('price_');
|
||||
|
||||
// ── Skip block that emits a visible reason in test output ──────
|
||||
|
||||
if (!SHOULD_RUN) {
|
||||
describe.skip('Stripe smoke E2E (H-33)', () => {
|
||||
it('skipped — set WAGGLE_STRIPE_SMOKE=1 + STRIPE_* env vars to run', () => {
|
||||
// Intentional no-op.
|
||||
});
|
||||
});
|
||||
} else {
|
||||
describe('Stripe smoke E2E (H-33)', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
let stripe: import('stripe').default;
|
||||
// Record structured checklist output for later inclusion in ops notes.
|
||||
const checklist: Record<string, { passed: boolean; detail: string }> = {};
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-stripe-smoke-'));
|
||||
|
||||
// Seed config.json at FREE so the tier flip is visible in step 1.
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, 'config.json'),
|
||||
JSON.stringify({ tier: 'FREE' }, null, 2),
|
||||
);
|
||||
|
||||
// Lazy imports so env stubs above land before @waggle/shared module-loads.
|
||||
const [{ buildLocalServer }, stripeModule, { authInject }] = await Promise.all([
|
||||
import('../../src/local/index.js'),
|
||||
import('stripe'),
|
||||
import('../test-utils.js'),
|
||||
]);
|
||||
|
||||
const Stripe = (stripeModule as unknown as { default: typeof import('stripe').default }).default;
|
||||
stripe = new Stripe(STRIPE_KEY, { apiVersion: '2025-03-31.basil' });
|
||||
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
// Attach the helper so individual tests don't re-import.
|
||||
(server as unknown as { _authInject: typeof authInject })._authInject = authInject;
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
try { await server?.close(); } catch { /* best effort */ }
|
||||
await new Promise(r => setTimeout(r, 150));
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* EBUSY on win32 */ }
|
||||
|
||||
// Print the structured checklist. Surfaces a CI-friendly summary even
|
||||
// when the UI rolls up per-assertion green ticks.
|
||||
|
||||
console.log('\n=== H-33 Stripe smoke checklist ===\n' +
|
||||
Object.entries(checklist)
|
||||
.map(([k, v]) => ` [${v.passed ? 'x' : ' '}] ${k} — ${v.detail}`)
|
||||
.join('\n') + '\n');
|
||||
});
|
||||
|
||||
function readConfig(): Record<string, unknown> {
|
||||
const raw = fs.readFileSync(path.join(tmpDir, 'config.json'), 'utf-8');
|
||||
return JSON.parse(raw) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function postWebhook(rawEvent: unknown, signatureOverride?: string): ReturnType<FastifyInstance['inject']> {
|
||||
const payload = JSON.stringify(rawEvent);
|
||||
const sig = signatureOverride ?? stripe.webhooks.generateTestHeaderString({
|
||||
payload,
|
||||
secret: WEBHOOK_SECRET,
|
||||
});
|
||||
return server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/webhook',
|
||||
payload,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'stripe-signature': sig,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Build a minimal-but-valid Stripe event shape. Our webhook doesn't
|
||||
// validate the whole schema — only the fields it consumes — so this
|
||||
// saves us from round-tripping through the real API.
|
||||
interface MinimalEvent {
|
||||
id: string;
|
||||
type: string;
|
||||
data: { object: Record<string, unknown> };
|
||||
}
|
||||
function makeEvent(id: string, type: string, object: Record<string, unknown>): MinimalEvent {
|
||||
return { id, type, data: { object } };
|
||||
}
|
||||
|
||||
it('[1] checkout.session.completed → tier=TEAMS + stripe_customer_id set', async () => {
|
||||
const event = makeEvent('evt_smoke_checkout_1', 'checkout.session.completed', {
|
||||
metadata: { tier: 'TEAMS' },
|
||||
customer: 'cus_smoke_1',
|
||||
});
|
||||
const res = await postWebhook(event);
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
const cfg = readConfig();
|
||||
expect(cfg.tier).toBe('TEAMS');
|
||||
expect(cfg.stripe_customer_id).toBe('cus_smoke_1');
|
||||
checklist['1. checkout.session.completed'] = {
|
||||
passed: true,
|
||||
detail: `tier=TEAMS + customer=cus_smoke_1`,
|
||||
};
|
||||
});
|
||||
|
||||
it('[2] customer.subscription.updated → tier flips to TEAMS for PRICE_TEAMS', async () => {
|
||||
const event = makeEvent('evt_smoke_sub_upd_1', 'customer.subscription.updated', {
|
||||
customer: 'cus_smoke_1',
|
||||
items: { data: [{ price: { id: PRICE_TEAMS } }] },
|
||||
});
|
||||
const res = await postWebhook(event);
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
const cfg = readConfig();
|
||||
expect(cfg.tier).toBe('TEAMS');
|
||||
checklist['2. customer.subscription.updated'] = {
|
||||
passed: true,
|
||||
detail: `PRICE_TEAMS (${PRICE_TEAMS.slice(0, 16)}…) → tier=TEAMS`,
|
||||
};
|
||||
});
|
||||
|
||||
it('[3] customer.subscription.deleted → tier reverts to FREE', async () => {
|
||||
const event = makeEvent('evt_smoke_sub_del_1', 'customer.subscription.deleted', {
|
||||
customer: 'cus_smoke_1',
|
||||
});
|
||||
const res = await postWebhook(event);
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
const cfg = readConfig();
|
||||
expect(cfg.tier).toBe('FREE');
|
||||
checklist['3. customer.subscription.deleted'] = {
|
||||
passed: true,
|
||||
detail: 'tier reverted to FREE',
|
||||
};
|
||||
});
|
||||
|
||||
it('[4] duplicate event ID is deduped — config unchanged', async () => {
|
||||
// Flip back to PRO, then re-fire the same event id. Second call must
|
||||
// be a no-op according to .stripe-processed-events.json.
|
||||
await postWebhook(makeEvent('evt_smoke_dedup_pre', 'checkout.session.completed', {
|
||||
metadata: { tier: 'TEAMS' },
|
||||
customer: 'cus_smoke_1',
|
||||
}));
|
||||
expect(readConfig().tier).toBe('TEAMS');
|
||||
|
||||
// Now mutate state would-be: send a dedup-checking event, then resend.
|
||||
const event = makeEvent('evt_smoke_checkout_1', 'checkout.session.completed', {
|
||||
metadata: { tier: 'FREE' }, // would downgrade if re-processed
|
||||
customer: 'cus_smoke_1',
|
||||
});
|
||||
const res = await postWebhook(event);
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body) as { received: boolean; duplicate?: boolean };
|
||||
expect(body.duplicate).toBe(true);
|
||||
|
||||
// Tier unchanged — the dedup guard kept us on TEAMS.
|
||||
expect(readConfig().tier).toBe('TEAMS');
|
||||
checklist['4. duplicate event dedup'] = {
|
||||
passed: true,
|
||||
detail: 'resending evt_smoke_checkout_1 left tier on TEAMS (duplicate skipped)',
|
||||
};
|
||||
});
|
||||
|
||||
it('[5] invalid signature → 400 INVALID_SIGNATURE', async () => {
|
||||
const event = makeEvent('evt_smoke_badsig', 'checkout.session.completed', {
|
||||
metadata: { tier: 'TEAMS' },
|
||||
});
|
||||
const res = await postWebhook(event, 't=0,v1=bogus');
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body) as { error: string };
|
||||
expect(body.error).toBe('INVALID_SIGNATURE');
|
||||
checklist['5. signature validation'] = {
|
||||
passed: true,
|
||||
detail: 'bogus signature → 400 INVALID_SIGNATURE',
|
||||
};
|
||||
});
|
||||
|
||||
it('[6] POST /api/stripe/create-checkout-session returns a real checkout URL', async () => {
|
||||
const authInject = (server as unknown as { _authInject: typeof import('../test-utils.js').authInject })._authInject;
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'POST',
|
||||
url: '/api/stripe/create-checkout-session',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
payload: { tier: 'TEAMS' },
|
||||
}));
|
||||
|
||||
// TEAMS is the only paid checkout tier (PRO removed). The route needs
|
||||
// STRIPE_PRICE_TEAMS to be configured.
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body) as { url: string };
|
||||
expect(body.url).toMatch(/^https:\/\/checkout\.stripe\.com\//);
|
||||
checklist['6. create-checkout-session'] = {
|
||||
passed: true,
|
||||
detail: `URL = ${body.url.slice(0, 48)}…`,
|
||||
};
|
||||
}, 30_000);
|
||||
|
||||
it('[7] POST /api/stripe/create-portal-session returns a real portal URL', async () => {
|
||||
// Create a real test-mode customer in the sandbox so the portal call
|
||||
// has something valid to target. Steps 1-4 wrote cus_smoke_1 into
|
||||
// config.json — that ID doesn't exist in Stripe, so we override it.
|
||||
const customer = await stripe.customers.create({
|
||||
description: 'Waggle H-33 smoke — ephemeral',
|
||||
metadata: { smoke_run: new Date().toISOString() },
|
||||
});
|
||||
|
||||
// Update config.json to point at the real customer. The portal is now
|
||||
// gated at FREE (any authenticated user) so the tier value is immaterial;
|
||||
// use TEAMS as a representative paid state.
|
||||
const cfgPath = path.join(tmpDir, 'config.json');
|
||||
const current = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
|
||||
fs.writeFileSync(cfgPath, JSON.stringify({
|
||||
...current,
|
||||
tier: 'TEAMS',
|
||||
stripe_customer_id: customer.id,
|
||||
}, null, 2));
|
||||
|
||||
const authInject = (server as unknown as { _authInject: typeof import('../test-utils.js').authInject })._authInject;
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'POST',
|
||||
url: '/api/stripe/create-portal-session',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
payload: {},
|
||||
}));
|
||||
|
||||
// Clean up the ephemeral customer so we don't accumulate fixtures.
|
||||
try { await stripe.customers.del(customer.id); } catch { /* best effort */ }
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body) as { url: string };
|
||||
expect(body.url).toMatch(/^https:\/\/billing\.stripe\.com\//);
|
||||
checklist['7. create-portal-session'] = {
|
||||
passed: true,
|
||||
detail: `customer=${customer.id} · URL = ${body.url.slice(0, 48)}…`,
|
||||
};
|
||||
}, 30_000);
|
||||
});
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
/**
|
||||
* GET /api/stripe/status — the secret-free "is checkout wired" probe backing the
|
||||
* F8 honest disabled state. With no STRIPE_SECRET_KEY (the default test env),
|
||||
* getStripe() returns null, so the route reports { configured: false } and the
|
||||
* billing UI can disable the upgrade CTAs pre-click instead of 503-ing after one.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import { statusRoutes } from '../../src/stripe/index.js';
|
||||
|
||||
describe('GET /api/stripe/status', () => {
|
||||
let server: FastifyInstance;
|
||||
const hadKey = process.env['STRIPE_SECRET_KEY'];
|
||||
|
||||
beforeEach(async () => {
|
||||
delete process.env['STRIPE_SECRET_KEY'];
|
||||
server = Fastify();
|
||||
await server.register(statusRoutes);
|
||||
await server.ready();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (hadKey !== undefined) process.env['STRIPE_SECRET_KEY'] = hadKey;
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('reports configured:false when Stripe is not wired (no secret key)', async () => {
|
||||
const res = await server.inject({ method: 'GET', url: '/api/stripe/status' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ configured: false });
|
||||
});
|
||||
|
||||
it('reports configured:true when the Stripe SDK has a secret key', async () => {
|
||||
process.env['STRIPE_SECRET_KEY'] = 'sk_test_status_probe';
|
||||
|
||||
const res = await server.inject({ method: 'GET', url: '/api/stripe/status' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ configured: true });
|
||||
});
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
|
||||
// ── Mock the Stripe SDK singleton ────────────────────────────────────
|
||||
// We control checkout.sessions.retrieve per-test via a settable holder.
|
||||
// tierFromPriceId stays REAL (we only override getStripe) so the
|
||||
// price-env resolution path is exercised end-to-end.
|
||||
let nextSession: unknown = null;
|
||||
|
||||
vi.mock('../../src/stripe/index.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../src/stripe/index.js')>(
|
||||
'../../src/stripe/index.js',
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
getStripe: () => ({
|
||||
checkout: {
|
||||
sessions: {
|
||||
retrieve: async () => nextSession,
|
||||
},
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
// Imported AFTER the mock is declared so the route picks up mocked getStripe.
|
||||
const { syncRoutes } = await import('../../src/stripe/sync.js');
|
||||
|
||||
function buildServer(dataDir: string): FastifyInstance {
|
||||
const server = Fastify();
|
||||
server.decorate('localConfig', { dataDir });
|
||||
server.register(syncRoutes);
|
||||
return server;
|
||||
}
|
||||
|
||||
function readTier(dataDir: string): string | undefined {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (!fs.existsSync(configPath)) return undefined;
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
return raw.tier as string | undefined;
|
||||
}
|
||||
|
||||
describe('POST /api/stripe/sync — payment gate (R1-002)', () => {
|
||||
let tmpDir: string;
|
||||
let server: FastifyInstance;
|
||||
|
||||
const PRICE_ENV_KEYS = ['STRIPE_PRICE_PRO'] as const;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-sync-test-'));
|
||||
nextSession = null;
|
||||
for (const k of PRICE_ENV_KEYS) delete process.env[k];
|
||||
process.env['STRIPE_SECRET_KEY'] = 'sk_test_dummy'; // not used (getStripe mocked) but keeps intent clear
|
||||
server = buildServer(tmpDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
for (const k of PRICE_ENV_KEYS) delete process.env[k];
|
||||
delete process.env['STRIPE_SECRET_KEY'];
|
||||
});
|
||||
|
||||
// (a) UNPAID session → 402, tier NOT persisted.
|
||||
it('rejects an unpaid session with 402 and does not change the tier', async () => {
|
||||
nextSession = {
|
||||
status: 'open',
|
||||
payment_status: 'unpaid',
|
||||
customer: 'cus_unpaid',
|
||||
metadata: { tier: 'TEAMS' },
|
||||
};
|
||||
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/sync',
|
||||
payload: { sessionId: 'cs_test_unpaid' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(402);
|
||||
expect(res.json()).toMatchObject({ error: 'PAYMENT_NOT_COMPLETED' });
|
||||
// config.json must NOT have been written with a paid tier.
|
||||
expect(readTier(tmpDir)).toBeUndefined();
|
||||
});
|
||||
|
||||
// Defensive: a 'complete' session that somehow is still 'unpaid' is also gated.
|
||||
it('rejects a complete-but-unpaid session with 402 and does not change the tier', async () => {
|
||||
nextSession = {
|
||||
status: 'complete',
|
||||
payment_status: 'unpaid',
|
||||
customer: 'cus_weird',
|
||||
metadata: { tier: 'TEAMS' },
|
||||
};
|
||||
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/sync',
|
||||
payload: { sessionId: 'cs_test_weird' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(402);
|
||||
expect(readTier(tmpDir)).toBeUndefined();
|
||||
});
|
||||
|
||||
// (b) Paid session with a legacy PRO subscription price → 200. Post-collapse a
|
||||
// legacy PRO price resolves to FREE (Solo), so a legacy PRO subscriber lands on
|
||||
// Solo rather than being locked out (decision #5).
|
||||
it('accepts a paid session and maps a legacy PRO subscription price to FREE (Solo)', async () => {
|
||||
process.env['STRIPE_PRICE_PRO'] = 'price_x';
|
||||
nextSession = {
|
||||
status: 'complete',
|
||||
payment_status: 'paid',
|
||||
customer: 'cus_paid',
|
||||
subscription: { items: { data: [{ price: { id: 'price_x' } }] } },
|
||||
};
|
||||
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/sync',
|
||||
payload: { sessionId: 'cs_test_paid' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ tier: 'FREE', customerId: 'cus_paid' });
|
||||
expect(readTier(tmpDir)).toBe('FREE');
|
||||
});
|
||||
|
||||
// (c) Promo / 100%-off session → no_payment_required is treated as paid → 200.
|
||||
// A legacy PRO metadata tier collapses to FREE via parseTier.
|
||||
it('accepts a no_payment_required (promo) session and maps a legacy PRO metadata tier to FREE', async () => {
|
||||
nextSession = {
|
||||
status: 'complete',
|
||||
payment_status: 'no_payment_required',
|
||||
customer: 'cus_promo',
|
||||
metadata: { tier: 'PRO' },
|
||||
};
|
||||
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/sync',
|
||||
payload: { sessionId: 'cs_test_promo' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ tier: 'FREE' });
|
||||
expect(readTier(tmpDir)).toBe('FREE');
|
||||
});
|
||||
});
|
||||
@@ -1,460 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import Fastify from 'fastify';
|
||||
import { updateUserTier } from '../../src/stripe/webhook.js';
|
||||
import { tierFromPriceId } from '../../src/stripe/index.js';
|
||||
import { securityMiddleware } from '../../src/local/security-middleware.js';
|
||||
import { parseTier } from '@waggle/shared';
|
||||
|
||||
// Mock only getStripe; keep the real tierFromPriceId so the 17 existing tests
|
||||
// (which import the genuine env-driven resolver) stay green.
|
||||
vi.mock('../../src/stripe/index.js', async (importActual) => {
|
||||
const actual = await importActual<typeof import('../../src/stripe/index.js')>();
|
||||
return { ...actual, getStripe: () => fakeStripe };
|
||||
});
|
||||
|
||||
// Fake Stripe whose webhooks.constructEvent returns whatever event the test
|
||||
// queued. The webhook handler never inspects the signature beyond calling this.
|
||||
let nextEvent: unknown = null;
|
||||
const fakeStripe = {
|
||||
webhooks: {
|
||||
constructEvent: () => nextEvent,
|
||||
},
|
||||
} as unknown as import('stripe').default;
|
||||
|
||||
describe('Stripe Webhook — tier update logic', () => {
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-stripe-test-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('updateUserTier', () => {
|
||||
it('creates config.json and sets tier to TEAMS on checkout complete', () => {
|
||||
updateUserTier(tmpDir, 'TEAMS');
|
||||
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
expect(fs.existsSync(configPath)).toBe(true);
|
||||
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
expect(raw.tier).toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('updates existing config.json without losing other fields', () => {
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
fs.writeFileSync(configPath, JSON.stringify({ theme: 'dark', tier: 'FREE' }));
|
||||
|
||||
updateUserTier(tmpDir, 'TEAMS');
|
||||
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
expect(raw.tier).toBe('TEAMS');
|
||||
expect(raw.theme).toBe('dark');
|
||||
});
|
||||
|
||||
it('retries a transient Windows lock while replacing config.json', () => {
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
fs.writeFileSync(configPath, JSON.stringify({ theme: 'dark', tier: 'FREE' }));
|
||||
const renameSync = fs.renameSync.bind(fs);
|
||||
const rename = vi.spyOn(fs, 'renameSync')
|
||||
.mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('temporarily locked'), { code: 'EPERM' });
|
||||
})
|
||||
.mockImplementation(renameSync);
|
||||
const wait = vi.spyOn(Atomics, 'wait').mockReturnValue('timed-out');
|
||||
|
||||
try {
|
||||
updateUserTier(tmpDir, 'TEAMS');
|
||||
|
||||
expect(rename).toHaveBeenCalledTimes(2);
|
||||
expect(wait).toHaveBeenCalledOnce();
|
||||
expect(JSON.parse(fs.readFileSync(configPath, 'utf-8'))).toMatchObject({
|
||||
theme: 'dark',
|
||||
tier: 'TEAMS',
|
||||
});
|
||||
} finally {
|
||||
rename.mockRestore();
|
||||
wait.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('downgrades tier to FREE on subscription deleted', () => {
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
fs.writeFileSync(configPath, JSON.stringify({ tier: 'TEAMS' }));
|
||||
|
||||
updateUserTier(tmpDir, 'FREE');
|
||||
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
expect(raw.tier).toBe('FREE');
|
||||
});
|
||||
|
||||
it('handles missing config.json gracefully', () => {
|
||||
// No config.json exists — should create one
|
||||
expect(() => updateUserTier(tmpDir, 'ENTERPRISE')).not.toThrow();
|
||||
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(tmpDir, 'config.json'), 'utf-8'));
|
||||
expect(raw.tier).toBe('ENTERPRISE');
|
||||
});
|
||||
});
|
||||
|
||||
describe('tierFromPriceId', () => {
|
||||
// All Stripe price env vars we touch. Cleared before/after each test so
|
||||
// tests are order-independent and don't leak into one another.
|
||||
const PRICE_ENV_KEYS = [
|
||||
'STRIPE_PRICE_BASIC',
|
||||
'STRIPE_PRICE_PRO',
|
||||
'STRIPE_PRICE_PRO_MONTHLY',
|
||||
'STRIPE_PRICE_PRO_ANNUAL',
|
||||
'STRIPE_PRICE_TEAMS',
|
||||
'STRIPE_PRICE_TEAMS_MONTHLY',
|
||||
'STRIPE_PRICE_TEAMS_ANNUAL',
|
||||
] as const;
|
||||
|
||||
beforeEach(() => {
|
||||
for (const k of PRICE_ENV_KEYS) delete process.env[k];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const k of PRICE_ENV_KEYS) delete process.env[k];
|
||||
});
|
||||
|
||||
// ── Legacy single-var contract (back-compat) ────────────────────────
|
||||
|
||||
it('returns null when no env vars are set', () => {
|
||||
expect(tierFromPriceId('price_abc123')).toBeNull();
|
||||
});
|
||||
|
||||
it('maps legacy BASIC price env to FREE (Solo)', () => {
|
||||
// BASIC/PRO were collapsed into Solo; STRIPE_PRICE_BASIC is kept as a legacy
|
||||
// alias that now resolves to FREE so a legacy subscriber lands on Solo,
|
||||
// never locked out (see stripe/index.ts).
|
||||
process.env['STRIPE_PRICE_BASIC'] = 'price_basic_test';
|
||||
expect(tierFromPriceId('price_basic_test')).toBe('FREE');
|
||||
});
|
||||
|
||||
it('maps legacy STRIPE_PRICE_PRO to FREE (Solo)', () => {
|
||||
process.env['STRIPE_PRICE_PRO'] = 'price_pro_test';
|
||||
expect(tierFromPriceId('price_pro_test')).toBe('FREE');
|
||||
});
|
||||
|
||||
it('maps legacy STRIPE_PRICE_TEAMS to TEAMS tier', () => {
|
||||
process.env['STRIPE_PRICE_TEAMS'] = 'price_teams_test';
|
||||
expect(tierFromPriceId('price_teams_test')).toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('returns null for unknown price ID with legacy contract', () => {
|
||||
process.env['STRIPE_PRICE_BASIC'] = 'price_basic_test';
|
||||
process.env['STRIPE_PRICE_TEAMS'] = 'price_teams_test';
|
||||
expect(tierFromPriceId('price_unknown')).toBeNull();
|
||||
});
|
||||
|
||||
// ── New 4-var contract (apps/www Next.js port) ──────────────────────
|
||||
|
||||
it('maps STRIPE_PRICE_PRO_MONTHLY to FREE (Solo — legacy PRO price)', () => {
|
||||
process.env['STRIPE_PRICE_PRO_MONTHLY'] = 'price_pro_monthly_test';
|
||||
expect(tierFromPriceId('price_pro_monthly_test')).toBe('FREE');
|
||||
});
|
||||
|
||||
it('maps STRIPE_PRICE_PRO_ANNUAL to FREE (Solo — legacy PRO price)', () => {
|
||||
process.env['STRIPE_PRICE_PRO_ANNUAL'] = 'price_pro_annual_test';
|
||||
expect(tierFromPriceId('price_pro_annual_test')).toBe('FREE');
|
||||
});
|
||||
|
||||
it('maps STRIPE_PRICE_TEAMS_MONTHLY to TEAMS tier', () => {
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_teams_monthly_test';
|
||||
expect(tierFromPriceId('price_teams_monthly_test')).toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('maps STRIPE_PRICE_TEAMS_ANNUAL to TEAMS tier', () => {
|
||||
process.env['STRIPE_PRICE_TEAMS_ANNUAL'] = 'price_teams_annual_test';
|
||||
expect(tierFromPriceId('price_teams_annual_test')).toBe('TEAMS');
|
||||
});
|
||||
|
||||
// ── Coexistence: both contracts active simultaneously ───────────────
|
||||
|
||||
it('resolves correctly when both new + legacy contracts are set with different IDs', () => {
|
||||
// apps/www landing config + sidecar legacy config on the same env.
|
||||
process.env['STRIPE_PRICE_PRO_MONTHLY'] = 'price_landing_pro_m';
|
||||
process.env['STRIPE_PRICE_PRO_ANNUAL'] = 'price_landing_pro_y';
|
||||
process.env['STRIPE_PRICE_PRO'] = 'price_sidecar_pro';
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_landing_teams_m';
|
||||
process.env['STRIPE_PRICE_TEAMS_ANNUAL'] = 'price_landing_teams_y';
|
||||
process.env['STRIPE_PRICE_TEAMS'] = 'price_sidecar_teams';
|
||||
|
||||
// Every configured legacy Pro price → FREE (Solo), every Teams price → TEAMS.
|
||||
expect(tierFromPriceId('price_landing_pro_m')).toBe('FREE');
|
||||
expect(tierFromPriceId('price_landing_pro_y')).toBe('FREE');
|
||||
expect(tierFromPriceId('price_sidecar_pro')).toBe('FREE');
|
||||
expect(tierFromPriceId('price_landing_teams_m')).toBe('TEAMS');
|
||||
expect(tierFromPriceId('price_landing_teams_y')).toBe('TEAMS');
|
||||
expect(tierFromPriceId('price_sidecar_teams')).toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('does not cross-pollute tiers (Teams price stays TEAMS, legacy Pro price → FREE)', () => {
|
||||
process.env['STRIPE_PRICE_PRO_MONTHLY'] = 'price_pro_m';
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_teams_m';
|
||||
|
||||
expect(tierFromPriceId('price_pro_m')).toBe('FREE');
|
||||
expect(tierFromPriceId('price_teams_m')).toBe('TEAMS');
|
||||
// And the negative case explicitly:
|
||||
expect(tierFromPriceId('price_teams_m')).not.toBe('FREE');
|
||||
expect(tierFromPriceId('price_pro_m')).not.toBe('TEAMS');
|
||||
});
|
||||
|
||||
it('returns null for unknown price ID when only the 4-var contract is set', () => {
|
||||
process.env['STRIPE_PRICE_PRO_MONTHLY'] = 'price_pro_m';
|
||||
process.env['STRIPE_PRICE_PRO_ANNUAL'] = 'price_pro_y';
|
||||
process.env['STRIPE_PRICE_TEAMS_MONTHLY'] = 'price_teams_m';
|
||||
process.env['STRIPE_PRICE_TEAMS_ANNUAL'] = 'price_teams_y';
|
||||
|
||||
expect(tierFromPriceId('price_unknown')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('tier round-trip via parseTier', () => {
|
||||
it('tier written by updateUserTier is readable via parseTier', () => {
|
||||
updateUserTier(tmpDir, 'TEAMS');
|
||||
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(tmpDir, 'config.json'), 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier));
|
||||
expect(parsed).toBe('TEAMS');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Webhook handler: atomic write + idempotency (R1-011) ────────────
|
||||
// Drives the full POST /api/stripe/webhook handler via fastify.inject,
|
||||
// with getStripe mocked (above) and STRIPE_WEBHOOK_SECRET set.
|
||||
describe('webhook handler — atomic write + idempotency', () => {
|
||||
afterEach(() => {
|
||||
nextEvent = null;
|
||||
delete process.env['STRIPE_WEBHOOK_SECRET'];
|
||||
});
|
||||
|
||||
async function buildServer() {
|
||||
const { webhookRoutes } = await import('../../src/stripe/webhook.js');
|
||||
const app = Fastify();
|
||||
app.decorate('localConfig', { dataDir: tmpDir });
|
||||
await app.register(webhookRoutes);
|
||||
await app.ready();
|
||||
return app;
|
||||
}
|
||||
|
||||
function postEvent(app: ReturnType<typeof Fastify>) {
|
||||
return app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/webhook',
|
||||
headers: { 'stripe-signature': 't=1,v1=fake', 'content-type': 'application/json' },
|
||||
payload: Buffer.from('{}'),
|
||||
});
|
||||
}
|
||||
|
||||
it('writes valid config.json with no leftover *.tmp file after checkout.session.completed', async () => {
|
||||
process.env['STRIPE_WEBHOOK_SECRET'] = 'whsec_test';
|
||||
// Legacy PRO metadata collapses to FREE (Solo) via parseTier — the write
|
||||
// still lands atomically; the granted tier is FREE.
|
||||
nextEvent = {
|
||||
id: 'evt_atomic_1',
|
||||
type: 'checkout.session.completed',
|
||||
data: { object: { payment_status: 'paid', metadata: { tier: 'PRO' }, customer: 'cus_123' } },
|
||||
};
|
||||
|
||||
const app = await buildServer();
|
||||
try {
|
||||
const res = await postEvent(app);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ received: true });
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
// config.json exists and is valid JSON with the expected tier
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
expect(fs.existsSync(configPath)).toBe(true);
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
expect(raw.tier).toBe('FREE');
|
||||
expect(raw.stripe_customer_id).toBe('cus_123');
|
||||
|
||||
// No torn/leftover temp file remains in dataDir
|
||||
const leftovers = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.tmp'));
|
||||
expect(leftovers).toEqual([]);
|
||||
});
|
||||
|
||||
it('is idempotent — replaying the same event.id returns duplicate:true and does not change config', async () => {
|
||||
process.env['STRIPE_WEBHOOK_SECRET'] = 'whsec_test';
|
||||
nextEvent = {
|
||||
id: 'evt_dup_1',
|
||||
type: 'checkout.session.completed',
|
||||
data: { object: { payment_status: 'paid', metadata: { tier: 'PRO' }, customer: 'cus_abc' } },
|
||||
};
|
||||
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
|
||||
// First delivery: applies the tier, returns plain received.
|
||||
const app1 = await buildServer();
|
||||
try {
|
||||
const res1 = await postEvent(app1);
|
||||
expect(res1.statusCode).toBe(200);
|
||||
expect(res1.json()).toEqual({ received: true });
|
||||
} finally {
|
||||
await app1.close();
|
||||
}
|
||||
const afterFirst = fs.readFileSync(configPath, 'utf-8');
|
||||
expect(JSON.parse(afterFirst).tier).toBe('FREE');
|
||||
|
||||
// Tamper with the config object the second event WOULD have produced,
|
||||
// so any non-idempotent re-processing would be observable.
|
||||
nextEvent = {
|
||||
id: 'evt_dup_1', // same id
|
||||
type: 'checkout.session.completed',
|
||||
data: { object: { payment_status: 'paid', metadata: { tier: 'TEAMS' }, customer: 'cus_xyz' } },
|
||||
};
|
||||
|
||||
const app2 = await buildServer();
|
||||
try {
|
||||
const res2 = await postEvent(app2);
|
||||
expect(res2.statusCode).toBe(200);
|
||||
expect(res2.json()).toEqual({ received: true, duplicate: true });
|
||||
} finally {
|
||||
await app2.close();
|
||||
}
|
||||
|
||||
// Config must be byte-identical to the first write (TEAMS was NOT applied)
|
||||
const afterSecond = fs.readFileSync(configPath, 'utf-8');
|
||||
expect(afterSecond).toBe(afterFirst);
|
||||
expect(JSON.parse(afterSecond).tier).toBe('FREE');
|
||||
});
|
||||
|
||||
// ── R1-002 (webhook path): payment gate ─────────────────────────────
|
||||
// checkout.session.completed fires for UNPAID sessions too (async payment
|
||||
// methods, expired/incomplete checkouts). Granting a paid tier on those is
|
||||
// a free-upgrade bypass. Mirror the sync.ts:46 guard: only payment_status
|
||||
// 'paid' | 'no_payment_required' may grant.
|
||||
it('does NOT grant a tier when payment_status is unpaid (R1-002 webhook gate)', async () => {
|
||||
process.env['STRIPE_WEBHOOK_SECRET'] = 'whsec_test';
|
||||
nextEvent = {
|
||||
id: 'evt_unpaid_1',
|
||||
type: 'checkout.session.completed',
|
||||
data: { object: { payment_status: 'unpaid', metadata: { tier: 'TEAMS' }, customer: 'cus_unpaid' } },
|
||||
};
|
||||
|
||||
const app = await buildServer();
|
||||
try {
|
||||
const res = await postEvent(app);
|
||||
// Still ack the event (200) so Stripe stops retrying — but no grant.
|
||||
expect(res.statusCode).toBe(200);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
// No config.json written at all (no tier ever granted from an unpaid session).
|
||||
const configPath = path.join(tmpDir, 'config.json');
|
||||
const tier = fs.existsSync(configPath)
|
||||
? JSON.parse(fs.readFileSync(configPath, 'utf-8')).tier
|
||||
: undefined;
|
||||
expect(tier).not.toBe('TEAMS');
|
||||
expect(tier).toBeUndefined();
|
||||
});
|
||||
|
||||
it('grants a tier when payment_status is no_payment_required (100%-off coupon)', async () => {
|
||||
process.env['STRIPE_WEBHOOK_SECRET'] = 'whsec_test';
|
||||
// Legacy PRO metadata collapses to FREE (Solo) via parseTier.
|
||||
nextEvent = {
|
||||
id: 'evt_free_1',
|
||||
type: 'checkout.session.completed',
|
||||
data: { object: { payment_status: 'no_payment_required', metadata: { tier: 'PRO' }, customer: 'cus_free' } },
|
||||
};
|
||||
|
||||
const app = await buildServer();
|
||||
try {
|
||||
const res = await postEvent(app);
|
||||
expect(res.statusCode).toBe(200);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(tmpDir, 'config.json'), 'utf-8'));
|
||||
expect(raw.tier).toBe('FREE');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── P2: webhook reachable under the global bearer-auth middleware ────────────
|
||||
// In a hosted (0.0.0.0) deploy the securityMiddleware requires a bearer token on
|
||||
// every /api/* request when a sessionToken is configured. Stripe posts to
|
||||
// /api/stripe/webhook with NO bearer (it can't have our per-process token), so
|
||||
// without an auth exemption the webhook 401s BEFORE the handler and
|
||||
// customer.subscription.deleted/updated never process — cancelled subs never
|
||||
// downgrade. This composes the REAL securityMiddleware + REAL webhookRoutes and
|
||||
// proves a no-auth POST reaches the handler (the route is independently
|
||||
// authenticated by Stripe signature verification inside the handler).
|
||||
describe('P2 — webhook is auth-exempt under securityMiddleware (hosted-deploy reachability)', () => {
|
||||
const SESSION_TOKEN = 'test-session-token-p2';
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-webhook-auth-'));
|
||||
// Exercise the SECURE auth path — the suite default is trust=1, which would
|
||||
// make this vacuous by trusting every loopback caller.
|
||||
process.env.WAGGLE_TRUST_LOCALHOST = '0';
|
||||
process.env.STRIPE_WEBHOOK_SECRET = 'whsec_test';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
nextEvent = null;
|
||||
delete process.env.STRIPE_WEBHOOK_SECRET;
|
||||
process.env.WAGGLE_TRUST_LOCALHOST = '1'; // restore suite default
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function buildGuardedServer() {
|
||||
const { webhookRoutes } = await import('../../src/stripe/webhook.js');
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(securityMiddleware, { sessionToken: SESSION_TOKEN });
|
||||
app.decorate('localConfig', { dataDir: tmpDir });
|
||||
// A normal protected route to prove auth IS enforced for non-exempt paths.
|
||||
app.post('/api/other', async () => ({ ok: true }));
|
||||
await app.register(webhookRoutes);
|
||||
await app.ready();
|
||||
return app;
|
||||
}
|
||||
|
||||
it('a NO-Authorization POST to /api/stripe/webhook reaches the handler (not 401)', async () => {
|
||||
nextEvent = { id: 'evt_authexempt_1', type: 'customer.subscription.deleted', data: { object: {} } };
|
||||
const app = await buildGuardedServer();
|
||||
try {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/stripe/webhook',
|
||||
headers: { 'stripe-signature': 't=1,v1=fake', 'content-type': 'application/json' },
|
||||
payload: Buffer.from('{}'),
|
||||
// NOTE: deliberately NO authorization header.
|
||||
});
|
||||
// Passed the bearer gate and ran the handler → 200. The load-bearing
|
||||
// assertion is that it is NOT a 401 (auth did not block Stripe).
|
||||
expect(res.statusCode).not.toBe(401);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ received: true });
|
||||
// The handler actually processed the cancel → tier downgraded to FREE.
|
||||
const cfg = JSON.parse(fs.readFileSync(path.join(tmpDir, 'config.json'), 'utf-8'));
|
||||
expect(cfg.tier).toBe('FREE');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('a NON-exempt /api/* POST with no token is STILL 401 (exemption is webhook-specific)', async () => {
|
||||
const app = await buildGuardedServer();
|
||||
try {
|
||||
const res = await app.inject({ method: 'POST', url: '/api/other' });
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json().code).toBe('MISSING_TOKEN');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,181 +0,0 @@
|
||||
/**
|
||||
* H-31 Tier Enforcement Matrix.
|
||||
*
|
||||
* Asserts that every gated route enforces its minimum tier per `tiers.ts`.
|
||||
* Matrix = every gated endpoint × every tier ∈ { FREE, TEAMS, ENTERPRISE, TRIAL }.
|
||||
*
|
||||
* For each cell we compute the expected verdict from TIER_ORDER:
|
||||
* - "allow" → response must not be 403 TIER_INSUFFICIENT (downstream 4xx/5xx is fine —
|
||||
* we only care the middleware let the request through).
|
||||
* - "deny" → response must be 403 with `error: 'TIER_INSUFFICIENT'` + correct
|
||||
* `required` / `actual` fields.
|
||||
*
|
||||
* Also covers the TRIAL-expired → FREE fallback path inside `readTierFromRequest`.
|
||||
*
|
||||
* If a new gated endpoint is added, extend GATED_ENDPOINTS below. If enforcement
|
||||
* is removed from an existing route, that row's "deny" tests will flip to "allow"
|
||||
* and fail — which is the intended tripwire.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { TIERS, type Tier } from '@waggle/shared';
|
||||
import { buildLocalServer } from '../src/local/index.js';
|
||||
import { authInject } from './test-utils.js';
|
||||
|
||||
interface GatedEndpoint {
|
||||
method: 'GET' | 'POST';
|
||||
url: string;
|
||||
minTier: Tier;
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
// Matches TIER_ORDER in @waggle/shared/tiers.ts. TRIAL ranks with ENTERPRISE
|
||||
// but downgrades to FREE when expired — the fallback is tested separately.
|
||||
// PRO removed (Solo/Team collapse): personal features are free/Solo now.
|
||||
const TIER_ORDER: Record<Tier, number> = {
|
||||
FREE: 0, TEAMS: 2, ENTERPRISE: 3, TRIAL: 3,
|
||||
};
|
||||
|
||||
const GATED_ENDPOINTS: GatedEndpoint[] = [
|
||||
// Free/Solo (PRO removed) — these were PRO-gated; now every tier is allowed.
|
||||
// Kept as minTier FREE so a re-gating regression flips these to "denies" and fails.
|
||||
{ method: 'POST', url: '/api/personas', minTier: 'FREE', body: { name: 'x', systemPrompt: 'y' } },
|
||||
{ method: 'POST', url: '/api/personas/generate', minTier: 'FREE', body: { prompt: 'x' } },
|
||||
{ method: 'POST', url: '/api/marketplace/install', minTier: 'FREE', body: { skillId: 'x' } },
|
||||
{ method: 'POST', url: '/api/marketplace/publish', minTier: 'FREE', body: {} },
|
||||
{ method: 'POST', url: '/api/stripe/create-portal-session', minTier: 'FREE', body: {} },
|
||||
|
||||
// TEAMS-gated — denies FREE, allows TEAMS/ENTERPRISE/TRIAL
|
||||
{ method: 'GET', url: '/api/cost/by-workspace', minTier: 'TEAMS' },
|
||||
{ method: 'POST', url: '/api/cloud-sync/toggle', minTier: 'TEAMS', body: { enabled: true } },
|
||||
{ method: 'GET', url: '/api/admin/overview', minTier: 'TEAMS' },
|
||||
{ method: 'GET', url: '/api/admin/audit-export', minTier: 'TEAMS' },
|
||||
{ method: 'POST', url: '/api/team/connect', minTier: 'TEAMS', body: { serverUrl: 'http://x', token: 'y' } },
|
||||
|
||||
// ENTERPRISE-gated — denies FREE/TEAMS, allows ENTERPRISE/TRIAL
|
||||
{ method: 'GET', url: '/api/marketplace/enterprise-packs', minTier: 'ENTERPRISE' },
|
||||
{ method: 'GET', url: '/api/team/governance/permissions?workspaceId=default', minTier: 'ENTERPRISE' },
|
||||
];
|
||||
|
||||
function writeTier(dataDir: string, tier: Tier, trialStartedAt: string | null = null): void {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
const existing = fs.existsSync(configPath)
|
||||
? JSON.parse(fs.readFileSync(configPath, 'utf-8'))
|
||||
: {};
|
||||
const next = { ...existing, tier, trialStartedAt };
|
||||
fs.writeFileSync(configPath, JSON.stringify(next));
|
||||
}
|
||||
|
||||
function parseJsonSafe(raw: string): { error?: string; required?: string; actual?: string } {
|
||||
try { return JSON.parse(raw) as { error?: string; required?: string; actual?: string }; }
|
||||
catch { return {}; }
|
||||
}
|
||||
|
||||
describe('Tier Enforcement Matrix (H-31)', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-tier-matrix-'));
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.close();
|
||||
// Windows needs a moment to release file handles.
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* EBUSY on win32 — ignore */ }
|
||||
});
|
||||
|
||||
for (const tier of TIERS) {
|
||||
describe(`tier = ${tier}`, () => {
|
||||
beforeAll(() => {
|
||||
// Fresh TRIAL for the TRIAL row; other tiers don't need a trialStartedAt.
|
||||
const trialStart = tier === 'TRIAL' ? new Date().toISOString() : null;
|
||||
writeTier(tmpDir, tier, trialStart);
|
||||
});
|
||||
|
||||
for (const ep of GATED_ENDPOINTS) {
|
||||
const shouldAllow = TIER_ORDER[tier] >= TIER_ORDER[ep.minTier];
|
||||
const verb = shouldAllow ? 'allows' : 'denies';
|
||||
it(`${verb} ${ep.method} ${ep.url} (requires ${ep.minTier})`, async () => {
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: ep.method,
|
||||
url: ep.url,
|
||||
payload: ep.body,
|
||||
}));
|
||||
|
||||
const body = parseJsonSafe(res.body);
|
||||
|
||||
if (shouldAllow) {
|
||||
// Tier gate passed. Downstream 4xx/5xx is acceptable — we only
|
||||
// guard against the middleware wrongly blocking.
|
||||
expect(res.statusCode).not.toBe(403);
|
||||
expect(body.error).not.toBe('TIER_INSUFFICIENT');
|
||||
} else {
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(body.error).toBe('TIER_INSUFFICIENT');
|
||||
expect(body.required).toBe(ep.minTier);
|
||||
expect(body.actual).toBe(tier);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
describe('TRIAL expiry fallback (getEffectiveTier)', () => {
|
||||
it('expired TRIAL is treated as FREE — denies a TEAMS endpoint', async () => {
|
||||
const sixteenDaysAgo = new Date(Date.now() - 16 * 24 * 3600 * 1000).toISOString();
|
||||
writeTier(tmpDir, 'TRIAL', sixteenDaysAgo);
|
||||
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'GET',
|
||||
url: '/api/cost/by-workspace',
|
||||
}));
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
const body = parseJsonSafe(res.body);
|
||||
expect(body.error).toBe('TIER_INSUFFICIENT');
|
||||
expect(body.actual).toBe('FREE');
|
||||
});
|
||||
|
||||
it('fresh TRIAL allows an ENTERPRISE endpoint', async () => {
|
||||
writeTier(tmpDir, 'TRIAL', new Date().toISOString());
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'GET',
|
||||
url: '/api/marketplace/enterprise-packs',
|
||||
}));
|
||||
expect(res.statusCode).not.toBe(403);
|
||||
});
|
||||
|
||||
it('TRIAL with null trialStartedAt is treated as FREE', async () => {
|
||||
writeTier(tmpDir, 'TRIAL', null);
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'GET',
|
||||
url: '/api/cost/by-workspace',
|
||||
}));
|
||||
expect(res.statusCode).toBe(403);
|
||||
const body = parseJsonSafe(res.body);
|
||||
expect(body.error).toBe('TIER_INSUFFICIENT');
|
||||
expect(body.actual).toBe('FREE');
|
||||
});
|
||||
});
|
||||
|
||||
describe('403 error shape contract', () => {
|
||||
it('denial response includes upgradeUrl for UI linking', async () => {
|
||||
writeTier(tmpDir, 'FREE');
|
||||
const res = await server.inject(authInject(server, {
|
||||
method: 'GET',
|
||||
url: '/api/cost/by-workspace',
|
||||
}));
|
||||
expect(res.statusCode).toBe(403);
|
||||
const body = JSON.parse(res.body) as Record<string, unknown>;
|
||||
expect(body.upgradeUrl).toBe('https://waggle-os.ai/upgrade');
|
||||
expect(body.message).toMatch(/requires the TEAMS tier/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ function deps(over: Partial<InterpretDeps> & { llm: InterpretDeps['llm'] }): Int
|
||||
return {
|
||||
text: 'do the thing',
|
||||
workspaceId: 'w1',
|
||||
currentTier: 'FREE',
|
||||
workspaces: [
|
||||
{ id: 'w1', name: 'Acme Redesign' },
|
||||
{ id: 'w2', name: 'Personal Notes' },
|
||||
@@ -38,9 +37,8 @@ describe('interpretCommand — Tier 1 resolver', () => {
|
||||
expect(res.action?.navigate).toEqual({ type: 'workspace', id: 'workspace:w1' });
|
||||
});
|
||||
|
||||
it('resolves install_mcp to an action on FREE — MCP install is free/Solo (never tier_gated)', async () => {
|
||||
it('resolves install_mcp to an action', async () => {
|
||||
const res = await interpretCommand(deps({
|
||||
currentTier: 'FREE',
|
||||
text: 'install the postgres mcp server',
|
||||
llm: llmReturning('{"kind":"action","actionId":"install_mcp","params":{"mcpId":"postgres"}}'),
|
||||
}));
|
||||
@@ -48,15 +46,6 @@ describe('interpretCommand — Tier 1 resolver', () => {
|
||||
expect(res.action?.id).toBe('install_mcp');
|
||||
});
|
||||
|
||||
it('passes the action through on a paid tier as well', async () => {
|
||||
const res = await interpretCommand(deps({
|
||||
currentTier: 'TEAMS',
|
||||
llm: llmReturning('{"kind":"action","actionId":"install_mcp","params":{"mcpId":"postgres"}}'),
|
||||
}));
|
||||
expect(res.kind).toBe('action');
|
||||
expect(res.action?.id).toBe('install_mcp');
|
||||
});
|
||||
|
||||
it('returns none (never an invented action) for an out-of-registry id', async () => {
|
||||
const res = await interpretCommand(deps({
|
||||
llm: llmReturning('{"kind":"action","actionId":"delete_production_db","params":{}}'),
|
||||
|
||||
@@ -2,7 +2,6 @@ import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
ACTION_IDS,
|
||||
validateAndBuildAction,
|
||||
checkTier,
|
||||
buildActionCatalog,
|
||||
type RegistryContext,
|
||||
} from '../../src/local/command-registry.js';
|
||||
@@ -90,17 +89,6 @@ describe('command-registry — closed action registry', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkTier', () => {
|
||||
it('never gates install_mcp — MCP install is free/Solo (PRO removed)', () => {
|
||||
expect(checkTier('install_mcp', 'FREE')).toEqual({ gated: false });
|
||||
expect(checkTier('install_mcp', 'TEAMS')).toEqual({ gated: false });
|
||||
});
|
||||
it('never gates a free/read action', () => {
|
||||
expect(checkTier('open_app', 'FREE')).toEqual({ gated: false });
|
||||
expect(checkTier('create_workspace', 'FREE')).toEqual({ gated: false });
|
||||
});
|
||||
});
|
||||
|
||||
it('renders a prompt catalog naming every action + nav/mcp targets', () => {
|
||||
const catalog = buildActionCatalog();
|
||||
for (const id of ACTION_IDS) expect(catalog).toContain(id);
|
||||
|
||||
@@ -310,9 +310,11 @@ describe('WorkspaceSessionManager — Phase A.1 concurrency invariants', () => {
|
||||
expect(statsB.frameCount).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('composes the FREE cap, concurrent same-workspace planning isolation, bounded cache, and cleanup', async () => {
|
||||
it('composes the session cap, concurrent same-workspace planning isolation, bounded cache, and cleanup', async () => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-solo-session-composition-'));
|
||||
const server = await buildLocalServer({ dataDir, tier: 'FREE' });
|
||||
const server = await buildLocalServer({ dataDir });
|
||||
// A small cap keeps the overflow check cheap; the sidecar default is MAX_WORKSPACE_SESSIONS.
|
||||
server.sessionManager.setMaxSessions(10);
|
||||
const workspaceId = server.agentState.activeWorkspaceId;
|
||||
expect(workspaceId).toBeTruthy();
|
||||
|
||||
@@ -440,7 +442,6 @@ describe('WorkspaceSessionManager — Phase A.1 concurrency invariants', () => {
|
||||
});
|
||||
|
||||
try {
|
||||
expect(server.localConfig.tier).toBe('FREE');
|
||||
expect(server.sessionManager.getMaxSessions()).toBe(10);
|
||||
expect(server.sessionManager.size).toBe(0);
|
||||
expect(server.mindCache.keys()).toEqual([workspaceId]);
|
||||
|
||||
Reference in New Issue
Block a user