-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(start): CSRF middleware #7373
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 all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| '@tanstack/start-client-core': minor | ||
| '@tanstack/start-plugin-core': patch | ||
| '@tanstack/start-server-core': patch | ||
| '@tanstack/start-fn-stubs': patch | ||
| --- | ||
|
|
||
| add createCsrfMiddleware based on Sec-Fetch-Site header, auto-apply to unconfigured servers, warn for others |
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
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,197 @@ | ||
| import { createIsomorphicFn } from '@tanstack/start-fn-stubs' | ||
| import { createMiddleware } from './createMiddleware' | ||
| import type { | ||
| RequestMiddlewareAfterServer, | ||
| RequestServerOptions, | ||
| } from './createMiddleware' | ||
| import type { Register } from '@tanstack/router-core' | ||
|
|
||
| export const csrfSymbol = Symbol.for('tanstack-start:csrf-middleware') | ||
|
|
||
| export type CsrfSecFetchSite = | ||
| | 'same-origin' | ||
| | 'same-site' | ||
| | 'cross-site' | ||
| | 'none' | ||
|
|
||
| export type CsrfMatcher<TValue, TRegister = Register, TMiddlewares = unknown> = | ||
| | TValue | ||
| | Array<TValue> | ||
| | (( | ||
| value: TValue | (string & {}), | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ) => boolean | Promise<boolean>) | ||
|
|
||
| export interface CsrfMiddlewareOptions< | ||
| TRegister = Register, | ||
| TMiddlewares = unknown, | ||
| > { | ||
| /** | ||
| * Return `true` to validate this request, or `false` to skip validation. | ||
| * | ||
| * @default undefined, which validates every request handled by this middleware. | ||
| */ | ||
| filter?: ( | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ) => boolean | Promise<boolean> | ||
| /** | ||
| * Allowed Origin values. Defaults to the trusted request origin. | ||
| */ | ||
| origin?: CsrfMatcher<string, TRegister, TMiddlewares> | ||
| /** | ||
| * Allowed Sec-Fetch-Site values. | ||
| * | ||
| * @default 'same-origin' | ||
| */ | ||
| secFetchSite?: CsrfMatcher<CsrfSecFetchSite, TRegister, TMiddlewares> | ||
| /** | ||
| * Whether to use Referer as a fallback when Sec-Fetch-Site and Origin are absent. | ||
| * | ||
| * @default true | ||
| */ | ||
| referer?: | ||
| | boolean | ||
| | (( | ||
| referer: string, | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ) => boolean | Promise<boolean>) | ||
| /** | ||
| * Allow requests when Sec-Fetch-Site, Origin, and Referer are all missing. | ||
| * | ||
| * @default false | ||
| */ | ||
| allowRequestsWithoutOriginCheck?: boolean | ||
| /** | ||
| * Optional response returned when CSRF validation fails. | ||
| * | ||
| * @default new Response('Forbidden', { status: 403 }) | ||
| */ | ||
| failureResponse?: | ||
| | Response | ||
| | (( | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ) => Response | Promise<Response>) | ||
| } | ||
|
|
||
| type CreateCsrfMiddleware = <TRegister, TMiddlewares>( | ||
| opts?: CsrfMiddlewareOptions<TRegister, TMiddlewares>, | ||
| ) => RequestMiddlewareAfterServer<{}, undefined, undefined> | ||
|
|
||
| const innerCreateCsrfMiddleware: CreateCsrfMiddleware = (opts = {}) => { | ||
| const middleware = createMiddleware().server(async (ctx) => { | ||
| const csrfCtx = ctx as RequestServerOptions<any, any> & typeof ctx | ||
|
|
||
| if (opts.filter && !(await opts.filter(csrfCtx))) { | ||
| return ctx.next() | ||
| } | ||
|
|
||
| if (await isCsrfRequestAllowed(opts, csrfCtx)) { | ||
| return ctx.next() | ||
| } | ||
|
|
||
| return getFailureResponse(opts, csrfCtx) | ||
| }) | ||
|
|
||
| if (process.env.NODE_ENV !== 'production') { | ||
| Object.defineProperty(middleware, csrfSymbol, { value: true }) | ||
| } | ||
|
|
||
| return middleware | ||
| } | ||
|
|
||
| export const createCsrfMiddleware: CreateCsrfMiddleware = | ||
| createIsomorphicFn().server(innerCreateCsrfMiddleware) as CreateCsrfMiddleware | ||
|
|
||
| export async function isCsrfRequestAllowed<TRegister, TMiddlewares>( | ||
| opts: CsrfMiddlewareOptions<TRegister, TMiddlewares>, | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ): Promise<boolean> { | ||
| const result = await getCsrfRequestValidationResult(opts, ctx) | ||
| return ( | ||
| result === true || | ||
| (result === undefined && opts.allowRequestsWithoutOriginCheck === true) | ||
| ) | ||
| } | ||
|
|
||
| export async function getCsrfRequestValidationResult<TRegister, TMiddlewares>( | ||
| opts: CsrfMiddlewareOptions<TRegister, TMiddlewares>, | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ): Promise<boolean | undefined> { | ||
| const fetchSite = ctx.request.headers.get('Sec-Fetch-Site') | ||
| if (fetchSite !== null) { | ||
| return matchValue(opts.secFetchSite ?? 'same-origin', fetchSite, ctx) | ||
| } | ||
|
|
||
| const origin = ctx.request.headers.get('Origin') | ||
| if (origin !== null) { | ||
| if (opts.origin) { | ||
| return matchValue(opts.origin, origin, ctx) | ||
| } | ||
|
|
||
| return origin === new URL(ctx.request.url).origin | ||
| } | ||
|
|
||
| const referer = ctx.request.headers.get('Referer') | ||
| if (referer === null || opts.referer === false) { | ||
| return undefined | ||
| } | ||
|
|
||
| if (typeof opts.referer === 'function') { | ||
| return opts.referer(referer, ctx) | ||
| } | ||
|
|
||
| if (opts.origin) { | ||
| const refererOrigin = getOriginFromUrl(referer) | ||
| return ( | ||
| refererOrigin !== undefined && matchValue(opts.origin, refererOrigin, ctx) | ||
| ) | ||
| } | ||
|
|
||
| return isRefererSameOrigin(referer, new URL(ctx.request.url).origin) | ||
| } | ||
|
|
||
| async function matchValue<TValue extends string, TRegister, TMiddlewares>( | ||
| matcher: CsrfMatcher<TValue, TRegister, TMiddlewares>, | ||
| value: string, | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ): Promise<boolean> { | ||
| if (typeof matcher === 'function') { | ||
| return matcher(value, ctx) | ||
| } | ||
|
|
||
| if (Array.isArray(matcher)) { | ||
| // typescript is dumb for array.includes() | ||
| return matcher.includes(value as TValue) | ||
| } | ||
|
|
||
| return value === matcher | ||
| } | ||
|
|
||
| function getOriginFromUrl(url: string): string | undefined { | ||
| try { | ||
| return new URL(url).origin | ||
| } catch { | ||
| return undefined | ||
| } | ||
| } | ||
|
|
||
| function isRefererSameOrigin(referer: string, requestOrigin: string): boolean { | ||
| if (referer === requestOrigin) return true | ||
| if (!referer.startsWith(requestOrigin)) return false | ||
| if (referer.length === requestOrigin.length) return true | ||
| const code = referer.charCodeAt(requestOrigin.length) | ||
| return code === 47 /* '/' */ || code === 63 /* '?' */ || code === 35 /* '#' */ | ||
| } | ||
|
|
||
| async function getFailureResponse<TRegister, TMiddlewares>( | ||
| opts: CsrfMiddlewareOptions<TRegister, TMiddlewares>, | ||
| ctx: RequestServerOptions<TRegister, TMiddlewares>, | ||
| ): Promise<Response> { | ||
| if (typeof opts.failureResponse === 'function') { | ||
| return opts.failureResponse(ctx) | ||
| } | ||
|
|
||
| return ( | ||
| opts.failureResponse?.clone() ?? new Response('Forbidden', { status: 403 }) | ||
| ) | ||
| } |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clarify whether to reuse or create a new middleware instance.
Line 466 says "use the same middleware" but the code example creates a new instance with
createCsrfMiddleware(). Either update the text to say "You can also use CSRF middleware to protect any other route" or update the code to reuse thecsrfMiddlewarevariable from the earlier example.Option 1: Update text to match code (creates new instance)
Option 2: Update code to reuse existing instance
export const Route = createFileRoute('/api/foo')({ server: { - middleware: [createCsrfMiddleware()], + middleware: [csrfMiddleware], handlers: { GET: () => {...} } } })📝 Committable suggestion
🤖 Prompt for AI Agents