-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
244 lines (204 loc) · 6.87 KB
/
Copy pathmiddleware.ts
File metadata and controls
244 lines (204 loc) · 6.87 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import {
SESSION_COOKIE_NAME,
SESSION_META_COOKIE_NAME,
SessionMeta,
} from '@/lib/session-constants';
import { isAdmin } from '@/lib/access-control';
import { NextRequest, NextResponse } from 'next/server';
const AGENT_DISCOVERY_LINKS = [
'</.well-known/api-catalog>; rel="api-catalog"; type="application/linkset+json"',
'</docs>; rel="service-doc"; type="text/html"',
'</.well-known/agent-skills/index.json>; rel="describedby"; type="application/json"',
'</.well-known/openapi.json>; rel="service-desc"; type="application/openapi+json"',
'</.well-known/openid-configuration>; rel="openid-configuration"; type="application/json"',
'</.well-known/oauth-protected-resource>; rel="oauth-protected-resource"; type="application/json"',
'</.well-known/mcp/server-card.json>; rel="describedby"; type="application/json"; title="MCP Server Card"',
].join(', ');
const HOME_MARKDOWN = `# CheFu Academy
CheFu Academy is an AI learning platform for guided courses, videos, quizzes, flashcards, and progress tracking.
## Key Resources
- [Courses](/courses)
- [Videos](/videos/all-videos)
- [Create a Course](/courses/create-course)
- [Developer Documentation](/docs)
- [API Catalog](/.well-known/api-catalog)
- [Agent Skills Index](/.well-known/agent-skills/index.json)
- [MCP Server Card](/.well-known/mcp/server-card.json)
## Agent Discovery
Agents can use the API catalog, service documentation, WebMCP tools, and published agent skills to discover CheFu Academy learning and developer workflows.
`;
const AUTH_ROUTES = ['/login', '/phone-number'];
const PROTECTED_PREFIXES = [
'/dashboard',
'/admin',
'/courses',
'/settings',
'/videos',
'/support',
'/feedback',
'/upgrade',
'/add-country',
];
const PUBLIC_APP_ROUTES = new Set([
'/videos/all-videos',
'/videos/beginner',
'/videos/advanced',
'/videos/search',
'/docs',
]);
function base64UrlToBytes(value: string) {
const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
const padded = base64.padEnd(
base64.length + ((4 - (base64.length % 4)) % 4),
'=',
);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function bytesToBase64Url(bytes: Uint8Array) {
let binary = '';
bytes.forEach(byte => {
binary += String.fromCharCode(byte);
});
return btoa(binary)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
}
function getSigningSecret() {
return (
process.env.AUTH_SESSION_SECRET ||
process.env.SESSION_COOKIE_SECRET ||
process.env.FIREBASE_SERVICE_ACCOUNT ||
''
);
}
async function verifySessionMeta(cookieValue?: string): Promise<SessionMeta | null> {
if (!cookieValue) return null;
const [payload, signature] = cookieValue.split('.');
const secret = getSigningSecret();
if (!payload || !signature || !secret) return null;
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
);
const signed = await crypto.subtle.sign(
'HMAC',
key,
new TextEncoder().encode(payload),
);
const expected = bytesToBase64Url(new Uint8Array(signed));
if (expected !== signature) return null;
const meta = JSON.parse(
new TextDecoder().decode(base64UrlToBytes(payload)),
) as SessionMeta;
if (!meta.exp || meta.exp <= Math.floor(Date.now() / 1000)) {
return null;
}
return meta;
}
function isProtectedPath(pathname: string) {
if (PUBLIC_APP_ROUTES.has(pathname)) {
return false;
}
return PROTECTED_PREFIXES.some(
prefix => pathname === prefix || pathname.startsWith(`${prefix}/`),
);
}
function redirectToLogin(request: NextRequest) {
const url = request.nextUrl.clone();
url.pathname = '/login';
url.searchParams.set('next', `${request.nextUrl.pathname}${request.nextUrl.search}`);
return NextResponse.redirect(url);
}
function markdownTokenCount(markdown: string) {
return String(markdown.trim().split(/\s+/).filter(Boolean).length);
}
function acceptsMarkdown(request: NextRequest) {
const accept = request.headers.get('accept') || '';
return accept
.split(',')
.map(value => value.trim().toLowerCase())
.some(value => value.startsWith('text/markdown'));
}
function withAgentDiscoveryHeaders(response: NextResponse) {
response.headers.set('Link', AGENT_DISCOVERY_LINKS);
return response;
}
function withRequestId(request: NextRequest, response: NextResponse) {
response.headers.set(
'x-request-id',
request.headers.get('x-request-id') || crypto.randomUUID(),
);
return response;
}
function markdownHomeResponse() {
return new NextResponse(HOME_MARKDOWN, {
headers: {
'Content-Type': 'text/markdown; charset=utf-8',
Link: AGENT_DISCOVERY_LINKS,
Vary: 'Accept',
'x-markdown-tokens': markdownTokenCount(HOME_MARKDOWN),
},
});
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const hasSessionCookie = Boolean(request.cookies.get(SESSION_COOKIE_NAME)?.value);
const sessionMeta = await verifySessionMeta(
request.cookies.get(SESSION_META_COOKIE_NAME)?.value,
);
const isSignedIn = hasSessionCookie && Boolean(sessionMeta);
if (pathname === '/') {
if (acceptsMarkdown(request)) {
return withRequestId(request, markdownHomeResponse());
}
const response = withAgentDiscoveryHeaders(NextResponse.next());
response.headers.set('Vary', 'Accept');
return withRequestId(request, response);
}
if (AUTH_ROUTES.includes(pathname) && isSignedIn) {
return withRequestId(
request,
NextResponse.redirect(new URL('/', request.url)),
);
}
if (!isProtectedPath(pathname)) {
return withRequestId(request, NextResponse.next());
}
if (!isSignedIn) {
return withRequestId(request, redirectToLogin(request));
}
if (pathname === '/admin' || pathname.startsWith('/admin/')) {
if (!isAdmin(sessionMeta?.roles)) {
return withRequestId(
request,
NextResponse.redirect(new URL('/not-admin', request.url)),
);
}
}
return withRequestId(request, NextResponse.next());
}
export const config = {
matcher: [
'/',
'/login',
'/phone-number',
'/dashboard/:path*',
'/admin/:path*',
'/courses/:path*',
'/settings/:path*',
'/videos/:path*',
'/support/:path*',
'/feedback',
'/upgrade',
'/add-country/:path*',
],
};