Skip to content

Commit 27bdc3d

Browse files
committed
refactor(@angular/ssr): reuse ɵisHostAllowed from @angular/platform-server
Replace the duplicate local `isHostAllowed` implementation in `@angular/ssr` with `ɵisHostAllowed` from `@angular/platform-server` so host allowlist matching stays consistent across both packages. Extract the framework-independent HTTP/proxy header helpers into `src/utils/headers.ts` so `node/src/request.ts` and its pure-Node unit tests do not pull in `@angular/platform-server`.
1 parent 0a61cbc commit 27bdc3d

8 files changed

Lines changed: 236 additions & 252 deletions

File tree

‎packages/angular/ssr/node/src/request.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
isProxyHeaderAllowed,
1414
normalizeTrustProxyHeaders,
1515
parseForwardedHeader,
16-
} from '../../src/utils/validation';
16+
} from '../../src/utils/headers';
1717

1818
/**
1919
* A set containing all the pseudo-headers defined in the HTTP/2 specification.

‎packages/angular/ssr/node/test/request_spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import { IncomingMessage } from 'node:http';
1010
import { Socket } from 'node:net';
11-
import { normalizeTrustProxyHeaders } from '../../src/utils/validation';
11+
import { normalizeTrustProxyHeaders } from '../../src/utils/headers';
1212
import { createRequestUrl } from '../src/request';
1313

1414
// Helper to create a mock request object for testing.

‎packages/angular/ssr/src/app-engine.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,10 @@ import type { AngularServerApp, getOrCreateAngularServerApp } from './app';
1010
import { Hooks } from './hooks';
1111
import { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n';
1212
import { EntryPointExports, getAngularAppEngineManifest } from './manifest';
13+
import { getFirstHeaderValue, normalizeTrustProxyHeaders } from './utils/headers';
1314
import { createRedirectResponse } from './utils/redirect';
1415
import { joinUrlParts } from './utils/url';
15-
import {
16-
getFirstHeaderValue,
17-
normalizeTrustProxyHeaders,
18-
sanitizeRequestHeaders,
19-
validateRequest,
20-
} from './utils/validation';
16+
import { sanitizeRequestHeaders, validateRequest } from './utils/validation';
2117

2218
/**
2319
* Options for the Angular server application engine.

‎packages/angular/ssr/src/app.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ import { getAngularAppManifest } from './manifest';
2121
import { RenderMode } from './routes/route-config';
2222
import { RouteTreeNodeMetadata } from './routes/route-tree';
2323
import { ServerRouter } from './routes/router';
24+
import { getFirstHeaderValue } from './utils/headers';
2425
import { AngularBootstrap, renderAngular } from './utils/ng';
2526
import { promiseWithAbort } from './utils/promise';
2627
import { createRedirectResponse } from './utils/redirect';
2728
import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url';
28-
import { getFirstHeaderValue } from './utils/validation';
2929

3030
/**
3131
* A set of well-known URLs that are not handled by Angular.
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
/**
10+
* Internal sentinel string representing a wildcard rule to trust all proxy headers.
11+
*/
12+
const TRUST_ALL_PROXY_HEADERS = '*';
13+
14+
/**
15+
* Extracts the first value from a multi-value header string.
16+
*
17+
* @param value - A string or an array of strings representing the header values.
18+
* If it's a string, values are expected to be comma-separated.
19+
* @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty.
20+
*
21+
* @example
22+
* ```typescript
23+
* getFirstHeaderValue("value1, value2, value3"); // "value1"
24+
* getFirstHeaderValue(["value1", "value2"]); // "value1"
25+
* getFirstHeaderValue(undefined); // undefined
26+
* ```
27+
*/
28+
export function getFirstHeaderValue(
29+
value: string | string[] | undefined | null,
30+
): string | undefined {
31+
return value?.toString().split(',', 1)[0]?.trim();
32+
}
33+
34+
/**
35+
* Checks if a specific proxy header is allowed.
36+
*
37+
* @param headerName - The name of the proxy header to check.
38+
* @param trustProxyHeaders - A set of allowed proxy headers.
39+
* @returns `true` if the header is allowed, `false` otherwise.
40+
*/
41+
export function isProxyHeaderAllowed(
42+
headerName: string,
43+
trustProxyHeaders: ReadonlySet<string>,
44+
): boolean {
45+
return (
46+
trustProxyHeaders.has(TRUST_ALL_PROXY_HEADERS) ||
47+
trustProxyHeaders.has(headerName.toLowerCase())
48+
);
49+
}
50+
51+
/**
52+
* Normalizes the `trustProxyHeaders` option to a consistent representation.
53+
* @param trustProxyHeaders The input `trustProxyHeaders` value.
54+
* @returns A `Set<string>` of normalized header names.
55+
*/
56+
export function normalizeTrustProxyHeaders(
57+
trustProxyHeaders: boolean | readonly string[] | undefined,
58+
): ReadonlySet<string> {
59+
if (!trustProxyHeaders) {
60+
return new Set();
61+
}
62+
63+
if (trustProxyHeaders === true) {
64+
return new Set([TRUST_ALL_PROXY_HEADERS]);
65+
}
66+
67+
const normalizedTrustedProxyHeaders = new Set<string>();
68+
for (const header of trustProxyHeaders) {
69+
const lowerHeader = header.toLowerCase();
70+
if (lowerHeader === TRUST_ALL_PROXY_HEADERS) {
71+
throw new Error(
72+
`"${TRUST_ALL_PROXY_HEADERS}" is not allowed as a value for the "trustProxyHeaders" option.`,
73+
);
74+
}
75+
const isValid = lowerHeader === 'forwarded' || lowerHeader.startsWith('x-forwarded-');
76+
if (!isValid) {
77+
throw new Error(
78+
`"${header}" is not a valid proxy header. Trusted proxy headers must be "forwarded" or start with "x-forwarded-".`,
79+
);
80+
}
81+
normalizedTrustedProxyHeaders.add(lowerHeader);
82+
}
83+
84+
return normalizedTrustedProxyHeaders;
85+
}
86+
87+
/**
88+
* Parses the standard `Forwarded` header (RFC 7239).
89+
* It extracts the parameters from the first (leftmost) element in the header.
90+
*
91+
* @param headerValue - The value of the `Forwarded` header.
92+
* @returns A record of lowercase parameter names to their values.
93+
*/
94+
export function parseForwardedHeader(
95+
headerValue: string | null | undefined,
96+
): Record<string, string> {
97+
if (!headerValue) {
98+
return {};
99+
}
100+
101+
const params: Record<string, string> = {};
102+
let inQuotes = false;
103+
let escaped = false;
104+
let currentKey = '';
105+
let currentValue = '';
106+
let isParsingValue = false;
107+
let isKeyEnded = false;
108+
let isParsingValueEnded = false;
109+
110+
for (const char of headerValue) {
111+
if (escaped) {
112+
escaped = false;
113+
if (isParsingValue) {
114+
currentValue += char;
115+
} else {
116+
currentKey += char;
117+
}
118+
continue;
119+
}
120+
121+
if (char === '\\') {
122+
if (inQuotes) {
123+
escaped = true;
124+
} else if (isParsingValue) {
125+
currentValue += char;
126+
} else {
127+
currentKey += char;
128+
}
129+
continue;
130+
}
131+
132+
if (char === '"') {
133+
inQuotes = !inQuotes;
134+
continue;
135+
}
136+
137+
if (inQuotes) {
138+
if (isParsingValue) {
139+
currentValue += char;
140+
} else {
141+
currentKey += char;
142+
}
143+
continue;
144+
}
145+
146+
if (char === ',') {
147+
addParam(currentKey, currentValue, isParsingValue, params);
148+
break;
149+
}
150+
151+
if (char === ';') {
152+
addParam(currentKey, currentValue, isParsingValue, params);
153+
currentKey = '';
154+
currentValue = '';
155+
isParsingValue = false;
156+
isKeyEnded = false;
157+
isParsingValueEnded = false;
158+
continue;
159+
}
160+
161+
if (char === '=') {
162+
if (!isParsingValue) {
163+
isParsingValue = true;
164+
} else {
165+
currentValue += char;
166+
}
167+
continue;
168+
}
169+
170+
if (char === ' ' || char === '\t') {
171+
if (isParsingValue) {
172+
if (currentValue.length > 0) {
173+
isParsingValueEnded = true;
174+
}
175+
} else if (currentKey.length > 0) {
176+
isKeyEnded = true;
177+
}
178+
continue;
179+
}
180+
181+
if (isParsingValue) {
182+
if (!isParsingValueEnded) {
183+
currentValue += char;
184+
}
185+
} else if (isKeyEnded) {
186+
currentKey = char;
187+
isKeyEnded = false;
188+
} else {
189+
currentKey += char;
190+
}
191+
}
192+
193+
if (currentKey || currentValue || isParsingValue) {
194+
addParam(currentKey, currentValue, isParsingValue, params);
195+
}
196+
197+
return params;
198+
}
199+
200+
/**
201+
* Helper function to add a parameter to the params object.
202+
* @param key - The key to add.
203+
* @param value - The value to add.
204+
* @param hasValue - Whether the parameter has a value.
205+
* @param params - The params object to add the parameter to.
206+
*/
207+
function addParam(
208+
key: string,
209+
value: string,
210+
hasValue: boolean,
211+
params: Record<string, string>,
212+
): void {
213+
if (!hasValue) {
214+
return;
215+
}
216+
217+
const trimmedKey = key.trim().toLowerCase();
218+
if (trimmedKey) {
219+
params[trimmedKey] = value;
220+
}
221+
}

‎packages/angular/ssr/src/utils/ng.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ import {
2424
} from '@angular/platform-server';
2525
import { ActivatedRoute, Router } from '@angular/router';
2626
import { Console } from '../console';
27+
import { getFirstHeaderValue } from './headers';
2728
import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url';
28-
import { getFirstHeaderValue } from './validation';
2929

3030
/**
3131
* Represents the bootstrap mechanism for an Angular application.

0 commit comments

Comments
 (0)