@nextsparkjs/plugin-social-media-publisher 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,471 @@
1
+ # Installation and Setup
2
+
3
+ ## Prerequisites
4
+
5
+ Before installing the Social Media Publisher plugin, ensure you have:
6
+
7
+ - ✅ NextSpark project set up and running
8
+ - ✅ PostgreSQL database configured
9
+ - ✅ Active theme with plugin support
10
+ - ✅ Facebook Developer account (free)
11
+ - ✅ Instagram Business Account (for Instagram publishing)
12
+ - ✅ Facebook Page (for Instagram Business connection or Facebook publishing)
13
+
14
+ ## Step 1: Create Facebook App
15
+
16
+ ### 1.1 Register as Facebook Developer
17
+
18
+ 1. Visit [Facebook Developers](https://developers.facebook.com/)
19
+ 2. Click "Get Started" or "My Apps"
20
+ 3. Complete developer registration (if needed)
21
+
22
+ ### 1.2 Create New App
23
+
24
+ 1. Click "Create App"
25
+ 2. Select "Business" as app type
26
+ 3. Fill in app details:
27
+ - **App Name:** Your SaaS Name Social Media
28
+ - **App Contact Email:** your@email.com
29
+ - **Business Account:** (Optional) Select if you have one
30
+ 4. Click "Create App"
31
+
32
+ ### 1.3 Configure OAuth Settings
33
+
34
+ **Add Facebook Login Product:**
35
+
36
+ 1. In app dashboard, click "Add Product"
37
+ 2. Find "Facebook Login" → Click "Set Up"
38
+ 3. Select "Web" as platform
39
+ 4. Skip quick start (we'll configure manually)
40
+
41
+ **Configure OAuth Redirect URLs:**
42
+
43
+ 1. Go to "Facebook Login" → "Settings"
44
+ 2. Add **Valid OAuth Redirect URIs:**
45
+
46
+ ```
47
+ Development:
48
+ http://localhost:5173/api/v1/plugin/social-media-publisher/social/connect/callback
49
+
50
+ Production:
51
+ https://yourdomain.com/api/v1/plugin/social-media-publisher/social/connect/callback
52
+ ```
53
+
54
+ 3. **Client OAuth Login:** ON
55
+ 4. **Web OAuth Login:** ON
56
+ 5. Save changes
57
+
58
+ ### 1.4 Request Permissions
59
+
60
+ **For Instagram Business:**
61
+
62
+ 1. Go to "App Review" → "Permissions and Features"
63
+ 2. Request these permissions:
64
+ - `pages_show_list` - Required
65
+ - `pages_manage_posts` - Required
66
+ - `pages_read_engagement` - Required
67
+ - `instagram_basic` - Required
68
+ - `instagram_content_publish` - Required
69
+ - `instagram_manage_insights` - Optional (for analytics)
70
+
71
+ **For Facebook Pages:**
72
+
73
+ 1. Same permissions as above
74
+ 2. Already includes everything needed for Page publishing
75
+
76
+ **Note:** These permissions require App Review for production apps. During development, admins, developers, and testers can use them immediately.
77
+
78
+ ### 1.5 Get App Credentials
79
+
80
+ 1. Go to "Settings" → "Basic"
81
+ 2. Copy your credentials:
82
+ - **App ID** (will be `FACEBOOK_CLIENT_ID`)
83
+ - **App Secret** (will be `FACEBOOK_CLIENT_SECRET`)
84
+ 3. Keep these secure!
85
+
86
+ ## Step 2: Configure Environment Variables
87
+
88
+ ### 2.1 Core Environment File
89
+
90
+ Create or update your main `.env` file:
91
+
92
+ ```bash
93
+ # Facebook OAuth Credentials
94
+ FACEBOOK_CLIENT_ID=your_app_id_here
95
+ FACEBOOK_CLIENT_SECRET=your_app_secret_here
96
+
97
+ # App URL (important for OAuth redirects)
98
+ NEXT_PUBLIC_APP_URL=http://localhost:5173
99
+
100
+ # OAuth Token Encryption (32-byte hex key)
101
+ OAUTH_ENCRYPTION_KEY=your_encryption_key_here
102
+ ```
103
+
104
+ ### 2.2 Generate Encryption Key
105
+
106
+ The `OAUTH_ENCRYPTION_KEY` is used to encrypt OAuth tokens in the database.
107
+
108
+ **Generate a secure key:**
109
+
110
+ ```bash
111
+ # Using Node.js
112
+ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
113
+
114
+ # Output example:
115
+ # a7f9b2c8d1e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9
116
+ ```
117
+
118
+ **Add to `.env`:**
119
+ ```bash
120
+ OAUTH_ENCRYPTION_KEY=a7f9b2c8d1e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9
121
+ ```
122
+
123
+ **Security Notes:**
124
+ - ✅ Key must be exactly 32 bytes (64 hex characters)
125
+ - ✅ Generate unique key for each environment
126
+ - ✅ Never commit to version control
127
+ - ✅ Store securely in production (e.g., AWS Secrets Manager)
128
+ - ✅ Rotate periodically (requires re-connecting accounts)
129
+
130
+ ### 2.3 Environment Variable Reference
131
+
132
+ ```bash
133
+ # ==============================================
134
+ # FACEBOOK OAUTH CONFIGURATION
135
+ # ==============================================
136
+
137
+ # Facebook App ID (from App Dashboard → Settings → Basic)
138
+ FACEBOOK_CLIENT_ID=123456789012345
139
+
140
+ # Facebook App Secret (from App Dashboard → Settings → Basic)
141
+ FACEBOOK_CLIENT_SECRET=abcdef123456789abcdef123456789ab
142
+
143
+ # ==============================================
144
+ # APPLICATION URL
145
+ # ==============================================
146
+
147
+ # Base URL of your application (no trailing slash)
148
+ # Development:
149
+ NEXT_PUBLIC_APP_URL=http://localhost:5173
150
+
151
+ # Production:
152
+ # NEXT_PUBLIC_APP_URL=https://yourdomain.com
153
+
154
+ # ==============================================
155
+ # SECURITY
156
+ # ==============================================
157
+
158
+ # 32-byte encryption key for OAuth tokens (64 hex chars)
159
+ # Generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
160
+ OAUTH_ENCRYPTION_KEY=your_32_byte_key_in_hex_format
161
+
162
+ # ==============================================
163
+ # DATABASE (if not already configured)
164
+ # ==============================================
165
+
166
+ DATABASE_URL=postgresql://user:password@localhost:5432/database
167
+ ```
168
+
169
+ ## Step 3: Enable Plugin
170
+
171
+ ### 3.1 Add to Theme Configuration
172
+
173
+ Edit your theme's `theme.config.ts`:
174
+
175
+ ```typescript
176
+ // contents/themes/[your-theme]/theme.config.ts
177
+ export const yourThemeConfig: ThemeConfig = {
178
+ name: 'your-theme',
179
+ // ... other config
180
+
181
+ plugins: [
182
+ 'ai',
183
+ 'social-media-publisher' // Add this line
184
+ ]
185
+ }
186
+ ```
187
+
188
+ ### 3.2 Verify Plugin Loads
189
+
190
+ ```bash
191
+ # Start development server
192
+ pnpm dev
193
+
194
+ # Check console for plugin load message:
195
+ # [Social Media Publisher] Plugin loaded - OAuth publishing ready
196
+ ```
197
+
198
+ ## Step 4: Database Setup
199
+
200
+ ### 4.1 Run Migrations
201
+
202
+ The plugin includes migrations for the required tables:
203
+
204
+ ```bash
205
+ # Apply all pending migrations
206
+ pnpm db:migrate
207
+
208
+ # Or specifically for social media publisher:
209
+ psql $DATABASE_URL -f contents/plugins/social-media-publisher/migrations/001_social_media_tables.sql
210
+ ```
211
+
212
+ ### 4.2 Verify Tables Created
213
+
214
+ ```sql
215
+ -- Check if tables exist
216
+ SELECT table_name
217
+ FROM information_schema.tables
218
+ WHERE table_name IN ('clients_social_platforms', 'audit_logs');
219
+
220
+ -- Should return:
221
+ -- clients_social_platforms
222
+ -- audit_logs
223
+ ```
224
+
225
+ ### 4.3 Database Schema Overview
226
+
227
+ **clients_social_platforms (Child Entity):**
228
+ ```sql
229
+ CREATE TABLE "clients_social_platforms" (
230
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
231
+ "parentId" UUID NOT NULL REFERENCES "clients"(id) ON DELETE CASCADE,
232
+ platform TEXT NOT NULL,
233
+ "platformAccountId" TEXT,
234
+ "platformAccountName" TEXT NOT NULL,
235
+ "accessToken" TEXT NOT NULL,
236
+ "tokenExpiresAt" TIMESTAMPTZ NOT NULL,
237
+ permissions JSONB DEFAULT '[]',
238
+ "accountMetadata" JSONB DEFAULT '{}',
239
+ "isActive" BOOLEAN DEFAULT true,
240
+ "createdAt" TIMESTAMPTZ DEFAULT now(),
241
+ "updatedAt" TIMESTAMPTZ DEFAULT now()
242
+ );
243
+ ```
244
+
245
+ **audit_logs (Plugin Entity):**
246
+ ```sql
247
+ CREATE TABLE "audit_logs" (
248
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
249
+ "userId" TEXT NOT NULL,
250
+ "accountId" UUID,
251
+ action TEXT NOT NULL,
252
+ details JSONB DEFAULT '{}',
253
+ "ipAddress" TEXT,
254
+ "userAgent" TEXT,
255
+ "createdAt" TIMESTAMPTZ DEFAULT now()
256
+ );
257
+ ```
258
+
259
+ ## Step 5: Configure Facebook App for Production
260
+
261
+ ### 5.1 App Review Process
262
+
263
+ **For Production Use:**
264
+
265
+ 1. Go to "App Review" → "Permissions and Features"
266
+ 2. Click "Request" next to each required permission
267
+ 3. Fill out "App Questionnaire" explaining use case
268
+ 4. Submit screenshots showing OAuth flow
269
+ 5. Wait for approval (typically 1-3 days)
270
+
271
+ **Required Permissions:**
272
+ - `pages_show_list`
273
+ - `pages_manage_posts`
274
+ - `pages_read_engagement`
275
+ - `instagram_basic`
276
+ - `instagram_content_publish`
277
+
278
+ ### 5.2 Switch to Live Mode
279
+
280
+ 1. App dashboard → Top toggle
281
+ 2. Switch from "Development" to "Live"
282
+ 3. Confirm app is ready for public use
283
+
284
+ **Before Going Live:**
285
+ - ✅ Permissions approved
286
+ - ✅ Privacy policy URL added
287
+ - ✅ Terms of service URL added
288
+ - ✅ App icon uploaded
289
+ - ✅ Category selected
290
+ - ✅ Business verification completed
291
+
292
+ ## Step 6: Connect Instagram Business Account
293
+
294
+ **Important:** Instagram Business accounts must be connected to a Facebook Page.
295
+
296
+ ### 6.1 Link Instagram to Facebook Page
297
+
298
+ 1. Go to your Facebook Page
299
+ 2. Click "Settings"
300
+ 3. In left sidebar, click "Instagram"
301
+ 4. Click "Connect Account"
302
+ 5. Log in to Instagram
303
+ 6. Authorize connection
304
+ 7. Select Instagram Business Account
305
+
306
+ **Note:** Personal Instagram accounts cannot be used. You must have an Instagram Business or Creator account.
307
+
308
+ ### 6.2 Verify Connection
309
+
310
+ ```bash
311
+ # Test Graph API endpoint
312
+ curl "https://graph.facebook.com/v18.0/{PAGE_ID}?fields=instagram_business_account&access_token={PAGE_TOKEN}"
313
+
314
+ # Should return:
315
+ {
316
+ "instagram_business_account": {
317
+ "id": "17841..."
318
+ },
319
+ "id": "123456..."
320
+ }
321
+ ```
322
+
323
+ ## Step 7: Verification
324
+
325
+ ### 7.1 Test OAuth Flow
326
+
327
+ 1. Navigate to a client detail page in your app
328
+ 2. Click "Add Social Platform"
329
+ 3. Select "Instagram Business"
330
+ 4. OAuth popup should open
331
+ 5. Authorize with Facebook
332
+ 6. Popup should close and accounts appear
333
+
334
+ ### 7.2 Verify Database
335
+
336
+ ```sql
337
+ -- Check connected accounts
338
+ SELECT
339
+ id,
340
+ "parentId",
341
+ platform,
342
+ "platformAccountName",
343
+ "tokenExpiresAt",
344
+ "isActive"
345
+ FROM "clients_social_platforms"
346
+ WHERE "isActive" = true;
347
+
348
+ -- Check encrypted tokens (should have format: encrypted:iv:keyId)
349
+ SELECT
350
+ id,
351
+ LENGTH("accessToken") as token_length,
352
+ "accessToken" LIKE '%:%:%' as is_encrypted
353
+ FROM "clients_social_platforms";
354
+ ```
355
+
356
+ ### 7.3 Test Publishing
357
+
358
+ ```bash
359
+ # Test publish endpoint
360
+ curl -X POST http://localhost:5173/api/v1/plugin/social-media-publisher/social/publish \
361
+ -H "Content-Type: application/json" \
362
+ -H "Cookie: your-session-cookie" \
363
+ -d '{
364
+ "accountId": "social-platform-uuid",
365
+ "platform": "instagram_business",
366
+ "imageUrl": "https://example.com/image.jpg",
367
+ "caption": "Test post"
368
+ }'
369
+ ```
370
+
371
+ ## Troubleshooting
372
+
373
+ ### Issue: "Invalid OAuth Redirect URI"
374
+
375
+ **Cause:** Redirect URI not configured in Facebook App
376
+
377
+ **Solution:**
378
+ 1. Go to Facebook App → Facebook Login → Settings
379
+ 2. Add exact callback URL to "Valid OAuth Redirect URIs"
380
+ 3. Format: `https://yourdomain.com/api/v1/plugin/social-media-publisher/social/connect/callback`
381
+ 4. Save changes
382
+
383
+ ### Issue: "OAUTH_ENCRYPTION_KEY validation failed"
384
+
385
+ **Cause:** Missing or invalid encryption key
386
+
387
+ **Solution:**
388
+ ```bash
389
+ # Generate new key
390
+ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
391
+
392
+ # Add to .env (must be exactly 64 hex characters)
393
+ OAUTH_ENCRYPTION_KEY=generated_key_here
394
+
395
+ # Restart server
396
+ pnpm dev
397
+ ```
398
+
399
+ ### Issue: "No Instagram Business Account found"
400
+
401
+ **Cause:** Facebook Page not linked to Instagram Business Account
402
+
403
+ **Solution:**
404
+ 1. Go to Facebook Page Settings
405
+ 2. Click "Instagram" in sidebar
406
+ 3. Connect Instagram Business Account
407
+ 4. Verify connection:
408
+ ```bash
409
+ # Should show instagram_business_account field
410
+ curl "https://graph.facebook.com/v18.0/{PAGE_ID}?fields=instagram_business_account&access_token={TOKEN}"
411
+ ```
412
+
413
+ ### Issue: "Permission denied" during publish
414
+
415
+ **Cause:** Missing OAuth permissions
416
+
417
+ **Solution:**
418
+ 1. Disconnect and reconnect account (gets new permissions)
419
+ 2. Verify permissions in Facebook App Review
420
+ 3. Check RLS policies allow user to access client
421
+
422
+ ### Issue: "App not set up: This app is still in development mode"
423
+
424
+ **Cause:** Using app with non-admin users while in Development mode
425
+
426
+ **Solutions:**
427
+ - Add users as "Testers" or "Developers" in App Roles
428
+ - OR Switch app to Live mode (requires App Review)
429
+
430
+ ### Issue: "clients_social_platforms table does not exist"
431
+
432
+ **Cause:** Migrations not run
433
+
434
+ **Solution:**
435
+ ```bash
436
+ # Run migrations
437
+ pnpm db:migrate
438
+
439
+ # Or manually:
440
+ psql $DATABASE_URL -f contents/plugins/social-media-publisher/migrations/001_social_media_tables.sql
441
+ ```
442
+
443
+ ## Security Checklist
444
+
445
+ Before going to production, verify:
446
+
447
+ - [ ] `FACEBOOK_CLIENT_SECRET` not committed to git
448
+ - [ ] `OAUTH_ENCRYPTION_KEY` not committed to git
449
+ - [ ] `.env` in `.gitignore`
450
+ - [ ] Unique encryption key per environment
451
+ - [ ] HTTPS enabled in production
452
+ - [ ] RLS policies active on all tables
453
+ - [ ] Audit logging enabled
454
+ - [ ] Facebook App in Live mode with permissions approved
455
+ - [ ] Token encryption verified (check database format)
456
+ - [ ] Privacy policy URL added to Facebook App
457
+ - [ ] Terms of service URL added to Facebook App
458
+
459
+ ## Next Steps
460
+
461
+ ✅ Plugin installed and configured
462
+ ✅ Facebook App created and approved
463
+ ✅ Database tables created
464
+ ✅ OAuth flow tested
465
+ ✅ Publishing verified
466
+
467
+ **Continue to:**
468
+ - **[Configuration](./03-configuration.md)** - Detailed configuration options
469
+ - **[OAuth Integration](../02-core-features/01-oauth-integration.md)** - Understanding OAuth flow
470
+ - **[Publishing](../02-core-features/02-publishing.md)** - Start publishing content
471
+ - **[Per-Client Architecture](../03-advanced-usage/03-per-client-architecture.md)** - Understand the data model