Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 && 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 && text(response)).toContain('angular.json');
});

it('allows a host when specified in the option', async () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/angular/build/src/builders/dev-server/vite/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ export async function setupServer(
ssrMode,
resetComponentUpdates: () => templateUpdates.clear(),
projectRoot: serverOptions.projectRoot,
allowedHosts: serverOptions.allowedHosts,
devHost: serverOptions.host,
}),
createRemoveIdPrefixPlugin(externalMetadata.explicitBrowser),
await createAngularSsrTransformPlugin(serverOptions.workspaceRoot),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* @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
*/

export 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}
.box{max-width:760px;margin:0 auto}
h1{font-size:1.5rem;margin-bottom:.75rem}
p{margin:.5rem 0}
.muted{color:#6b7280}
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 { html403 } from './host-check-middleware';
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/

import { IncomingMessage, ServerResponse } from 'node:http';
import type { Connect, Plugin } from 'vite';
import {
ComponentStyleRecord,
Expand All @@ -17,6 +18,7 @@ import {
createAngularSsrExternalMiddleware,
createAngularSsrInternalMiddleware,
createChromeDevtoolsMiddleware,
html403,
} from '../middlewares';
import { AngularMemoryOutputFiles, AngularOutputAssets } from '../utils';

Expand Down Expand Up @@ -55,6 +57,8 @@ interface AngularSetupMiddlewaresPluginOptions {
ssrMode: ServerSsrMode;
resetComponentUpdates: () => void;
projectRoot: string;
allowedHosts: true | string[];
devHost: string;
}

async function createEncapsulateStyle(): Promise<
Expand Down Expand Up @@ -109,6 +113,36 @@ export function createAngularSetupMiddlewaresPlugin(
// before the built-in HTML middleware
// eslint-disable-next-line @typescript-eslint/no-misused-promises
return async () => {
// Vite/Connect do not expose a typed stack, cast once to a precise structural type.
const entry = server.middlewares.stack.find(
({ handle }) =>
typeof handle === 'function' && handle.name.startsWith('hostValidationMiddleware'),
);

if (typeof entry?.handle === 'function') {
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,
);
};
}

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