Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
227 lines (202 loc) · 8.62 KB
/
Copy pathproxy.ts
File metadata and controls
227 lines (202 loc) · 8.62 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
/**
* @fileoverview
* Next.js Proxy entrypoint.
*
* Starting in **Next.js 16**, `proxy.ts` is the new name for what used to be
* `middleware.ts` (same runtime + semantics) — it is *not* a custom concept in
* this repo. Keep implementing and maintaining this file exactly as we would
* have done in `middleware.ts`.
*
* Reference: https://nextjs.org/docs/app/getting-started/proxy
*/
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { apiPolicy } from "./lib/api/policy";
const IS_PROD = process.env.NODE_ENV === "production";
const IS_DEV = process.env.NODE_ENV === "development";
if (!process.env.NEXT_PUBLIC_SUPABASE_URL) {
console.warn(
"[CONTRIBUTER MODE]: Supabase Backedn is not configured - some feature may restricted"
);
}
// GRIDA-SEC-004 — desktop CSP lives in ./lib/desktop/csp (Next.js 16 forbids
// extra exports from this proxy entrypoint). `buildDesktopCsp` interpolates the
// per-request nonce into a hoisted template.
type DesktopHeaderState = {
isDesktop: boolean;
csp?: string;
requestHeaders?: Headers;
};
async function prepareDesktopHeaders(
req: NextRequest
): Promise<DesktopHeaderState> {
const isDesktop =
req.nextUrl.pathname === "/desktop" ||
req.nextUrl.pathname.startsWith("/desktop/");
if (!isDesktop) return { isDesktop };
const isPrefetch =
req.headers.get("next-router-prefetch") !== null ||
req.headers.get("purpose") === "prefetch";
if (isPrefetch) return { isDesktop };
const { buildDesktopCsp } = await import("./lib/desktop/csp");
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const csp = buildDesktopCsp(nonce);
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-nonce", nonce);
requestHeaders.set("Content-Security-Policy", csp);
return { isDesktop, csp, requestHeaders };
}
function applyDesktopResponseHeaders(res: NextResponse, csp?: string): void {
if (csp) {
res.headers.set("Content-Security-Policy", csp);
}
res.headers.set("X-Robots-Tag", "noindex, nofollow");
res.headers.set("Referrer-Policy", "no-referrer");
res.headers.set("X-Content-Type-Options", "nosniff");
}
export async function proxy(req: NextRequest) {
// GRIDA-SEC-012 — machine dispatch precedes all browser/tenant work.
// Admission here grants no identity; each registered handler authenticates
// using its own declared credential family.
if (apiPolicy.matches(req.nextUrl.pathname)) {
return apiPolicy.respond(req) ?? NextResponse.next({ request: req });
}
// Canonical source bridge authenticates its dedicated workload in the route.
// No browser session refresh, tenant routing or cookie authority applies.
if (
req.nextUrl.pathname.startsWith("/internal/platform/accounts/") ||
req.nextUrl.pathname.startsWith("/internal/platform/products/")
) {
return NextResponse.next({ request: req });
}
// Check if the request path starts with /dev/ and NODE_ENV is not development
if (req.nextUrl.pathname.startsWith("/dev/") && !IS_DEV) {
return new NextResponse("Not Found", { status: 404 });
}
// GRIDA-SEC-002 —
// see editor/app/(insiders)/layout.tsx and /SECURITY.md.
//
// The `(insiders)` route group is a developer harness with intentionally
// unauthenticated server actions (mutators that take an arbitrary
// `organizationId` as the first argument). It MUST NOT be reachable from
// any non-development environment. Block both page loads and server-action
// POSTs at the proxy — the gate runs before any handler, so this also
// covers `Next-Action` invocations against `/insiders/*`.
if (
(req.nextUrl.pathname === "/insiders" ||
req.nextUrl.pathname.startsWith("/insiders/")) &&
!IS_DEV
) {
return new NextResponse("Not Found", { status: 404 });
}
// GRIDA-SEC-001 — retired machine ingress must never reach a handler.
if (
req.nextUrl.pathname === "/webhooks" ||
req.nextUrl.pathname.startsWith("/webhooks/")
) {
return new NextResponse("Not Found", { status: 404 });
}
// #region maintenance mode
if (IS_PROD) {
try {
// Edge Config value reused per server instance; see the module for scope,
// TTL configuration and error behavior.
const { isInMaintenanceMode } =
await import("./lib/maintenance/server-instance-cache");
// If is in maintenance mode, point the url pathname to the maintenance page
if (await isInMaintenanceMode()) {
req.nextUrl.pathname = `/maintenance`;
// Rewrite to the url
return NextResponse.rewrite(req.nextUrl);
}
} catch (error) {
// show the default page if EDGE_CONFIG env var is missing,
// but log the error to the console
console.error(error);
}
}
// #endregion maintenance mode
// GRIDA-SEC-004 — Desktop services sidecar trust boundary.
//
// Every `/desktop/*` response carries a strict CSP that blocks
// third-party scripts (analytics, sentry, marketing tags) from
// running inside the desktop renderer. Without this, an XSS in a
// future third-party include — or in user-generated content rendered
// through grida.co — could call `window.grida.*` and reach the
// services sidecar. Headers are scoped to `/desktop/*`; the rest of grida.co
// is unaffected — the per-request work below runs only when
// `isDesktop` holds, so non-desktop requests pay only one pathname
// compare on this proxy.
//
// We follow Next.js's canonical **nonce + `'strict-dynamic'`** pattern
// (see https://nextjs.org/docs/app/guides/content-security-policy).
// Next.js's own hydration scripts (`self.__next_f.push(...)`,
// `self.__next_r`, the dev-mode reload runtime) are inline — without
// a nonce they violate `script-src`, hydration aborts, and the
// renderer is stuck on the server snapshot (which for `/desktop/*`
// routes is the `<OpenInDesktopCta />` fallback, since the bridge
// gate's server snapshot is `null`).
//
// The nonce is generated here, exposed to the SSR pass via the
// `x-nonce` request header, and Next.js attaches it to every
// framework script automatically. `'strict-dynamic'` then lets those
// trusted scripts load further scripts without each needing its own
// nonce.
//
// The other GRIDA-SEC-004 layers (path-scoped preload,
// `contextIsolation: true`, services sidecar Basic Auth, services sidecar Referer check)
// remain load-bearing; CSP is one layer, not the only boundary.
const desktopHeaders = await prepareDesktopHeaders(req);
let res: NextResponse;
// ------------------------------------------------------------
// contributor dx
const env_not_set_but_can_skip_on_local_dev =
process.env.NODE_ENV === "development" &&
(!process.env.NEXT_PUBLIC_SUPABASE_URL ||
!process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY);
const publicMetadataRead =
(req.method === "GET" || req.method === "HEAD") &&
(req.nextUrl.pathname === "/ai/models" ||
req.nextUrl.pathname === "/ai/models/feed" ||
req.nextUrl.pathname === "/desktop/compatibility");
// Public metadata never depends on identity/session refresh. Maintenance and
// tenant-host routing still apply; this grants no execution/account authority.
if (publicMetadataRead || env_not_set_but_can_skip_on_local_dev) {
res = NextResponse.next({
request: desktopHeaders.requestHeaders
? { headers: desktopHeaders.requestHeaders }
: req,
});
if (!publicMetadataRead) {
console.warn(
"SUPABASE_URL or SUPABASE_PUBLISHABLE_KEY is not set this will break all db-requests, please set them in the .env.local file",
"If you are just testing things around, you can ignore this message",
"Learn more at https://github.com/gridaco/grida/blob/main/CONTRIBUTING.md"
);
}
} else {
const { updateSession } = await import("./lib/supabase/proxy");
res = await updateSession(req, desktopHeaders.requestHeaders);
}
// ------------------------------------------------------------
const { TenantMiddleware } = await import("./lib/tenant/middleware");
const routed = await TenantMiddleware.routeProxyRequest(req, res);
if (routed) return routed;
if (desktopHeaders.isDesktop) {
applyDesktopResponseHeaders(res, desktopHeaders.csp);
}
return res;
}
// Ensure the middleware is only called for relevant paths.
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - monitoring (sentry telemetry)
*/
"/((?!_next/static|_next/image|favicon.ico|monitoring).*)",
],
};