Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
183 lines (167 loc) · 10 KB
/
Copy pathproxy.ts
File metadata and controls
183 lines (167 loc) · 10 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
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { clerkMiddleware, type ClerkMiddlewareAuth } from "@clerk/nextjs/server";
import { fetchQuery } from "convex/nextjs";
import { api } from "@/convex/_generated/api";
import { inFlow, isPage, SETUP_DONE_COOKIE, SETUP_HEADER, SETUP_PATH } from "@/lib/profile/setup";
import { locales } from "@/i18n/config";
import { detectLocaleFromAcceptLanguage } from "@/i18n/locale-detection";
import { languageFromLink } from "@/i18n/link-language";
import { shouldProtectPath } from "@/lib/auth/proxy-policy";
import { isPublicFile } from "@/lib/auth/public-routes";
import { bareWorkLink } from "@/lib/search-params/bare-work-link";
import { LOOK_COOKIE, readCache, slugOf, WORKSPACE_HEADER } from "@/lib/workspaces/look-cache";
import { ADDRESS_HEADER, startIn } from "@/lib/workspaces/paths";
import { CITATION_FILES, type CitationFile } from "@/lib/citations/formats";
import { citeFilePath } from "@/lib/papers/page-address";
import { LINKED_CODE_COOKIE, LINKED_CODE_MAX_AGE, linkedCode } from "@/lib/reports/linked-code";
const COOKIE_NAME = "NEXT_LOCALE";
const ONE_YEAR = 60 * 60 * 24 * 365;
const authMiddleware = clerkMiddleware(
async (auth, request) => {
if (shouldProtectPath(request.nextUrl.pathname)) {
await auth.protect();
}
// Someone who arrives at the home page, a search or a new report starts in the organization they used last.
const start = await lastWorkspaceStart(auth, request);
if (start) return NextResponse.redirect(new URL(start, request.url));
// The workspace the address is in, for the root layout, which gets no route params: it draws
// the rail as that workspace looked last time (lib/workspaces/look-cache.ts).
const headers = new Headers(request.headers);
headers.set(WORKSPACE_HEADER, slugOf(request.nextUrl.pathname) ?? "");
// And the address itself, for an organization's layout to send someone outside it to the same page in their own workspace.
headers.set(ADDRESS_HEADER, request.nextUrl.pathname + request.nextUrl.search);
// Only this proxy says a page is the profile setup.
headers.delete(SETUP_HEADER);
const setup = await profileSetup(auth, request);
if (setup.due) {
// The page asked for is never rendered, so none of its code runs; the address stays as it is.
headers.set(SETUP_HEADER, "due");
return NextResponse.rewrite(new URL(SETUP_PATH, request.url), { request: { headers } });
}
const response = NextResponse.next({ request: { headers } });
if (setup.doneFor) response.cookies.set(SETUP_DONE_COOKIE, setup.doneFor, { maxAge: ONE_YEAR, path: "/", sameSite: "lax", httpOnly: true });
return response;
},
{
// The session's active organization follows the address (#651): an organization's pages sit
// under /o/<slug>, every other page is the person's own. Convex reads its own memberships.
organizationSyncOptions: { organizationPatterns: ["/o/:slug", "/o/:slug/(.*)"], personalAccountPatterns: ["/(.*)"] },
},
);
/**
* Whether a page request is a new account's profile setup instead (convex/users/profileSetup.ts). Asked of Convex once
* per account and browser: an account found done is kept in a cookie, `doneFor`. Never for a request inside a flow
* (signing in, an app's request, an invitation, a hand-off), a server action, a file or route that isn't a page
* (`isPage`) or a request that isn't a GET: the setup comes on the next page.
* An answer that can't be had lets the page through: the setup must never stand in the way of the site.
*/
async function profileSetup(auth: ClerkMiddlewareAuth, request: NextRequest): Promise<{ due: boolean; doneFor?: string }> {
const path = request.nextUrl.pathname;
if (request.method !== "GET" || request.headers.has("next-action") || !isPage(path) || path === SETUP_PATH || inFlow(path)) return { due: false };
const { userId, getToken } = await auth();
if (!userId || request.cookies.get(SETUP_DONE_COOKIE)?.value === userId) return { due: false };
try {
const token = await getToken({ template: "convex" });
if (!token) return { due: false };
return (await fetchQuery(api.users.profileSetup.due, {}, { token })) ? { due: true } : { due: false, doneFor: userId };
} catch (error) {
console.error(JSON.stringify({ event: "profile-setup-due-failed", error: String(error).slice(0, 300) }));
return { due: false };
}
}
/**
* Whether a request was made from the sign-in page, which the browser says in its Referer. Only its path is read:
* behind the host's proxy this server doesn't know the site's own address to compare the rest with.
*/
function fromSignIn(request: NextRequest) {
const referer = request.headers.get("referer");
return !!referer && URL.canParse(referer) && /^\/sign-in(\/|$)/.test(new URL(referer).pathname);
}
/**
* Where a page request goes instead, for someone who arrives from outside the site at an address that starts
* something new and names no workspace (lib/workspaces/paths.ts `startIn`): the same address in the organization this
* browser's rail drew last for them. Null for any other request. Only when the browser loads the page itself
* (`Sec-Fetch-Dest: document`) or comes from signing in: a link followed inside the site stays in the workspace its
* page is in, so a tab in a person's own workspace is never moved by what another tab did. An organization they are
* no longer in, or an answer that can't be had, lets the page through as it is: its layout would send them straight
* back here.
*/
async function lastWorkspaceStart(auth: ClerkMiddlewareAuth, request: NextRequest): Promise<string | null> {
if (request.method !== "GET" || request.headers.has("next-action") || (request.headers.get("sec-fetch-dest") !== "document" && !fromSignIn(request))) return null;
const raw = request.cookies.get(LOOK_COOKIE)?.value;
if (!raw) return null;
const { userId, getToken } = await auth();
const last = readCache(raw, userId).last;
const target = last ? startIn(last, request.nextUrl.pathname, request.nextUrl.searchParams) : null;
if (!last || !target) return null;
try {
const token = await getToken({ template: "convex" });
return token && (await fetchQuery(api.workspaces.queries.bySlug, { slug: last }, { token })) ? target + request.nextUrl.search : null;
} catch (error) {
console.error(JSON.stringify({ event: "last-workspace-start-failed", error: String(error).slice(0, 300) }));
return null;
}
}
function hasValidLocaleCookie(request: NextRequest): boolean {
const raw = request.cookies.get(COOKIE_NAME)?.value;
return !!raw && locales.includes(raw as (typeof locales)[number]);
}
export default async function proxy(
request: NextRequest,
event: NextFetchEvent
) {
// A file or redirect a route serves to anyone never meets Clerk: Clerk sends a browser with no session token, or a
// stale one, to its handshake first, and Cloudflare keeps that redirect for hours on a `.pdf` address, which loops.
if (isPublicFile(request.nextUrl.pathname)) return NextResponse.next();
const bareLink = bareWorkLink(request.nextUrl);
if (bareLink) return NextResponse.redirect(bareLink);
// Our index names each record by an address, openscholar.ai/OS… or /OSA…, which reaches here: the paper's or the author's page.
const ownRecord = /^\/(OSA?\d+)$/i.exec(request.nextUrl.pathname)?.[1]?.toUpperCase();
if (ownRecord) return NextResponse.redirect(new URL(`/${ownRecord.startsWith("OSA") ? "authors" : "papers"}/${ownRecord}`, request.url), 308);
// A link from a community site names the language its reader chose (`?hl=fr`): someone with no language here yet
// starts in that one, and the address drops it. A language they already have here stays theirs.
const linked = languageFromLink(request.nextUrl, hasValidLocaleCookie(request));
if (linked) {
const redirect = NextResponse.redirect(linked.clean);
if (linked.locale) redirect.cookies.set(COOKIE_NAME, linked.locale, { maxAge: ONE_YEAR, path: "/", sameSite: "lax" });
return redirect;
}
// A Publish link's promotion code outlasts the address it came in: signing in, a new tab, a later visit.
const code = request.method === "GET" && !request.headers.has("next-action") ? linkedCode(request.nextUrl, request.cookies.get(LINKED_CODE_COOKIE)?.value) : null;
if (code && "back" in code) return NextResponse.redirect(code.back);
const needsLocaleCookie = !hasValidLocaleCookie(request);
const detectedLocale = needsLocaleCookie
? detectLocaleFromAcceptLanguage(request.headers.get("accept-language"))
: null;
const authResponse = await authMiddleware(request, event);
const response = authResponse ?? NextResponse.next();
// A paper page says, in its headers, where its citation files are and what it is (signposting.org), for tools that read headers, not pages.
const paperPage = /^\/papers\/((?:OS|W)\d+)(?:\/[^/.]*)?$/i.exec(request.nextUrl.pathname)?.[1];
if (paperPage) response.headers.append("Link", [
...(Object.keys(CITATION_FILES) as CitationFile[]).map((kind) => `<${citeFilePath(paperPage.toUpperCase(), kind)}>; rel="describedby"; type="${CITATION_FILES[kind].type}"`),
'<https://schema.org/ScholarlyArticle>; rel="type"',
].join(", "));
if (code && response instanceof NextResponse) response.cookies.set(LINKED_CODE_COOKIE, code.keep, { maxAge: LINKED_CODE_MAX_AGE, path: "/", sameSite: "lax" });
if (needsLocaleCookie && detectedLocale) {
const cookieValue = `${COOKIE_NAME}=${encodeURIComponent(detectedLocale)}; Path=/; Max-Age=${ONE_YEAR}; SameSite=Lax`;
if (response instanceof NextResponse) {
response.cookies.set(COOKIE_NAME, detectedLocale, {
maxAge: ONE_YEAR,
path: "/",
sameSite: "lax",
});
} else {
response.headers.append("Set-Cookie", cookieValue);
}
}
return response;
}
export const config = {
// Clerk-recommended matcher shape:
// 1) Skip Next internals + static files.
// 2) Always run middleware for API/TRPC routes.
matcher: [
"/((?!_next|citation-styles/|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/(api|trpc)(.*)",
],
};