Skip to content

Commit f5c4a07

Browse files
committed
feat(sec): normalize rbac role handling
1 parent 616f712 commit f5c4a07

46 files changed

Lines changed: 3929 additions & 44 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Added
1111

12+
- Supabase-backed feature flag governance service with admin management UI, audit logging, and typed SDK instrumentation.
13+
- Hardened Supabase RBAC with updated roles/profile_roles migrations, refreshed RLS policies, and the `rbac_hardening_v1` rollout flag.
1214
- **Alert Dialog Component**: Installed neo-brutalism styled alert-dialog component from neobrutalism.dev
1315
- **Confirmation Dialogs**: Implemented confirmation dialogs for all major destructive actions across the application
1416
- Post deletion and publishing in PostsTable (mobile and desktop views)
@@ -27,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2729
- Updated CommentsModeration to use AlertDialog for comment deletion
2830
- Updated UserAccountPanel to use AlertDialog for sign out confirmation
2931
- Removed `window.confirm` usage in favor of accessible AlertDialog components
32+
- Updated admin dashboard to surface highest-role badges and gate role management via `rbac_hardening_v1` with new authz telemetry.
3033

3134
### Planned - Library Feature
3235
- **User Library System**: Complete Medium-style library feature for saving and organizing content
@@ -46,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4649
### Documentation
4750
- Added `docs/library-feature-implementation-plan.md` - Complete implementation roadmap
4851
- Added `docs/library-feature-summary.md` - Executive summary and feature overview
52+
- Refreshed security, data model, release plan, and test strategy docs to capture SEC-001 RBAC changes and telemetry.
4953
- Added `docs/library-technical-spec.md` - Detailed technical specifications and database schema
5054

5155
## [1.12.9] - 2025-02-27

