Skip to content

Commit

Permalink
Image optimization endpoint redirects to underlying image URL if the …
Browse files Browse the repository at this point in the history
…signature is not the latest. (#2665)
  • Loading branch information
emmerich authored Dec 30, 2024
1 parent 99579ac commit db74ea3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/tender-bags-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'gitbook': minor
---

Image optimization endpoint redirects to underlying image URL if the signature is not the latest.
11 changes: 10 additions & 1 deletion packages/gitbook/src/app/(global)/~gitbook/image/route.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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',
Expand Down
7 changes: 6 additions & 1 deletion packages/gitbook/src/lib/image-signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit db74ea3

Please sign in to comment.