Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): update vite to version 5.4.14
Browse files Browse the repository at this point in the history
Version update from 5.1.8 to address advisory GHSA-vg6x-rcgg-rjx6

Vite version 5.4.12+, which is now used by the Angular CLI with the `application`/`browser-esbuild`
builders, contains a potentially breaking change for some development setups. Examples of such
setups include those that use reverse proxies or custom host names during development.
The change within a patch release was made by Vite to address a security vulnerability.
For projects that directly access the development server via `localhost`, no changes should
be needed. However, some development setups may now need to adjust the
`allowedHosts` development server option. This option can include an array
of host names that are allowed to communicate with the development server. The option
sets the corresponding Vite option within the Angular CLI.
For more information on the option and its specific behavior, please see the Vite
documentation located here:
https://vite.dev/config/server-options.html#server-allowedhosts

The following is an example of the configuration option allowing `example.com`:
```
"serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "allowedHosts": ["example.com"]
      },
```
  • Loading branch information
clydin committed Feb 12, 2025
1 parent 29c6b0d commit d832370
Show file tree
Hide file tree
Showing 9 changed files with 406 additions and 75 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@
"undici": "6.11.1",
"verdaccio": "5.29.2",
"verdaccio-auth-memory": "^10.0.0",
"vite": "5.1.8",
"vite": "5.4.14",
"watchpack": "2.4.0",
"webpack": "5.94.0",
"webpack-dev-middleware": "6.1.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/angular_devkit/build_angular/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"tree-kill": "1.2.2",
"tslib": "2.6.2",
"undici": "6.11.1",
"vite": "5.1.8",
"vite": "5.4.14",
"watchpack": "2.4.0",
"webpack": "5.94.0",
"webpack-dev-middleware": "6.1.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,6 @@ export function execute(
);
}

if (options.allowedHosts?.length) {
context.logger.warn(
`The "allowedHosts" option will not be used because it is not supported by the "${builderName}" builder.`,
);
}

if (options.publicHost) {
context.logger.warn(
`The "publicHost" option will not be used because it is not supported by the "${builderName}" builder.`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,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 Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/

import { IncomingMessage, RequestOptions, get } from 'node:http';
import { text } from 'node:stream/consumers';
import { lastValueFrom, mergeMap, take, timeout } from 'rxjs';
import { URL } from 'url';
import {
BuilderHarness,
BuilderHarnessExecutionOptions,
Expand Down Expand Up @@ -41,3 +42,48 @@ 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.
*/
export async function executeOnceAndGet<T>(
harness: BuilderHarness<T>,
url: string,
options?: Partial<BuilderHarnessExecutionOptions> & { request?: RequestOptions },
): Promise<BuilderHarnessExecutionResult & { response?: IncomingMessage; content?: string }> {
return lastValueFrom(
harness.execute().pipe(
timeout(30_000),
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
Expand Up @@ -7,65 +7,60 @@
*/

import { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
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, isViteRun) => {
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xdescribe : describe)('option: "allowedHosts"', () => {
beforeEach(async () => {
setupTarget(harness);
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isVite) => {
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,
});
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});

const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
it('does not allow an invalid host when option is not present', async () => {
harness.useTarget('serve', { ...BASE_OPTIONS });

expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
const { result, response, content } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

it('does not allow an invalid host when option is an empty array', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: [],
});
expect(result?.success).toBeTrue();
if (isVite) {
expect(response?.statusCode).toBe(403);
} else {
expect(content).toBe('Invalid Host header');
}
});

const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
it('does not allow an invalid host when option is an empty array', async () => {
harness.useTarget('serve', { ...BASE_OPTIONS, allowedHosts: [] });

expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
const { result, response, content } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

it('allows a host when specified in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: ['example.com'],
});
expect(result?.success).toBeTrue();
if (isVite) {
expect(response?.statusCode).toBe(403);
} else {
expect(content).toBe('Invalid Host header');
}
});

const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
it('allows a host when specified in the option', async () => {
harness.useTarget('serve', { ...BASE_OPTIONS, allowedHosts: ['example.com'] });

expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('<title>');
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 @@ -485,6 +485,7 @@ export async function setupServer(
strictPort: true,
host: serverOptions.host,
open: serverOptions.open,
allowedHosts: serverOptions.allowedHosts,
headers: serverOptions.headers,
proxy,
cors: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,7 @@ export function createAngularMemoryPlugin(options: AngularMemoryPluginOptions):
const codeContents = outputFiles.get(relativeFile)?.contents;
if (codeContents === undefined) {
if (relativeFile.endsWith('/node_modules/vite/dist/client/client.mjs')) {
return {
code: await loadViteClientCode(file),
map: await readFile(file + '.map', 'utf-8'),
};
return await loadViteClientCode(file);
}

return;
Expand Down Expand Up @@ -309,19 +306,21 @@ export function createAngularMemoryPlugin(options: AngularMemoryPluginOptions):
* @param file The absolute path to the Vite client code.
* @returns
*/
async function loadViteClientCode(file: string) {
async function loadViteClientCode(file: string): Promise<string> {
const originalContents = await readFile(file, 'utf-8');
const firstUpdate = originalContents.replace('You can also disable this overlay by setting', '');
assert(originalContents !== firstUpdate, 'Failed to update Vite client error overlay text. (1)');

const secondUpdate = firstUpdate.replace(
// eslint-disable-next-line max-len
'<code part="config-option-name">server.hmr.overlay</code> to <code part="config-option-value">false</code> in <code part="config-file-name">${hmrConfigName}.</code>',
const updatedContents = originalContents.replace(
`"You can also disable this overlay by setting ",
h("code", { part: "config-option-name" }, "server.hmr.overlay"),
" to ",
h("code", { part: "config-option-value" }, "false"),
" in ",
h("code", { part: "config-file-name" }, hmrConfigName),
"."`,
'',
);
assert(firstUpdate !== secondUpdate, 'Failed to update Vite client error overlay text. (2)');
assert(originalContents !== updatedContents, 'Failed to update Vite client error overlay text.');

return secondUpdate;
return updatedContents;
}

function pathnameWithoutBasePath(url: string, basePath: string): string {
Expand Down
Loading

0 comments on commit d832370

Please sign in to comment.