-
Notifications
You must be signed in to change notification settings - Fork 5
Internal requests bypassing rate limits #1609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 17 commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
a2d81c9
Internal requests bypassing rate limits
prxt6529 7f2754e
WIP
prxt6529 c6aba37
WIP
prxt6529 cf6419b
WIP
prxt6529 86b6c4f
WIP
prxt6529 ded305d
WIP - waf internal
prxt6529 6f298b9
WIP
prxt6529 076052e
WIP
prxt6529 10d522d
WIP
prxt6529 16d03e8
WIP
prxt6529 042eadc
WIP
prxt6529 27c6dff
WIP
prxt6529 c0cefe4
WIP
prxt6529 be98c20
WIP
prxt6529 642dd83
WIP
prxt6529 b427a0a
WIP
prxt6529 c44a958
WIP
prxt6529 136f0f8
WIP
prxt6529 a0d3096
WIP
prxt6529 b75d5a2
WIP
prxt6529 3f8465d
WIP
prxt6529 3219307
WIP
prxt6529 e18cad4
Merge branch 'main' into internal-ssr-rate-limit
prxt6529 88beddc
WIP remove fallback
prxt6529 139c9bc
WIP
prxt6529 244a05f
WIP
prxt6529 5eb002b
WIP
prxt6529 4650b33
WIP
prxt6529 53b132b
WIP
prxt6529 5872c36
WIP
prxt6529 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import { z } from "zod"; | ||
|
|
||
| export const serverEnvSchema = z.object({ | ||
| SSR_CLIENT_ID: z.string().min(1, "SSR_CLIENT_ID is required"), | ||
| SSR_CLIENT_SECRET: z.string().min(1, "SSR_CLIENT_SECRET is required"), | ||
| }); | ||
|
|
||
| export type ServerEnv = z.infer<typeof serverEnvSchema>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import { serverEnvSchema, type ServerEnv } from "./serverEnv.schema"; | ||
|
|
||
| if (globalThis.window !== undefined) { | ||
| throw new TypeError("serverEnv can only be accessed on the server side"); | ||
| } | ||
|
|
||
| const getServerEnv = (): ServerEnv | null => { | ||
| if (typeof process === "undefined" || !process.env) { | ||
| return null; | ||
| } | ||
|
|
||
| const raw = { | ||
| SSR_CLIENT_ID: process.env.SSR_CLIENT_ID, | ||
| SSR_CLIENT_SECRET: process.env.SSR_CLIENT_SECRET, | ||
| }; | ||
|
|
||
| const parsed = serverEnvSchema.safeParse(raw); | ||
| if (!parsed.success) { | ||
| return null; | ||
| } | ||
|
|
||
| return parsed.data; | ||
| }; | ||
|
|
||
| export const getServerEnvOrThrow = (): ServerEnv => { | ||
| const env = getServerEnv(); | ||
| if (!env) { | ||
| throw new Error( | ||
| "SSR_CLIENT_ID and SSR_CLIENT_SECRET must be set as runtime environment variables" | ||
| ); | ||
| } | ||
| return env; | ||
| }; | ||
|
|
||
| export const serverEnv: ServerEnv | null = getServerEnv(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { createHmac } from "node:crypto"; | ||
|
|
||
| /** | ||
| * Generates a client signature for server-side authentication. | ||
| * | ||
| * The signature scheme uses HMAC-SHA256 to create a cryptographic signature | ||
| * from a payload containing the client ID, timestamp, HTTP method, and path. | ||
| * The timestamp is used to prevent replay attacks within a configurable time window | ||
| * (typically 300 seconds / 5 minutes). The signature must match exactly on both | ||
| * client and server for authentication to succeed. | ||
| * | ||
| * @param clientId - The client identifier (must be a non-empty string) | ||
| * @param secret - The shared secret key for HMAC signing (must be a non-empty string) | ||
| * @param method - The HTTP method (will be normalized to uppercase, must be non-empty) | ||
| * @param path - The request path including query string if present (pathname + search, e.g., '/api/users?page=1'; must be non-empty) | ||
| * @param timestamp - Optional Unix timestamp in seconds. If not provided, uses current time. | ||
| * @returns An object containing the clientId, timestamp, and generated signature | ||
| * @throws {TypeError} If called in a browser environment or if any required parameter is invalid | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * const { signature } = generateClientSignature( | ||
| * 'my-client-id', | ||
| * 'my-secret', | ||
| * 'POST', | ||
| * '/api/users?page=1' | ||
| * ); | ||
| * ``` | ||
| */ | ||
| export function generateClientSignature( | ||
| clientId: string, | ||
| secret: string, | ||
| method: string, | ||
| path: string, | ||
| timestamp?: number | ||
| ): { clientId: string; timestamp: number; signature: string } { | ||
| if (globalThis.window !== undefined) { | ||
| throw new TypeError( | ||
| "generateClientSignature can only be used on the server side" | ||
| ); | ||
| } | ||
|
|
||
| if (typeof clientId !== "string" || clientId.trim().length === 0) { | ||
| throw new TypeError( | ||
| "generateClientSignature: clientId must be a non-empty string" | ||
| ); | ||
| } | ||
|
|
||
| if (typeof secret !== "string" || secret.trim().length === 0) { | ||
| throw new TypeError( | ||
| "generateClientSignature: secret must be a non-empty string" | ||
| ); | ||
| } | ||
|
|
||
| if (typeof method !== "string" || method.trim().length === 0) { | ||
| throw new TypeError( | ||
| "generateClientSignature: method must be a non-empty string" | ||
| ); | ||
| } | ||
|
|
||
| if (typeof path !== "string" || path.trim().length === 0) { | ||
| throw new TypeError( | ||
| "generateClientSignature: path must be a non-empty string" | ||
| ); | ||
| } | ||
|
|
||
| const normalizedMethod = method.toUpperCase(); | ||
| const ts = timestamp ?? Math.floor(Date.now() / 1000); | ||
| const payload = `${clientId}\n${ts}\n${normalizedMethod}\n${path}`; | ||
| const signature = createHmac("sha256", secret).update(payload).digest("hex"); | ||
|
|
||
| return { | ||
| clientId, | ||
| timestamp: ts, | ||
| signature, | ||
| }; | ||
| } | ||
|
prxt6529 marked this conversation as resolved.
|
||
|
|
||
| export function generateWafSignature(clientId: string, secret: string): string { | ||
| if (globalThis.window !== undefined) { | ||
| throw new TypeError( | ||
| "generateWafSignature can only be used on the server side" | ||
| ); | ||
| } | ||
|
|
||
| if (typeof clientId !== "string" || clientId.trim().length === 0) { | ||
| throw new TypeError( | ||
| "generateWafSignature: clientId must be a non-empty string" | ||
| ); | ||
| } | ||
|
|
||
| if (typeof secret !== "string" || secret.trim().length === 0) { | ||
| throw new TypeError( | ||
| "generateWafSignature: secret must be a non-empty string" | ||
| ); | ||
| } | ||
|
|
||
| const signature = createHmac("sha256", secret).update(clientId).digest("hex"); | ||
|
|
||
| return signature; | ||
|
prxt6529 marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| import { publicEnv } from "@/config/env"; | ||
| import { getServerEnvOrThrow } from "@/config/serverEnv"; | ||
| import { | ||
| generateClientSignature, | ||
| generateWafSignature, | ||
| } from "@/helpers/server-signature.helpers"; | ||
| import { getAppCommonHeaders } from "@/helpers/server.app.helpers"; | ||
|
|
||
| const getOriginalFetch = (): typeof fetch => { | ||
| if (globalThis.fetch === undefined) { | ||
| throw new TypeError( | ||
| "fetch not available in current runtime. This module requires a fetch implementation." | ||
| ); | ||
| } | ||
| if (typeof globalThis.fetch !== "function") { | ||
| throw new TypeError( | ||
| "fetch is not a function in current runtime. Expected a function but got a different type." | ||
| ); | ||
| } | ||
| return globalThis.fetch; | ||
| }; | ||
|
|
||
| const originalFetch = getOriginalFetch(); | ||
|
|
||
| const isApiRequest = (url: string | URL): boolean => { | ||
| const urlString = typeof url === "string" ? url : url.toString(); | ||
| try { | ||
| const parsedUrl = new URL(urlString, publicEnv.API_ENDPOINT); | ||
| return parsedUrl.origin === new URL(publicEnv.API_ENDPOINT).origin; | ||
| } catch { | ||
| return false; | ||
| } | ||
| }; | ||
|
|
||
| const extractPathFromUrl = (url: string | URL, baseUrl: string): string => { | ||
| const urlString = typeof url === "string" ? url : url.toString(); | ||
| try { | ||
| const parsedUrl = new URL(urlString, baseUrl); | ||
| return parsedUrl.pathname + parsedUrl.search; | ||
| } catch { | ||
| return ""; | ||
| } | ||
| }; | ||
|
|
||
| const enhancedFetch: typeof fetch = async ( | ||
| input: RequestInfo | URL, | ||
| init?: RequestInit | ||
| ): Promise<Response> => { | ||
| if (globalThis.window !== undefined) { | ||
| return originalFetch(input, init); | ||
| } | ||
|
|
||
| let url: string; | ||
| if (typeof input === "string") { | ||
| url = input; | ||
| } else if (input instanceof URL) { | ||
| url = input.toString(); | ||
| } else { | ||
| url = input.url; | ||
| } | ||
|
|
||
| if (!isApiRequest(url)) { | ||
| return originalFetch(input, init); | ||
| } | ||
|
|
||
| let clientId: string; | ||
| let clientSecret: string; | ||
|
|
||
| try { | ||
| const env = getServerEnvOrThrow(); | ||
| clientId = env.SSR_CLIENT_ID; | ||
| clientSecret = env.SSR_CLIENT_SECRET; | ||
| } catch { | ||
| return originalFetch(input, init); | ||
| } | ||
|
prxt6529 marked this conversation as resolved.
Outdated
|
||
|
|
||
| const method = ( | ||
| init?.method ?? | ||
| (input instanceof Request ? input.method : undefined) ?? | ||
| "GET" | ||
| ).toUpperCase(); | ||
| const path = extractPathFromUrl(url, publicEnv.API_ENDPOINT); | ||
|
|
||
| if (!path) { | ||
| return originalFetch(input, init); | ||
| } | ||
|
|
||
| const signatureData = generateClientSignature( | ||
| clientId, | ||
| clientSecret, | ||
| method, | ||
| path | ||
| ); | ||
|
|
||
| const wafSignature = generateWafSignature(clientId, clientSecret); | ||
|
|
||
| const baseHeaders = input instanceof Request ? input.headers : undefined; | ||
| const enhancedHeaders = new Headers(baseHeaders); | ||
| if (init?.headers) { | ||
| new Headers(init.headers).forEach((value, key) => { | ||
| enhancedHeaders.set(key, value); | ||
| }); | ||
| } | ||
|
|
||
| enhancedHeaders.set("x-6529-internal-id", signatureData.clientId); | ||
| enhancedHeaders.set("x-6529-internal-signature", signatureData.signature); | ||
| enhancedHeaders.set( | ||
| "x-6529-internal-timestamp", | ||
| signatureData.timestamp.toString() | ||
| ); | ||
| enhancedHeaders.set("x-6529-internal-waf-signature", wafSignature); | ||
|
|
||
| try { | ||
| const appHeaders = await getAppCommonHeaders(); | ||
| Object.entries(appHeaders).forEach(([key, value]) => { | ||
| enhancedHeaders.set(key, value); | ||
| }); | ||
| } catch {} | ||
|
|
||
| return originalFetch(input, { | ||
| ...init, | ||
| headers: enhancedHeaders, | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }; | ||
|
|
||
| if (globalThis.window === undefined) { | ||
| globalThis.fetch = enhancedFetch; | ||
| } | ||
|
|
||
| export { enhancedFetch as ssrFetch }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.