Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@uppy/companion: pass fetched origins to window.postMessage() #5529

Merged
merged 3 commits into from
Dec 17, 2024

Conversation

Murderlon
Copy link
Member

Closes #5310

This fixes the Companion side of the issue. Another change is required on the api side.

When the origins don't match the screen ends up with a 404.

@Murderlon Murderlon requested a review from mifi November 28, 2024 14:09
@Murderlon Murderlon self-assigned this Nov 28, 2024
Copy link
Contributor

github-actions bot commented Nov 28, 2024

Diff output files
diff --git a/packages/@uppy/companion/lib/companion.js b/packages/@uppy/companion/lib/companion.js
index 333b8b9..055c7ec 100644
--- a/packages/@uppy/companion/lib/companion.js
+++ b/packages/@uppy/companion/lib/companion.js
@@ -224,6 +224,7 @@ module.exports.app = (optionsArg = {}) => {
           key,
           secret,
           redirect_uri: getRedirectUri(),
+          origins: ["http://localhost:5173"],
         },
       });
     });
diff --git a/packages/@uppy/companion/lib/server/controllers/connect.d.ts b/packages/@uppy/companion/lib/server/controllers/connect.d.ts
index 668b7e4..d638d03 100644
--- a/packages/@uppy/companion/lib/server/controllers/connect.d.ts
+++ b/packages/@uppy/companion/lib/server/controllers/connect.d.ts
@@ -1,2 +1,13 @@
 declare function _exports(req: object, res: object, next: any): void;
+declare namespace _exports {
+    export { isOriginAllowed };
+}
 export = _exports;
+/**
+ * Derived from `cors` npm package.
+ * @see https://github.com/expressjs/cors/blob/791983ebc0407115bc8ae8e64830d440da995938/lib/index.js#L19-L34
+ * @param {string} origin
+ * @param {*} allowedOrigins
+ * @returns {boolean}
+ */
+declare function isOriginAllowed(origin: string, allowedOrigins: any): boolean;
diff --git a/packages/@uppy/companion/lib/server/controllers/connect.js b/packages/@uppy/companion/lib/server/controllers/connect.js
index 7d7d616..f436472 100644
--- a/packages/@uppy/companion/lib/server/controllers/connect.js
+++ b/packages/@uppy/companion/lib/server/controllers/connect.js
@@ -107,3 +107,4 @@ module.exports = function connect(req, res, next) {
   }
   encodeStateAndRedirect(req, res, stateObj);
 };
+module.exports.isOriginAllowed = isOriginAllowed;
diff --git a/packages/@uppy/companion/lib/server/controllers/index.d.ts b/packages/@uppy/companion/lib/server/controllers/index.d.ts
index 044ac31..6b64f8b 100644
--- a/packages/@uppy/companion/lib/server/controllers/index.d.ts
+++ b/packages/@uppy/companion/lib/server/controllers/index.d.ts
@@ -1,12 +1,15 @@
 export let callback: (req: any, res: any, next: Function) => any;
 export let deauthorizationCallback: typeof import("./deauth-callback");
