stripe / stripe-apps

Stripe Apps lets you embed custom user experiences directly in the Stripe Dashboard and orchestrate the Stripe API.
https://stripe.com/docs/stripe-apps
MIT License
148 stars 73 forks source link

External api request is blocked by cors #981

Closed TilWiggers closed 4 months ago

TilWiggers commented 4 months ago

Describe the bug I want to fetch data from an external api from a "Stripe Apps frontend component". But I get the error: "Content-Security-Policy: The page’s settings blocked the loading of a resource at https://google.com/ (“connect-src”)."

To Reproduce Steps to reproduce the behavior:

  1. Specify the url in the manifest:
    "content_security_policy": {
      "connect-src": [
        "https://google.com"
      ],
      "image-src": null,
      "purpose": "test"
    }
  2. Invoke fetch
    fetch("https://google.com", {
    body,
    method: "GET",
    headers: {
        "Authorization": this.token,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    })

Expected behavior I expect the request not to be blocked by CORS.

Screenshots image

Desktop:

Additional context I double checked by using the "isSourceInAuthorizedCSP" function to confirm that the url is authorized.

console.log("isSourceInAuthorizedCSP", await isSourceInAuthorizedCSP(`https://google.com`), `https://google.com`);

https://google.com is used as a placeholder for the actual api endpoint. The actual api states:

This API features Cross-Origin Resource Sharing (CORS). It enables cross-domain communication from the browser. All responses have a wildcard same-origin which makes them completely public and accessible to everyone, including any code on any site.

bensontrent commented 4 months ago

You'll need to proxy your request to google to handle cors. For example in a Express app, you can add the necessary cors headers:

import cors from "cors";
import express from "express";
import { createProxyMiddleware } from 'http-proxy-middleware';
const app = express();

app.use(cors());

const GoogleProxy = createProxyMiddleware({
  target: 'https://www.google.com', // target host with the same base path
  changeOrigin: true,
  autoRewrite:true,
  logLevel: 'debug',
  pathRewrite: {
    [`^/api/google`]: '',
  },
});
app.use('/api/google', GoogleProxy );

You would then change your fetch to:

fetch("https://api.MYDOMAIN.com/api/google", {
    body,
    method: "GET",
    headers: {
        "Authorization": this.token,
        "Content-Type": "application/x-www-form-urlencoded"
    }
})

See https://docs.stripe.com/stripe-apps/build-backend#handle-cross-origin-resource-sharing-(cors)

TilWiggers commented 4 months ago

The proxy did the trick. Thanks!