/home/techb158/balavpn.abdallabala.com/docs
Edit: /home/techb158/balavpn.abdallabala.com/docs/application-documentation.md (27515B)
# COSMIC AI-Risk SaaS Application Documentation
Generated: 2026-07-07
## Purpose
This document explains the COSMIC AI-Risk SaaS application as it exists in this workspace. It covers the original academic prototype, the SaaS rebuild, the database, services, API routes, frontend, local fallback harness, tests, and deployment files.
The project has two related layers:
- The frozen academic prototype in the repository root.
- The commercial SaaS rebuild in `saas-app/`.
The SaaS app preserves the COSMIC domain language and risk logic from the prototype while adding multi-tenancy, PostgreSQL, Prisma, authentication, role permissions, billing boundaries, SSO boundaries, and deployment structure.
## Repository Map
### Root Prototype
| Path | Purpose |
|---|---|
| `server.js` | Original Node.js API server for the academic prototype. |
| `public/index.html` | Original dashboard UI. |
| `public/styles.css` | Original green/white COSMIC dashboard styling. |
| `public/app.js` | Original browser application and dashboard workflows. |
| `public/risk-engine.js` | Browser-side COSMIC risk engine used by prototype mode. |
| `data/database.json` | Normalized JSON data store used by the original prototype. |
| `src/` | Prototype repositories, services, security helpers, PM integrations, and operations. |
| `tests/` | Prototype test suite for risk engine, storage, workflows, integrations, reports, access control, and production hardening. |
| `docs/` | Academic design docs, UML, database model, runbooks, QA reports, and SaaS planning docs. |
| `COSMIC-AI-Risk-Dashboard-chat-export.md` | Structured development record from the project conversation. |
### SaaS Rebuild
| Path | Purpose |
|---|---|
| `saas-app/src/app/` | Next.js App Router pages, layouts, and API routes. |
| `saas-app/src/components/` | Shared React components such as app shell, logout button, and error boundary. |
| `saas-app/src/domain/` | Dependency-free business rules: risk scoring, permissions, entitlements, integrations. |
| `saas-app/src/services/` | Application services for auth, projects, risks, gates, integrations, reports, SSO, and audit. |
| `saas-app/src/lib/` | Infrastructure helpers: Prisma, request context, tenant guard, OIDC, metrics, rate limit, idempotency, HTTP responses. |
| `saas-app/prisma/schema.prisma` | PostgreSQL SaaS data model. |
| `saas-app/prisma/seed.js` | Seed script for users, orgs, workspaces, projects, risks, mitigations, gates, indicators, and integrations. |
| `saas-app/local-server.js` | Dependency-free local fallback harness on port `8090`. |
| `saas-app/mock-oidc-provider.js` | Local OIDC provider for SSO development. |
| `saas-app/tests/` | SaaS unit and integration tests. |
| `saas-app/docker-compose.yml` | Docker Compose app, PostgreSQL, and pgAdmin. |
| `saas-app/docker-compose.supabase.yml` | Compose override for Supabase-managed PostgreSQL. |
| `saas-app/Dockerfile` | Multi-stage production container build. |
| `saas-app/docs/` | SaaS documentation. |
## Product Scope
The SaaS product targets:
- B2B teams managing AI project risk across departments.
- Consultants managing many client workspaces.
- Enterprise customers requiring auditability, roles, integrations, SSO, and compliance-ready deployment.
Current implementation supports a strong local SaaS foundation:
- Organization and workspace tenancy.
- Session-based login/signup.
- Role-based access control.
- Project CRUD.
- Risk and mitigation CRUD.
- COSMIC scoring and dashboard aggregation.
- Deployment gate evaluation and reviewer decisions.
- Audit logging.
- Report exports.
- Integration models and simulated/live-boundary sync.
- Manual subscription and entitlement rules.
- OIDC/SSO development path.
- Docker, PostgreSQL, pgAdmin, and Supabase deployment paths.
## Technology Stack
| Layer | Implementation |
|---|---|
| Framework | Next.js 15 App Router |
| UI | React 19 |
| Database | PostgreSQL 16 |
| ORM | Prisma 5.22 |
| Auth | Session cookie named `cosmic_session` |
| Password hashing | bcryptjs |
| Validation/helpers | Zod, custom guards |
| Billing boundary | Stripe package installed, checkout/portal/webhook route placeholders |
| Deployment | Docker, Docker Compose, optional Supabase DB |
| Local fallback | Native Node.js HTTP server, no Next/Prisma runtime required |
## Runtime Ports
| Mode | URL |
|---|---|
| Next.js dev script | `http://localhost:8091` |
| Docker app mapping | `http://localhost:8092` maps to container port `8090` |
| Local fallback harness | `http://localhost:8090` |
| pgAdmin | `http://127.0.0.1:5050` |
| Mock OIDC provider | `http://localhost:8093` |
## Environment Variables
Important variables used by the SaaS app:
| Variable | Purpose |
|---|---|
| `DATABASE_URL` | PostgreSQL connection string. |
| `NEXT_PUBLIC_APP_URL` | Public app URL used by frontend and auth flows. |
| `POSTGRES_PASSWORD` | Local Docker PostgreSQL password. |
| `COSMIC_SESSION_SECRET` | Required configuration secret for production checks. |
| `COSMIC_INVITE_SECRET` | Used for invite token hashing. |
| `COSMIC_TOKEN_ENCRYPTION_KEY` | Required boundary for encrypted OAuth credentials. |
| `COSMIC_MANUAL_BILLING_ENABLED` | Allows manual billing mode without Stripe. |
| `STRIPE_SECRET_KEY` | Future Stripe integration secret. |
| `COSMIC_SSO_ENABLED` | Enables SSO route flow. |
| `COSMIC_OIDC_ISSUER` | OIDC issuer URL. |
| `COSMIC_OIDC_CLIENT_ID` | OIDC client ID. |
| `COSMIC_OIDC_CLIENT_SECRET` | OIDC client secret. |
| `COSMIC_OIDC_REDIRECT_URL` | OIDC callback URL. |
| `COSMIC_BOOTSTRAP_EMAIL` | Header fallback actor email for local/dev API calls. |
Do not commit real production secrets.
## Database Model
The SaaS database is defined in `saas-app/prisma/schema.prisma`.
### Tenant Structure
```text
Organization
Workspace
Project
Risk
Mitigation
Evidence
LifecyclePhase
Indicator
Experiment
ModelMetric
GateEvaluation
GateCriterion
GateDecision
AuditEvent
ReportExport
Integration
ExternalWorkItemMapping
IntegrationSyncRun
Membership
User
Subscription
Invitation
UsageEvent
OAuthToken
```
### Enums
| Enum | Values |
|---|---|
| `OrganizationStatus` | `TRIAL`, `ACTIVE`, `SUSPENDED`, `CANCELED` |
| `WorkspaceType` | `B2B_TEAM`, `CONSULTANT_CLIENT`, `ENTERPRISE` |
| `MembershipStatus` | `INVITED`, `ACTIVE`, `DISABLED` |
| `SubscriptionSource` | `MANUAL`, `STRIPE` |
| `SubscriptionStatus` | `TRIALING`, `ACTIVE`, `PAST_DUE`, `CANCELED`, `SUSPENDED` |
| `RiskStatus` | `OPEN`, `IN_MITIGATION`, `ACCEPTED`, `CLOSED` |
| `ApprovalStatus` | `PENDING`, `APPROVED`, `REJECTED`, `ACCEPTED` |
| `MitigationStatus` | `NOT_STARTED`, `IN_PROGRESS`, `DONE`, `REJECTED` |
| `GateStatus` | `READY`, `WARNING`, `BLOCKED` |
| `GateDecisionValue` | `APPROVED`, `REJECTED`, `ACCEPTED`, `NEEDS_CHANGES` |
| `IntegrationProvider` | `TRELLO`, `JIRA`, `ASANA`, `MICROSOFT_PLANNER` |
| `IntegrationStatus` | `CONNECTED`, `NEEDS_CONFIGURATION`, `DISABLED` |
For full field-level details, see `saas-app/docs/database-guide.md`.
## Seed Data
`saas-app/prisma/seed.js` creates:
- System roles.
- Multiple demo users.
- Organizations and workspaces.
- Projects.
- Risks.
- Mitigations.
- Evidence.
- Lifecycle phases.
- Indicators.
- Experiments and model metrics.
- Gate evaluations and criteria.
- PM integrations.
Documented demo users:
| Email | Password | Role |
|---|---|---|
| `owner@cosmic.local` | `cosmic123` | owner |
| `admin@cosmic.local` | `admin123` | admin |
| `pm@cosmic.local` | `pm123` | project manager |
| `risk-owner@cosmic.local` | `risk123` | risk owner |
| `viewer@cosmic.local` | `view123` | viewer |
## Domain Logic
### Risk Engine
File: `saas-app/src/domain/risk-engine.js`
Responsibilities:
- Scores risks using probability, impact, and detectability.
- Calculates normalized score from a 1-5 scale.
- Calculates residual risk using mitigation progress and effectiveness.
- Classifies scores as `Low`, `Moderate`, `High`, or `Critical`.
- Aggregates organizational, technical, and human dimension scores.
- Aggregates lifecycle risk.
- Calculates mitigation completion.
- Evaluates deployment gate status.
- Produces project dashboard payloads.
Core formulas:
```text
rawScore = probability * impact * detectability
normalizedScore = round((rawScore / 125) * 100)
reduction = mitigationProgress% * mitigationEffectiveness%
residualScore = normalizedScore * (1 - reduction)
```
Closed risks receive a residual reduction to 10 percent of normalized score.
### Gate Logic
The gate evaluates:
- Overall risk score.
- Open critical risks.
- Mitigation completeness.
- Data readiness.
- Selected model F1.
- Selected model stability.
- Ethical review.
- Legal review.
- High-risk approval state.
Gate status is:
- `BLOCKED` if any blocking criterion fails.
- `WARNING` if warnings exist or risk score crosses warning threshold.
- `READY` if release criteria pass.
### Permissions
File: `saas-app/src/domain/permissions.js`
Defined permission strings include:
```text
organization:manage
workspace:manage
project:read
project:write
risk:read
risk:write
risk:delete
mitigation:write
gate:read
gate:evaluate
gate:review
report:export
integration:read
integration:manage
integration:sync
oauth:manage
billing:manage
audit:read
```
Roles:
- owner
- admin
- project_manager
- risk_owner
- governance_reviewer
- legal_ethics_reviewer
- integration_admin
- viewer
- consultant
### Entitlements
File: `saas-app/src/domain/entitlements.js`
Plans:
| Plan | Users | Projects | Reports/month | Integrations | Storage |
|---|---:|---:|---:|---:|---:|
| pilot | 10 | 5 | 100 | 4 | 1024 MB |
| starter | 5 | 3 | 25 | 1 | 512 MB |
| team | 25 | 20 | 500 | 4 | 10240 MB |
| enterprise | 1000 | 1000 | 100000 | 100 | 102400 MB |
Access is allowed for `TRIALING` and `ACTIVE` subscriptions, or when `adminOverride` is enabled, unless the organization is suspended.
### Integration Mapping
File: `saas-app/src/domain/integrations.js`
Supported providers:
- Trello
- Jira
- Asana
- Microsoft Planner
The domain layer maps COSMIC risk state into provider-specific statuses, for example:
- Trello: `Blocked by risk`, `In mitigation`, `Approved for deployment`.
- Jira: `To Do`, `In Progress`, `Done`.
- Asana: `Open`, `In progress`, `Complete`.
- Microsoft Planner: `Blocked bucket`, `In progress`, `Not started`, `Completed`.
## Service Layer
### Auth Service
File: `saas-app/src/services/auth-service.js`
Implements:
- Password hashing with bcrypt.
- Login.
- Signup.
- Session creation.
- Session lookup and expiry cleanup.
- Logout.
- Actor extraction from session token.
Signup creates:
- User.
- Organization.
- Owner membership.
- Manual pilot subscription.
- Default workspace.
- Starter project.
### Project Service
File: `saas-app/src/services/project-service.js`
Implements:
- Listing workspace projects.
- Creating projects with entitlement checks.
- Loading project aggregate data.
- Updating project metadata.
- Explicit cascade delete for related project records.
- Audit logging for create/update/delete.
### Risk Service
File: `saas-app/src/services/risk-service.js`
Implements:
- Risk list with calculated score.
- Risk create/update/delete.
- Mitigation create/read/list/update/delete.
- Evidence attachment to mitigations.
- Status normalization for UI-friendly and enum-friendly values.
- Audit events for sensitive mutations.
### Dashboard Service
File: `saas-app/src/services/dashboard-service.js`
Implements:
- Prisma include tree for project aggregate loading.
- Dashboard generation by passing the aggregate into the risk engine.
### Gate Service
File: `saas-app/src/services/gate-service.js`
Implements:
- Evaluate and persist gate.
- Persist criteria.
- Add reviewer decisions.
- Update gate criterion reviewer notes and evidence links.
- List gate history.
- List audit events.
### Integration Service
File: `saas-app/src/services/integration-service.js`
Implements:
- Get/update/delete integration.
- Simulated sync from COSMIC risks into external work item mappings.
- Sync run history.
- Live connector test boundary.
- Live sync boundary.
- Audit events for sync actions.
Current live connector behavior is still a controlled local boundary. It creates mappings and external URLs but does not call real third-party APIs unless future provider clients are wired.
### Reporting Service
File: `saas-app/src/services/reporting-service.js`
Implements:
- Risk register CSV.
- Executive HTML.
- JSON dashboard report fallback for other report types.
### SSO Service
File: `saas-app/src/services/sso-service.js`
Implements:
- OIDC discovery.
- Authorization code exchange.
- ID token claim parsing.
- User lookup or first-time provisioning.
- Session creation after SSO callback.
First-time SSO users receive an organization, owner membership, subscription, workspace, and starter project.
### Audit Service
File: `saas-app/src/services/audit-service.js`
Writes audit events with:
- Organization.
- Workspace.
- Project.
- Actor.
- Entity type and ID.
- Action.
- Before/after JSON snapshots.
- IP address and user agent.
## Infrastructure Helpers
| File | Purpose |
|---|---|
| `src/lib/prisma.js` | Creates and reuses Prisma client. |
| `src/lib/request-context.js` | Reads session cookie or bootstrap email and resolves active memberships. |
| `src/lib/tenant-guard.js` | Enforces project-level tenant and permission checks. |
| `src/lib/http.js` | Standard JSON/error response helpers. |
| `src/lib/api-client.js` | Frontend fetch wrapper. |
| `src/lib/idempotency.js` | In-memory idempotency key support for POST flows. |
| `src/lib/metrics.js` | Request metric aggregation. |
| `src/lib/rate-limit.js` | Shared in-memory rate limit helpers. |
| `src/lib/oidc.js` | OIDC config, discovery, nonce/state, JWT payload decode. |
| `src/lib/crypto.js` | Token generation and redaction helpers. |
| `src/middleware.js` | API route rate limiting at 100 requests/minute per IP. |
## Frontend
### Main App Pages
| File | Purpose |
|---|---|
| `src/app/page.jsx` | Public landing/home page. |
| `src/app/login/page.jsx` | Login form. |
| `src/app/signup/page.jsx` | Signup form. |
| `src/app/dashboard/layout.jsx` | Dashboard layout wrapper. |
| `src/app/dashboard/page.jsx` | Main interactive dashboard SPA. |
| `src/app/layout.jsx` | Root HTML layout and metadata. |
| `src/app/globals.css` | Global styling, app shell, sidebar, tabs, tables, modals, badges, toasts. |
### Dashboard Tabs
The Next.js dashboard has seven tabs:
1. Overview: summary cards, dimensions, lifecycle.
2. Projects: list, open, create, and delete projects.
3. Risks: search, sort, create, view, edit, delete, status changes.
4. Mitigations: create, edit, delete, status/progress management.
5. Gate: evaluate gate and submit decisions.
6. Integrations: create integration records and trigger sync.
7. Audit: read project audit events.
The dashboard uses query params:
```text
/dashboard?tab=Risks&projectId=
```
This avoids route-level 404s for tabs and keeps the selected project shareable.
### Components
| Component | Purpose |
|---|---|
| `AppShell.jsx` | Sidebar/top-level authenticated shell. |
| `LogoutButton.jsx` | Client logout action. |
| `ErrorBoundary.jsx` | UI failure boundary with retry behavior. |
## API Routes
### Health and Operations
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/health` | Basic service health. |
| GET | `/api/ready` | Readiness check with database connectivity. |
| GET | `/api/metrics` | In-memory metrics snapshot. |
### Auth
| Method | Route | Purpose |
|---|---|---|
| POST | `/api/auth/signup` | Create user/org/workspace/project and session. |
| POST | `/api/auth/login` | Login with email/password and create session. |
| POST | `/api/auth/logout` | Delete session. |
| GET | `/api/auth/session` | Return authenticated session state. |
| GET | `/api/auth/me` | Return current actor details. |
| POST | `/api/auth/invite` | Create organization invite. |
| POST | `/api/auth/accept-invite` | Accept invitation. |
| GET | `/api/auth/sso` | Start OIDC flow. |
| GET | `/api/auth/sso/callback` | Complete OIDC callback. |
### Tenancy
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/organizations` | List actor organizations. |
| POST | `/api/organizations` | Create organization. |
| GET | `/api/workspaces` | List workspaces, optionally by organization. |
| POST | `/api/workspaces` | Create workspace. |
| PATCH | `/api/workspaces/:workspaceId` | Update workspace. |
### Projects
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/workspaces/:workspaceId/projects` | List projects in workspace. |
| POST | `/api/workspaces/:workspaceId/projects` | Create project. |
| GET | `/api/projects/:projectId` | Get project. |
| PATCH | `/api/projects/:projectId` | Update project. |
| DELETE | `/api/projects/:projectId` | Delete project and related records. |
| GET | `/api/projects/:projectId/dashboard` | Return calculated dashboard. |
### Risks and Mitigations
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/projects/:projectId/risks` | List scored project risks. |
| POST | `/api/projects/:projectId/risks` | Create risk. |
| PATCH | `/api/risks/:riskId` | Update risk. |
| DELETE | `/api/risks/:riskId` | Delete risk. |
| GET | `/api/projects/:projectId/mitigations` | List project mitigations. |
| POST | `/api/risks/:riskId/mitigations` | Create mitigation for risk. |
| GET | `/api/mitigations/:mitigationId` | Get mitigation. |
| PATCH | `/api/mitigations/:mitigationId` | Update mitigation. |
| DELETE | `/api/mitigations/:mitigationId` | Delete mitigation. |
| POST | `/api/mitigations/:mitigationId/evidence` | Attach evidence. |
### Gate and Audit
| Method | Route | Purpose |
|---|---|---|
| POST | `/api/projects/:projectId/gate/evaluate` | Evaluate and persist gate. |
| GET | `/api/projects/:projectId/gate/history` | List gate evaluations. |
| POST | `/api/gates/:gateId/decisions` | Add reviewer decision. |
| PATCH | `/api/gate-criteria/:criterionId` | Update reviewer notes/evidence. |
| GET | `/api/projects/:projectId/audit` | List project audit events. |
### Reports
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/projects/:projectId/reports/:reportType` | Return report in CSV, HTML, or JSON. |
Important report types:
- `executive.html`
- `risk-register.csv`
- any other value returns JSON dashboard package.
### Integrations
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/integration-providers` | List supported providers. |
| GET | `/api/workspaces/:workspaceId/integrations` | List workspace integrations. |
| POST | `/api/workspaces/:workspaceId/integrations` | Create integration. |
| GET | `/api/integrations/:integrationId` | Get integration. |
| PATCH | `/api/integrations/:integrationId` | Update integration. |
| DELETE | `/api/integrations/:integrationId` | Delete integration. |
| POST | `/api/integrations/:integrationId/sync` | Simulated sync. |
| POST | `/api/integrations/:integrationId/live/test` | Live connector test boundary. |
| POST | `/api/integrations/:integrationId/live/sync` | Live connector sync boundary. |
| GET | `/api/workspaces/:workspaceId/integration-mappings` | List external mappings. |
| GET | `/api/workspaces/:workspaceId/sync-runs` | List sync runs. |
### Billing
| Method | Route | Purpose |
|---|---|---|
| GET | `/api/billing/subscription` | Get current subscription and entitlements. |
| POST | `/api/billing/checkout` | Stripe checkout boundary. |
| POST | `/api/billing/portal` | Stripe billing portal boundary. |
| POST | `/api/billing/webhook` | Stripe webhook boundary. |
## Local Fallback Harness
File: `saas-app/local-server.js`
Purpose:
- Lets the project run locally without Next.js, Prisma, or PostgreSQL.
- Imports the original prototype seed data from `data/database.json`.
- Uses SaaS domain modules in memory.
- Serves the original prototype dashboard on `/dashboard`.
- Serves the simple SaaS fallback dashboard on `/saas-local`.
- Provides compatibility API routes for the original frontend.
- Provides SaaS-like routes for health, tenancy, projects, risks, mitigations, gates, reports, integrations, billing, and auth.
Run:
```powershell
cd saas-app
npm run local:fallback
```
Open:
```text
http://localhost:8090
```
## Authentication Flow
### Email/Password
1. User submits `/api/auth/login`.
2. Auth service validates bcrypt password.
3. Auth service creates `Session`.
4. API route sets `cosmic_session` cookie.
5. Frontend calls `/api/auth/session`.
6. Request context loads user, active memberships, organization, and role.
### Signup
1. User submits `/api/auth/signup`.
2. App creates user.
3. App creates organization.
4. App creates owner membership.
5. App creates manual pilot subscription.
6. App creates default workspace.
7. App creates starter project.
8. App creates session cookie.
### SSO
1. `/api/auth/sso` starts OIDC authorization.
2. Mock or real provider redirects to `/api/auth/sso/callback`.
3. Callback verifies state, exchanges code, parses ID token.
4. Existing user logs in or first-time user is provisioned.
5. Session cookie is created.
## Authorization and Tenant Isolation
The app enforces access through:
- Active organization membership.
- Role permission arrays.
- Optional workspace scopes.
- Project-to-workspace-to-organization lookup.
Key guard:
```text
requireProjectAccess(actor, projectId, permission)
```
This rejects access when:
- Project does not exist.
- Actor is not a member of the project organization.
- Actor lacks the requested permission.
- Actor membership has workspace scope that excludes the project workspace.
## Billing and Plan Limits
Billing is currently manual-first with Stripe-ready route boundaries.
Implemented:
- Subscription table.
- Plan limits.
- Active/trial access logic.
- Suspended organization blocking.
- Project creation entitlement check.
- Manual admin override.
Pending production work:
- Real Stripe checkout session creation.
- Stripe customer portal.
- Stripe webhook verification.
- Usage metering enforcement across reports, storage, integrations, and users.
## Integration Workflow
Current integration workflow:
1. Create integration in workspace.
2. Trigger sync.
3. For every project risk in the workspace, create or update an external mapping.
4. Record `IntegrationSyncRun`.
5. Mark integration connected.
6. Write audit event.
The live endpoints currently act as safe boundaries and local sync simulations. Real provider calls should be implemented behind explicit credentials and feature flags.
## Reporting Workflow
Reports are generated from the dashboard aggregate.
Current outputs:
- `risk-register.csv`
- `executive.html`
- JSON package for any other report type.
Report exports can be expanded later to store `ReportExport` records, enforce monthly report limits, and generate PDF artifacts.
## Testing
### SaaS Tests
Run:
```powershell
cd saas-app
npm test
```
Test files:
| File | Coverage |
|---|---|
| `saas-domain.test.js` | Risk scoring, gate logic, permissions, entitlements, provider mappings. |
| `tenant-security.test.js` | Workspace access, risk mutation permissions, subscription access. |
| `idempotency.test.js` | Idempotency key behavior. |
| `metrics.test.js` | Metrics aggregation. |
| `oidc.test.js` | OIDC helper behavior. |
| `rate-limit.test.js` | Rate limit behavior. |
| `integration-service.test.js` | Integration provider status mapping. |
| `local-server.test.js` | Dependency-free local harness API workflows. |
### Prototype Tests
Run from repository root:
```powershell
npm test
```
Covers:
- Risk engine.
- JSON storage.
- Risk CRUD.
- Mitigation workflow.
- Gate workflow.
- Integrations.
- OAuth/live connector boundaries.
- Reporting.
- Access control.
- Production hardening.
- API workflows.
## Local Development
### Full SaaS Mode
```powershell
cd saas-app
npm install
docker compose up -d postgres
npm run db:push
npm run db:seed
npm run dev
```
Open:
```text
http://localhost:8091
```
### Docker Mode
```powershell
cd saas-app
docker compose up -d --build
```
Open:
```text
http://localhost:8092
```
pgAdmin:
```text
http://127.0.0.1:5050
```
### Fallback Mode
```powershell
cd saas-app
npm run local:fallback
```
Open:
```text
http://localhost:8090
```
## Deployment
### Dockerfile
The production image:
- Uses `node:20-bookworm-slim`.
- Runs `npm ci`.
- Generates Prisma client.
- Builds Next standalone output.
- Installs runtime dependencies including `wget`, CA certificates, and `libssl1.1`.
- Runs as non-root user `cosmic`.
- Exposes port `8090`.
- Runs a healthcheck against `/api/health`.
- Starts by pushing Prisma schema, seeding data, then running `node server.js`.
### Docker Compose
`saas-app/docker-compose.yml` includes:
- `app`
- `postgres`
- `pgadmin`
- persistent `cosmic-postgres-data` volume
App service maps:
```text
localhost:8092 -> container:8090
```
### Supabase
`saas-app/docker-compose.supabase.yml` disables local Postgres and expects `DATABASE_URL` from `.env`.
Use:
```powershell
docker compose -f docker-compose.yml -f docker-compose.supabase.yml up -d
```
## Configuration Check
Run:
```powershell
cd saas-app
npm run check:config
```
Required:
- `DATABASE_URL`
- `COSMIC_SESSION_SECRET`
- `COSMIC_INVITE_SECRET`
- `COSMIC_TOKEN_ENCRYPTION_KEY`
Production warnings include:
- `NEXT_PUBLIC_APP_URL` still pointing to localhost.
- Short session secret.
- Stripe missing when manual billing is not enabled.
## Current Limitations
- Stripe routes are boundary placeholders and need real checkout, portal, and webhook implementation.
- OAuth token encryption model exists, but full provider credential storage and refresh flows are not production-complete in SaaS mode.
- Live integration endpoints simulate or locally map work items; they do not yet call Trello/Jira/Asana/Microsoft Planner APIs.
- The fallback server is for local testing only and stores data in memory.
- The Next.js dashboard is functional, but the fallback route currently restores the original prototype UI for visual parity.
- Some docs generated earlier contain encoding artifacts from PowerShell output; content is still usable, but cleanup would improve polish.
## Recommended Next Steps
1. Normalize the full UI direction: decide whether the production SaaS should use the new Next.js dashboard styling or the restored original COSMIC prototype styling.
2. Add customer-facing SaaS pages: pricing, privacy, terms, security, docs, and onboarding.
3. Complete Stripe checkout, portal, and webhook flows.
4. Complete OAuth token storage and live provider sync.
5. Add organization settings UI for domains, data retention, SSO enforcement, and billing.
6. Add workspace/member invitation UI.
7. Add report export persistence and plan limit enforcement for reports.
8. Add backup/restore automation for PostgreSQL.
9. Add structured logging and production monitoring.
10. Add end-to-end browser tests for core workflows.
## Quick Status
The project currently has:
- A working original academic prototype.
- A SaaS rebuild with Next.js, Prisma, PostgreSQL, auth, RBAC, tenant guards, CRUD APIs, dashboard UI, SSO boundary, and integration/reporting boundaries.
- A local fallback harness on port `8090`.
- Docker and Supabase deployment paths.
- Passing root prototype and SaaS test suites from the last verification run.