opencode/packages/console/app/src/middleware.ts

65 lines
2.8 KiB
TypeScript

import { createMiddleware } from "@solidjs/start/middleware"
import { appleAppSiteAssociation } from "~/lib/apple-app-site-association"
import { LOCALE_HEADER, cookie, fromPathname, strip } from "~/lib/language"
import { sanitizeServerActionRequest } from "~/lib/server-action"
export default createMiddleware({
async onRequest(event) {
const association = appleAppSiteAssociation(event.request)
if (association) return association
event.request = sanitizeServerActionRequest(event.request)
const url = new URL(event.request.url)
const locale = fromPathname(url.pathname)
if (locale) {
url.pathname = strip(url.pathname)
if (/^\/changelog\/?$/.test(url.pathname))
return new Response(null, { status: 301, headers: { Location: "/changelog" } })
// English pages live at unprefixed URLs, so /en/... would be a duplicate of every page.
// /data keeps /en because it redirects unprefixed visits by cookie and Accept-Language.
// Collapse leading slashes so /en//example.com can't become a protocol-relative redirect.
if (
locale === "en" &&
(event.request.method === "GET" || event.request.method === "HEAD") &&
!/^\/data(\/|$)/.test(url.pathname)
)
return new Response(null, {
status: 301,
headers: { Location: `${url.pathname.replace(/^\/+/, "/")}${url.search}` },
})
const request = new Request(url, event.request)
request.headers.set(LOCALE_HEADER, locale)
event.request = request
event.response.headers.append("set-cookie", cookie(locale))
}
// Black subscriptions were migrated to Go.
if (/^\/black(\/|$)/.test(url.pathname))
return new Response(null, { status: 301, headers: { Location: locale ? `/${locale}/go` : "/go" } })
// The legacy dashboard and its sign-in moved to the new Console.
if (/^\/(auth|workspace)(\/|$)/.test(url.pathname))
return new Response(null, {
status: 302,
headers: { Location: "https://opencode.ai/console/login", "Cache-Control": "no-store" },
})
// The Go, Zen, pricing, models and teams pages moved to the Console. Match the exact paths only: /zen/v1/* and
// /zen/go/v1/* are the inference API, so a prefix match here would break API clients if the inference routes ever
// stopped catching them.
const moved = new Map([
["/go", "/console/go"],
["/zen", "/console/models"],
["/zen/go", "/console/go"],
["/pricing", "/console/go"],
["/models", "/console/models"],
["/teams", "/console/teams"],
]).get(url.pathname.replace(/(.)\/$/, "$1"))
if (moved && !locale && (event.request.method === "GET" || event.request.method === "HEAD"))
return new Response(null, {
status: 302,
headers: { Location: `${moved}${url.search}`, "Cache-Control": "no-store" },
})
},
})