From 52187d1ff694c75a4a900a15f52a4d06f7409f4b Mon Sep 17 00:00:00 2001 From: ccbikai Date: Sat, 20 Jul 2024 18:34:49 +0800 Subject: [PATCH] feat: disable query string redirection by default Enhances security and performance by preventing query strings from being carried over during redirection, aligning with best practices. --- .env.example | 1 + docs/configuration.md | 4 ++++ nuxt.config.ts | 1 + server/middleware/1.redirect.ts | 7 ++++--- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index b1f341d..7f1a286 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,7 @@ NUXT_PUBLIC_SLUG_DEFAULT_LENGTH=5 NUXT_SITE_TOKEN=SinkCool NUXT_REDIRECT_STATUS_CODE=308 NUXT_LINK_CACHE_TTL=60 +NUXT_REDIRECT_WITH_QUERY=false NUXT_HOME_URL="https://sink.cool" NUXT_CF_ACCOUNT_ID=123456 NUXT_CF_API_TOKEN=CloudflareAPIToken diff --git a/docs/configuration.md b/docs/configuration.md index 47669be..a6be688 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -18,6 +18,10 @@ Redirects default to use HTTP 301 status code, you can set it to `302`/`307`/`30 Cache links can speed up access, but setting them too long may result in slow changes taking effect. The default value is 60 seconds. +## `NUXT_REDIRECT_WITH_QUERY` + +URL parameters are not carried during link redirection by default and it is not recommended to enable this feature. + ## `NUXT_HOME_URL` The default Sink homepage is the introduction page, you can replace it with your own website. diff --git a/nuxt.config.ts b/nuxt.config.ts index a071081..144b2a7 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -53,6 +53,7 @@ export default defineNuxtConfig({ siteToken: 'SinkCool', redirectStatusCode: '301', linkCacheTtl: 60, + redirectWithQuery: false, homeURL: '', cfAccountId: '', cfApiToken: '', diff --git a/server/middleware/1.redirect.ts b/server/middleware/1.redirect.ts index 327f2af..81f32dd 100644 --- a/server/middleware/1.redirect.ts +++ b/server/middleware/1.redirect.ts @@ -1,11 +1,11 @@ import type { z } from 'zod' -import { parsePath } from 'ufo' +import { parsePath, withQuery } from 'ufo' import type { LinkSchema } from '@/schemas/link' export default eventHandler(async (event) => { const { pathname: slug } = parsePath(event.path.slice(1)) // remove leading slash const { slugRegex, reserveSlug } = useAppConfig(event) - const { homeURL, linkCacheTtl } = useRuntimeConfig(event) + const { homeURL, linkCacheTtl, redirectWithQuery } = useRuntimeConfig(event) const { cloudflare } = event.context if (event.path === '/' && homeURL) @@ -22,7 +22,8 @@ export default eventHandler(async (event) => { catch (error) { console.error('Failed write access log:', error) } - return sendRedirect(event, link.url, +useRuntimeConfig(event).redirectStatusCode) + const target = redirectWithQuery ? withQuery(link.url, getQuery(event)) : link.url + return sendRedirect(event, target, +useRuntimeConfig(event).redirectStatusCode) } } })