Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),

## [Unreleased]

### Added

- Added experimental support for configuring trusted proxy header sources used to construct request URLs. Header sources can provide the complete URL through `{ url: "header" }` or specify separate protocol and host headers through `{ protocol: "header-proto", host: "header-host" }`. The configuration also includes built-in sources such as `forwarded`, `forwarded.proto`, and `forwarded.host`. [#275](https://github.com/aura-stack-ts/auth/pull/275)

### Changed

- Upgraded `@aura-stack/router` to `v0.11.4`, adding response schema validation and adopting the built-in `handle()` function for processing incoming requests. This release also updates unsupported HTTP method handling to return a standardized `404 Not Found` response instead of `405 Method Not Allowed`. [#274](https://github.com/aura-stack-ts/auth/pull/274)
Expand Down
19 changes: 18 additions & 1 deletion packages/core/src/@types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
Awaitable,
ZodIdentitySchema,
EditableShape,
LiteralUnion,
} from "@/@types/index.ts"
import type { ZodObject } from "zod"
import type { SerializeOptions } from "@aura-stack/router/cookie"
Expand Down Expand Up @@ -212,7 +213,7 @@ export type TrustedProxyHeadersConfig =
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
* @experimental
*/
trustedProxyHeaders: true
trustedProxyHeaders: true | TrustedProxyHeadersSource[]
/**
* Defines trusted origins for your application to prevent open redirect attacks.
* URLs from the Referer header, Origin header, request URL, and redirectTo option
Expand Down Expand Up @@ -489,3 +490,19 @@ export type RateLimiterConfig = Partial<
>
>["rules"]
>

/**
* Defines the source of trusted proxy headers to construct the incoming request's origin.
* It can be a URL string or an object with protocol and host properties.
*
* @example
* { url: "x-custom-header" }
* // or
* { protocol: "x-forwarded-proto", host: "x-forwarded-host" }
*/
export type TrustedProxyHeadersSource =
| { url: LiteralUnion<"forwarded"> }
| {
protocol: LiteralUnion<"forwarded.proto" | "x-forwarded-proto">
host: LiteralUnion<"host" | "forwarded.host" | "x-forwarded-host">
}
3 changes: 2 additions & 1 deletion packages/core/src/@types/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type {
RateLimiterConfig,
SignUpConfig,
TrustedOrigin,
TrustedProxyHeadersSource,
} from "@/@types/config.ts"
import type {
JWTKey,
Expand Down Expand Up @@ -80,7 +81,7 @@ export interface RouterGlobalContext<DefaultUser extends User = User, SignUpSche
secret?: JWTKey
baseURL?: string
basePath: string
trustedProxyHeaders: boolean
trustedProxyHeaders: boolean | TrustedProxyHeadersSource[]
trustedOrigins?: TrustedOrigin[] | ((request: Request) => Promise<TrustedOrigin[]> | TrustedOrigin[])
logger?: InternalLogger
sessionStrategy: SessionStrategy<DefaultUser>
Expand Down
23 changes: 15 additions & 8 deletions packages/core/src/router/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { createJoseInstance } from "@/jose.ts"
import { createCookieStore } from "@/cookie.ts"
import { AuraAuthError } from "@/shared/errors.ts"
import { createProxyLogger } from "@/shared/logger.ts"
import { isStatelessStrategy } from "@/shared/assert.ts"
import { isBoolean, isStatelessStrategy } from "@/shared/assert.ts"
import { createSessionStrategy } from "@/session/strategy.ts"
import { createJoseManager } from "@/session/jose-manager.ts"
import { createSchemaRegistry } from "@/validator/registry.ts"
import { createBuiltInOAuthProviders } from "@/oauth/index.ts"
import { getEnv, getEnvArray, getEnvBoolean } from "@/shared/env.ts"
import { getEnvArray, getEnvBoolean } from "@/shared/env.ts"
import { createRateLimiterInstance } from "@/router/rate-limiter.ts"
import type { Identities, SchemaTypes } from "@/identity/index.ts"
import type { AuthConfig, FromShapeToObject } from "@/@types/index.ts"
Expand All @@ -16,9 +16,16 @@ import type { InternalContext } from "@/@types/internal.ts"
export const createContext = <Identity extends Identities, SignUpSchema extends SchemaTypes>(
config?: AuthConfig<Identity, SignUpSchema>
) => {
const trustedProxyHeadersEnv = getEnv("TRUSTED_PROXY_HEADERS")
const useProxyHeaders =
trustedProxyHeadersEnv === undefined ? (config?.trustedProxyHeaders ?? false) : getEnvBoolean("TRUSTED_PROXY_HEADERS")
const { trustedProxyHeaders } = config ?? {}
const trustedProxyHeadersEnv = getEnvBoolean("TRUSTED_PROXY_HEADERS")

const proxyHeaders = trustedProxyHeadersEnv
? trustedProxyHeadersEnv
: Array.isArray(trustedProxyHeaders)
Comment thread
halvaradop marked this conversation as resolved.
? trustedProxyHeaders
: isBoolean(trustedProxyHeaders)
? trustedProxyHeaders
: false
const envTrustedOrigins = getEnvArray("TRUSTED_ORIGINS")
const resolvedTrustedOrigins = envTrustedOrigins.length > 0 ? envTrustedOrigins : config?.trustedOrigins
const logger = createProxyLogger(config)
Expand All @@ -38,7 +45,7 @@ export const createContext = <Identity extends Identities, SignUpSchema extends
})

if (
useProxyHeaders &&
proxyHeaders &&
(!resolvedTrustedOrigins || (Array.isArray(resolvedTrustedOrigins) && resolvedTrustedOrigins.length === 0))
) {
throw new AuraAuthError({ code: "AUTH_INVALID_PROXY_HEADERS_CONFIG" })
Expand All @@ -51,7 +58,7 @@ export const createContext = <Identity extends Identities, SignUpSchema extends
jose: jose,
secret: config?.secret,
basePath: config?.basePath ?? "/auth",
trustedProxyHeaders: useProxyHeaders,
trustedProxyHeaders: proxyHeaders,
trustedOrigins: resolvedTrustedOrigins,
logger,
cookieConfig: { secure: secureCookieStore, standard: standardCookieStore },
Expand All @@ -63,7 +70,7 @@ export const createContext = <Identity extends Identities, SignUpSchema extends
},
signUp: config?.signUp,
jwtManager: createJoseManager(isStatelessStrategy(config?.session) ? config?.session?.jwt : undefined, jose),
rateLimiters: createRateLimiterInstance(config?.rateLimiter, useProxyHeaders),
rateLimiters: createRateLimiterInstance(config?.rateLimiter, Boolean(proxyHeaders)),
sessionConfig: config?.session,
} as InternalContext<Identity, SignUpSchema>
ctx.sessionStrategy = createSessionStrategy<Identity>({
Expand Down
24 changes: 24 additions & 0 deletions packages/core/src/shared/assert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
SessionConfig,
StatefulStrategyConfig,
StatelessStrategyConfig,
TrustedProxyHeadersSource,
} from "@/@types/index.ts"

export const isFalsy = (value: unknown): boolean => {
Expand Down Expand Up @@ -275,3 +276,26 @@ export const isInvalidSlidingThreshold = (value: unknown): value is number => {
export const isHeadersInit = (value: unknown): value is HeadersInit => {
return typeof value === "object" && value !== null && (value instanceof Headers || Array.isArray(value) || isObject(value))
}

export const isTrustedProxyHeadersSource = (value: unknown): value is TrustedProxyHeadersSource => {
return isTrustedProxyHeadersSourceURL(value) || isTrustedProxyHeadersSourceProtocolHost(value)
}

export const isTrustedProxyHeadersSourceURL = (value: unknown): value is { url: string } => {
return typeof value === "object" && value !== null && "url" in value
}

export const isTrustedProxyHeadersSourceProtocolHost = (value: unknown): value is { protocol: string; host: string } => {
return (
typeof value === "object" &&
value !== null &&
"protocol" in value &&
"host" in value &&
typeof (value as any).protocol === "string" &&
typeof (value as any).host === "string"
)
}

export const isBoolean = (value: unknown): value is boolean => {
return typeof value === "boolean"
}
10 changes: 10 additions & 0 deletions packages/core/src/shared/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ export const AuraErrorCode = {
*/
INVALID_SLIDING_THRESHOLD_CONFIG_VALUE: "INVALID_SLIDING_THRESHOLD_CONFIG_VALUE",
INVALID_CSRF_TOKEN: "INVALID_CSRF_TOKEN",
INVALID_CUSTOM_TRUSTED_PROXY_HEADERS_CONFIG: "INVALID_CUSTOM_TRUSTED_PROXY_HEADERS_CONFIG",
} as const

export type AuraErrorCode = (typeof AuraErrorCode)[keyof typeof AuraErrorCode]
Expand Down Expand Up @@ -958,6 +959,15 @@ export const ERROR_CATALOG: Record<AuraErrorCode, CatalogEntry> = {
"CSRF security verification failed. The provided anti-CSRF token does not match the token embedded in the secure session cookie context or failed cryptographic validation.",
userMessage: "Security verification failed. Invalid or missing CSRF token.",
},
INVALID_CUSTOM_TRUSTED_PROXY_HEADERS_CONFIG: {
type: "AUTH_FLOW",
statusCode: 500,
name: "ConfigError",
message:
"Initialization aborted: The custom 'trustedProxyHeaders' configuration is insecure or invalid. Allowing arbitrary or untrusted headers to construct the absolute application URL exposes the server to Host Header Injection and request forgery vulnerabilities.",
userMessage:
"Internal library configuration error. The custom trusted proxy headers configuration allows unsafe URL construction.",
},
}

export interface AuraErrorOptions extends ErrorOptions {
Expand Down
67 changes: 61 additions & 6 deletions packages/core/src/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ import { getCookie } from "@/cookie.ts"
import { createHash } from "@/shared/crypto.ts"
import { encoder } from "@aura-stack/jose/crypto"
import { AuraAuthError } from "@/shared/errors.ts"
import { isRelativeURL, isString, isValidURL } from "@/shared/assert.ts"
import {
isBoolean,
isRelativeURL,
isString,
isTrustedProxyHeadersSource,
isTrustedProxyHeadersSourceURL,
isValidURL,
} from "@/shared/assert.ts"
import type { DeviceType } from "@/@types/entities.ts"
import type { OAuthTokenPayload } from "@/@types/index.ts"
import type { AuthConfig, OAuthTokenPayload, TrustedProxyHeadersSource } from "@/@types/index.ts"
import type {
InternalCookieStoreConfig,
InternalLogger,
Expand All @@ -26,14 +33,21 @@ export const getBaseURL = (request: Request) => {
return `${url.origin}${url.pathname}`
}

export const isSecureConnection = (request: Request | Headers, trustedProxyHeaders: boolean): boolean => {
export const isSecureConnection = (
request: Request | Headers,
trustedProxyHeaders: AuthConfig["trustedProxyHeaders"]
): boolean => {
const headers = request instanceof Headers ? request : request.headers
const url = request instanceof Headers ? null : request.url
return trustedProxyHeaders
? url?.startsWith("https://") ||
return isBoolean(trustedProxyHeaders)
? trustedProxyHeaders
? url?.startsWith("https://") ||
headers.get("X-Forwarded-Proto") === "https" ||
(headers.get("Forwarded")?.includes("proto=https") ?? false)
: (url?.startsWith("https://") ?? false)
: (url?.startsWith("https://") ?? false)
: Array.isArray(trustedProxyHeaders)
? getBaseURLFromProxyHeaders(headers, trustedProxyHeaders).startsWith("https://")
: false
}

export const extractPath = (url: string): string => {
Expand Down Expand Up @@ -271,3 +285,44 @@ export const getDeviceInfo = (request: Request) => {
deviceType: getDeviceType(userAgent, secChUaMobile),
}
}

export const getProtoFromForwarded = (headers: Headers) => {
return headers?.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1]
}

export const getHostFromForwarded = (headers: Headers) => {
return headers?.get("Forwarded")?.match(/host=([^;]+)/i)?.[1]
}

/**
* Extracts the base URL from a set of trusted proxy headers.
*
* @param headers - The request headers.
* @param proxyHeaders - The configured trusted proxy headers.
* @returns The base URL derived from the proxy headers.
*/
export const getBaseURLFromProxyHeaders = (headers: Headers, proxyHeaders: TrustedProxyHeadersSource[]): string => {
let baseURL = ""
proxyHeaders.find((config) => {
try {
if (isTrustedProxyHeadersSourceURL(config)) {
const url =
config.url === "forwarded"
? `${getProtoFromForwarded(headers)}://${getHostFromForwarded(headers)}`
: (headers.get(config.url) ?? null)
if (!url || !isValidURL(url)) return false
return (baseURL = new URL(url).origin)
} else {
const protocol =
config.protocol === "forwarded.proto" ? getProtoFromForwarded(headers) : headers.get(config.protocol)!
const host = config.host === "forwarded.host" ? getHostFromForwarded(headers) : headers.get(config.host)!
if (!protocol || !host || !isValidURL(`${protocol}://${host}`)) return false
return (baseURL = new URL(`${protocol}://${host}`).origin)
}
} catch {
return false
}
})
if (!baseURL) throw new AuraAuthError({ code: "INVALID_CUSTOM_TRUSTED_PROXY_HEADERS_CONFIG" })
return baseURL
}
22 changes: 14 additions & 8 deletions packages/core/src/shared/utils/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import { getEnv } from "@/shared/env.ts"
import { OAuthAuthorization } from "@/shared/schemas/general.ts"
import { AuraAuthError } from "@/shared/errors.ts"
import { createPKCE, createSecretValue } from "@/shared/crypto.ts"
import { equals, extractPath, patternToRegex } from "@/shared/utils.ts"
import {
equals,
extractPath,
getBaseURLFromProxyHeaders,
getHostFromForwarded,
getProtoFromForwarded,
patternToRegex,
} from "@/shared/utils.ts"
import { isRelativeURL, isSameOrigin, isValidURL, isTrustedOrigin } from "@/shared/assert.ts"
import type { GlobalContext } from "@aura-stack/router"
import type { AuthConfig, OAuthProvider } from "@/@types/index.ts"
Expand Down Expand Up @@ -32,13 +39,12 @@ export const getBaseURL = async ({
const origin = getEnv("BASE_URL") || ctx?.baseURL
if (origin && origin !== "/") return origin
if (ctx?.trustedProxyHeaders) {
const headers = (headersInit && new Headers(headersInit)) || request?.headers
const protocol = headers?.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Proto") ?? "http"
const host =
headers?.get("Host") ??
headers?.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ??
headers?.get("X-Forwarded-Host") ??
null
const headers = new Headers(request?.headers ?? headersInit ?? {})
if (Array.isArray(ctx.trustedProxyHeaders)) {
return getBaseURLFromProxyHeaders(headers, ctx.trustedProxyHeaders)
}
const protocol = getProtoFromForwarded(headers) ?? headers?.get("X-Forwarded-Proto") ?? "http"
const host = headers?.get("Host") ?? getHostFromForwarded(headers) ?? headers?.get("X-Forwarded-Host") ?? null
if (host) return `${protocol}://${host}`
throw new AuraAuthError({ code: "INVALID_AUTH_CONFIGURATION" })
}
Expand Down
Loading
Loading