diff --git a/.dockerignore b/.dockerignore index 629229d..8ba5dec 100644 --- a/.dockerignore +++ b/.dockerignore @@ -5,7 +5,8 @@ dist .env.local npm-debug.log* serviceAccountKey*.json -data/*.tmp.* +data +.migration-* # Private webhook signing registrations and test-only emulator artifacts data/.clickup-webhooks.json* diff --git a/.env.example b/.env.example index f87a247..eea073c 100644 --- a/.env.example +++ b/.env.example @@ -8,6 +8,6 @@ NODE_ENV=production # Firebase Service Account Key (JSON string, base64, or file path) for zen-flow Firestore FIREBASE_SERVICE_ACCOUNT_KEY= -# Optional persistent volume for local store, audit log and private webhook registry. -# Cloud persistence uses Firebase Admin; unauthenticated Web SDK fallback is disabled. -ZENFLOW_DATA_DIR= +# Existing Firestore storage target. Google identity trust remains zen-flow-7173d. +FIREBASE_PROJECT_ID=zen-flow-7173d +FIREBASE_DATABASE_ID=(default) diff --git a/.github/workflows/readiness.yml b/.github/workflows/readiness.yml index bb74c4a..031dce9 100644 --- a/.github/workflows/readiness.yml +++ b/.github/workflows/readiness.yml @@ -24,4 +24,4 @@ jobs: - run: npm run lint - run: npx tsc --noEmit --noUnusedLocals --noUnusedParameters - run: npm run build - - run: node --import tsx tests/smoke-production.ts + - run: npm run test:persistence diff --git a/.gitignore b/.gitignore index e671757..13f96c8 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ data/*.tmp.* data/.clickup-webhooks.json* .firebase/ *-debug.log + +data/ diff --git a/AGENTS.md b/AGENTS.md index 2efc03a..9c06306 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,14 @@ This document records the complete lifecycle of architectural sweeps, discovered ## 1. Discovered Optimizations +### Sweep 53: 2026-10-27 (Standalone Firestore Workspace) + +- Removed active ClickUp integration: synchronization, proxy routes, webhooks, credential controls, member mapping and task destination/link UI. Retired API URLs return 410; native cross-board subtask delegation remains available. +- Firestore now owns members, tasks, timers, activity history and append-only audit records. Mutations commit atomically before HTTP success and SSE, with revision conflict detection and rollback on database failure. Local JSON/NDJSON persistence and browser credential upload are removed. +- Added a restart-safe migration and private metadata backup without saved tokens. Existing IDs, content, native parent links and ownership are retained. +- Added database failure tests and Firestore/Auth emulator coverage for migration, atomic audit rollback, conflicts, compiled-server CRUD, delegation and restart/deletion recovery. See docs/READINESS.md for deployment constraints and evidence; earlier integration descriptions below are historical. + + ### Sweep 52: 2026-10-25 (Verified API Identity, Private ClickUp Credentials, Server-Owned Firebase, Signed Webhooks and Bounded Resources) - **SEC-16 (Verified Backend Identity and Authorization):** Firebase identities are verified against the fixed Google login project, independently of configurable storage credentials. HttpOnly same-origin sessions protect REST, downloads and SSE. Server-owned role and ownership checks replace client header assertions, including atomic batch validation. Universal authenticated cross-board subtask delegation remains available (AUTH-07). diff --git a/Dockerfile b/Dockerfile index feee855..9852901 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,10 +4,10 @@ FROM node:22-slim AS builder WORKDIR /app COPY package*.json ./ -RUN npm install +RUN npm ci COPY . . -RUN mkdir -p /app/data && npm run build +RUN npm run build FROM node:22-slim AS runner @@ -17,10 +17,9 @@ ENV NODE_ENV=production ENV PORT=3000 COPY package*.json ./ -RUN npm install --omit=dev +RUN npm ci --omit=dev COPY --from=builder /app/dist ./dist -COPY --from=builder /app/data ./data COPY --from=builder /app/firebase-applet-config.json* ./ EXPOSE 3000 diff --git a/README.md b/README.md index 224cb27..f614272 100644 --- a/README.md +++ b/README.md @@ -1,379 +1,41 @@ -# zenFlow | Intelligent Workload Management System +# zenFlow -[![Node Version](https://img.shields.io/badge/Node-%3E%3D22.0.0-339933?logo=node.js)](https://nodejs.org/) -[![React Version](https://img.shields.io/badge/React-19.0.1-61DAFB?logo=react)](https://react.dev/) -[![TypeScript](https://img.shields.io/badge/TypeScript-5.8.2-3178C6?logo=typescript)](https://www.typescriptlang.org/) -[![Tailwind CSS](https://img.shields.io/badge/Tailwind-4.1.14-06B6D4?logo=tailwindcss)](https://tailwindcss.com/) -[![Firebase](https://img.shields.io/badge/Firebase-Admin%20Firestore-FFCA28?logo=firebase)](https://firebase.google.com/) -[![ClickUp API](https://img.shields.io/badge/ClickUp-v2%20Integration-7B68EE?logo=clickup)](https://clickup.com/) +zenFlow is a standalone workload and task manager for content and design teams. Cloud Firestore stores members, tasks, ownership, deadlines, timers, activity history and compliance audit records. The authenticated Node backend controls access and broadcasts committed changes over SSE. -**zenFlow** is an institutional-grade, real-time workload orchestration platform engineered for high-velocity creative, content, and design agencies. It balances individual cognitive loads, enforces Work-In-Progress (WIP) limits, provides universal cross-board task delegation, and synchronizes bidirectionally with ClickUp while maintaining strict zero-trust security and compliance auditability. +## Run ---- - -## πŸ“‘ Table of Contents - -- [Core Capabilities](#-core-capabilities) -- [System Architecture](#-system-architecture) -- [Technology Stack](#-technology-stack) -- [Directory Structure](#-directory-structure) -- [Getting Started](#-getting-started) - - [Prerequisites](#prerequisites) - - [Installation](#installation) - - [Environment Configuration](#environment-configuration) - - [Running the Development Server](#running-the-development-server) -- [Available Scripts](#-available-scripts) -- [Security & Access Control](#-security--access-control) -- [ClickUp Two-Way Synchronization](#-clickup-two-way-synchronization) -- [Data Persistence & Storage Modes](#-data-persistence--storage-modes) -- [Testing & Quality Assurance](#-testing--quality-assurance) -- [Production Deployment](#-production-deployment) -- [Audit & Compliance Trail](#-audit--compliance-trail) - ---- - -## ⚑ Core Capabilities - -### 1. Cognitive Load & Workload Scoring - -- **Dynamic Load Scoring**: Tasks are weighted by cognitive strain (`Low = 1`, `Medium = 2`, `High = 3`), dynamically calculating active workload pressure per team member. -- **WIP Limits & Demand Alarms**: Configurable Work-In-Progress thresholds flag overloaded members with immediate visual warnings and demand alerts before task assignments breach capacity. -- **Billable Hours & Cycle Metrics**: Active time accumulation while tasks reside in `in_progress`, alongside manual time adjustments, cycle tracking, and historical activity trails. - -### 2. Multi-Stage Swimlane Lifecycle - -ZenFlow partitions workflows into dedicated swimlanes for Content and Design boards: - -- **Pipeline**: Backlog ideation space for uncommitted initiatives. ClickUp list assignment and deadlines remain optional; tasks do not trigger unassigned warnings. -- **Retainer**: Dedicated lane for ongoing, recurring, or retainer client engagements. Retainer tasks do not require deadlines, do not inflate WIP counts, and feature direct one-click `+ Subtask` generation that feeds actionable items into execution lanes. -- **To Do**: Prioritized queue ready for immediate execution. -- **In Progress**: Active execution lane with live billable duration tracking. -- **In Review**: Creative Director and client review staging. -- **Done & Archived**: Completed milestones with timestamped cycle analytics. - -### 3. Floating Cross-Board Free Pool - -- **Idle Capacity Detection**: A persistent glassmorphic floating pill continuously monitors all Content and Design team members, identifying individuals with zero active tasks in `To Do` or `In Progress`. -- **Instant Allocation**: Expand the floating panel to review idle members across roles and instantly allocate tasks without leaving the active board view. - -### 4. ClickUp Deep Bi-Directional Integration - -- **Universal Subtask Delegation**: Any authenticated team member can delegate subtasks across boards. Subtasks nest hierarchically under the parent task in both ZenFlow and ClickUp. -- **Isolated Per-Task Hierarchy**: Dynamic resolution of ClickUp Spaces, Folders, Lists, and Custom Task Types without cross-space UI pollution. -- **Single Source of Truth (SSoT)**: ZenFlow asserts authoritative state on ownership, status, and deadlines, defensively correcting divergence from ClickUp webhooks. -- **HMAC SHA-256 Webhooks**: Raw request signature verification prevents spoofing or tampering of incoming status and assignee updates. -- **Credential Redaction**: Personal API tokens are isolated server-side; client browser payloads receive only non-sensitive connection indicators (`clickupConnected: true`). - -### 5. Resilient Real-Time Engine & Offline Capability - -- **Server-Sent Events (SSE)**: Bounded output streaming (256 KiB backpressure limit) ensures low latency and memory safety under multi-client loads. -- **Optimistic UI with FIFO Replay**: Offline changes, reorders, and creations are applied instantly to local state and replayed sequentially upon network reconnection. - ---- - -## πŸ— System Architecture - -```mermaid -flowchart TD - Client["ZenFlow Web App (React 19 + Tailwind v4 + Motion)"] - SSE["SSE Connection (/api/events)"] - AuthCookie["HttpOnly Strict Session Cookie"] - - subgraph Backend["Express & TypeScript Server (Node 22)"] - SecMiddleware["Security & Auth Middleware (Google Token Verification)"] - RBAC["Role-Based Access Control (Superadmin / CD / Member)"] - Store["In-Memory App Store + Atomic Store Serializer"] - SSEHub["Bounded SSE Event Broadcaster"] - WebhookHandler["ClickUp Webhook Engine (HMAC Verification)"] - AuditEngine["Compliance Audit Log (NDJSON Tail Engine)"] - end - - subgraph External["External Services"] - GoogleAuth["Google Identity Platform (zen-flow-7173d)"] - FirestoreAdmin["Google Cloud Firestore (Admin SDK)"] - ClickUpAPI["ClickUp API v2 REST & Webhooks"] - LocalStorage["Local Store (data/store.json & data/audit.ndjson)"] - end - - Client -->|Google ID Token Exchange| SecMiddleware - SecMiddleware -->|Verify Token| GoogleAuth - SecMiddleware -->|Set Session Cookie| AuthCookie - Client <-->|REST API Requests| SecMiddleware - SecMiddleware --> RBAC --> Store - Store --> SSEHub -->|Live Updates| SSE --> Client - - Store <-->|Primary Persistence| FirestoreAdmin - Store <-->|Local Fallback Volume| LocalStorage - WebhookHandler <-->|Two-Way Sync| ClickUpAPI - AuditEngine -->|Append Log Entry| FirestoreAdmin - AuditEngine -->|Local NDJSON Stream| LocalStorage -``` - ---- - -## πŸ›  Technology Stack - -| Layer | Technologies | -| :--- | :--- | -| **Frontend Framework** | [React 19](https://react.dev/) + [TypeScript](https://www.typescriptlang.org/) | -| **Build & Tooling** | [Vite 6](https://vitejs.dev/) + [esbuild](https://esbuild.github.io/) | -| **Styling & Animation** | [Tailwind CSS v4](https://tailwindcss.com/) + [Motion (Framer Motion v12)](https://motion.dev/) | -| **Icons & UI** | [Lucide React](https://lucide.dev/) | -| **Backend Server** | [Express 4](https://expressjs.com/) on [Node.js >= 22](https://nodejs.org/) (ES Modules & `tsx`) | -| **Database & Cloud Storage** | [Firebase Admin SDK](https://firebase.google.com/docs/admin/setup) + [@google-cloud/firestore](https://cloud.google.com/firestore) | -| **Authentication** | Google Identity Platform (`zen-flow-7173d`) via Firebase Auth + HttpOnly Session Cookies | -| **External Integration** | [ClickUp API v2](https://clickup.com/api) with HMAC SHA-256 Webhook Verification | -| **Testing** | Node.js Test Runner (`node --test`), `@firebase/rules-unit-testing`, Firebase Emulators | -| **Deployment** | Docker (Multi-stage build), Railway, Nixpacks, Procfile | - ---- - -## πŸ“‚ Directory Structure - -```text -c:/ZenFlow/ -β”œβ”€β”€ .github/workflows/ # CI/CD workflows (Node 22 / Java 21) -β”œβ”€β”€ data/ # Local volume data (store.json, audit.ndjson, webhooks.json) -β”œβ”€β”€ docs/ -β”‚ └── READINESS.md # Enterprise readiness & deployment verification guide -β”œβ”€β”€ public/ # Static assets & favicons -β”œβ”€β”€ server/ -β”‚ β”œβ”€β”€ resources.ts # Audit tail reader & bounded SSE transport -β”‚ β”œβ”€β”€ security.ts # Auth middleware, cookie issuance & payload redaction -β”‚ └── webhooks.ts # ClickUp webhook HMAC registry & signature validator -β”œβ”€β”€ src/ -β”‚ β”œβ”€β”€ components/ # Reusable UI components & modals (Swimlanes, FreePool, etc.) -β”‚ β”œβ”€β”€ context/ # DashboardContext (state management, ClickUp sync, offline queue) -β”‚ β”œβ”€β”€ lib/ # Firebase client initialization & session management -β”‚ β”œβ”€β”€ utils/ # Workload calculations, date formatting & audit helpers -β”‚ β”œβ”€β”€ App.tsx # Main application layout & swimlane orchestrator -β”‚ β”œβ”€β”€ index.css # Design tokens & Tailwind theme definitions -β”‚ β”œβ”€β”€ main.tsx # React DOM entry point -β”‚ └── types.ts # TypeScript interfaces (User, Task, AuditLog, ClickUp) -β”œβ”€β”€ tests/ -β”‚ β”œβ”€β”€ benchmark-audit.ts # Synthetic benchmark for asynchronous audit log reading -β”‚ β”œβ”€β”€ client-session.test.ts # Client session migration & token race tests -β”‚ β”œβ”€β”€ firestore.emulator.ts # Firestore Security Rules unit test suite -β”‚ β”œβ”€β”€ fixtures.ts # Mock server, store & identity fixtures -β”‚ β”œβ”€β”€ resources.test.ts # SSE backpressure & audit tail unit tests -β”‚ β”œβ”€β”€ security.test.ts # Comprehensive RBAC & webhook verification tests -β”‚ └── smoke-production.ts # Compiled server artifact production smoke test -β”œβ”€β”€ Dockerfile # Multi-stage container definition -β”œβ”€β”€ firestore.rules # Server-owned Firestore security rules -β”œβ”€β”€ package.json # Project dependencies and script declarations -β”œβ”€β”€ server.ts # Central Express application and ClickUp sync engine -└── vite.config.ts # Vite frontend configuration -``` - ---- - -## πŸš€ Getting Started - -### Prerequisites - -- **Node.js**: `v22.0.0` or higher -- **npm**: `v10.0.0` or higher -- **Java**: JRE 21+ *(optional, required only for running local Firestore Emulator tests)* -- **Google Cloud / Firebase Project**: Dedicated Firebase project for Firestore storage (Google Identity uses `zen-flow-7173d`) -- **ClickUp Account**: Personal or Workspace API token with admin/member access for two-way synchronization - -### Installation - -1. **Clone the repository**: - - ```sh - git clone https://github.com/schultz911/ZenFlow.git - cd ZenFlow - ``` - -2. **Install dependencies**: - - ```sh - npm ci - ``` - -### Environment Configuration - -Create a `.env` file in the project root: - -```sh -cp .env.example .env -``` - -Populate the configuration values: - -```env -# Application URL where the app is hosted (e.g. http://localhost:3000) -APP_URL=http://localhost:3000 - -# Server Port and Node Environment -PORT=3000 -NODE_ENV=development - -# Firebase Service Account Key (JSON string, base64-encoded string, or path to serviceAccountKey.json) -FIREBASE_SERVICE_ACCOUNT_KEY= - -# Optional local persistent storage directory (defaults to ./data) -ZENFLOW_DATA_DIR=./data -``` - -### Running the Development Server - -Start the full-stack server (serves the Vite frontend and the Express backend concurrently): +Use Node.js 22 or later. Set `FIREBASE_SERVICE_ACCOUNT_KEY` to the existing storage project's service-account JSON, base64 JSON, or a private file path. Set `FIREBASE_PROJECT_ID` and `FIREBASE_DATABASE_ID` when needed. Credentials belong in Railway variables, never the client bundle or Git. ```sh +npm ci npm run dev ``` -Visit [http://localhost:3000](http://localhost:3000) in your browser. - ---- - -## πŸ“œ Available Scripts - -| Command | Action | -| :--- | :--- | -| `npm run dev` | Starts the server in development mode using `tsx server.ts`. | -| `npm run build` | Compiles the Vite frontend to `dist/` and bundles `server.ts` into `dist/server.cjs` via `esbuild`. | -| `npm run start` | Runs the compiled production server (`node dist/server.cjs`). | -| `npm run lint` | Runs TypeScript compiler checks without emitting files (`tsc --noEmit`). | -| `npm test` | Runs the complete Node.js test suite across security, sessions, and resources. | -| `npm run test:rules` | Executes Firestore Security Rules unit tests against the local Firebase Emulator. | -| `npm run clean` | Cleans build artifacts (`dist/` and temporary server outputs). | - ---- - -## πŸ” Security & Access Control - -ZenFlow adopts a **Zero-Trust, Server-Owned** security posture: - -```text -+--------------------------------------------------------------------------+ -| RBAC Role Hierarchy | -+--------------------------------------------------------------------------+ -| Superadmin (kiran.s@zensciences.com) | -| β”œβ”€β”€ Full system administration, member provisioning & CD assignment | -| β”œβ”€β”€ Firebase credential management & database status inspection | -| └── ClickUp Webhook HMAC registration & compliance audit downloads | -| | -| Creative Director (CD) | -| β”œβ”€β”€ Board oversight for assigned team (Content / Design) | -| └── Task review, workload balancing & team member task management | -| | -| Team Member | -| β”œβ”€β”€ Universal cross-board subtask delegation to any peer | -| β”œβ”€β”€ Personal task creation, status updates & billable adjustments | -| └── Personal ClickUp token connection management (server-redacted) | -+--------------------------------------------------------------------------+ -``` - -### Key Security Safeguards - -1. **HttpOnly Cookie Sessions**: Verified Google ID tokens are exchanged for an `HttpOnly`, `SameSite=Strict` session cookie scoped strictly to `/api`. Tokens are never exposed in URLs or client-accessible web storage. -2. **CSRF & Same-Origin Mutation Protection**: All state-modifying requests require custom headers validated against the application origin. -3. **Firestore Security Rules**: Direct client reads and writes are denied unconditionally (`allow read, write: if false;`). Data is manipulated exclusively by the backend via the Firebase Admin SDK through IAM credentials. -4. **ClickUp Secret Isolation**: Member API tokens are stored securely on the backend and are stripped from all broadcast and response payloads (`clickupConnected` boolean allowlist). - ---- - -## πŸ”„ ClickUp Two-Way Synchronization - -ZenFlow acts as the **authoritative single source of truth** when coordinating with ClickUp: - -```text - ZenFlow Mutation ──────► POST/PUT ClickUp API v2 ──────► ClickUp Task Updated - β–² β”‚ - β”‚ β–Ό -ZenFlow Re-Asserts SSoT ◄─── HMAC Verified Webhook ◄──────── ClickUp Webhook - (if diverged) (taskStatusUpdated, etc.) -``` - -1. **Task Creation & Updates**: Modifying a task in ZenFlow immediately pushes updates (status, assignees, due dates, custom field mappings) to ClickUp. -2. **Assignee Replacement**: ZenFlow computes exact assignee diffs (`{ add: [...], rem: [...] }`) to prevent task reassignment bouncebacks. -3. **Webhook Verification**: All incoming webhooks sent to `/api/clickup/webhook` are cryptographically verified against the private HMAC secret before processing. -4. **Self-Healing Subtask Placement**: If a subtask creation receives ClickUp code `ITEM_137` ("Parent not child of list"), ZenFlow queries the parent task dynamically, resolves the current list ID, and retries placement transparently. - ---- +Google sign-in remains tied to `zen-flow-7173d`. Workspace membership and permissions are checked server-side. Direct browser Firestore reads and writes remain denied. There is no local-file database fallback: startup fails if Firestore cannot be initialized or read, and failed writes return errors. -## πŸ’Ύ Data Persistence & Storage Modes +## Workflows -ZenFlow operates under two coordinated persistence tiers: +- Content/design boards, workload scoring, WIP limits, deadlines and free-pool visibility. +- Pipeline and retainer tasks without mandatory deadlines. +- Independent cross-board subtasks for all registered members. +- Billable timers, task activity history and cloud audit exports. +- Member-owned offline mutation queues with snapshot reconciliation. Queued changes are visibly offline until acknowledged by the backend. -1. **Cloud Persistence (Primary)**: - - Powered by Firebase Admin and `@google-cloud/firestore`. - - Collections: `users`, `tasks`, `compliance_audit_logs`, and private `server_secrets/clickup_webhooks`. - - Active whenever `FIREBASE_SERVICE_ACCOUNT_KEY` is supplied in the environment or uploaded by Superadmin. -2. **Local Volume Fallback**: - - Persisted as structured JSON in `data/store.json` and append-only NDJSON in `data/audit.ndjson`. - - Guaranteed atomic writes using temporary swap files (`.tmp`) to eliminate corruption during sudden process restarts. - ---- - -## πŸ§ͺ Testing & Quality Assurance - -The test suite exercises real extracted handlers behind live authorization middleware without accessing production services: +## Verify ```sh -# 1. Run all unit and security integration tests npm test - -# 2. Run Firestore Security Rules emulator tests (requires Java 21) -npm run test:rules - -# 3. Perform static analysis and TypeScript verification npm run lint npx tsc --noEmit --noUnusedLocals --noUnusedParameters - -# 4. Run the synthetic audit tail performance benchmark -node --expose-gc --import tsx tests/benchmark-audit.ts -``` - ---- - -## 🚒 Production Deployment - -### Docker Deployment - -ZenFlow includes a multi-stage `Dockerfile` optimized for minimal attack surface and resource efficiency: - -```sh -# Build the production container image -docker build -t zenflow:latest . - -# Run container with persistent local storage and environment credentials -docker run -d \ - -p 3000:3000 \ - -e PORT=3000 \ - -e NODE_ENV=production \ - -e FIREBASE_SERVICE_ACCOUNT_KEY="" \ - -v zenflow_data:/app/data \ - --name zenflow zenflow:latest +npm run build +npm run test:rules +npm run test:persistence ``` -### Cloud Platforms (Railway / Nixpacks / Cloud Run) - -ZenFlow provides pre-configured [`railway.json`](railway.json), [`nixpacks.toml`](nixpacks.toml), and [`Procfile`](Procfile) manifests for deployment. Ensure the following steps are performed: - -1. Provide `FIREBASE_SERVICE_ACCOUNT_KEY` in platform environment variables. -2. Mount a persistent volume to `/app/data` (or specify `ZENFLOW_DATA_DIR`). -3. Deploy frontend and backend together. -4. Deploy Firestore security rules via `npx firebase deploy --only firestore:rules --project `. -5. Access the **Connections & Compliance** modal as Superadmin to register the ClickUp HMAC webhook. - -For a detailed deployment runbook, refer to [`docs/READINESS.md`](docs/READINESS.md). - ---- - -## πŸ“œ Audit & Compliance Trail - -All critical system actions (task creations, edits, status transitions, user updates, credential modifications, and webhook deliveries) are recorded to an append-only compliance log: - -- **Streaming NDJSON**: Stored in `data/audit.ndjson` and mirrored to Firestore `compliance_audit_logs`. -- **Tail-Optimized Reads**: Backend reverse-reads recent log entries in 64 KiB blocks, providing fast initial log hydration without loading multi-megabyte audit histories into memory. -- **Exportable Compliance Logs**: Superadmins can stream and download complete compliance records via `/api/audit/download`. +Emulator tests require Java 21 or later. CI uses Node 22 and Java 21 on Linux. Tests cover actual authorization/workflow handlers, SSE, offline replay, database failure rollback, Firestore atomicity, migration, compiled-server CRUD and restart recovery. See [deployment and persistence details](docs/READINESS.md). ---- +## Railway -## πŸ“„ License & Attribution +The existing `web` service builds this repository and starts `node dist/server.cjs`. `/api/health` probes Firestore and returns 503 when unavailable. Deploy the matching client and server together. Do not include `data/`, service-account files or `.env` files in the container. -Designed and maintained for ZenSciences. All rights reserved. +The October 2026 transition removes ClickUp sync, API proxies, webhooks, tokens, mapping controls, destination selectors and cloud-link fields. Retired `/api/clickup/*` URLs return 410. Existing native records retain their IDs and ownership; pre-transition metadata is backed up privately without tokens. No tasks in the external service are modified or deleted. diff --git a/data/compliance-audit.jsonl b/data/compliance-audit.jsonl deleted file mode 100644 index d544374..0000000 --- a/data/compliance-audit.jsonl +++ /dev/null @@ -1,28 +0,0 @@ -{"id":"audit-1791180608236-fb6ep1","timestamp":"2026-10-05T06:10:08.236Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180608234","targetType":"user","details":"User account created: Mistyped User (wrong.typo@zensciences.com) - Role: content","metadata":{"isCreativeDirector":false,"role":"content"}} -{"id":"audit-1791180608350-uvdr8v","timestamp":"2026-10-05T06:10:08.350Z","category":"user","action":"user_email_corrected","actor":{"ip":"127.0.0.1","email":"kiran.s@zensciences.com"},"targetId":"user-1791180608234","targetType":"user","details":"Superadmin corrected email for \"Mistyped User\" from wrong.typo@zensciences.com to corrected.clean@zensciences.com. (Remapped orphan tasks: 0)","metadata":{"oldEmail":"wrong.typo@zensciences.com","newEmail":"corrected.clean@zensciences.com","remappedTasksCount":0}} -{"id":"audit-1791180608350-k01sqr","timestamp":"2026-10-05T06:10:08.350Z","category":"user","action":"user_privilege_modified","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180608234","targetType":"user","details":"User profile / privileges modified for \"Corrected User\"","metadata":{"role":"content","isCreativeDirector":false}} -{"id":"audit-1791180676671-e1linz","timestamp":"2026-10-05T06:11:16.671Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180676668","targetType":"user","details":"User account created: Mistyped User (wrong.typo@zensciences.com) - Role: content","metadata":{"isCreativeDirector":false,"role":"content"}} -{"id":"audit-1791180676691-lnpuuo","timestamp":"2026-10-05T06:11:16.691Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180676690-inc7","targetType":"task","details":"Task \"Task 1 for Wrong User\" created for user user-1791180676668","metadata":{"status":"todo","cognitiveLoad":"medium","dueDate":"2026-10-15"}} -{"id":"audit-1791180676733-pubgrx","timestamp":"2026-10-05T06:11:16.733Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180676732-e4d3","targetType":"task","details":"Task \"Task 2 for Wrong User\" created for user user-1791180676668","metadata":{"status":"in_progress","cognitiveLoad":"high","dueDate":"2026-10-16"}} -{"id":"audit-1791180678694-ssdz0g","timestamp":"2026-10-05T06:11:18.694Z","category":"user","action":"user_merged_and_tasks_remapped","actor":{"ip":"127.0.0.1","email":"kiran.s@zensciences.com"},"targetId":"user-1791180608234","targetType":"user","details":"Superadmin corrected email from \"wrong.typo@zensciences.com\" to \"corrected.clean@zensciences.com\". Merged profile into \"Corrected User\" and remapped 2 task(s).","metadata":{"fromUserId":"user-1791180676668","toUserId":"user-1791180608234","fromEmail":"wrong.typo@zensciences.com","toEmail":"corrected.clean@zensciences.com","remappedTasksCount":2}} -{"id":"audit-1791180748205-wjut7o","timestamp":"2026-10-05T06:12:28.205Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180748204","targetType":"user","details":"User account created: Mistyped User (wrong.typo@zensciences.com) - Role: content","metadata":{"isCreativeDirector":false,"role":"content"}} -{"id":"audit-1791180748214-4h2i10","timestamp":"2026-10-05T06:12:28.214Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180748214-7seo","targetType":"task","details":"Task \"Task 1 for Wrong User\" created for user user-1791180748204","metadata":{"status":"todo","cognitiveLoad":"medium","dueDate":"2026-10-15"}} -{"id":"audit-1791180748229-t2omk0","timestamp":"2026-10-05T06:12:28.229Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180748229-f9kc","targetType":"task","details":"Task \"Task 2 for Wrong User\" created for user user-1791180748204","metadata":{"status":"in_progress","cognitiveLoad":"high","dueDate":"2026-10-16"}} -{"id":"audit-1791180749765-i73bs5","timestamp":"2026-10-05T06:12:29.765Z","category":"user","action":"user_merged_and_tasks_remapped","actor":{"ip":"127.0.0.1","email":"kiran.s@zensciences.com"},"targetId":"user-1791180608234","targetType":"user","details":"Superadmin corrected email from \"wrong.typo@zensciences.com\" to \"corrected.clean@zensciences.com\". Merged profile into \"Corrected User\" and remapped 2 task(s).","metadata":{"fromUserId":"user-1791180748204","toUserId":"user-1791180608234","fromEmail":"wrong.typo@zensciences.com","toEmail":"corrected.clean@zensciences.com","remappedTasksCount":2}} -{"id":"audit-1791180791732-ci7uds","timestamp":"2026-10-05T06:13:11.732Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180791731","targetType":"user","details":"User account created: Mistyped User (wrong.typo.1791180791650@zensciences.com) - Role: content","metadata":{"isCreativeDirector":false,"role":"content"}} -{"id":"audit-1791180791738-yk702s","timestamp":"2026-10-05T06:13:11.738Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180791738-tg5a","targetType":"task","details":"Task \"Task 1 for Wrong User\" created for user user-1791180791731","metadata":{"status":"todo","cognitiveLoad":"medium","dueDate":"2026-10-15"}} -{"id":"audit-1791180791754-sha77p","timestamp":"2026-10-05T06:13:11.754Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180791754-ckkr","targetType":"task","details":"Task \"Task 2 for Wrong User\" created for user user-1791180791731","metadata":{"status":"in_progress","cognitiveLoad":"high","dueDate":"2026-10-16"}} -{"id":"audit-1791180791785-66jice","timestamp":"2026-10-05T06:13:11.785Z","category":"user","action":"user_email_corrected","actor":{"ip":"127.0.0.1","email":"kiran.s@zensciences.com"},"targetId":"user-1791180791731","targetType":"user","details":"Superadmin corrected email for \"Mistyped User\" from wrong.typo.1791180791650@zensciences.com to corrected.clean.1791180791650@zensciences.com. (Remapped orphan tasks: 0)","metadata":{"oldEmail":"wrong.typo.1791180791650@zensciences.com","newEmail":"corrected.clean.1791180791650@zensciences.com","remappedTasksCount":0}} -{"id":"audit-1791180791785-63dl4y","timestamp":"2026-10-05T06:13:11.785Z","category":"user","action":"user_privilege_modified","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180791731","targetType":"user","details":"User profile / privileges modified for \"Corrected User\"","metadata":{"role":"content","isCreativeDirector":false}} -{"id":"audit-1791180791817-apa3qh","timestamp":"2026-10-05T06:13:11.817Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180791816","targetType":"user","details":"User account created: Real Employee (real.employee.1791180791650@zensciences.com) - Role: design","metadata":{"isCreativeDirector":false,"role":"design"}} -{"id":"audit-1791180791832-6fsxn4","timestamp":"2026-10-05T06:13:11.832Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180791832","targetType":"user","details":"User account created: Typo Employee (reel.employee.1791180791650@zensciences.com) - Role: design","metadata":{"isCreativeDirector":false,"role":"design"}} -{"id":"audit-1791180791848-shzndj","timestamp":"2026-10-05T06:13:11.848Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180791848-fi0q","targetType":"task","details":"Task \"Task 3 for Typo Account\" created for user user-1791180791832","metadata":{"status":"todo","cognitiveLoad":"low","dueDate":"2026-10-20"}} -{"id":"audit-1791180791864-ymn9l2","timestamp":"2026-10-05T06:13:11.864Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180791864-xope","targetType":"task","details":"Task \"Task 4 for Typo Account\" created for user user-1791180791832","metadata":{"status":"pipeline","cognitiveLoad":"high"}} -{"id":"audit-1791180795351-ti0n5v","timestamp":"2026-10-05T06:13:15.351Z","category":"user","action":"user_merged_and_tasks_remapped","actor":{"ip":"127.0.0.1","email":"kiran.s@zensciences.com"},"targetId":"user-1791180791816","targetType":"user","details":"Superadmin corrected email from \"reel.employee.1791180791650@zensciences.com\" to \"real.employee.1791180791650@zensciences.com\". Merged profile into \"Real Employee\" and remapped 2 task(s).","metadata":{"fromUserId":"user-1791180791832","toUserId":"user-1791180791816","fromEmail":"reel.employee.1791180791650@zensciences.com","toEmail":"real.employee.1791180791650@zensciences.com","remappedTasksCount":2}} -{"id":"audit-1791180795436-v9i32d","timestamp":"2026-10-05T06:13:15.436Z","category":"user","action":"user_created","actor":{"ip":"127.0.0.1"},"targetId":"user-1791180795436","targetType":"user","details":"User account created: Donor User (donor.1791180791650@zensciences.com) - Role: content","metadata":{"isCreativeDirector":false,"role":"content"}} -{"id":"audit-1791180795452-bxu0qq","timestamp":"2026-10-05T06:13:15.452Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-1791180795452-7sha","targetType":"task","details":"Task \"Task 5 to be transferred\" created for user user-1791180795436","metadata":{"status":"in_review","cognitiveLoad":"medium","dueDate":"2026-10-25"}} -{"id":"audit-1791180796302-9ircmc","timestamp":"2026-10-05T06:13:16.302Z","category":"user","action":"tasks_manually_remapped","actor":{"ip":"127.0.0.1","email":"kiran.s@zensciences.com"},"targetId":"user-1791180791816","targetType":"user","details":"Superadmin remapped 1 task(s) from Donor User (donor.1791180791650@zensciences.com) to Real Employee (real.employee.1791180791650@zensciences.com)","metadata":{"fromUserId":"user-1791180795436","fromEmail":"donor.1791180791650@zensciences.com","toUserId":"user-1791180791816","toEmail":"real.employee.1791180791650@zensciences.com","remappedCount":1,"deletedSourceUser":true}} -{"id":"audit-1791287451318-af96pz","timestamp":"2026-10-06T11:50:51.318Z","category":"task","action":"task_created","actor":{"ip":"127.0.0.1"},"targetId":"task-test-retainer","targetType":"task","details":"Task \"Acme Retainer Q4\" created for user user-superadmin-kiran","metadata":{"status":"retainer","cognitiveLoad":"medium"}} -{"id":"audit-1791287460914-iismcs","timestamp":"2026-10-06T11:51:00.914Z","category":"task","action":"task_subtask_delegated_to_board","actor":{"ip":"127.0.0.1","id":"user-superadmin-kiran","name":"Kiran S","email":"kiran.s@zensciences.com"},"targetId":"task-1791287460913-9olx","targetType":"task","from":"user-superadmin-kiran","to":"user-superadmin-kiran","details":"Subtask of \"Acme Retainer Q4\" created on Kiran S's board by Kiran S","metadata":{"sourceTaskId":"task-test-retainer","newTaskId":"task-1791287460913-9olx","targetBoardId":"user-superadmin-kiran"}} -{"id":"audit-1791287475595-n8v8zl","timestamp":"2026-10-06T11:51:15.595Z","category":"task","action":"task_deleted","actor":{"ip":"127.0.0.1"},"targetId":"task-test-retainer","targetType":"task","details":"Task \"Acme Retainer Q4\" (ID: task-test-retainer) deleted","metadata":{"userId":"user-superadmin-kiran"}} -{"id":"audit-1791287475874-5ca92g","timestamp":"2026-10-06T11:51:15.874Z","category":"task","action":"task_deleted","actor":{"ip":"127.0.0.1"},"targetId":"task-1791287460913-9olx","targetType":"task","details":"Task \"Deliverable A for Acme\" (ID: task-1791287460913-9olx) deleted","metadata":{"userId":"user-superadmin-kiran"}} diff --git a/data/store.json b/data/store.json deleted file mode 100644 index 8c5b739..0000000 --- a/data/store.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "users": [ - { - "id": "user-superadmin-kiran", - "name": "Kiran S", - "email": "kiran.s@zensciences.com", - "role": "content", - "avatarColor": "from-blue-600 to-indigo-600", - "isCreativeDirector": true, - "createdAt": "2026-10-03T19:56:18.738Z" - } - ], - "tasks": [] -} \ No newline at end of file diff --git a/docs/READINESS.md b/docs/READINESS.md index aed9bb6..4d30f10 100644 --- a/docs/READINESS.md +++ b/docs/READINESS.md @@ -1,45 +1,35 @@ -# Readiness hardening deployment +# Firestore-only workspace deployment -The 25 October 2026 implementation closes API identity/permission bypasses, removes shared ClickUp credentials, restricts direct Firestore access, verifies ClickUp webhook signatures, bounds SSE output, and reads only the recent audit-log tail. +## Storage and migration -## Deploy in this order +Firestore is authoritative. The backend reads a fresh database snapshot for each API operation, applies the existing authorized workflow, then commits changed documents and create-only audit records atomically before returning success or broadcasting SSE. In-memory state is a request working copy. Local JSON and NDJSON files are no longer storage sources and are excluded from images. -1. Configure `FIREBASE_SERVICE_ACCOUNT_KEY` for the intended Firestore project. The backend requires Firestore Admin/IAM access to `users`, `tasks`, `compliance_audit_logs`, and the private `server_secrets/clickup_webhooks` document. Identity verification always uses the Google login project `zen-flow-7173d`, regardless of the storage project. An uploaded database credential cannot change identity trust. -2. Back up the existing store/audit data. If relying on local persistence, mount a persistent volume and set `ZENFLOW_DATA_DIR` to that directory. Local mode remains usable but does not provide cloud persistence; the connection status reports this explicitly. `serviceAccountKey.json` uploads remain supported for Superadmin only; prefer the environment credential for redeployment persistence. -3. Deploy the client and server together. Check Google sign-in and `/api/firestore/status` with a registered account; confirm `mode: admin`, `connected: true`, and actual successful writes before changing live database rules. Do not treat successful compilation or SDK initialization alone as proof of database access. -4. Deploy the reviewed rules using `npx firebase deploy --only firestore:rules --project YOUR_STORAGE_PROJECT`. All direct client reads/writes, including authenticated ones, are denied. Only the authorized backend serves app data. The Admin SDK bypasses these rules through IAM. These rules are committed source changes; pushing GitHub alone does not deploy them. -5. Re-register the ClickUp webhook from Connections & Compliance as Superadmin. Previous registrations without a recoverable signing secret are intentionally rejected. New secrets are persisted privately in Firestore and in the local data directory, never returned to browsers. Registration and deletion are restricted to Superadmin. -6. Check task creation/edit/reorder, universal cross-board subtasks, pipeline/retainer behavior, member management, and a correctly signed webhook. Confirm reconnection recovers changes/deletions. Rotate personal ClickUp tokens if the prior deployment exposed them. +A revision document at `workspace/state` prevents overlapping deployments from silently overwriting one another. Conflicting writes return 503 for retry. One operation is bounded to 500 Firestore writes including audit records and revision; oversized member remaps/deletions fail atomically. This design favors correctness for the current workspace; full-snapshot reads per operation have a Firestore read cost that grows with workspace size. -## Authentication and permissions +On the first startup, existing `users` and `tasks` documents are copied to private `workspace_backups/native-v1/{users|tasks}/{id}` subcollections with saved tokens excluded. Retired integration fields are removed using document update-time preconditions. IDs, task content, parent links, statuses, dates, timer totals and activity history are retained. The migration marker is `workspace/native-v1`. The private webhook registry is removed. The external service's tasks are untouched; any old external webhook registration receives 410 from ZenFlow. -- Google identities must be signed for `zen-flow-7173d`, verified, unexpired, from the Google provider, and already registered in ZenFlow. -- A verified ID token is exchanged for an HttpOnly, SameSite=Strict cookie scoped to `/api`. HTTPS requests receive Secure cookies. The cookie lasts no longer than the ID token. Every request verifies its identity and current membership; caller-supplied role/email/ID assertions cannot authorize an action. -- Cookie mutations require a same-origin non-simple request header. Bearer-token API clients are also supported. SSE and downloads use the HttpOnly cookie, keeping tokens out of URLs. -- Regular members edit their own tasks and connection preferences. CDs can edit their assigned team's tasks/members. Only Superadmin changes email/CD privileges, remaps accounts, changes Firebase credentials, or manages webhook registration. All registered members retain cross-board subtask delegation and workspace/free-pool visibility. -- Public user payloads use an allowlist plus a `clickupConnected` boolean. Personal ClickUp keys remain server-side. The connection form accepts a new key but never prefills or returns the stored one. -- Browser migration removes old stored tokens. Offline queues are scoped to the member who created them; previous queued work is migrated under the original cached member ID. A reconnect snapshot overlays pending changes before FIFO replay. Auth failures retain queued work. +The database is never repopulated from a local seed or merged with stale deleted records. A new database only bootstraps the owner account. Uploaded credentials and runtime database switching are removed; credentials are deployment configuration. -## Verification +## Deploy -Run Node 22 and Java 21: +1. Confirm the existing storage project and database. Production currently targets `zen-flow-7173d` / `(default)`, Firestore Standard, Mumbai (`asia-south1`). +2. Configure `FIREBASE_SERVICE_ACCOUNT_KEY`, `FIREBASE_PROJECT_ID` and `FIREBASE_DATABASE_ID` on Railway. Admin IAM must allow `users`, `tasks`, `compliance_audit_logs`, `workspace`, `workspace_backups` and removal of the retired `server_secrets/clickup_webhooks` document. Startup requires successful database reads and migration writes. +3. Deploy the same tested client/server revision to the existing Railway service. Use `/api/health` as the deployment healthcheck. +4. Inspect the migration counts, private backup, deployed health and authenticated Firestore status. Compare native record IDs before/after deployment. +5. Verify Google login, member management, tasks, delegation, timers, audit export and SSE reconnect. Anonymous API reads/writes and caller-header spoofing must remain denied. Retired integration routes return 410 and make no external requests. -```sh -npm ci -npm test -npm run test:rules -npm run lint -npx tsc --noEmit --noUnusedLocals --noUnusedParameters -npm run build -node --expose-gc --import tsx tests/benchmark-audit.ts -``` +## Security -The ordinary test suite executes actual extracted server handlers behind the real authorization middleware with fixture identity/persistence, plus actual client session logic, real HTTP SSE tests, offline reconciliation, and audit-tail edge cases. It never accesses production credentials or services. The emulator suite compiles the real rules and checks anonymous/authenticated/claimed-admin operations and server-owned seed writes against the emulator rules engine. CI repeats verification on Linux with Node 22 / Java 21. The initial GitHub run passed all 25 tests, all 63 emulator-denial checks, type checks, build and production smoke checks. Local Windows emulator HTTP/2 transport failed; its failures were not counted as passes. The final head also includes the large-workspace handshake regression test. +Google identity verification is fixed to `zen-flow-7173d`, independently of storage credentials. A verified identity must be a registered member. API/SSE sessions use HttpOnly same-origin cookies; mutations require the same-origin non-simple request header. Bearer API clients are supported. Superadmin, Creative Director and owner permission boundaries remain enforced server-side. All registered members retain independent cross-board delegation and workspace visibility. -Measured on Node 22.23.4: a 45,889,000-byte / 100,000-record synthetic log read fell from 40.89 ms to 2.17 ms median over five runs (94.7% less time), preserving the last 100 entries. This is a local synthetic benchmark, not a production SLA. Stalled SSE output is bounded to 256 KiB plus one large event; healthy connections can receive a snapshot larger than the bound. Audit history is not deleted or rotated. +The existing live Firestore rules deny all direct client access, including authenticated and claimed-admin clients. IAM-authenticated Admin access bypasses these rules and is constrained by backend authorization. Backups, revisions and audits inherit the same default deny policy. No rule relaxation is needed for this release. -I've set up prototype Security Rules to keep the data in Firestore safe. They are designed to be secure for server-owned persistence because all direct client access is denied and backend access is checked independently. However, you should review and verify them before broadly sharing your app. If you'd like, I can help you harden these rules. +## Tests -## Rollback +`npm test` runs workflow/permission/SSE/offline and database failure tests. `npm run test:rules` verifies anonymous, authenticated and claimed-admin access remains denied. `npm run test:persistence` runs Firestore/Auth emulators, tests migration/atomic commits/conflicts/deletes, then starts the compiled production server for authenticated CRUD, delegation, audit export and restart recovery. Credentials and identities are synthetic; these tests never mutate production. -Do not restore public Firestore rules or trusted caller headers. If a functional regression occurs, retain authenticated access and use the prior data backup with a compatible secured server/client release. Webhook registration secrets must remain private during rollback. +Windows' older direct-gRPC rule harness can report HTTP/2 protocol errors; count those as failures. Linux CI uses Node 22 / Java 21. Persistence and compiled-server tests use the current SDK's emulator transport. A successful build alone is not evidence of authenticated production workflow behavior. + +## Recovery + +Retain authenticated APIs and deny-all client rules. The private metadata backup excludes saved personal tokens, so restoration cannot reconnect an external integration. Restore native records through Admin access after identifying the specific failed operation; do not re-enable a local JSON merge or broadly restore deleted records. Cloud audit history is create-only and exported from Firestore in bounded pages. diff --git a/firebase-blueprint.json b/firebase-blueprint.json index f31c032..6e09c3e 100644 --- a/firebase-blueprint.json +++ b/firebase-blueprint.json @@ -20,7 +20,10 @@ }, "role": { "type": "string", - "enum": ["content", "design"], + "enum": [ + "content", + "design" + ], "description": "Team swimlane role" }, "avatarColor": { @@ -39,29 +42,15 @@ "creativeDirectorId": { "type": "string", "description": "ID of the Creative Director this user is mapped to" - }, - "clickupApiKey": { - "type": "string", - "description": "Personal ClickUp API Token" - }, - "selectedClickupSpaceId": { - "type": "string", - "description": "Active ClickUp space ID" - }, - "selectedClickupSpaceName": { - "type": "string", - "description": "Active ClickUp space name" - }, - "clickupUserId": { - "type": "string", - "description": "Mapped ClickUp Member ID" - }, - "clickupUsername": { - "type": "string", - "description": "Mapped ClickUp Username" } }, - "required": ["id", "name", "email", "role", "createdAt"] + "required": [ + "id", + "name", + "email", + "role", + "createdAt" + ] }, "Task": { "title": "Task", @@ -90,12 +79,24 @@ }, "cognitiveLoad": { "type": "string", - "enum": ["low", "medium", "high"], + "enum": [ + "low", + "medium", + "high" + ], "description": "Cognitive workload level" }, "status": { "type": "string", - "enum": ["pipeline", "retainer", "todo", "in_progress", "in_review", "done", "archived"], + "enum": [ + "pipeline", + "retainer", + "todo", + "in_progress", + "in_review", + "done", + "archived" + ], "description": "Current status in the workflow" }, "order": { @@ -120,46 +121,6 @@ "type": "array", "description": "Audit trail of task lifecycle state transitions and assignments" }, - "clickupTaskId": { - "type": "string", - "description": "Associated ClickUp task ID" - }, - "clickupFolderId": { - "type": "string", - "description": "Associated ClickUp folder ID" - }, - "clickupFolderName": { - "type": "string", - "description": "Associated ClickUp folder name" - }, - "clickupListId": { - "type": "string", - "description": "Associated ClickUp list ID" - }, - "clickupListName": { - "type": "string", - "description": "Associated ClickUp list name" - }, - "clickupSpaceId": { - "type": "string", - "description": "Associated ClickUp space ID" - }, - "clickupUrl": { - "type": "string", - "description": "URL to the task on ClickUp" - }, - "clickupTaskType": { - "type": "string", - "description": "Selected ClickUp Task Type name" - }, - "clickupTaskTypeId": { - "type": "string", - "description": "Selected ClickUp Task Type custom field option ID" - }, - "clickupTaskTypeFieldId": { - "type": "string", - "description": "ClickUp Task Type custom field ID" - }, "parentTaskId": { "type": "string", "description": "Source parent task ID if this task is a subtask" @@ -168,10 +129,6 @@ "type": "string", "description": "Source parent task title for display" }, - "clickupParentTaskId": { - "type": "string", - "description": "Associated parent ClickUp task ID" - }, "isSubtask": { "type": "boolean", "description": "Whether this task is a subtask of another task" @@ -187,7 +144,16 @@ "description": "Last updated timestamp ISO string" } }, - "required": ["id", "userId", "title", "cognitiveLoad", "status", "order", "createdAt", "updatedAt"] + "required": [ + "id", + "userId", + "title", + "cognitiveLoad", + "status", + "order", + "createdAt", + "updatedAt" + ] }, "AuditLogEntry": { "title": "AuditLogEntry", @@ -205,7 +171,13 @@ }, "category": { "type": "string", - "enum": ["task", "user", "security", "webhook", "system"], + "enum": [ + "task", + "user", + "security", + "webhook", + "system" + ], "description": "Event classification category" }, "action": { @@ -218,7 +190,12 @@ }, "targetType": { "type": "string", - "enum": ["task", "user", "workspace", "webhook"], + "enum": [ + "task", + "user", + "workspace", + "webhook" + ], "description": "Type of the target entity" }, "details": { @@ -234,7 +211,14 @@ "description": "Structured contextual metadata payload" } }, - "required": ["id", "timestamp", "category", "action", "targetId", "targetType"] + "required": [ + "id", + "timestamp", + "category", + "action", + "targetId", + "targetType" + ] } }, "firestore": { diff --git a/firebase.json b/firebase.json index 95bcbbc..f91c7f0 100644 --- a/firebase.json +++ b/firebase.json @@ -1,4 +1,19 @@ { - "firestore": { "rules": "firestore.rules" }, - "emulators": { "firestore": { "host": "127.0.0.1", "port": 8089 }, "ui": { "enabled": false }, "singleProjectMode": true } + "firestore": { + "rules": "firestore.rules" + }, + "emulators": { + "firestore": { + "host": "127.0.0.1", + "port": 8089 + }, + "ui": { + "enabled": false + }, + "singleProjectMode": true, + "auth": { + "host": "127.0.0.1", + "port": 9099 + } + } } diff --git a/package.json b/package.json index e016c06..e2a54ec 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "clean": "rm -rf dist server.js", "lint": "tsc --noEmit", "test": "node --import tsx --test tests/*.test.ts", - "test:rules": "firebase emulators:exec --only firestore --project demo-zenflow \"node --import tsx tests/firestore.emulator.ts\"" + "test:rules": "firebase emulators:exec --only firestore --project demo-zenflow \"node --import tsx tests/firestore.emulator.ts\"", + "test:persistence": "firebase emulators:exec --only firestore,auth --project demo-zenflow \"node --import tsx tests/workspace.emulator.ts && node --import tsx tests/smoke-production.ts\"" }, "dependencies": { "@google-cloud/firestore": "^9.1.0", diff --git a/server.ts b/server.ts index d9081ac..8da3df9 100644 --- a/server.ts +++ b/server.ts @@ -3,9 +3,10 @@ import express, { Request, Response } from 'express'; import path from 'path'; import fs from 'fs'; import compression from 'compression'; -import { createApiSecurity, redactPayload, SESSION_COOKIE, sameOriginMutation, validSignature } from './server/security'; -import { readAuditTail, writeSse } from './server/resources'; -import { WebhookRegistry } from './server/webhooks'; +import crypto from 'node:crypto'; +import { FirestoreWorkspace, workspaceMiddleware } from './server/workspace'; +import { createApiSecurity, redactPayload, SESSION_COOKIE, sameOriginMutation } from './server/security'; +import { writeSse } from './server/resources'; import { initializeApp as initializeAdminApp, getApps as getAdminApps } from 'firebase-admin/app'; import { getAuth as getAdminAuth } from 'firebase-admin/auth'; @@ -19,11 +20,7 @@ interface User { order?: number; isCreativeDirector?: boolean; creativeDirectorId?: string; - clickupApiKey?: string; - selectedClickupSpaceId?: string; - selectedClickupSpaceName?: string; - clickupUserId?: string; - clickupUsername?: string; + } type TaskStatus = 'pipeline' | 'retainer' | 'todo' | 'in_progress' | 'in_review' | 'done' | 'archived'; @@ -53,19 +50,10 @@ interface Task { createdAt: string; updatedAt: string; activityLog?: TaskActivity[]; - clickupTaskId?: string; - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - clickupUrl?: string; - clickupTaskType?: string; - clickupTaskTypeId?: string; - clickupTaskTypeFieldId?: string; + parentTaskId?: string; parentTaskTitle?: string; - clickupParentTaskId?: string; + isSubtask?: boolean; } @@ -76,16 +64,6 @@ interface AppStore { const SUPERADMIN_EMAIL = 'kiran.s@zensciences.com'; -const ZENFLOW_TO_CLICKUP_STATUS: Record = { - pipeline: 'open', - retainer: 'in progress', - todo: 'to do', - in_progress: 'in progress', - in_review: 'internal review', - done: 'client review', - archived: 'complete', -}; - export interface AuditLogEntry { id: string; timestamp: string; @@ -105,34 +83,13 @@ export interface AuditLogEntry { metadata?: Record; } -const COGNITIVE_LOAD_ESTIMATES_MS: Record = { - low: 12 * 3600 * 1000, - medium: 24 * 3600 * 1000, - high: 36 * 3600 * 1000, -}; - // Support Railway dynamic PORT or default to 3000 const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; -const DATA_DIR = process.env.ZENFLOW_DATA_DIR || path.join(process.cwd(), 'data'); -const DATA_FILE = path.join(DATA_DIR, 'store.json'); -const AUDIT_LOG_FILE = path.join(DATA_DIR, 'compliance-audit.jsonl'); -const webhookRegistry = new WebhookRegistry(path.join(DATA_DIR, '.clickup-webhooks.json')); // Identity trust is deliberately independent of the configurable Firestore credentials. const identityApp = getAdminApps().find(app => app.name === 'zenflow-identity') || initializeAdminApp({ projectId: 'zen-flow-7173d' }, 'zenflow-identity'); const verifyIdentity = (token: string) => getAdminAuth(identityApp).verifyIdToken(token); -const recentAuditLogs: AuditLogEntry[] = []; -const MAX_RECENT_AUDIT_LOGS = 100; - -// ClickUp Real-Time Webhook Listener State -let registeredWebhookId: string | null = null; -let activeWebhookEndpoint: string | null = null; -let webhookEventsCount = 0; -let lastWebhookEventAt: string | null = null; -let lastWebhookAction: string | null = null; - - // Auto-detect production mode if running compiled dist artifact or in container environments let currentFile = ''; try { @@ -156,101 +113,8 @@ const AVATAR_COLORS = [ 'from-cyan-500 to-blue-600', ]; -// O(1) Fast lookup sets for legacy template filters -const DUMMY_USER_IDS = new Set(['user-1', 'user-2', 'user-3', 'user-4']); -const DUMMY_TASK_IDS = new Set([ - 'task-101', 'task-102', 'task-103', 'task-104', - 'task-201', 'task-202', 'task-203', - 'task-301', 'task-302', 'task-303', 'task-304', - 'task-401', 'task-402', 'task-403' -]); - -// Persistent state manager with non-blocking async queue -let isWriting = false; -let pendingSave: AppStore | null = null; -let saveDebounceTimer: NodeJS.Timeout | null = null; -let stateRevision = Date.now(); // Global revision identifier for ETag HTTP 304 validation - -function flushStoreSync() { - if (saveDebounceTimer) { - clearTimeout(saveDebounceTimer); - saveDebounceTimer = null; - } - if (pendingSave) { - try { - if (!fs.existsSync(DATA_DIR)) { - fs.mkdirSync(DATA_DIR, { recursive: true }); - } - fs.writeFileSync(DATA_FILE, JSON.stringify(pendingSave, null, 2), 'utf-8'); - console.log('[Server Shutdown] In-flight store data flushed synchronously.'); - pendingSave = null; - } catch (err) { - console.error('[Server Shutdown] Failed to flush store synchronously:', err); - } - } -} - -function loadStore(): AppStore { - try { - if (!fs.existsSync(DATA_DIR)) { - fs.mkdirSync(DATA_DIR, { recursive: true }); - } - if (fs.existsSync(DATA_FILE)) { - const content = fs.readFileSync(DATA_FILE, 'utf-8'); - const parsed = JSON.parse(content); - if (Array.isArray(parsed.users) && Array.isArray(parsed.tasks)) { - // Filter out initial template dummy placeholders - const cleanUsers = parsed.users.filter( - (u: User) => !DUMMY_USER_IDS.has(u.id) && !u.email?.endsWith('@acme.studio') - ); - const cleanTasks = parsed.tasks.filter( - (t: Task) => !DUMMY_TASK_IDS.has(t.id) && !DUMMY_USER_IDS.has(t.userId) - ); - return { users: cleanUsers, tasks: cleanTasks }; - } - } - } catch (err) { - console.error('Error reading data file, using defaults:', err); - } - - const initialStore: AppStore = { - users: [], - tasks: [], - }; - saveStore(initialStore); - return initialStore; -} - -// Non-blocking debounced asynchronous persistence to prevent event loop bottlenecks -function saveStore(storeToSave: AppStore) { - pendingSave = storeToSave; - stateRevision = Date.now(); - - if (saveDebounceTimer) { - clearTimeout(saveDebounceTimer); - } - - saveDebounceTimer = setTimeout(async () => { - if (isWriting || !pendingSave) return; - isWriting = true; - const dataToWrite = pendingSave; - pendingSave = null; - - try { - await fs.promises.mkdir(DATA_DIR, { recursive: true }); - const tempPath = `${DATA_FILE}.tmp.${Date.now()}`; - await fs.promises.writeFile(tempPath, JSON.stringify(dataToWrite, null, 2), 'utf-8'); - await fs.promises.rename(tempPath, DATA_FILE); - } catch (err) { - console.error('Failed to persist store asynchronously:', err); - } finally { - isWriting = false; - if (pendingSave) { - saveStore(pendingSave); - } - } - }, 50); -} +let stateRevision = Date.now(); +function saveStore(_store: AppStore) { stateRevision++; } // Input sanitizer to prevent XSS / malicious injection in titles & descriptions function sanitizeString(input: unknown): string { @@ -306,13 +170,14 @@ function createRateLimiter(maxRequests: number, windowMs: number) { } // In-memory active store -let store: AppStore = loadStore(); +let store: AppStore = { users: [], tasks: [] }; -// Server-owned persistence: Admin SDK with private credentials, or local storage. +// Firestore is the mandatory server-owned data store. let adminDb: any = null; let firestoreLastError: string | null = null; let firestoreLastSyncTime: string | null = null; -let firestoreMode: 'admin' | 'web' | 'local' = 'local'; +let firestoreMode: 'admin' = 'admin'; +let workspace: FirestoreWorkspace; let firestoreProjectId: string = 'zen-flow-7173d'; let firestoreDatabaseId: string = '(default)'; @@ -392,7 +257,8 @@ async function initFirestore() { if (serviceAccountObj) { try { - firestoreProjectId = serviceAccountObj.project_id || firestoreProjectId; + firestoreProjectId = process.env.FIREBASE_PROJECT_ID || serviceAccountObj.project_id || firestoreProjectId; + firestoreDatabaseId = process.env.FIREBASE_DATABASE_ID || firestoreDatabaseId; const adminAppModule = await import('firebase-admin/app'); let adminFirestoreModule: any = null; try { @@ -413,9 +279,9 @@ async function initFirestore() { }, 'zenflow-firestore') : adminAppModule.getApp('zenflow-firestore'); - adminDb = adminFirestoreModule.getFirestore(adminApp); + adminDb = adminFirestoreModule.getFirestore(adminApp, process.env.FIREBASE_DATABASE_ID || firestoreDatabaseId); try { - adminDb.settings({ ignoreUndefinedProperties: true }); + adminDb.settings({ ignoreUndefinedProperties: true, preferRest: !process.env.FIRESTORE_EMULATOR_HOST }); } catch { // settings already configured } @@ -429,264 +295,25 @@ async function initFirestore() { } } - // Direct unauthenticated Firestore access is intentionally disabled. Local mode - // remains available for offline development or an explicitly provisioned volume. - firestoreMode = 'local'; - firestoreLastError ||= 'Firebase Admin credentials required for cloud persistence'; + // Refuse startup when the authoritative cloud store cannot be configured. + throw new Error(firestoreLastError || 'Firebase Admin credentials are required; local persistence is disabled'); })(); } await initPromise; } -// Utility to clean undefined values so Firestore never throws unsupported field value error -function cleanDocData>(obj: T): Partial { - const clean: any = {}; - for (const [k, v] of Object.entries(obj)) { - if (v !== undefined) { - if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) { - clean[k] = cleanDocData(v); - } else { - clean[k] = v; - } - } - } - return clean; -} - -// Read the tail of the compliance audit log into the in-memory cache for fast sub-millisecond retrieval -async function loadRecentAuditLogs(): Promise { - try { - recentAuditLogs.push(...await readAuditTail(AUDIT_LOG_FILE, MAX_RECENT_AUDIT_LOGS)); - } catch { - console.warn('[Audit Log] Failed to load recent audit records'); - } -} - -// Append-only compliance audit logger (SOC2 non-repudiation stream) -async function appendAuditLog(entry: Omit & { id?: string; timestamp?: string }): Promise { - const fullEntry: AuditLogEntry = { - id: entry.id || `audit-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`, - timestamp: entry.timestamp || new Date().toISOString(), - ...entry, - }; - - recentAuditLogs.unshift(fullEntry); - if (recentAuditLogs.length > MAX_RECENT_AUDIT_LOGS) { - recentAuditLogs.pop(); - } - - // Non-blocking disk append to compliance-audit.jsonl - try { - if (!fs.existsSync(DATA_DIR)) { - await fs.promises.mkdir(DATA_DIR, { recursive: true }); - } - const line = JSON.stringify(fullEntry) + '\n'; - await fs.promises.appendFile(AUDIT_LOG_FILE, line, 'utf-8'); - } catch (err) { - console.error('[Compliance Audit] Failed to append audit log to disk:', err); - } - - // Mirror to Cloud Firestore audit collection if active - try { - if (!adminDb) await initFirestore(); - const payload = cleanDocData(fullEntry); - if (adminDb) { - adminDb.collection('compliance_audit_logs').doc(fullEntry.id).create(payload).catch(() => {}); - } - } catch { - // ignore - } -} - -// Unified DB helper methods with error tracking & auto-recovery -async function dbSaveUser(user: User) { - try { - if (!adminDb) await initFirestore(); - const payload = cleanDocData(user); - if (adminDb) { - await adminDb.collection('users').doc(user.id).set(payload, { merge: true }); - firestoreLastError = null; - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Save User Error]:', firestoreLastError); - } -} - -async function dbSaveTask(task: Task) { - try { - if (!adminDb) await initFirestore(); - const payload = cleanDocData(task); - if (adminDb) { - await adminDb.collection('tasks').doc(task.id).set(payload, { merge: true }); - firestoreLastError = null; - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Save Task Error]:', firestoreLastError); - } -} - -async function dbDeleteTask(taskId: string) { - try { - if (!adminDb) await initFirestore(); - if (adminDb) { - await adminDb.collection('tasks').doc(taskId).delete(); - firestoreLastError = null; - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Delete Task Error]:', firestoreLastError); - } -} - -async function dbDeleteUser(userId: string) { - try { - if (!adminDb) await initFirestore(); - if (adminDb) { - await adminDb.collection('users').doc(userId).delete(); - firestoreLastError = null; - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Delete User Error]:', firestoreLastError); - } -} - -async function dbBatchDeleteTasks(taskIds: string[]) { - if (taskIds.length === 0) return; - try { - if (!adminDb) await initFirestore(); - const CHUNK_SIZE = 500; - for (let i = 0; i < taskIds.length; i += CHUNK_SIZE) { - const chunk = taskIds.slice(i, i + CHUNK_SIZE); - if (adminDb) { - const batch = adminDb.batch(); - for (const id of chunk) { - batch.delete(adminDb.collection('tasks').doc(id)); - } - await batch.commit(); - firestoreLastError = null; - } - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Batch Delete Tasks Error]:', firestoreLastError); - } -} - -async function dbBatchSaveUsers(users: User[]) { - if (users.length === 0) return; - try { - if (!adminDb) await initFirestore(); - const CHUNK_SIZE = 500; - for (let i = 0; i < users.length; i += CHUNK_SIZE) { - const chunk = users.slice(i, i + CHUNK_SIZE); - if (adminDb) { - const batch = adminDb.batch(); - for (const u of chunk) { - batch.set(adminDb.collection('users').doc(u.id), cleanDocData(u), { merge: true }); - } - await batch.commit(); - firestoreLastError = null; - } - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Batch Save Users Error]:', firestoreLastError); - } +// Workspace changes and audit records are committed together before responses or SSE. +let pendingEvents: Array<{ type: string; payload: any }> | null = null; +let pendingAudit: AuditLogEntry[] = []; +async function appendAuditLog(entry: Omit): Promise { + pendingAudit.push({ ...entry, id: crypto.randomUUID(), timestamp: new Date().toISOString() }); } - -async function dbBatchSaveTasks(tasks: Task[]) { - if (tasks.length === 0) return; - try { - if (!adminDb) await initFirestore(); - // Firestore has a maximum batch limit of 500 operations. Chunk tasks into blocks of 500. - const CHUNK_SIZE = 500; - for (let i = 0; i < tasks.length; i += CHUNK_SIZE) { - const chunk = tasks.slice(i, i + CHUNK_SIZE); - if (adminDb) { - const batch = adminDb.batch(); - for (const t of chunk) { - batch.set(adminDb.collection('tasks').doc(t.id), cleanDocData(t), { merge: true }); - } - await batch.commit(); - firestoreLastError = null; - } - } - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.error('[Firestore Batch Save Tasks Error]:', firestoreLastError); - } -} - -// Sync existing users and tasks with Firestore async function syncFromFirestore() { - if (!adminDb) { - await initFirestore(); - if (!adminDb) return; - } - - try { - // Use module-level DUMMY_USER_IDS β€” eliminates duplicate Set literal (single source of truth) - - const firestoreUsers: User[] = []; - const firestoreTasks: Task[] = []; - - if (adminDb) { - const usersSnap = await adminDb.collection('users').get(); - const tasksSnap = await adminDb.collection('tasks').get(); - - usersSnap.forEach((d: any) => { - const u = d.data() as User; - if (!DUMMY_USER_IDS.has(u.id) && !u.email?.endsWith('@acme.studio')) { - firestoreUsers.push(u); - } - }); - - tasksSnap.forEach((d: any) => { - const t = d.data() as Task; - if (!DUMMY_TASK_IDS.has(t.id) && !DUMMY_USER_IDS.has(t.userId)) { - firestoreTasks.push(t); - } - }); - } - - // Merge strategy: - // 1. Users: If Firestore has documents, integrate them with store. - // If Firestore is empty but store has users, push store users to Firestore via fast batch commit! - if (firestoreUsers.length > 0) { - const userMap = new Map(store.users.map(u => [u.id, u])); - for (const u of firestoreUsers) { - userMap.set(u.id, u); - } - store.users = Array.from(userMap.values()); - } else if (store.users.length > 0) { - await dbBatchSaveUsers(store.users); - } - - // 2. Tasks: If Firestore has tasks, integrate them. - // If Firestore is empty but store has tasks, push store tasks to Firestore via fast batch commit! - if (firestoreTasks.length > 0) { - const taskMap = new Map(store.tasks.map(t => [t.id, t])); - for (const t of firestoreTasks) { - taskMap.set(t.id, t); - } - store.tasks = Array.from(taskMap.values()); - } else if (store.tasks.length > 0) { - await dbBatchSaveTasks(store.tasks); - } - - ensureSuperadmin(store); - saveStore(store); - firestoreLastError = null; - firestoreLastSyncTime = new Date().toISOString(); - console.log(`[Firestore] Sync complete: ${store.users.length} user(s), ${store.tasks.length} task(s).`); - } catch (err: any) { - firestoreLastError = err.message || String(err); - console.warn('[Firestore] Sync warning, retaining local store:', firestoreLastError); - } + const snapshot = await workspace.load(); + store = snapshot.store as AppStore; + stateRevision = snapshot.revision; + firestoreLastSyncTime = new Date().toISOString(); } // Connected clients for Server-Sent Events (SSE) real-time broadcasting @@ -702,6 +329,7 @@ let nextClientId = 1; const MAX_SSE_CLIENTS = 100; function broadcastEvent(type: string, payload: any) { + if (pendingEvents) { pendingEvents.push({ type, payload: structuredClone(payload) }); return; } const eventData = JSON.stringify({ type, payload: redactPayload(payload), @@ -727,467 +355,6 @@ function broadcastEvent(type: string, payload: any) { }); } -function deduplicateUsers(appStore: AppStore): boolean { - let changed = false; - const byEmail = new Map(); - for (const u of appStore.users) { - if (!u || !u.email) continue; - const em = u.email.toLowerCase().trim(); - if (!byEmail.has(em)) byEmail.set(em, []); - byEmail.get(em)!.push(u); - } - - for (const [email, list] of byEmail.entries()) { - if (list.length <= 1) { - if (email === SUPERADMIN_EMAIL.toLowerCase() && list[0] && !list[0].isCreativeDirector) { - list[0].isCreativeDirector = true; - changed = true; - } - continue; - } - - changed = true; - console.log(`[Deduplication] Resolving ${list.length} duplicate accounts for ${email}...`); - - // Determine primary user: - // 1. Account that has tasks in appStore.tasks - // 2. Account whose ID is NOT 'user-superadmin-kiran' - // 3. Earliest created account - let primary = list.find(u => appStore.tasks.some(t => t.userId === u.id)); - if (!primary) { - primary = list.find(u => u.id !== 'user-superadmin-kiran') || list[0]; - } - - if (email === SUPERADMIN_EMAIL.toLowerCase()) { - primary.isCreativeDirector = true; - } - - // Reassign any tasks belonging to other duplicate accounts to primary ID - for (const dup of list) { - if (dup.id === primary.id) continue; - for (const t of appStore.tasks) { - if (t.userId === dup.id) { - t.userId = primary.id; - changed = true; - } - } - dbDeleteUser(dup.id).catch(() => {}); - } - - // Retain only the primary user - appStore.users = appStore.users.filter(u => { - if (u.email && u.email.toLowerCase().trim() === email) { - return u.id === primary.id; - } - return true; - }); - - console.log(`[Deduplication] Successfully retained primary user: ${primary.name} (${primary.id}) and pruned duplicates.`); - } - - if (changed) { - saveStore(appStore); - } - return changed; -} - -function ensureSuperadmin(appStore: AppStore) { - deduplicateUsers(appStore); - - const existingSuperadmin = appStore.users.find( - u => u.email.toLowerCase() === SUPERADMIN_EMAIL.toLowerCase() - ); - - if (existingSuperadmin) { - if (!existingSuperadmin.isCreativeDirector) { - existingSuperadmin.isCreativeDirector = true; - saveStore(appStore); - dbSaveUser(existingSuperadmin).catch(e => console.error('Firestore superadmin update err:', e)); - } - } else { - // Only bootstrap if NO user with SUPERADMIN_EMAIL exists - const superadmin: User = { - id: 'user-superadmin-kiran', - name: 'Kiran S', - email: SUPERADMIN_EMAIL, - role: 'content', - avatarColor: 'from-blue-600 to-indigo-600', - isCreativeDirector: true, - createdAt: new Date().toISOString(), - }; - appStore.users.unshift(superadmin); - saveStore(appStore); - dbSaveUser(superadmin).catch(e => console.error('Firestore superadmin init err:', e)); - console.log(`[Superadmin] Initialized ${SUPERADMIN_EMAIL} with Creative Director privileges.`); - } -} - -// Ensure superadmin exists and data is deduplicated on startup -ensureSuperadmin(store); - -const cachedClickupTeamIds = new Map(); -async function resolveClickupTeamId(token: string): Promise { - const cached = cachedClickupTeamIds.get(token); - if (cached) return cached; - try { - const teamRes = await fetch('https://api.clickup.com/api/v2/team', { - headers: { Authorization: token }, - }); - if (teamRes.ok) { - const teamData = await teamRes.json(); - const tid = teamData.teams?.[0]?.id ? String(teamData.teams[0].id) : null; - if (tid) cachedClickupTeamIds.set(token, tid); - return tid; - } - } catch (err) { - console.warn('[ClickUp] Could not resolve team ID for time tracking:', err); - } - return null; -} - -// Post time entry ensuring it is credited to the board member (taskUser), never polluting the caller's timesheet -async function postClickupTimeEntry(params: { - clickupTaskId: string; - durationMs: number; - taskUser: User; - callerUserId?: string; - callerToken: string; -}): Promise { - const { clickupTaskId, durationMs, taskUser, callerUserId, callerToken } = params; - const timeMs = Math.round(durationMs); - if (timeMs < 1000) return true; - - const isOwnBoard = !callerUserId || callerUserId === taskUser.id; - const boardUserToken = taskUser.clickupApiKey?.trim(); - const boardUserClickupId = taskUser.clickupUserId ? parseInt(taskUser.clickupUserId, 10) : undefined; - - // PRIORITY 1: If board member has their own ClickUp API key, authenticate with it. - // This guarantees the entry is credited directly to the board member's personal timesheet. - if (boardUserToken) { - const teamId = await resolveClickupTeamId(boardUserToken); - if (teamId) { - try { - const timeRes = await fetch(`https://api.clickup.com/api/v2/team/${teamId}/time_entries`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: boardUserToken, - }, - body: JSON.stringify({ - tid: clickupTaskId, - duration: timeMs, - start: Date.now() - timeMs, - stop: Date.now(), - billable: false, - ...(boardUserClickupId && !isNaN(boardUserClickupId) ? { assignee: boardUserClickupId } : {}), - }), - }); - if (timeRes.ok) { - console.log(`[ClickUp Time Sync] Tracked ${timeMs}ms directly to board member's timesheet (${taskUser.name}) via personal API key`); - return true; - } - } catch (err) { - console.warn(`[ClickUp Time Sync] Error via board member team time entries:`, err); - } - } - - try { - const timeRes = await fetch(`https://api.clickup.com/api/v2/task/${clickupTaskId}/time`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: boardUserToken, - }, - body: JSON.stringify({ - time: timeMs, - start: Date.now() - timeMs, - end: Date.now(), - }), - }); - if (timeRes.ok) { - console.log(`[ClickUp Time Sync] Tracked ${timeMs}ms to board member's timesheet (${taskUser.name}) via task time endpoint`); - return true; - } - } catch (err) { - console.warn(`[ClickUp Time Sync] Error via board member task time endpoint:`, err); - } - } - - // PRIORITY 2: If caller token is available and board member has a mapped ClickUp User ID, - // post via ClickUp Time Tracking API specifying "assignee: boardUserClickupId". - // This attributes the time entry to the board member in ClickUp. - if (callerToken && boardUserClickupId && !isNaN(boardUserClickupId)) { - const teamId = await resolveClickupTeamId(callerToken); - if (teamId) { - try { - const timeRes = await fetch(`https://api.clickup.com/api/v2/team/${teamId}/time_entries`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: callerToken, - }, - body: JSON.stringify({ - tid: clickupTaskId, - duration: timeMs, - start: Date.now() - timeMs, - stop: Date.now(), - billable: false, - assignee: boardUserClickupId, - }), - }); - if (timeRes.ok) { - console.log(`[ClickUp Time Sync] Tracked ${timeMs}ms for assignee ${boardUserClickupId} (${taskUser.name}) on board`); - return true; - } else { - const errText = await timeRes.text(); - console.warn(`[ClickUp Time Sync] Failed to post time for assignee ${boardUserClickupId}:`, errText); - } - } catch (err) { - console.warn(`[ClickUp Time Sync] Exception posting time for assignee ${boardUserClickupId}:`, err); - } - } - } - - // PRIORITY 3: If this is the logged-in user's OWN board, caller token can log to their own timesheet. - if (isOwnBoard && callerToken) { - try { - const timeRes = await fetch(`https://api.clickup.com/api/v2/task/${clickupTaskId}/time`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: callerToken, - }, - body: JSON.stringify({ - time: timeMs, - start: Date.now() - timeMs, - end: Date.now(), - }), - }); - if (timeRes.ok) { - console.log(`[ClickUp Time Sync] Tracked ${timeMs}ms on logged-in user's own board (${taskUser.name})`); - return true; - } - } catch (err) { - console.warn(`[ClickUp Time Sync] Error posting time for own board:`, err); - } - } - - // GUARANTEE: If syncing another user's board and direct attribution to that user is not possible, - // DO NOT log under the caller's token! Skipping protects the caller's timesheet from cross-contamination. - if (!isOwnBoard) { - console.log(`[ClickUp Time Sync] Protected caller timesheet: Skipped time sync for task on ${taskUser.name}'s board because time could not be attributed directly to ${taskUser.name}.`); - } - return false; -} - -async function syncTaskToClickUp(task: Task, apiKey?: string, user?: User, callerUserId?: string) { - const taskUser = user || store.users.find(u => u.id === task.userId); - if (!taskUser) return; - const callerToken = (apiKey || '').trim(); - const token = (taskUser.clickupApiKey || callerToken || store.users.find(u => u.clickupApiKey)?.clickupApiKey || '').trim(); - if (!token || !task.clickupListId) return; - - const targetStatus = ZENFLOW_TO_CLICKUP_STATUS[task.status] || 'to do'; - const estimateMs = COGNITIVE_LOAD_ESTIMATES_MS[task.cognitiveLoad] || COGNITIVE_LOAD_ESTIMATES_MS.medium; - const clickupAssigneeId = taskUser?.clickupUserId ? parseInt(taskUser.clickupUserId, 10) : undefined; - - // Tracked duration in ms from ZenFlow - let zenflowTrackedMs = task.inProgressDurationMs || 0; - if (task.status === 'in_progress' && task.inProgressStartedAt) { - zenflowTrackedMs += Math.max(0, Date.now() - new Date(task.inProgressStartedAt).getTime()); - } - - // If task already exists in ClickUp, update it - if (task.clickupTaskId) { - try { - // 1. Fetch current task on ClickUp to inspect time_spent and sync tracked time accurately - let clickupTimeSpent = 0; - let existingClickupAssignees: number[] = []; - try { - const getRes = await fetch(`https://api.clickup.com/api/v2/task/${task.clickupTaskId}`, { - headers: { Authorization: token }, - }); - if (getRes.ok) { - const cuTask = await getRes.json(); - clickupTimeSpent = typeof cuTask.time_spent === 'number' ? cuTask.time_spent : 0; - if (Array.isArray(cuTask.assignees)) { - existingClickupAssignees = cuTask.assignees - .map((a: any) => (typeof a === 'object' && a?.id ? parseInt(String(a.id), 10) : parseInt(String(a), 10))) - .filter((id: number) => !isNaN(id)); - } - } - } catch (err) { - console.warn(`[ClickUp Sync] Error reading task ${task.id} details:`, err); - } - - // Sync tracked time if ZenFlow has more time than recorded in ClickUp - const timeDiffMs = zenflowTrackedMs - clickupTimeSpent; - if (timeDiffMs >= 1000) { - await postClickupTimeEntry({ - clickupTaskId: task.clickupTaskId, - durationMs: timeDiffMs, - taskUser, - callerUserId, - callerToken: callerToken || token, - }); - } - - // 2. Update task attributes on ClickUp (replace assignees, not add) - const updatePayload: Record = { - name: task.title, - status: targetStatus, - time_estimate: estimateMs, - }; - if (task.description) updatePayload.description = task.description; - if (task.dueDate) updatePayload.due_date = new Date(task.dueDate + 'T23:59:59').getTime(); - if (task.inProgressStartedAt) updatePayload.start_date = new Date(task.inProgressStartedAt).getTime(); - - // Replace assignee: remove previous assignees, add new assignee - if (clickupAssigneeId && !isNaN(clickupAssigneeId)) { - const rem = existingClickupAssignees.filter(id => id !== clickupAssigneeId); - const add = existingClickupAssignees.includes(clickupAssigneeId) ? [] : [clickupAssigneeId]; - updatePayload.assignees = { - ...(add.length > 0 ? { add } : {}), - ...(rem.length > 0 ? { rem } : {}), - }; - } else if (existingClickupAssignees.length > 0) { - updatePayload.assignees = { rem: existingClickupAssignees }; - } - - const res = await fetch(`https://api.clickup.com/api/v2/task/${task.clickupTaskId}`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - Authorization: token, - }, - body: JSON.stringify(updatePayload), - }); - if (!res.ok) { - console.warn(`[ClickUp Sync] Failed to update task ${task.id} in ClickUp:`, await res.text()); - } - - // 3. Set "Task Type" Custom Field value - if (task.clickupTaskTypeFieldId && task.clickupTaskTypeId) { - try { - await fetch(`https://api.clickup.com/api/v2/task/${task.clickupTaskId}/field/${task.clickupTaskTypeFieldId}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: token, - }, - body: JSON.stringify({ value: task.clickupTaskTypeId }), - }); - } catch (cfErr) { - console.warn(`[ClickUp Sync] Error setting Task Type custom field on ${task.id}:`, cfErr); - } - } else if (task.clickupTaskType && task.clickupListId) { - // Resolve field and option dynamically if needed - try { - const fRes = await fetch(`https://api.clickup.com/api/v2/list/${task.clickupListId}/field`, { - headers: { Authorization: token }, - }); - if (fRes.ok) { - const fData = await fRes.json(); - const ttField = (fData.fields || []).find((f: any) => - (f.name || '').toLowerCase().trim() === 'task type' || (f.name || '').toLowerCase().includes('task type') - ); - if (ttField) { - const matchedOpt = (ttField.type_config?.options || []).find((o: any) => - o.name.toLowerCase() === task.clickupTaskType?.toLowerCase() || o.id === task.clickupTaskType - ); - if (matchedOpt) { - task.clickupTaskTypeFieldId = ttField.id; - task.clickupTaskTypeId = matchedOpt.id; - await fetch(`https://api.clickup.com/api/v2/task/${task.clickupTaskId}/field/${ttField.id}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: token, - }, - body: JSON.stringify({ value: matchedOpt.id }), - }); - } - } - } - } catch (cfErr) { - console.warn(`[ClickUp Sync] Dynamic Task Type lookup err:`, cfErr); - } - } - } catch (err) { - console.warn(`[ClickUp Sync] Error updating task ${task.id}:`, err); - } - return; - } - - // Create new task in ClickUp (without tags, with custom fields) - try { - const createPayload: Record = { - name: task.title, - status: targetStatus, - time_estimate: estimateMs, - }; - if (task.description) createPayload.description = task.description; - if (task.dueDate) createPayload.due_date = new Date(task.dueDate + 'T23:59:59').getTime(); - if (task.inProgressStartedAt) createPayload.start_date = new Date(task.inProgressStartedAt).getTime(); - if (clickupAssigneeId && !isNaN(clickupAssigneeId)) { - createPayload.assignees = [clickupAssigneeId]; - } - if (task.clickupTaskTypeFieldId && task.clickupTaskTypeId) { - createPayload.custom_fields = [{ id: task.clickupTaskTypeFieldId, value: task.clickupTaskTypeId }]; - } - - const res = await fetch(`https://api.clickup.com/api/v2/list/${task.clickupListId}/task`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: token, - }, - body: JSON.stringify(createPayload), - }); - if (res.ok) { - const clickupTask = await res.json(); - task.clickupTaskId = clickupTask.id; - task.clickupUrl = clickupTask.url; - - // Sync initial tracked duration if already accumulated - if (zenflowTrackedMs >= 1000) { - await postClickupTimeEntry({ - clickupTaskId: clickupTask.id, - durationMs: zenflowTrackedMs, - taskUser, - callerUserId, - callerToken: callerToken || token, - }); - } - - // Ensure custom field is set if not accepted in create payload - if (task.clickupTaskTypeFieldId && task.clickupTaskTypeId) { - try { - await fetch(`https://api.clickup.com/api/v2/task/${clickupTask.id}/field/${task.clickupTaskTypeFieldId}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: token, - }, - body: JSON.stringify({ value: task.clickupTaskTypeId }), - }); - } catch { - // ignore - } - } - - saveStore(store); - dbSaveTask(task).catch(e => console.error('Firestore save task err:', e)); - broadcastEvent('task_updated', task); - console.log(`[ClickUp Sync] Created task ${task.id} in ClickUp (${clickupTask.id}) with status ${targetStatus} and tracked time ${zenflowTrackedMs}ms`); - } else { - console.warn(`[ClickUp Sync] Failed to create task ${task.id} in ClickUp:`, await res.text()); - } - } catch (err) { - console.warn(`[ClickUp Sync] Error creating task ${task.id}:`, err); - } -} - const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000; function autoArchiveDoneTasks(): boolean { @@ -1234,9 +401,7 @@ function autoArchiveDoneTasks(): boolean { if (changed) { saveStore(store); - dbBatchSaveTasks(newlyArchived).catch(e => - console.error('[Auto-Archive] Firestore batch save error:', e) - ); + broadcastEvent('tasks_reordered', newlyArchived); console.log(`[Auto-Archive] Automatically archived ${newlyArchived.length} completed task(s) older than 7 days.`); } @@ -1244,185 +409,11 @@ function autoArchiveDoneTasks(): boolean { return changed; } -// Background sweep running every hour -setInterval(autoArchiveDoneTasks, 60 * 60 * 1000).unref(); - -// Debounce guard for per-request calls β€” skips the O(N) scan if the sweep ran within the last 60 seconds -let lastArchiveSweepMs = 0; -const ARCHIVE_DEBOUNCE_MS = 60_000; -function maybeArchive(): void { - const now = Date.now(); - if (now - lastArchiveSweepMs < ARCHIVE_DEBOUNCE_MS) return; - lastArchiveSweepMs = now; - autoArchiveDoneTasks(); -} - -// Process inbound ClickUp webhook events (status updates, assignee reassignments, deadline syncing, deletions) -async function processClickupWebhookEvent(params: { - taskId: string; - eventType: string; - historyItems: any[]; - rawBody: any; - ip?: string; -}): Promise { - const { taskId, eventType, historyItems, rawBody, ip } = params; - if (!taskId) { - appendAuditLog({ - category: 'webhook', - action: 'clickup_webhook_ping', - actor: { ip }, - targetId: 'workspace', - targetType: 'webhook', - details: `ClickUp webhook event received without task_id: ${eventType}`, - metadata: { eventType, rawBody }, - }); - return; - } - - console.log(`[ClickUp Webhook] Processing event "${eventType}" for task ${taskId}`); - - const matchingTasks = store.tasks.filter(t => t.clickupTaskId === taskId); - - // Requirement: Do NOT pull tasks from ClickUp even if assigned to a user on the app. - // Only tasks added on ZenFlow and present on the ZenFlow board should be updated by the live webhook. - if (matchingTasks.length === 0) { - console.log(`[ClickUp Webhook] Task ${taskId} is not present on the ZenFlow board. Ignoring event "${eventType}".`); - return; - } - - const existingTask = matchingTasks[0]; - - // ZenFlow Single Source of Truth Enforcement: - // If task was deleted on ClickUp, do NOT delete from ZenFlow. Re-assert ZenFlow task state. - if (eventType === 'taskDeleted') { - appendAuditLog({ - category: 'webhook', - action: 'clickup_task_deleted_preserved', - actor: { ip }, - targetId: existingTask.id, - targetType: 'task', - details: `ClickUp deleted task "${existingTask.title}" (${taskId}), but ZenFlow remains authoritative. Task preserved in ZenFlow.`, - metadata: { clickupTaskId: taskId }, - }); - console.log(`[ClickUp Webhook] Task ${taskId} was deleted in ClickUp. Preserving in ZenFlow (authoritative source of truth).`); - return; - } - - // Retrieve full task from ClickUp API if available to inspect divergence - let clickupTaskData: any = null; - const assignedUser = store.users.find(u => u.id === existingTask.userId); - const userWithKey = store.users.find(u => u.clickupApiKey); - const token = (assignedUser?.clickupApiKey || userWithKey?.clickupApiKey)?.trim(); - - if (token) { - try { - const cRes = await fetch(`https://api.clickup.com/api/v2/task/${taskId}`, { - headers: { Authorization: token }, - }); - if (cRes.ok) { - clickupTaskData = await cRes.json(); - } - } catch (e) { - console.warn(`[ClickUp Webhook] Could not fetch ClickUp task ${taskId}:`, e); - } - } - - // Detect if ClickUp task diverges from ZenFlow authoritative state - let hasDivergence = false; - let divergenceReason = ''; - - // 1. Inspect Status Divergence - const expectedClickupStatus = ZENFLOW_TO_CLICKUP_STATUS[existingTask.status] || 'to do'; - let cuStatusRaw: string | null = null; - const statusItem = historyItems.find((h: any) => h.field === 'status'); - if (statusItem?.after) { - cuStatusRaw = typeof statusItem.after === 'string' - ? statusItem.after.toLowerCase().trim() - : (statusItem.after?.status || '').toLowerCase().trim(); - } else if (clickupTaskData?.status?.status) { - cuStatusRaw = (clickupTaskData.status.status || '').toLowerCase().trim(); - } - if (cuStatusRaw && cuStatusRaw !== expectedClickupStatus.toLowerCase()) { - hasDivergence = true; - divergenceReason = `Status on ClickUp ("${cuStatusRaw}") differs from ZenFlow ("${existingTask.status}")`; - } - - // 2. Inspect Assignee Divergence - const expectedClickupUserId = assignedUser?.clickupUserId ? String(assignedUser.clickupUserId) : null; - let cuAssigneeId: string | null = null; - const assigneeItem = historyItems.find((h: any) => h.field === 'assignee'); - if (assigneeItem?.after) { - if (typeof assigneeItem.after === 'object') { - cuAssigneeId = assigneeItem.after.id ? String(assigneeItem.after.id) : null; - } else { - cuAssigneeId = String(assigneeItem.after); - } - } else if (clickupTaskData?.assignees?.[0]) { - cuAssigneeId = String(clickupTaskData.assignees[0].id); - } - if (expectedClickupUserId && cuAssigneeId && cuAssigneeId !== expectedClickupUserId) { - hasDivergence = true; - divergenceReason = `Assignee on ClickUp (${cuAssigneeId}) differs from ZenFlow assignee (${expectedClickupUserId})`; - } - - // 3. Inspect Due Date Divergence - if (existingTask.dueDate && clickupTaskData?.due_date !== undefined) { - const expectedDueMs = new Date(existingTask.dueDate + 'T23:59:59').getTime(); - const actualDueMs = Number(clickupTaskData.due_date); - // Tolerate timezone shift under 24h - if (!isNaN(actualDueMs) && Math.abs(expectedDueMs - actualDueMs) > 86400000) { - hasDivergence = true; - divergenceReason = `Due date on ClickUp differs from ZenFlow (${existingTask.dueDate})`; - } - } - - // If any divergence is detected, assert ZenFlow as source of truth and update ClickUp - if (hasDivergence && token) { - console.log(`[ClickUp Webhook] Divergence detected (${divergenceReason}). Re-syncing ZenFlow authoritative state to ClickUp for task "${existingTask.title}" (${taskId}).`); - syncTaskToClickUp(existingTask, token, assignedUser).catch(e => - console.error('[ClickUp Webhook] Error pushing authoritative state to ClickUp:', e) - ); - - appendAuditLog({ - category: 'webhook', - action: 'zenflow_source_of_truth_asserted', - actor: { ip }, - targetId: existingTask.id, - targetType: 'task', - details: `ClickUp diverged from ZenFlow (${divergenceReason}). ZenFlow authoritative state pushed to ClickUp.`, - metadata: { clickupTaskId: taskId, divergenceReason }, - }); - return; - } - - // If time tracked on ClickUp changed and ZenFlow has less tracked time, record duration - const timeItem = historyItems.find((h: any) => h.field === 'time_spent' || h.field === 'time_tracked'); - if (timeItem?.after !== undefined) { - const parsedMs = Number(timeItem.after); - if (!isNaN(parsedMs) && parsedMs > (existingTask.inProgressDurationMs || 0)) { - existingTask.inProgressDurationMs = parsedMs; - existingTask.updatedAt = new Date().toISOString(); - const activityEntries = Array.isArray(existingTask.activityLog) ? [...existingTask.activityLog] : []; - activityEntries.unshift({ - id: `act-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`, - timestamp: new Date().toISOString(), - action: 'billable_adjusted', - details: `Tracked duration synced to ${formatBillableHoursServer(parsedMs)} from ClickUp`, - }); - existingTask.activityLog = activityEntries.slice(0, 15); - saveStore(store); - dbSaveTask(existingTask).catch(e => console.error('Firestore save err:', e)); - broadcastEvent('task_updated', existingTask); - } - } -} - - async function startServer() { const app = express(); app.set('case sensitive routing', true); - // Initialize Firestore if credentials are provided, or fall back safely + // Refuse startup without a reachable Firestore database. await initFirestore(); // Trust first proxy hop in containerized cloud environments (Railway, Cloud Run, Nixpacks) @@ -1454,7 +445,7 @@ async function startServer() { res.setHeader('X-Permitted-Cross-Domain-Policies', 'none'); res.setHeader( 'Content-Security-Policy', - "default-src 'self'; script-src 'self' 'unsafe-inline' https://apis.google.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https://lh3.googleusercontent.com https://*.googleusercontent.com; connect-src 'self' https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://api.clickup.com; frame-src 'self' https://*.firebaseapp.com https://accounts.google.com; frame-ancestors 'none';" + "default-src 'self'; script-src 'self' 'unsafe-inline' https://apis.google.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https://lh3.googleusercontent.com https://*.googleusercontent.com; connect-src 'self' https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com; frame-src 'self' https://*.firebaseapp.com https://accounts.google.com; frame-ancestors 'none';" ); next(); }); @@ -1476,22 +467,36 @@ async function startServer() { next(); }); - app.use(express.json({ limit: '1mb', verify: (req, _res, buffer) => { - if (req.url?.split('?')[0].replace(/\/+$/, '') === '/api/clickup/webhook') (req as Request & { rawBody?: Buffer }).rawBody = Buffer.from(buffer); - } })); + app.use(express.json({ limit: '1mb' })); + // Retired integration URLs never reach authentication, persistence or SPA fallback. + app.use('/api/clickup', (_req, res) => { res.status(410).json({ error: 'Integration removed' }); }); + // Reject anonymous traffic before any database reads. Authorization runs again + // against the fresh Firestore snapshot below, including revoked membership. + app.use('/api', (req, res, next) => { + if (['/auth/session', '/health'].includes(req.path)) return next(); + return createApiSecurity({ getStore: () => store, verify: verifyIdentity })(req, res, next); + }); // Sliding-window rate limiters for sensitive endpoints (prevent DoS and quota depletion) const authLimiter = createRateLimiter(20, 60 * 1000); // 20 login attempts per minute per IP const firestoreLimiter = createRateLimiter(10, 60 * 1000); // 10 sync/credential submissions per minute per IP // Initialize and load database records from Firestore + workspace = new FirestoreWorkspace(adminDb); + await workspace.migrate(); + await workspace.bootstrap(); await syncFromFirestore(); - autoArchiveDoneTasks(); - await loadRecentAuditLogs(); - await webhookRegistry.load(adminDb); - const savedWebhook = webhookRegistry.latest(); - registeredWebhookId = savedWebhook?.id || null; - activeWebhookEndpoint = savedWebhook?.endpoint || null; + app.use('/api', workspaceMiddleware({ + workspace, getStore: () => store, setStore: value => { store = value as AppStore; }, + begin: revision => { stateRevision = revision; pendingEvents = []; pendingAudit = []; }, + audit: () => pendingAudit, + committed: revision => { + stateRevision = revision; firestoreLastSyncTime = new Date().toISOString(); firestoreLastError = null; + const events = pendingEvents || []; pendingEvents = null; + for (const event of events) broadcastEvent(event.type, event.payload); + }, + failed: error => { pendingEvents = null; pendingAudit = []; if (error) firestoreLastError = 'Firestore operation failed'; }, + })); // Exchange a verified Firebase ID token for an HttpOnly, same-origin SSE/API cookie. app.post('/api/auth/session', authLimiter, async (req: Request, res: Response) => { @@ -1516,20 +521,21 @@ async function startServer() { app.use('/api', createApiSecurity({ getStore: () => store, verify: verifyIdentity })); // API: Health check - app.get('/api/health', (_req: Request, res: Response) => { + app.get('/api/health', async (_req: Request, res: Response) => { res.setHeader('Cache-Control', 'no-store'); - res.json({ status: 'ok', time: new Date().toISOString() }); + try { + await adminDb.doc('workspace/state').get(); + res.json({ status: 'ok', storage: 'firestore', time: new Date().toISOString() }); + } catch { res.status(503).json({ status: 'unavailable', storage: 'firestore' }); } }); // API: Get entire state with ETag conditional validation (HTTP 304 Not Modified) app.get('/api/state', (req: Request, res: Response) => { - maybeArchive(); + autoArchiveDoneTasks(); const etag = `W/"zenflow-rev-${stateRevision}"`; res.setHeader('ETag', etag); res.setHeader('Cache-Control', 'private, no-cache, must-revalidate'); - deduplicateUsers(store); - if (req.headers['if-none-match'] === etag) { return res.status(304).end(); } @@ -1552,8 +558,6 @@ async function startServer() { const cleanName = name ? sanitizeString(name) : ''; const cleanRole = (role === 'design' ? 'design' : 'content') as 'content' | 'design'; - deduplicateUsers(store); - let existingUser = store.users.find(u => u.email.toLowerCase() === cleanEmail); if (existingUser) { @@ -1564,7 +568,7 @@ async function startServer() { } if (changed) { saveStore(store); - dbSaveUser(existingUser).catch(e => console.error('Firestore user update err:', e)); + broadcastEvent('user_updated', existingUser); } appendAuditLog({ @@ -1591,7 +595,7 @@ async function startServer() { }; store.users.unshift(superadmin); saveStore(store); - dbSaveUser(superadmin).catch(e => console.error('Firestore user create err:', e)); + broadcastEvent('user_created', superadmin); appendAuditLog({ category: 'security', @@ -1623,7 +627,6 @@ async function startServer() { const { email } = req.body; if (!email) return res.status(400).json({ error: 'Email is required' }); const cleanEmail = sanitizeString(email).toLowerCase(); - deduplicateUsers(store); const user = store.users.find(u => u.email.toLowerCase() === cleanEmail); if (!user) { return res.status(404).json({ error: 'No account registered with this email address' }); @@ -1633,7 +636,6 @@ async function startServer() { // API: Get all users with ETag conditional validation (HTTP 304 Not Modified) app.get('/api/users', (req: Request, res: Response) => { - deduplicateUsers(store); const etag = `W/"zenflow-users-${stateRevision}"`; res.setHeader('ETag', etag); res.setHeader('Cache-Control', 'private, no-cache, must-revalidate'); @@ -1653,11 +655,6 @@ async function startServer() { role, isCreativeDirector, creativeDirectorId, - clickupApiKey, - selectedClickupSpaceId, - selectedClickupSpaceName, - clickupUserId, - clickupUsername, } = req.body; if (!name || !email || !role) { @@ -1678,11 +675,9 @@ async function startServer() { existingUser.role = cleanRole; if (isCreativeDirector !== undefined) existingUser.isCreativeDirector = !!isCreativeDirector; if (creativeDirectorId !== undefined) existingUser.creativeDirectorId = creativeDirectorId ? sanitizeString(creativeDirectorId) : undefined; - if (clickupApiKey !== undefined) existingUser.clickupApiKey = clickupApiKey ? sanitizeString(clickupApiKey) : undefined; - if (clickupUserId !== undefined) existingUser.clickupUserId = clickupUserId ? sanitizeString(clickupUserId) : undefined; - if (clickupUsername !== undefined) existingUser.clickupUsername = clickupUsername ? sanitizeString(clickupUsername) : undefined; + saveStore(store); - dbSaveUser(existingUser).catch(e => console.error('Firestore user update err:', e)); + broadcastEvent('user_updated', existingUser); appendAuditLog({ category: 'user', @@ -1705,17 +700,12 @@ async function startServer() { avatarColor: AVATAR_COLORS[colorIndex], isCreativeDirector: !!isCreativeDirector, creativeDirectorId: creativeDirectorId ? sanitizeString(creativeDirectorId) : undefined, - clickupApiKey: clickupApiKey ? sanitizeString(clickupApiKey) : undefined, - selectedClickupSpaceId: selectedClickupSpaceId ? sanitizeString(selectedClickupSpaceId) : undefined, - selectedClickupSpaceName: selectedClickupSpaceName ? sanitizeString(selectedClickupSpaceName) : undefined, - clickupUserId: clickupUserId ? sanitizeString(clickupUserId) : undefined, - clickupUsername: clickupUsername ? sanitizeString(clickupUsername) : undefined, + createdAt: new Date().toISOString(), }; store.users.push(newUser); saveStore(store); - dbSaveUser(newUser).catch(e => console.error('Firestore user create err:', e)); broadcastEvent('user_created', newUser); appendAuditLog({ @@ -1732,6 +722,13 @@ async function startServer() { // API: Update user settings / profile (Superadmin can also correct email addresses) app.put('/api/users/:id', async (req: Request, res: Response) => { + const { + name, + email, + role, + isCreativeDirector, + creativeDirectorId, + } = req.body; const { id } = req.params; const userIndex = store.users.findIndex(u => u.id === id); @@ -1740,18 +737,6 @@ async function startServer() { } const current = store.users[userIndex]; - const { - name, - email, - role, - isCreativeDirector, - creativeDirectorId, - clickupApiKey, - selectedClickupSpaceId, - selectedClickupSpaceName, - clickupUserId, - clickupUsername, - } = req.body; const callerId = (req.headers['x-caller-user-id'] as string || '').trim(); const callerEmail = (req.headers['x-caller-email'] as string || '').trim().toLowerCase(); @@ -1812,7 +797,7 @@ async function startServer() { }); if (tasksToRemap.length > 0) { - await dbBatchSaveTasks(tasksToRemap); + } // Merge profile fields into existingTargetUser @@ -1829,38 +814,11 @@ async function startServer() { if (creativeDirectorId !== undefined) { existingTargetUser.creativeDirectorId = creativeDirectorId ? sanitizeString(creativeDirectorId) : undefined; } - if (clickupApiKey !== undefined) { - existingTargetUser.clickupApiKey = clickupApiKey ? sanitizeString(clickupApiKey) : undefined; - } else if (!existingTargetUser.clickupApiKey && current.clickupApiKey) { - existingTargetUser.clickupApiKey = current.clickupApiKey; - } - if (selectedClickupSpaceId !== undefined) { - existingTargetUser.selectedClickupSpaceId = selectedClickupSpaceId ? sanitizeString(selectedClickupSpaceId) : undefined; - } else if (!existingTargetUser.selectedClickupSpaceId && current.selectedClickupSpaceId) { - existingTargetUser.selectedClickupSpaceId = current.selectedClickupSpaceId; - } - if (selectedClickupSpaceName !== undefined) { - existingTargetUser.selectedClickupSpaceName = selectedClickupSpaceName ? sanitizeString(selectedClickupSpaceName) : undefined; - } else if (!existingTargetUser.selectedClickupSpaceName && current.selectedClickupSpaceName) { - existingTargetUser.selectedClickupSpaceName = current.selectedClickupSpaceName; - } - if (clickupUserId !== undefined) { - existingTargetUser.clickupUserId = clickupUserId ? sanitizeString(clickupUserId) : undefined; - } else if (!existingTargetUser.clickupUserId && current.clickupUserId) { - existingTargetUser.clickupUserId = current.clickupUserId; - } - if (clickupUsername !== undefined) { - existingTargetUser.clickupUsername = clickupUsername ? sanitizeString(clickupUsername) : undefined; - } else if (!existingTargetUser.clickupUsername && current.clickupUsername) { - existingTargetUser.clickupUsername = current.clickupUsername; - } // Remove the obsolete user record store.users = store.users.filter(u => u.id !== oldUserId); - await dbDeleteUser(oldUserId); saveStore(store); - await dbSaveUser(existingTargetUser); appendAuditLog({ category: 'user', @@ -1906,7 +864,7 @@ async function startServer() { task.updatedAt = new Date().toISOString(); }); if (orphanTasks.length > 0) { - await dbBatchSaveTasks(orphanTasks); + } appendAuditLog({ @@ -1940,24 +898,9 @@ async function startServer() { if (creativeDirectorId !== undefined) { current.creativeDirectorId = creativeDirectorId ? sanitizeString(creativeDirectorId) : undefined; } - if (clickupApiKey !== undefined) { - current.clickupApiKey = clickupApiKey ? sanitizeString(clickupApiKey) : undefined; - } - if (selectedClickupSpaceId !== undefined) { - current.selectedClickupSpaceId = selectedClickupSpaceId ? sanitizeString(selectedClickupSpaceId) : undefined; - } - if (selectedClickupSpaceName !== undefined) { - current.selectedClickupSpaceName = selectedClickupSpaceName ? sanitizeString(selectedClickupSpaceName) : undefined; - } - if (clickupUserId !== undefined) { - current.clickupUserId = clickupUserId ? sanitizeString(clickupUserId) : undefined; - } - if (clickupUsername !== undefined) { - current.clickupUsername = clickupUsername ? sanitizeString(clickupUsername) : undefined; - } saveStore(store); - dbSaveUser(current).catch(e => console.error('Firestore user update err:', e)); + broadcastEvent('user_updated', current); appendAuditLog({ category: 'user', @@ -2034,12 +977,12 @@ async function startServer() { }); if (tasksToRemap.length > 0) { - await dbBatchSaveTasks(tasksToRemap); + } if (deleteSourceUser && sourceUser && sourceUser.email.toLowerCase() !== SUPERADMIN_EMAIL.toLowerCase()) { store.users = store.users.filter(u => u.id !== sourceUser.id); - await dbDeleteUser(sourceUser.id); + broadcastEvent('user_deleted', { id: sourceUser.id }); } @@ -2099,9 +1042,9 @@ async function startServer() { saveStore(store); // Asynchronously delete user and tasks from Firestore if connected - dbDeleteUser(removedUser.id).catch(e => console.error('Firestore user delete err:', e)); + if (deletedTaskIds.length > 0) { - dbBatchDeleteTasks(deletedTaskIds).catch(e => console.error('Firestore batch delete tasks err:', e)); + } broadcastEvent('user_deleted', { id: removedUser.id, taskIds: deletedTaskIds }); @@ -2123,7 +1066,7 @@ async function startServer() { // API: Get all tasks with ETag conditional validation (HTTP 304 Not Modified) app.get('/api/tasks', (req: Request, res: Response) => { - maybeArchive(); + autoArchiveDoneTasks(); const etag = `W/"zenflow-tasks-${stateRevision}"`; res.setHeader('ETag', etag); res.setHeader('Cache-Control', 'private, no-cache, must-revalidate'); @@ -2145,16 +1088,6 @@ async function startServer() { dueDate, cognitiveLoad, status, - clickupTaskId, - clickupFolderId, - clickupFolderName, - clickupListId, - clickupListName, - clickupSpaceId, - clickupUrl, - clickupTaskType, - clickupTaskTypeId, - clickupTaskTypeFieldId, } = req.body; // Idempotency guard for offline mutation replay: if task with this ID already exists, return it @@ -2210,16 +1143,7 @@ async function startServer() { completedAt: isDone ? new Date().toISOString() : undefined, inProgressStartedAt: isInProgress ? new Date().toISOString() : undefined, inProgressDurationMs: 0, - clickupTaskId: clickupTaskId ? sanitizeString(clickupTaskId) : undefined, - clickupFolderId: clickupFolderId ? sanitizeString(clickupFolderId) : undefined, - clickupFolderName: clickupFolderName ? sanitizeString(clickupFolderName) : undefined, - clickupListId: clickupListId ? sanitizeString(clickupListId) : undefined, - clickupListName: clickupListName ? sanitizeString(clickupListName) : undefined, - clickupSpaceId: clickupSpaceId ? sanitizeString(clickupSpaceId) : undefined, - clickupUrl: clickupUrl ? sanitizeString(clickupUrl) : undefined, - clickupTaskType: clickupTaskType ? sanitizeString(clickupTaskType) : undefined, - clickupTaskTypeId: clickupTaskTypeId ? sanitizeString(clickupTaskTypeId) : undefined, - clickupTaskTypeFieldId: clickupTaskTypeFieldId ? sanitizeString(clickupTaskTypeFieldId) : undefined, + createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), activityLog: [initialActivity], @@ -2227,7 +1151,6 @@ async function startServer() { store.tasks.push(newTask); saveStore(store); - dbSaveTask(newTask).catch(e => console.error('Firestore task create err:', e)); broadcastEvent('task_created', newTask); appendAuditLog({ @@ -2240,23 +1163,12 @@ async function startServer() { metadata: { status: newTask.status, cognitiveLoad: newTask.cognitiveLoad, dueDate: newTask.dueDate }, }); - // Asynchronously push task to ClickUp if a list has been assigned - const assignedUser = store.users.find(u => u.id === userId); - const callerApiKey = (req.headers['x-clickup-api-key'] as string) || (req.body.clickupApiKey as string); - const callerId = (req.headers['x-caller-user-id'] as string) || (req.body.callerUserId as string); - const syncToken = (assignedUser?.clickupApiKey || callerApiKey || store.users.find(u => u.clickupApiKey)?.clickupApiKey || '').trim(); - if (newTask.clickupListId && syncToken) { - syncTaskToClickUp(newTask, syncToken, assignedUser, callerId).catch(e => - console.error('[ClickUp] Post-create sync err:', e) - ); - } - res.status(201).json(newTask); }); // API: Duplicate a task to another board (Creative Directors and Superadmins only) - // Preserves ClickUp linkage and adds the new user as a secondary assignee on ClickUp app.post('/api/tasks/:id/duplicate', async (req: Request, res: Response) => { + const { id } = req.params; const sourceTask = store.tasks.find(t => t.id === id); if (!sourceTask) { @@ -2264,7 +1176,6 @@ async function startServer() { } const callerId = (req.headers['x-caller-user-id'] as string) || (req.body.callerUserId as string); - const callerApiKey = (req.headers['x-clickup-api-key'] as string) || (req.body.clickupApiKey as string); const callerEmail = ((req.headers['x-caller-email'] as string) || (req.body.callerEmail as string) || '').toLowerCase(); let caller = callerId ? store.users.find(u => u.id === callerId) : undefined; @@ -2334,211 +1245,16 @@ async function startServer() { isSubtask: true, parentTaskId: sourceTask.id, parentTaskTitle: sourceTask.title, - clickupParentTaskId: sourceTask.clickupTaskId, - clickupFolderId: sourceTask.clickupFolderId, - clickupFolderName: sourceTask.clickupFolderName, - clickupListId: sourceTask.clickupListId, - clickupListName: sourceTask.clickupListName, - clickupSpaceId: sourceTask.clickupSpaceId, - clickupTaskType: sourceTask.clickupTaskType, - clickupTaskTypeId: sourceTask.clickupTaskTypeId, - clickupTaskTypeFieldId: sourceTask.clickupTaskTypeFieldId, + createdAt: now, updatedAt: now, activityLog: [initialActivity], }; - // ClickUp Subtask Creation: creates a dedicated subtask under the parent task assigned to targetUser - let clickupSubtaskCreated = false; - let clickupWarning: string | undefined; - - if (sourceTask.clickupTaskId) { - const syncToken = (callerApiKey || caller?.clickupApiKey || targetUser.clickupApiKey || store.users.find(u => u.clickupApiKey)?.clickupApiKey || '').trim(); - - let targetClickupUserId = targetUser.clickupUserId ? parseInt(targetUser.clickupUserId, 10) : undefined; - - // Auto-resolve ClickUp member ID by email if not set - if ((!targetClickupUserId || isNaN(targetClickupUserId)) && syncToken && targetUser.email) { - try { - const teamRes = await fetch('https://api.clickup.com/api/v2/team', { - headers: { Authorization: syncToken }, - }); - if (teamRes.ok) { - const teamData = await teamRes.json(); - for (const team of teamData.teams || []) { - for (const m of team.members || []) { - if (m?.user?.email && m.user.email.toLowerCase() === targetUser.email.toLowerCase()) { - targetClickupUserId = parseInt(String(m.user.id), 10); - targetUser.clickupUserId = String(m.user.id); - if (m.user.username) targetUser.clickupUsername = m.user.username; - saveStore(store); - dbSaveUser(targetUser).catch(e => console.error('Firestore save user err:', e)); - broadcastEvent('user_updated', targetUser); - break; - } - } - if (targetClickupUserId) break; - } - } - } catch (memErr) { - console.warn('[Duplicate Subtask] Error auto-resolving ClickUp member by email:', memErr); - } - } - - if (syncToken) { - let listId = sourceTask.clickupListId; - - // Authoritatively query the parent task directly from ClickUp to resolve its true, current list. - // This permanently eliminates ClickUp ITEM_137 ("Parent not child of list") error. - try { - const pRes = await fetch(`https://api.clickup.com/api/v2/task/${sourceTask.clickupTaskId}`, { - headers: { Authorization: syncToken }, - }); - if (pRes.ok) { - const pData = await pRes.json(); - if (pData.list?.id) { - listId = String(pData.list.id); - sourceTask.clickupListId = listId; - newTask.clickupListId = listId; - if (pData.list.name) { - sourceTask.clickupListName = pData.list.name; - newTask.clickupListName = pData.list.name; - } - if (pData.space?.id) { - sourceTask.clickupSpaceId = String(pData.space.id); - newTask.clickupSpaceId = String(pData.space.id); - } - if (pData.folder?.id) { - sourceTask.clickupFolderId = String(pData.folder.id); - newTask.clickupFolderId = String(pData.folder.id); - } - if (pData.folder?.name) { - sourceTask.clickupFolderName = pData.folder.name; - newTask.clickupFolderName = pData.folder.name; - } - } - } - } catch (pErr) { - console.warn('[Duplicate Subtask] Could not resolve fresh parent list ID from ClickUp:', pErr); - } - - if (listId) { - const targetStatusCu = ZENFLOW_TO_CLICKUP_STATUS[resolvedStatus] || 'to do'; - const estimateMs = COGNITIVE_LOAD_ESTIMATES_MS[newTask.cognitiveLoad] || COGNITIVE_LOAD_ESTIMATES_MS.medium; - const subtaskPayload: Record = { - name: newTask.title, - description: newTask.description || '', - parent: sourceTask.clickupTaskId, - status: targetStatusCu, - time_estimate: estimateMs, - }; - if (resolvedDueDate) { - subtaskPayload.due_date = new Date(resolvedDueDate + 'T23:59:59').getTime(); - } - if (targetClickupUserId && !isNaN(targetClickupUserId)) { - subtaskPayload.assignees = [targetClickupUserId]; - } - if (newTask.clickupTaskTypeFieldId && newTask.clickupTaskTypeId) { - subtaskPayload.custom_fields = [{ id: newTask.clickupTaskTypeFieldId, value: newTask.clickupTaskTypeId }]; - } - - try { - let cuRes = await fetch(`https://api.clickup.com/api/v2/list/${listId}/task`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: syncToken, - }, - body: JSON.stringify(subtaskPayload), - }); - - // Defensive self-healing retry if ClickUp returns ITEM_137 ("Parent not child of list") - if (!cuRes.ok) { - const errBody = await cuRes.text(); - if (errBody.includes('Parent not child of list') || errBody.includes('ITEM_137')) { - console.warn(`[ClickUp Subtask] Parent ${sourceTask.clickupTaskId} not in list ${listId} (ITEM_137). Querying ClickUp for true parent list...`); - try { - const refreshRes = await fetch(`https://api.clickup.com/api/v2/task/${sourceTask.clickupTaskId}`, { - headers: { Authorization: syncToken }, - }); - if (refreshRes.ok) { - const freshParent = await refreshRes.json(); - if (freshParent.list?.id && String(freshParent.list.id) !== listId) { - const trueListId = String(freshParent.list.id); - console.log(`[ClickUp Subtask] Retrying subtask creation in true parent list ${trueListId}...`); - const retryRes = await fetch(`https://api.clickup.com/api/v2/list/${trueListId}/task`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: syncToken, - }, - body: JSON.stringify(subtaskPayload), - }); - if (retryRes.ok) { - cuRes = retryRes; - listId = trueListId; - sourceTask.clickupListId = trueListId; - newTask.clickupListId = trueListId; - if (freshParent.list.name) { - sourceTask.clickupListName = freshParent.list.name; - newTask.clickupListName = freshParent.list.name; - } - } else { - const retryErrText = await retryRes.text(); - console.warn(`[ClickUp Subtask] Retry under list ${trueListId} failed:`, retryErrText); - } - } - } - } catch (retryErr) { - console.warn('[ClickUp Subtask] Error during ITEM_137 recovery:', retryErr); - } - } - - if (!cuRes.ok) { - console.warn(`[ClickUp Subtask] Failed to create subtask under ${sourceTask.clickupTaskId}:`, errBody); - clickupWarning = `Could not create ClickUp subtask: ${errBody}`; - } - } - - if (cuRes.ok) { - const cuSubtask = await cuRes.json(); - newTask.clickupTaskId = cuSubtask.id; // Distinct subtask ClickUp task ID! - newTask.clickupUrl = cuSubtask.url; - newTask.clickupListId = listId; - clickupSubtaskCreated = true; - console.log(`[ClickUp Subtask] Created subtask ${cuSubtask.id} under parent ${sourceTask.clickupTaskId} assigned to ${targetUser.name}`); - - appendAuditLog({ - category: 'task', - action: 'clickup_subtask_created', - actor: { ip: req.ip, id: caller?.id, name: actorDisplayName, email: caller?.email }, - targetId: newTask.id, - targetType: 'task', - details: `Created ClickUp subtask #${cuSubtask.id} under parent #${sourceTask.clickupTaskId} assigned to ${targetUser.name}`, - metadata: { - parentClickupTaskId: sourceTask.clickupTaskId, - subtaskClickupTaskId: cuSubtask.id, - targetClickupUserId, - newTaskId: newTask.id, - }, - }); - } - } catch (cuErr: any) { - console.warn('[ClickUp Subtask] Network error creating subtask:', cuErr); - clickupWarning = cuErr.message || 'Network error reaching ClickUp'; - } - } else { - clickupWarning = 'Could not resolve ClickUp list ID for subtask.'; - } - } else { - clickupWarning = 'No ClickUp API key configured in workspace to create subtask.'; - } - } - // Save and broadcast subtask card in ZenFlow store.tasks.push(newTask); saveStore(store); - dbSaveTask(newTask).catch(e => console.error('Firestore save subtask err:', e)); + broadcastEvent('task_created', newTask); // Update parent task activity log @@ -2550,7 +1266,7 @@ async function startServer() { actorName: actorDisplayName, details: `Subtask delegated to ${targetUser.name}'s board by ${actorDisplayName}`, }); - dbSaveTask(sourceTask).catch(e => console.error('Firestore save parent err:', e)); + broadcastEvent('task_updated', sourceTask); appendAuditLog({ @@ -2565,32 +1281,19 @@ async function startServer() { metadata: { sourceTaskId: sourceTask.id, newTaskId: newTask.id, - clickupParentTaskId: sourceTask.clickupTaskId, - subtaskClickupTaskId: newTask.clickupTaskId, + targetBoardId: targetUser.creativeDirectorId || targetUser.id, }, }); res.status(201).json({ task: newTask, - clickupSubtaskCreated, - warning: clickupWarning, - message: clickupSubtaskCreated - ? `Subtask created under "${sourceTask.title}" on ${targetUser.name}'s board and synced with ClickUp.` - : `Subtask created on ${targetUser.name}'s board.`, + message: `Subtask created on ${targetUser.name}'s board.`, }); }); // API: Update a task app.put('/api/tasks/:id', (req: Request, res: Response) => { - const { id } = req.params; - const taskIndex = store.tasks.findIndex(t => t.id === id); - - if (taskIndex === -1) { - return res.status(404).json({ error: 'Task not found' }); - } - - const currentTask = store.tasks[taskIndex]; const { title, description, @@ -2604,17 +1307,15 @@ async function startServer() { inProgressStartedAt: reqStartedAt, adjustmentReason, actorName, - clickupTaskId, - clickupFolderId, - clickupFolderName, - clickupListId, - clickupListName, - clickupSpaceId, - clickupUrl, - clickupTaskType, - clickupTaskTypeId, - clickupTaskTypeFieldId, } = req.body; + const { id } = req.params; + const taskIndex = store.tasks.findIndex(t => t.id === id); + + if (taskIndex === -1) { + return res.status(404).json({ error: 'Task not found' }); + } + + const currentTask = store.tasks[taskIndex]; if (title !== undefined) { const cleanTitle = sanitizeString(title); @@ -2758,23 +1459,13 @@ async function startServer() { completedAt, inProgressStartedAt, inProgressDurationMs, - clickupTaskId: clickupTaskId !== undefined ? (clickupTaskId ? sanitizeString(clickupTaskId) : undefined) : currentTask.clickupTaskId, - clickupFolderId: clickupFolderId !== undefined ? (clickupFolderId ? sanitizeString(clickupFolderId) : undefined) : currentTask.clickupFolderId, - clickupFolderName: clickupFolderName !== undefined ? (clickupFolderName ? sanitizeString(clickupFolderName) : undefined) : currentTask.clickupFolderName, - clickupListId: clickupListId !== undefined ? (clickupListId ? sanitizeString(clickupListId) : undefined) : currentTask.clickupListId, - clickupListName: clickupListName !== undefined ? (clickupListName ? sanitizeString(clickupListName) : undefined) : currentTask.clickupListName, - clickupSpaceId: clickupSpaceId !== undefined ? (clickupSpaceId ? sanitizeString(clickupSpaceId) : undefined) : currentTask.clickupSpaceId, - clickupUrl: clickupUrl !== undefined ? (clickupUrl ? sanitizeString(clickupUrl) : undefined) : currentTask.clickupUrl, - clickupTaskType: clickupTaskType !== undefined ? (clickupTaskType ? sanitizeString(clickupTaskType) : undefined) : currentTask.clickupTaskType, - clickupTaskTypeId: clickupTaskTypeId !== undefined ? (clickupTaskTypeId ? sanitizeString(clickupTaskTypeId) : undefined) : currentTask.clickupTaskTypeId, - clickupTaskTypeFieldId: clickupTaskTypeFieldId !== undefined ? (clickupTaskTypeFieldId ? sanitizeString(clickupTaskTypeFieldId) : undefined) : currentTask.clickupTaskTypeFieldId, + updatedAt: new Date().toISOString(), activityLog: activityEntries.slice(0, 15), }; store.tasks[taskIndex] = updatedTask; saveStore(store); - dbSaveTask(updatedTask).catch(e => console.error('Firestore task update err:', e)); broadcastEvent('task_updated', updatedTask); appendAuditLog({ @@ -2789,17 +1480,6 @@ async function startServer() { metadata: { taskId: updatedTask.id, title: updatedTask.title }, }); - // Live Push to ClickUp - const taskUser = store.users.find(u => u.id === updatedTask.userId); - const callerApiKey = (req.headers['x-clickup-api-key'] as string) || (req.body.clickupApiKey as string); - const callerId = (req.headers['x-caller-user-id'] as string) || (req.body.callerUserId as string); - const syncToken = (taskUser?.clickupApiKey || callerApiKey || store.users.find(u => u.clickupApiKey)?.clickupApiKey || '').trim(); - if ((updatedTask.clickupTaskId || updatedTask.clickupListId) && syncToken) { - syncTaskToClickUp(updatedTask, syncToken, taskUser, callerId).catch(e => - console.error('[ClickUp] Post-update sync err:', e) - ); - } - res.json(updatedTask); }); @@ -2814,7 +1494,6 @@ async function startServer() { const removed = store.tasks.splice(taskIndex, 1)[0]; saveStore(store); - dbDeleteTask(removed.id).catch(e => console.error('Firestore task delete err:', e)); broadcastEvent('task_deleted', { id: removed.id, userId: removed.userId }); appendAuditLog({ @@ -2824,7 +1503,7 @@ async function startServer() { targetId: removed.id, targetType: 'task', details: `Task "${removed.title}" (ID: ${removed.id}) deleted`, - metadata: { userId: removed.userId, clickupTaskId: removed.clickupTaskId }, + metadata: { userId: removed.userId, }, }); res.json({ success: true, id: removed.id }); }); @@ -2847,13 +1526,12 @@ async function startServer() { } const modifiedTasks: Task[] = []; - const clickupTasksToSync: Task[] = []; for (const update of updates) { if (!update || typeof update !== 'object' || !update.id) continue; const task = taskMap.get(update.id); if (task) { - let hasClickupAttributeChanged = false; + if (!task.activityLog) task.activityLog = []; if (update.userId && typeof update.userId === 'string' && userMap.has(update.userId) && update.userId !== task.userId) { @@ -2868,7 +1546,6 @@ async function startServer() { details: `Reassigned from ${oldUser} to ${newUser}`, }); task.userId = update.userId; - hasClickupAttributeChanged = true; } if (update.status && ['pipeline', 'retainer', 'todo', 'in_progress', 'in_review', 'done', 'archived'].includes(update.status)) { @@ -2902,7 +1579,6 @@ async function startServer() { } task.status = update.status; - hasClickupAttributeChanged = true; } } @@ -2922,7 +1598,6 @@ async function startServer() { details: 'Deadline removed upon moving to pipeline', }); task.dueDate = undefined; - hasClickupAttributeChanged = true; } } else if (update.dueDate !== undefined) { const newDate = update.dueDate ? sanitizeString(update.dueDate) : undefined; @@ -2936,7 +1611,6 @@ async function startServer() { details: newDate ? `Due date set to ${newDate}` : 'Deadline removed', }); task.dueDate = newDate; - hasClickupAttributeChanged = true; } } @@ -2947,710 +1621,38 @@ async function startServer() { task.updatedAt = new Date().toISOString(); modifiedTasks.push(task); - if (hasClickupAttributeChanged && (task.clickupTaskId || task.clickupListId)) { - clickupTasksToSync.push(task); - } } } saveStore(store); if (modifiedTasks.length > 0) { - dbBatchSaveTasks(modifiedTasks).catch(e => console.error('Firestore batch reorder err:', e)); + } broadcastEvent('tasks_reordered', modifiedTasks); - // Live push status/assignee/deadline changed tasks to ClickUp (skip pure internal order updates) - const callerApiKey = (req.headers['x-clickup-api-key'] as string) || (req.body.clickupApiKey as string); - const callerId = (req.headers['x-caller-user-id'] as string) || (req.body.callerUserId as string); - for (const modTask of clickupTasksToSync) { - const modUser = store.users.find(u => u.id === modTask.userId); - const syncToken = (modUser?.clickupApiKey || callerApiKey || store.users.find(u => u.clickupApiKey)?.clickupApiKey || '').trim(); - if (syncToken) { - syncTaskToClickUp(modTask, syncToken, modUser, callerId).catch(e => - console.error('[ClickUp] Reorder sync err:', e) - ); - } - } - res.json({ success: true, tasks: modifiedTasks }); }); - // ========================================== - // CLICKUP INTEGRATION ENDPOINTS - // ========================================== - - // In-memory sliding TTL cache for ClickUp proxy endpoints (120s TTL) - interface ClickupCacheEntry { - data: any; - expiresAt: number; - } - const clickupCache = new Map(); - const CLICKUP_CACHE_TTL_MS = 120 * 1000; - - function getFromClickupCache(key: string): any | null { - const entry = clickupCache.get(key); - if (!entry) return null; - if (Date.now() > entry.expiresAt) { - clickupCache.delete(key); - return null; - } - return entry.data; - } - - function setClickupCache(key: string, data: any, ttlMs: number = CLICKUP_CACHE_TTL_MS) { - clickupCache.set(key, { data, expiresAt: Date.now() + ttlMs }); - if (clickupCache.size > 200) { - const now = Date.now(); - for (const [k, e] of clickupCache.entries()) { - if (now > e.expiresAt) clickupCache.delete(k); - } - } - } - - function invalidateClickupCache(prefix?: string) { - if (!prefix) { - clickupCache.clear(); - return; - } - for (const k of clickupCache.keys()) { - if (k.includes(prefix)) clickupCache.delete(k); - } - } - - // API: Verify Personal ClickUp API Token & retrieve teams - app.post('/api/clickup/verify', async (req: Request, res: Response) => { - const { apiKey } = req.body; - if (!apiKey || typeof apiKey !== 'string') { - return res.status(400).json({ error: 'ClickUp API key is required' }); - } - - try { - const cleanKey = apiKey.trim(); - const userRes = await fetch('https://api.clickup.com/api/v2/user', { - headers: { Authorization: cleanKey }, - }); - - if (!userRes.ok) { - return res.status(401).json({ error: 'Invalid or unauthorized ClickUp API Token' }); - } - - const userData = await userRes.json(); - const teamRes = await fetch('https://api.clickup.com/api/v2/team', { - headers: { Authorization: cleanKey }, - }); - const teamData = teamRes.ok ? await teamRes.json() : { teams: [] }; - - res.json({ - valid: true, - user: userData.user, - teams: teamData.teams || [], - }); - } catch (err: any) { - console.error('[ClickUp] Verify error:', err); - res.status(500).json({ error: err.message || 'Error communicating with ClickUp API' }); - } - }); - - // API: Get Spaces for a ClickUp Workspace/Team - app.get('/api/clickup/spaces', async (req: Request, res: Response) => { - const apiKey = (req.headers['x-clickup-api-key'] as string) || (req.query.apiKey as string); - const teamId = req.query.teamId as string; - - if (!apiKey) { - return res.status(400).json({ error: 'ClickUp API key is required' }); - } - - const cleanKey = apiKey.trim(); - const cacheKey = `spaces:${cleanKey.slice(-10)}:${teamId || 'default'}`; - const cached = getFromClickupCache(cacheKey); - if (cached) { - return res.json(cached); - } - - try { - let targetTeamId = teamId; - - if (!targetTeamId) { - const teamRes = await fetch('https://api.clickup.com/api/v2/team', { - headers: { Authorization: cleanKey }, - }); - if (teamRes.ok) { - const teamData = await teamRes.json(); - targetTeamId = teamData.teams?.[0]?.id; - } - } - - if (!targetTeamId) { - return res.json({ spaces: [] }); - } - - const spacesRes = await fetch(`https://api.clickup.com/api/v2/team/${targetTeamId}/space`, { - headers: { Authorization: cleanKey }, - }); - - if (!spacesRes.ok) { - return res.status(spacesRes.status).json({ error: 'Failed to retrieve spaces from ClickUp' }); - } - - const data = await spacesRes.json(); - const result = { spaces: data.spaces || [], teamId: targetTeamId }; - setClickupCache(cacheKey, result); - res.json(result); - } catch (err: any) { - console.error('[ClickUp] Spaces fetch error:', err); - res.status(500).json({ error: err.message || 'Error fetching ClickUp spaces' }); - } - }); - - // API: Get Workspace Members from ClickUp - app.get('/api/clickup/members', async (req: Request, res: Response) => { - let apiKey = (req.headers['x-clickup-api-key'] as string) || (req.query.apiKey as string); - - if (!apiKey) { - const userWithKey = store.users.find(u => u.clickupApiKey); - if (userWithKey?.clickupApiKey) { - apiKey = userWithKey.clickupApiKey; - } - } - - if (!apiKey) { - return res.status(400).json({ error: 'ClickUp API key is required' }); - } - - const cleanKey = apiKey.trim(); - const cacheKey = `members:${cleanKey.slice(-10)}`; - const cached = getFromClickupCache(cacheKey); - if (cached) { - return res.json(cached); - } - - try { - const teamRes = await fetch('https://api.clickup.com/api/v2/team', { - headers: { Authorization: cleanKey }, - }); - - if (!teamRes.ok) { - return res.status(teamRes.status).json({ error: 'Failed to retrieve teams from ClickUp' }); - } - - const teamData = await teamRes.json(); - const memberMap = new Map(); - - for (const team of teamData.teams || []) { - for (const m of team.members || []) { - if (m?.user && m.user.id) { - const uId = String(m.user.id); - if (!memberMap.has(uId)) { - memberMap.set(uId, { - id: uId, - username: m.user.username || m.user.email?.split('@')[0] || 'ClickUp User', - email: m.user.email || '', - color: m.user.color, - profilePicture: m.user.profilePicture, - initials: m.user.initials, - }); - } - } - } - } - - const result = { members: Array.from(memberMap.values()) }; - setClickupCache(cacheKey, result); - res.json(result); - } catch (err: any) { - console.error('[ClickUp] Members fetch error:', err); - res.status(500).json({ error: err.message || 'Error fetching ClickUp members' }); - } - }); - - // API: Get Folders and Folderless Lists for a ClickUp Space - app.get('/api/clickup/folders-and-lists', async (req: Request, res: Response) => { - const apiKey = (req.headers['x-clickup-api-key'] as string) || (req.query.apiKey as string); - const spaceId = req.query.spaceId as string; - - if (!apiKey || !spaceId) { - return res.status(400).json({ error: 'apiKey and spaceId are required' }); - } - - const cleanKey = apiKey.trim(); - const cacheKey = `folders-lists:${cleanKey.slice(-10)}:${spaceId}`; - const cached = getFromClickupCache(cacheKey); - if (cached) { - return res.json(cached); - } - - try { - const [foldersRes, listsRes] = await Promise.all([ - fetch(`https://api.clickup.com/api/v2/space/${spaceId}/folder`, { - headers: { Authorization: cleanKey }, - }), - fetch(`https://api.clickup.com/api/v2/space/${spaceId}/list`, { - headers: { Authorization: cleanKey }, - }), - ]); - - const foldersData = foldersRes.ok ? await foldersRes.json() : { folders: [] }; - const listsData = listsRes.ok ? await listsRes.json() : { lists: [] }; - - const result = { - folders: foldersData.folders || [], - folderlessLists: listsData.lists || [], - }; - setClickupCache(cacheKey, result); - res.json(result); - } catch (err: any) { - console.error('[ClickUp] Folders & Lists fetch error:', err); - res.status(500).json({ error: err.message || 'Error fetching folders and lists' }); - } - }); - - // API: Get Custom Fields (specifically "Task Type") from ClickUp - app.get('/api/clickup/custom-fields', async (req: Request, res: Response) => { - let apiKey = (req.headers['x-clickup-api-key'] as string) || (req.query.apiKey as string); - const listId = req.query.listId as string; - const spaceId = req.query.spaceId as string; - const folderId = req.query.folderId as string; - - if (!apiKey) { - const userWithKey = store.users.find(u => u.clickupApiKey); - if (userWithKey?.clickupApiKey) { - apiKey = userWithKey.clickupApiKey; - } - } - - if (!apiKey) { - return res.status(400).json({ error: 'ClickUp API key is required' }); - } - - const cleanKey = apiKey.trim(); - const cacheKey = `cf:${cleanKey.slice(-10)}:${listId || spaceId || folderId}`; - const cached = getFromClickupCache(cacheKey); - if (cached) { - return res.json(cached); - } - - try { - let url = ''; - if (listId) { - url = `https://api.clickup.com/api/v2/list/${listId}/field`; - } else if (spaceId) { - url = `https://api.clickup.com/api/v2/space/${spaceId}/field`; - } else if (folderId) { - url = `https://api.clickup.com/api/v2/folder/${folderId}/field`; - } else { - return res.status(400).json({ error: 'listId, spaceId, or folderId is required' }); - } - - const response = await fetch(url, { - headers: { Authorization: cleanKey }, - }); - - if (!response.ok) { - return res.status(response.status).json({ error: 'Failed to fetch custom fields from ClickUp' }); - } - - const data = await response.json(); - const fields = data.fields || []; - - // Find the "Task Type" field (case-insensitive) - const taskTypeField = fields.find((f: any) => - (f.name || '').toLowerCase().trim() === 'task type' || (f.name || '').toLowerCase().includes('task type') - ); - - const options = taskTypeField?.type_config?.options || []; - - const result = { - fields, - taskTypeField: taskTypeField ? { - id: taskTypeField.id, - name: taskTypeField.name, - type: taskTypeField.type, - options, - } : null, - options, - }; - setClickupCache(cacheKey, result); - res.json(result); - } catch (err: any) { - console.error('[ClickUp] Custom fields error:', err); - res.status(500).json({ error: err.message || 'Error fetching custom fields' }); - } - }); - - // API: Create a new List in ClickUp (under a folder or folderless under a space) - app.post('/api/clickup/lists', async (req: Request, res: Response) => { - const { apiKey, spaceId, folderId, name } = req.body; - - if (!apiKey || !name || (!spaceId && !folderId)) { - return res.status(400).json({ error: 'apiKey, name, and spaceId or folderId are required' }); - } - - try { - const cleanKey = apiKey.trim(); - const cleanName = sanitizeString(name); - const url = folderId - ? `https://api.clickup.com/api/v2/folder/${folderId}/list` - : `https://api.clickup.com/api/v2/space/${spaceId}/list`; - - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: cleanKey, - }, - body: JSON.stringify({ name: cleanName }), - }); - - if (spaceId) invalidateClickupCache(spaceId); - - if (!response.ok) { - const text = await response.text(); - return res.status(response.status).json({ error: text }); - } - - const list = await response.json(); - res.status(201).json({ list }); - } catch (err: any) { - console.error('[ClickUp] Create list error:', err); - res.status(500).json({ error: err.message || 'Error creating list in ClickUp' }); - } - }); - - // API: Sync tasks for a specific user with ClickUp - app.post('/api/clickup/sync-user-tasks', async (req: Request, res: Response) => { - const { userId, apiKey } = req.body; - if (!userId) { - return res.status(400).json({ error: 'userId is required' }); - } - - const user = store.users.find(u => u.id === userId); - const callerId = (req.body.callerUserId as string) || (req.headers['x-caller-user-id'] as string) || ''; - const callerToken = ((req.headers['x-clickup-api-key'] as string) || apiKey || '').trim(); - const token = (user?.clickupApiKey || callerToken || '').trim(); - - if (!token) { - return res.status(400).json({ error: 'ClickUp API key is not connected for this user' }); - } - - const userTasks = store.tasks.filter(t => t.userId === userId); - let syncedCount = 0; - let archivedCount = 0; - const modifiedTasks: Task[] = []; - - for (const task of userTasks) { - // 1. Archive sync exception: Check if task in done is completed on ClickUp - if (task.status === 'done' && task.clickupTaskId) { - try { - const cRes = await fetch(`https://api.clickup.com/api/v2/task/${task.clickupTaskId}`, { - headers: { Authorization: token }, - }); - if (cRes.ok) { - const cTask = await cRes.json(); - const cuStatus = (cTask.status?.status || '').toLowerCase(); - const cuType = (cTask.status?.type || '').toLowerCase(); - - if (cuStatus === 'complete' || cuStatus === 'closed' || cuType === 'closed') { - task.status = 'archived'; - task.updatedAt = new Date().toISOString(); - if (!task.activityLog) task.activityLog = []; - task.activityLog.unshift({ - id: `act-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`, - timestamp: new Date().toISOString(), - action: 'status_change', - from: 'done', - to: 'archived', - details: 'Archived via ClickUp task completion sync', - }); - if (task.activityLog.length > 15) task.activityLog = task.activityLog.slice(0, 15); - archivedCount++; - modifiedTasks.push(task); - continue; - } - } - } catch (err) { - console.warn(`[ClickUp Sync] Error checking task ${task.id} status:`, err); - } - } - - // 2. Push active tasks with assigned list to ClickUp - if (task.clickupListId) { - await syncTaskToClickUp(task, callerToken || token, user, callerId); - syncedCount++; - } - } - - if (modifiedTasks.length > 0) { - saveStore(store); - dbBatchSaveTasks(modifiedTasks).catch(e => console.error('Firestore batch save err:', e)); - broadcastEvent('tasks_reordered', modifiedTasks); - } - - res.json({ - success: true, - syncedCount, - archivedCount, - message: `Synced ${syncedCount} task(s), archived ${archivedCount} completed task(s).`, - }); - }); - - // ========================================================================= - // ClickUp Inbound Webhook Listener & Registration Endpoints - // ========================================================================= - - // API: Inbound ClickUp Webhook Listener (zero-friction status, assignee, and task sync) - app.post('/api/clickup/webhook', (req: Request, res: Response) => { - const registration = webhookRegistry.get(req.body?.webhook_id); - if (!validSignature((req as Request & { rawBody?: Buffer }).rawBody, req.get('x-signature'), registration?.secret)) { - return res.status(401).json({ error: 'Invalid webhook signature' }); - } - res.status(200).json({ received: true }); - - webhookEventsCount++; - lastWebhookEventAt = new Date().toISOString(); - lastWebhookAction = req.body.event || 'webhook_received'; - - const rawTaskId = req.body.task_id || req.body.taskId || req.body.task?.id; - const taskId = typeof rawTaskId === 'string' ? rawTaskId.trim() : ''; - const eventType = req.body.event || 'unknown'; - const historyItems = Array.isArray(req.body.history_items) ? req.body.history_items : []; - - // 2. Asynchronously process payload without blocking HTTP connection - (async () => { - try { - await processClickupWebhookEvent({ - taskId, - eventType, - historyItems, - rawBody: req.body, - ip: req.ip, - }); - } catch (err) { - console.error('[ClickUp Webhook Error]:', err); - } - })(); - }); - - // API: Register ClickUp Webhook for Workspace Team - app.post('/api/clickup/webhook/register', async (req: Request, res: Response) => { - try { - let apiKey = (req.headers['x-clickup-api-key'] as string) || (req.body.apiKey as string); - if (!apiKey) { - const u = store.users.find(usr => usr.clickupApiKey); - if (u?.clickupApiKey) apiKey = u.clickupApiKey; - } - - if (!apiKey) { - return res.status(400).json({ error: 'ClickUp API key is required to register webhook' }); - } - - const cleanKey = apiKey.trim(); - - // Retrieve team id if not provided - let teamId = req.body.teamId; - if (!teamId) { - const teamRes = await fetch('https://api.clickup.com/api/v2/team', { - headers: { Authorization: cleanKey }, - }); - if (teamRes.ok) { - const tData = await teamRes.json(); - teamId = tData.teams?.[0]?.id; - } - } - - if (!teamId) { - return res.status(400).json({ error: 'Failed to retrieve ClickUp team ID' }); - } - - // Determine webhook endpoint URL - const host = req.get('host') || 'localhost:3000'; - const proto = req.headers['x-forwarded-proto'] || req.protocol || 'http'; - const endpoint = req.body.endpoint || `${proto}://${host}/api/clickup/webhook`; - - const webhookPayload = { - endpoint, - events: [ - 'taskCreated', - 'taskUpdated', - 'taskStatusUpdated', - 'taskAssigneeUpdated', - 'taskDueDateUpdated', - 'taskDeleted', - 'taskTimeTrackedUpdated', - 'taskMoved', - ], - }; - - const cuRes = await fetch(`https://api.clickup.com/api/v2/team/${teamId}/webhook`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: cleanKey, - }, - body: JSON.stringify(webhookPayload), - }); - - const responseData = await cuRes.json(); - if (!cuRes.ok) { - return res.status(cuRes.status).json({ - error: responseData.err || responseData.error || 'Failed to register webhook in ClickUp', - details: responseData, - }); - } - - const registration = responseData.webhook || responseData; - if (typeof registration.id !== 'string' || typeof registration.secret !== 'string' || !registration.secret) { - return res.status(502).json({ error: 'ClickUp did not return a webhook signing secret' }); - } - await webhookRegistry.save({ id: registration.id, secret: registration.secret, endpoint }, adminDb); - registeredWebhookId = registration.id; - activeWebhookEndpoint = endpoint; - - appendAuditLog({ - category: 'webhook', - action: 'clickup_webhook_registered', - actor: { ip: req.ip }, - targetId: registeredWebhookId || 'webhook', - targetType: 'webhook', - details: `ClickUp webhook successfully registered with endpoint ${endpoint}`, - metadata: { teamId, endpoint, webhookId: registeredWebhookId }, - }); - - res.json({ - success: true, - webhookId: registeredWebhookId, - endpoint, - message: 'ClickUp real-time webhook registered successfully.', - }); - } catch (err: any) { - console.error('[ClickUp Webhook Register Error]:', err); - res.status(500).json({ error: err.message || 'Internal server error registering webhook' }); - } - }); - - // API: Get ClickUp Webhook Status - app.get('/api/clickup/webhook/status', (req: Request, res: Response) => { - const host = req.get('host') || 'localhost:3000'; - const proto = req.headers['x-forwarded-proto'] || req.protocol || 'http'; - const defaultEndpoint = `${proto}://${host}/api/clickup/webhook`; - - res.json({ - listening: true, - registered: Boolean(registeredWebhookId), - webhookId: registeredWebhookId, - endpointUrl: activeWebhookEndpoint || defaultEndpoint, - totalEventsCount: webhookEventsCount, - lastEventAt: lastWebhookEventAt, - lastEventAction: lastWebhookAction, - supportedEvents: [ - 'taskCreated', - 'taskUpdated', - 'taskStatusUpdated', - 'taskAssigneeUpdated', - 'taskDueDateUpdated', - 'taskDeleted', - 'taskTimeTrackedUpdated', - 'taskMoved', - ], - }); - }); - - // API: Delete ClickUp Webhook - app.delete('/api/clickup/webhook/:id', async (req: Request, res: Response) => { - try { - const { id } = req.params; - let apiKey = (req.headers['x-clickup-api-key'] as string) || (req.query.apiKey as string); - if (!apiKey) { - const u = store.users.find(usr => usr.clickupApiKey); - if (u?.clickupApiKey) apiKey = u.clickupApiKey; - } - if (!apiKey) return res.status(400).json({ error: 'ClickUp API key required' }); - - const cuRes = await fetch(`https://api.clickup.com/api/v2/webhook/${id}`, { - method: 'DELETE', - headers: { Authorization: apiKey.trim() }, - }); - if (cuRes.ok) { - await webhookRegistry.remove(id, adminDb); - if (registeredWebhookId === id) { - registeredWebhookId = null; - activeWebhookEndpoint = null; - } - appendAuditLog({ - category: 'webhook', - action: 'clickup_webhook_deleted', - actor: { ip: req.ip }, - targetId: id, - targetType: 'webhook', - details: `ClickUp webhook ${id} deleted`, - }); - return res.json({ success: true, message: `Webhook ${id} deleted` }); - } - const data = await cuRes.json(); - res.status(cuRes.status).json({ error: data.err || 'Failed to delete webhook from ClickUp' }); - } catch (err: any) { - res.status(500).json({ error: err.message || 'Error deleting webhook' }); - } - }); - - // ========================================================================= - // Compliance Activity & Audit Stream Endpoints (SOC2 Ready) - // ========================================================================= - // API: Get recent compliance audit log records (in-memory sliding cache) - app.get('/api/audit/logs', (req: Request, res: Response) => { - const limit = Math.min(200, Math.max(1, parseInt(req.query.limit as string, 10) || 50)); - res.setHeader('Cache-Control', 'no-store'); - res.json({ - totalInMemory: recentAuditLogs.length, - limit, - logs: recentAuditLogs.slice(0, limit), - }); + app.get('/api/audit/logs', async (req: Request, res: Response, next) => { + try { + const limit = Math.min(200, Math.max(1, parseInt(req.query.limit as string, 10) || 50)); + res.json({ limit, logs: await workspace.recentAudit(limit) }); + } catch (error) { next(error); } }); - - // API: Download complete append-only JSON-lines compliance audit stream - app.get('/api/audit/download', (_req: Request, res: Response) => { + app.get('/api/audit/download', async (_req: Request, res: Response) => { res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8'); res.setHeader('Content-Disposition', 'attachment; filename="zenflow-compliance-audit.jsonl"'); res.setHeader('Cache-Control', 'no-store'); - - if (fs.existsSync(AUDIT_LOG_FILE)) { - const stream = fs.createReadStream(AUDIT_LOG_FILE); - stream.on('error', (err) => { - console.error('[Audit Download Stream Error]:', err); - if (!res.headersSent) { - res.status(500).end(); - } - stream.destroy(); - }); - res.on('close', () => { - stream.destroy(); - }); - stream.pipe(res); - } else { - const content = [...recentAuditLogs].reverse().map(l => JSON.stringify(l)).join('\n'); - res.send(content); - } + try { await workspace.downloadAudit(res); } + catch (error) { console.error('[Audit export failed]', error); res.destroy(); } }); - - // API: Get compliance audit statistics & storage telemetry - app.get('/api/audit/stats', (_req: Request, res: Response) => { - let fileSize = 0; + app.get('/api/audit/stats', async (_req: Request, res: Response, next) => { try { - if (fs.existsSync(AUDIT_LOG_FILE)) { - const stat = fs.statSync(AUDIT_LOG_FILE); - fileSize = stat.size; - } - } catch {} - - res.json({ - filePath: AUDIT_LOG_FILE, - fileSizeFormatted: `${(fileSize / 1024).toFixed(1)} KB`, - fileSizeBytes: fileSize, - inMemoryCount: recentAuditLogs.length, - lastRecordedAt: recentAuditLogs[0]?.timestamp || null, - status: 'active_streaming', - }); + const count = await adminDb.collection('compliance_audit_logs').count().get(); + res.json({ storage: 'firestore', totalRecords: count.data().count, status: 'active' }); + } catch (error) { next(error); } }); // API: Firestore status & health check @@ -3668,50 +1670,6 @@ async function startServer() { }); }); - // API: Submit or update Firebase Service Account Key - app.post('/api/firestore/credentials', firestoreLimiter, async (req: Request, res: Response) => { - try { - const { serviceAccountKey } = req.body; - if (!serviceAccountKey) { - return res.status(400).json({ success: false, message: 'serviceAccountKey is required' }); - } - - let parsed: any; - if (typeof serviceAccountKey === 'string') { - parsed = JSON.parse(serviceAccountKey); - } else { - parsed = serviceAccountKey; - } - - if (!parsed.project_id || !parsed.private_key || !parsed.client_email) { - return res.status(400).json({ - success: false, - message: 'Invalid service account JSON: missing project_id, private_key, or client_email', - }); - } - - const keyPath = path.join(process.cwd(), 'serviceAccountKey.json'); - await fs.promises.writeFile(keyPath, JSON.stringify(parsed, null, 2), 'utf-8'); - - const adminApps = await import('firebase-admin/app'); - const existingApp = adminApps.getApps().find(app => app.name === 'zenflow-firestore'); - if (existingApp) await adminApps.deleteApp(existingApp); - initPromise = null; - adminDb = null; - await initFirestore(); - if (!adminDb) return res.status(503).json({ success: false, message: 'Firebase Admin initialization failed' }); - await syncFromFirestore(); - await webhookRegistry.load(adminDb); - - res.json({ - success: true, - message: `Successfully connected to Firestore (Project: ${parsed.project_id}) and saved all workspace data.`, - }); - } catch (err: any) { - res.status(500).json({ success: false, message: err.message || 'Failed to process credentials' }); - } - }); - // API: Force manual synchronization with Firestore app.post('/api/firestore/sync', firestoreLimiter, async (_req: Request, res: Response) => { try { @@ -3730,7 +1688,7 @@ async function startServer() { } }); - // API: Server-Sent Events (SSE) for zero-friction real-time sync across all connected browser tabs & devices + // API: Server-Sent Events (SSE) for real-time sync across connected browsers app.get('/api/events', (req: Request, res: Response) => { // Prevent memory leaks: prune oldest clients if limit exceeded if (clients.length >= MAX_SSE_CLIENTS) { @@ -3783,6 +1741,8 @@ async function startServer() { }); }); + app.use('/api', (_req, res) => { res.status(404).json({ error: 'API route not found' }); }); + const serveStaticFiles = () => { const distPath = path.join(process.cwd(), 'dist'); app.use( @@ -3834,7 +1794,6 @@ async function startServer() { // Graceful shutdown traps for cloud containers (Railway, Cloud Run, Nixpacks) const handleShutdown = (signal: string) => { console.log(`[Process] Received ${signal}. Executing zero-loss graceful shutdown...`); - flushStoreSync(); // Cleanly close real-time SSE streams clients.forEach(c => { @@ -3863,4 +1822,4 @@ async function startServer() { process.on('SIGINT', () => handleShutdown('SIGINT')); } -startServer(); +startServer().catch(error => { console.error('[Startup failed]', error); process.exit(1); }); diff --git a/server/security.ts b/server/security.ts index 1bdc06e..6d907d1 100644 --- a/server/security.ts +++ b/server/security.ts @@ -1,10 +1,9 @@ import type { Request, Response, NextFunction } from 'express'; -import { createHmac, timingSafeEqual } from 'node:crypto'; export const SUPERADMIN_EMAIL = 'kiran.s@zensciences.com'; export const SESSION_COOKIE = 'zenflow_identity'; export interface Member { - id: string; email: string; isCreativeDirector?: boolean; creativeDirectorId?: string; clickupApiKey?: string; + id: string; email: string; isCreativeDirector?: boolean; creativeDirectorId?: string; } export interface Identity { email?: string; email_verified?: boolean; exp: number; firebase?: { sign_in_provider?: string } } export const isSuperadmin = (user: Member) => user.email.toLowerCase() === SUPERADMIN_EMAIL; @@ -16,10 +15,9 @@ export const canEdit = (caller: Member, owner: Member | undefined) => Boolean(ow export function publicMember(user: any) { const result: Record = {}; for (const key of ['id', 'name', 'email', 'role', 'avatarColor', 'createdAt', 'order', 'isCreativeDirector', - 'creativeDirectorId', 'selectedClickupSpaceId', 'selectedClickupSpaceName', 'clickupUserId', 'clickupUsername']) { + 'creativeDirectorId']) { if (user[key] !== undefined) result[key] = user[key]; } - result.clickupConnected = Boolean(user.clickupApiKey || user.clickupConnected); return result; } export function redactPayload(value: any): any { @@ -33,10 +31,6 @@ export function redactPayload(value: any): any { return Object.fromEntries(Object.entries(value).filter(([key]) => !['secret', 'private_key', 'clickupApiKey'].includes(key)) .map(([key, item]) => [key, redactPayload(item)])); } -export function validSignature(raw: Buffer | undefined, signature: unknown, secret: string | undefined): boolean { - if (!raw || !secret || typeof signature !== 'string' || !/^[a-f0-9]{64}$/i.test(signature)) return false; - return timingSafeEqual(createHmac('sha256', secret).update(raw).digest(), Buffer.from(signature, 'hex')); -} export function readCookie(req: Request): string { const part = req.headers.cookie?.split(';').find(item => item.trim().startsWith(`${SESSION_COOKIE}=`)); try { return part ? decodeURIComponent(part.trim().slice(SESSION_COOKIE.length + 1)) : ''; } catch { return ''; } @@ -54,7 +48,7 @@ export function createApiSecurity(options: { }) { return async (req: Request, res: Response, next: NextFunction) => { const routePath = req.path.replace(/\/+$/, '') || '/'; - if ((req.method === 'GET' && routePath === '/health') || (req.method === 'POST' && routePath === '/clickup/webhook')) return next(); + if ((req.method === 'GET' && routePath === '/health')) return next(); const bearer = req.get('authorization')?.match(/^Bearer (\S+)$/)?.[1]; const token = bearer || readCookie(req); if (!token) return res.status(401).json({ error: 'Google authentication required' }); @@ -78,8 +72,7 @@ export function createApiSecurity(options: { req.body = body; if (routePath.startsWith('/audit/') && !manager) return denied(); - if ((routePath.startsWith('/firestore/') || routePath === '/clickup/webhook/register' || - (req.method === 'DELETE' && routePath.startsWith('/clickup/webhook/'))) && req.method !== 'GET' && !superadmin) return denied(); + if (routePath.startsWith('/firestore/') && req.method !== 'GET' && !superadmin) return denied(); if (routePath === '/auth/login' || routePath === '/auth/verify-email') body.email = caller.email; if (routePath === '/users/remap-tasks' && !superadmin) return denied(); @@ -88,7 +81,6 @@ export function createApiSecurity(options: { const existing = store.users.find(user => user.email.toLowerCase() === String(body.email || '').toLowerCase()); if (!superadmin && (body.isCreativeDirector || (existing && (!edit(existing.id) || existing.isCreativeDirector)))) return denied(); if (!superadmin) body.creativeDirectorId = caller.id; - if (body.clickupApiKey !== undefined && existing?.id !== caller.id) return denied(); } const userMatch = routePath.match(/^\/users\/([^/]+)$/); if (userMatch && ['PUT', 'DELETE'].includes(req.method)) { @@ -97,9 +89,8 @@ export function createApiSecurity(options: { if (req.method === 'DELETE' && (!manager || (target && isSuperadmin(target)))) return denied(); if (req.method === 'PUT') { if (!superadmin && (body.email !== undefined || body.isCreativeDirector !== undefined)) return denied(); - if (!manager && Object.keys(body).some(key => !['clickupApiKey', 'selectedClickupSpaceId', 'selectedClickupSpaceName', 'clickupUserId', 'clickupUsername'].includes(key))) return denied(); + if (!manager) return denied(); if (!superadmin && body.creativeDirectorId !== undefined && body.creativeDirectorId !== caller.id) return denied(); - if (body.clickupApiKey !== undefined && target?.id !== caller.id) return denied(); } } if (routePath === '/tasks' && req.method === 'POST' && !edit(body.userId)) return denied(); @@ -119,7 +110,6 @@ export function createApiSecurity(options: { if ((task && !edit(task.userId)) || (update.userId !== undefined && !edit(update.userId))) return denied(); } } - if (routePath === '/clickup/sync-user-tasks' && !edit(body.userId)) return denied(); // Existing integration handlers consume these values; overwrite every caller assertion. req.headers['x-caller-user-id'] = caller.id; @@ -129,13 +119,6 @@ export function createApiSecurity(options: { body.callerUserId = caller.id; body.callerEmail = caller.email; body.isSuperadmin = superadmin; - const savedKey = caller.clickupApiKey || store.users.find(user => user.clickupApiKey)?.clickupApiKey; - if (routePath !== '/clickup/verify') { - req.headers['x-clickup-api-key'] = savedKey || ''; - body.apiKey = savedKey || ''; - if (!routePath.startsWith('/users')) body.clickupApiKey = savedKey || ''; - delete req.query.apiKey; - } const json = res.json.bind(res); res.json = ((value: any) => json(redactPayload(value))) as Response['json']; res.setHeader('Cache-Control', 'private, no-cache, must-revalidate'); diff --git a/server/webhooks.ts b/server/webhooks.ts deleted file mode 100644 index 2aa8ce8..0000000 --- a/server/webhooks.ts +++ /dev/null @@ -1,41 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -export interface WebhookRegistration { id: string; secret: string; endpoint: string } -export class WebhookRegistry { - private registrations = new Map(); - constructor(private file: string) {} - async load(db?: any) { - const disk = await fs.promises.readFile(this.file, 'utf8').then(JSON.parse).catch((error: any) => { - if (error.code !== 'ENOENT') console.warn('[Webhook] Cannot load local registrations'); - return []; - }); - const cloud = db ? await db.collection('server_secrets').doc('clickup_webhooks').get().then((snapshot: any) => snapshot.data()?.registrations || []) : []; - for (const item of [...disk, ...cloud]) { - if (typeof item.id === 'string' && typeof item.secret === 'string' && item.secret) this.registrations.set(item.id, item); - } - } - get(id: unknown) { return typeof id === 'string' ? this.registrations.get(id) : undefined; } - latest() { return [...this.registrations.values()].at(-1); } - async save(registration: WebhookRegistration, db?: any) { - const previous = this.registrations.get(registration.id); - this.registrations.set(registration.id, registration); - try { await this.persist(db); } catch (error) { - if (previous) this.registrations.set(registration.id, previous); else this.registrations.delete(registration.id); - throw error; - } - } - async remove(id: string, db?: any) { - this.registrations.delete(id); - await this.persist(db); - } - private async persist(db?: any) { - const registrations = [...this.registrations.values()]; - // Cloud copy survives redeployment; private local copy supports local-only deployments. - if (db) await db.collection('server_secrets').doc('clickup_webhooks').set({ registrations }); - await fs.promises.mkdir(path.dirname(this.file), { recursive: true }); - const temporary = `${this.file}.tmp`; - await fs.promises.writeFile(temporary, JSON.stringify(registrations), { mode: 0o600 }); - await fs.promises.rename(temporary, this.file); - } -} diff --git a/server/workspace.ts b/server/workspace.ts new file mode 100644 index 0000000..5c8ff41 --- /dev/null +++ b/server/workspace.ts @@ -0,0 +1,189 @@ +import type { Firestore } from 'firebase-admin/firestore'; +import { FieldValue } from 'firebase-admin/firestore'; +import type { RequestHandler, Response } from 'express'; +import { once } from 'node:events'; + +export interface WorkspaceData { users: any[]; tasks: any[] } +export interface WorkspaceSnapshot { store: WorkspaceData; revision: number } + +// Strip retired integration metadata without changing native IDs, ownership or history. +export function nativeData(value: any): any { + if (Array.isArray(value)) return value.map(nativeData); + if (!value || typeof value !== 'object') return value; + if (value instanceof Date || typeof value.toDate === 'function') return value; + return Object.fromEntries(Object.entries(value) + .filter(([key, item]) => item !== undefined && !/clickup/i.test(key)) + .map(([key, item]) => [key, nativeData(item)])); +} + +export class FirestoreWorkspace { + constructor(readonly db: Firestore) {} + private get revisionRef() { return this.db.doc('workspace/state'); } + + async load(): Promise { + return this.db.runTransaction(async tx => { + const [revision, users, tasks] = await Promise.all([ + tx.get(this.revisionRef), tx.get(this.db.collection('users')), tx.get(this.db.collection('tasks')), + ]); + return { + revision: revision.data()?.revision || 0, + store: { + users: users.docs.map(doc => nativeData({ ...doc.data(), id: doc.id })), + tasks: tasks.docs.map(doc => nativeData({ ...doc.data(), id: doc.id })), + }, + }; + }, { readOnly: true }); + } + + async bootstrap() { + // No local seed import: an empty database remains an empty workspace with its owner. + await this.db.runTransaction(async tx => { + const users = await tx.get(this.db.collection('users')); + if (!users.docs.some(doc => String(doc.data().email).toLowerCase() === 'kiran.s@zensciences.com')) { + tx.create(this.db.doc('users/user-superadmin-kiran'), { + id: 'user-superadmin-kiran', name: 'Kiran S', email: 'kiran.s@zensciences.com', + role: 'content', isCreativeDirector: true, createdAt: new Date().toISOString(), + avatarColor: 'from-blue-600 to-indigo-600', + }); + } + }); + } + + async migrate() { + const marker = this.db.doc('workspace/native-v1'); + if ((await marker.get()).exists) return; + // Back up native data and remove retired credentials/links atomically per document. + // Update-time preconditions prevent overwriting changes made during deployment overlap. + const counts: Record = {}; + for (const collection of ['users', 'tasks']) { + const snapshot = await this.db.collection(collection).get(); + counts[collection] = snapshot.size; + for (let offset = 0; offset < snapshot.size; offset += 200) { + const batch = this.db.batch(); + for (const doc of snapshot.docs.slice(offset, offset + 200)) { + // Preserve original task metadata for recovery, excluding saved credentials. + const backup = Object.fromEntries(Object.entries({ ...doc.data(), id: doc.id }) + .filter(([key]) => !/apikey|secret|token/i.test(key))); + batch.set(this.db.doc(`workspace_backups/native-v1/${collection}/${doc.id}`), backup); + batch.update(doc.ref, { id: doc.id, ...Object.fromEntries(Object.entries(doc.data()) + .filter(([key]) => /clickup/i.test(key)).map(([key]) => [key, FieldValue.delete()])), + }, { lastUpdateTime: doc.updateTime }); + } + await batch.commit(); + } + } + await this.db.doc('server_secrets/clickup_webhooks').delete(); + await marker.set({ completedAt: new Date().toISOString(), counts }); + console.log('[Firestore migration] Native workspace ready:', counts); + } + + async commit(before: WorkspaceSnapshot, after: WorkspaceData, audit: any[]): Promise { + const changes: Array<{ path: string; data?: any }> = []; + for (const collection of ['users', 'tasks'] as const) { + const previous = new Map(before.store[collection].map(doc => [doc.id, doc])); + for (const doc of after[collection]) { + if (!doc.id || doc.id.includes('/')) throw new Error('Invalid document ID'); + const data = nativeData(doc); + if (JSON.stringify(previous.get(doc.id)) !== JSON.stringify(data)) changes.push({ path: `${collection}/${doc.id}`, data }); + previous.delete(doc.id); + } + for (const id of previous.keys()) changes.push({ path: `${collection}/${id}` }); + } + if (!changes.length && !audit.length) return before.revision; + // Bound one user operation to an atomic Firestore commit, including its audit records. + if (changes.length + audit.length + 1 > 500) throw new Error('Operation exceeds atomic workspace write limit'); + return this.db.runTransaction(async tx => { + const current = await tx.get(this.revisionRef); + if ((current.data()?.revision || 0) !== before.revision) throw new Error('Workspace changed; retry the operation'); + for (const change of changes) { + if (change.data) tx.set(this.db.doc(change.path), change.data); + else tx.delete(this.db.doc(change.path)); + } + for (const entry of audit) tx.create(this.db.doc(`compliance_audit_logs/${entry.id}`), nativeData(entry)); + const revision = before.revision + 1; + tx.set(this.revisionRef, { revision, updatedAt: new Date().toISOString() }); + return revision; + }); + } + + async recentAudit(limit: number) { + const snapshot = await this.db.collection('compliance_audit_logs').orderBy('timestamp', 'desc').limit(limit).get(); + return snapshot.docs.map(doc => nativeData(doc.data())); + } + + async downloadAudit(res: Response) { + let cursor: FirebaseFirestore.QueryDocumentSnapshot | undefined; + while (!res.destroyed) { + let query = this.db.collection('compliance_audit_logs').orderBy('timestamp').limit(200); + if (cursor) query = query.startAfter(cursor); + const page = await query.get(); + if (page.empty) break; + for (const doc of page.docs) { + if (res.destroyed) return; + if (!res.write(JSON.stringify(nativeData(doc.data())) + '\n')) { + await Promise.race([once(res, 'drain'), once(res, 'close')]); + } + } + cursor = page.docs.at(-1); + } + res.end(); + } +} + +// Existing workflow handlers run against a fresh snapshot under a process-local lock. +// A database revision check also prevents lost writes across overlapping deployments. +// The response and queued SSE events become visible only after the atomic commit. +export function workspaceMiddleware(options: { + workspace: FirestoreWorkspace; getStore: () => WorkspaceData; setStore: (store: WorkspaceData) => void; + begin: (revision: number) => void; audit: () => any[]; committed: (revision: number) => void; failed: (error?: unknown) => void; +}): RequestHandler { + let tail: Promise = Promise.resolve(); + return async (req, res, next) => { + if (req.path === '/health') return next(); + const previous = tail; + let release!: () => void; + tail = new Promise(resolve => { release = resolve; }); + await previous; + let released = false; + const unlock = () => { if (!released) { released = true; release(); } }; + const json = res.json.bind(res); + let snapshot: WorkspaceSnapshot; + try { + snapshot = await options.workspace.load(); + options.setStore(structuredClone(snapshot.store)); + options.begin(snapshot.revision); + } catch (error) { + console.error('[Firestore read failed]', error); + options.failed(error); unlock(); + res.status(503); json({ error: 'Workspace database unavailable. Please retry.' }); return; + } + let responding = false; + res.json = ((body: any) => { + if (responding) return res; + responding = true; + const status = res.statusCode; + void (async () => { + try { + if (status < 400) { + const revision = await options.workspace.commit(snapshot, options.getStore(), options.audit()); + options.committed(revision); + } else { options.setStore(snapshot.store); options.failed(); } + res.statusCode = status; + json(body); + } catch (error) { + console.error('[Firestore commit failed]', error); + options.setStore(snapshot.store); options.failed(error); + res.removeHeader('ETag'); res.status(503); + json({ error: 'Workspace changes could not be saved. Please retry.' }); + } finally { unlock(); } + })(); + return res; + }) as Response['json']; + // SSE and read-only downloads own their stream after the handler starts. + if (req.method === 'GET' && ['/events', '/audit/download'].includes(req.path)) { + options.failed(); next(); unlock(); return; + } + res.once('finish', () => { if (!responding) { options.failed(); unlock(); } }); + next(); + }; +} diff --git a/src/App.tsx b/src/App.tsx index b6782ce..2178cbd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -11,7 +11,7 @@ import { DeleteUserModal } from './components/DeleteUserModal'; import { BillableHoursModal } from './components/BillableHoursModal'; import { ErrorBoundary } from './components/ErrorBoundary'; import { MarqueeRibbon } from './components/MarqueeRibbon'; -import { UnassignedListRibbon } from './components/UnassignedListRibbon'; + import { EditUserModal } from './components/EditUserModal'; import { DuplicateTaskModal } from './components/DuplicateTaskModal'; import { DeleteTaskModal } from './components/DeleteTaskModal'; @@ -46,8 +46,7 @@ function DashboardContent() { rescheduleTask, activeBoardId, setActiveBoardId, - showClickupPrompt, - setShowClickupPrompt, + } = useDashboard(); // Modals state @@ -341,13 +340,7 @@ function DashboardContent() { status: TaskStatus, cognitiveLoad: 'low' | 'medium' | 'high', dueDate?: string, - clickupDetails?: { - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - } + ) => { await createTask({ userId, @@ -355,11 +348,7 @@ function DashboardContent() { status, cognitiveLoad, dueDate, - clickupFolderId: clickupDetails?.clickupFolderId, - clickupFolderName: clickupDetails?.clickupFolderName, - clickupListId: clickupDetails?.clickupListId, - clickupListName: clickupDetails?.clickupListName, - clickupSpaceId: clickupDetails?.clickupSpaceId, + }); }, [createTask] @@ -483,11 +472,7 @@ function DashboardContent() { users={users} onTaskClick={handleEditTask} /> - + @@ -613,10 +598,10 @@ function DashboardContent() { /> { setFirestoreModalOpen(false); - setShowClickupPrompt(false); + }} /> diff --git a/src/components/ClickupMemberPicker.tsx b/src/components/ClickupMemberPicker.tsx deleted file mode 100644 index 34a93bd..0000000 --- a/src/components/ClickupMemberPicker.tsx +++ /dev/null @@ -1,243 +0,0 @@ -import React, { useState, useMemo, useRef, useEffect } from 'react'; -import { ClickupMember } from '../types'; -import { Search, X, Check, Loader2, RefreshCw } from 'lucide-react'; - -interface ClickupMemberPickerProps { - members: ClickupMember[]; - selectedMemberId?: string; - onSelect: (member: ClickupMember | null) => void; - isLoading?: boolean; - onRefresh?: () => void; - disabled?: boolean; -} - -export const ClickupMemberPicker: React.FC = ({ - members, - selectedMemberId, - onSelect, - isLoading = false, - onRefresh, - disabled = false, -}) => { - const [searchQuery, setSearchQuery] = useState(''); - const [isOpen, setIsOpen] = useState(false); - const containerRef = useRef(null); - const inputRef = useRef(null); - - const selectedMember = useMemo(() => { - if (!selectedMemberId) return null; - return members.find(m => m.id === selectedMemberId) || null; - }, [members, selectedMemberId]); - - // Filter members by query - const filteredMembers = useMemo(() => { - const q = searchQuery.toLowerCase().trim(); - if (!q) return members; - return members.filter( - m => - (m.username || '').toLowerCase().includes(q) || - Boolean(m.email && m.email.toLowerCase().includes(q)) - ); - }, [members, searchQuery]); - - // Click outside to close dropdown - useEffect(() => { - const handleOutside = (e: MouseEvent) => { - if (containerRef.current && !containerRef.current.contains(e.target as Node)) { - setIsOpen(false); - } - }; - document.addEventListener('mousedown', handleOutside); - return () => document.removeEventListener('mousedown', handleOutside); - }, []); - - return ( -
- {/* Current selection summary card if selected and not actively searching */} - {selectedMember && !isOpen ? ( -
-
- {selectedMember.profilePicture ? ( - {selectedMember.username} - ) : ( -
- {selectedMember.initials || (selectedMember.username ? selectedMember.username.slice(0, 2).toUpperCase() : '??')} -
- )} -
-

- {selectedMember.username} -

- {selectedMember.email && ( -

- {selectedMember.email} -

- )} -
-
- -
- - -
-
- ) : ( - /* In-Line Search Input and Results */ -
-
-
- -
- setIsOpen(true)} - onChange={e => { - setSearchQuery(e.target.value); - setIsOpen(true); - }} - placeholder="Search ClickUp member by name or email..." - className="w-full rounded-xl border border-neutral-300 dark:border-white/10 bg-white dark:bg-[#141414] py-2 pl-9 pr-8 text-xs text-neutral-900 dark:text-white placeholder:text-neutral-400 dark:placeholder:text-white/30 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors" - /> - {searchQuery && ( - - )} -
- - {/* Dropdown Options */} - {isOpen && ( -
- {/* Option to unassign/clear */} - - - {isLoading ? ( -
- - Loading ClickUp members... -
- ) : filteredMembers.length === 0 ? ( -
- No ClickUp members match "{searchQuery}" -
- ) : ( - filteredMembers.map(m => { - const isCurrent = m.id === selectedMemberId; - return ( - - ); - }) - )} -
- )} -
- )} - - {/* Helper reload action if no members available */} - {members.length === 0 && !isLoading && onRefresh && ( -
- No workspace members loaded. - -
- )} -
- ); -}; diff --git a/src/components/DeleteTaskModal.tsx b/src/components/DeleteTaskModal.tsx index cc4acdc..a522847 100644 --- a/src/components/DeleteTaskModal.tsx +++ b/src/components/DeleteTaskModal.tsx @@ -1,7 +1,7 @@ import React, { useState, useEffect } from 'react'; import { motion, AnimatePresence } from 'motion/react'; import { Task, User } from '../types'; -import { AlertTriangle, Trash2, X, Loader2, CornerDownRight, ExternalLink } from 'lucide-react'; +import { AlertTriangle, Trash2, X, Loader2, CornerDownRight } from 'lucide-react'; interface DeleteTaskModalProps { task: Task | null; @@ -125,12 +125,6 @@ export const DeleteTaskModal: React.FC = ({ - {task.clickupTaskId && ( -
- - Linked ClickUp Task #{task.clickupTaskId} -
- )}
diff --git a/src/components/DuplicateTaskModal.tsx b/src/components/DuplicateTaskModal.tsx index 1b7f943..cb68ae8 100644 --- a/src/components/DuplicateTaskModal.tsx +++ b/src/components/DuplicateTaskModal.tsx @@ -10,7 +10,7 @@ import { Layers, Loader2, AlertCircle, - ExternalLink, + ArrowRight, Shield, UserCheck, @@ -93,7 +93,7 @@ export const DuplicateTaskModal: React.FC = ({ const [feedback, setFeedback] = useState<{ type: 'success' | 'error'; message: string; - clickupSubtaskCreated?: boolean; + warning?: string; targetBoardId?: string; targetBoardName?: string; @@ -200,7 +200,7 @@ export const DuplicateTaskModal: React.FC = ({ setFeedback({ type: 'success', message: `Subtask created under "${task.title}" on ${targetUserName}'s board!`, - clickupSubtaskCreated: res.clickupSubtaskCreated, + warning: res.warning, targetBoardId: selectedBoardId, targetBoardName: boardName, @@ -338,29 +338,8 @@ export const DuplicateTaskModal: React.FC = ({
- {/* ClickUp Linkage Pill */}
- {task.clickupTaskId ? ( -
-
- - Parent ClickUp Task #{task.clickupTaskId} - {task.clickupListName && ( - - ({task.clickupFolderName ? `${task.clickupFolderName} / ` : ''}{task.clickupListName}) - - )} -
- - Creates ClickUp Subtask - -
- ) : ( -

- - Parent task is local to ZenFlow. Subtask will be created on ZenFlow board. -

- )} +
@@ -401,11 +380,11 @@ export const DuplicateTaskModal: React.FC = ({ className="w-full rounded-xl border border-neutral-300 dark:border-white/10 bg-white dark:bg-[#1A1A1A] px-3 py-2 text-xs text-neutral-900 dark:text-white focus:border-blue-500 focus:outline-none transition-colors cursor-pointer disabled:opacity-50" > {availableUsers.map(u => { - const hasClickup = Boolean(u.clickupUserId); + return ( ); })} @@ -428,17 +407,7 @@ export const DuplicateTaskModal: React.FC = ({ {selectedTargetUser.role} - {selectedTargetUser.clickupUserId ? ( - - - ClickUp ID: {selectedTargetUser.clickupUserId} - - ) : ( - - - Match via {selectedTargetUser.email} - - )} + )} @@ -581,11 +550,7 @@ export const DuplicateTaskModal: React.FC = ({ )}

{feedback.message}

- {feedback.clickupSubtaskCreated && ( -

- βœ“ Dedicated subtask created under parent #{task.clickupTaskId} on ClickUp and assigned to {selectedTargetUser?.name}. -

- )} + {feedback.warning && (

Notice: {feedback.warning} diff --git a/src/components/EditUserModal.tsx b/src/components/EditUserModal.tsx index cdc22e9..1dd03a0 100644 --- a/src/components/EditUserModal.tsx +++ b/src/components/EditUserModal.tsx @@ -10,14 +10,13 @@ import { Crown, ShieldCheck, Loader2, - Link2, + Mail, ArrowRightLeft, AlertTriangle, CheckCircle2, KeyRound, } from 'lucide-react'; -import { ClickupMemberPicker } from './ClickupMemberPicker'; interface EditUserModalProps { isOpen: boolean; @@ -35,10 +34,7 @@ export const EditUserModal: React.FC = ({ isSuperadmin, creativeDirectors, canManageMembers, - clickupMembers, - loadClickupMembers, - isClickupConnected, - clickupApiKey, + users, tasks, remapUserTasks, @@ -49,9 +45,7 @@ export const EditUserModal: React.FC = ({ const [role, setRole] = useState('content'); const [isCD, setIsCD] = useState(false); const [selectedCDId, setSelectedCDId] = useState(''); - const [clickupUserId, setClickupUserId] = useState(''); - const [clickupUsername, setClickupUsername] = useState(''); - const [isLoadingMembers, setIsLoadingMembers] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -70,21 +64,15 @@ export const EditUserModal: React.FC = ({ setRole(user.role); setIsCD(!!user.isCreativeDirector); setSelectedCDId(user.creativeDirectorId || ''); - setClickupUserId(user.clickupUserId || ''); - setClickupUsername(user.clickupUsername || ''); + setError(null); setShowRemapTool(false); setRemapSourceUserId(''); setRemapDeleteSource(false); setRemapStatusMessage(null); - // Auto-load ClickUp members if empty - if (clickupMembers.length === 0 && (isClickupConnected || clickupApiKey)) { - setIsLoadingMembers(true); - loadClickupMembers(clickupApiKey).finally(() => setIsLoadingMembers(false)); - } } - }, [user, isOpen, clickupMembers.length, isClickupConnected, clickupApiKey, loadClickupMembers]); + }, [user, isOpen]); // Global Escape key dismissal useEffect(() => { @@ -149,8 +137,7 @@ export const EditUserModal: React.FC = ({ const updates: Partial = { name: cleanName, role, - clickupUserId: clickupUserId || undefined, - clickupUsername: clickupUsername || undefined, + }; if (isSuperadmin && !isTargetSuperadmin) { @@ -417,48 +404,6 @@ export const EditUserModal: React.FC = ({

)} - {/* ClickUp Member Mapping */} -
-
-
-
- -
-
- -

- Map to ClickUp profile so tasks are assigned to the right person. -

-
-
- {isLoadingMembers && ( - - )} -
- - { - setIsLoadingMembers(true); - await loadClickupMembers(clickupApiKey); - setIsLoadingMembers(false); - }} - onSelect={member => { - if (member) { - setClickupUserId(member.id); - setClickupUsername(member.username || ''); - } else { - setClickupUserId(''); - setClickupUsername(''); - } - }} - /> -
- {/* Superadmin Task Remapping & Transfer Section */} {isSuperadmin && (
diff --git a/src/components/FirestoreModal.tsx b/src/components/FirestoreModal.tsx index 5b1708b..de84b90 100644 --- a/src/components/FirestoreModal.tsx +++ b/src/components/FirestoreModal.tsx @@ -1,804 +1,58 @@ -import React, { useState, useEffect } from 'react'; -import { createPortal } from 'react-dom'; +import React, { useEffect, useState } from 'react'; import { motion, AnimatePresence } from 'motion/react'; +import { Database, Download, RefreshCw, X } from 'lucide-react'; import { useDashboard } from '../context/DashboardContext'; -import { AuditLogEntry } from '../types'; -import { - Database, - AlertCircle, - CheckCircle2, - RefreshCw, - X, - Key, - ExternalLink, - Unlink, - CheckCircle, - Loader2, - Layers, - Radio, - ShieldCheck, - Download, - ChevronDown, - ChevronUp, -} from 'lucide-react'; +import type { AuditLogEntry } from '../types'; -interface FirestoreModalProps { - isOpen: boolean; - onClose: () => void; -} - -export const FirestoreModal: React.FC = ({ isOpen, onClose }) => { - const { - firestoreStatus, - refreshFirestoreStatus, - syncWithFirestore, - users, - tasks, - isSuperadmin, - canManageMembers, - isClickupConnected, - clickupApiKey, - connectClickup, - disconnectClickup, - clickupSpaces, - clickupWebhookStatus, - refreshClickupWebhookStatus, - registerClickupWebhook, - fetchAuditLogs, - downloadAuditLogs, - } = useDashboard(); - - const [isSyncing, setIsSyncing] = useState(false); - const [isRefreshing, setIsRefreshing] = useState(false); - const [feedback, setFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null); - - // ClickUp connection states - const [apiKeyInput, setApiKeyInput] = useState(''); - const [isClickupLoading, setIsClickupLoading] = useState(false); - const [clickupError, setClickupError] = useState(null); - const [clickupSuccess, setClickupSuccess] = useState(null); - - // ClickUp Webhook states - const [isRegisteringWebhook, setIsRegisteringWebhook] = useState(false); - const [webhookFeedback, setWebhookFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null); - - // SOC2 Compliance Audit states - const [auditLogs, setAuditLogs] = useState([]); - const [isLoadingAudit, setIsLoadingAudit] = useState(false); - const [showAuditFeed, setShowAuditFeed] = useState(false); - - // Collapsible section states - collapsed by default! - const [expandedSections, setExpandedSections] = useState>({ - firestore: false, - clickup: false, - webhook: false, - audit: false, - }); - - const toggleSection = (section: string) => { - setExpandedSections(prev => ({ - ...prev, - [section]: !prev[section], - })); - }; - - // Close on Escape key +export const FirestoreModal: React.FC<{ isOpen: boolean; onClose: () => void }> = ({ isOpen, onClose }) => { + const { firestoreStatus, refreshFirestoreStatus, fetchAuditLogs, downloadAuditLogs, canManageMembers } = useDashboard(); + const [logs, setLogs] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); useEffect(() => { if (!isOpen) return; - const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === 'Escape' && !isClickupLoading && !isSyncing && !isRegisteringWebhook) { - onClose(); - } - }; - window.addEventListener('keydown', handleKeyDown); - return () => window.removeEventListener('keydown', handleKeyDown); - }, [isOpen, onClose, isClickupLoading, isSyncing, isRegisteringWebhook]); - - // Refresh status and collapse all details whenever modal opens - useEffect(() => { - if (isOpen) { - refreshFirestoreStatus(); - refreshClickupWebhookStatus(); - setFeedback(null); - setApiKeyInput(''); - setClickupError(null); - setClickupSuccess(null); - setWebhookFeedback(null); - setShowAuditFeed(false); - setExpandedSections({ - firestore: false, - clickup: false, - webhook: false, - audit: false, - }); - } - }, [isOpen, clickupApiKey, refreshFirestoreStatus, refreshClickupWebhookStatus]); - - const handleManualSync = async () => { - setIsSyncing(true); - setFeedback(null); - try { - const res = await syncWithFirestore(); - if (res.success) { - setFeedback({ - type: 'success', - message: res.message || 'Confirmed: Workspace synchronized with Firestore!', - }); - } else { - setFeedback({ type: 'error', message: res.message || 'Sync failed' }); - } - } catch (err: any) { - setFeedback({ type: 'error', message: err.message || 'Sync verification failed' }); - } finally { - setIsSyncing(false); - } + setError(''); setLogs([]); + void refreshFirestoreStatus(); + const keydown = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); }; + window.addEventListener('keydown', keydown); + return () => window.removeEventListener('keydown', keydown); + }, [isOpen, onClose, refreshFirestoreStatus]); + const loadAudit = async () => { + setLoading(true); setError(''); + try { setLogs(await fetchAuditLogs(100)); } + catch { setError('Audit history could not be loaded. Please retry.'); } + finally { setLoading(false); } }; - - const handleRefreshStatus = async () => { - setIsRefreshing(true); - try { - await refreshFirestoreStatus(); - setFeedback({ type: 'success', message: 'Connection status updated.' }); - } catch { - setFeedback({ type: 'error', message: 'Failed to refresh status.' }); - } finally { - setIsRefreshing(false); - } - }; - - const handleConnectClickUp = async (e: React.FormEvent) => { - e.preventDefault(); - setClickupError(null); - setClickupSuccess(null); - - const key = apiKeyInput.trim(); - if (!key) { - setClickupError('Please provide a ClickUp Personal API token (starts with pk_).'); - return; - } - - setIsClickupLoading(true); - try { - const res = await connectClickup(key); - if (res.success) { - setClickupSuccess('Successfully connected to ClickUp!'); - } else { - setClickupError(res.error || 'Failed to authenticate with ClickUp. Please verify your token.'); - } - } catch (err: any) { - setClickupError(err.message || 'Network error verifying ClickUp token.'); - } finally { - setIsClickupLoading(false); - } - }; - - const handleDisconnectClickUp = () => { - disconnectClickup(); - setApiKeyInput(''); - setClickupSuccess('Disconnected from ClickUp.'); - }; - - const handleRegisterWebhook = async () => { - setIsRegisteringWebhook(true); - setWebhookFeedback(null); - try { - const res = await registerClickupWebhook(); - if (res.success) { - setWebhookFeedback({ type: 'success', message: res.message }); - } else { - setWebhookFeedback({ type: 'error', message: res.message }); - } - } catch (err: any) { - setWebhookFeedback({ type: 'error', message: err.message || 'Failed to register webhook' }); - } finally { - setIsRegisteringWebhook(false); - } - }; - - const handleToggleAuditFeed = async () => { - if (!showAuditFeed) { - setIsLoadingAudit(true); - try { - const logs = await fetchAuditLogs(30); - setAuditLogs(logs); - } finally { - setIsLoadingAudit(false); - } - } - setShowAuditFeed(prev => !prev); - }; - - const isConnected = firestoreStatus?.connected; - const displayProject = firestoreStatus?.projectId || 'zen-flow-7173d'; - - const modalContent = ( - - {isOpen && ( - { - if (e.target === e.currentTarget && !isClickupLoading && !isSyncing && !isRegisteringWebhook) onClose(); - }} - > - e.stopPropagation()} - id="workspace-connections-modal" - className="w-full max-w-xl max-h-[90vh] my-auto flex flex-col rounded-2xl border border-neutral-200 dark:border-white/10 bg-white dark:bg-[#111111] shadow-2xl transition-all text-neutral-900 dark:text-white overflow-hidden" - > - {/* Fixed Header */} -
-
-
- -
-
-

- Connections & Compliance -

-

- Cloud Database, ClickUp Webhooks & SOC2 Audit Stream -

-
-
- -
- - {/* Scrollable Body - Collapsed Section Cards */} -
- {/* ========================================= */} - {/* SECTION 1: Cloud Storage (Firestore) */} - {/* ========================================= */} -
- - - {expandedSections.firestore && ( -
- {/* Feedback Alert for Firestore */} - {feedback && ( -
- {feedback.type === 'success' ? ( - - ) : ( - - )} - {feedback.message} -
- )} - - {/* Connection Details Card */} -
-
- Firebase Project - - {displayProject} - -
- -
- Storage Collections - - /users, /tasks, /compliance_audit_logs - -
- -
- Workspace Data - - {users.length} member swimlanes Β· {tasks.length} tasks - -
- - {firestoreStatus?.lastSyncTime && ( -
- Last Synchronized - - {new Date(firestoreStatus.lastSyncTime).toLocaleTimeString()} - -
- )} -
- - {/* Firestore Actions */} -
- - - -
-
- )} -
- - {/* ========================================= */} - {/* SECTION 2: ClickUp Workspace Integration */} - {/* ========================================= */} -
- - - {expandedSections.clickup && ( -
- {/* ClickUp Feedback Alerts */} - {clickupError && ( -
- - {clickupError} -
- )} - - {clickupSuccess && ( -
- - {clickupSuccess} -
- )} - - {isClickupConnected ? ( -
-
-
- - ClickUp API Authenticated -
- -
- -
-
- Personal API Token - - {'Active'} - -
-
- Available Spaces - - {clickupSpaces.length} space(s) available - -
-
-
- ) : ( -
-

- Connect your ClickUp account to synchronize tasks, custom fields, deadlines, and tracked time. -

-
- - setApiKeyInput(e.target.value)} - placeholder="pk_1234567_abcdef..." - disabled={isClickupLoading} - className="w-full px-3 py-2 rounded-xl border border-neutral-300 dark:border-white/10 bg-white dark:bg-[#161616] text-xs focus:outline-none focus:border-purple-500 transition-all font-mono text-neutral-900 dark:text-white" - /> -

- Find this in ClickUp: Settings → Apps → API Token → Generate. - - Open ClickUp - -

-
- - -
- )} -
- )} -
- - {/* ========================================= */} - {/* SECTION 3: ClickUp Real-Time Webhook */} - {/* ========================================= */} -
- - - {expandedSections.webhook && ( -
- {webhookFeedback && ( -
- {webhookFeedback.type === 'success' ? ( - - ) : ( - - )} - {webhookFeedback.message} -
- )} - -
-
- Inbound Endpoint - - {clickupWebhookStatus?.endpointUrl || '/api/clickup/webhook'} - -
- -
- Events Ingested - - {clickupWebhookStatus?.totalEventsCount ?? 0} events received - -
- - {clickupWebhookStatus?.lastEventAt && ( -
- Last Inbound Event - - {new Date(clickupWebhookStatus.lastEventAt).toLocaleTimeString()} ({clickupWebhookStatus.lastEventAction || 'event'}) - -
- )} - -
- Propagation Route - - Instantaneous SSE via /api/events - -
-
- - -
- )} -
- - {/* ========================================= */} - {/* SECTION 4: SOC2 Compliance Audit Stream */} - {/* ========================================= */} -
- - - {expandedSections.audit && ( -
-
-
- Persistence Storage - - data/compliance-audit.jsonl & /compliance_audit_logs - -
- -
- Audit Coverage - - Reassignments, hours overrides, permissions, deletions & webhooks - -
-
- -
- - - -
- - {/* Expandable Recent Audit Log Feed */} - {showAuditFeed && ( -
-
- Recent Audit Events ({auditLogs.length}) - Immutable Stream -
- {auditLogs.length === 0 ? ( -
No audit records logged yet.
- ) : ( - auditLogs.slice(0, 20).map(entry => ( -
-
- - [{entry.category}] {entry.action} - - - {new Date(entry.timestamp).toLocaleTimeString()} - -
-
- {entry.details || `${entry.targetType}:${entry.targetId}`} -
- {entry.actor?.name && ( -
- Actor: {entry.actor.name} ({entry.actor.email || 'system'}) -
- )} -
- )) - )} -
- )} -
- )} -
+ return {isOpen && { if (event.target === event.currentTarget) onClose(); }}> + +
+

Workspace & Compliance

+ +
+
+
Cloud Firestore
+

Members, tasks, activity history and audit records are saved in your workspace database.

+

{firestoreStatus?.connected ? 'Connected' : 'Checking connection…'} Β· {firestoreStatus?.totalUsers ?? 'β€”'} members Β· {firestoreStatus?.totalTasks ?? 'β€”'} tasks

+ {firestoreStatus?.lastError &&

Workspace database unavailable. Please retry.

} + +
+ {canManageMembers &&
+

Audit history

+
+ +
- - {/* Modal Footer */} -
- -
- + {error &&

{error}

} +
{logs.map(log =>
+ +

{log.details || log.action}

+
)}
+
}
- )} -
- ); - - if (typeof document !== 'undefined') { - return createPortal(modalContent, document.body); - } - - return modalContent; + }; }; diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 37271d5..5672f33 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -37,8 +37,7 @@ const HeaderComponent: React.FC = ({ isSuperadmin, isCreativeDirector, canManageMembers, - isZensciencesUser, - isClickupConnected, + } = useDashboard(); const [userDropdownOpen, setUserDropdownOpen] = useState(false); @@ -63,7 +62,7 @@ const HeaderComponent: React.FC = ({
- + {/* Logo & Brand: zenFlow */}
= ({
- {/* Right Actions: ClickUp Space Dropdown, Realtime status, Theme toggle, User Profile */}
- {/* Unified Connection Status Button (Firestore & ClickUp) */} @@ -296,7 +289,7 @@ const HeaderComponent: React.FC = ({ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 dark:text-white/80 hover:bg-neutral-50 dark:hover:bg-white/5 hover:text-neutral-900 dark:hover:text-white transition-colors cursor-pointer" > - Connections & Compliance + Workspace & Compliance
)} - {/* New Account Only: ClickUp Member Mapping with in-line search filtering */} - {isNewAccountOnly && ( -
- - { - setSelectedClickupUserId(member?.id || ''); - }} - /> -

- Automatically assigns tasks created in ZenFlow to this ClickUp member. -

-
- )} -
@@ -239,46 +170,6 @@ const RetainerSwimlaneComponent: React.FC = ({ className="w-full rounded-lg border border-neutral-200 dark:border-white/10 bg-neutral-50 dark:bg-[#121212] px-2.5 py-1.5 text-xs text-neutral-900 dark:text-white placeholder:text-neutral-400 dark:placeholder:text-white/30 focus:border-emerald-500 focus:outline-none" /> - {/* ClickUp Destination Selection for Retainer parent task */} - {isClickupConnected && isZensciencesUser && ( -
- - ClickUp: - - {folders.length > 0 && ( - - )} - -
- )} -
{(['low', 'medium', 'high'] as const).map(load => ( @@ -415,16 +306,6 @@ const RetainerSwimlaneComponent: React.FC = ({
- {/* ClickUp List Badge */} - {task.clickupListName && ( - - - {task.clickupListName} - - )}
diff --git a/src/components/Swimlane.tsx b/src/components/Swimlane.tsx index 3a7141b..00e4da8 100644 --- a/src/components/Swimlane.tsx +++ b/src/components/Swimlane.tsx @@ -24,7 +24,7 @@ import { ArrowUp, ArrowDown, Calendar, - RefreshCw, + UserCog, } from 'lucide-react'; import { useDashboard } from '../context/DashboardContext'; @@ -42,13 +42,7 @@ interface SwimlaneProps { status: TaskStatus, cognitiveLoad: 'low' | 'medium' | 'high', dueDate?: string, - clickupDetails?: { - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - } + ) => Promise; onEditTask: (task: Task) => void; onRescheduleTask?: (taskId: string, newDueDate: string | undefined) => void; @@ -131,48 +125,14 @@ const SwimlaneComponent: React.FC = ({ canMoveDown, }) => { const { - isZensciencesUser, - isClickupConnected, - syncUserTasksWithClickUp, + canManageMembers, canEditUserTasks, - setShowClickupPrompt, - getUserSyncState, - } = useDashboard(); - const [isSyncingClickUp, setIsSyncingClickUp] = useState(false); - const [syncFeedback, setSyncFeedback] = useState(null); + } = useDashboard(); const canEdit = useMemo(() => canEditUserTasks(user.id), [canEditUserTasks, user.id]); - const syncState = useMemo(() => { - return getUserSyncState(user.id); - }, [getUserSyncState, user.id, tasks]); - - const handleSyncClickUp = async () => { - if (!isClickupConnected) { - setShowClickupPrompt(true); - return; - } - setIsSyncingClickUp(true); - setSyncFeedback(null); - try { - const res = await syncUserTasksWithClickUp(user.id); - if (res.success) { - setSyncFeedback(`Synced ${res.syncedCount}`); - setTimeout(() => setSyncFeedback(null), 3000); - } else { - setSyncFeedback(res.message || 'Sync failed'); - setTimeout(() => setSyncFeedback(null), 3000); - } - } catch { - setSyncFeedback('Sync error'); - setTimeout(() => setSyncFeedback(null), 3000); - } finally { - setIsSyncingClickUp(false); - } - }; - const [showArchived, setShowArchived] = useState(false); const [dragOverColumn, setDragOverColumn] = useState(null); const [dragOverHeader, setDragOverHeader] = useState(false); @@ -421,16 +381,10 @@ const SwimlaneComponent: React.FC = ({ targetUserId: string, title: string, cognitiveLoad: CognitiveLoad, - clickupDetails?: { - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - } + ) => { if (onQuickAddTask) { - await onQuickAddTask(targetUserId, title, 'retainer', cognitiveLoad, undefined, clickupDetails); + await onQuickAddTask(targetUserId, title, 'retainer', cognitiveLoad); } }, [onQuickAddTask] @@ -748,40 +702,6 @@ const SwimlaneComponent: React.FC = ({ )} - {/* 3. Sync tasks with ClickUp button (Icon only, 4 color states) */} - {isZensciencesUser && ( - - )} - {/* 4. Edit User Button - Only Superadmin and CDs */} {onEditUser && canManageMembers && ( - ) : null} - {/* Optional Context snippet */} {task.description && (

diff --git a/src/components/TaskModal.tsx b/src/components/TaskModal.tsx index 0ae3240..a984ac9 100644 --- a/src/components/TaskModal.tsx +++ b/src/components/TaskModal.tsx @@ -1,9 +1,9 @@ -import React, { useState, useEffect, useMemo, useRef } from 'react'; +import React, { useState, useEffect, useMemo } from 'react'; import { motion, AnimatePresence } from 'motion/react'; import { useDashboard } from '../context/DashboardContext'; -import { Task, CognitiveLoad, TaskStatus, ClickupFolder, ClickupList } from '../types'; +import { Task, CognitiveLoad, TaskStatus, } from '../types'; import { getTaskBillableMs, formatBillableDetailed, getLastDayOfMonth } from '../utils/workload'; -import { X, Calendar, Brain, Trash2, History, Clock, ArrowRight, CheckCircle2, UserCheck, PlusCircle, Timer, ChevronDown, Check, CopyPlus, CornerDownRight, AlertCircle, MapPin, ExternalLink } from 'lucide-react'; +import { X, Calendar, Brain, Trash2, History, Clock, ArrowRight, CheckCircle2, UserCheck, PlusCircle, Timer, ChevronDown, CopyPlus, CornerDownRight, AlertCircle, } from 'lucide-react'; function formatActivityTime(isoString: string): string { try { @@ -43,93 +43,6 @@ interface TaskModalProps { onDuplicateTask?: (task: Task) => void; } -interface SpaceDropdownRowProps { - space: { id: string; name: string }; - folderListStr: string; - fullText: string; - isSelected: boolean; - onSelect: () => void; -} - -const SpaceDropdownRow: React.FC = ({ - space, - folderListStr, - fullText, - isSelected, - onSelect, -}) => { - const containerRef = useRef(null); - const textRef = useRef(null); - const [isHovered, setIsHovered] = useState(false); - const [overflowDistance, setOverflowDistance] = useState(0); - - const measureOverflow = () => { - if (containerRef.current && textRef.current) { - const diff = Math.ceil(textRef.current.offsetWidth - containerRef.current.clientWidth); - setOverflowDistance(diff > 4 ? diff : 0); - } - }; - - useEffect(() => { - measureOverflow(); - }, [fullText]); - - const totalDuration = useMemo(() => { - if (overflowDistance <= 0) return 0; - return Math.max(3.5, Math.min(10, overflowDistance / 25 + 2)); - }, [overflowDistance]); - - return ( -

{ - measureOverflow(); - setIsHovered(true); - }} - onMouseLeave={() => { - setIsHovered(false); - }} - className={`group w-full max-w-full px-2.5 py-1.5 text-xs cursor-pointer flex items-center justify-between transition-colors ${ - isSelected - ? 'bg-purple-50 dark:bg-purple-950/40 text-purple-700 dark:text-purple-300 font-medium' - : 'text-neutral-800 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-white/5' - }`} - > -
-
0 - ? ({ - '--scroll-dist': `-${overflowDistance}px`, - animation: `auto-scroll-hover ${totalDuration}s ease-in-out infinite`, - } as React.CSSProperties) - : { - transform: 'translateX(0)', - transition: 'transform 0.3s ease-out', - } - } - className="inline-block whitespace-nowrap" - > - {space.name} - {folderListStr && ( - - | {folderListStr} - - )} -
-
- {isSelected && ( - - )} -
- ); -}; - export const TaskModal: React.FC = ({ isOpen, onClose, @@ -139,27 +52,8 @@ export const TaskModal: React.FC = ({ onAdjustBillableHours, onDuplicateTask, }) => { - const { - tasks, - users, - currentUser, - createTask, - updateTask, - deleteTask, - isZensciencesUser, - isClickupConnected, - selectedClickupSpaceId, - clickupSpaces, - clickupFoldersAndLists, - spaceFoldersMap, - spaceFoldersAndListsMap, - getFoldersAndListsForSpace, - createClickupList, - canEditUserTasks, - clickupCustomFieldOptions, - clickupTaskTypeFieldId: ctxClickupTaskTypeFieldId, - } = useDashboard(); + const { tasks, users, currentUser, createTask, updateTask, deleteTask, canEditUserTasks } = useDashboard(); const canDuplicate = Boolean(onDuplicateTask); const [submitError, setSubmitError] = useState(null); @@ -176,28 +70,8 @@ export const TaskModal: React.FC = ({ const [cognitiveLoad, setCognitiveLoad] = useState('medium'); const [status, setStatus] = useState('todo'); - // ClickUp Task Type custom field state - const [clickupTaskType, setClickupTaskType] = useState(''); - const [clickupTaskTypeId, setClickupTaskTypeId] = useState(''); - const [clickupTaskTypeFieldId, setClickupTaskTypeFieldId] = useState(''); - - // ClickUp folder and list destination state (isolated per task modal) - const [modalSpaceId, setModalSpaceId] = useState(''); - const [modalFoldersAndLists, setModalFoldersAndLists] = useState<{ - folders: ClickupFolder[]; - folderlessLists: ClickupList[]; - }>({ folders: [], folderlessLists: [] }); - const [clickupFolderId, setClickupFolderId] = useState(''); - const [clickupListId, setClickupListId] = useState(''); - const [isCreatingList, setIsCreatingList] = useState(false); - const [newListName, setNewListName] = useState(''); - const [isSubmittingNewList, setIsSubmittingNewList] = useState(false); - const [newListError, setNewListError] = useState(null); - const [isSubmitting, setIsSubmitting] = useState(false); const [showConfirmDelete, setShowConfirmDelete] = useState(false); - const [isSpaceDropdownOpen, setIsSpaceDropdownOpen] = useState(false); - const spaceDropdownRef = useRef(null); const canEdit = useMemo(() => { if (!taskToEdit) return true; @@ -212,28 +86,7 @@ export const TaskModal: React.FC = ({ setDueDate(taskToEdit.dueDate || ''); setCognitiveLoad(taskToEdit.cognitiveLoad || 'medium'); setStatus(taskToEdit.status || 'todo'); - setClickupFolderId(taskToEdit.clickupFolderId || ''); - setClickupListId(taskToEdit.clickupListId || ''); - setClickupTaskType(taskToEdit.clickupTaskType || ''); - setClickupTaskTypeId(taskToEdit.clickupTaskTypeId || ''); - setClickupTaskTypeFieldId(taskToEdit.clickupTaskTypeFieldId || ctxClickupTaskTypeFieldId || ''); - // Resolve space ID specific to this task - let initialSpaceId = taskToEdit.clickupSpaceId || ''; - if (!initialSpaceId && taskToEdit.clickupListId && spaceFoldersAndListsMap) { - for (const [sId, data] of Object.entries(spaceFoldersAndListsMap)) { - const inFolders = data.folders?.some(f => f.lists?.some(l => l.id === taskToEdit.clickupListId)); - const inFolderless = data.folderlessLists?.some(l => l.id === taskToEdit.clickupListId); - if (inFolders || inFolderless) { - initialSpaceId = sId; - break; - } - } - } - if (!initialSpaceId) { - initialSpaceId = selectedClickupSpaceId || (clickupSpaces.length > 0 ? clickupSpaces[0].id : ''); - } - setModalSpaceId(initialSpaceId); } else { setTitle(''); setDescription(''); @@ -242,31 +95,10 @@ export const TaskModal: React.FC = ({ setDueDate(''); setCognitiveLoad('medium'); setStatus(defaultStatus || 'todo'); - setClickupFolderId(''); - setClickupListId(''); - setModalSpaceId(selectedClickupSpaceId || (clickupSpaces.length > 0 ? clickupSpaces[0].id : '')); - // If user has a role, match default task type if options available - const userObj = users.find(u => u.id === defaultUser); - const roleName = userObj?.role === 'content' ? 'Content & Copy' : 'Design'; - const matchedOption = (clickupCustomFieldOptions || []).find( - o => (o?.name || '').toLowerCase() === roleName.toLowerCase() - ); - if (matchedOption) { - setClickupTaskType(matchedOption.name); - setClickupTaskTypeId(matchedOption.id); - } else { - setClickupTaskType(''); - setClickupTaskTypeId(''); - } - setClickupTaskTypeFieldId(ctxClickupTaskTypeFieldId || ''); } setShowConfirmDelete(false); - setIsCreatingList(false); - setNewListName(''); - setNewListError(null); setSubmitError(null); - setIsSpaceDropdownOpen(false); }, [ taskToEdit, defaultUserId, @@ -274,32 +106,8 @@ export const TaskModal: React.FC = ({ currentUser, users, isOpen, - ctxClickupTaskTypeFieldId, - clickupCustomFieldOptions, - selectedClickupSpaceId, - clickupSpaces, - spaceFoldersAndListsMap, - ]); - // Derived effective task type options (ClickUp dropdown custom fields with fallback) - const effectiveTaskTypeOptions = useMemo(() => { - let list = - clickupCustomFieldOptions && clickupCustomFieldOptions.length > 0 - ? [...clickupCustomFieldOptions] - : [ - { id: 'content', name: 'Content & Copy' }, - { id: 'design', name: 'Design' }, - ]; - if ( - clickupTaskType && - !list.some( - o => (o?.name || '').toLowerCase() === (clickupTaskType || '').toLowerCase() || o?.id === clickupTaskTypeId - ) - ) { - list.unshift({ id: clickupTaskTypeId || clickupTaskType, name: clickupTaskType }); - } - return list; - }, [clickupCustomFieldOptions, clickupTaskType, clickupTaskTypeId]); + ]); const activities = useMemo(() => { return Array.isArray(taskToEdit?.activityLog) ? taskToEdit.activityLog : []; @@ -337,153 +145,6 @@ export const TaskModal: React.FC = ({ } }, [taskToEdit, activities]); - // Keep modal's folders and lists synced with modalSpaceId for this task - useEffect(() => { - if (!modalSpaceId) { - setModalFoldersAndLists({ folders: [], folderlessLists: [] }); - return; - } - let isMounted = true; - if (spaceFoldersAndListsMap?.[modalSpaceId]) { - setModalFoldersAndLists(spaceFoldersAndListsMap[modalSpaceId]); - } else if (modalSpaceId === selectedClickupSpaceId && clickupFoldersAndLists) { - setModalFoldersAndLists(clickupFoldersAndLists); - } - - if (getFoldersAndListsForSpace) { - getFoldersAndListsForSpace(modalSpaceId).then(data => { - if (isMounted && data) { - setModalFoldersAndLists(data); - } - }); - } - - return () => { - isMounted = false; - }; - }, [modalSpaceId, spaceFoldersAndListsMap, selectedClickupSpaceId, clickupFoldersAndLists, getFoldersAndListsForSpace]); - - // Available lists for the selected folder within the modal's space - const availableLists = useMemo(() => { - const folders = Array.isArray(modalFoldersAndLists?.folders) ? modalFoldersAndLists.folders : []; - const folderlessLists = Array.isArray(modalFoldersAndLists?.folderlessLists) ? modalFoldersAndLists.folderlessLists : []; - if (clickupFolderId) { - const folder = folders.find(f => f && f.id === clickupFolderId); - return Array.isArray(folder?.lists) ? folder.lists : []; - } - return folderlessLists; - }, [clickupFolderId, modalFoldersAndLists]); - - // Click outside and Escape key handler for Space dropdown - useEffect(() => { - if (!isSpaceDropdownOpen) return; - const handleOutsideClick = (e: MouseEvent) => { - if (spaceDropdownRef.current && !spaceDropdownRef.current.contains(e.target as Node)) { - setIsSpaceDropdownOpen(false); - } - }; - const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === 'Escape') { - setIsSpaceDropdownOpen(false); - } - }; - document.addEventListener('mousedown', handleOutsideClick); - document.addEventListener('keydown', handleKeyDown); - return () => { - document.removeEventListener('mousedown', handleOutsideClick); - document.removeEventListener('keydown', handleKeyDown); - }; - }, [isSpaceDropdownOpen]); - - // Currently selected space display label for the modal - const selectedSpaceInfo = useMemo(() => { - if (!modalSpaceId) return null; - const spaces = Array.isArray(clickupSpaces) ? clickupSpaces : []; - const s = spaces.find(space => space && space.id === modalSpaceId); - if (!s) return null; - const rawFolders = - spaceFoldersMap?.[s.id] || - (s.id === modalSpaceId && Array.isArray(modalFoldersAndLists?.folders) - ? modalFoldersAndLists.folders.map(f => f?.name).filter(Boolean) - : undefined); - const folders = Array.isArray(rawFolders) ? rawFolders : undefined; - const folderListStr = - folders && folders.length > 0 - ? `(${folders.join(', ')})` - : folders - ? '(Folderless)' - : ''; - return { - name: s.name, - folderListStr, - fullText: folderListStr ? `${s.name} | ${folderListStr}` : s.name, - }; - }, [clickupSpaces, modalSpaceId, spaceFoldersMap, modalFoldersAndLists]); - - // Derived current selected ClickUp destination breadcrumb for this specific task - const currentDestinationDisplay = useMemo(() => { - if (!isZensciencesUser || !isClickupConnected) return null; - - const spaces = Array.isArray(clickupSpaces) ? clickupSpaces : []; - const spaceObj = spaces.find(s => s && s.id === modalSpaceId); - const spaceName = spaceObj?.name || (modalSpaceId ? `Space ${modalSpaceId}` : ''); - - const folders = Array.isArray(modalFoldersAndLists?.folders) ? modalFoldersAndLists.folders : []; - const folderlessLists = Array.isArray(modalFoldersAndLists?.folderlessLists) ? modalFoldersAndLists.folderlessLists : []; - - let folderName: string | undefined = taskToEdit?.clickupFolderName; - if (clickupFolderId) { - const f = folders.find(fold => fold && fold.id === clickupFolderId); - if (f?.name) folderName = f.name; - } - - let listName: string | undefined = taskToEdit?.clickupListName; - if (clickupListId) { - if (clickupFolderId) { - const f = folders.find(fold => fold && fold.id === clickupFolderId); - const l = f?.lists?.find(lst => lst && lst.id === clickupListId); - if (l?.name) listName = l.name; - } else { - const l = folderlessLists.find(lst => lst && lst.id === clickupListId); - if (l?.name) listName = l.name; - } - } - - const parts: string[] = []; - if (spaceName) parts.push(spaceName); - if (folderName) parts.push(folderName); - if (listName) parts.push(listName); - - const hasList = Boolean(clickupListId || taskToEdit?.clickupListId); - const isPipeline = status === 'pipeline'; - - let pathString = parts.length > 0 ? parts.join(' β€Ί ') : 'None selected'; - if (!hasList && isPipeline) { - pathString = spaceName ? `${spaceName} (List optional for Pipeline)` : 'None (Pipeline - no list required)'; - } - - return { - spaceName, - folderName, - listName, - hasList, - isPipeline, - pathString, - clickupUrl: taskToEdit?.clickupUrl, - clickupTaskId: taskToEdit?.clickupTaskId, - }; - }, [ - isZensciencesUser, - isClickupConnected, - modalSpaceId, - clickupSpaces, - modalFoldersAndLists, - clickupFolderId, - clickupListId, - taskToEdit, - status, - ]); - const selectedUser = users.find(u => u.id === userId); const role = selectedUser?.role || 'content'; @@ -501,31 +162,6 @@ export const TaskModal: React.FC = ({ setDueDate(`${yyyy}-${mm}-${dd}`); }; - const handleCreateNewList = async (e: React.FormEvent) => { - e.preventDefault(); - if (!newListName.trim()) return; - setIsSubmittingNewList(true); - setNewListError(null); - try { - const created = await createClickupList( - newListName.trim(), - modalSpaceId, - clickupFolderId || undefined - ); - if (created) { - setClickupListId(created.id); - setIsCreatingList(false); - setNewListName(''); - } else { - setNewListError('Failed to create list'); - } - } catch (err: any) { - setNewListError(err.message || 'Error creating list'); - } finally { - setIsSubmittingNewList(false); - } - }; - const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); const isDeadlineRequired = status !== 'pipeline' && status !== 'retainer'; @@ -535,21 +171,6 @@ export const TaskModal: React.FC = ({ setSubmitError(null); const finalDueDate = (status === 'pipeline' || status === 'retainer') ? undefined : (dueDate.trim() || undefined); - // Resolve folder and list names from the modal's space data - let folderName: string | undefined; - let listName: string | undefined; - const folders = modalFoldersAndLists?.folders || []; - const folderlessLists = modalFoldersAndLists?.folderlessLists || []; - if (clickupFolderId) { - const f = folders.find(fold => fold.id === clickupFolderId); - folderName = f?.name || taskToEdit?.clickupFolderName; - const l = f?.lists?.find(lst => lst.id === clickupListId); - listName = l?.name || (clickupListId === taskToEdit?.clickupListId ? taskToEdit?.clickupListName : undefined); - } else if (clickupListId) { - const l = folderlessLists.find(lst => lst.id === clickupListId); - listName = l?.name || (clickupListId === taskToEdit?.clickupListId ? taskToEdit?.clickupListName : undefined); - } - try { if (taskToEdit) { await updateTask(taskToEdit.id, { @@ -559,14 +180,7 @@ export const TaskModal: React.FC = ({ dueDate: finalDueDate, cognitiveLoad, status, - clickupFolderId: clickupFolderId || undefined, - clickupFolderName: folderName, - clickupListId: clickupListId || undefined, - clickupListName: listName, - clickupSpaceId: modalSpaceId || undefined, - clickupTaskType: clickupTaskType || undefined, - clickupTaskTypeId: clickupTaskTypeId || undefined, - clickupTaskTypeFieldId: clickupTaskTypeFieldId || ctxClickupTaskTypeFieldId || undefined, + }); } else { await createTask({ @@ -576,14 +190,7 @@ export const TaskModal: React.FC = ({ dueDate: finalDueDate, cognitiveLoad, status, - clickupFolderId: clickupFolderId || undefined, - clickupFolderName: folderName, - clickupListId: clickupListId || undefined, - clickupListName: listName, - clickupSpaceId: modalSpaceId || undefined, - clickupTaskType: clickupTaskType || undefined, - clickupTaskTypeId: clickupTaskTypeId || undefined, - clickupTaskTypeFieldId: clickupTaskTypeFieldId || ctxClickupTaskTypeFieldId || undefined, + }); } onClose(); @@ -612,13 +219,13 @@ export const TaskModal: React.FC = ({ useEffect(() => { if (!isOpen) return; const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === 'Escape' && !isSubmitting && !isSubmittingNewList) { + if (e.key === 'Escape' && !isSubmitting) { onClose(); } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); - }, [isOpen, isSubmitting, isSubmittingNewList, onClose]); + }, [isOpen, isSubmitting, onClose]); return ( @@ -630,7 +237,7 @@ export const TaskModal: React.FC = ({ transition={{ duration: 0.15 }} className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/65 backdrop-blur-xs overflow-y-auto" onClick={e => { - if (e.target === e.currentTarget && !isSubmitting && !isSubmittingNewList) onClose(); + if (e.target === e.currentTarget && !isSubmitting) onClose(); }} > = ({
)} - {/* Task Name & Task Type */} -
-
+ {/* Task Name */} +
+
@@ -736,37 +343,6 @@ export const TaskModal: React.FC = ({ />
-
- -
- - -
-
{/* Row: Assignee & Status */} @@ -977,201 +553,6 @@ export const TaskModal: React.FC = ({ )}
- {/* ClickUp Destination (Folder & List) - for @zensciences.com users */} - {isZensciencesUser && isClickupConnected && ( -
-
-
- - ClickUp Destination - - {status === 'pipeline' && ( - - Optional for Pipeline - - )} -
- -
- - {/* Current Destination Path Preview for this specific task */} -
-
-
- - - Destination: - - - {currentDestinationDisplay?.pathString} - -
- {currentDestinationDisplay?.clickupUrl ? ( - - Open in ClickUp - - - ) : status === 'pipeline' && !currentDestinationDisplay?.hasList ? ( - - No list required - - ) : null} -
-
- - {/* Space Selection with folders against each space name */} -
- -
- - - {isSpaceDropdownOpen && (Array.isArray(clickupSpaces) ? clickupSpaces.length > 0 : false) && ( -
- {(Array.isArray(clickupSpaces) ? clickupSpaces : []).map(s => { - const rawFolders = - spaceFoldersMap?.[s.id] || - (s.id === modalSpaceId && Array.isArray(modalFoldersAndLists?.folders) - ? modalFoldersAndLists.folders.map(f => f?.name).filter(Boolean) - : undefined); - const folders = Array.isArray(rawFolders) ? rawFolders : undefined; - const folderListStr = - folders && folders.length > 0 - ? `(${folders.join(', ')})` - : folders - ? '(Folderless)' - : ''; - const fullText = folderListStr ? `${s.name} | ${folderListStr}` : s.name; - const isSelected = s.id === modalSpaceId; - - return ( - { - setModalSpaceId(s.id); - setClickupFolderId(''); - setClickupListId(''); - setIsSpaceDropdownOpen(false); - }} - /> - ); - })} -
- )} -
-
- - {isCreatingList ? ( -
- setNewListName(e.target.value)} - placeholder="Enter new ClickUp list name..." - className="w-full rounded-xl border border-purple-300 dark:border-purple-700 bg-white dark:bg-[#141414] py-1.5 px-3 text-xs text-neutral-900 dark:text-white" - /> - {newListError &&

{newListError}

} - -
- ) : ( -
- {/* Folder Selection */} -
- -
- - -
-
- - {/* List Selection */} -
- -
- - -
-
-
- )} -
- )} - {!canEdit && (
Read-only view: You only have permission to edit tasks on your assigned board or swimlane. diff --git a/src/components/UnassignedListRibbon.tsx b/src/components/UnassignedListRibbon.tsx deleted file mode 100644 index 3b2d51d..0000000 --- a/src/components/UnassignedListRibbon.tsx +++ /dev/null @@ -1,321 +0,0 @@ -import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react'; -import { createPortal } from 'react-dom'; -import { Task, User } from '../types'; -import { useDashboard } from '../context/DashboardContext'; -import { Folder, ListPlus, FolderPlus, ChevronRight, Check, Plus, AlertCircle, Loader2 } from 'lucide-react'; - -interface UnassignedListRibbonProps { - tasks: Task[]; - users: User[]; - onTaskClick: (task: Task) => void; -} - -export const UnassignedListRibbon: React.FC = React.memo(({ - tasks, - users, - onTaskClick, -}) => { - const { - isZensciencesUser, - isClickupConnected, - setShowClickupPrompt, - selectedClickupSpaceId, - clickupFoldersAndLists, - createClickupList, - assignTaskClickupList, - } = useDashboard(); - - const userMap = useMemo(() => new Map(users.map(u => [u.id, u])), [users]); - - // Safe folders and folderless lists - const folders = useMemo(() => clickupFoldersAndLists?.folders || [], [clickupFoldersAndLists]); - const folderlessLists = useMemo(() => clickupFoldersAndLists?.folderlessLists || [], [clickupFoldersAndLists]); - - // Tasks lacking ClickUp list assignment, excluding done/archived/pipeline - const unassignedTasks = useMemo(() => { - return tasks.filter( - t => !t.clickupListId && t.status !== 'done' && t.status !== 'archived' && t.status !== 'pipeline' - ); - }, [tasks]); - - // List Assignment Flyout State - const [activeFlyoutTaskId, setActiveFlyoutTaskId] = useState(null); - const [flyoutPosition, setFlyoutPosition] = useState<{ top: number; left: number } | null>(null); - const [isCreatingList, setIsCreatingList] = useState(false); - const [newListName, setNewListName] = useState(''); - const [selectedFolderForNewList, setSelectedFolderForNewList] = useState(''); - const [isSubmittingNewList, setIsSubmittingNewList] = useState(false); - const [newListError, setNewListError] = useState(null); - - const flyoutMenuRef = useRef(null); - const activeTriggerRef = useRef(null); - - const closeFlyout = useCallback(() => { - setActiveFlyoutTaskId(null); - setFlyoutPosition(null); - activeTriggerRef.current = null; - setIsCreatingList(false); - setNewListName(''); - setNewListError(null); - }, []); - - const openFlyout = useCallback((taskId: string, element: HTMLElement) => { - if (!isClickupConnected) { - setShowClickupPrompt(true); - return; - } - activeTriggerRef.current = element; - const rect = element.getBoundingClientRect(); - const popupHeight = 320; - const popupWidth = 280; - const openAbove = rect.top >= popupHeight + 10; - const top = openAbove ? rect.top - popupHeight - 4 : rect.bottom + 4; - const left = Math.max(10, Math.min(rect.left, window.innerWidth - popupWidth - 10)); - setFlyoutPosition({ top, left }); - setActiveFlyoutTaskId(taskId); - setIsCreatingList(false); - setNewListName(''); - setNewListError(null); - }, [isClickupConnected, setShowClickupPrompt]); - - // Dismiss on outside click - useEffect(() => { - if (!activeFlyoutTaskId) return; - const handleOutside = (e: MouseEvent) => { - if (flyoutMenuRef.current && !flyoutMenuRef.current.contains(e.target as Node)) { - closeFlyout(); - } - }; - window.addEventListener('mousedown', handleOutside); - return () => window.removeEventListener('mousedown', handleOutside); - }, [activeFlyoutTaskId, closeFlyout]); - - const handleSelectList = async (listId: string, listName: string, folderId?: string, folderName?: string) => { - if (!activeFlyoutTaskId) return; - try { - await assignTaskClickupList(activeFlyoutTaskId, listId, listName, folderId, folderName); - closeFlyout(); - } catch (err) { - console.warn('Failed to assign task list:', err); - } - }; - - const handleCreateAndAssignList = async (e: React.FormEvent) => { - e.preventDefault(); - if (!activeFlyoutTaskId || !newListName.trim()) return; - setIsSubmittingNewList(true); - setNewListError(null); - try { - const created = await createClickupList( - newListName.trim(), - selectedClickupSpaceId, - selectedFolderForNewList || undefined - ); - if (created) { - const folder = folders.find(f => f.id === selectedFolderForNewList); - await assignTaskClickupList( - activeFlyoutTaskId, - created.id, - created.name, - folder?.id, - folder?.name - ); - closeFlyout(); - } else { - setNewListError('Failed to create list in ClickUp'); - } - } catch (err: any) { - setNewListError(err.message || 'Error creating list'); - } finally { - setIsSubmittingNewList(false); - } - }; - - // If not zensciences user or no unassigned tasks, don't display - if (!isZensciencesUser || unassignedTasks.length === 0) { - return null; - } - - const activeTask = tasks.find(t => t.id === activeFlyoutTaskId); - - return ( -
-
- {/* Leading badge */} -
- - Unassigned ClickUp Lists - - {unassignedTasks.length} - -
- - {/* Scrollable list of task chips */} -
- {unassignedTasks.map(task => { - const assignee = userMap.get(task.userId); - return ( -
- - - {assignee && ( - - {assignee.name.split(' ')[0]} - - )} - - -
- ); - })} -
-
- - {/* Popover Flyout for List Selection / Creation */} - {activeFlyoutTaskId && flyoutPosition && createPortal( -
-
-
-

Assign ClickUp Destination

-

{activeTask?.title}

-
- -
- - {/* Create new list form */} - {isCreatingList ? ( -
-

Create New ClickUp List

- setNewListName(e.target.value)} - placeholder="List name..." - autoFocus - className="w-full px-2 py-1.5 rounded border border-zinc-300 dark:border-zinc-700 bg-white dark:bg-zinc-800 text-xs focus:outline-none focus:ring-1 focus:ring-purple-500" - /> - {folders.length > 0 && ( - - )} - {newListError && ( -

{newListError}

- )} -
- - -
-
- ) : null} - - {/* List existing folders and lists */} -
- {/* Folders and lists */} - {folders.map(folder => ( -
-
- - {folder.name} -
- {folder.lists?.map(list => ( - - ))} -
- ))} - - {/* Folderless lists */} - {folderlessLists.length > 0 && ( -
-
- - Folderless Lists -
- {folderlessLists.map(list => ( - - ))} -
- )} - - {folders.length === 0 && folderlessLists.length === 0 && ( -
- -

No lists found in this space.

- -
- )} -
-
, - document.body - )} -
- ); -}); - -UnassignedListRibbon.displayName = 'UnassignedListRibbon'; diff --git a/src/context/DashboardContext.tsx b/src/context/DashboardContext.tsx index 1277647..a76f8e0 100644 --- a/src/context/DashboardContext.tsx +++ b/src/context/DashboardContext.tsx @@ -11,13 +11,9 @@ import { TaskOrderUpdate, QueuedMutation, TaskActivity, - ClickupSpace, - ClickupList, - ClickupFolder, - ClickupMember, - ClickupCustomFieldOption, + AuditLogEntry, - ClickupWebhookStatus, + } from '../types'; import { INITIAL_USERS, INITIAL_TASKS } from '../data/initialData'; import { compareTasksByDeadline, formatBillableHours, getTaskBillableMs } from '../utils/workload'; @@ -25,7 +21,7 @@ import { signInWithGoogle, signOutFirebase, onFirebaseAuthStateChanged } from '. export interface FirestoreStatus { connected: boolean; - mode: 'admin' | 'web' | 'local'; + mode: 'admin'; projectId: string; databaseId: string; serviceAccountFound: boolean; @@ -100,7 +96,6 @@ interface DashboardContextType { authError: string | null; setAuthError: (err: string | null) => void; syncWithFirestore: () => Promise<{ success: boolean; message: string }>; - uploadServiceAccountKey: (keyContent: string) => Promise<{ success: boolean; message: string }>; login: (name: string, role: Role, email: string) => Promise; loginWithGoogle: () => Promise; logout: () => void; @@ -111,8 +106,7 @@ interface DashboardContextType { role: Role; isCreativeDirector?: boolean; creativeDirectorId?: string; - clickupUserId?: string; - clickupUsername?: string; + }) => Promise; updateUserProfile: (userId: string, updates: Partial) => Promise; remapUserTasks: (fromUserIdOrEmail: string, toUserId: string, deleteSourceUser?: boolean) => Promise<{ success: boolean; remappedCount: number; error?: string }>; @@ -125,35 +119,6 @@ interface DashboardContextType { creativeDirectors: User[]; activeBoardId: string; setActiveBoardId: (boardId: string) => void; - // ClickUp Integration - isZensciencesUser: boolean; - isClickupConnected: boolean; - clickupApiKey: string; - clickupMembers: ClickupMember[]; - loadClickupMembers: (apiKey?: string) => Promise; - clickupSpaces: ClickupSpace[]; - selectedClickupSpaceId: string; - clickupFoldersAndLists: { folders: ClickupFolder[]; folderlessLists: ClickupList[] }; - spaceFoldersMap: Record; - spaceFoldersAndListsMap: Record; - getFoldersAndListsForSpace: (spaceId: string) => Promise<{ folders: ClickupFolder[]; folderlessLists: ClickupList[] }>; - showClickupPrompt: boolean; - setShowClickupPrompt: (val: boolean) => void; - connectClickup: (apiKey: string) => Promise<{ success: boolean; error?: string }>; - disconnectClickup: () => void; - setSelectedClickupSpaceId: (spaceId: string, spaceName?: string) => Promise; - createClickupList: (name: string, spaceId: string, folderId?: string) => Promise; - syncUserTasksWithClickUp: (userId: string) => Promise<{ success: boolean; syncedCount: number; archivedCount: number; message: string }>; - assignTaskClickupList: (taskId: string, listId: string, listName: string, folderId?: string, folderName?: string) => Promise; - clickupCustomFieldOptions: ClickupCustomFieldOption[]; - clickupTaskTypeFieldId: string; - isLoadingTaskTypes: boolean; - fetchClickupCustomFields: (params: { listId?: string; spaceId?: string; folderId?: string }) => Promise; - getUserSyncState: (userId: string) => 'synced' | 'pending' | 'failed' | 'unmapped'; - // ClickUp Real-Time Webhook & Audit Stream - clickupWebhookStatus: ClickupWebhookStatus | null; - refreshClickupWebhookStatus: () => Promise; - registerClickupWebhook: (customEndpoint?: string) => Promise<{ success: boolean; message: string; webhookId?: string }>; fetchAuditLogs: (limit?: number) => Promise; downloadAuditLogs: () => void; // Tasks @@ -164,16 +129,7 @@ interface DashboardContextType { dueDate?: string; cognitiveLoad: 'low' | 'medium' | 'high'; status: TaskStatus; - clickupTaskId?: string; - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - clickupUrl?: string; - clickupTaskType?: string; - clickupTaskTypeId?: string; - clickupTaskTypeFieldId?: string; + }) => Promise; updateTask: (id: string, updates: Partial) => Promise; adjustBillableHours: (taskId: string, newDurationMs: number, reason?: string) => Promise; @@ -190,7 +146,7 @@ interface DashboardContextType { title?: string; targetStatus?: TaskStatus; targetDueDate?: string; - }) => Promise<{ task: Task; clickupSubtaskCreated: boolean; warning?: string; message?: string }>; + }) => Promise<{ task: Task; warning?: string; message?: string }>; } const DashboardContext = createContext(undefined); @@ -297,37 +253,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children return targetUserId === currentUser.id; }, [currentUser, isSuperadmin, isCreativeDirector]); - // ClickUp Integration State - const isZensciencesUser = useMemo(() => { - return Boolean(currentUser?.email?.toLowerCase().endsWith('@zensciences.com')); - }, [currentUser]); - - const clickupApiKey = useMemo(() => { - return ''; // Saved credentials stay on the server; use clickupConnected. - }, [currentUser]); - - const isClickupConnected = useMemo(() => { - return Boolean(isZensciencesUser && currentUser?.clickupConnected); - }, [isZensciencesUser, currentUser?.clickupConnected]); - - const [showClickupPrompt, setShowClickupPrompt] = useState(false); - const [clickupSpaces, setClickupSpaces] = useState([]); - const [selectedClickupSpaceId, setSelectedClickupSpaceIdState] = useState(() => { - return currentUser?.selectedClickupSpaceId || localStorage.getItem('zenflow_clickup_space_id') || ''; - }); - const selectedClickupSpaceIdRef = useRef(selectedClickupSpaceId); - selectedClickupSpaceIdRef.current = selectedClickupSpaceId; - const [clickupFoldersAndLists, setClickupFoldersAndLists] = useState<{ - folders: ClickupFolder[]; - folderlessLists: ClickupList[]; - }>({ folders: [], folderlessLists: [] }); - const [spaceFoldersMap, setSpaceFoldersMap] = useState>({}); - const [spaceFoldersAndListsMap, setSpaceFoldersAndListsMap] = useState< - Record - >({}); - const spaceFoldersAndListsMapRef = useRef(spaceFoldersAndListsMap); - spaceFoldersAndListsMapRef.current = spaceFoldersAndListsMap; - const [darkMode, setDarkMode] = useState(() => { try { const saved = localStorage.getItem(THEME_KEY); @@ -340,12 +265,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children const [isAuthChecking, setIsAuthChecking] = useState(true); const [authError, setAuthError] = useState(null); - const [clickupMembers, setClickupMembers] = useState([]); - const [clickupCustomFieldOptions, setClickupCustomFieldOptions] = useState([]); - const [clickupTaskTypeFieldId, setClickupTaskTypeFieldId] = useState(''); - const [isLoadingTaskTypes, setIsLoadingTaskTypes] = useState(false); - const [userSyncFailures, setUserSyncFailures] = useState>({}); - const [clickupWebhookStatus, setClickupWebhookStatus] = useState(null); const [syncStatus, setSyncStatus] = useState<'connected' | 'connecting' | 'offline'>('connecting'); const [isLoading, setIsLoading] = useState(true); @@ -363,18 +282,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children } }, []); - const refreshClickupWebhookStatus = useCallback(async () => { - try { - const res = await fetch('/api/clickup/webhook/status'); - if (res.ok) { - const data: ClickupWebhookStatus = await res.json(); - setClickupWebhookStatus(data); - } - } catch { - // ignore - } - }, []); - // Apply dark mode class to root document & body useEffect(() => { try { @@ -572,8 +479,8 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children if (!currentUser) return; fetchState(); refreshFirestoreStatus(); - refreshClickupWebhookStatus(); - }, [currentUser?.id, fetchState, refreshFirestoreStatus, refreshClickupWebhookStatus]); + + }, [currentUser?.id, fetchState, refreshFirestoreStatus]); // Online / Offline network status listener with auto queue replay useEffect(() => { @@ -735,152 +642,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children }; }, [replayQueue, currentUser?.id]); - // ClickUp Loaders & Handlers - const loadClickupSpaces = useCallback(async (apiKey: string) => { - try { - const res = await fetch('/api/clickup/spaces', { - headers: { 'x-clickup-api-key': apiKey }, - }); - if (res.ok) { - const data = await res.json(); - if (Array.isArray(data.spaces)) { - setClickupSpaces(data.spaces); - if (data.spaces.length > 0 && !selectedClickupSpaceIdRef.current) { - const firstId = data.spaces[0].id; - setSelectedClickupSpaceIdState(firstId); - localStorage.setItem('zenflow_clickup_space_id', firstId); - } - // Preload folder names for all spaces in background - data.spaces.forEach(async (sp: ClickupSpace) => { - try { - const fRes = await fetch( - `/api/clickup/folders-and-lists?spaceId=${encodeURIComponent(sp.id)}`, - { headers: { 'x-clickup-api-key': apiKey } } - ); - if (fRes.ok) { - const fData = await fRes.json(); - const folderNames = (fData.folders || []).map((f: ClickupFolder) => f.name); - setSpaceFoldersMap(prev => ({ - ...prev, - [sp.id]: folderNames, - })); - setSpaceFoldersAndListsMap(prev => ({ - ...prev, - [sp.id]: { - folders: fData.folders || [], - folderlessLists: fData.folderlessLists || [], - }, - })); - } - } catch { - // ignore - } - }); - } - } - } catch (err) { - console.warn('Failed to load ClickUp spaces:', err); - } - }, []); - - const loadClickupFoldersAndLists = useCallback(async (spaceId: string, apiKey: string) => { - if (!spaceId) return; - try { - const res = await fetch(`/api/clickup/folders-and-lists?spaceId=${encodeURIComponent(spaceId)}`, { - headers: { 'x-clickup-api-key': apiKey }, - }); - if (res.ok) { - const data = await res.json(); - const payload = { - folders: data.folders || [], - folderlessLists: data.folderlessLists || [], - }; - setClickupFoldersAndLists(payload); - setSpaceFoldersAndListsMap(prev => ({ - ...prev, - [spaceId]: payload, - })); - const folderNames = (data.folders || []).map((f: ClickupFolder) => f.name); - setSpaceFoldersMap(prev => ({ - ...prev, - [spaceId]: folderNames, - })); - } - } catch (err) { - console.warn('Failed to load ClickUp folders & lists:', err); - } - }, []); - - const getFoldersAndListsForSpace = useCallback(async (spaceId: string) => { - if (!spaceId) return { folders: [], folderlessLists: [] }; - if (spaceFoldersAndListsMapRef.current[spaceId]) { - return spaceFoldersAndListsMapRef.current[spaceId]; - } - const key = ''; - try { - const res = await fetch(`/api/clickup/folders-and-lists?spaceId=${encodeURIComponent(spaceId)}`, { - headers: key ? { 'x-clickup-api-key': key } : {}, - }); - if (res.ok) { - const data = await res.json(); - const result = { - folders: data.folders || [], - folderlessLists: data.folderlessLists || [], - }; - setSpaceFoldersAndListsMap(prev => ({ - ...prev, - [spaceId]: result, - })); - const folderNames = (data.folders || []).map((f: ClickupFolder) => f.name); - setSpaceFoldersMap(prev => ({ - ...prev, - [spaceId]: folderNames, - })); - return result; - } - } catch (err) { - console.warn('Failed to load folders & lists for space:', err); - } - return { folders: [], folderlessLists: [] }; - }, []); - - useEffect(() => { - if (isClickupConnected) { - loadClickupSpaces(clickupApiKey); - } - }, [isClickupConnected, clickupApiKey, loadClickupSpaces]); - - useEffect(() => { - if (isClickupConnected && selectedClickupSpaceId) { - loadClickupFoldersAndLists(selectedClickupSpaceId, clickupApiKey); - } - }, [isClickupConnected, clickupApiKey, selectedClickupSpaceId, loadClickupFoldersAndLists]); - - const loadClickupMembers = useCallback(async (apiKey?: string): Promise => { - const key = (apiKey || clickupApiKey || '').trim(); - try { - const headers: Record = {}; - if (key) headers['x-clickup-api-key'] = key; - const res = await fetch('/api/clickup/members', { headers }); - if (res.ok) { - const data = await res.json(); - if (Array.isArray(data.members)) { - setClickupMembers(data.members); - return data.members; - } - } - } catch (err) { - console.warn('Failed to load ClickUp members:', err); - } - return []; - }, [clickupApiKey]); - - useEffect(() => { - if (isClickupConnected) { - loadClickupMembers(clickupApiKey); - } - }, [isClickupConnected, clickupApiKey, loadClickupMembers]); - // Google Auth Session Enforcement // If not logged in via Google Auth, log them out and bring them to login screen useEffect(() => { @@ -961,12 +722,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children }, []); const updateUserProfile = useCallback(async (userId: string, updates: Partial): Promise => { - const publicUpdates = { ...updates }; - delete publicUpdates.clickupApiKey; - setUsers(prev => prev.map(u => (u.id === userId ? { ...u, ...publicUpdates } : u))); - if (currentUserRef.current?.id === userId) { - setCurrentUser(prev => (prev ? { ...prev, ...publicUpdates } : null)); - } try { const res = await fetch(`/api/users/${userId}`, { method: 'PUT', @@ -1056,226 +811,11 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children } }, [isSuperadmin]); - const connectClickup = useCallback(async (apiKey: string): Promise<{ success: boolean; error?: string }> => { - const cleanKey = apiKey.trim(); - if (!cleanKey) return { success: false, error: 'API key is required' }; - try { - const res = await fetch('/api/clickup/verify', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ apiKey: cleanKey }), - }); - const data = await res.json(); - if (!res.ok || !data.valid) { - return { success: false, error: data.error || 'Invalid ClickUp API Key' }; - } - if (currentUserRef.current) { - await updateUserProfile(currentUserRef.current.id, { clickupApiKey: cleanKey }); - } - await loadClickupSpaces(''); - setShowClickupPrompt(false); - return { success: true }; - } catch (err: any) { - return { success: false, error: err.message || 'Connection failed' }; - } - }, [updateUserProfile, loadClickupSpaces]); - - const disconnectClickup = useCallback(() => { - localStorage.removeItem('zenflow_clickup_api_key'); - if (currentUserRef.current) { - updateUserProfile(currentUserRef.current.id, { clickupApiKey: '' }); - } - setClickupSpaces([]); - setClickupFoldersAndLists({ folders: [], folderlessLists: [] }); - }, [updateUserProfile]); - - const setSelectedClickupSpaceId = useCallback(async (spaceId: string, spaceName?: string) => { - setSelectedClickupSpaceIdState(spaceId); - try { - localStorage.setItem('zenflow_clickup_space_id', spaceId); - if (spaceName) localStorage.setItem('zenflow_clickup_space_name', spaceName); - } catch {} - - if (currentUserRef.current) { - await updateUserProfile(currentUserRef.current.id, { - selectedClickupSpaceId: spaceId, - selectedClickupSpaceName: spaceName, - }); - } - - if (isClickupConnected) { - await loadClickupFoldersAndLists(spaceId, clickupApiKey); - } - }, [clickupApiKey, isClickupConnected, updateUserProfile, loadClickupFoldersAndLists]); - - const createClickupList = useCallback(async ( - name: string, - spaceId: string, - folderId?: string - ): Promise => { - const apiKey = ''; - if (!name) return null; - try { - const res = await fetch('/api/clickup/lists', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - apiKey, - spaceId, - folderId, - name: name.trim(), - }), - }); - if (res.ok) { - const data = await res.json(); - const createdList: ClickupList = data.list; - await loadClickupFoldersAndLists(spaceId, apiKey); - return createdList; - } - } catch (err) { - console.warn('Failed to create ClickUp list:', err); - } - return null; - }, [loadClickupFoldersAndLists]); - - const syncUserTasksWithClickUp = useCallback(async (userId: string) => { - const apiKey = ''; - const callerUserId = currentUserRef.current?.id; - try { - const res = await fetch('/api/clickup/sync-user-tasks', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - ...(apiKey ? { 'x-clickup-api-key': apiKey } : {}), - ...(callerUserId ? { 'x-caller-user-id': callerUserId } : {}), - }, - body: JSON.stringify({ userId, apiKey, callerUserId }), - }); - let data: any = null; - try { - const text = await res.text(); - data = text ? JSON.parse(text) : null; - } catch { - data = null; - } - if (res.ok && data?.success) { - setUserSyncFailures(prev => ({ ...prev, [userId]: false })); - await fetchState(); - return { - success: true, - syncedCount: data.syncedCount || 0, - archivedCount: data.archivedCount || 0, - message: data.message || 'Sync complete', - }; - } - setUserSyncFailures(prev => ({ ...prev, [userId]: true })); - return { - success: false, - syncedCount: 0, - archivedCount: 0, - message: data?.error || (res.status === 502 ? 'Server temporarily updating (502 Bad Gateway). Please retry in a moment.' : 'Failed to sync with ClickUp'), - }; - } catch (err: any) { - setUserSyncFailures(prev => ({ ...prev, [userId]: true })); - return { - success: false, - syncedCount: 0, - archivedCount: 0, - message: err.message || 'Sync request failed', - }; - } - }, [fetchState]); - - const fetchClickupCustomFields = useCallback(async (params: { listId?: string; spaceId?: string; folderId?: string }): Promise => { - const apiKey = ''; - setIsLoadingTaskTypes(true); - try { - const q = new URLSearchParams(); - if (params.listId) q.set('listId', params.listId); - else if (params.spaceId) q.set('spaceId', params.spaceId); - else if (params.folderId) q.set('folderId', params.folderId); - - const res = await fetch(`/api/clickup/custom-fields?${q.toString()}`, { - headers: { 'x-clickup-api-key': apiKey }, - }); - if (res.ok) { - const data = await res.json(); - const options: ClickupCustomFieldOption[] = data.options || []; - setClickupCustomFieldOptions(options); - if (data.taskTypeField?.id) { - setClickupTaskTypeFieldId(data.taskTypeField.id); - } - return options; - } - } catch (err) { - console.warn('[DashboardContext] Failed to fetch custom fields:', err); - } finally { - setIsLoadingTaskTypes(false); - } - return []; - }, []); - - useEffect(() => { - if (selectedClickupSpaceId && isClickupConnected) { - fetchClickupCustomFields({ spaceId: selectedClickupSpaceId }); - } - }, [selectedClickupSpaceId, isClickupConnected, fetchClickupCustomFields]); - - const getUserSyncState = useCallback((targetUserId: string): 'synced' | 'pending' | 'failed' | 'unmapped' => { - const targetUser = usersRef.current.find(u => u.id === targetUserId); - if (!targetUser?.clickupUserId) { - return 'unmapped'; - } - if (userSyncFailures[targetUserId]) { - return 'failed'; - } - const targetTasks = tasksRef.current.filter(t => t.userId === targetUserId); - const hasUnsynced = targetTasks.some(t => t.clickupListId && !t.clickupTaskId); - if (hasUnsynced) { - return 'pending'; - } - return 'synced'; - }, [userSyncFailures]); - - // ClickUp Real-Time Webhook Registration - const registerClickupWebhook = useCallback(async (customEndpoint?: string): Promise<{ success: boolean; message: string; webhookId?: string }> => { - try { - const key = clickupApiKey || currentUserRef.current?.clickupApiKey || ''; - const res = await fetch('/api/clickup/webhook/register', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - ...(key ? { 'x-clickup-api-key': key } : {}), - }, - body: JSON.stringify({ endpoint: customEndpoint }), - }); - const data = await res.json(); - if (res.ok && data.success) { - await refreshClickupWebhookStatus(); - return { - success: true, - message: data.message || 'ClickUp real-time webhook registered successfully!', - webhookId: data.webhookId, - }; - } - return { success: false, message: data.error || 'Failed to register webhook in ClickUp' }; - } catch (err: any) { - return { success: false, message: err.message || 'Network error registering webhook' }; - } - }, [clickupApiKey, refreshClickupWebhookStatus]); - // SOC2 Compliance Audit Stream Queries & Export const fetchAuditLogs = useCallback(async (limit: number = 50): Promise => { - try { - const res = await fetch(`/api/audit/logs?limit=${limit}`); - if (res.ok) { - const data = await res.json(); - return data.logs || []; - } - } catch (err) { - console.warn('Failed to fetch compliance audit logs:', err); - } - return []; + const res = await fetch(`/api/audit/logs?limit=${limit}`); + if (!res.ok) throw new Error('Audit history could not be loaded'); + return (await res.json()).logs || []; }, []); const downloadAuditLogs = useCallback(() => { @@ -1331,9 +871,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children setCurrentUser(existing); setActiveRoleTab(existing.role); - if (existing.email.toLowerCase().endsWith('@zensciences.com') && !existing.clickupConnected) { - setShowClickupPrompt(true); - } + return existing; }, []); @@ -1359,8 +897,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children role: Role; isCreativeDirector?: boolean; creativeDirectorId?: string; - clickupUserId?: string; - clickupUsername?: string; + }): Promise => { const res = await fetch('/api/users', { method: 'POST', @@ -1387,16 +924,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children dueDate?: string; cognitiveLoad: 'low' | 'medium' | 'high'; status: TaskStatus; - clickupTaskId?: string; - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - clickupUrl?: string; - clickupTaskType?: string; - clickupTaskTypeId?: string; - clickupTaskTypeFieldId?: string; + }): Promise => { const realId = `task-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`; const currentTasks = tasksRef.current; @@ -1425,16 +953,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children completedAt: isCompleted ? now : undefined, inProgressStartedAt: isInProgress ? now : undefined, inProgressDurationMs: 0, - clickupTaskId: data.clickupTaskId, - clickupFolderId: data.clickupFolderId, - clickupFolderName: data.clickupFolderName, - clickupListId: data.clickupListId, - clickupListName: data.clickupListName, - clickupSpaceId: data.clickupSpaceId, - clickupUrl: data.clickupUrl, - clickupTaskType: data.clickupTaskType, - clickupTaskTypeId: data.clickupTaskTypeId, - clickupTaskTypeFieldId: data.clickupTaskTypeFieldId, + createdAt: now, updatedAt: now, activityLog: [initialActivity], @@ -1452,7 +971,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children const payload = { id: realId, ...data }; const callerId = currentUserRef.current?.id || ''; - const clickKey = ''; try { if (!navigator.onLine) throw new Error('Offline'); @@ -1460,7 +978,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children method: 'POST', headers: { 'Content-Type': 'application/json', - ...(clickKey ? { 'x-clickup-api-key': clickKey } : {}), ...(callerId ? { 'x-caller-user-id': callerId } : {}), }, body: JSON.stringify(payload), @@ -1547,7 +1064,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children }); const callerId = currentUserRef.current?.id || ''; - const clickKey = ''; try { if (!navigator.onLine) throw new Error('Offline'); @@ -1555,7 +1071,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children method: 'PUT', headers: { 'Content-Type': 'application/json', - ...(clickKey ? { 'x-clickup-api-key': clickKey } : {}), ...(callerId ? { 'x-caller-user-id': callerId } : {}), }, body: JSON.stringify(updates), @@ -1585,21 +1100,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children return updatedTask || (tasksRef.current.find(t => t.id === id) as Task); }, []); - const assignTaskClickupList = useCallback(async ( - taskId: string, - listId: string, - listName: string, - folderId?: string, - folderName?: string - ): Promise => { - return await updateTask(taskId, { - clickupListId: listId, - clickupListName: listName, - clickupFolderId: folderId, - clickupFolderName: folderName, - }); - }, [updateTask]); - // Dedicated helper to adjust billable hours manually with immediate optimistic update and audit history logging const adjustBillableHours = useCallback(async (taskId: string, newDurationMs: number, reason?: string): Promise => { const cleanDuration = Math.max(0, Math.round(newDurationMs)); @@ -1654,7 +1154,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children }; const callerId = currentUserRef.current?.id || ''; - const clickKey = ''; try { if (!navigator.onLine) throw new Error('Offline'); @@ -1662,7 +1161,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children method: 'PUT', headers: { 'Content-Type': 'application/json', - ...(clickKey ? { 'x-clickup-api-key': clickKey } : {}), ...(callerId ? { 'x-caller-user-id': callerId } : {}), }, body: JSON.stringify(payload), @@ -1841,7 +1339,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children }); const callerId = currentUserRef.current?.id || ''; - const clickKey = ''; try { if (!navigator.onLine) throw new Error('Offline'); @@ -1849,7 +1346,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children method: 'POST', headers: { 'Content-Type': 'application/json', - ...(clickKey ? { 'x-clickup-api-key': clickKey } : {}), ...(callerId ? { 'x-caller-user-id': callerId } : {}), }, body: JSON.stringify({ updates: batchUpdates }), @@ -1895,7 +1391,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children title?: string; targetStatus?: TaskStatus; targetDueDate?: string; - }): Promise<{ task: Task; clickupSubtaskCreated: boolean; warning?: string; message?: string }> => { + }): Promise<{ task: Task; warning?: string; message?: string }> => { const { taskId, targetUserId, title, targetStatus, targetDueDate } = params; const sourceTask = tasksRef.current.find(t => t.id === taskId); if (!sourceTask) { @@ -1903,7 +1399,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children } const callerId = currentUserRef.current?.id || ''; - const clickKey = ''; + const isSuper = Boolean(isSuperadmin || currentUserRef.current?.email?.toLowerCase() === SUPERADMIN_EMAIL.toLowerCase()); const res = await fetch(`/api/tasks/${taskId}/duplicate`, { @@ -1911,7 +1407,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children headers: { 'Content-Type': 'application/json', ...(callerId ? { 'x-caller-user-id': callerId } : {}), - ...(clickKey ? { 'x-clickup-api-key': clickKey } : {}), ...(isSuper ? { 'isSuperadmin': 'true', 'x-is-superadmin': 'true' } : {}), }, body: JSON.stringify({ @@ -1937,7 +1432,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children return { task: newTask, - clickupSubtaskCreated: Boolean(data.clickupSubtaskCreated), + warning: data.warning, message: data.message, }; @@ -1985,7 +1480,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children ); const callerId = currentUserRef.current?.id || ''; - const clickKey = ''; try { if (!navigator.onLine) throw new Error('Offline'); @@ -1993,7 +1487,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children method: 'POST', headers: { 'Content-Type': 'application/json', - ...(clickKey ? { 'x-clickup-api-key': clickKey } : {}), ...(callerId ? { 'x-caller-user-id': callerId } : {}), }, body: JSON.stringify({ updates }), @@ -2024,23 +1517,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children } }, [fetchState, refreshFirestoreStatus]); - // Upload or apply Firebase Service Account Key - const uploadServiceAccountKey = useCallback(async (keyContent: string): Promise<{ success: boolean; message: string }> => { - try { - const res = await fetch('/api/firestore/credentials', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ serviceAccountKey: keyContent }), - }); - const data = await res.json(); - await fetchState(); - await refreshFirestoreStatus(); - return data; - } catch (err: any) { - return { success: false, message: err.message || 'Key upload failed' }; - } - }, [fetchState, refreshFirestoreStatus]); - const contextValue = useMemo( () => ({ currentUser, @@ -2060,7 +1536,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children setActiveDragInfo, refreshFirestoreStatus, syncWithFirestore, - uploadServiceAccountKey, login, loginWithGoogle, logout, @@ -2077,35 +1552,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children creativeDirectors, activeBoardId, setActiveBoardId, - // ClickUp Integration - isZensciencesUser, - isClickupConnected, - clickupApiKey, - clickupMembers, - loadClickupMembers, - clickupSpaces, - selectedClickupSpaceId, - clickupFoldersAndLists, - spaceFoldersMap, - spaceFoldersAndListsMap, - getFoldersAndListsForSpace, - showClickupPrompt, - setShowClickupPrompt, - connectClickup, - disconnectClickup, - setSelectedClickupSpaceId, - createClickupList, - syncUserTasksWithClickUp, - assignTaskClickupList, - clickupCustomFieldOptions, - clickupTaskTypeFieldId, - isLoadingTaskTypes, - fetchClickupCustomFields, - getUserSyncState, - // Real-Time Webhook & Compliance Audit - clickupWebhookStatus, - refreshClickupWebhookStatus, - registerClickupWebhook, + fetchAuditLogs, downloadAuditLogs, // Tasks @@ -2135,7 +1582,6 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children activeDragInfo, refreshFirestoreStatus, syncWithFirestore, - uploadServiceAccountKey, login, loginWithGoogle, logout, @@ -2151,32 +1597,7 @@ export const DashboardProvider: React.FC<{ children: ReactNode }> = ({ children creativeDirectors, activeBoardId, setActiveBoardId, - isZensciencesUser, - isClickupConnected, - clickupApiKey, - clickupMembers, - loadClickupMembers, - clickupSpaces, - selectedClickupSpaceId, - clickupFoldersAndLists, - spaceFoldersMap, - spaceFoldersAndListsMap, - getFoldersAndListsForSpace, - showClickupPrompt, - connectClickup, - disconnectClickup, - setSelectedClickupSpaceId, - createClickupList, - syncUserTasksWithClickUp, - assignTaskClickupList, - clickupCustomFieldOptions, - clickupTaskTypeFieldId, - isLoadingTaskTypes, - fetchClickupCustomFields, - getUserSyncState, - clickupWebhookStatus, - refreshClickupWebhookStatus, - registerClickupWebhook, + fetchAuditLogs, downloadAuditLogs, createTask, diff --git a/src/lib/api.ts b/src/lib/api.ts index 6fdf122..fd0aae7 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -16,8 +16,10 @@ try { } localStorage.removeItem('zenflow_mutation_queue_v1'); localStorage.removeItem('zenflow_clickup_api_key'); + localStorage.removeItem('zenflow_clickup_space_id'); + localStorage.removeItem('zenflow_clickup_space_name'); if (cached) { - delete cached.clickupApiKey; + for (const key of Object.keys(cached)) if (/clickup/i.test(key)) delete cached[key]; localStorage.setItem('team_dash_current_user_v1', JSON.stringify(cached)); } } catch { /* Browser storage may be unavailable. */ } diff --git a/src/lib/firebase.ts b/src/lib/firebase.ts index 694d982..d0f261a 100644 --- a/src/lib/firebase.ts +++ b/src/lib/firebase.ts @@ -1,6 +1,5 @@ import { apiFetch } from './api'; import type { FirebaseApp } from 'firebase/app'; -import type { Firestore } from 'firebase/firestore'; import appletConfig from '../../firebase-applet-config.json'; // Default config loaded from firebase-applet-config.json or Vite environment variables @@ -17,27 +16,8 @@ export const firebaseConfig = { }; let appInstance: FirebaseApp | null = null; -let dbInstance: Firestore | null = null; let authInstance: any = null; -export async function getClientDb(): Promise { - if (dbInstance) return dbInstance; - if (firebaseConfig.apiKey && firebaseConfig.projectId) { - try { - const { initializeApp, getApps, getApp } = await import('firebase/app'); - const { getFirestore } = await import('firebase/firestore'); - appInstance = getApps().length === 0 ? initializeApp(firebaseConfig) : getApp(); - dbInstance = firebaseConfig.firestoreDatabaseId - ? getFirestore(appInstance, firebaseConfig.firestoreDatabaseId) - : getFirestore(appInstance); - return dbInstance; - } catch (err) { - console.warn('Firebase client initialization warning:', err); - } - } - return null; -} - export async function getFirebaseAuth(): Promise { if (authInstance) return authInstance; if (firebaseConfig.apiKey && firebaseConfig.projectId) { @@ -137,7 +117,7 @@ let inFlightStatusPromise: Promise | null = null; /** * Validates connection to Firestore at app initialization (mandated by firebase-skill). - * Uses server-side API verification first, falling back to on-demand dynamic client SDK only if needed. + * Checks the authenticated backend; direct client database access is disabled. * Deduplicates in-flight status requests to prevent redundant network egress on boot. */ export async function testConnection(): Promise { diff --git a/src/types.ts b/src/types.ts index 400a378..d0febe4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,21 +14,7 @@ export interface User { order?: number; isCreativeDirector?: boolean; creativeDirectorId?: string; - clickupApiKey?: string; - clickupConnected?: boolean; - selectedClickupSpaceId?: string; - selectedClickupSpaceName?: string; - clickupUserId?: string; - clickupUsername?: string; -} -export interface ClickupMember { - id: string; - username: string; - email: string; - color?: string; - profilePicture?: string; - initials?: string; } export interface TaskActivity { @@ -56,63 +42,11 @@ export interface Task { createdAt: string; updatedAt: string; activityLog?: TaskActivity[]; - clickupTaskId?: string; - clickupFolderId?: string; - clickupFolderName?: string; - clickupListId?: string; - clickupListName?: string; - clickupSpaceId?: string; - clickupUrl?: string; - clickupTaskType?: string; - clickupTaskTypeId?: string; - clickupTaskTypeFieldId?: string; + parentTaskId?: string; parentTaskTitle?: string; - clickupParentTaskId?: string; - isSubtask?: boolean; -} - -export interface ClickupCustomFieldOption { - id: string; - name: string; - color?: string; - orderindex?: number; -} - -export interface ClickupCustomField { - id: string; - name: string; - type: string; - type_config?: { - options?: ClickupCustomFieldOption[]; - }; -} -export interface ClickupSpace { - id: string; - name: string; - color?: string; - private?: boolean; -} - -export interface ClickupList { - id: string; - name: string; - orderindex?: number; - folder?: { - id: string; - name: string; - }; - space?: { - id: string; - name: string; - }; -} - -export interface ClickupFolder { - id: string; - name: string; - lists: ClickupList[]; + isSubtask?: boolean; } export interface QueuedMutation { @@ -176,7 +110,7 @@ export interface TaskOrderUpdate { dueDate?: string | null; } -export type RealtimeEventType = +export type RealtimeEventType = | 'user_created' | 'user_updated' | 'user_deleted' @@ -211,14 +145,3 @@ export interface AuditLogEntry { metadata?: Record; } -export interface ClickupWebhookStatus { - listening: boolean; - registered: boolean; - webhookId?: string; - endpointUrl: string; - lastEventAt?: string; - lastEventAction?: string; - totalEventsCount: number; - supportedEvents?: string[]; -} - diff --git a/tests/fixtures.ts b/tests/fixtures.ts index ebb8cbf..0fc3a78 100644 --- a/tests/fixtures.ts +++ b/tests/fixtures.ts @@ -4,7 +4,6 @@ import ts from 'typescript'; import express from 'express'; import { createApiSecurity, redactPayload, SUPERADMIN_EMAIL, SESSION_COOKIE, sameOriginMutation } from '../server/security'; import { writeSse } from '../server/resources'; -import { WebhookRegistry } from '../server/webhooks'; const source = ts.createSourceFile('server.ts', fs.readFileSync('server.ts', 'utf8'), ts.ScriptTarget.Latest, true); const handlers = new Map(); @@ -22,7 +21,7 @@ const compile = (text: string) => ts.transpileModule(text, { compilerOptions: { export function fixtureTask(id: string, userId: string, status = 'todo') { return { id, userId, title: id, status, cognitiveLoad: 'medium', order: 0, createdAt: '2026-10-20T00:00:00Z', updatedAt: '2026-10-20T00:00:00Z', inProgressDurationMs: 0, activityLog: [] }; } -export async function fixtureServer(directory: string) { +export async function fixtureServer(_directory: string) { const store: any = { users: [ { id: 'root', name: 'Root', email: SUPERADMIN_EMAIL, role: 'content', isCreativeDirector: true }, @@ -35,28 +34,26 @@ export async function fixtureServer(directory: string) { const events: any[] = [], audit: any[] = []; const noop = () => {}; const asyncNoop = async () => {}; - const registry = new WebhookRegistry(`${directory}/webhooks.json`); const ctx: any = { - store, stateRevision: 1, maybeArchive: noop, deduplicateUsers: noop, + adminDb: { doc: () => ({ get: async () => ({ exists: true }) }) }, + pendingEvents: null, structuredClone, store, stateRevision: 1, autoArchiveDoneTasks: noop, deduplicateUsers: noop, saveStore: noop, dbSaveUser: asyncNoop, dbSaveTask: asyncNoop, dbDeleteUser: asyncNoop, dbDeleteTask: asyncNoop, dbBatchDeleteTasks: asyncNoop, dbBatchSaveTasks: asyncNoop, dbBatchSaveUsers: asyncNoop, - syncTaskToClickUp: asyncNoop, SUPERADMIN_EMAIL, + SUPERADMIN_EMAIL, broadcastEvent: (type: string, payload: any) => events.push({ type, payload: redactPayload(payload) }), appendAuditLog: async (entry: any) => { audit.push(entry); }, console: { log: noop, warn: noop, error: noop }, - AVATAR_COLORS: ['blue'], ZENFLOW_TO_CLICKUP_STATUS: { todo: 'to do', retainer: 'in progress' }, + AVATAR_COLORS: ['blue'], COGNITIVE_LOAD_ESTIMATES_MS: { medium: 86400000 }, fetch: async () => ({ ok: true, json: async () => ({ teams: [], assignees: [], status: { status: 'to do' } }) }), - webhookRegistry: registry, webhookEventsCount: 0, lastWebhookEventAt: null, lastWebhookAction: null, clients: [], nextClientId: 1, MAX_SSE_CLIENTS: 100, writeSse, redactPayload, setInterval, clearInterval, }; - for (const name of ['sanitizeString', 'formatBillableHoursServer', 'processClickupWebhookEvent']) { + for (const name of ['sanitizeString', 'formatBillableHoursServer']) { ctx[name] = vm.runInNewContext(compile(functions.get(name)!) + `; ${name}`, ctx); } - const { validSignature } = await import('../server/security'); - ctx.validSignature = validSignature; + const app = express(); app.set('case sensitive routing', true); app.use(express.json({ verify: (req, _res, buffer) => { (req as any).rawBody = Buffer.from(buffer); } })); @@ -81,7 +78,7 @@ export async function fixtureServer(directory: string) { const routes = ['get /api/health', 'get /api/state', 'get /api/users', 'post /api/users', 'put /api/users/:id', 'delete /api/users/:id', 'get /api/tasks', 'post /api/tasks', 'put /api/tasks/:id', 'delete /api/tasks/:id', 'post /api/tasks/reorder', - 'post /api/tasks/:id/duplicate', 'post /api/clickup/webhook', 'get /api/events']; + 'post /api/tasks/:id/duplicate', 'get /api/events']; for (const route of routes) { const handler = vm.runInNewContext(compile(`var handler = ${handlers.get(route)}`) + '; handler', ctx); const [method, routePath] = route.split(' '); @@ -94,7 +91,7 @@ export async function fixtureServer(directory: string) { await new Promise(resolve => server.on('listening', resolve)); const address = server.address() as any; const url = `http://127.0.0.1:${address.port}`; - return { store, events, audit, ctx, registry, url, + return { store, events, audit, ctx, url, enableLiveBroadcast: () => { ctx.broadcastEvent = vm.runInNewContext(compile(functions.get('broadcastEvent')!) + '; broadcastEvent', ctx); }, request: (route: string, who = 'alice', method = 'GET', body?: any, headers: Record = {}) => fetch(url + '/api' + route, { method, headers: { ...(who ? { Authorization: `Bearer ${who}` } : {}), 'Content-Type': 'application/json', ...headers }, diff --git a/tests/persistence.test.ts b/tests/persistence.test.ts new file mode 100644 index 0000000..744b719 --- /dev/null +++ b/tests/persistence.test.ts @@ -0,0 +1,63 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import express from 'express'; +import { FirestoreWorkspace, nativeData, workspaceMiddleware, WorkspaceSnapshot } from '../server/workspace'; + +test('retired metadata is stripped while native relationships and history survive', () => { + const data = nativeData({ id: 'child', parentTaskId: 'parent', userId: 'alice', clickupTaskId: 'remote', + activityLog: [{ action: 'updated', details: 'Keep history' }], missing: undefined }); + assert.deepEqual(data, { id: 'child', parentTaskId: 'parent', userId: 'alice', activityLog: [{ action: 'updated', details: 'Keep history' }] }); +}); + +test('Firestore outage never reports success or broadcasts; later reads reload durable data', async () => { + let durable: WorkspaceSnapshot = { revision: 1, store: { users: [], tasks: [{ id: 'a', title: 'Saved' }] } }; + let store = structuredClone(durable.store); + let failWrite = false, failRead = false; + let releaseCommit: (() => void) | undefined; + let delay: Promise | undefined; + let audit: any[] = [], events: any[] = [], staged: any[] = []; + const workspace = { + load: async () => { if (failRead) throw new Error('read unavailable'); return structuredClone(durable); }, + commit: async (_before: any, after: any, records: any[]) => { + if (delay) await delay; + if (failWrite) throw new Error('write unavailable'); + durable = { store: structuredClone(after), revision: durable.revision + 1 }; + audit.push(...records); return durable.revision; + }, + } as unknown as FirestoreWorkspace; + const app = express(); + app.use(express.json()); + let pendingAudit: any[] = []; + app.use(workspaceMiddleware({ workspace, getStore: () => store, setStore: value => { store = value; }, + begin: () => { pendingAudit = []; staged = []; }, audit: () => pendingAudit, + committed: () => { events.push(...staged); staged = []; }, failed: () => { staged = []; }, + })); + app.put('/task', (req, res) => { store.tasks[0].title = req.body.title; pendingAudit.push({ id: 'audit' }); staged.push('updated'); res.json(store.tasks[0]); }); + app.get('/state', (_req, res) => { res.json(store); }); + const server = app.listen(0, '127.0.0.1'); + await new Promise(resolve => server.on('listening', resolve)); + const url = `http://127.0.0.1:${(server.address() as any).port}`; + const put = (title: string) => fetch(url + '/task', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) }); + try { + failWrite = true; + assert.equal((await put('Unsaved')).status, 503); + assert.equal(store.tasks[0].title, 'Saved'); + assert.equal(durable.store.tasks[0].title, 'Saved'); + assert.equal(events.length, 0); assert.equal(audit.length, 0); + failWrite = false; + delay = new Promise(resolve => { releaseCommit = resolve; }); + let returned = false; + const request = put('Committed').then(response => { returned = true; return response; }); + await new Promise(resolve => setTimeout(resolve, 30)); + assert.equal(returned, false); assert.equal(events.length, 0); + releaseCommit!(); + assert.equal((await request).status, 200); + assert.equal(durable.store.tasks[0].title, 'Committed'); + assert.equal(events.length, 1); assert.equal(audit.length, 1); + durable.store.tasks = []; // A deleted cloud record must never be resurrected from cache. + const state = await (await fetch(url + '/state')).json(); + assert.deepEqual(state.tasks, []); + failRead = true; + assert.equal((await fetch(url + '/state')).status, 503); + } finally { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); } +}); diff --git a/tests/security.test.ts b/tests/security.test.ts index 8a2e955..b750ba3 100644 --- a/tests/security.test.ts +++ b/tests/security.test.ts @@ -3,10 +3,8 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import { createHmac } from 'node:crypto'; + import { fixtureServer, fixtureTask } from './fixtures'; -import { publicMember, redactPayload, validSignature } from '../server/security'; -import { WebhookRegistry } from '../server/webhooks'; async function withServer(run: (server: Awaited>) => Promise) { const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'zenflow-security-')); @@ -64,23 +62,8 @@ test('member provisioning, profile updates and root protection retain the role m assert.equal((await server.request('/users', 'cd', 'POST', { name: 'New CD', email: 'newcd@example.invalid', role: 'content', isCreativeDirector: true })).status, 403); assert.equal((await server.request('/users/root', 'root', 'DELETE')).status, 403); assert.equal((await server.request('/users/alice', 'alice', 'PUT', { role: 'design' })).status, 403); - assert.equal((await server.request('/users/alice', 'alice', 'PUT', { selectedClickupSpaceId: 'space' })).status, 200); -})); -test('HTTP user payloads and mutation events never disclose saved credentials', async () => withServer(async server => { - server.store.users[2].clickupApiKey = 'SYNTHETIC_PRIVATE_KEY'; - for (const route of ['/state', '/users']) { - const response = await server.request(route); - assert.equal(response.status, 200); - assert.ok(!(await response.text()).includes('SYNTHETIC_PRIVATE_KEY')); - } - const response = await server.request('/users/alice', 'alice', 'PUT', { clickupApiKey: 'REPLACEMENT_SECRET' }); - const publicUser = await response.json(); - assert.equal(publicUser.clickupConnected, true); - assert.equal(publicUser.clickupApiKey, undefined); - assert.ok(!JSON.stringify(server.events).includes('REPLACEMENT_SECRET')); - assert.equal((await server.request('/users/alice', 'alice', 'PUT', { clickupApiKey: '' })).status, 200); - assert.equal(server.store.users[2].clickupApiKey, undefined); })); + test('cookie mutations require the same-origin non-simple header; Bearer API requests work', async () => withServer(async server => { const cookie = { Cookie: 'zenflow_identity=alice' }; assert.equal((await server.request('/tasks/a', '', 'PUT', { title: 'bad' }, cookie)).status, 403); @@ -104,42 +87,7 @@ test('actual session exchange and logout issue HttpOnly cookies only for verifie assert.equal(logout.status, 204); assert.match(logout.headers.get('set-cookie')!, /Expires=Thu, 01 Jan 1970/i); })); -test('unsigned or modified webhook cannot alter state, telemetry, audit or trigger persistence', async () => withServer(async server => { - server.store.tasks[0].clickupTaskId = 'cu-a'; - await server.registry.save({ id: 'hook', secret: 'fixture-signing-secret', endpoint: 'https://example.invalid/api/clickup/webhook' }); - const body = { webhook_id: 'hook', task_id: 'cu-a', event: 'taskTimeTrackedUpdated', history_items: [{ field: 'time_spent', after: 360000000 }] }; - const signature = createHmac('sha256', 'fixture-signing-secret').update(JSON.stringify(body)).digest('hex'); - for (const header of ['', 'a'.repeat(64), 'not-hex']) assert.equal((await server.request('/clickup/webhook', '', 'POST', body, { 'x-signature': header })).status, 401); - assert.equal(server.store.tasks[0].inProgressDurationMs, 0); - assert.equal(server.ctx.webhookEventsCount, 0); - assert.equal(server.audit.length, 0); - assert.equal((await server.request('/clickup/webhook', '', 'POST', body, { 'x-signature': signature })).status, 200); - await new Promise(resolve => setTimeout(resolve, 10)); - assert.equal(server.store.tasks[0].inProgressDurationMs, 360000000); - assert.equal(server.ctx.webhookEventsCount, 1); -})); -test('webhook secrets survive restart without becoming a public response field', async () => { - const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'zenflow-hook-')); - try { - const file = path.join(directory, 'registration.json'); - const registry = new WebhookRegistry(file); - await registry.save({ id: 'hook', secret: 'private', endpoint: 'https://example.invalid' }); - const reloaded = new WebhookRegistry(file); - await reloaded.load(); - assert.equal(reloaded.get('hook')?.secret, 'private'); - assert.equal(redactPayload({ webhook: reloaded.get('hook') }).webhook.secret, undefined); - await reloaded.remove('hook'); - const deleted = new WebhookRegistry(file); await deleted.load(); - assert.equal(deleted.get('hook'), undefined); - } finally { await fs.rm(directory, { recursive: true, force: true }); } -}); -test('public fields use an allowlist and HMAC checks exact raw bytes', () => { - assert.equal(publicMember({ id: 'a', email: 'a@b.invalid', role: 'design', futureSecret: 'secret', clickupApiKey: 'key' }).futureSecret, undefined); - const raw = Buffer.from('{"event":"test"}'); - const signature = createHmac('sha256', 'secret').update(raw).digest('hex'); - assert.equal(validSignature(raw, signature, 'secret'), true); - assert.equal(validSignature(Buffer.from('{ "event":"test"}'), signature, 'secret'), false); -}); + test('pipeline and retainer tasks retain deadline and timer behavior', async () => withServer(async server => { for (const status of ['pipeline', 'retainer']) { const response = await server.request('/tasks', 'alice', 'POST', { userId: 'alice', title: `Task ${status}`, status, cognitiveLoad: 'medium' }); diff --git a/tests/smoke-production.ts b/tests/smoke-production.ts index 65275c6..389129c 100644 --- a/tests/smoke-production.ts +++ b/tests/smoke-production.ts @@ -1,37 +1,95 @@ -import { spawn } from 'node:child_process'; +import { spawn, ChildProcess } from 'node:child_process'; import fs from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; import net from 'node:net'; +import { generateKeyPairSync } from 'node:crypto'; import assert from 'node:assert/strict'; +import { initializeApp, deleteApp } from 'firebase-admin/app'; +import { getAuth } from 'firebase-admin/auth'; const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'zenflow-production-')); const reservation = net.createServer(); await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve)); const port = (reservation.address() as net.AddressInfo).port; await new Promise(resolve => reservation.close(() => resolve())); -const env = { ...process.env, NODE_ENV: 'production', PORT: String(port), ZENFLOW_DATA_DIR: path.join(directory, 'data') }; -for (const name of ['FIREBASE_SERVICE_ACCOUNT_KEY', 'GOOGLE_APPLICATION_CREDENTIALS', 'FIREBASE_AUTH_EMULATOR_HOST', 'FIRESTORE_EMULATOR_HOST']) delete env[name]; -const child = spawn(process.execPath, [path.resolve('dist/server.cjs')], { cwd: directory, env, stdio: ['ignore', 'pipe', 'pipe'] }); +const env: NodeJS.ProcessEnv = { ...process.env, NODE_ENV: 'production', PORT: String(port) }; +for (const name of ['FIREBASE_SERVICE_ACCOUNT_KEY', 'GOOGLE_APPLICATION_CREDENTIALS', 'FIREBASE_AUTH_EMULATOR_HOST']) delete env[name]; +let child: ChildProcess; let output = ''; -child.stdout.on('data', chunk => { output += chunk.toString(); }); -child.stderr.on('data', chunk => { output += chunk.toString(); }); -try { - const timeout = Date.now() + 15000; +const start = () => { + output = ''; + child = spawn(process.execPath, [path.resolve('dist/server.cjs')], { cwd: directory, env, stdio: ['ignore', 'pipe', 'pipe'] }); + child.stdout!.on('data', chunk => { output += chunk.toString(); }); + child.stderr!.on('data', chunk => { output += chunk.toString(); }); +}; +const stop = async () => { + if (child.exitCode === null) { const exited = new Promise(resolve => child.once('exit', () => resolve())); child.kill('SIGTERM'); await exited; } +}; +const ready = async () => { + const timeout = Date.now() + 30000; while (!output.includes('Server running on port') && Date.now() < timeout) { if (child.exitCode !== null) throw new Error(`Production process exited: ${output}`); await new Promise(resolve => setTimeout(resolve, 100)); } assert.match(output, /Server running on port/); - const url = `http://127.0.0.1:${port}`; - assert.equal((await fetch(url + '/api/health')).status, 200); - assert.equal((await fetch(url + '/api/state')).status, 401); - assert.equal((await fetch(url + '/api/events')).status, 401); - assert.equal((await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-is-superadmin': 'true' }, body: JSON.stringify({ email: 'spoof@example.invalid' }) })).status, 401); - assert.equal((await fetch(url + '/api/clickup/webhook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })).status, 401); - console.log('Compiled production server: health passes; anonymous API/SSE/mutations and unsigned webhook rejected. No live services used.'); +}; +try { + start(); + await new Promise(resolve => child.once('exit', () => resolve())); + assert.equal(child.exitCode, 1); + assert.match(output, /credentials are required/); + console.log('Compiled server refuses startup without Firestore credentials.'); + if (process.env.FIRESTORE_EMULATOR_HOST) { + assert.match(process.env.FIRESTORE_EMULATOR_HOST, /^127\.0\.0\.1:\d+$/); + const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + env.FIREBASE_SERVICE_ACCOUNT_KEY = JSON.stringify({ project_id: 'demo-zenflow', client_email: 'smoke@demo-zenflow.iam.gserviceaccount.com', private_key: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString() }); + env.FIREBASE_PROJECT_ID = 'demo-zenflow'; + env.FIREBASE_DATABASE_ID = 'smoke'; + env.FIREBASE_AUTH_EMULATOR_HOST = '127.0.0.1:9099'; + const authApp = initializeApp({ projectId: 'zen-flow-7173d' }, 'smoke-auth'); + await getAuth(authApp).createUser({ uid: 'smoke-owner', email: 'kiran.s@zensciences.com', emailVerified: true }); + await deleteApp(authApp); + const now = Math.floor(Date.now() / 1000); + const token = [Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url'), Buffer.from(JSON.stringify({ + sub: 'smoke-owner', user_id: 'smoke-owner', aud: 'zen-flow-7173d', iss: 'https://securetoken.google.com/zen-flow-7173d', + iat: now, auth_time: now, exp: now + 3600, email: 'kiran.s@zensciences.com', email_verified: true, firebase: { sign_in_provider: 'google.com' }, + })).toString('base64url'), ''].join('.'); + const url = `http://127.0.0.1:${port}`; + const request = (route: string, method = 'GET', body?: any, authenticated = true) => fetch(url + '/api' + route, { + method, headers: { 'Content-Type': 'application/json', ...(authenticated ? { Authorization: `Bearer ${token}` } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + start(); await ready(); + assert.equal((await request('/health', 'GET', undefined, false)).status, 200); + for (const route of ['/state', '/events', '/users']) assert.equal((await request(route, 'GET', undefined, false)).status, 401); + for (const route of ['/clickup/webhook', '/clickup/spaces', '/clickup/verify']) assert.equal((await request(route, 'POST', {}, false)).status, 410); + const status = await (await request('/firestore/status')).json(); + assert.equal(status.connected, true, JSON.stringify(status) + output); assert.equal(status.mode, 'admin'); assert.equal(status.databaseId, 'smoke'); + const state = await (await request('/state')).json(); + const owner = state.users.find((user: any) => user.email === 'kiran.s@zensciences.com'); + const create = await request('/tasks', 'POST', { id: 'smoke-parent', userId: owner.id, title: 'Native retainer', status: 'retainer', cognitiveLoad: 'medium' }); + assert.equal(create.status, 201, await create.text()); + const subtask = await request('/tasks/smoke-parent/duplicate', 'POST', { targetUserId: owner.id, targetStatus: 'todo', targetDueDate: '2026-11-01' }); + assert.equal(subtask.status, 201); + const childId = (await subtask.json()).task.id; + assert.equal((await request(`/tasks/${childId}`, 'PUT', { title: 'Independent child' })).status, 200); + await stop(); start(); await ready(); + const recovered = await (await request('/state')).json(); + assert.equal(recovered.tasks.find((task: any) => task.id === childId).parentTaskId, 'smoke-parent'); + assert.equal(recovered.tasks.find((task: any) => task.id === childId).title, 'Independent child'); + assert.equal((await request(`/tasks/${childId}`, 'DELETE')).status, 200); + await stop(); start(); await ready(); + const deleted = await (await request('/state')).json(); + assert.ok(!deleted.tasks.some((task: any) => task.id === childId)); + assert.ok(deleted.tasks.some((task: any) => task.id === 'smoke-parent')); + const audit = await (await request('/audit/logs')).json(); + assert.ok(audit.logs.some((entry: any) => entry.action === 'task_deleted')); + const download = await request('/audit/download'); + assert.equal(download.status, 200); assert.ok((await download.text()).includes('task_deleted')); + console.log('Compiled server + Firestore emulator: authenticated CRUD, delegation, audit export, restart and deletion recovery passed.'); + } } finally { - child.kill('SIGTERM'); - if (child.exitCode === null) await new Promise(resolve => child.once('exit', () => resolve())); + await stop(); await fs.rm(directory, { recursive: true, force: true }); } diff --git a/tests/workspace.emulator.ts b/tests/workspace.emulator.ts new file mode 100644 index 0000000..a2a789a --- /dev/null +++ b/tests/workspace.emulator.ts @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { Firestore } from '@google-cloud/firestore'; +import { FirestoreWorkspace } from '../server/workspace'; +import { generateKeyPairSync } from 'node:crypto'; + +if (!process.env.FIRESTORE_EMULATOR_HOST?.startsWith('127.0.0.1:')) throw new Error('Local emulator required'); +const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); +const db = new Firestore({ projectId: 'demo-zenflow', preferRest: false, ignoreUndefinedProperties: true, + credentials: { client_email: 'test@demo-zenflow.iam.gserviceaccount.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString() } }); +const workspace = new FirestoreWorkspace(db as any); +await db.recursiveDelete(db.collection('users')); +await db.recursiveDelete(db.collection('tasks')); +await db.recursiveDelete(db.collection('workspace')); +await db.recursiveDelete(db.collection('compliance_audit_logs')); +await db.doc('users/alice').set({ id: 'alice', email: 'alice@example.invalid', role: 'content', clickupApiKey: 'SYNTHETIC_SECRET' }); +await db.doc('tasks/parent').set({ id: 'parent', userId: 'alice', title: 'Parent', clickupTaskId: 'legacy' }); +await workspace.migrate(); +assert.equal((await db.doc('users/alice').get()).data()?.clickupApiKey, undefined); +assert.equal((await db.doc('tasks/parent').get()).data()?.clickupTaskId, undefined); +assert.equal((await db.doc('workspace_backups/native-v1/tasks/parent').get()).data()?.title, 'Parent'); +const before = await workspace.load(); +const after = structuredClone(before.store); +after.tasks.push({ id: 'child', parentTaskId: 'parent', userId: 'alice', title: 'Child' }); +after.tasks[0].activityLog = [{ action: 'updated', details: 'Delegated' }]; +await workspace.commit(before, after, [{ id: 'audit-1', timestamp: new Date().toISOString(), action: 'delegated' }]); +assert.equal((await db.doc('tasks/child').get()).data()?.parentTaskId, 'parent'); +assert.equal((await workspace.recentAudit(10)).length, 1); +await assert.rejects(workspace.commit(before, before.store, [{ id: 'audit-conflict', action: 'stale' }])); +assert.equal((await db.doc('compliance_audit_logs/audit-conflict').get()).exists, false); +const restart = new FirestoreWorkspace(db as any); +const restored = await restart.load(); +assert.equal(restored.store.tasks.length, 2); +const removed = structuredClone(restored.store); +removed.tasks = removed.tasks.filter(task => task.id !== 'child'); +await restart.commit(restored, removed, []); +assert.equal((await workspace.load()).store.tasks.length, 1); +// Repeated audit IDs must fail the whole write, including its associated task update. +const atomic = await workspace.load(); +const changed = structuredClone(atomic.store); changed.tasks[0].title = 'Must rollback'; +await assert.rejects(workspace.commit(atomic, changed, [{ id: 'audit-1', action: 'overwrite' }])); +assert.equal((await db.doc('tasks/parent').get()).data()?.title, 'Parent'); +console.log('Firestore emulator: migration, restart, delegation, deletes, revision conflicts and atomic audit rollback passed.'); +await db.terminate(); diff --git a/vite.config.ts b/vite.config.ts index 64fb583..e797697 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -41,7 +41,7 @@ export default defineConfig(() => { server: { headers: { 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()', - 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' https://apis.google.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https://lh3.googleusercontent.com https://*.googleusercontent.com; connect-src 'self' https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://api.clickup.com; frame-src 'self' https://*.firebaseapp.com https://accounts.google.com; frame-ancestors 'none';", + 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' https://apis.google.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https://lh3.googleusercontent.com https://*.googleusercontent.com; connect-src 'self' https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com; frame-src 'self' https://*.firebaseapp.com https://accounts.google.com; frame-ancestors 'none';", }, // HMR is disabled in AI Studio via DISABLE_HMR env var. // Do not modifyβ€”file watching is disabled to prevent flickering during agent edits.