From be15b886c75d0ed9834aef38690d3169fcf16ef5 Mon Sep 17 00:00:00 2001
From: Alan Agius <alanagius@google.com>
Date: Wed, 12 Feb 2025 09:42:28 +0000
Subject: [PATCH] fix(@angular/build): configure Vite CORS option
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Vite's `allowedHosts` option does not enable CORS; instead, it allows the dev server to respond to requests with a matching hostname (e.g., http://example.com/main.js). It only verifies that the request’s hostname is on the allowed list. However, this does not consider the `origin` in the case of a CORS request.

This commit updates Vite's configuration to enable CORS.

Closes #29549
---
 packages/angular/build/src/builders/dev-server/schema.json    | 4 ++--
 packages/angular/build/src/builders/dev-server/vite-server.ts | 3 +++
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/packages/angular/build/src/builders/dev-server/schema.json b/packages/angular/build/src/builders/dev-server/schema.json
index 3d5cf155aa..c36d8614e4 100644
--- a/packages/angular/build/src/builders/dev-server/schema.json
+++ b/packages/angular/build/src/builders/dev-server/schema.json
@@ -37,12 +37,12 @@
       "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",
+      "description": "The hosts that the development server will respond to. 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.",
+          "description": "A list of hosts that the development server will respond to.",
           "items": {
             "type": "string"
           }
diff --git a/packages/angular/build/src/builders/dev-server/vite-server.ts b/packages/angular/build/src/builders/dev-server/vite-server.ts
index fcdf5e4293..6773e8945c 100644
--- a/packages/angular/build/src/builders/dev-server/vite-server.ts
+++ b/packages/angular/build/src/builders/dev-server/vite-server.ts
@@ -841,6 +841,9 @@ export async function setupServer(
           ? (proxy ?? {})
           : proxy,
       cors: {
+        // This will add the header `Access-Control-Allow-Origin: http://example.com`,
+        // where `http://example.com` is the requesting origin.
+        origin: true,
         // Allow preflight requests to be proxied.
         preflightContinue: true,
       },