Skip to content

fix(@angular/build): support Vite allowedHosts option for development server #29466

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 1 commit into from
Jan 23, 2025
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
1 change: 1 addition & 0 deletions goldens/public-api/angular/build/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export enum BuildOutputFileType {

// @public
export type DevServerBuilderOptions = {
allowedHosts?: AllowedHosts;
buildTarget: string;
headers?: {
[key: string]: string;
Expand Down
2 changes: 2 additions & 0 deletions packages/angular/build/src/builders/dev-server/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export async function normalizeOptions(
sslCert,
sslKey,
prebundle,
allowedHosts,
} = options;

// Return all the normalized options
Expand All @@ -128,5 +129,6 @@ export async function normalizeOptions(
// Prebundling defaults to true but requires caching to function
prebundle: cacheOptions.enabled && !optimization.scripts && prebundle,
inspect,
allowedHosts: allowedHosts ? allowedHosts : [],
};
}
17 changes: 17 additions & 0 deletions packages/angular/build/src/builders/dev-server/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@
"type": "string",
"description": "SSL certificate to use for serving HTTPS."
},
"allowedHosts": {
"description": "The hosts that can access the development server. This option sets the Vite option of the same name. For further details: https://vite.dev/config/server-options.html#server-allowedhosts",
"default": [],
"oneOf": [
{
"type": "array",
"description": "List of hosts that are allowed to access the development server.",
"items": {
"type": "string"
}
},
{
"type": "boolean",
"description": "Indicates that all hosts are allowed. This is not recommended and a security risk."
}
]
},
"headers": {
"type": "object",
"description": "Custom HTTP headers to be added to all responses.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
*/

import { lastValueFrom, mergeMap, take, timeout } from 'rxjs';
import { URL } from 'url';
import { get, IncomingMessage, RequestOptions } from 'node:http';
import { text } from 'node:stream/consumers';
import {
BuilderHarness,
BuilderHarnessExecutionOptions,
Expand Down Expand Up @@ -41,3 +42,49 @@ export async function executeOnceAndFetch<T>(
),
);
}

/**
* Executes the builder and then immediately performs a GET request
* via the Node.js `http` builtin module. This is useful for cases
* where the `fetch` API is limited such as testing different `Host`
* header values with the development server.
* The `fetch` based alternative is preferred otherwise.
*
* @param harness A builder harness instance.
* @param url The URL string to get.
* @param options An options object.
* @returns
*/
export async function executeOnceAndGet<T>(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider: Would it be worth sharing the "executeOnce" part of these two functions and refactoring that into a shared utility so the major difference is the fetch vs. http part? This way future changes don't risk diverging the two.

harness: BuilderHarness<T>,
url: string,
options?: Partial<BuilderHarnessExecutionOptions> & { request?: RequestOptions },
): Promise<BuilderHarnessExecutionResult & { response?: IncomingMessage; content?: string }> {
return lastValueFrom(
harness.execute().pipe(
timeout(30000),
mergeMap(async (executionResult) => {
let response = undefined;
let content = undefined;
if (executionResult.result?.success) {
let baseUrl = `${executionResult.result.baseUrl}`;
baseUrl = baseUrl[baseUrl.length - 1] === '/' ? baseUrl : `${baseUrl}/`;
const resolvedUrl = new URL(url, baseUrl);

response = await new Promise<IncomingMessage>((resolve) =>
get(resolvedUrl, options?.request ?? {}, resolve),
);

if (response.statusCode === 200) {
content = await text(response);
}

response.resume();
}

return { ...executionResult, response, content };
}),
take(1),
),
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { executeDevServer } from '../../index';
import { executeOnceAndGet } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';

const FETCH_HEADERS = Object.freeze({ Host: 'example.com' });

describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
describe('option: "allowedHosts"', () => {
beforeEach(async () => {
setupTarget(harness);

// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});

it('does not allow an invalid host when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});

const { result, response } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(response?.statusCode).toBe(403);
});

it('does not allow an invalid host when option is an empty array', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: [],
});

const { result, response } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(response?.statusCode).toBe(403);
});

it('allows a host when specified in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: ['example.com'],
});

const { result, content } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(content).toContain('<title>');
});

it('allows a host when option is true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: true,
});

const { result, content } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(content).toContain('<title>');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,7 @@ export async function setupServer(
strictPort: true,
host: serverOptions.host,
open: serverOptions.open,
allowedHosts: serverOptions.allowedHosts,
headers: serverOptions.headers,
// Disable the websocket if live reload is disabled (false/undefined are the only valid values)
ws: serverOptions.liveReload === false && serverOptions.hmr === false ? false : undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,22 @@ export function execute(
// New build system defaults hmr option to the value of liveReload
normalizedOptions.hmr ??= normalizedOptions.liveReload;

// New build system uses Vite's allowedHost option convention of true for disabling host checks
if (normalizedOptions.disableHostCheck) {
(normalizedOptions as unknown as { allowedHosts: true }).allowedHosts = true;
} else {
normalizedOptions.allowedHosts ??= [];
}

return defer(() =>
Promise.all([import('@angular/build/private'), import('../browser-esbuild')]),
).pipe(
switchMap(([{ serveWithVite, buildApplicationInternal }, { convertBrowserOptions }]) =>
serveWithVite(
normalizedOptions as typeof normalizedOptions & { hmr: boolean },
normalizedOptions as typeof normalizedOptions & {
hmr: boolean;
allowedHosts: true | string[];
},
builderName,
(options, context, codePlugins) => {
return builderName === '@angular-devkit/build-angular:browser-esbuild'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
},
"allowedHosts": {
"type": "array",
"description": "List of hosts that are allowed to access the dev server. This option has no effect when using the 'application' or other esbuild-based builders.",
"description": "List of hosts that are allowed to access the dev server.",
"default": [],
"items": {
"type": "string"
Expand All @@ -79,7 +79,7 @@
},
"disableHostCheck": {
"type": "boolean",
"description": "Don't verify connected clients are part of allowed hosts. This option has no effect when using the 'application' or other esbuild-based builders.",
"description": "Don't verify connected clients are part of allowed hosts.",
"default": false
},
"hmr": {
Expand Down
Loading