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
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { executeDevServer } from '../../index';
import { executeOnceAndGet } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
import { text } from 'node:stream/consumers';

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

Expand All @@ -33,6 +34,7 @@ describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupT

expect(result?.success).toBeTrue();
expect(response?.statusCode).toBe(403);
expect(response && (await text(response))).toContain('angular.json');
});

it('does not allow an invalid host when option is an empty array', async () => {
Expand All @@ -47,6 +49,7 @@ describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupT

expect(result?.success).toBeTrue();
expect(response?.statusCode).toBe(403);
expect(response && (await text(response))).toContain('angular.json');
});

it('allows a host when specified in the option', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* @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 type { IncomingMessage, ServerResponse } from 'node:http';
import type { Connect } from 'vite';

export function patchHostValidationMiddleware(middlewares: Connect.Server): void {
const entry = middlewares.stack.find(
({ handle }) =>
typeof handle === 'function' && handle.name.startsWith('hostValidationMiddleware'),
);

if (typeof entry?.handle !== 'function') {
return;
}

const originalHandle = entry.handle as Connect.NextHandleFunction;

entry.handle = function angularHostValidationMiddleware(
req: IncomingMessage,
res: ServerResponse,
next: (err?: unknown) => void,
) {
originalHandle(
req,
{
writeHead: (code) => {
res.writeHead(code, { 'content-type': 'text/html' });
},
end: () => {
const hostname = req.headers.host?.toLowerCase().split(':')[0] ?? '';
res.end(html403(hostname));
},
} as ServerResponse,
next,
);
};
}

function html403(hostname: string): string {
return `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Blocked request</title>
<style>
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,sans-serif;
line-height:1.4;margin:2rem;color:#1f2937}
code{background:#f3f4f6;padding:.15rem .35rem;border-radius:.25rem}
main{max-width:760px;margin:0 auto}
h1{font-size:1.5rem;margin-bottom:.75rem}
p{margin:.5rem 0}
pre{background:#f9fafb;border:1px solid #e5e7eb;padding:.75rem;border-radius:.5rem;overflow:auto}
</style>
</head>
<body>
<main>
<h1>Blocked request. This host ("${hostname}") is not allowed.</h1>
<p>To allow this host, add it to <code>allowedHosts</code> under the <code>serve</code> target in <code>angular.json</code>.</p>
<pre><code>{
"serve": {
"options": {
"allowedHosts": ["${hostname}"]
}
}
}</code></pre>
</main>
</body>
</html>`;
}
1 change: 1 addition & 0 deletions packages/angular/build/src/tools/vite/middlewares/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export {
export { createAngularHeadersMiddleware } from './headers-middleware';
export { createAngularComponentMiddleware } from './component-middleware';
export { createChromeDevtoolsMiddleware } from './chrome-devtools-middleware';
export { patchHostValidationMiddleware } from './host-check-middleware';
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
createAngularSsrExternalMiddleware,
createAngularSsrInternalMiddleware,
createChromeDevtoolsMiddleware,
patchHostValidationMiddleware,
} from '../middlewares';
import { AngularMemoryOutputFiles, AngularOutputAssets } from '../utils';

Expand Down Expand Up @@ -109,6 +110,8 @@ export function createAngularSetupMiddlewaresPlugin(
// before the built-in HTML middleware
// eslint-disable-next-line @typescript-eslint/no-misused-promises
return async () => {
patchHostValidationMiddleware(server.middlewares);

if (ssrMode === ServerSsrMode.ExternalSsrMiddleware) {
server.middlewares.use(
await createAngularSsrExternalMiddleware(server, indexHtmlTransformer),
Expand Down