From db74ea3001611e268147c1a86156843a641a2b87 Mon Sep 17 00:00:00 2001 From: Steven H Date: Mon, 30 Dec 2024 13:08:49 +0000 Subject: [PATCH] Image optimization endpoint redirects to underlying image URL if the signature is not the latest. (#2665) --- .changeset/tender-bags-guess.md | 5 +++++ .../gitbook/src/app/(global)/~gitbook/image/route.ts | 11 ++++++++++- packages/gitbook/src/lib/image-signatures.ts | 7 ++++++- 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 .changeset/tender-bags-guess.md diff --git a/.changeset/tender-bags-guess.md b/.changeset/tender-bags-guess.md new file mode 100644 index 0000000000..dc39a0691e --- /dev/null +++ b/.changeset/tender-bags-guess.md @@ -0,0 +1,5 @@ +--- +'gitbook': minor +--- + +Image optimization endpoint redirects to underlying image URL if the signature is not the latest. diff --git a/packages/gitbook/src/app/(global)/~gitbook/image/route.ts b/packages/gitbook/src/app/(global)/~gitbook/image/route.ts index 1e00ca5ec0..99a1db12b8 100644 --- a/packages/gitbook/src/app/(global)/~gitbook/image/route.ts +++ b/packages/gitbook/src/app/(global)/~gitbook/image/route.ts @@ -1,6 +1,11 @@ import { NextRequest } from 'next/server'; -import { isSignatureVersion, SignatureVersion, verifyImageSignature } from '@/lib/image-signatures'; +import { + CURRENT_SIGNATURE_VERSION, + isSignatureVersion, + SignatureVersion, + verifyImageSignature, +} from '@/lib/image-signatures'; import { resizeImage, CloudflareImageOptions, checkIsSizableImageURL } from '@/lib/images'; import { parseImageAPIURL } from '@/lib/urls'; @@ -39,6 +44,10 @@ export async function GET(request: NextRequest) { return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 }); } + if (signatureVersion !== CURRENT_SIGNATURE_VERSION) { + return Response.redirect(url, 302); + } + // Cloudflare-specific options are in the cf object. const options: CloudflareImageOptions = { fit: 'scale-down', diff --git a/packages/gitbook/src/lib/image-signatures.ts b/packages/gitbook/src/lib/image-signatures.ts index aa3a90fe3e..cddf652d4f 100644 --- a/packages/gitbook/src/lib/image-signatures.ts +++ b/packages/gitbook/src/lib/image-signatures.ts @@ -11,6 +11,11 @@ import { host } from './links'; */ export type SignatureVersion = '0' | '1' | '2'; +/** + * The current version of the signature. + */ +export const CURRENT_SIGNATURE_VERSION: SignatureVersion = '2'; + /** * A mapping of signature versions to signature functions. */ @@ -48,7 +53,7 @@ export function generateImageSignature(input: string): { version: SignatureVersion; } { const result = generateSignatureV2(input); - return { signature: result, version: '2' }; + return { signature: result, version: CURRENT_SIGNATURE_VERSION }; } // Reused buffer for FNV-1a hashing in the v2 algorithm