chore(infra): retire managed Supabase cloud; Hetzner self-host is SSOT

The managed Supabase Cloud project (ohkueislstxomdjavyhs) is retired; the
self-hosted instance at supabase.orangecat.ch on the Hetzner box is the single
source of truth. Repoint the image host + setup scripts, rewrite the agent/dev
guidance to use the self-host directly (not the Supabase MCP, which only reaches
the retired cloud), update active docs, exit retired cloud-Management-API
scripts behind a RETIRED guard, env-ify direct-connect scripts, gitignore
.env-backups, and add a founder-run DECOMMISSION-CLOUD runbook. No live code
path references the managed project anymore.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.8 committed 2026-06-15 09:26:58 +02:00
1 parent 2ca20e80b0
commit 054204e943
82 files changed
+1102 -801

No files matched your search

+27 -14
View File
@@ -176,29 +176,42 @@ const { data } = await supabase
---
## Critical: Remote-Only Supabase
## Critical: Self-Hosted Supabase on Hetzner is the SSOT
**NO local Supabase** - always use remote instance.
The database is a **self-hosted Supabase instance on the Hetzner box (`bitbaum`),
reachable at `https://supabase.orangecat.ch`**. This is the single source of truth.
> ⚠️ **The managed Supabase Cloud project (`ohkueislstxomdjavyhs.supabase.co`) is
> RETIRED (2026-06).** Do NOT use it, and do NOT use the Supabase **MCP**
> (`mcp_supabase_*` / `mcp__claude_ai_Supabase__*`) — it only talks to the
> managed-cloud Management API, which no longer backs production. Any
> `mcp_supabase_*` examples elsewhere in `.claude/` are legacy and being retired.
```bash
# Credentials in .env.local
NEXT_PUBLIC_SUPABASE_URL=https://...
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
# Credentials live in .env.local (points at supabase.orangecat.ch).
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=...
SUPABASE_SERVICE_ROLE_KEY=...
# DON'T use these:
npx supabase start # Won't work
npx supabase stop # Won't work
# Do NOT spin up a separate local stack for normal work:
npx supabase start # not the workflow
```
**Use MCP tools instead**:
**To inspect / change the DB**, connect to the self-hosted instance directly:
```typescript
mcp_supabase_list_tables();
mcp_supabase_execute_sql();
mcp_supabase_apply_migration();
```bash
# Read/query via the pooled connection string in .env.local
psql "$POSTGRES_URL" -c '\d+ notifications'
# Schema changes: add a migration under supabase/migrations/ and apply it
# against the self-hosted DB (psql or supabase CLI pointed at supabase.orangecat.ch).
# Migrations are the SSOT for schema — keep them runnable on a fresh box.
```
Note: this agent's sandbox generally cannot reach `supabase.orangecat.ch` directly
(it's behind Caddy on the box). Box-side DB work goes through the founder /
FleetCrown agent. Never reintroduce the managed-cloud project as a shortcut.
---
## API Pattern
+20 -23
View File
@@ -273,49 +273,46 @@ CREATE TABLE user_products (
---
## Remote-Only Supabase
## Self-Hosted Supabase on Hetzner (SSOT)
### Critical Rules
**NO local Supabase** for development:
The database is a **self-hosted Supabase instance on the Hetzner box** at
`https://supabase.orangecat.ch`. It is the single source of truth.
- Always use remote instance
- Connection string in `.env.local`
- See `docs/operations/REMOTE_ONLY_SUPABASE.md`
- Connection string + keys in `.env.local` (already points at the self-host)
- **The managed Supabase Cloud project (`ohkueislstxomdjavyhs`) is RETIRED (2026-06)**
**Environment Variables**:
```bash
# .env.local
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=...
SUPABASE_SERVICE_ROLE_KEY=...
```
**Why Remote-Only**:
**Why self-hosted on Hetzner**:
- Shared database across team
- No local Docker complexity
- Consistent data for all developers
- Easier onboarding
- Real-time features work correctly
- We own the data and the box — no managed-cloud dependency or fair-use limits
- Single SSOT for prod and (per current setup) local dev
- Real-time, auth, storage all served from the one instance
**Commands to AVOID**:
**Do NOT**:
```bash
# ❌ Don't run these
npx supabase start # Won't work
npx supabase stop # Won't work
npx supabase db reset # Use remote migration instead
# ❌ Don't use the retired managed cloud or its MCP
mcp_supabase_* # talks to managed-cloud Management API — retired
# ❌ Don't spin up a throwaway local stack for normal work
npx supabase start
```
**Use Instead**:
```bash
# ✅ Use MCP tools
mcp_supabase_list_tables()
mcp_supabase_execute_sql()
mcp_supabase_apply_migration()
# ✅ Talk to the self-hosted DB directly
psql "$POSTGRES_URL" -c 'select 1;'
# ✅ Schema changes = a new file in supabase/migrations/ applied to the self-host
```
---
+3
View File
@@ -157,3 +157,6 @@ __pycache__/
# Local debug screenshots
post-*.png
.env.selfhost.local
# Env backups (contain secrets — never commit)
.env-backups/
+1 -1
View File
@@ -276,6 +276,6 @@ console.log('Update error:', error);
- [Supabase Auth Documentation](https://supabase.com/docs/guides/auth)
- [Row Level Security Guide](https://supabase.com/docs/guides/auth/row-level-security)
- [Supabase SQL Editor](https://supabase.com/dashboard/project/YOUR_PROJECT/sql)
- SQL editor — (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
This documentation should be updated whenever the schema changes to keep it accurate and useful for development and debugging.
+23 -2
View File
@@ -18,6 +18,7 @@
## Security Status
✅ **SECURE** - All critical vulnerabilities fixed (June 2025):
- File upload authorization bypass - **FIXED**
- Celebrity impersonation prevention - **IMPLEMENTED**
- Console.log data exposure - **ELIMINATED**
@@ -28,6 +29,7 @@
## Test Coverage Status
⚠️ **CRITICAL GAP** - Current test coverage: **4.9%** (Target: 85%)
- **Security Tests**: Excellent (77 tests)
- **Component Tests**: Minimal coverage
- **Integration Tests**: None
@@ -77,6 +79,7 @@ src/
## Key Components
### Authentication (✅ Security Hardened)
- Implemented using Supabase Auth with enhanced security
- `useAuth` hook for authentication state management (21 tests)
- Protected routes using middleware
@@ -84,6 +87,7 @@ src/
- **Security**: Auth state inconsistency fixes implemented
### Profile Management (✅ Security Hardened)
- Complete CRUD operations through Supabase
- Type-safe operations with TypeScript
- **Security**: Enhanced profile validation and sanitization
@@ -92,6 +96,7 @@ src/
- Avatar upload with security validation
### File Upload System (✅ Security Hardened)
- **Security**: Mandatory user authentication
- **Security**: Magic byte validation for file types
- **Security**: Malicious content scanning
@@ -100,6 +105,7 @@ src/
- Comprehensive security testing (9 tests)
### Funding System
- Bitcoin and Lightning Network integration
- Transaction tracking and verification
- Goal tracking and progress updates
@@ -107,6 +113,7 @@ src/
- **Security**: Enhanced Bitcoin address validation
### Testing Infrastructure (⚠️ CRITICAL GAP)
- Jest for unit testing
- React Testing Library for component testing
- **Current Coverage**: 4.9% (Need 85% for production)
@@ -115,6 +122,7 @@ src/
- **Integration Tests**: Critical gap
### Celebrity Impersonation Prevention (✅ NEW)
- 75+ protected celebrity/brand usernames
- Character substitution attack detection
- Unicode lookalike character prevention
@@ -122,6 +130,7 @@ src/
- Comprehensive testing (25 tests)
### Logging System (✅ Security Hardened)
- Structured logging with proper log levels
- Production-safe (no sensitive data exposure)
- Replaced 85%+ of console.log statements
@@ -130,6 +139,7 @@ src/
## Environment Variables
Required environment variables:
```env
# Application Configuration
NEXT_PUBLIC_SITE_URL=http://localhost:3000
@@ -137,7 +147,7 @@ NEXT_PUBLIC_SITE_NAME=OrangeCat (Dev)
NODE_ENV=development
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=https://ohkueislstxomdjavyhs.supabase.co
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key
# Bitcoin Configuration
@@ -149,6 +159,7 @@ BITCOIN_NETWORK=mainnet
## Database Schema
### Users Table
```sql
create table users (
id uuid references auth.users on delete cascade,
@@ -161,6 +172,7 @@ create table users (
```
### Profiles Table
```sql
create table profiles (
id uuid default uuid_generate_v4() primary key,
@@ -176,6 +188,7 @@ create table profiles (
```
### Funding Pages Table
```sql
create table funding_pages (
id uuid default uuid_generate_v4() primary key,
@@ -195,22 +208,26 @@ create table funding_pages (
## Development Setup
1. Clone the repository:
```bash
git clone https://github.com/g-but/orangecat.git
cd orangecat
```
2. Install dependencies:
```bash
npm install
```
3. Set up environment variables:
```bash
cp .env.example .env.local
```
4. Start development server (recommended):
```bash
npm run fresh:start
```
@@ -242,6 +259,7 @@ npm test -- --testPathPattern="security|verification|validation"
```
### Test Coverage Goals
- **Current**: 4.9% (CRITICAL - need improvement)
- **Target**: 85% before production
- **Security Coverage**: Excellent (77 tests)
@@ -250,6 +268,7 @@ npm test -- --testPathPattern="security|verification|validation"
## Deployment
The application is deployed on Vercel with the following configuration:
- Automatic deployments from main branch
- Environment variables managed in Vercel dashboard
- Production URL: https://orangecat.ch
@@ -260,6 +279,7 @@ The application is deployed on Vercel with the following configuration:
## Architecture Priorities
### ✅ COMPLETED
- Critical security vulnerabilities fixed
- Celebrity impersonation prevention
- File upload security hardening
@@ -267,6 +287,7 @@ The application is deployed on Vercel with the following configuration:
- Console.log production exposure eliminated
### 🚨 CRITICAL NEXT STEPS
1. **Test Coverage** (Essential for production)
- Increase from 4.9% to 85%
- Add component testing
@@ -291,4 +312,4 @@ The application is deployed on Vercel with the following configuration:
- **State Management**: Use Zustand for complex state (projects, auth)
- **Logging**: Use structured logger, never console.log in production
- **Validation**: Multi-layer security validation for all inputs
- **Documentation**: Keep documentation updated with current state
- **Documentation**: Keep documentation updated with current state
@@ -24,6 +24,7 @@
```
**Why this matters:**
- ✅ Easy onboarding for new developers
- ✅ Single source of truth for database architecture
- ✅ Clear roadmap for future improvements
@@ -34,20 +35,24 @@
### 2. ✅ Two High-Priority Migrations Created
#### Migration #1: Add Index on transactions.status
**File:** `supabase/migrations/20251017000001_add_transactions_status_index.sql`
**What it does:**
```sql
CREATE INDEX idx_transactions_status ON transactions(status);
```
**Impact:**
- 🚀 **10x faster** queries filtering by transaction status
- 📊 Critical for admin dashboards
- 💳 Essential for payment processing
- 📈 Improves analytics performance
**Before:**
```sql
EXPLAIN ANALYZE
SELECT * FROM transactions WHERE status = 'pending';
@@ -56,6 +61,7 @@ SELECT * FROM transactions WHERE status = 'pending';
```
**After (once applied):**
```sql
EXPLAIN ANALYZE
SELECT * FROM transactions WHERE status = 'pending';
@@ -68,9 +74,11 @@ SELECT * FROM transactions WHERE status = 'pending';
---
#### Migration #2: Create audit_logs Table
**File:** `supabase/migrations/20251017000002_create_audit_logs.sql`
**What it creates:**
- 📋 `audit_logs` table - Complete audit trail
- 🔧 `create_audit_log()` function - Easy logging from code
- ⚡ 6 strategic indexes - Efficient querying
@@ -78,12 +86,14 @@ SELECT * FROM transactions WHERE status = 'pending';
- 📝 Example trigger on profiles table - Automatic logging
**Impact:**
- 🔐 **Security**: Track all critical operations
- 📜 **Compliance**: Meet financial regulations (Bitcoin)
- 🐛 **Debugging**: Trace complex state changes
- 👥 **Support**: Help users with issues
**What gets logged:**
- ✅ Profile updates (especially verification, Bitcoin addresses)
- ✅ Financial transactions (all state changes)
- ✅ Organization membership changes
@@ -91,6 +101,7 @@ SELECT * FROM transactions WHERE status = 'pending';
- ✅ Campaign status changes
**Example usage:**
```sql
-- Automatic (via trigger)
UPDATE profiles SET is_verified = true WHERE id = '...';
@@ -132,6 +143,7 @@ SELECT create_audit_log(
- CI/CD ready
**Includes:**
- ✅ Step-by-step instructions
- ✅ Verification scripts
- ✅ Rollback procedures
@@ -143,6 +155,7 @@ SELECT create_audit_log(
## 📚 What You Learned Today
### 1. Database Analysis & Rating
- How to systematically evaluate database architecture
- What makes a "good" database design
- Trade-offs between normalization, performance, and flexibility
@@ -150,6 +163,7 @@ SELECT create_audit_log(
**Key takeaway:** Your database scored **8.7/10** - production-ready with room for optimization!
### 2. Migration Strategy
- Different approaches to applying database changes
- Idempotent migrations (`IF NOT EXISTS`)
- Transaction wrapping (`BEGIN`/`COMMIT`)
@@ -158,6 +172,7 @@ SELECT create_audit_log(
**Key takeaway:** Always test, document, verify, and have a rollback plan!
### 3. PostgreSQL Best Practices
- **Indexes**: Speed up queries but add write overhead
- **JSONB**: Flexibility vs structure
- **RLS**: Security at database level
@@ -165,6 +180,7 @@ SELECT create_audit_log(
- **SECURITY DEFINER**: Controlled privilege escalation
### 4. Real-World Debugging
- Connection issues in production
- Environment variable management
- Multiple deployment methods (fallbacks!)
@@ -179,6 +195,7 @@ SELECT create_audit_log(
### Step 1: Review the Migrations
Read through both migration files to understand what they do:
```bash
# Migration 1: Index
cat supabase/migrations/20251017000001_add_transactions_status_index.sql
@@ -188,6 +205,7 @@ cat supabase/migrations/20251017000002_create_audit_logs.sql
```
**Ask yourself:**
- What does this change?
- Why do we need it?
- What could go wrong?
@@ -198,11 +216,12 @@ cat supabase/migrations/20251017000002_create_audit_logs.sql
This is a **safe, high-impact change**. Let's get a win!
**Recommended method:** Supabase Dashboard
**Method:** SQL editor
1. Go to: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new
1. Run in the SQL editor. (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
2. Copy this SQL:
```sql
BEGIN;
@@ -253,6 +272,7 @@ LIMIT 10;
```
**What to look for:**
- ✅ Plan shows: "Index Scan using idx_transactions_status"
- ✅ Execution time is fast (<100ms)
@@ -263,6 +283,7 @@ LIMIT 10;
This is a **more complex change** but still safe (new table).
**Same process:**
1. Go to Supabase SQL Editor
2. Copy entire content of: `20251017000002_create_audit_logs.sql`
3. Click "RUN"
@@ -302,6 +323,7 @@ LIMIT 5;
After applying both migrations, monitor:
**For the index:**
```sql
-- Check if index is being used
SELECT
@@ -313,6 +335,7 @@ WHERE indexname = 'idx_transactions_status';
```
**For audit logs:**
```sql
-- Check volume of logs
SELECT
@@ -356,18 +379,21 @@ ORDER BY hour DESC;
After applying these improvements, you should see:
### Immediate (Day 1)
- ✅ Index exists in database
- ✅ Audit logs table created
- ✅ No errors in application
- ✅ Queries using new index
### Short-term (Week 1)
- ✅ Faster dashboard load times
- ✅ Audit logs being created automatically
- ✅ Index usage stats showing > 0
- ✅ No performance regressions
### Long-term (Month 1)
- ✅ Reduced query times (metrics)
- ✅ Useful audit trail for debugging
- ✅ Compliance requirements met
@@ -380,6 +406,7 @@ After applying these improvements, you should see:
**After these two migrations**, we have a roadmap:
### Next Priorities (Q1 2026)
1. **Table Partitioning** for transactions
- Handle unlimited growth
- 10x faster queries on old data
@@ -404,6 +431,7 @@ After applying these improvements, you should see:
### For Future Migrations
1. **Always use transactions**
```sql
BEGIN;
-- Your changes
@@ -412,17 +440,20 @@ After applying these improvements, you should see:
```
2. **Make it idempotent**
```sql
CREATE INDEX IF NOT EXISTS ...
CREATE TABLE IF NOT EXISTS ...
```
3. **Add documentation**
```sql
COMMENT ON INDEX ... IS 'Why this exists...';
```
4. **Verify after applying**
```sql
SELECT * FROM pg_indexes WHERE ...
```
@@ -445,6 +476,7 @@ After applying these improvements, you should see:
## 🎉 Congratulations!
You now have:
- ✅ **Complete database documentation**
- ✅ **Two production-ready migrations**
- ✅ **Comprehensive deployment guide**
@@ -469,6 +501,7 @@ If you get stuck:
4. **Check Supabase logs:** Dashboard → Logs
**Remember:** Every production engineer runs into issues. The key is:
- Stay calm 🧘
- Read error messages carefully 🔍
- Have multiple approaches 🛠️
@@ -478,4 +511,4 @@ If you get stuck:
**Happy deploying!** 🎊
*Remember: You're learning with a senior engineer. There's no such thing as a "stupid question" - only unasked questions that lead to production issues later!*
_Remember: You're learning with a senior engineer. There's no such thing as a "stupid question" - only unasked questions that lead to production issues later!_
+45 -15
View File
@@ -19,32 +19,35 @@
## 🔗 Essential Links
| Resource | URL |
|----------|-----|
| **Supabase Dashboard** | https://supabase.com/dashboard/project/ohkueislstxomdjavyhs |
| **SQL Editor** | https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new |
| **Database Explorer** | https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/editor |
| **Logs** | https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/logs/explorer |
| **Indexes** | https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/database/indexes |
> (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; Studio / SQL editor / logs are accessed via the box / founder.)
| Resource | URL |
| --------------------- | ----------------------------------- |
| **Supabase Studio** | self-hosted (via the box / founder) |
| **SQL Editor** | self-hosted Studio |
| **Database Explorer** | self-hosted Studio |
| **Logs** | self-hosted Studio |
| **Indexes** | self-hosted Studio |
---
## 📁 Documentation Navigation
| Document | Purpose |
|----------|---------|
| **[README.md](./README.md)** | Start here - navigation hub |
| **[schema-overview.md](./schema-overview.md)** | Architecture & design patterns |
| **[analysis-rating.md](./analysis-rating.md)** | Comprehensive 8.7/10 analysis |
| **[improvements-roadmap.md](./improvements-roadmap.md)** | Planned enhancements |
| **[DEPLOYMENT_GUIDE.md](./DEPLOYMENT_GUIDE.md)** | How to apply migrations |
| **[IMPROVEMENTS_SUMMARY.md](./IMPROVEMENTS_SUMMARY.md)** | What we built today |
| Document | Purpose |
| -------------------------------------------------------- | ------------------------------ |
| **[README.md](./README.md)** | Start here - navigation hub |
| **[schema-overview.md](./schema-overview.md)** | Architecture & design patterns |
| **[analysis-rating.md](./analysis-rating.md)** | Comprehensive 8.7/10 analysis |
| **[improvements-roadmap.md](./improvements-roadmap.md)** | Planned enhancements |
| **[DEPLOYMENT_GUIDE.md](./DEPLOYMENT_GUIDE.md)** | How to apply migrations |
| **[IMPROVEMENTS_SUMMARY.md](./IMPROVEMENTS_SUMMARY.md)** | What we built today |
---
## ⚡ Common Commands
### Check Table Sizes
```sql
SELECT
schemaname,
@@ -56,6 +59,7 @@ ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
```
### Check Index Usage
```sql
SELECT
schemaname,
@@ -68,6 +72,7 @@ ORDER BY idx_scan ASC;
```
### Find Slow Queries
```sql
SELECT
pid,
@@ -81,6 +86,7 @@ ORDER BY duration DESC;
```
### Check Active Connections
```sql
SELECT
count(*) as total_connections,
@@ -90,6 +96,7 @@ FROM pg_stat_activity;
```
### View Recent Audit Logs (After Migration #2)
```sql
SELECT
created_at,
@@ -109,6 +116,7 @@ LIMIT 20;
### ✅ Ready to Apply
#### 1. Add transactions.status Index
```bash
File: supabase/migrations/20251017000001_add_transactions_status_index.sql
Priority: P0 - Critical
@@ -118,11 +126,13 @@ Time: 2 minutes
```
**Quick Apply (Supabase Dashboard):**
```sql
CREATE INDEX IF NOT EXISTS idx_transactions_status ON transactions(status);
```
#### 2. Create Audit Logs Table
```bash
File: supabase/migrations/20251017000002_create_audit_logs.sql
Priority: P0 - Compliance
@@ -138,6 +148,7 @@ Time: 5 minutes
## 🔍 Verification Queries
### After Migration #1 (Index)
```sql
-- Verify index exists
SELECT * FROM pg_indexes
@@ -152,6 +163,7 @@ LIMIT 10;
```
### After Migration #2 (Audit Logs)
```sql
-- Verify table exists
SELECT count(*) FROM audit_logs;
@@ -169,6 +181,7 @@ SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT 1;
## 📊 Monitoring Queries
### Index Health
```sql
SELECT
indexname,
@@ -182,6 +195,7 @@ ORDER BY idx_scan DESC;
```
### Table Bloat
```sql
SELECT
tablename,
@@ -195,6 +209,7 @@ ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
```
### Audit Log Volume (After Migration #2)
```sql
SELECT
date_trunc('day', created_at) as day,
@@ -211,6 +226,7 @@ ORDER BY day DESC;
## 🛠️ Useful Functions
### Create Manual Audit Log (After Migration #2)
```sql
SELECT create_audit_log(
p_user_id := auth.uid(),
@@ -223,11 +239,13 @@ SELECT create_audit_log(
```
### Increment Profile Views
```sql
SELECT increment_profile_views('profile-uuid');
```
### Update Follow Counts (Automatic via Trigger)
```sql
-- Automatically maintained when follows are added/removed
INSERT INTO follows (follower_id, following_id)
@@ -239,12 +257,14 @@ VALUES ('user-a-id', 'user-b-id');
## 🚨 Troubleshooting
### Connection Issues
```sql
-- Check if you can connect
SELECT current_database(), current_user, version();
```
### Permission Issues
```sql
-- Check your role
SELECT current_user, session_user;
@@ -258,6 +278,7 @@ WHERE schemaname = 'public';
```
### Migration Failed
```sql
-- Check what migrations were applied
SELECT * FROM supabase_migrations.schema_migrations
@@ -272,6 +293,7 @@ ROLLBACK;
## 📈 Performance Baselines
### Current (Before Improvements)
```
transactions table:
- Status filter query: ~500ms (seq scan)
@@ -279,6 +301,7 @@ transactions table:
```
### Target (After Improvements)
```
transactions table:
- Status filter query: ~50ms (index scan) ✨ 10x faster
@@ -306,6 +329,7 @@ Before applying any migration:
## 📞 Emergency Contacts
### Supabase Support
- Status Page: https://status.supabase.com/
- Support: Dashboard → Help → Support
- Community: https://github.com/supabase/supabase/discussions
@@ -313,6 +337,7 @@ Before applying any migration:
### Rollback Procedures
#### Rollback Index Creation
```sql
BEGIN;
DROP INDEX IF EXISTS idx_transactions_status;
@@ -320,6 +345,7 @@ COMMIT;
```
#### Rollback Audit Logs (if needed)
```sql
BEGIN;
DROP TRIGGER IF EXISTS trigger_audit_profile_changes ON profiles;
@@ -334,11 +360,13 @@ COMMIT;
## 🎓 Learning Resources
### PostgreSQL
- Official Docs: https://www.postgresql.org/docs/
- Performance Tips: https://wiki.postgresql.org/wiki/Performance_Optimization
- Index Types: https://www.postgresql.org/docs/current/indexes-types.html
### Supabase
- Docs: https://supabase.com/docs
- RLS Guide: https://supabase.com/docs/guides/auth/row-level-security
- Migrations: https://supabase.com/docs/guides/cli/local-development#database-migrations
@@ -348,6 +376,7 @@ COMMIT;
## 💡 Pro Tips
1. **Always wrap in transactions**
```sql
BEGIN;
-- your changes
@@ -355,6 +384,7 @@ COMMIT;
```
2. **Use EXPLAIN ANALYZE**
```sql
EXPLAIN ANALYZE SELECT ...
```
+21 -1
View File
@@ -10,29 +10,35 @@
## 📋 Quick Navigation
### 🚀 Getting Started
- **[QUICK_REFERENCE.md](./QUICK_REFERENCE.md)** - Essential commands & links (start here!)
- **[IMPROVEMENTS_SUMMARY.md](./IMPROVEMENTS_SUMMARY.md)** - What we built & how to deploy
- **[DEPLOYMENT_GUIDE.md](./DEPLOYMENT_GUIDE.md)** - Step-by-step deployment instructions
### Core Documentation
- **[Schema Overview](./schema-overview.md)** - High-level architecture and design patterns
- **[Analysis & Rating](./analysis-rating.md)** - Comprehensive 9.2/10 analysis of simplified architecture
- **[Current Schema](./database-schema.md)** - Complete database schema reference
- **[Migration Guide](./migrations-guide.md)** - Database migration instructions
### Current Tables (5 Core Tables)
- **[profiles](./tables/profiles.md)** - User profiles with Bitcoin features (15 essential fields)
- **[projects](./tables/projects.md)** - Unified fundraising entity (replaces campaigns + projects)
- **[transactions](./tables/transactions.md)** - Multi-entity Bitcoin payments (any → any)
- **[organizations](./tables/organizations.md)** - Group entities for collaborative fundraising
- **[organization_members](./tables/organization_members.md)** - Simple team management
### Key Features
- **Multi-Entity Transactions** - Any entity can donate to any other entity
- **Bitcoin Wallet Integration** - Lightning/Bitcoin addresses for all entities
- **Transparency by Default** - Public transaction visibility and audit trails
- **Simplified Permissions** - Clear role-based access control
### Database Benefits
- ✅ **60% Fewer Tables** - 5 core tables vs 10+ complex tables
- ✅ **Bitcoin-Native** - Lightning/Bitcoin addresses for all entities
- ✅ **Transparent** - Public transaction visibility and audit trails
@@ -40,12 +46,14 @@
- ✅ **Maintainable** - Simple relationships and clear data flow
### Analysis & Roadmap
- **[Architecture Analysis & Rating](./analysis-rating.md)** - Comprehensive 9.2/10 analysis of simplified architecture
- **[Improvements Roadmap](./improvements-roadmap.md)** - Planned enhancements for current schema
## 🎯 Database at a Glance
### Statistics
- **5 Core Tables** - Essential entities for Bitcoin crowdfunding
- **Multi-Entity Transactions** - Any entity can donate to any other
- **Bitcoin Wallet Support** - Lightning/Bitcoin addresses for all entities
@@ -59,6 +67,7 @@
### Key Features
#### 1. Bitcoin-Native Architecture (9/10)
- ✅ Precise decimal handling: `numeric(20,8)` for satoshi precision
- ✅ Multiple payment methods: On-chain + Lightning Network
- ✅ Address validation with regex patterns
@@ -67,6 +76,7 @@
- ✅ Revenue sharing via `reward_percentage`
#### 2. Polymorphic Associations (10/10)
- ✅ Flexible entity relationships in single table
- ✅ Temporal relationships (starts_at, ends_at)
- ✅ Version tracking for change history
@@ -74,12 +84,14 @@
- ✅ Complete audit trail
#### 3. Security First (8.5/10)
- ✅ RLS enabled on all tables
- ✅ Principle of least privilege
- ✅ Role-based access for organizations
- ✅ SECURITY DEFINER functions for controlled escalation
#### 4. Performance Optimized (8/10)
- ✅ GIN trigram indexes for fuzzy search
- ✅ Partial indexes for hot queries
- ✅ Denormalized counters with triggers
@@ -88,6 +100,7 @@
## 🚀 Quick Start
### Accessing the Database
```bash
# Using Supabase CLI
supabase db pull
@@ -97,13 +110,15 @@ psql $DATABASE_URL
```
### Environment Variables
```bash
NEXT_PUBLIC_SUPABASE_URL=https://ohkueislstxomdjavyhs.supabase.co
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your-anon-key>
SUPABASE_SERVICE_ROLE_KEY=<your-service-role-key>
```
### Common Queries
```sql
-- Get profile with associations
SELECT p.*,
@@ -138,12 +153,15 @@ WHERE status IN ('pending', 'processing');
## ⚠️ Important Notes
### Current Limitations
- Transactions table not partitioned (will need this as volume grows)
- No dedicated audit log table (recommended for compliance)
- Missing index on `transactions.status` (being added)
### Planned Improvements
See [Improvements Roadmap](./improvements-roadmap.md) for:
- Table partitioning strategy
- Audit logging implementation
- Materialized views for analytics
@@ -159,12 +177,14 @@ See [Improvements Roadmap](./improvements-roadmap.md) for:
## 🛠️ Maintenance
### Regular Tasks
- **Weekly**: Review slow query logs
- **Monthly**: Check index usage statistics
- **Quarterly**: Analyze table bloat and vacuum
- **As needed**: Update RLS policies for new features
### Monitoring
```sql
-- Check table sizes
SELECT
+1 -1
View File
@@ -62,7 +62,7 @@ The following variables should always be present in `.env.local`:
NODE_ENV=development
NEXT_PUBLIC_SITE_URL=http://localhost:3000
NEXT_PUBLIC_SITE_NAME=OrangeCat
NEXT_PUBLIC_SUPABASE_URL=https://ohkueislstxomdjavyhs.supabase.co
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=...
NEXT_PUBLIC_BITCOIN_ADDRESS=...
NEXT_PUBLIC_LIGHTNING_ADDRESS=...
+26 -5
View File
@@ -7,11 +7,13 @@
Before you begin, ensure you have:
### Required Software
- **Node.js** 18+ LTS - [Download](https://nodejs.org/)
- **Git** - Version control system
- **npm** or **yarn** - Package manager (npm recommended)
### Optional but Recommended
- **VS Code** - IDE with excellent TypeScript support
- **Supabase CLI** - For local database development
- **Docker** - For containerized development
@@ -19,17 +21,20 @@ Before you begin, ensure you have:
## ⚡ Quick Setup (5 minutes)
### 1. Clone Repository
```bash
git clone <repository-url>
cd orangecat
```
### 2. Install Dependencies
```bash
npm install
```
### 3. Set Up Environment Variables
```bash
# Copy template
cp config/production.env.template .env.local
@@ -39,6 +44,7 @@ cp config/production.env.template .env.local
```
### 4. Database Setup
OrangeCat uses **cloud Supabase only**. No database setup required.
- Database is pre-configured and running in the cloud
@@ -46,6 +52,7 @@ OrangeCat uses **cloud Supabase only**. No database setup required.
- Environment variables are already configured
### 5. Start Development Server
```bash
# Use the clean start command (recommended)
npm run fresh:start
@@ -57,16 +64,19 @@ npm run dev:clean
## 🔧 Development Environment Details
### Node.js Setup
- **Version**: 18.17.0+ (LTS)
- **Package Manager**: npm (yarn also supported)
- **Environment**: Development uses `.env.local`
### Supabase Configuration
- **Development & Production**: Uses hosted Supabase instance only
- **No Local Database**: Cloud-only setup for consistency and resource efficiency
- **Migrations**: Via Supabase dashboard or API
### VS Code Extensions (Recommended)
```json
{
"recommendations": [
@@ -83,6 +93,7 @@ npm run dev:clean
## 🧪 Testing Setup
### Test Database
```bash
# Set up test environment
cp .env.example .env.test.local
@@ -95,6 +106,7 @@ npm run test:coverage
```
### Browser Testing
```bash
# Install Playwright browsers
npx playwright install
@@ -106,6 +118,7 @@ npm run test:e2e
## 🔒 Security Setup
### Environment Variables
```bash
# Required for development
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
@@ -117,6 +130,7 @@ SUPABASE_ACCESS_TOKEN=your_access_token
```
### Authentication Setup
- Supabase handles authentication automatically
- No additional setup required for basic auth
- Social logins configured in Supabase dashboard
@@ -124,12 +138,14 @@ SUPABASE_ACCESS_TOKEN=your_access_token
## 🐛 Debugging Setup
### Browser DevTools
1. Open Chrome DevTools (F12)
2. Go to Network tab
3. Check Console for errors
4. Monitor Application tab for React DevTools
### VS Code Debugging
```json
// .vscode/launch.json
{
@@ -150,6 +166,7 @@ SUPABASE_ACCESS_TOKEN=your_access_token
## 📊 Monitoring Setup
### Local Monitoring
```bash
# Start monitoring dashboard
npm run monitor:metrics
@@ -159,6 +176,7 @@ npm run health:check
```
### Error Tracking
- Console errors automatically logged
- Production errors sent to monitoring service
- Database query performance tracked
@@ -166,6 +184,7 @@ npm run health:check
## 🚀 Advanced Setup Options
### Docker Development
```bash
# Build and run with Docker
docker-compose up --build
@@ -175,11 +194,12 @@ docker-compose run --rm app npm test
```
### Multiple Environment Setup
```bash
# Development
cp config/production.env.template .env.local
# Staging
# Staging
cp config/production.env.template .env.staging
# Production
@@ -189,6 +209,7 @@ cp config/production.env.template .env.staging
## 🔧 Troubleshooting Setup Issues
### Port Conflicts
```bash
# Kill existing Node processes
npm run kill:node
@@ -201,19 +222,19 @@ npm run fresh:start
```
### Database Issues
OrangeCat uses cloud Supabase - no local database to manage.
```bash
# Check cloud database connectivity
node scripts/diagnostics/check-supabase.js
# View database logs (via Supabase dashboard)
# https://app.supabase.com/project/ohkueislstxomdjavyhs/dashboard
# For schema changes, use the dashboard SQL editor
# View database logs / run schema changes
# (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
```
### Permission Issues
```bash
# Fix file permissions
chmod +x scripts/*.sh
+4 -2
View File
@@ -132,9 +132,11 @@ node --inspect-brk scripts/debug-script.js
## 🗄️ Database Debugging
### Supabase Dashboard
### Supabase Studio
1. **Go to your project** - supabase.com/dashboard
(Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
1. **Open Studio** on the self-hosted instance
2. **Table Editor** - View and edit data directly
3. **SQL Editor** - Run queries and view results
4. **Logs** - Monitor database activity
+110 -142
View File
@@ -41,6 +41,7 @@ This guide provides step-by-step instructions for implementing the architecture
### TypeScript Updates
**`/src/types/database.ts`** - Added:
- `organization_members` table types (Row, Insert, Update)
- `projects` table types (Row, Insert, Update)
- `project_id` field to projects
@@ -64,9 +65,9 @@ cd /home/g/dev/orangecat
# Apply migrations using Supabase CLI
npx supabase db push
# Or apply manually via Supabase Dashboard SQL Editor:
# 1. Go to https://app.supabase.com/project/ohkueislstxomdjavyhs/editor
# 2. Run each migration file in order:
# Or apply manually via SQL editor:
# (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
# Run each migration file in order:
# - 20251013_create_organization_members.sql
# - 20251013_create_projects.sql
# - 20251013_add_project_to_projects.sql
@@ -96,13 +97,13 @@ Create service files for the new entities following the existing pattern.
**File:** `/src/services/supabase/organization-members.ts`
```typescript
import { createServerClient } from './server'
import { createServerClient } from './server';
import type {
OrganizationMember,
OrganizationMemberInsert,
OrganizationMemberUpdate,
OrganizationPermissions
} from '@/types/database'
OrganizationPermissions,
} from '@/types/database';
/**
* Get all members of an organization
@@ -110,17 +111,17 @@ import type {
export async function getOrganizationMembers(
organizationId: string
): Promise<OrganizationMember[]> {
const supabase = await createServerClient()
const supabase = await createServerClient();
const { data, error } = await supabase
.from('organization_members')
.select('*, profiles(*)')
.eq('organization_id', organizationId)
.eq('status', 'active')
.order('joined_at', { ascending: true })
.order('joined_at', { ascending: true });
if (error) throw error
return data || []
if (error) throw error;
return data || [];
}
/**
@@ -133,7 +134,7 @@ export async function addOrganizationMember(
invitedBy: string,
permissions?: OrganizationPermissions
): Promise<OrganizationMember> {
const supabase = await createServerClient()
const supabase = await createServerClient();
const memberData: OrganizationMemberInsert = {
organization_id: organizationId,
@@ -141,17 +142,17 @@ export async function addOrganizationMember(
role,
invited_by: invitedBy,
permissions: permissions || {},
status: 'pending' // Requires acceptance
}
status: 'pending', // Requires acceptance
};
const { data, error } = await supabase
.from('organization_members')
.insert(memberData)
.select()
.single()
.single();
if (error) throw error
return data
if (error) throw error;
return data;
}
/**
@@ -161,33 +162,28 @@ export async function updateOrganizationMember(
memberId: string,
updates: OrganizationMemberUpdate
): Promise<OrganizationMember> {
const supabase = await createServerClient()
const supabase = await createServerClient();
const { data, error } = await supabase
.from('organization_members')
.update(updates)
.eq('id', memberId)
.select()
.single()
.single();
if (error) throw error
return data
if (error) throw error;
return data;
}
/**
* Remove a member from an organization
*/
export async function removeOrganizationMember(
memberId: string
): Promise<void> {
const supabase = await createServerClient()
export async function removeOrganizationMember(memberId: string): Promise<void> {
const supabase = await createServerClient();
const { error } = await supabase
.from('organization_members')
.delete()
.eq('id', memberId)
const { error } = await supabase.from('organization_members').delete().eq('id', memberId);
if (error) throw error
if (error) throw error;
}
/**
@@ -197,7 +193,7 @@ export async function canEditOrganization(
userId: string,
organizationId: string
): Promise<boolean> {
const supabase = await createServerClient()
const supabase = await createServerClient();
const { data, error } = await supabase
.from('organization_members')
@@ -205,17 +201,17 @@ export async function canEditOrganization(
.eq('organization_id', organizationId)
.eq('profile_id', userId)
.eq('status', 'active')
.single()
.single();
if (error || !data) return false
if (error || !data) return false;
// Owners and admins can always edit
if (data.role === 'owner' || data.role === 'admin') {
return true
return true;
}
// Check specific permission
return (data.permissions as OrganizationPermissions)?.can_edit_org === true
return (data.permissions as OrganizationPermissions)?.can_edit_org === true;
}
```
@@ -224,22 +220,14 @@ export async function canEditOrganization(
**File:** `/src/services/supabase/projects.ts`
```typescript
import { createServerClient } from './server'
import type {
Project,
ProjectInsert,
ProjectUpdate,
ProjectWithProjects
} from '@/types/database'
import { createServerClient } from './server';
import type { Project, ProjectInsert, ProjectUpdate, ProjectWithProjects } from '@/types/database';
/**
* Get all public projects
*/
export async function getPublicProjects(
limit = 50,
offset = 0
): Promise<Project[]> {
const supabase = await createServerClient()
export async function getPublicProjects(limit = 50, offset = 0): Promise<Project[]> {
const supabase = await createServerClient();
const { data, error } = await supabase
.from('projects')
@@ -247,84 +235,70 @@ export async function getPublicProjects(
.eq('visibility', 'public')
.eq('status', 'active')
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
.range(offset, offset + limit - 1);
if (error) throw error
return data || []
if (error) throw error;
return data || [];
}
/**
* Get project by slug
*/
export async function getProjectBySlug(
slug: string
): Promise<ProjectWithProjects | null> {
const supabase = await createServerClient()
export async function getProjectBySlug(slug: string): Promise<ProjectWithProjects | null> {
const supabase = await createServerClient();
const { data, error } = await supabase
.from('projects')
.select('*, projects(*)')
.eq('slug', slug)
.single()
.single();
if (error) {
if (error.code === 'PGRST116') return null // Not found
throw error
if (error.code === 'PGRST116') return null; // Not found
throw error;
}
return data
return data;
}
/**
* Create a new project
*/
export async function createProject(
projectData: ProjectInsert
): Promise<Project> {
const supabase = await createServerClient()
export async function createProject(projectData: ProjectInsert): Promise<Project> {
const supabase = await createServerClient();
const { data, error } = await supabase
.from('projects')
.insert(projectData)
.select()
.single()
const { data, error } = await supabase.from('projects').insert(projectData).select().single();
if (error) throw error
return data
if (error) throw error;
return data;
}
/**
* Update a project
*/
export async function updateProject(
projectId: string,
updates: ProjectUpdate
): Promise<Project> {
const supabase = await createServerClient()
export async function updateProject(projectId: string, updates: ProjectUpdate): Promise<Project> {
const supabase = await createServerClient();
const { data, error } = await supabase
.from('projects')
.update(updates)
.eq('id', projectId)
.select()
.single()
.single();
if (error) throw error
return data
if (error) throw error;
return data;
}
/**
* Delete a project
*/
export async function deleteProject(projectId: string): Promise<void> {
const supabase = await createServerClient()
const supabase = await createServerClient();
const { error } = await supabase
.from('projects')
.delete()
.eq('id', projectId)
const { error } = await supabase.from('projects').delete().eq('id', projectId);
if (error) throw error
if (error) throw error;
}
/**
@@ -334,17 +308,17 @@ export async function getProjectsByOwner(
ownerType: 'profile' | 'organization',
ownerId: string
): Promise<Project[]> {
const supabase = await createServerClient()
const supabase = await createServerClient();
const { data, error } = await supabase
.from('projects')
.select('*')
.eq('owner_type', ownerType)
.eq('owner_id', ownerId)
.order('created_at', { ascending: false })
.order('created_at', { ascending: false });
if (error) throw error
return data || []
if (error) throw error;
return data || [];
}
```
@@ -359,64 +333,52 @@ Create API endpoints following the existing pattern in `/src/app/api/`.
**File:** `/src/app/api/organizations/[id]/members/route.ts`
```typescript
import { NextRequest } from 'next/server'
import { createServerClient } from '@/services/supabase/server'
import { NextRequest } from 'next/server';
import { createServerClient } from '@/services/supabase/server';
import {
getOrganizationMembers,
addOrganizationMember,
canEditOrganization
} from '@/services/supabase/organization-members'
import { handleApiError, AuthError } from '@/lib/errors'
canEditOrganization,
} from '@/services/supabase/organization-members';
import { handleApiError, AuthError } from '@/lib/errors';
// GET /api/organizations/[id]/members - List organization members
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
try {
const members = await getOrganizationMembers(params.id)
return Response.json({ success: true, data: members })
const members = await getOrganizationMembers(params.id);
return Response.json({ success: true, data: members });
} catch (error) {
return handleApiError(error)
return handleApiError(error);
}
}
// POST /api/organizations/[id]/members - Add a member
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
try {
const supabase = await createServerClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
const supabase = await createServerClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
throw new AuthError()
throw new AuthError();
}
// Check permission to add members
const canEdit = await canEditOrganization(user.id, params.id)
const canEdit = await canEditOrganization(user.id, params.id);
if (!canEdit) {
return Response.json(
{ success: false, error: 'Insufficient permissions' },
{ status: 403 }
)
return Response.json({ success: false, error: 'Insufficient permissions' }, { status: 403 });
}
const body = await request.json()
const { profile_id, role, permissions } = body
const body = await request.json();
const { profile_id, role, permissions } = body;
const member = await addOrganizationMember(
params.id,
profile_id,
role,
user.id,
permissions
)
const member = await addOrganizationMember(params.id, profile_id, role, user.id, permissions);
return Response.json({ success: true, data: member })
return Response.json({ success: true, data: member });
} catch (error) {
return handleApiError(error)
return handleApiError(error);
}
}
```
@@ -426,57 +388,60 @@ export async function POST(
**File:** `/src/app/api/projects/route.ts`
```typescript
import { NextRequest } from 'next/server'
import { createServerClient } from '@/services/supabase/server'
import { getPublicProjects, createProject } from '@/services/supabase/projects'
import { handleApiError, AuthError } from '@/lib/errors'
import { NextRequest } from 'next/server';
import { createServerClient } from '@/services/supabase/server';
import { getPublicProjects, createProject } from '@/services/supabase/projects';
import { handleApiError, AuthError } from '@/lib/errors';
// GET /api/projects - List public projects
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
const { searchParams } = new URL(request.url);
const limit = parseInt(searchParams.get('limit') || '50');
const offset = parseInt(searchParams.get('offset') || '0');
const projects = await getPublicProjects(limit, offset)
return Response.json({ success: true, data: projects })
const projects = await getPublicProjects(limit, offset);
return Response.json({ success: true, data: projects });
} catch (error) {
return handleApiError(error)
return handleApiError(error);
}
}
// POST /api/projects - Create a project
export async function POST(request: NextRequest) {
try {
const supabase = await createServerClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
const supabase = await createServerClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
throw new AuthError()
throw new AuthError();
}
const body = await request.json()
const body = await request.json();
// If creating for organization, check permissions
if (body.owner_type === 'organization') {
const { canEditOrganization } = await import('@/services/supabase/organization-members')
const canCreate = await canEditOrganization(user.id, body.owner_id)
const { canEditOrganization } = await import('@/services/supabase/organization-members');
const canCreate = await canEditOrganization(user.id, body.owner_id);
if (!canCreate) {
return Response.json(
{ success: false, error: 'Insufficient permissions' },
{ status: 403 }
)
);
}
} else {
// For personal projects, ensure owner_id matches user
body.owner_id = user.id
body.owner_id = user.id;
}
const project = await createProject(body)
return Response.json({ success: true, data: project })
const project = await createProject(body);
return Response.json({ success: true, data: project });
} catch (error) {
return handleApiError(error)
return handleApiError(error);
}
}
```
@@ -667,6 +632,7 @@ export function CreateProjectForm() {
After implementation, test these scenarios:
### Organization Members
- [ ] Create an organization
- [ ] Add members with different roles (owner, admin, member)
- [ ] Set granular permissions for members
@@ -675,6 +641,7 @@ After implementation, test these scenarios:
- [ ] Verify RLS policies work (members can only see what they should)
### Projects
- [ ] Create a personal project
- [ ] Create an organization project
- [ ] Link projects to projects
@@ -683,6 +650,7 @@ After implementation, test these scenarios:
- [ ] Delete projects
### Permissions
- [ ] Organization owners can manage all settings
- [ ] Organization admins can manage members
- [ ] Regular members cannot edit organization
+14 -6
View File
@@ -11,12 +11,12 @@ This guide will help you configure GitHub, Google, and Twitter/X OAuth providers
---
## 📋 Step 1: Access Your Supabase Dashboard
## 📋 Step 1: Access Supabase Studio
1. **Navigate to**: https://supabase.com/dashboard
2. **Sign in** to your Supabase account
3. **Select your project** (the one for OrangeCat)
4. **Go to**: Settings → Authentication → Providers
(Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
1. **Open Studio** on the self-hosted instance
2. **Go to**: Settings → Authentication → Providers
You should see a screen like this:
@@ -29,16 +29,19 @@ You should see a screen like this:
In your Supabase dashboard, enable these providers:
### ✅ GitHub Provider
- **Toggle**: ON
- **Client ID**: `your-github-client-id` (you'll get this from GitHub)
- **Client Secret**: `your-github-client-secret` (you'll get this from GitHub)
### ✅ Google Provider
- **Toggle**: ON
- **Client ID**: `your-google-client-id` (you'll get this from Google)
- **Client Secret**: `your-google-client-secret` (you'll get this from Google)
### ✅ Twitter/X Provider
- **Toggle**: ON
- **Client ID**: `your-twitter-client-id` (you'll get this from Twitter/X)
- **Client Secret**: `your-twitter-client-secret` (you'll get this from Twitter/X)
@@ -152,16 +155,21 @@ npm run dev
## 🎯 Troubleshooting
### ❌ "Provider is not enabled" Error
**Solution**: Go back to Supabase Dashboard → Authentication → Providers and ensure all three providers are enabled.
### ❌ "Invalid redirect URL" Error
**Solution**: Make sure the redirect URL in Supabase matches exactly: `https://www.orangecat.ch/auth/callback`
### ❌ "Invalid client credentials" Error
**Solution**: Double-check that the Client ID and Secret in `.env.local` match exactly what you copied from each OAuth provider.
### ❌ Social login buttons not showing
**Solution**:
1. Check browser console for errors
2. Verify all OAuth providers are enabled in Supabase
3. Check that `.env.local` has valid credentials
@@ -175,7 +183,7 @@ Your `.env.local` should look like this (with real values):
```bash
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
# OAuth Provider Configuration
+111
View File
@@ -0,0 +1,111 @@
# Decommission the Managed Supabase Cloud Project
**Goal:** retire the managed Supabase Cloud project and make the self-hosted
Supabase on Hetzner (`https://supabase.orangecat.ch`) the only database.
**Status of the repo side (done in code, 2026-06-15):**
- `.env.local` repointed to `supabase.orangecat.ch` (cloud + Vercel/Turbo cruft dropped; backup in `.env-backups/`)
- `next.config.js` image host = self-host only (cloud host removed)
- `.claude/CLAUDE.md` + `.claude/rules/domain-specific.md` rewritten: self-host is SSOT, **do not use the Supabase MCP** (it only reaches the managed cloud)
- Active docs under `docs/` updated; `docs/archive/**` left as history
**What remains is the founder's to run** (this agent has no SSH to the box and
cannot reach `supabase.orangecat.ch`; it can only reach the managed cloud, so it
must NOT be the one to delete it).
---
## Managed project being retired
| Field | Value |
| ----------- | ---------------------------------- |
| Project ref | `ohkueislstxomdjavyhs` |
| Host | `ohkueislstxomdjavyhs.supabase.co` |
| Org | `conkscndiljdvkhvwbpo` |
---
## Step 1 — Confirm the self-host is authoritative (DO NOT SKIP)
Do **not** pause or delete the cloud until parity is proven. Run the same query
on **both** the cloud and the self-host and compare.
```sql
-- Run on cloud (Supabase SQL editor for ohkueislstxomdjavyhs)
-- AND on self-host: psql "$POSTGRES_URL" on the Hetzner box.
select 'profiles' t, count(*) from profiles
union all select 'notifications', count(*) from notifications
union all select 'transactions', count(*) from transactions
union all select 'actors', count(*) from actors;
-- Auth users
select count(*) from auth.users;
-- Freshness: latest activity should be on the SELF-HOST, not the cloud
select max(created_at) from notifications;
select max(created_at) from profiles;
```
✅ Proceed only if the self-host counts are **>=** cloud and its `max(created_at)`
is **newer**. If the cloud is still fresher, production traffic is still hitting
the cloud — stop and fix the cutover first.
## Step 2 — Take a final cloud backup (safety net)
```bash
# From any machine with the cloud DB connection string:
pg_dump "postgresql://postgres:<pw>@db.ohkueislstxomdjavyhs.supabase.co:5432/postgres" \
--no-owner --format=custom -f cloud-final-$(date +%Y%m%d).dump
# Store off-box (e.g. encrypted in the founder's backup location). Keep >= 90 days.
```
Also export Storage buckets and any Auth settings/SMTP/OAuth provider config you
still need, since those don't come through `pg_dump`.
## Step 3 — Confirm no app points at the cloud anymore
```bash
# On the Hetzner box, the running app env must show the self-host:
grep SUPABASE_URL /path/to/orangecat/.env* # -> supabase.orangecat.ch
# Optional: watch the cloud project's API logs for ~24–48h; traffic should be ~0.
```
## Step 4 — Pause first (reversible), observe, then delete
1. **Pause** the project in the Supabase dashboard
(`Settings → General → Pause project`). Pausing is reversible.
2. Watch the app for 24–48h. If anything breaks, it was still depending on the
cloud — resume and re-do Step 1/3.
3. When confident, **delete** the project
(`Settings → General → Delete project`).
## Step 5 — Revoke cloud-only credentials
These only mattered for the managed cloud and must be rotated/revoked:
- **`SUPABASE_ACCESS_TOKEN`** (Management API / MCP token) — revoke at
`supabase.com/dashboard/account/tokens`. It was dropped from `.env.local`
during cutover; ensure it's gone from any CI/secrets store too.
- The cloud `anon` / `service_role` keys die with the project, but scrub them
from any password manager / CI that referenced the cloud explicitly.
- Remove the managed project from the Supabase **MCP** configuration so no agent
accidentally reaches it again.
## Step 6 — Final repo sweep (optional tidy)
Historical references intentionally remain under `docs/archive/**` and inside the
banner-marked `docs/workflows/*MIGRATION*` tutorials. If you want them gone too:
```bash
grep -rIn 'ohkueislstxomdjavyhs' . | grep -v node_modules | grep -v '/.next/'
```
---
## Rollback
Until Step 4's delete, rollback is: resume the cloud project, then
`cp .env-backups/.env.local.pre-selfhost-cutover.* .env.local` (and revert
`next.config.js`). After deletion, rollback means restoring the Step 2 dump into
a new project — so do not delete until Step 4's observation window is clean.
+11 -11
View File
@@ -1,24 +1,24 @@
# Remote-Only Supabase Policy
# Self-Hosted Supabase (Hetzner) — SSOT
OrangeCat uses Supabase Cloud only. Do not run local Supabase/Postgres.
The single source of truth for OrangeCat's database is the **self-hosted Supabase at `https://supabase.orangecat.ch`**, running on the Hetzner box. Do not run a separate local Supabase/Postgres against app code.
- No `supabase start`, `supabase db start`, or Docker services.
- Manage schema with remote migrations or Studio SQL only.
- CLI is allowed for remote ops: `supabase link`, `supabase db push`, `supabase db dump`.
> ⚠️ **Managed Supabase Cloud retired 2026-06.** The managed-cloud guidance below (`supabase link --project-ref`, `db push`/`db dump` against the cloud project) is RETIRED. Schema work now happens against the self-hosted instance via SQL migrations + `psql` (access via the box / founder). Kept for reference.
Recommended remote-first workflow:
- No `supabase start`, `supabase db start`, or Docker services for app development.
- Manage schema with migrations + `psql` against the self-hosted instance, or Studio SQL on the box.
1) Link once
Retired managed-cloud workflow (historical):
1. Link once
SUPABASE_ACCESS_TOKEN=… supabase link --project-ref <ref> --workdir supabase
2) Create a migration (remote-intended)
2. Create a migration (remote-intended)
supabase migration new <name> --workdir supabase
3) Apply to remote
3. Apply to remote
SUPABASE_ACCESS_TOKEN=… supabase db push --workdir supabase --include-all
4) Verify
4. Verify
SUPABASE_ACCESS_TOKEN=… supabase db dump --schema public --workdir supabase -f /tmp/public.sql
If CLI refuses due to history mismatches, prefer running SQL once in Studio, then align migrations in Git.
+61 -15
View File
@@ -25,6 +25,7 @@ Created a **professional, navigable documentation structure**:
```
**What this gives you:**
- ✅ **Onboarding**: New developers can understand the system quickly
- ✅ **Decision making**: Architecture documented for informed choices
- ✅ **Troubleshooting**: Clear reference for debugging
@@ -36,6 +37,7 @@ Created a **professional, navigable documentation structure**:
### 🔧 2. Two Production-Ready Migrations
#### Migration #1: Performance Optimization
**File:** `supabase/migrations/20251017000001_add_transactions_status_index.sql`
```sql
@@ -43,6 +45,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
```
**Impact:**
- 🚀 **10x faster** transaction queries (500ms → 50ms)
- 📊 Improved dashboard performance
- 💳 Faster payment processing
@@ -53,9 +56,11 @@ CREATE INDEX idx_transactions_status ON transactions(status);
---
#### Migration #2: Security & Compliance
**File:** `supabase/migrations/20251017000002_create_audit_logs.sql`
**Creates:**
- 📋 `audit_logs` table with complete audit trail
- 🔧 `create_audit_log()` helper function
- ⚡ 6 strategic indexes for efficient querying
@@ -63,6 +68,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
- 📝 Example trigger for automatic profile logging
**Impact:**
- 🔐 **Security**: Track all critical operations
- 📜 **Compliance**: Meet financial regulations
- 🐛 **Debugging**: Trace complex issues
@@ -77,6 +83,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
**You learned:**
#### Database Design Principles
- ✅ How to evaluate database architecture
- ✅ Trade-offs: normalization vs performance
- ✅ When to use indexes (and when not to)
@@ -84,6 +91,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
- ✅ Polymorphic associations pattern
#### PostgreSQL Best Practices
- ✅ Idempotent migrations (`IF NOT EXISTS`)
- ✅ Transaction wrapping (`BEGIN`/`COMMIT`)
- ✅ Index types and strategies
@@ -92,6 +100,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
- ✅ SECURITY DEFINER for controlled privileges
#### Production Deployment
- ✅ Multiple deployment methods (Dashboard, Functions, CLI)
- ✅ Verification before and after
- ✅ Rollback procedures
@@ -99,6 +108,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
- ✅ Dealing with real-world connection issues
#### Professional Practices
- ✅ Documentation-first approach
- ✅ Test → Document → Deploy → Verify
- ✅ Always have a rollback plan
@@ -110,6 +120,7 @@ CREATE INDEX idx_transactions_status ON transactions(status);
## 📊 Database Quality: Before & After
### Before Today
```
Database:
✅ Functional - Basic operations work
@@ -123,6 +134,7 @@ Rating: ~7.5/10 (Good but needs work)
```
### After Today
```
Database:
✅ Functional - All operations work
@@ -143,6 +155,7 @@ Rating: 8.7/10 (Production-ready, with clear optimization path)
### Immediate Actions (You)
#### Step 1: Review the Documentation (10 minutes)
```bash
# Start here
cat docs/architecture/database/QUICK_REFERENCE.md
@@ -156,11 +169,13 @@ cat docs/architecture/database/IMPROVEMENTS_SUMMARY.md
---
#### Step 2: Apply Migration #1 - Index (2 minutes)
**This is a safe, high-impact change!**
1. Go to: [Supabase SQL Editor](https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new)
1. Run in the SQL editor. (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
2. Paste this:
```sql
BEGIN;
@@ -185,6 +200,7 @@ cat docs/architecture/database/IMPROVEMENTS_SUMMARY.md
---
#### Step 3: Test the Index (2 minutes)
```sql
-- Test query uses the new index
EXPLAIN ANALYZE
@@ -198,11 +214,13 @@ LIMIT 10;
---
#### Step 4: Apply Migration #2 - Audit Logs (5 minutes)
**This adds comprehensive audit logging!**
1. Go to: [Supabase SQL Editor](https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new)
1. Run in the SQL editor (self-hosted — see note above).
2. Copy entire content of:
```bash
supabase/migrations/20251017000002_create_audit_logs.sql
```
@@ -216,6 +234,7 @@ LIMIT 10;
---
#### Step 5: Test Audit Logging (2 minutes)
```sql
-- Make a change to your profile
UPDATE profiles
@@ -256,6 +275,7 @@ LIMIT 5;
See: `docs/architecture/database/improvements-roadmap.md`
**Priorities:**
1. Table partitioning for transactions (handle growth)
2. Archival strategy for old data (reduce costs)
3. Materialized views for analytics (faster dashboards)
@@ -264,15 +284,15 @@ See: `docs/architecture/database/improvements-roadmap.md`
## 📚 Documentation Files Created
| File | Purpose | Lines |
|------|---------|-------|
| **README.md** | Navigation hub | 200+ |
| **QUICK_REFERENCE.md** | Commands & links | 400+ |
| **IMPROVEMENTS_SUMMARY.md** | What we built | 600+ |
| **DEPLOYMENT_GUIDE.md** | How to deploy | 700+ |
| **schema-overview.md** | Architecture | 800+ |
| **analysis-rating.md** | 8.7/10 analysis | 465 |
| **improvements-roadmap.md** | Future plans | 600+ |
| File | Purpose | Lines |
| --------------------------- | ---------------- | ----- |
| **README.md** | Navigation hub | 200+ |
| **QUICK_REFERENCE.md** | Commands & links | 400+ |
| **IMPROVEMENTS_SUMMARY.md** | What we built | 600+ |
| **DEPLOYMENT_GUIDE.md** | How to deploy | 700+ |
| **schema-overview.md** | Architecture | 800+ |
| **analysis-rating.md** | 8.7/10 analysis | 465 |
| **improvements-roadmap.md** | Future plans | 600+ |
**Total:** ~3,800 lines of professional documentation! 📖
@@ -280,10 +300,10 @@ See: `docs/architecture/database/improvements-roadmap.md`
## 🗂️ Migration Files Created
| File | Purpose | Risk | Time |
|------|---------|------|------|
| **20251017000001_add_transactions_status_index.sql** | Performance | Low | 2 min |
| **20251017000002_create_audit_logs.sql** | Compliance | Low | 5 min |
| File | Purpose | Risk | Time |
| ---------------------------------------------------- | ----------- | ---- | ----- |
| **20251017000001_add_transactions_status_index.sql** | Performance | Low | 2 min |
| **20251017000002_create_audit_logs.sql** | Compliance | Low | 5 min |
**Total deployment time:** 7 minutes
**Downtime:** None
@@ -294,6 +314,7 @@ See: `docs/architecture/database/improvements-roadmap.md`
## 🎯 Success Metrics
### Documentation
- ✅ All tables documented
- ✅ All design patterns explained
- ✅ Clear navigation structure
@@ -301,6 +322,7 @@ See: `docs/architecture/database/improvements-roadmap.md`
- ✅ Troubleshooting guides
### Database Improvements
- ✅ Critical performance index (ready)
- ✅ Audit logging system (ready)
- ✅ Verification scripts (ready)
@@ -308,6 +330,7 @@ See: `docs/architecture/database/improvements-roadmap.md`
- ✅ Monitoring queries (provided)
### Knowledge Transfer
- ✅ PostgreSQL best practices
- ✅ Production deployment
- ✅ Real-world debugging
@@ -319,15 +342,18 @@ See: `docs/architecture/database/improvements-roadmap.md`
## 💡 Key Takeaways
### 1. Documentation is Infrastructure
**Good documentation is as important as good code.**
Without it:
- ❌ New developers struggle
- ❌ Decisions are made blindly
- ❌ Knowledge is lost when people leave
- ❌ Same mistakes repeated
With it:
- ✅ Faster onboarding
- ✅ Better decisions
- ✅ Institutional knowledge preserved
@@ -336,6 +362,7 @@ With it:
---
### 2. Small Improvements Compound
**The index we created (2 minutes to apply) will save hours of compute time.**
- Every query that filters by status: 450ms saved
@@ -347,16 +374,19 @@ With it:
---
### 3. Production is Messy - Be Prepared
**We hit connection issues, auth problems, and environment mismatches.**
This is **normal**! The difference between junior and senior:
**Junior engineer:**
- Panics when first method fails
- Gives up after 2 attempts
- Doesn't document the issue
**Senior engineer:**
- Has 3 backup methods ready
- Documents the issue for next time
- Stays calm and methodical
@@ -367,9 +397,11 @@ This is **normal**! The difference between junior and senior:
---
### 4. Always Have a Rollback Plan
**Every change should be reversible.**
We documented:
- ✅ How to apply
- ✅ How to verify
- ✅ How to rollback
@@ -382,16 +414,19 @@ This is **professional engineering**. 🏗️
## 🚧 What We Didn't Do (And Why)
### Table Partitioning
**Why not:** Complex, requires testing, not urgent yet
**When:** Q1 2026, when transaction volume grows
**Documented:** In roadmap
### Materialized Views
**Why not:** Need to identify use cases first
**When:** Q2 2026, after analytics requirements clear
**Documented:** In roadmap
### Read Replicas
**Why not:** Current scale doesn't require it
**When:** When concurrent users > 10K
**Documented:** In roadmap
@@ -403,16 +438,19 @@ This is **professional engineering**. 🏗️
## 🎓 Learning Resources for Continuing
### PostgreSQL
- [Official Docs](https://www.postgresql.org/docs/) - The bible
- [Performance Tips](https://wiki.postgresql.org/wiki/Performance_Optimization)
- [Index Types](https://www.postgresql.org/docs/current/indexes-types.html)
### Supabase
- [Supabase Docs](https://supabase.com/docs)
- [RLS Guide](https://supabase.com/docs/guides/auth/row-level-security)
- [Migrations Guide](https://supabase.com/docs/guides/cli/local-development)
### Database Design
- "Designing Data-Intensive Applications" by Martin Kleppmann
- "The Art of PostgreSQL" by Dimitri Fontaine
- "High Performance PostgreSQL" by Grant McAlister
@@ -422,18 +460,21 @@ This is **professional engineering**. 🏗️
## 📞 When You Need Help
### Stuck on deployment?
1. Check: `docs/architecture/database/DEPLOYMENT_GUIDE.md`
2. Try: Different deployment method
3. Review: Error messages carefully
4. Ask: Specific questions with error logs
### Want to add more improvements?
1. Read: `docs/architecture/database/improvements-roadmap.md`
2. Test: On local/staging first
3. Document: Before implementing
4. Deploy: During low traffic
### Need to understand a design decision?
1. Check: `docs/architecture/database/schema-overview.md`
2. Review: `docs/architecture/database/analysis-rating.md`
3. Ask: Specific questions about trade-offs
@@ -443,11 +484,13 @@ This is **professional engineering**. 🏗️
## 🏆 Final Thoughts
**You started with:**
- A good database that needed documentation
- Some missing optimizations
- Unclear improvement path
**You now have:**
- Comprehensive, professional documentation
- Two production-ready improvements
- Clear roadmap for the future
@@ -464,6 +507,7 @@ That's the difference between following tutorials and becoming an engineer. 🎓
## 🎉 Ready to Deploy!
Your database improvements are:
- ✅ **Well-documented**
- ✅ **Tested and verified**
- ✅ **Safe to deploy**
@@ -473,6 +517,7 @@ Your database improvements are:
**Next step:** Apply the migrations!
**Timeline:**
- 📖 Review docs: 10 minutes
- 🚀 Apply Migration #1: 2 minutes
- ✅ Verify Migration #1: 2 minutes
@@ -488,6 +533,7 @@ Your database improvements are:
**Congratulations on completing this session!** 🎊
You've done the work of a **senior database engineer**:
- Analyzed the system
- Identified improvements
- Documented thoroughly
+30 -1
View File
@@ -21,11 +21,13 @@ During live profile editing testing, user reported:
### Fix #1: Storage Bucket RLS Policies ✅
**Problem:**
- Users couldn't upload avatars/banners
- Storage RLS policies were blocking authenticated uploads
- Error: "new row violates row-level security policy"
**Root Cause:**
- `src/app/api/upload/route.ts` uploads to 'profiles' bucket
- Missing or incorrect RLS policies on `storage.objects`
@@ -41,6 +43,7 @@ Created migration: `supabase/migrations/20251017000003_fix_storage_rls_policies.
```
**Impact:**
- ✅ Avatar uploads now work
- ✅ Banner uploads now work
- ✅ Users can only modify their own images (secure)
@@ -54,12 +57,14 @@ Created migration: `supabase/migrations/20251017000003_fix_storage_rls_policies.
**Problem:**
When uploading avatar and saving profile, users saw **3 toasts**:
1. "Avatar uploaded successfully!" (ModernProfileEditor.tsx:175)
2. "Profile saved successfully!" (ModernProfileEditor.tsx:196)
3. "Profile updated successfully!" (useUnifiedProfile.ts:90)
**Root Cause:**
Three separate success toasts in the call chain:
```
User uploads avatar
→ Toast #1: "Avatar uploaded"
@@ -69,11 +74,13 @@ User clicks Save
```
**Solution:**
- ✅ Removed toast from avatar upload (ModernProfileEditor.tsx:175)
- ✅ Removed toast from profile save (ModernProfileEditor.tsx:196)
- ✅ Kept only final toast in useUnifiedProfile.ts:90
**Impact:**
- ✅ Now shows only ONE toast: "Profile updated successfully!"
- ✅ Clean, professional UX
- ✅ No duplicate notifications
@@ -89,12 +96,14 @@ User feedback: "a lot of unnecessary animation all over the site. looks unprofes
**Analysis:**
Found **82 instances** of Tailwind animation classes across **51 files**:
- `animate-bounce` - Bouncing elements
- `animate-pulse` - Pulsing effects
- `animate-spin` - Spinning loaders
- `animate-ping` - Ping effects
**Custom animations in globals.css:**
1. `bounce-in` - Bouncy entrance (scale 0.3 → 1.05 → 0.9 → 1)
2. `slide-up` - Slide from bottom
3. `pulse-orange` - Orange pulsing effect
@@ -104,6 +113,7 @@ Found **82 instances** of Tailwind animation classes across **51 files**:
7. `ripple` - Ripple effect
**Recommendation:**
```css
/* PROFESSIONAL ANIMATION GUIDELINES */
@@ -136,12 +146,15 @@ Found **82 instances** of Tailwind animation classes across **51 files**:
## 📝 Files Modified
### Migrations Created:
1. `supabase/migrations/20251017000003_fix_storage_rls_policies.sql` - Storage RLS fix
### Code Files Modified:
1. `src/components/profile/ModernProfileEditor.tsx` - Removed duplicate toasts (2 places)
### Documentation Created:
1. `FIXES_SESSION_2025-10-17.md` - This file
---
@@ -152,9 +165,10 @@ Found **82 instances** of Tailwind animation classes across **51 files**:
**Method: Supabase Dashboard (Recommended)**
1. Go to [Supabase SQL Editor](https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new)
1. Run in the SQL editor. (Managed Supabase Cloud retired 2026-06 — DB is now self-hosted at supabase.orangecat.ch on the Hetzner box; access via the box / founder.)
2. Copy entire content of:
```bash
cat supabase/migrations/20251017000003_fix_storage_rls_policies.sql
```
@@ -162,6 +176,7 @@ Found **82 instances** of Tailwind animation classes across **51 files**:
3. Paste into SQL Editor and click **"RUN"**
4. Verify success:
```sql
SELECT * FROM storage.buckets WHERE id = 'profiles';
-- Should show: { id: 'profiles', public: true }
@@ -215,11 +230,13 @@ git push origin main
## ✅ Success Metrics
### Before Fixes:
- ❌ Avatar uploads fail with RLS error
- ❌ 3 duplicate toasts on save
- ❌ Bouncy, unprofessional animations
### After Fixes:
- ✅ Avatar uploads work perfectly
- ✅ 1 clean success notification
- ✅ Animation analysis complete (cleanup planned)
@@ -229,18 +246,21 @@ git push origin main
## 🎯 Next Steps (Future Session)
### High Priority:
1. **Animation Cleanup** - Remove bouncy animations, reduce durations
- Estimated time: 1-2 hours
- Files to modify: globals.css + 51 component files
- Impact: More professional, polished UX
### Medium Priority:
2. **Apply Database Migrations** (from previous session)
- Migration #1: transactions.status index
- Migration #2: audit_logs table
- See: `docs/architecture/database/DEPLOYMENT_GUIDE.md`
### Low Priority:
3. **Profile Completion Indicator** - "Your profile is 60% complete"
4. **Image Upload** - Direct upload instead of URLs
5. **Unsaved Changes Warning** - "You have unsaved changes"
@@ -250,17 +270,20 @@ git push origin main
## 📊 Session Summary
**Time Spent:**
- Investigation: 10 minutes
- Fix Implementation: 15 minutes
- Documentation: 5 minutes
- **Total: 30 minutes**
**Lines of Code Changed:**
- Migration: 60 lines (new file)
- ModernProfileEditor: 4 lines (comments)
- Documentation: 400+ lines (this file)
**User Impact:**
- 🎉 **Immediate:** Avatar uploads work, clean notifications
- 📈 **Future:** More professional animations
@@ -269,9 +292,11 @@ git push origin main
## 🎓 What We Learned
### 1. RLS Policy Debugging
**Problem:** "new row violates row-level security policy"
**Solution Process:**
1. Check error message (RLS violation)
2. Find upload code (`src/app/api/upload/route.ts`)
3. Identify bucket name (`'profiles'`)
@@ -283,9 +308,11 @@ git push origin main
---
### 2. Duplicate Notification Debugging
**Problem:** Multiple toasts for one action
**Solution Process:**
1. Search for `toast.success` in codebase
2. Find all 3 locations in call chain
3. Remove intermediate toasts
@@ -296,9 +323,11 @@ git push origin main
---
### 3. Animation Analysis
**Problem:** "looks unprofessional"
**Solution Process:**
1. Grep for animation classes
2. Check globals.css for custom animations
3. Identify bouncy/excessive effects
@@ -1,5 +1,7 @@
# Migration Lessons Learned - Post-Mortem Analysis
> ⚠️ **RETIRED — managed cloud only.** This post-mortem concerns the managed Supabase Cloud Management API / `PROJECT_REF` workflow, retired 2026-06. Schema work now happens against the self-hosted instance (`supabase.orangecat.ch`) via SQL migrations + `psql`. Kept for historical reference.
**Date:** November 14, 2025
**Task:** Apply timeline social features migration with dislikes system
**Result:** ✅ Success (after debugging)
@@ -1,5 +1,7 @@
# Supabase Migration Quick Reference
> ⚠️ **RETIRED — managed cloud only.** The `PROJECT_REF` + `api.supabase.com` Management API workflow below targeted the managed Supabase Cloud, retired 2026-06. Schema work now happens against the self-hosted instance (`supabase.orangecat.ch`) via SQL migrations + `psql`. Kept for historical reference.
**Use this for fast lookup. See SUPABASE_MIGRATION_WORKFLOW.md for detailed explanation.**
---
+2
View File
@@ -16,6 +16,8 @@ section used to describe was removed with the migration.)
### 2. Supabase Migration Workflow
> ⚠️ **RETIRED — managed cloud only.** The migration workflow docs in this section (`SUPABASE_MIGRATION_WORKFLOW.md`, `MIGRATION_QUICK_REFERENCE.md`, `MIGRATION_LESSONS_LEARNED.md`) and the `PROJECT_REF` / `api.supabase.com` scripts they describe targeted the managed Supabase Cloud, retired 2026-06. Schema work now happens against the self-hosted instance (`supabase.orangecat.ch`, Hetzner box) via SQL migrations + `psql`. Kept for historical reference.
**File:** `SUPABASE_MIGRATION_WORKFLOW.md`
**Use this when:** You need to apply database migrations to Supabase
@@ -1,5 +1,7 @@
# Supabase Migration Workflow - Successful CLI Application
> ⚠️ **RETIRED — managed cloud only.** This workflow targeted the managed Supabase Cloud project (`api.supabase.com` Management API + `PROJECT_REF`). The managed cloud was retired 2026-06; the DB is now self-hosted at `supabase.orangecat.ch` on the Hetzner box. Schema work now happens against the self-hosted instance via SQL migrations + `psql`. Kept for historical reference.
## 📋 Overview
This document captures the **successful methodology** for applying Supabase migrations via CLI without leaving the development environment. This workflow was developed after resolving multiple authentication and SQL syntax issues.
+2 -7
View File
@@ -53,13 +53,8 @@ const nextConfig = {
pathname: '/**',
},
{
protocol: 'https',
hostname: 'ohkueislstxomdjavyhs.supabase.co',
port: '',
pathname: '/storage/v1/object/public/**',
},
{
// Self-hosted Supabase storage (Hetzner migration 2026-06)
// Self-hosted Supabase storage on Hetzner — the SSOT.
// Managed-cloud host (ohkueislstxomdjavyhs.supabase.co) retired 2026-06.
protocol: 'https',
hostname: 'supabase.orangecat.ch',
port: '',
+1 -1
View File
@@ -75,7 +75,7 @@ try {
console.log('─'.repeat(60))
console.log('\n🎯 Instructions:')
console.log('1. Go to: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new')
console.log('1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired')
console.log('2. Paste the SQL above')
console.log('3. Click "Run"')
console.log('4. Verify: Index should appear in Database → Indexes')
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
echo "=== Applying messaging fixes via SQL ==="
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
# Test send_message function
echo "Testing send_message RPC function..."
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
echo "=== Checking conversations table ==="
curl -s "${BASE_URL}/rest/v1/conversations?select=*&limit=3" \
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
# Test get_total_unread_count function
echo "=== Testing get_total_unread_count RPC ==="
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
# Check realtime config via the Supabase REST API
echo "Checking realtime enablement for tables..."
+1 -1
View File
@@ -1,6 +1,6 @@
-- ============================================================================
-- FINAL FIX FOR AVATAR UPLOAD RLS
-- Run this in: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new
-- Run this via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired
-- ============================================================================
-- Set role to postgres (superuser) to have permission to modify storage.objects
+7 -6
View File
@@ -85,7 +85,7 @@ async function addContactEmailColumn() {
if (error.message.includes('contact_email') || error.message.includes('column')) {
console.log('❌ Column does not exist. Please apply the migration manually:\n');
console.log(
' 1. Go to: https://app.supabase.com/project/ohkueislstxomdjavyhs/sql/new'
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.log(' 2. Copy and paste this SQL:\n');
console.log(sql);
@@ -100,7 +100,9 @@ async function addContactEmailColumn() {
} catch (checkError) {
console.error('❌ Error checking column:', checkError.message);
console.log('\n💡 Please apply the migration manually via Supabase Dashboard:\n');
console.log(' 1. Go to: https://app.supabase.com/project/ohkueislstxomdjavyhs/sql/new');
console.log(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.log(' 2. Copy and paste this SQL:\n');
console.log(sql);
console.log('\n 3. Click "Run"\n');
@@ -126,7 +128,9 @@ async function addContactEmailColumn() {
console.error('❌ Fatal error:', err.message);
console.error(err.stack);
console.log('\n💡 Please apply the migration manually via Supabase Dashboard:\n');
console.log(' 1. Go to: https://app.supabase.com/project/ohkueislstxomdjavyhs/sql/new');
console.log(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.log(' 2. Copy and paste this SQL:\n');
console.log(sql);
console.log('\n 3. Click "Run"\n');
@@ -138,6 +142,3 @@ addContactEmailColumn().catch(err => {
console.error('❌ Unhandled error:', err);
process.exit(1);
});
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
API_URL="https://api.supabase.com/v1/projects/ohkueislstxomdjavyhs/database/query"
TOKEN="sbp_7bc7546939c5675c6146d5773f83f05b0131c614"
+3 -4
View File
@@ -117,7 +117,9 @@ async function applyMigration() {
console.log('\n✨ Migration process complete!\n');
console.log("💡 If the column still doesn't exist, apply the SQL manually:");
console.log(' 1. Go to: https://app.supabase.com/project/ohkueislstxomdjavyhs/sql/new');
console.log(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.log(
' 2. Copy the SQL from: supabase/migrations/20251124060022_add_contact_email.sql'
);
@@ -132,6 +134,3 @@ applyMigration().catch(err => {
console.error('❌ Unhandled error:', err);
process.exit(1);
});
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Apply conversation_participants RLS policies migration
* Reads SUPABASE_ACCESS_TOKEN from .env.local and applies the migration
@@ -39,7 +44,10 @@ console.log(`📍 Project: ${PROJECT_REF}`);
console.log(`🔑 Token: ${ACCESS_TOKEN.substring(0, 10)}...`);
// Read migration SQL
const migrationPath = path.join(__dirname, 'supabase/migrations/20250102000000_add_conversation_participants_policies.sql');
const migrationPath = path.join(
__dirname,
'supabase/migrations/20250102000000_add_conversation_participants_policies.sql'
);
const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
console.log('📄 Reading migration file...');
@@ -47,7 +55,7 @@ console.log(`📏 Migration size: ${migrationSQL.length} characters\n`);
// Apply via Supabase Management API
const postData = JSON.stringify({
query: migrationSQL
query: migrationSQL,
});
const options = {
@@ -58,17 +66,17 @@ const options = {
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'apikey': ACCESS_TOKEN
}
Authorization: `Bearer ${ACCESS_TOKEN}`,
apikey: ACCESS_TOKEN,
},
};
console.log('⚡ Applying migration...\n');
const req = https.request(options, (res) => {
const req = https.request(options, res => {
let data = '';
res.on('data', (chunk) => {
res.on('data', chunk => {
data += chunk;
});
@@ -99,12 +107,10 @@ const req = https.request(options, (res) => {
});
});
req.on('error', (error) => {
req.on('error', error => {
console.error('❌ Request error:', error);
process.exit(1);
});
req.write(postData);
req.end();
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
# Apply full timeline_events migration
# This creates the table, indexes, RLS policies, and functions
+5 -46
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Generic Supabase migration runner using Management API.
*
@@ -109,49 +114,3 @@ req.on('error', error => {
req.write(data);
req.end();
+2 -2
View File
@@ -7,9 +7,9 @@ echo "🔧 Applying Post Duplication Fix Migration"
echo "=========================================="
echo ""
# Apply migration using Supabase CLI
# Apply migration using Supabase CLI against the self-hosted DB (supabase.orangecat.ch) - managed cloud retired
echo "📝 Pushing migration to database..."
npx supabase db push --db-url "postgresql://postgres.ohkueislstxomdjavyhs:${SUPABASE_SERVICE_ROLE_KEY}@aws-0-us-west-1.pooler.supabase.com:6543/postgres"
npx supabase db push --db-url "${POSTGRES_URL:?POSTGRES_URL is required (self-hosted: supabase.orangecat.ch) - managed cloud retired}"
echo ""
echo "✨ Migration complete!"
+13 -154
View File
@@ -1,160 +1,19 @@
#!/usr/bin/env node
/**
* Apply Personal Economy Migration
* Apply Personal Economy Migration — RETIRED
*
* This script applies the personal economy tables migration to add:
* - user_products (My Store)
* - user_services (My Services)
* - user_causes (My Causes)
* - user_ai_assistants (My Cat)
* This script applied a migration through the managed Supabase Cloud workflow,
* which was removed 2026-06. The database is now self-hosted at
* supabase.orangecat.ch on the Hetzner box. Apply SQL directly instead:
* psql "$POSTGRES_URL" -f supabase/migrations/20251202_create_personal_economy_tables.sql
* See docs/operations/DECOMMISSION-CLOUD.md.
*/
import { createClient } from '@supabase/supabase-js';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import dotenv from 'dotenv';
dotenv.config({ path: '.env.local' });
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !supabaseServiceKey) {
console.error('❌ Error: Missing Supabase environment variables');
console.error(' Required: NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY');
console.error(' Make sure .env.local exists and contains these variables');
process.exit(1);
}
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
auth: {
autoRefreshToken: false,
persistSession: false,
},
});
async function applyMigration() {
try {
console.log('🚀 Applying Personal Economy migration...\n');
// Read the migration file
const migrationPath = join(
__dirname,
'../../supabase/migrations/20251202_create_personal_economy_tables.sql'
);
const migrationSQL = readFileSync(migrationPath, 'utf-8');
console.log('📄 Migration file loaded successfully');
console.log(`📏 File size: ${migrationSQL.length} characters\n`);
// Apply RLS policy fixes
console.log('🔧 Applying RLS policy fixes...\n');
const rlsFixes = `
-- Admin policies for service role operations
CREATE POLICY "Admin can manage all products"
ON user_products FOR ALL
USING (auth.jwt() ->> 'role' = 'service_role')
WITH CHECK (auth.jwt() ->> 'role' = 'service_role');
CREATE POLICY "Admin can manage all services"
ON user_services FOR ALL
USING (auth.jwt() ->> 'role' = 'service_role')
WITH CHECK (auth.jwt() ->> 'role' = 'service_role');
CREATE POLICY "Admin can manage all causes"
ON user_causes FOR ALL
USING (auth.jwt() ->> 'role' = 'service_role')
WITH CHECK (auth.jwt() ->> 'role' = 'service_role');
`;
try {
// Try to execute the RLS fixes using RPC if available
console.log('Attempting to apply RLS policy fixes...');
// Note: This would require creating an RPC function in Supabase
console.log('⚠️ RLS fixes need to be applied manually via Supabase Dashboard SQL Editor.');
console.log('📋 Copy and run this SQL:\n');
console.log(rlsFixes);
console.log('\n');
console.log('⚠️ Original migration still needs manual application.');
console.log('📋 To apply the full migration:\n');
console.log(' Option 1 - Via Supabase Dashboard:');
console.log(' 1. Go to: https://supabase.com/dashboard');
console.log(' 2. Select your project');
console.log(' 3. Go to SQL Editor');
console.log(' 4. Copy and paste the entire migration file:');
console.log(` ${migrationPath}`);
console.log(' 5. Click "Run"\n');
console.log(' Option 2 - Via Supabase CLI (if installed):');
console.log(' supabase db push\n');
// Test if we can connect to Supabase
console.log('🔍 Testing Supabase connection...');
const { data, error } = await supabase.from('profiles').select('count').limit(1).single();
if (error) {
console.error('❌ Supabase connection failed:', error.message);
console.log('\n💡 Make sure your Supabase project is running and credentials are correct.');
} else {
console.log('✅ Supabase connection successful!');
console.log('🎯 Ready to apply migration via dashboard.');
}
console.log('\n📝 Migration includes:');
console.log(' ✅ user_products table - Product catalog');
console.log(' ✅ user_services table - Service offerings');
console.log(' ✅ user_causes table - Charity campaigns');
console.log(' ✅ user_ai_assistants table - AI assistants');
console.log(' ✅ RLS policies for security');
console.log(' ✅ Performance indexes');
console.log(' ✅ Automatic timestamps');
} catch (error) {
console.error('❌ Error:', error.message);
process.exit(1);
}
}
applyMigration();
console.error(
'RETIRED: this script used the managed Supabase Cloud workflow (removed 2026-06). ' +
'The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: ' +
'psql "$POSTGRES_URL" -f supabase/migrations/20251202_create_personal_economy_tables.sql. ' +
'See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
+9 -3
View File
@@ -4,9 +4,15 @@ const { createClient } = require('@supabase/supabase-js');
const fs = require('fs');
const path = require('path');
const supabaseUrl = 'https://ohkueislstxomdjavyhs.supabase.co';
const supabaseServiceKey =
process.env.SUPABASE_SERVICE_ROLE_KEY;
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !supabaseServiceKey) {
console.error(
'Missing NEXT_PUBLIC_SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY (self-hosted: https://supabase.orangecat.ch) - managed cloud retired'
);
process.exit(1);
}
const supabase = createClient(supabaseUrl, supabaseServiceKey);
@@ -1,10 +1,14 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Apply Production Readiness Migrations via Supabase Management API
*
*
* Uses Supabase Management API to apply migrations.
* Requires SUPABASE_ACCESS_TOKEN in .env.local
*
*
* Usage: node scripts/db/apply-production-migrations-via-api.js
*/
@@ -64,7 +68,7 @@ const migrations = [
function applyMigration(migration) {
return new Promise((resolve, reject) => {
const filePath = path.join(process.cwd(), migration.file);
if (!fs.existsSync(filePath)) {
reject(new Error(`Migration file not found: ${filePath}`));
return;
@@ -72,7 +76,7 @@ function applyMigration(migration) {
console.log(`\n📄 ${migration.name}`);
console.log(` File: ${migration.file}`);
const sql = fs.readFileSync(filePath, 'utf-8');
console.log(` Size: ${sql.length} characters`);
@@ -128,7 +132,7 @@ async function main() {
for (let i = 0; i < migrations.length; i++) {
const migration = migrations[i];
await applyMigration(migration);
// Small delay between migrations
if (i < migrations.length - 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
@@ -141,7 +145,6 @@ async function main() {
console.log('2. Test group creation/editing');
console.log('3. Test entity ownership with actors');
console.log('4. Run: npm run build (check for TypeScript errors)');
} catch (error) {
console.error('\n❌ Migration failed:');
console.error(error.message);
@@ -150,5 +153,3 @@ async function main() {
}
main();
+4 -2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API (linked-project "supabase db push" + SUPABASE_ACCESS_TOKEN), which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
# Apply RLS Fix Migration via Supabase CLI
#
# This script applies the RLS fix migration using the Supabase CLI.
@@ -21,7 +23,7 @@ if [ -z "$SUPABASE_ACCESS_TOKEN" ]; then
echo " 4. Then run this script again"
echo ""
echo "📋 Or apply manually via Supabase Studio:"
echo " 1. Go to: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new"
echo " 1. apply via psql \"\$POSTGRES_URL\" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired"
echo " 2. Copy contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql"
echo " 3. Paste and execute"
exit 1
@@ -41,7 +43,7 @@ else
echo "❌ Migration failed"
echo ""
echo "📋 Please apply manually via Supabase Studio:"
echo " 1. Go to: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new"
echo " 1. apply via psql \"\$POSTGRES_URL\" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired"
echo " 2. Copy contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql"
echo " 3. Paste and execute"
exit 1
+22 -13
View File
@@ -1,7 +1,11 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Apply RLS Fix via Supabase Management API
*
*
* Uses the Supabase Management API to execute the migration SQL directly.
*/
@@ -29,32 +33,35 @@ const managementApiUrl = `https://api.supabase.com/v1/projects/${projectRef}/dat
async function applyMigration() {
console.log('🚀 Applying RLS fix migration via Management API...\n');
try {
const migrationPath = join(__dirname, '../../supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql');
const migrationPath = join(
__dirname,
'../../supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql'
);
const migrationSQL = readFileSync(migrationPath, 'utf-8');
console.log('📤 Sending migration to Supabase Management API...');
const response = await fetch(managementApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
query: migrationSQL,
}),
});
const responseText = await response.text();
if (response.ok) {
console.log('✅ Migration applied successfully!');
console.log('🔄 Please refresh your browser to test groups functionality.');
return;
}
// Try parsing as JSON for error details
let errorDetails;
try {
@@ -62,16 +69,18 @@ async function applyMigration() {
} catch {
errorDetails = { message: responseText };
}
console.error('❌ Migration failed');
console.error(` Status: ${response.status}`);
console.error(` Error: ${JSON.stringify(errorDetails, null, 2)}`);
console.log('\n📋 Please apply manually via Supabase Studio:');
console.log(' 1. Go to: https://supabase.com/dashboard/project/' + projectRef + '/sql/new');
console.log(' 2. Copy contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql');
console.log(
' 2. Copy contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql'
);
console.log(' 3. Paste and execute');
process.exit(1);
} catch (error) {
console.error('❌ Failed to apply migration:', error.message);
+37 -26
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env node
/**
* Apply RLS Fix Migration
*
*
* Applies the group_members RLS recursion fix migration directly to the database.
*
*
* Usage: node scripts/db/apply-rls-fix.js
*/
@@ -55,25 +55,28 @@ async function executeSQL(sql, description) {
async function applyMigration() {
console.log('🚀 Applying RLS fix migration...\n');
try {
const migrationPath = join(__dirname, '../../supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql');
const migrationPath = join(
__dirname,
'../../supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql'
);
const migrationSQL = readFileSync(migrationPath, 'utf-8');
// Split into statements (handling multi-line statements with $$)
const statements = [];
let currentStatement = '';
let inDollarQuote = false;
let dollarTag = '';
const lines = migrationSQL.split('\n');
for (const line of lines) {
const trimmed = line.trim();
// Skip comments
if (trimmed.startsWith('--')) continue;
// Handle dollar-quoted strings (for function definitions)
if (trimmed.includes('$$')) {
const dollarMatches = trimmed.match(/\$\$([^$]*)\$\$/g);
@@ -86,7 +89,7 @@ async function applyMigration() {
}
continue;
}
// Start or end of dollar quote
const dollarTagMatch = trimmed.match(/\$\$([^$]*)?/);
if (dollarTagMatch) {
@@ -99,9 +102,9 @@ async function applyMigration() {
}
}
}
currentStatement += line + '\n';
// If we're not in a dollar quote and see a semicolon, it's the end of a statement
if (!inDollarQuote && trimmed.endsWith(';')) {
const stmt = currentStatement.trim();
@@ -111,53 +114,61 @@ async function applyMigration() {
currentStatement = '';
}
}
// Add any remaining statement
if (currentStatement.trim()) {
statements.push(currentStatement.trim());
}
console.log(`📊 Found ${statements.length} SQL statements to execute\n`);
let successCount = 0;
let failCount = 0;
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (!statement || statement.length < 10) continue;
const description = statement.substring(0, 60).replace(/\n/g, ' ') + '...';
const success = await executeSQL(statement, `[${i + 1}/${statements.length}] ${description}`);
if (success) {
successCount++;
} else {
failCount++;
// Don't stop on first error - some statements might fail safely
if (statement.includes('DROP POLICY IF EXISTS') || statement.includes('CREATE OR REPLACE')) {
if (
statement.includes('DROP POLICY IF EXISTS') ||
statement.includes('CREATE OR REPLACE')
) {
console.log(' ⚠️ Continuing despite error (expected for idempotent operations)');
}
}
// Small delay between statements
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log(`\n📊 Results: ${successCount} success, ${failCount} failed`);
if (failCount === 0) {
console.log('\n✅ Migration applied successfully!');
console.log('🔄 Please refresh the browser to test groups functionality.');
} else {
console.log('\n⚠️ Some statements failed. Please check the errors above.');
console.log('💡 You may need to apply this migration manually via Supabase Studio SQL editor.');
console.log(
'💡 You may need to apply this migration manually via Supabase Studio SQL editor.'
);
}
} catch (error) {
console.error('❌ Failed to apply migration:', error);
console.error('\n📋 Please apply this migration manually via Supabase Studio:');
console.error(' 1. Go to https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new');
console.error(' 2. Copy the contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql');
console.error(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.error(
' 2. Copy the contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql'
);
console.error(' 3. Paste and execute');
process.exit(1);
}
+26 -26
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env tsx
/**
* Apply RLS Fix Migration
*
*
* Applies the group_members RLS recursion fix migration directly to the database.
*
*
* Usage: npx tsx scripts/db/apply-rls-fix.ts
*/
@@ -18,16 +18,16 @@ const migrationSQL = readFileSync(
async function applyMigration() {
console.log('🔧 Applying RLS fix migration...');
const admin = createAdminClient();
try {
// Split SQL into individual statements and execute
const statements = migrationSQL
.split(';')
.map(s => s.trim())
.filter(s => s.length > 0 && !s.startsWith('--'));
for (const statement of statements) {
if (statement.length > 0) {
// TODO: Fix RPC call - exec_sql function may not exist
@@ -47,11 +47,11 @@ async function applyMigration() {
// }
}
}
// Actually, let's use the Supabase REST API to execute raw SQL
// We'll need to use the admin client's connection
console.log('📝 Executing migration SQL...');
// TODO: Fix RPC call - exec_sql function may not exist
// Execute the full migration as a single transaction
// const { error } = await admin.rpc('exec_sql', {
@@ -59,40 +59,40 @@ async function applyMigration() {
// });
console.log('⚠️ Migration execution disabled - use MCP Supabase tools instead');
const error = null;
if (error) {
// Fallback: execute statement by statement
console.log('⚠️ RPC failed, trying statement-by-statement...');
// Use a different approach - execute via REST API
const response = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/rest/v1/rpc/exec_sql`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': process.env.SUPABASE_SERVICE_ROLE_KEY || '',
'Authorization': `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY || ''}`,
},
body: JSON.stringify({ sql: migrationSQL }),
}
);
const response = await fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}/rest/v1/rpc/exec_sql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
apikey: process.env.SUPABASE_SERVICE_ROLE_KEY || '',
Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY || ''}`,
},
body: JSON.stringify({ sql: migrationSQL }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Migration failed: ${errorText}`);
}
console.log('✅ Migration applied successfully!');
} else {
console.log('✅ Migration applied successfully!');
}
} catch (error) {
console.error('❌ Failed to apply migration:', error);
console.error('\n📋 Please apply this migration manually via Supabase Studio:');
console.error(' 1. Go to https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new');
console.error(' 2. Copy the contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql');
console.error(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.error(
' 2. Copy the contents of: supabase/migrations/20250130000007_fix_group_members_rls_recursion.sql'
);
console.error(' 3. Paste and execute');
process.exit(1);
}
+9 -3
View File
@@ -4,9 +4,15 @@ const { createClient } = require('@supabase/supabase-js');
const fs = require('fs');
const path = require('path');
const supabaseUrl = 'https://ohkueislstxomdjavyhs.supabase.co';
const supabaseServiceKey =
process.env.SUPABASE_SERVICE_ROLE_KEY;
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !supabaseServiceKey) {
console.error(
'Missing NEXT_PUBLIC_SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY (self-hosted: https://supabase.orangecat.ch) - managed cloud retired'
);
process.exit(1);
}
const supabase = createClient(supabaseUrl, supabaseServiceKey);
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Apply Timeline Social Features Migration
*
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
# Apply create_timeline_event function migration
# This creates the database function needed for posting
+3 -1
View File
@@ -63,7 +63,9 @@ async function applyMigration() {
// For now, let's try using rpc if there's an exec_sql function, or guide user
console.log('⚠️ Direct SQL execution via JS client is limited.');
console.log('📋 Please apply this migration manually:\n');
console.log(' 1. Go to: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new');
console.log(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.log(' 2. Copy and paste the contents of:');
console.log(` ${migrationPath}`);
console.log(' 3. Click "Run"\n');
+21 -15
View File
@@ -3,9 +3,16 @@ import { createClient } from '@supabase/supabase-js';
import { readFileSync } from 'fs';
// Use service role key to bypass RLS
const supabaseUrl = 'https://ohkueislstxomdjavyhs.supabase.co';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SERVICE_KEY;
if (!supabaseUrl) {
console.log(
'❌ Missing NEXT_PUBLIC_SUPABASE_URL (self-hosted: https://supabase.orangecat.ch) - managed cloud retired'
);
process.exit(1);
}
if (!serviceRoleKey) {
console.log('❌ No service role key found in environment');
console.log('💡 Please set SUPABASE_SERVICE_ROLE_KEY or SUPABASE_SERVICE_KEY');
@@ -13,36 +20,36 @@ if (!serviceRoleKey) {
}
const supabase = createClient(supabaseUrl, serviceRoleKey, {
auth: { persistSession: false }
auth: { persistSession: false },
});
async function applyRLSFixes() {
console.log('🔧 Applying RLS fixes with service role...');
try {
// Read the SQL file
const sqlContent = readFileSync('final_rls_fix.sql', 'utf-8');
// Split into individual statements
const statements = sqlContent
.split(';')
.map(s => s.trim())
.filter(s => s.length > 0 && !s.startsWith('--'));
console.log(`📊 Found ${statements.length} statements to execute`);
let successCount = 0;
let failCount = 0;
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement) {
console.log(`🔄 Executing ${i + 1}/${statements.length}: ${statement.substring(0, 50)}...`);
try {
// Execute raw SQL
const { error } = await supabase.from('_supabase_policies').select('*').limit(0);
if (error) {
console.log(`⚠️ Error: ${error.message}`);
failCount++;
@@ -56,9 +63,9 @@ async function applyRLSFixes() {
}
}
}
console.log(`\n📊 Results: ${successCount} success, ${failCount} failed`);
// Test service creation
console.log('\n🧪 Testing service creation...');
const testService = {
@@ -67,22 +74,21 @@ async function applyRLSFixes() {
category: 'Other',
fixed_price_sats: 50000,
currency: 'SATS',
status: 'draft'
status: 'draft',
};
const { data, error } = await supabase
.from('user_services')
.insert(testService)
.select()
.single();
if (error) {
console.log('❌ Service creation still failing:', error.message);
} else {
console.log('✅ Service creation successful!');
console.log(' Service:', data.title, '(ID:', data.id, ')');
}
} catch (error) {
console.error('❌ Unexpected error:', error.message);
}
+4 -5
View File
@@ -60,8 +60,10 @@ async function checkAndAddColumn() {
const errorText = await response.text();
console.error('❌ Failed to execute SQL via REST API');
console.error(` Error: ${errorText}`);
console.log('\n💡 Please apply this SQL manually via Supabase Dashboard:');
console.log(' https://app.supabase.com/project/ohkueislstxomdjavyhs/sql/new\n');
console.log('\n💡 Please apply this SQL manually:');
console.log(
' apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired\n'
);
console.log('SQL to execute:');
console.log(sql);
process.exit(1);
@@ -101,6 +103,3 @@ checkAndAddColumn().catch(err => {
console.error('❌ Unhandled error:', err);
process.exit(1);
});
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
API_URL="https://api.supabase.com/v1/projects/ohkueislstxomdjavyhs/database/query"
TOKEN="sbp_7bc7546939c5675c6146d5773f83f05b0131c614"
+3 -4
View File
@@ -46,7 +46,9 @@ async function createTables() {
console.log('📋 For security, Supabase requires manual application via Dashboard');
console.log('');
console.log('🔗 Please apply the migration manually:');
console.log(' 1. Go to: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql/new');
console.log(
' 1. apply via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired'
);
console.log(
' 2. Copy the entire SQL from: supabase/migrations/20251202_create_personal_economy_tables.sql'
);
@@ -88,6 +90,3 @@ async function createTables() {
}
createTables();
+5
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Database Diagnostic Script
* Checks the current state of timeline-related database objects
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
API_URL="https://api.supabase.com/v1/projects/ohkueislstxomdjavyhs/database/query"
TOKEN="sbp_7bc7546939c5675c6146d5773f83f05b0131c614"
+1 -1
View File
@@ -1,6 +1,6 @@
-- ============================================================================
-- FIX AVATAR UPLOAD RLS POLICY
-- Run this in your Supabase SQL Editor: https://supabase.com/dashboard/project/ohkueislstxomdjavyhs/sql
-- Run this via psql "$POSTGRES_URL" on the self-hosted DB (supabase.orangecat.ch) - managed cloud retired
-- ============================================================================
-- Enable RLS on storage.objects if not already enabled
+5
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Fix Profile Bootstrap
* Creates a profile record for the authenticated user if missing
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
# Run location field sync migration
API_URL="https://api.supabase.com/v1/projects/ohkueislstxomdjavyhs/database/query"
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
echo "========================================="
echo "Location Field Fix - Verification Script"
+3
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env python3
import sys
print('RETIRED: this script scraped the managed Supabase Cloud dashboard for API keys, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch); read keys from .env.local / the self-hosted Studio. See docs/operations/DECOMMISSION-CLOUD.md.', file=sys.stderr)
sys.exit(1)
"""
Supabase API Key Extraction Script
+13 -8
View File
@@ -1,4 +1,8 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script scraped the managed Supabase Cloud dashboard for API keys, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch); read keys from .env.local / the self-hosted Studio. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Automated Supabase API Key Retrieval Script
@@ -50,7 +54,7 @@ const SELECTORS = {
loginForm: 'form[action*="login"]',
emailInput: 'input[type="email"]',
passwordInput: 'input[type="password"]',
signInButton: 'button[type="submit"], button:has-text("Sign in")'
signInButton: 'button[type="submit"], button:has-text("Sign in")',
};
async function delay(ms) {
@@ -72,7 +76,7 @@ async function extractApiKey(page) {
'[data-testid*="anon"]',
'[data-testid*="api-key"]',
'.anon-key',
'.api-key'
'.api-key',
];
for (const selector of selectors) {
@@ -152,7 +156,7 @@ async function extractApiKey(page) {
return matches.sort((a, b) => b.length - a.length)[0];
}
return null;
}
},
];
// Try each strategy
@@ -219,14 +223,16 @@ async function main() {
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu'
]
'--disable-gpu',
],
});
const page = await browser.newPage();
// Set user agent
await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
await page.setUserAgent(
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
);
console.log('🌐 Navigating to Supabase dashboard...');
await page.goto(DASHBOARD_URL, { waitUntil: 'networkidle2', timeout: 30000 });
@@ -263,7 +269,6 @@ async function main() {
await updateEnvFile(apiKey);
console.log('🎉 Success! API key has been updated in .env.local');
} catch (error) {
console.error('❌ Error:', error.message);
process.exit(1);
@@ -301,4 +306,4 @@ if (require.main === module) {
main();
}
module.exports = { extractApiKey, updateEnvFile };
module.exports = { extractApiKey, updateEnvFile };
+13 -7
View File
@@ -1,3 +1,8 @@
console.error(
'RETIRED: this script scraped the managed Supabase Cloud dashboard for API keys, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch); read keys from .env.local / the self-hosted Studio. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
@@ -8,7 +13,7 @@ async function getSupabaseApiKeys() {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: null,
args: ['--start-maximized']
args: ['--start-maximized'],
});
const page = await browser.newPage();
@@ -16,7 +21,7 @@ async function getSupabaseApiKeys() {
try {
console.log('🔗 Navigating to Supabase project...');
await page.goto('https://app.supabase.com/project/ohkueislstxomdjavyhs/settings/api', {
waitUntil: 'networkidle2'
waitUntil: 'networkidle2',
});
// Wait for the API keys section to load
@@ -32,7 +37,7 @@ async function getSupabaseApiKeys() {
'tr:has(td:contains("anon")) code',
'tr:has(td:contains("public")) code',
'.api-key',
'code'
'code',
];
let anonKey = null;
@@ -86,7 +91,6 @@ async function getSupabaseApiKeys() {
await browser.close();
return anonKey;
} catch (error) {
console.error('❌ Error:', error.message);
await browser.close();
@@ -95,12 +99,14 @@ async function getSupabaseApiKeys() {
}
// Run the function
getSupabaseApiKeys().then((key) => {
getSupabaseApiKeys().then(key => {
if (key) {
console.log('🎉 Success! OrangeCat should now work!');
console.log('🔄 Restart your development server: npm run dev');
} else {
console.log('⚠️ Manual intervention required.');
console.log('🔗 Please visit: https://app.supabase.com/project/ohkueislstxomdjavyhs/settings/api');
console.log(
'🔗 Please visit: https://app.supabase.com/project/ohkueislstxomdjavyhs/settings/api'
);
}
});
});
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script scraped the managed Supabase Cloud dashboard for API keys, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch); read keys from .env.local / the self-hosted Studio. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
# Supabase API Key Retrieval Script
# This script automates the process of getting the fresh anon public API key
+11 -5
View File
@@ -1,4 +1,8 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script targeted the managed Supabase Cloud dashboard for API keys, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch); read keys from .env.local / the self-hosted Studio. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Simple API Key Update Script
@@ -74,11 +78,11 @@ function updateEnvFile(newApiKey) {
async function promptForApiKey() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
output: process.stdout,
});
return new Promise((resolve) => {
rl.question('🔑 Paste the anon public API key here: ', (answer) => {
return new Promise(resolve => {
rl.question('🔑 Paste the anon public API key here: ', answer => {
rl.close();
resolve(answer.trim());
});
@@ -122,7 +126,9 @@ async function main() {
const validation = validateApiKey(apiKey);
if (validation.valid) {
console.log('✅ API key validation passed');
console.log(`🔑 Key preview: ${apiKey.substring(0, 20)}...${apiKey.substring(apiKey.length - 20)}`);
console.log(
`🔑 Key preview: ${apiKey.substring(0, 20)}...${apiKey.substring(apiKey.length - 20)}`
);
updateEnvFile(apiKey);
@@ -170,4 +176,4 @@ if (require.main === module) {
});
}
module.exports = { validateApiKey, updateEnvFile };
module.exports = { validateApiKey, updateEnvFile };
+2
View File
@@ -1,4 +1,6 @@
#!/bin/bash
echo 'RETIRED: this script opened the managed Supabase Cloud dashboard for API keys, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch); read keys from .env.local / the self-hosted Studio. See docs/operations/DECOMMISSION-CLOUD.md.' >&2
exit 1
# 🧡 OrangeCat - Automatic API Key Updater
# This script will open your browser and guide you through updating the API key
+55 -54
View File
@@ -1,70 +1,71 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Fix Storage Bucket Policies using Supabase Management API
* This approach uses the proper API instead of direct SQL
*/
require('dotenv').config({ path: '.env.local' })
require('dotenv').config({ path: '.env.local' });
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const accessToken = process.env.SUPABASE_ACCESS_TOKEN
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const accessToken = process.env.SUPABASE_ACCESS_TOKEN;
if (!supabaseUrl || !accessToken) {
console.error('❌ Missing required environment variables:')
console.error('- NEXT_PUBLIC_SUPABASE_URL')
console.error('- SUPABASE_ACCESS_TOKEN')
console.log('\nYou can get your access token from: https://supabase.com/dashboard/account/tokens')
process.exit(1)
console.error('❌ Missing required environment variables:');
console.error('- NEXT_PUBLIC_SUPABASE_URL');
console.error('- SUPABASE_ACCESS_TOKEN');
console.log(
'\nYou can get your access token from: https://supabase.com/dashboard/account/tokens'
);
process.exit(1);
}
// Extract project ref from URL
const projectRef = supabaseUrl.match(/https:\/\/([^.]+)\./)?.[1]
const projectRef = supabaseUrl.match(/https:\/\/([^.]+)\./)?.[1];
if (!projectRef) {
console.error('❌ Could not extract project reference from URL')
process.exit(1)
console.error('❌ Could not extract project reference from URL');
process.exit(1);
}
console.log(`🔧 Fixing Storage Policies for project: ${projectRef}\n`)
console.log(`🔧 Fixing Storage Policies for project: ${projectRef}\n`);
async function updateBucketPolicies() {
const managementUrl = `https://api.supabase.com/v1/projects/${projectRef}/storage/buckets/avatars`
const managementUrl = `https://api.supabase.com/v1/projects/${projectRef}/storage/buckets/avatars`;
console.log('📝 Updating avatars bucket configuration...\n')
console.log('📝 Updating avatars bucket configuration...\n');
// Update bucket to be public and set proper policies
const response = await fetch(managementUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
public: true,
file_size_limit: 5242880, // 5MB
allowed_mime_types: [
'image/jpeg',
'image/jpg',
'image/png',
'image/webp',
'image/gif'
]
})
})
allowed_mime_types: ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'],
}),
});
if (!response.ok) {
const error = await response.text()
console.error('❌ Failed to update bucket:', error)
return false
const error = await response.text();
console.error('❌ Failed to update bucket:', error);
return false;
}
console.log('✅ Bucket configuration updated!\n')
return true
console.log('✅ Bucket configuration updated!\n');
return true;
}
async function createStoragePolicies() {
console.log('📝 Creating RLS policies via SQL...\n')
console.log('📝 Creating RLS policies via SQL...\n');
const sql = `
-- Drop existing policies
@@ -90,53 +91,53 @@ async function createStoragePolicies() {
CREATE POLICY "Public avatars bucket is publicly readable"
ON storage.objects FOR SELECT TO public
USING (bucket_id = 'avatars');
`
`;
const sqlUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`
const sqlUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`;
const response = await fetch(sqlUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ query: sql })
})
body: JSON.stringify({ query: sql }),
});
if (!response.ok) {
const error = await response.json()
console.error('❌ Failed to create policies:', error.message || error)
console.log('\n⚠️ This requires running SQL manually in the dashboard.')
return false
const error = await response.json();
console.error('❌ Failed to create policies:', error.message || error);
console.log('\n⚠️ This requires running SQL manually in the dashboard.');
return false;
}
console.log('✅ RLS policies created!\n')
return true
console.log('✅ RLS policies created!\n');
return true;
}
async function main() {
console.log('=' .repeat(80))
console.log('FIXING STORAGE RLS POLICIES')
console.log('=' .repeat(80) + '\n')
console.log('='.repeat(80));
console.log('FIXING STORAGE RLS POLICIES');
console.log('='.repeat(80) + '\n');
// Step 1: Update bucket configuration
const bucketSuccess = await updateBucketPolicies()
const bucketSuccess = await updateBucketPolicies();
// Step 2: Try to create policies via API
const policySuccess = await createStoragePolicies()
const policySuccess = await createStoragePolicies();
console.log('=' .repeat(80))
console.log('='.repeat(80));
if (bucketSuccess && policySuccess) {
console.log('\n🎉 All done! Avatar uploads should now work.\n')
console.log('\n🎉 All done! Avatar uploads should now work.\n');
} else if (bucketSuccess) {
console.log('\n⚠️ Bucket updated but policies need manual creation.')
console.log('\nPlease run this SQL in your Supabase dashboard:')
console.log('https://supabase.com/dashboard/project/' + projectRef + '/sql/new\n')
console.log('See: apply-storage-fix.sql\n')
console.log('\n⚠️ Bucket updated but policies need manual creation.');
console.log('\nPlease run this SQL in your Supabase dashboard:');
console.log('https://supabase.com/dashboard/project/' + projectRef + '/sql/new\n');
console.log('See: apply-storage-fix.sql\n');
} else {
console.log('\n⚠️ Could not update via API. Please use the dashboard method.\n')
console.log('\n⚠️ Could not update via API. Please use the dashboard method.\n');
}
}
main().catch(console.error)
main().catch(console.error);
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
echo "=== Listing all messaging-related functions ==="
curl -s "${BASE_URL}/rest/v1/rpc/" \
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Apply Timeline Social Features Migration
*
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
const https = require('https');
const fs = require('fs');
+5
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Database Diagnostic Script
* Checks the current state of timeline-related database objects
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Fix Profile Bootstrap
* Creates a profile record for the authenticated user if missing
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Test Timeline Functions
* Verifies that all timeline RPC functions work correctly
+90 -82
View File
@@ -10,30 +10,30 @@
* Usage: node scripts/setup-oauth-providers.js
*/
const fs = require('fs')
const path = require('path')
require('dotenv').config({ path: '.env.local' })
const fs = require('fs');
const path = require('path');
require('dotenv').config({ path: '.env.local' });
class OAuthSetup {
constructor() {
this.envFilePath = path.join(process.cwd(), '.env.local')
this.errors = []
this.envFilePath = path.join(process.cwd(), '.env.local');
this.errors = [];
}
async log(message, type = 'info') {
const timestamp = new Date().toISOString()
const timestamp = new Date().toISOString();
const colors = {
info: '\x1b[36m',
success: '\x1b[32m',
warning: '\x1b[33m',
error: '\x1b[31m',
reset: '\x1b[0m'
}
reset: '\x1b[0m',
};
console.log(`${colors[type]}[${timestamp}] ${message}${colors.reset}`)
console.log(`${colors[type]}[${timestamp}] ${message}${colors.reset}`);
if (type === 'error') {
this.errors.push({ timestamp, message })
this.errors.push({ timestamp, message });
}
}
@@ -45,7 +45,7 @@ class OAuthSetup {
# ==================== REQUIRED ENVIRONMENT VARIABLES ====================
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=https://ohkueislstxomdjavyhs.supabase.co
NEXT_PUBLIC_SUPABASE_URL=https://supabase.orangecat.ch
NEXT_PUBLIC_SUPABASE_ANON_KEY=${NEXT_PUBLIC_SUPABASE_ANON_KEY}
# Site Configuration
@@ -76,110 +76,118 @@ SUPABASE_AUTH_EXTERNAL_X_SECRET=your-x-client-secret
# 1. Copy this file to .env.local (already done)
# 2. Fill in all the OAuth credentials above
# 3. Set up OAuth providers in Supabase Dashboard:
# - Go to https://supabase.com/dashboard/project/YOUR_PROJECT/settings/auth
# - Go to the self-hosted Supabase Studio (supabase.orangecat.ch) Authentication settings - managed cloud retired
# - Enable GitHub, Google, and Twitter/X providers
# - Add your OAuth credentials
# - Set redirect URLs to: https://www.orangecat.ch/auth/callback
# 4. Restart your development server
`
fs.writeFileSync(this.envFilePath, envContent)
this.log('✅ Created .env.local file with OAuth configuration', 'success')
`;
fs.writeFileSync(this.envFilePath, envContent);
this.log('✅ Created .env.local file with OAuth configuration', 'success');
} catch (error) {
this.log(`❌ Failed to create .env.local file: ${error.message}`, 'error')
throw error
this.log(`❌ Failed to create .env.local file: ${error.message}`, 'error');
throw error;
}
}
displaySetupInstructions() {
this.log('🚀 OAUTH PROVIDER SETUP INSTRUCTIONS', 'info')
this.log('=====================================', 'info')
this.log('🚀 OAUTH PROVIDER SETUP INSTRUCTIONS', 'info');
this.log('=====================================', 'info');
this.log('', 'info')
this.log('📋 STEP 1: Configure OAuth Providers in Supabase Dashboard', 'info')
this.log(' Go to: https://supabase.com/dashboard/project/YOUR_PROJECT/settings/auth', 'info')
this.log(' Enable the following providers:', 'info')
this.log(' • GitHub', 'info')
this.log(' • Google', 'info')
this.log(' • Twitter/X', 'info')
this.log('', 'info')
this.log('', 'info');
this.log('📋 STEP 1: Configure OAuth Providers in Supabase Dashboard', 'info');
this.log(
' Go to: the self-hosted Supabase Studio (supabase.orangecat.ch) Authentication settings - managed cloud retired',
'info'
);
this.log(' Enable the following providers:', 'info');
this.log(' • GitHub', 'info');
this.log(' • Google', 'info');
this.log(' • Twitter/X', 'info');
this.log('', 'info');
this.log('📋 STEP 2: Set up GitHub OAuth', 'info')
this.log(' 1. Go to: https://github.com/settings/applications/new', 'info')
this.log(' 2. Application name: OrangeCat', 'info')
this.log(' 3. Homepage URL: https://www.orangecat.ch', 'info')
this.log(' 4. Authorization callback URL: https://www.orangecat.ch/auth/callback', 'info')
this.log(' 5. Copy Client ID and Client Secret to .env.local', 'info')
this.log('', 'info')
this.log('📋 STEP 2: Set up GitHub OAuth', 'info');
this.log(' 1. Go to: https://github.com/settings/applications/new', 'info');
this.log(' 2. Application name: OrangeCat', 'info');
this.log(' 3. Homepage URL: https://www.orangecat.ch', 'info');
this.log(' 4. Authorization callback URL: https://www.orangecat.ch/auth/callback', 'info');
this.log(' 5. Copy Client ID and Client Secret to .env.local', 'info');
this.log('', 'info');
this.log('📋 STEP 3: Set up Google OAuth', 'info')
this.log(' 1. Go to: https://console.cloud.google.com/', 'info')
this.log(' 2. Create/select project and enable Google+ API', 'info')
this.log(' 3. Go to Credentials > Create Credentials > OAuth 2.0 Client IDs', 'info')
this.log(' 4. Application type: Web application', 'info')
this.log(' 5. Authorized redirect URIs: https://www.orangecat.ch/auth/callback', 'info')
this.log(' 6. Copy Client ID and Client Secret to .env.local', 'info')
this.log('', 'info')
this.log('📋 STEP 3: Set up Google OAuth', 'info');
this.log(' 1. Go to: https://console.cloud.google.com/', 'info');
this.log(' 2. Create/select project and enable Google+ API', 'info');
this.log(' 3. Go to Credentials > Create Credentials > OAuth 2.0 Client IDs', 'info');
this.log(' 4. Application type: Web application', 'info');
this.log(' 5. Authorized redirect URIs: https://www.orangecat.ch/auth/callback', 'info');
this.log(' 6. Copy Client ID and Client Secret to .env.local', 'info');
this.log('', 'info');
this.log('📋 STEP 4: Set up Twitter/X OAuth', 'info')
this.log(' 1. Go to: https://developer.twitter.com/en/portal/dashboard', 'info')
this.log(' 2. Create/select app', 'info')
this.log(' 3. App permissions: Read', 'info')
this.log(' 4. Authentication settings: Enable OAuth 2.0', 'info')
this.log(' 5. Callback URLs: https://www.orangecat.ch/auth/callback', 'info')
this.log(' 6. Copy API Key (Client ID) and API Key Secret (Client Secret) to .env.local', 'info')
this.log('', 'info')
this.log('📋 STEP 4: Set up Twitter/X OAuth', 'info');
this.log(' 1. Go to: https://developer.twitter.com/en/portal/dashboard', 'info');
this.log(' 2. Create/select app', 'info');
this.log(' 3. App permissions: Read', 'info');
this.log(' 4. Authentication settings: Enable OAuth 2.0', 'info');
this.log(' 5. Callback URLs: https://www.orangecat.ch/auth/callback', 'info');
this.log(
' 6. Copy API Key (Client ID) and API Key Secret (Client Secret) to .env.local',
'info'
);
this.log('', 'info');
this.log('📋 STEP 5: Update .env.local file', 'info')
this.log(' Edit .env.local and replace "your-*-client-id" and "your-*-client-secret"', 'info')
this.log(' with the actual values from the OAuth provider dashboards', 'info')
this.log('', 'info')
this.log('📋 STEP 5: Update .env.local file', 'info');
this.log(
' Edit .env.local and replace "your-*-client-id" and "your-*-client-secret"',
'info'
);
this.log(' with the actual values from the OAuth provider dashboards', 'info');
this.log('', 'info');
this.log('📋 STEP 6: Restart development server', 'info')
this.log(' Run: npm run dev', 'info')
this.log('', 'info')
this.log('📋 STEP 6: Restart development server', 'info');
this.log(' Run: npm run dev', 'info');
this.log('', 'info');
this.log('🎯 TROUBLESHOOTING:', 'info')
this.log(' • If "provider is not enabled" error: Check Supabase dashboard provider settings', 'warning')
this.log(' • If redirect URL error: Make sure callback URL matches exactly', 'warning')
this.log(' • If credentials error: Verify Client ID and Secret are correct', 'warning')
this.log('', 'info')
this.log('🎯 TROUBLESHOOTING:', 'info');
this.log(
' • If "provider is not enabled" error: Check Supabase dashboard provider settings',
'warning'
);
this.log(' • If redirect URL error: Make sure callback URL matches exactly', 'warning');
this.log(' • If credentials error: Verify Client ID and Secret are correct', 'warning');
this.log('', 'info');
}
run() {
try {
this.log('🚀 STARTING OAUTH PROVIDER SETUP', 'info')
this.log('=================================', 'info')
this.log('🚀 STARTING OAUTH PROVIDER SETUP', 'info');
this.log('=================================', 'info');
// Create .env.local file
this.createEnvFile()
this.createEnvFile();
// Display setup instructions
this.displaySetupInstructions()
this.displaySetupInstructions();
this.log('✅ OAUTH PROVIDER SETUP COMPLETE', 'success')
this.log('=================================', 'success')
this.log('🌐 Next steps:', 'info')
this.log(' 1. Follow the setup instructions above', 'info')
this.log(' 2. Update .env.local with real OAuth credentials', 'info')
this.log(' 3. Restart development server: npm run dev', 'info')
this.log(' 4. Test authentication at: https://orangecat.ch/auth', 'info')
this.log('✅ OAUTH PROVIDER SETUP COMPLETE', 'success');
this.log('=================================', 'success');
this.log('🌐 Next steps:', 'info');
this.log(' 1. Follow the setup instructions above', 'info');
this.log(' 2. Update .env.local with real OAuth credentials', 'info');
this.log(' 3. Restart development server: npm run dev', 'info');
this.log(' 4. Test authentication at: https://orangecat.ch/auth', 'info');
} catch (error) {
this.log(`💥 SETUP FAILED: ${error.message}`, 'error')
throw error
this.log(`💥 SETUP FAILED: ${error.message}`, 'error');
throw error;
}
}
}
// Run if called directly
if (require.main === module) {
const setup = new OAuthSetup()
setup.run()
const setup = new OAuthSetup();
setup.run();
}
module.exports = OAuthSetup
module.exports = OAuthSetup;
+13 -8
View File
@@ -15,11 +15,11 @@ const ENV_FILE_PATH = path.join(process.cwd(), '.env.local');
function askQuestion(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
return new Promise(resolve => {
rl.question(question, answer => {
rl.close();
resolve(answer);
});
@@ -43,11 +43,15 @@ async function setupEnvironment() {
}
console.log('\n📋 You need your Supabase project credentials.');
console.log(' You can find them at: https://app.supabase.com/project/YOUR_PROJECT/settings/api');
console.log(
' You can find them in .env.local or the self-hosted Supabase Studio (supabase.orangecat.ch) - managed cloud retired'
);
console.log('');
// Get Supabase URL
const supabaseUrl = await askQuestion('Enter your Supabase Project URL (e.g., https://your-project.supabase.co): ');
const supabaseUrl = await askQuestion(
'Enter your Supabase Project URL (e.g., https://your-project.supabase.co): '
);
if (!supabaseUrl || !supabaseUrl.includes('supabase.co')) {
console.error('❌ Invalid Supabase URL. It should end with .supabase.co');
@@ -55,7 +59,9 @@ async function setupEnvironment() {
}
// Get Supabase Anon Key
const supabaseKey = await askQuestion('Enter your Supabase anon/public key (starts with eyJ...): ');
const supabaseKey = await askQuestion(
'Enter your Supabase anon/public key (starts with eyJ...): '
);
if (!supabaseKey || !supabaseKey.startsWith('eyJ')) {
console.error('❌ Invalid Supabase key. It should start with "eyJ"');
@@ -105,7 +111,7 @@ NODE_ENV=development
.limit(1);
if (profilesError) {
console.log('⚠️ Connection test failed - this might be normal if tables don\'t exist yet');
console.log("⚠️ Connection test failed - this might be normal if tables don't exist yet");
console.log(` Error: ${profilesError.message}`);
} else {
console.log('✅ Database connection successful!');
@@ -121,4 +127,3 @@ NODE_ENV=development
if (require.main === module) {
setupEnvironment().catch(console.error);
}
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
SERVICE_KEY="${SUPABASE_SERVICE_ROLE_KEY}"
BASE_URL="https://ohkueislstxomdjavyhs.supabase.co"
BASE_URL="${NEXT_PUBLIC_SUPABASE_URL:?NEXT_PUBLIC_SUPABASE_URL is required (self-hosted: https://supabase.orangecat.ch) - managed cloud retired}"
CONV_ID="2ef0fe8f-79ba-497e-8fe2-b66a9e4759a3"
USER_ID="cec88bc9-557f-452b-92f1-e093092fecd6"
+13 -4
View File
@@ -1,8 +1,14 @@
// Comprehensive debug script for service creation
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = 'https://ohkueislstxomdjavyhs.supabase.co';
const supabaseKey = 'eyJhbGciOiJIUzI1NiIsImtpZCI6Ik13K25NM0twQVdEL1dLU2G0.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9oa3VlaXNsc3R4b21kamF2eWhzIiwicm9sZSI6MjA2MDEyMzk1MH0.Qc6ahUbs_5BCa4csEYsBtyxNUDYb4h3Y4K_16N1DNaY';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseKey) {
console.error(
'Missing NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY (self-hosted: https://supabase.orangecat.ch) - managed cloud retired'
);
process.exit(1);
}
async function debugServiceCreation() {
console.log('🔍 Comprehensive Service Creation Debug\n');
@@ -11,7 +17,10 @@ async function debugServiceCreation() {
// Test 1: Check authentication
console.log('1️⃣ Testing Authentication...');
const { data: { user }, error: authError } = await supabase.auth.getUser();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
console.log('❌ Not authenticated:', authError?.message || 'No user');
return;
@@ -64,7 +73,7 @@ async function debugServiceCreation() {
title: 'Debug Test Service',
description: 'Test service for debugging',
category: 'Other',
status: 'draft'
status: 'draft',
};
console.log('📝 Attempting to create service with data:', minimalService);
+38 -16
View File
@@ -1,10 +1,14 @@
const { Client } = require('pg');
// Connect to the remote Supabase instance since that's what the app uses
// Connect to the self-hosted Supabase instance (supabase.orangecat.ch) since that's what the app uses
if (!process.env.POSTGRES_URL) {
console.error(
'Missing POSTGRES_URL (self-hosted: supabase.orangecat.ch) - managed cloud retired'
);
process.exit(1);
}
const client = new Client({
connectionString: process.env.SUPABASE_SERVICE_ROLE_KEY ?
`postgresql://postgres:${process.env.SUPABASE_SERVICE_ROLE_KEY}@db.ohkueislstxomdjavyhs.supabase.co:5432/postgres` :
'postgresql://postgres:postgres@localhost:54322/postgres'
connectionString: process.env.POSTGRES_URL,
});
async function testMessagingAPI() {
@@ -23,18 +27,23 @@ async function testMessagingAPI() {
console.log('Testing with user:', userId, users.rows[0].email);
// Test getting conversations for this user
const conversations = await client.query(`
const conversations = await client.query(
`
SELECT c.id, c.title, c.is_group,
COUNT(cp.user_id) as participant_count
FROM conversations c
JOIN conversation_participants cp ON c.id = cp.conversation_id
WHERE cp.user_id = $1 AND cp.is_active = true
GROUP BY c.id, c.title, c.is_group
`, [userId]);
`,
[userId]
);
console.log('User conversations:');
conversations.rows.forEach(conv => {
console.log(` - ${conv.id}: ${conv.title || 'Untitled'} (${conv.participant_count} participants)`);
console.log(
` - ${conv.id}: ${conv.title || 'Untitled'} (${conv.participant_count} participants)`
);
});
// Test getting messages for first conversation
@@ -42,14 +51,17 @@ async function testMessagingAPI() {
const convId = conversations.rows[0].id;
console.log(`\nTesting messages for conversation: ${convId}`);
const messages = await client.query(`
const messages = await client.query(
`
SELECT m.id, m.content, m.sender_id, p.name as sender_name
FROM messages m
JOIN profiles p ON m.sender_id = p.id
WHERE m.conversation_id = $1
ORDER BY m.created_at DESC
LIMIT 5
`, [convId]);
`,
[convId]
);
console.log('Recent messages:');
messages.rows.forEach(msg => {
@@ -58,16 +70,23 @@ async function testMessagingAPI() {
// Test conversation_details view for this user
console.log('\nTesting get_user_conversations() function:');
const convDetails = await client.query(`
const convDetails = await client.query(
`
SELECT * FROM get_user_conversations($1)
WHERE id = $2
`, [userId, convId]);
`,
[userId, convId]
);
console.log('User conversations (function) result:', convDetails.rows.length > 0 ? 'SUCCESS' : 'NO DATA');
console.log(
'User conversations (function) result:',
convDetails.rows.length > 0 ? 'SUCCESS' : 'NO DATA'
);
// Test message_details view
console.log('Testing message_details view:');
const msgDetails = await client.query(`
const msgDetails = await client.query(
`
SELECT m.id, m.content, p.name as sender_name,
EXISTS (
SELECT 1 FROM message_read_receipts r
@@ -78,16 +97,19 @@ async function testMessagingAPI() {
WHERE m.conversation_id = $1
ORDER BY m.created_at DESC
LIMIT 3
`, [convId, userId]);
`,
[convId, userId]
);
console.log('Message details result:', msgDetails.rows.length > 0 ? 'SUCCESS' : 'NO DATA');
msgDetails.rows.forEach(msg => {
console.log(` - ${msg.sender_name}: ${msg.content.substring(0, 30)}... (read: ${msg.is_read})`);
console.log(
` - ${msg.sender_name}: ${msg.content.substring(0, 30)}... (read: ${msg.is_read})`
);
});
}
console.log('\n✅ Messaging system test completed successfully!');
} catch (error) {
console.error('❌ Messaging test failed:', error.message);
} finally {
+5
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Test Timeline Functions
* Verifies that all timeline RPC functions work correctly
+28 -23
View File
@@ -1,15 +1,20 @@
#!/usr/bin/env node
console.error(
'RETIRED: this script used the managed Supabase Cloud Management API, which was removed 2026-06. The DB is now self-hosted (supabase.orangecat.ch). Apply SQL via: psql "$POSTGRES_URL" -f <file>. See docs/operations/DECOMMISSION-CLOUD.md.'
);
process.exit(1);
/**
* Verify Storage Policies
*/
require('dotenv').config({ path: '.env.local' })
require('dotenv').config({ path: '.env.local' });
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const accessToken = process.env.SUPABASE_ACCESS_TOKEN
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const accessToken = process.env.SUPABASE_ACCESS_TOKEN;
const projectRef = supabaseUrl.match(/https:\/\/([^.]+)\./)?.[1]
const projectRef = supabaseUrl.match(/https:\/\/([^.]+)\./)?.[1];
async function checkPolicies() {
const sql = `
@@ -24,41 +29,41 @@ async function checkPolicies() {
AND schemaname = 'storage'
AND policyname LIKE '%avatar%'
ORDER BY policyname;
`
`;
const sqlUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`
const sqlUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`;
const response = await fetch(sqlUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ query: sql })
})
body: JSON.stringify({ query: sql }),
});
if (!response.ok) {
console.error('❌ Could not verify policies')
return
console.error('❌ Could not verify policies');
return;
}
const result = await response.json()
const result = await response.json();
console.log('\n📋 Current Storage Policies for Avatars:\n')
console.log('='.repeat(80))
console.log('\n📋 Current Storage Policies for Avatars:\n');
console.log('='.repeat(80));
if (result.result && result.result.length > 0) {
result.result.forEach((policy, i) => {
console.log(`\n${i + 1}. ${policy.policyname}`)
console.log(` Command: ${policy.cmd}`)
console.log(` Roles: ${policy.roles}`)
})
console.log('\n' + '='.repeat(80))
console.log(`\n✅ Found ${result.result.length} avatar policies!`)
console.log('\n🎉 You should now be able to upload avatars!\n')
console.log(`\n${i + 1}. ${policy.policyname}`);
console.log(` Command: ${policy.cmd}`);
console.log(` Roles: ${policy.roles}`);
});
console.log('\n' + '='.repeat(80));
console.log(`\n✅ Found ${result.result.length} avatar policies!`);
console.log('\n🎉 You should now be able to upload avatars!\n');
} else {
console.log('\n⚠️ No avatar policies found.\n')
console.log('\n⚠️ No avatar policies found.\n');
}
}
checkPolicies().catch(console.error)
checkPolicies().catch(console.error);
+1 -2
View File
@@ -10,8 +10,7 @@
const { createClient } = require('@supabase/supabase-js');
// Environment variables
const supabaseUrl =
process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://ohkueislstxomdjavyhs.supabase.co';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://supabase.orangecat.ch';
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || 'REDACTED_ANON_KEY';
async function initializeOrangeCatOrganization() {
+1 -2
View File
@@ -10,8 +10,7 @@
const { createClient } = require('@supabase/supabase-js');
// Environment variables
const supabaseUrl =
process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://ohkueislstxomdjavyhs.supabase.co';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://supabase.orangecat.ch';
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || 'REDACTED_ANON_KEY';
async function setupSubscriptionFunding() {
+1 -1
View File
@@ -255,7 +255,7 @@ max_frequency = "5s"
#
# OAuth Setup Instructions:
# 1. Register an app at each provider's developer console
# 2. Set callback URL to: https://ohkueislstxomdjavyhs.supabase.co/auth/v1/callback
# 2. Set callback URL to: https://supabase.orangecat.ch/auth/v1/callback
# 3. Add client ID and secret in Supabase Dashboard > Authentication > Providers
# 4. Or set them below using environment variable substitution
+1 -1
View File
@@ -107,7 +107,7 @@ async function testFullFlow() {
// Test 6: Database connection verification
console.log('\n💾 Test 6: Database connectivity...');
const dbTestUrl = 'https://ohkueislstxomdjavyhs.supabase.co/rest/v1/profiles?select=count&limit=1';
const dbTestUrl = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/rest/v1/profiles?select=count&limit=1`;
const dbResponse = await page.request.get(dbTestUrl, {
headers: {
'apikey': process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
+1 -1
View File
@@ -29,7 +29,7 @@ async function testProfileSave() {
console.log('-'.repeat(70));
// First, let's verify the schema consistency
const profileResponse = await page.request.get('https://ohkueislstxomdjavyhs.supabase.co/rest/v1/profiles?select=*&limit=1', {
const profileResponse = await page.request.get(`${process.env.NEXT_PUBLIC_SUPABASE_URL}/rest/v1/profiles?select=*&limit=1`, {
headers: {
'apikey': process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
'Authorization': 'Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}'