forked from boticlaw/SuperBotijo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
206 lines (181 loc) · 5.22 KB
/
middleware.ts
File metadata and controls
206 lines (181 loc) · 5.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { validateAgentAuth } from "@/lib/agent-auth";
import { jwtUtils } from "@/lib/jwt-utils";
import { isAdminRoute, isAdminFromToken } from "@/lib/role-based-access";
// Startup validation — ensures critical config is present
(() => {
const secret = process.env.JWT_SECRET;
if (!secret || secret.length < 32) {
console.error(
"❌ CRITICAL: JWT_SECRET environment variable must be set and at least 32 characters long."
);
throw new Error(
"JWT_SECRET not configured correctly. This is required for secure JWT signing."
);
}
console.log("✅ JWT_SECRET validated (" + secret.length + " characters)");
})();
// Routes that never require authentication
const PUBLIC_ROUTES = new Set(["/login"]);
// API routes that are always public (minimal surface)
const PUBLIC_API_ROUTES = new Set([
"/api/auth/login",
"/api/auth/logout",
"/api/health",
]);
// API routes requiring agent credentials ONLY (no browser session)
const AGENT_ONLY_API_PREFIXES = [
"/api/heartbeat",
"/api/config",
"/api/cron",
"/api/collect-usage",
"/api/terminal",
"/api/subagents",
"/api/handoffs",
"/api/logs",
"/api/sessions",
];
// API routes allowing agent credentials OR authenticated browser session
const AGENT_OR_SESSION_API_PREFIXES = [
"/api/agents",
"/api/files",
"/api/openclaw",
"/api/reports",
"/api/wiki",
"/api/skills",
"/api/integrations",
"/api/notifications",
"/api/projects",
"/api/learning",
"/api/media",
"/api/activities",
"/api/costs",
"/api/chat",
"/api/memory",
"/api/memories",
"/api/pipeline",
"/api/kanban",
"/api/gateway",
"/api/system",
"/api/telemetry",
"/api/performance",
"/api/analytics",
"/api/browse",
"/api/catalog",
"/api/search",
"/api/suggestions",
"/api/tasks",
"/api/actions",
"/api/journal",
"/api/models",
"/api/pricing",
"/api/weather",
"/api/office",
"/api/notepad",
"/api/morning",
"/api/realtime",
"/api/git",
"/api/live",
"/api/hindsight",
];
function extractToken(request: NextRequest): string | null {
// Check Authorization header first
const authHeader = request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
return authHeader.slice(7);
}
// Fall back to cookie (set by login API)
return request.cookies.get("auth_token")?.value ?? null;
}
async function isAuthenticated(request: NextRequest): Promise<boolean> {
const token = extractToken(request);
if (!token) {
return false;
}
return jwtUtils.isValidToken(token);
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Always allow public pages (login)
if (PUBLIC_ROUTES.has(pathname)) {
return NextResponse.next();
}
// Always allow explicit public API routes
if (PUBLIC_API_ROUTES.has(pathname)) {
return NextResponse.next();
}
// Agent-only API routes must use explicit agent credentials
if (AGENT_ONLY_API_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
const agentId = validateAgentAuth(request);
if (!agentId) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Valid X-Agent-Id and X-Agent-Key headers required",
},
{ status: 401 }
);
}
return NextResponse.next();
}
// Kanban agent endpoints allow either agent headers or authenticated session
if (AGENT_OR_SESSION_API_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
const agentId = validateAgentAuth(request);
if (agentId) {
return NextResponse.next();
}
if (!(await isAuthenticated(request))) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Valid X-Agent-Id and X-Agent-Key headers or authenticated session required",
},
{ status: 401 }
);
}
return NextResponse.next();
}
// Check authentication
if (!(await isAuthenticated(request))) {
// For API routes: return 401 JSON
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ error: "Unauthorized", message: "Authentication required" },
{ status: 401 }
);
}
// For page routes: redirect to login
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("from", pathname);
return NextResponse.redirect(loginUrl);
}
// Check admin access for admin routes
if (isAdminRoute(pathname)) {
const token = jwtUtils.getTokenFromRequest(request);
if (!token) {
return NextResponse.json(
{ error: "Forbidden", message: "Admin access required" },
{ status: 403 }
);
}
const isAdmin = await isAdminFromToken(token);
if (!isAdmin) {
// For API routes: return 403 JSON
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ error: "Forbidden", message: "Admin access required" },
{ status: 403 }
);
}
// For page routes: redirect to 403
return NextResponse.redirect(new URL("/forbidden", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|_next/webpack|favicon.ico|.*\\..*).*)",
],
};