@jhits/plugin-dep 0.0.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.
- package/package.json +48 -0
- package/src/actions.ts +765 -0
- package/src/config.ts +137 -0
- package/src/index.server.ts +18 -0
- package/src/index.ts +14 -0
- package/src/router.ts +387 -0
- package/src/types.ts +58 -0
- package/src/utils/auth.ts +20 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin Deprecated - Auto Setup
|
|
3
|
+
* Automatically creates API routes in the client app
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { writeFileSync, mkdirSync, existsSync } from 'fs';
|
|
7
|
+
import { join } from 'path';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Ensure the deprecated API route is set up in the client app
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* @deprecated Routes are now handled by the unified /api/[pluginId]/[...path]/route.ts
|
|
14
|
+
* This function is kept for backwards compatibility but does nothing
|
|
15
|
+
*/
|
|
16
|
+
export function ensureDepRoutes() {
|
|
17
|
+
// Routes are now handled by the unified /api/[pluginId]/[...path]/route.ts
|
|
18
|
+
// No need to generate individual routes anymore
|
|
19
|
+
return;
|
|
20
|
+
try {
|
|
21
|
+
// Find the host app directory (where next.config.ts is)
|
|
22
|
+
let appDir = process.cwd();
|
|
23
|
+
const possiblePaths = [
|
|
24
|
+
appDir,
|
|
25
|
+
join(appDir, '..'),
|
|
26
|
+
join(appDir, '..', '..'),
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
for (const basePath of possiblePaths) {
|
|
30
|
+
const configPath = join(basePath, 'next.config.ts');
|
|
31
|
+
if (existsSync(configPath)) {
|
|
32
|
+
appDir = basePath;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const apiDir = join(appDir, 'src', 'app', 'api');
|
|
38
|
+
const pluginDepApiDir = join(apiDir, 'plugin-dep', '[...path]');
|
|
39
|
+
const pluginDepApiPath = join(pluginDepApiDir, 'route.ts');
|
|
40
|
+
|
|
41
|
+
// Check if route already exists
|
|
42
|
+
if (existsSync(pluginDepApiPath)) {
|
|
43
|
+
const fs = require('fs');
|
|
44
|
+
const existingContent = fs.readFileSync(pluginDepApiPath, 'utf8');
|
|
45
|
+
if (existingContent.includes('@jhits/plugin-dep') || existingContent.includes('plugin-dep')) {
|
|
46
|
+
// Already set up, skip
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Create plugin-dep API catch-all route
|
|
52
|
+
mkdirSync(pluginDepApiDir, { recursive: true });
|
|
53
|
+
writeFileSync(pluginDepApiPath, `// Auto-generated by @jhits/plugin-dep - Deprecated API Plugin
|
|
54
|
+
// This route is automatically created for the deprecated API plugin
|
|
55
|
+
import { NextRequest } from 'next/server';
|
|
56
|
+
import { handleDepApi } from '@jhits/plugin-dep';
|
|
57
|
+
import clientPromise from '@/lib/mongodb';
|
|
58
|
+
import { authOptions } from '@jhits/dashboard/lib/auth';
|
|
59
|
+
import { join } from 'path';
|
|
60
|
+
|
|
61
|
+
export const dynamic = 'force-dynamic';
|
|
62
|
+
|
|
63
|
+
async function getConfig() {
|
|
64
|
+
return {
|
|
65
|
+
mongoClient: clientPromise,
|
|
66
|
+
jwtSecret: process.env.JWT_SECRET || 'secret',
|
|
67
|
+
authOptions,
|
|
68
|
+
emailConfig: process.env.EMAIL_SERVER_HOST ? {
|
|
69
|
+
host: process.env.EMAIL_SERVER_HOST,
|
|
70
|
+
port: Number(process.env.EMAIL_SERVER_PORT || 465),
|
|
71
|
+
user: process.env.EMAIL_SERVER_USER || '',
|
|
72
|
+
password: process.env.EMAIL_SERVER_PASSWORD || '',
|
|
73
|
+
from: process.env.EMAIL_FROM || '',
|
|
74
|
+
} : undefined,
|
|
75
|
+
baseUrl: process.env.NEXT_PUBLIC_BASE_URL,
|
|
76
|
+
githubWebhookSecret: process.env.GITHUB_WEBHOOK_SECRET,
|
|
77
|
+
deploymentPaths: {
|
|
78
|
+
flagPath: process.env.DEPLOYMENT_FLAG_PATH || '/home/pi/botanics/update-pending.json',
|
|
79
|
+
scriptPath: process.env.DEPLOYMENT_SCRIPT_PATH || '/home/pi/botanics/scripts/update.sh',
|
|
80
|
+
},
|
|
81
|
+
localesDir: process.env.LOCALES_DIR || join(process.cwd(), 'data/locales'),
|
|
82
|
+
uploadsDir: process.env.UPLOADS_DIR || join(process.cwd(), 'data/uploads'),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function GET(
|
|
87
|
+
req: NextRequest,
|
|
88
|
+
{ params }: { params: Promise<{ path: string[] }> }
|
|
89
|
+
) {
|
|
90
|
+
const { path } = await params;
|
|
91
|
+
const config = await getConfig();
|
|
92
|
+
return handleDepApi(req, path, config);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function POST(
|
|
96
|
+
req: NextRequest,
|
|
97
|
+
{ params }: { params: Promise<{ path: string[] }> }
|
|
98
|
+
) {
|
|
99
|
+
const { path } = await params;
|
|
100
|
+
const config = await getConfig();
|
|
101
|
+
return handleDepApi(req, path, config);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function PUT(
|
|
105
|
+
req: NextRequest,
|
|
106
|
+
{ params }: { params: Promise<{ path: string[] }> }
|
|
107
|
+
) {
|
|
108
|
+
const { path } = await params;
|
|
109
|
+
const config = await getConfig();
|
|
110
|
+
return handleDepApi(req, path, config);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function PATCH(
|
|
114
|
+
req: NextRequest,
|
|
115
|
+
{ params }: { params: Promise<{ path: string[] }> }
|
|
116
|
+
) {
|
|
117
|
+
const { path } = await params;
|
|
118
|
+
const config = await getConfig();
|
|
119
|
+
return handleDepApi(req, path, config);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function DELETE(
|
|
123
|
+
req: NextRequest,
|
|
124
|
+
{ params }: { params: Promise<{ path: string[] }> }
|
|
125
|
+
) {
|
|
126
|
+
const { path } = await params;
|
|
127
|
+
const config = await getConfig();
|
|
128
|
+
return handleDepApi(req, path, config);
|
|
129
|
+
}
|
|
130
|
+
`);
|
|
131
|
+
|
|
132
|
+
} catch (error) {
|
|
133
|
+
// Ignore errors - route might already exist or app structure is different
|
|
134
|
+
console.warn('[plugin-dep] Could not ensure deprecated routes:', error);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin Deprecated - Server-Only Entry Point
|
|
3
|
+
* Re-exports server-side API handlers and business logic
|
|
4
|
+
*
|
|
5
|
+
* Note: This file is server-only (no 'use server' needed - that's only for Server Actions)
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// Export router (main API handler)
|
|
9
|
+
export { handleDepApi as handleApi } from './router';
|
|
10
|
+
|
|
11
|
+
// Export actions (business logic)
|
|
12
|
+
export * as actions from './actions';
|
|
13
|
+
|
|
14
|
+
// Export types
|
|
15
|
+
export * from './types';
|
|
16
|
+
|
|
17
|
+
// Note: Config functions are server-only and not exported to avoid client-side import errors
|
|
18
|
+
// They are deprecated anyway since routes are now handled by the unified route system
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin Deprecated - Root Entry Point
|
|
3
|
+
*
|
|
4
|
+
* NOTE: This plugin is SERVER-ONLY and has no client UI.
|
|
5
|
+
*
|
|
6
|
+
* This file exists only to satisfy package.json "main" field requirements.
|
|
7
|
+
* It should NEVER be imported by client code.
|
|
8
|
+
*
|
|
9
|
+
* For server-side usage, ALWAYS import from '@jhits/plugin-dep/server' instead.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// Empty export - this plugin has no client-side code
|
|
13
|
+
// Importing this will result in an empty module
|
|
14
|
+
// Use '@jhits/plugin-dep/server' for server-side imports
|
package/src/router.ts
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
'use server';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Plugin Deprecated - Router
|
|
5
|
+
* Framework-agnostic router that routes API requests to business logic actions
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
9
|
+
import { DepApiConfig } from './types';
|
|
10
|
+
import * as actions from './actions';
|
|
11
|
+
import { verifyToken } from './utils/auth';
|
|
12
|
+
import crypto from 'crypto';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Handle deprecated API requests
|
|
16
|
+
* Routes requests to appropriate action handlers based on path and method
|
|
17
|
+
*/
|
|
18
|
+
export async function handleDepApi(
|
|
19
|
+
req: NextRequest,
|
|
20
|
+
path: string[],
|
|
21
|
+
config: DepApiConfig
|
|
22
|
+
): Promise<NextResponse> {
|
|
23
|
+
const method = req.method;
|
|
24
|
+
const route = path[0] || '';
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
// ====================================================================
|
|
28
|
+
// AUTH ROUTES
|
|
29
|
+
// ====================================================================
|
|
30
|
+
if (route === 'me') {
|
|
31
|
+
if (method === 'GET') {
|
|
32
|
+
let session: any = null;
|
|
33
|
+
if (config.authOptions) {
|
|
34
|
+
const { getServerSession } = await import('next-auth');
|
|
35
|
+
session = await getServerSession(config.authOptions);
|
|
36
|
+
}
|
|
37
|
+
const result = await actions.getMe(config, session);
|
|
38
|
+
return NextResponse.json(result);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ====================================================================
|
|
43
|
+
// FEEDBACK ROUTES
|
|
44
|
+
// ====================================================================
|
|
45
|
+
else if (route === 'feedback') {
|
|
46
|
+
if (path[1]) {
|
|
47
|
+
// /api/plugin-dep/feedback/[id]
|
|
48
|
+
const id = path[1];
|
|
49
|
+
if (method === 'PATCH') {
|
|
50
|
+
const body = await req.json();
|
|
51
|
+
const result = await actions.updateFeedback(config, id, body);
|
|
52
|
+
return NextResponse.json(result);
|
|
53
|
+
} else if (method === 'DELETE') {
|
|
54
|
+
const result = await actions.deleteFeedback(config, id);
|
|
55
|
+
return NextResponse.json(result);
|
|
56
|
+
}
|
|
57
|
+
} else {
|
|
58
|
+
// /api/plugin-dep/feedback
|
|
59
|
+
if (method === 'GET') {
|
|
60
|
+
const result = await actions.listFeedback(config);
|
|
61
|
+
return NextResponse.json(result);
|
|
62
|
+
} else if (method === 'POST') {
|
|
63
|
+
const body = await req.json();
|
|
64
|
+
const cookies = await req.cookies;
|
|
65
|
+
const token = cookies.get('auth_token')?.value;
|
|
66
|
+
let userId: string | undefined;
|
|
67
|
+
if (token) {
|
|
68
|
+
const payload = verifyToken(token, config.jwtSecret);
|
|
69
|
+
if (payload && typeof payload !== 'string') {
|
|
70
|
+
userId = payload.id;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const result = await actions.createFeedback(config, body, userId);
|
|
74
|
+
return NextResponse.json(result);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ====================================================================
|
|
80
|
+
// SETTINGS ROUTES
|
|
81
|
+
// ====================================================================
|
|
82
|
+
else if (route === 'settings') {
|
|
83
|
+
if (path[1] === 'maintenance') {
|
|
84
|
+
// /api/plugin-dep/settings/maintenance
|
|
85
|
+
if (method === 'GET') {
|
|
86
|
+
const result = await actions.getMaintenanceMode(config);
|
|
87
|
+
return NextResponse.json(result);
|
|
88
|
+
} else if (method === 'POST') {
|
|
89
|
+
const body = await req.json();
|
|
90
|
+
const result = await actions.setMaintenanceMode(config, body.active);
|
|
91
|
+
return NextResponse.json(result);
|
|
92
|
+
}
|
|
93
|
+
} else {
|
|
94
|
+
// /api/plugin-dep/settings
|
|
95
|
+
if (method === 'GET') {
|
|
96
|
+
const result = await actions.getSettings(config);
|
|
97
|
+
return NextResponse.json(result);
|
|
98
|
+
} else if (method === 'POST') {
|
|
99
|
+
const body = await req.json();
|
|
100
|
+
const result = await actions.updateSettings(config, body);
|
|
101
|
+
return NextResponse.json(result);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ====================================================================
|
|
107
|
+
// USER ROUTES
|
|
108
|
+
// ====================================================================
|
|
109
|
+
else if (route === 'users') {
|
|
110
|
+
if (path[1]) {
|
|
111
|
+
// /api/plugin-dep/users/[id]
|
|
112
|
+
const id = path[1];
|
|
113
|
+
if (method === 'PATCH') {
|
|
114
|
+
const body = await req.json();
|
|
115
|
+
const result = await actions.updateUser(config, id, body);
|
|
116
|
+
return NextResponse.json(result);
|
|
117
|
+
} else if (method === 'DELETE') {
|
|
118
|
+
const result = await actions.deleteUser(config, id);
|
|
119
|
+
return NextResponse.json(result);
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
// /api/plugin-dep/users
|
|
123
|
+
if (method === 'GET') {
|
|
124
|
+
const result = await actions.listUsers(config);
|
|
125
|
+
return NextResponse.json(result);
|
|
126
|
+
} else if (method === 'POST') {
|
|
127
|
+
const body = await req.json();
|
|
128
|
+
const result = await actions.createUser(config, body);
|
|
129
|
+
return NextResponse.json(result);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ====================================================================
|
|
135
|
+
// NEWSLETTER ROUTES
|
|
136
|
+
// ====================================================================
|
|
137
|
+
else if (route === 'newsletter') {
|
|
138
|
+
if (path[1] === 'subscribers') {
|
|
139
|
+
if (path[2]) {
|
|
140
|
+
// /api/plugin-dep/newsletter/subscribers/[user]
|
|
141
|
+
const email = decodeURIComponent(path[2]).toLowerCase();
|
|
142
|
+
if (method === 'GET') {
|
|
143
|
+
const result = await actions.getSubscriber(config, email);
|
|
144
|
+
return NextResponse.json(result);
|
|
145
|
+
} else if (method === 'DELETE') {
|
|
146
|
+
const result = await actions.deleteSubscriber(config, email);
|
|
147
|
+
return NextResponse.json(result);
|
|
148
|
+
}
|
|
149
|
+
} else {
|
|
150
|
+
// /api/plugin-dep/newsletter/subscribers
|
|
151
|
+
if (method === 'GET') {
|
|
152
|
+
const result = await actions.listSubscribers(config);
|
|
153
|
+
return NextResponse.json(result);
|
|
154
|
+
} else if (method === 'POST') {
|
|
155
|
+
const body = await req.json();
|
|
156
|
+
const headers = await req.headers;
|
|
157
|
+
const host = headers.get('host') || undefined;
|
|
158
|
+
const result = await actions.subscribeNewsletter(config, body, host);
|
|
159
|
+
return NextResponse.json(result, { status: 201 });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
} else if (path[1] === 'settings') {
|
|
163
|
+
// /api/plugin-dep/newsletter/settings
|
|
164
|
+
if (method === 'GET') {
|
|
165
|
+
const result = await actions.getNewsletterSettings(config);
|
|
166
|
+
return NextResponse.json(result);
|
|
167
|
+
} else if (method === 'POST') {
|
|
168
|
+
const body = await req.json();
|
|
169
|
+
const result = await actions.updateNewsletterSettings(config, body);
|
|
170
|
+
return NextResponse.json(result);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ====================================================================
|
|
176
|
+
// NOTIFICATIONS ROUTES
|
|
177
|
+
// ====================================================================
|
|
178
|
+
else if (route === 'notifications') {
|
|
179
|
+
if (path[1] === 'stream') {
|
|
180
|
+
// /api/plugin-dep/notifications/stream
|
|
181
|
+
if (method === 'GET') {
|
|
182
|
+
return handleNotificationStream(req, config);
|
|
183
|
+
}
|
|
184
|
+
} else if (path[1] === 'action') {
|
|
185
|
+
// /api/plugin-dep/notifications/action
|
|
186
|
+
if (method === 'POST') {
|
|
187
|
+
const body = await req.json();
|
|
188
|
+
const cookies = await req.cookies;
|
|
189
|
+
const token = cookies.get('auth_token')?.value;
|
|
190
|
+
if (!token) {
|
|
191
|
+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
192
|
+
}
|
|
193
|
+
const payload = verifyToken(token, config.jwtSecret);
|
|
194
|
+
if (!payload || typeof payload === 'string') {
|
|
195
|
+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
196
|
+
}
|
|
197
|
+
const result = await actions.updateNotification(config, body, payload.id);
|
|
198
|
+
return NextResponse.json(result);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ====================================================================
|
|
204
|
+
// TRANSLATION ROUTES
|
|
205
|
+
// ====================================================================
|
|
206
|
+
else if (route === 'save-translation') {
|
|
207
|
+
if (method === 'POST') {
|
|
208
|
+
const body = await req.json();
|
|
209
|
+
const result = await actions.saveTranslation(config, body);
|
|
210
|
+
return NextResponse.json(result);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ====================================================================
|
|
215
|
+
// STATS ROUTES
|
|
216
|
+
// ====================================================================
|
|
217
|
+
else if (route === 'stats') {
|
|
218
|
+
if (path[1] === 'storage') {
|
|
219
|
+
// /api/plugin-dep/stats/storage
|
|
220
|
+
if (method === 'GET') {
|
|
221
|
+
const result = await actions.getStorageStats(config);
|
|
222
|
+
return NextResponse.json(result);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
} else if (route === 'media') {
|
|
226
|
+
if (path[1] === 'stats') {
|
|
227
|
+
// /api/plugin-dep/media/stats
|
|
228
|
+
if (method === 'GET') {
|
|
229
|
+
const result = await actions.getMediaStats(config);
|
|
230
|
+
return NextResponse.json(result);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ====================================================================
|
|
236
|
+
// VERSION ROUTES
|
|
237
|
+
// ====================================================================
|
|
238
|
+
else if (route === 'version') {
|
|
239
|
+
if (method === 'GET') {
|
|
240
|
+
const result = await actions.getVersion();
|
|
241
|
+
return NextResponse.json(result);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ====================================================================
|
|
246
|
+
// GITHUB DEPLOYMENT ROUTES
|
|
247
|
+
// ====================================================================
|
|
248
|
+
else if (route === 'github') {
|
|
249
|
+
if (path[1] === 'deploy') {
|
|
250
|
+
// /api/plugin-dep/github/deploy
|
|
251
|
+
if (method === 'GET') {
|
|
252
|
+
const result = await actions.getDeploymentStatus(config);
|
|
253
|
+
return NextResponse.json(result);
|
|
254
|
+
} else if (method === 'POST') {
|
|
255
|
+
const signature = req.headers.get('x-hub-signature-256') || '';
|
|
256
|
+
let payload: any = null;
|
|
257
|
+
if (signature !== 'manual') {
|
|
258
|
+
const rawBody = await req.text();
|
|
259
|
+
const secret = config.githubWebhookSecret;
|
|
260
|
+
if (!secret) {
|
|
261
|
+
return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
|
|
262
|
+
}
|
|
263
|
+
const hmac = crypto.createHmac('sha256', secret);
|
|
264
|
+
const digest = 'sha256=' + hmac.update(rawBody).digest('hex');
|
|
265
|
+
if (signature !== digest) {
|
|
266
|
+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
267
|
+
}
|
|
268
|
+
payload = rawBody.startsWith('payload=')
|
|
269
|
+
? JSON.parse(decodeURIComponent(rawBody.substring(8)))
|
|
270
|
+
: JSON.parse(rawBody);
|
|
271
|
+
}
|
|
272
|
+
const result = await actions.triggerDeployment(config, signature, payload);
|
|
273
|
+
return NextResponse.json(result);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Method not allowed
|
|
279
|
+
return NextResponse.json(
|
|
280
|
+
{ error: `Method ${method} not allowed for route: ${route || '/'}` },
|
|
281
|
+
{ status: 405 }
|
|
282
|
+
);
|
|
283
|
+
} catch (error: any) {
|
|
284
|
+
console.error('[DepApiRouter] Error:', error);
|
|
285
|
+
const status = error.message?.includes('not found') ? 404
|
|
286
|
+
: error.message?.includes('Unauthorized') ? 401
|
|
287
|
+
: error.message?.includes('already') ? 409
|
|
288
|
+
: error.message?.includes('too short') ? 400
|
|
289
|
+
: 500;
|
|
290
|
+
return NextResponse.json(
|
|
291
|
+
{ error: error.message || 'Internal server error' },
|
|
292
|
+
{ status }
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Handle Server-Sent Events stream for notifications
|
|
299
|
+
*/
|
|
300
|
+
async function handleNotificationStream(
|
|
301
|
+
req: NextRequest,
|
|
302
|
+
config: DepApiConfig
|
|
303
|
+
): Promise<NextResponse> {
|
|
304
|
+
const encoder = new TextEncoder();
|
|
305
|
+
const cookies = await req.cookies;
|
|
306
|
+
const token = cookies.get('auth_token')?.value;
|
|
307
|
+
|
|
308
|
+
let userRole = 'guest';
|
|
309
|
+
let currentUserId: string | null = null;
|
|
310
|
+
|
|
311
|
+
if (token) {
|
|
312
|
+
try {
|
|
313
|
+
const payload = verifyToken(token, config.jwtSecret);
|
|
314
|
+
if (payload && typeof payload !== 'string') {
|
|
315
|
+
userRole = payload.role || 'guest';
|
|
316
|
+
currentUserId = payload.id;
|
|
317
|
+
}
|
|
318
|
+
} catch (e) {
|
|
319
|
+
console.error('Token verification failed in stream');
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
let changeStream: any;
|
|
324
|
+
|
|
325
|
+
const stream = new ReadableStream({
|
|
326
|
+
async start(controller) {
|
|
327
|
+
try {
|
|
328
|
+
const client = await config.mongoClient;
|
|
329
|
+
const db = client.db();
|
|
330
|
+
const collection = db.collection('notifications');
|
|
331
|
+
|
|
332
|
+
const streamData = await actions.getNotificationStream(config, userRole, currentUserId);
|
|
333
|
+
|
|
334
|
+
// Send history
|
|
335
|
+
streamData.history.forEach((notif) => {
|
|
336
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(notif)}\n\n`));
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
// Send connection status
|
|
340
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'connected', role: userRole })}\n\n`));
|
|
341
|
+
|
|
342
|
+
// Watch for changes
|
|
343
|
+
changeStream = collection.watch(streamData.pipeline, { fullDocument: 'updateLookup' });
|
|
344
|
+
|
|
345
|
+
changeStream.on('change', (change: any) => {
|
|
346
|
+
if (change.operationType === 'insert') {
|
|
347
|
+
const data = `data: ${JSON.stringify(change.fullDocument)}\n\n`;
|
|
348
|
+
controller.enqueue(encoder.encode(data));
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const keepAlive = setInterval(() => {
|
|
353
|
+
try {
|
|
354
|
+
controller.enqueue(encoder.encode(': keep-alive\n\n'));
|
|
355
|
+
} catch {
|
|
356
|
+
clearInterval(keepAlive);
|
|
357
|
+
}
|
|
358
|
+
}, 20000);
|
|
359
|
+
|
|
360
|
+
changeStream.on('error', (err: any) => {
|
|
361
|
+
console.error('Mongo Stream Error:', err);
|
|
362
|
+
clearInterval(keepAlive);
|
|
363
|
+
if (changeStream) changeStream.close();
|
|
364
|
+
});
|
|
365
|
+
} catch (err) {
|
|
366
|
+
console.error('Stream Start Error:', err);
|
|
367
|
+
controller.error(err);
|
|
368
|
+
}
|
|
369
|
+
},
|
|
370
|
+
cancel() {
|
|
371
|
+
if (changeStream) {
|
|
372
|
+
changeStream.close();
|
|
373
|
+
console.log(`Stream connection closed for role: ${userRole}`);
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
return new NextResponse(stream, {
|
|
379
|
+
headers: {
|
|
380
|
+
'Content-Type': 'text/event-stream',
|
|
381
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
382
|
+
Connection: 'keep-alive',
|
|
383
|
+
'X-Accel-Buffering': 'no',
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin Deprecated - Types
|
|
3
|
+
* Type definitions for deprecated client API routes
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { MongoClient } from 'mongodb';
|
|
7
|
+
import { NextRequest } from 'next/server';
|
|
8
|
+
|
|
9
|
+
export interface DepApiConfig {
|
|
10
|
+
/** MongoDB client promise */
|
|
11
|
+
mongoClient: Promise<MongoClient>;
|
|
12
|
+
/** JWT secret for token verification */
|
|
13
|
+
jwtSecret: string;
|
|
14
|
+
/** NextAuth auth options (for session-based auth) */
|
|
15
|
+
authOptions?: any;
|
|
16
|
+
/** Email configuration for newsletter */
|
|
17
|
+
emailConfig?: {
|
|
18
|
+
host: string;
|
|
19
|
+
port: number;
|
|
20
|
+
user: string;
|
|
21
|
+
password: string;
|
|
22
|
+
from: string;
|
|
23
|
+
};
|
|
24
|
+
/** Base URL for email links */
|
|
25
|
+
baseUrl?: string;
|
|
26
|
+
/** GitHub webhook secret */
|
|
27
|
+
githubWebhookSecret?: string;
|
|
28
|
+
/** Paths for deployment scripts */
|
|
29
|
+
deploymentPaths?: {
|
|
30
|
+
flagPath: string;
|
|
31
|
+
scriptPath: string;
|
|
32
|
+
};
|
|
33
|
+
/** Locales directory path */
|
|
34
|
+
localesDir?: string;
|
|
35
|
+
/** Uploads directory path */
|
|
36
|
+
uploadsDir?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ApiRequest {
|
|
40
|
+
method: string;
|
|
41
|
+
url: string;
|
|
42
|
+
body?: any;
|
|
43
|
+
headers: Headers;
|
|
44
|
+
cookies?: Map<string, string>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ApiResponse {
|
|
48
|
+
status: number;
|
|
49
|
+
body: any;
|
|
50
|
+
headers?: Record<string, string>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type ApiHandler = (
|
|
54
|
+
req: ApiRequest,
|
|
55
|
+
config: DepApiConfig,
|
|
56
|
+
params?: Record<string, string>
|
|
57
|
+
) => Promise<ApiResponse>;
|
|
58
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth utilities for plugin-dep
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import jwt from 'jsonwebtoken';
|
|
6
|
+
|
|
7
|
+
export interface AuthPayload {
|
|
8
|
+
id: string;
|
|
9
|
+
email: string;
|
|
10
|
+
role: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function verifyToken(token: string, secret: string): AuthPayload | null {
|
|
14
|
+
try {
|
|
15
|
+
return jwt.verify(token, secret) as AuthPayload;
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|