docs/00-audit-report.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Phase 0 Audit Report
2+
3+
## 1. Executive Summary
4+
Syntax & Sips currently delivers a production-grade editorial and community publishing experience built on Next.js 15 (App Router) and Supabase Postgres/Auth. The platform already exposes public storytelling surfaces (blogs, tutorials, podcasts, changelog), gated admin tooling, gamification widgets, and Supabase edge functions for newsletters and AI summarization. However, it lacks the governance, extensibility, and documentation required to evolve into the Community Platform Fusion vision that blends long-form publishing, structured Q&A, discussion spaces, and events/commerce. Phase 0 exposes the gaps and codifies priorities for an incremental roadmap.
5+
6+
## 2. System Inventory
7+
### 2.1 Applications & Frontend
8+
- **Next.js App Router** under `src/app` with feature-first routes (`/blogs`, `/tutorials`, `/videos`, `/community`, `/admin`).
9+
- **Neo-brutalist component library** stored in `src/components`, `src/components/ui`, `src/components/magicui`, and themed via `tailwind.config.js` & `src/app/globals.css`.
10+
- **Authentication middleware** (`src/middleware.ts`, `src/lib/supabase`) gating admin, account, and onboarding routes.
11+
- **Client integrations** for analytics, newsletters, and gamification controls (e.g., `src/components/admin`, `src/components/auth`, `src/components/ui/NewSummarizeButton.tsx`).
12+
13+
### 2.2 Backend & Data
14+
- **Supabase Postgres** schema defined through migrations under `supabase/migrations`. Key tables: `posts`, `post_tags`, `categories`, `tags`, `profiles`, `roles`, `profile_roles`, `comments`, `newsletter_subscribers`, `site_settings`.
15+
- **Supabase Functions** for newsletter opt-in/out and AI summarization inside `supabase/functions`.
16+
- **Next.js API routes** within `src/app/api/**` handling CRUD for content, newsletter, gamification, and admin workflows.
17+
- **Edge/Server components** performing server-side Supabase queries with caching hints and streaming responses.
18+
19+
### 2.3 Tooling & Operations
20+
- **Testing:** Vitest configuration (`vitest.config.ts`) and Playwright setup (`playwright.config.ts`, `tests/` directory) with partial coverage.
21+
- **Linting & formatting:** ESLint (`eslint.config.mjs`), Tailwind/PostCSS configs, but no documented Prettier hook.
22+
- **Scripts:** `scripts/` folder for build-time helpers (e.g., chunk sync) and deployment automation.
23+
- **Observability:** No unified telemetry spec; ad-hoc logging via console. No dashboards or metric definitions in repo.
24+
25+
### 2.4 Documentation
26+
- Extensive marketing and program documentation in `/docs`, but missing the mandated artifacts for architecture, backlog, release plan, security posture, observability, and risk tracking.
27+
28+
## 3. Current Data Flows
29+
| Flow | Trigger | Path | Notes |
30+
| --- | --- | --- | --- |
31+
| Public content render | Anonymous visitor requests `/blogs/[slug]` | Next.js server component fetches from Supabase `posts` and `post_tags` tables, caches response per ISR settings | No feature flags; all users share same experience |
32+
| Admin moderation | Authenticated admin visits `/admin` | Middleware validates Supabase session → client components fetch analytics/queues via API routes → updates persisted via Supabase | Audit logging limited to Supabase defaults |
33+
| Newsletter opt-in | Visitor submits email form | API route validates input → Supabase function handles subscription + transactional email via Mailtrap | Limited error handling surfaced to UI |
34+
| Gamified summarization | Reader clicks summarize button | Client component calls Supabase function / edge worker to generate summary | No usage caps; potential abuse risk |
35+
36+
## 4. Dependencies & Integrations
37+
- **Supabase services:** Auth, Postgres, Edge Functions, Storage (for media assets referenced in content components).
38+
- **Mailtrap SMTP:** For newsletter confirmations (per README environment requirements).
39+
- **Analytics:** References to dashboards in admin components but no documented provider (likely Supabase or bespoke). Needs confirmation.
40+
- **Third-party assets:** Tabler icon CDN in README, fonts under `/fonts`.
41+
42+
## 5. Known Gaps & Technical Debt (Prioritized)
43+
| Priority | Gap / Debt | Impact | Recommendation |
44+
| --- | --- | --- | --- |
45+
| P0 | Missing governance documents & feature flag framework for new modules | Blocks compliant delivery of new capabilities | Produce documentation suite (this Phase 0), define flag utilities, integrate with release plan |
46+
| P0 | No dedicated spaces/communities domain model | Prevents Spaces rollout | Design new schema (`spaces`, `space_members`, `space_rules`, `space_roles`) and APIs with feature flags |
47+
| P0 | Observability & KPI metrics undefined | Cannot monitor KPIs or enforce SLOs | Establish telemetry spec (metrics, traces, logging) and dashboards before Phase 1 |
48+
| P1 | Moderation tooling lacks audit logs & sanctions | Non-compliant with safety requirements | Introduce `audit_logs`, sanctions workflow, and mod action logging |
49+
| P1 | Search experience limited to curated content pages | Does not meet taxonomy/search goals | Implement full-text search index, synonyms, and topic pages |
50+
| P2 | Payments, donations, events, and bounties absent | Blocks monetization phases | Plan integrations (Stripe/Razorpay/UPI) with compliance and KYC flows |
51+
| P2 | Reputation system incomplete | Privilege ladder not enforceable | Model `reputation_events`, scoring rules, and privilege gating |
52+
| P3 | Accessibility baseline unverified | Risk of WCAG non-compliance | Add automated accessibility tests, manual audits, and design token checks |
53+
54+
## 6. Risks & Constraints
55+
- **Data Integrity:** Existing schema may lack foreign keys/indices for new relationships; migrations must be reversible.
56+
- **AuthZ Complexity:** Role expansion (member → admin) will require new policy definitions in Supabase; current RLS coverage unknown.
57+
- **Operational Load:** Supabase quotas and email providers need capacity review before launching events/donations.
58+
- **Timeline Pressure:** Deliverables span product, engineering, and UX; cross-functional syncs required to avoid drift.
59+
60+
## 7. Baseline Metrics & Gaps
61+
- **Content publish latency:** No measurement instrumentation; must be added in Phase 1.
62+
- **Search P95 latency:** Search not centralized; baseline TBD.
63+
- **Donation success rate:** Payments not implemented; baseline 0%.
64+
- **Moderation queue age:** Admin views exist but no metric tracking; instrumentation required.
65+
- **Event RSVP conversion:** Events not yet live.
66+
67+
## 8. Recommendations for Phase 1 Kickoff
68+
1. Adopt the documentation suite defined in this repo (target architecture, product spec, roadmap, backlog, release plan).
69+
2. Stand up feature flag utilities (likely using Supabase `site_settings` or ConfigCat/LaunchDarkly) to gate new modules.
70+
3. Define telemetry plan before building new features to avoid retrofitting instrumentation.
71+
4. Align design system updates with forthcoming Spaces/Content templates to reduce rework.
72+
5. Audit Supabase RLS policies and plan for expanded role matrix.