-export let sendToken: (req: any, res: any, next: Function) => void;
+export let sendToken: (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => void | import("express").Response<any, Record<string, any>>;
 export let get: typeof import("./get");
 export let thumbnail: typeof import("./thumbnail");
 export let list: typeof import("./list");
 export let simpleAuth: typeof import("./simple-auth");
 export let logout: typeof import("./logout");
-export let connect: (req: any, res: any, next: any) => void;
+export let connect: {
+    (req: any, res: any, next: any): void;
+    isOriginAllowed: typeof import("./connect").isOriginAllowed;
+};
 export let preauth: typeof import("./preauth");
 export let redirect: (req: any, res: any) => void;
 export let refreshToken: typeof import("./refresh-token");
diff --git a/packages/@uppy/companion/lib/server/controllers/send-token.d.ts b/packages/@uppy/companion/lib/server/controllers/send-token.d.ts
index 097d912..31373f8 100644
--- a/packages/@uppy/companion/lib/server/controllers/send-token.d.ts
+++ b/packages/@uppy/companion/lib/server/controllers/send-token.d.ts
@@ -1,2 +1,2 @@
-declare function _exports(req: object, res: object, next: Function): void;
+declare function _exports(req: import('express').Request, res: import('express').Response, next: import('express').NextFunction): void | import("express").Response<any, Record<string, any>>;
 export = _exports;
diff --git a/packages/@uppy/companion/lib/server/controllers/send-token.js b/packages/@uppy/companion/lib/server/controllers/send-token.js
index 5769dc2..4d397a4 100644
--- a/packages/@uppy/companion/lib/server/controllers/send-token.js
+++ b/packages/@uppy/companion/lib/server/controllers/send-token.js
@@ -1,6 +1,7 @@
 "use strict";
 Object.defineProperty(exports, "__esModule", { value: true });
 const serialize = require("serialize-javascript");
+const { isOriginAllowed } = require("./connect");
 const oAuthState = require("../helpers/oauth-state");
 /**
  * @param {string} token uppy auth token
@@ -43,17 +44,29 @@ const htmlContent = (token, origin) => {
     </html>`;
 };
 /**
- * @param {object} req
- * @param {object} res
- * @param {Function} next
+ * @param {import('express').Request} req
+ * @param {import('express').Response} res
+ * @param {import('express').NextFunction} next
  */
 module.exports = function sendToken(req, res, next) {
-  const uppyAuthToken = req.companion.authToken;
+  // @ts-expect-error untyped
+  const { companion } = req;
+  const uppyAuthToken = companion.authToken;
   const { state } = oAuthState.getGrantDynamicFromRequest(req);
-  if (state) {
-    const origin = oAuthState.getFromState(state, "origin", req.companion.options.secret);
-    res.send(htmlContent(uppyAuthToken, origin));
-    return;
+  if (!state) {
+    return next();
   }
-  next();
+  const clientOrigin = oAuthState.getFromState(state, "origin", companion.options.secret);
+  const customerDefinedAllowedOrigins = oAuthState.getFromState(
+    state,
+    "customerDefinedAllowedOrigins",
+    companion.options.secret,
+  );
+  if (
+    customerDefinedAllowedOrigins
+    && !isOriginAllowed(clientOrigin, customerDefinedAllowedOrigins)
+  ) {
+    return next();
+  }
+  return res.send(htmlContent(uppyAuthToken, clientOrigin));
 };
diff --git a/packages/@uppy/companion/lib/server/provider/credentials.js b/packages/@uppy/companion/lib/server/provider/credentials.js
index cdd6fb2..e559a03 100644
--- a/packages/@uppy/companion/lib/server/provider/credentials.js
+++ b/packages/@uppy/companion/lib/server/provider/credentials.js
@@ -97,10 +97,31 @@ exports.getCredentialsOverrideMiddleware = (providers, companionOptions) => {
         return;
       }
       const credentials = await fetchProviderKeys(providerName, companionOptions, payload);
+      // Besides the key and secret the fetched credentials can also contain `origins`,
+      // which is an array of strings of allowed origins to prevent any origin from getting the OAuth
+      // token through window.postMessage (see comment in connect.js).
+      // postMessage happens in send-token.js, which is a different request, so we need to put the allowed origins
+      // on the encrypted session state to access it later there.
+      if (Array.isArray(credentials.origins) && credentials.origins.length > 0) {
+        const decodedState = oAuthState.decodeState(state, companionOptions.secret);
+        decodedState.customerDefinedAllowedOrigins = credentials.origins;
+        const newState = oAuthState.encodeState(decodedState, companionOptions.secret);
+        // @ts-expect-error untyped
+        req.session.grant = {
+          // @ts-expect-error untyped
+          ...req.session.grant,
+          dynamic: {
+            // @ts-expect-error untyped
+            ...req.session.grant?.dynamic,
+            state: newState,
+          },
+        };
+      }
       res.locals.grant = {
         dynamic: {
           key: credentials.key,
           secret: credentials.secret,
+          origins: credentials.origins,
         },
       };
       if (credentials.redirect_uri) {
diff --git a/packages/@uppy/companion/lib/server/provider/index.js b/packages/@uppy/companion/lib/server/provider/index.js
index 12e8acb..126720c 100644
--- a/packages/@uppy/companion/lib/server/provider/index.js
+++ b/packages/@uppy/companion/lib/server/provider/index.js
@@ -123,7 +123,7 @@ module.exports.addProviderOptions = (companionOptions, grantConfig, getOauthProv
       grantConfig[oauthProvider].secret = providerOptions[providerName].secret;
       if (providerOptions[providerName].credentialsURL) {
         // eslint-disable-next-line no-param-reassign
-        grantConfig[oauthProvider].dynamic = ["key", "secret", "redirect_uri"];
+        grantConfig[oauthProvider].dynamic = ["key", "secret", "redirect_uri", "origins"];
       }
       const provider = exports.getDefaultProviders()[providerName];
       Object.assign(grantConfig[oauthProvider], provider.getExtraGrantConfig());

Copy link
Contributor

@mifi mifi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one simplification, other than that lgtm!

Co-authored-by: Mikael Finstad <finstaden@gmail.com>
@Murderlon Murderlon merged commit 07956e2 into main Dec 17, 2024
19 checks passed
@Murderlon Murderlon deleted the companion-fetched-origins branch December 17, 2024 12:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

@uppy/companion: include origin in dynamic customer credentials
2 participants