docs/01-target-architecture.md

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# Target Architecture Blueprint
2+
3+
## 1. Context Diagram
4+
```mermaid
5+
flowchart LR
6+
subgraph Users
7+
Visitor[Visitor]
8+
Member[Member]
9+
Creator[Creator]
10+
Moderator[Moderator]
11+
Admin[Platform Admin]
12+
Sponsor[Sponsor / Donor]
13+
end
14+
15+
Visitor -->|consume content| WebApp[Next.js Web Experience]
16+
Member -->|publish / engage| WebApp
17+
Creator -->|manage projects/events| WebApp
18+
Moderator -->|review queues| WebApp
19+
Admin -->|configure policies| WebApp
20+
Sponsor -->|fund bounties/donations| WebApp
21+
22+
WebApp -->|RLS-secured queries| Supabase[(Supabase Postgres + Auth)]
23+
WebApp -->|Edge functions| SupaFunctions[Supabase Edge Functions]
24+
WebApp -->|Payments API| Payments[Stripe / Razorpay / UPI]
25+
WebApp -->|Video & Conferencing| Conferencing[Zoom / Google Meet]
26+
WebApp -->|Email + Webhooks| Messaging[Mailer (SMTP) + Webhooks]
27+
WebApp -->|Analytics events| Observability[Metrics & Tracing Pipeline]
28+
29+
Supabase -->|Auth callbacks| WebApp
30+
SupaFunctions -->|Automation| Supabase
31+
Payments -->|webhooks| WebApp
32+
Messaging -->|notifications| Users
33+
```
34+
35+
## 2. Container Diagram
36+
```mermaid
37+
flowchart TB
38+
subgraph Client
39+
NextClient[Next.js Client Components]
40+
end
41+
subgraph Server
42+
NextServer[Next.js Server Components & Route Handlers]
43+
FeatureFlags[Feature Flag Service]
44+
Worker[Background Workers (Jobs/Queues)]
45+
end
46+
subgraph DataPlane
47+
SupabaseDB[(Supabase Postgres)]
48+
Storage[(Supabase Storage)]
49+
Search[Index & Vector Search]
50+
end
51+
subgraph External
52+
PaymentAPI[Stripe/Razorpay/UPI]
53+
ConferencingAPI[Zoom/Google Meet]
54+
EmailAPI[SMTP Provider]
55+
ObservabilityStack[Telemetry Collector → Dashboard]
56+
end
57+
58+
NextClient <--> NextServer
59+
NextServer -->|SQL/RPC| SupabaseDB
60+
NextServer --> Storage
61+
NextServer -->|search queries| Search
62+
NextServer --> FeatureFlags
63+
NextServer --> EmailAPI
64+
NextServer --> ObservabilityStack
65+
NextServer -->|webhooks| Worker
66+
Worker --> SupabaseDB
67+
Worker --> ObservabilityStack
68+
Worker --> PaymentAPI
69+
Worker --> ConferencingAPI
70+
PaymentAPI --> NextServer
71+
ConferencingAPI --> NextServer
72+
EmailAPI --> Users
73+
```
74+
75+
## 3. Component Diagram (Core Modules)
76+
```mermaid
77+
flowchart LR
78+
subgraph Presentation
79+
AppRouter[App Router Layouts]
80+
SpaceShell[Space Shell & Navigation]
81+
ContentTemplates[Article/Discussion/Q&A/Event Templates]
82+
ReputationWidgets[XP, Badges, Leaderboards]
83+
NotificationsPanel[Notification Center]
84+
end
85+
86+
subgraph Domain Services
87+
SpaceService[Spaces Service]
88+
ContentService[Content Service]
89+
TaxonomyService[Tags & Search Service]
90+
ReputationService[Reputation & Privileges]
91+
ModerationService[Moderation & Safety]
92+
CommerceService[Donations/Bounties/Events]
93+
MessagingService[Comments & Direct Messages]
94+
NotificationService[Notifications & Webhooks]
95+
end
96+
97+
subgraph Data Access
98+
SupabaseClient[Supabase Typed Client]
99+
FeatureFlagClient[Feature Flag SDK]
100+
TelemetryClient[Telemetry SDK]
101+
end
102+
103+
AppRouter --> SpaceShell
104+
SpaceShell --> ContentTemplates
105+
ContentTemplates --> SpaceService
106+
ContentTemplates --> ContentService
107+
ContentTemplates --> TaxonomyService
108+
ContentTemplates --> MessagingService
109+
ReputationWidgets --> ReputationService
110+
NotificationsPanel --> NotificationService
111+
112+
SpaceService --> SupabaseClient
113+
ContentService --> SupabaseClient
114+
TaxonomyService --> SupabaseClient
115+
TaxonomyService --> SearchEngine[Search Index]
116+
ReputationService --> SupabaseClient
117+
ModerationService --> SupabaseClient
118+
CommerceService --> SupabaseClient
119+
CommerceService --> PaymentGateway[Payment Gateway SDK]
120+
MessagingService --> SupabaseClient
121+
NotificationService --> SupabaseClient
122+
NotificationService --> EmailAPI
123+
124+
SupabaseClient --> TelemetryClient
125+
FeatureFlagClient --> AppRouter
126+
```
127+
128+
## 4. Key Sequence Diagrams
129+
### 4.1 Article Publication with Reputation & Notifications
130+
```mermaid
131+
sequenceDiagram
132+
participant C as Creator
133+
participant UI as Next.js Client
134+
participant API as Route Handler (Content Service)
135+
participant DB as Supabase Postgres
136+
participant Rep as Reputation Service
137+
participant Notif as Notification Service
138+
139+
C->>UI: Draft article & click Publish
140+
UI->>API: POST /api/content (draft_id, publish_at)
141+
API->>DB: validate permissions + upsert posts, post_versions
142+
DB-->>API: success
143+
API->>Rep: record reputation_event(feature_flag="spaces_v1")
144+
Rep->>DB: insert reputation event & update aggregate
145+
API->>Notif: enqueue notifications (followers, space members)
146+
Notif->>DB: insert notification rows & webhooks
147+
Notif-->>API: queued
148+
API-->>UI: 202 Created + publish metadata
149+
UI->>C: Confirmation toast + redirect
150+
```
151+
152+
### 4.2 Space Moderation Workflow
153+
```mermaid
154+
sequenceDiagram
155+
participant Mod as Space Moderator
156+
participant UI as Admin Console
157+
participant API as Moderation Service
158+
participant DB as Supabase
159+
participant Audit as Audit Logger
160+
161+
Mod->>UI: Review reported post
162+
UI->>API: POST /api/moderation/resolve {action: "remove", flag_id}
163+
API->>DB: update report status, post visibility
164+
API->>Audit: log action with user, role, reason
165+
Audit->>DB: insert audit_logs entry
166+
API-->>UI: success response
167+
UI->>Mod: Display resolution & next steps
168+
```
169+
170+
## 5. Architectural Principles
171+
1. **Feature-flag first:** Every new capability (Spaces, Q&A, Events, Commerce) ships behind env-configurable flags with safe defaults.
172+
2. **Supabase as system of record:** Postgres tables capture canonical content, community, and commerce data with RLS enforcing role matrix.
173+
3. **Modular domain services:** Route handlers delegate to typed service modules to keep business logic testable and reusable across server components and workers.
174+
4. **Telemetry baked in:** Each service emits metrics and traces for the KPIs defined in `/docs/08-observability.md`.
175+
5. **Reversible migrations:** SQL migrations include down scripts and backfill jobs with resume tokens.
176+
6. **Zero-trust external integrations:** Payments, conferencing, and email providers communicate through signed webhooks and rotate secrets regularly.

0 commit comments

Comments
 (0)