From 7ad4d2561aff09320636bc0e31eee66bdf803c7b Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 30 Jan 2024 16:27:27 -0600 Subject: [PATCH 01/35] Added validation check for disparate FAUST_SECRET_KEYs --- .../src/healthCheck/validateFaustEnvVars.ts | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 066d18e89..371d29605 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -1,10 +1,10 @@ -import { getWpSecret } from '../utils/index.js'; +import { getWpSecret, getWpUrl } from '../utils/index.js'; import { errorLog, warnLog } from '../stdout/index.js'; /** * Validates that the appropriate Faust related environment variables are set. */ -export const validateFaustEnvVars = () => { +export const validateFaustEnvVars = async () => { if (!process.env.NEXT_PUBLIC_WORDPRESS_URL) { errorLog('Could not find NEXT_PUBLIC_WORDPRESS_URL environment variable.'); @@ -28,4 +28,31 @@ export const validateFaustEnvVars = () => { 'Please make sure your production Faust app runs with a WordPress instance on https!', ); } + if (getWpSecret()) { + // send secret key + + const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/check_key`; + const headers = { + 'x-faustwp-secret': getWpSecret() || '', + }; + + try { + const response = await fetch(apiUrl, { + headers, + method: 'POST', + timeout: 30000, // 30 seconds timeout + } as unknown as RequestInit); + if (response.status === 204) { + // Success: User receives a 204 status code + // Handle the successful response here + } else if (response.status === 401) { + // Unauthorized: User receives a 401 status code + warnLog( + 'Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings', + ); + } + } catch (error) { + console.log('error', error); + } + } }; From 9ec13b954e9eb44725eaf615f5a8bf463d787d51 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 30 Jan 2024 16:27:42 -0600 Subject: [PATCH 02/35] typo --- packages/faustwp-cli/src/healthCheck/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/src/healthCheck/index.ts b/packages/faustwp-cli/src/healthCheck/index.ts index ddfa3929d..83f0cf935 100644 --- a/packages/faustwp-cli/src/healthCheck/index.ts +++ b/packages/faustwp-cli/src/healthCheck/index.ts @@ -5,7 +5,7 @@ import { verifyGraphQLEndpoint } from './verifyGraphQLEndpoint.js'; * Ensure that everything Faust requires to run is available. */ export async function healthCheck(): Promise { - // Check Faust Env varibles before continuing. + // Check Faust Env variables before continuing. validateFaustEnvVars(); // Perform our health checks. From ab66bcb816f295026c56d30f5490de4625ffd288 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Mon, 5 Feb 2024 11:49:40 -0600 Subject: [PATCH 03/35] Continued tinkering with /validate_secret_key endpoint --- .../src/healthCheck/validateFaustEnvVars.ts | 10 +-- plugins/faustwp/includes/rest/callbacks.php | 86 +++++++++++++++++++ 2 files changed, 91 insertions(+), 5 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 371d29605..a96de12c3 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -30,12 +30,13 @@ export const validateFaustEnvVars = async () => { } if (getWpSecret()) { // send secret key - - const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/check_key`; + console.log('NEW TESTING FOR SECRET KEY'); + const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/authorize`; + console.log('apiUrl', apiUrl); const headers = { 'x-faustwp-secret': getWpSecret() || '', }; - + console.log('headers', headers); try { const response = await fetch(apiUrl, { headers, @@ -44,9 +45,8 @@ export const validateFaustEnvVars = async () => { } as unknown as RequestInit); if (response.status === 204) { // Success: User receives a 204 status code - // Handle the successful response here } else if (response.status === 401) { - // Unauthorized: User receives a 401 status code + // Unauthorized: User receives a 401 status code AND the message below warnLog( 'Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings', ); diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 7ef66ec6c..543738bd6 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -129,6 +129,17 @@ function register_rest_routes() { ) ); + // TODO: after initial set up of Postman call to auth, uncomment this. + register_rest_route( + 'faustwp/v1', + '/validate_secret_key', + array( + 'methods' => 'GET', + 'callback' => __NAMESPACE__ . '\\handle_rest_validate_secret_key_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_validate_secret_key_permission_callback', + ) + ); + /** * Faust.js packages now use `faustwp/v1/authorize`. * @@ -333,6 +344,8 @@ function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) return rest_authorize_permission_callback( $request ); } + + /** * Callback for WordPress register_rest_route() 'callback' parameter. * @@ -392,9 +405,14 @@ function handle_rest_authorize_callback( \WP_REST_Request $request ) { * @return bool True if current user can, false if else. */ function rest_authorize_permission_callback( \WP_REST_Request $request ) { + $secret_key = get_secret_key(); $header_key = $request->get_header( 'x-faustwp-secret' ); + // Add console log for get_secret_key() + error_log( 'Secret Key: ' . $secret_key ); + + if ( $secret_key && $header_key ) { return $secret_key === $header_key; } @@ -476,3 +494,71 @@ function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { ); return rest_ensure_response( $response ); } + +//TODO: after initial set up of Postman call to auth, uncomment this. +/** + * Callback for WordPress register_rest_route() 'callback' parameter. + * + * Handle POST /faustwp/v1/validate)_secret_key response. + * + * @link https://developer.wordpress.org/reference/functions/register_rest_route/ + * @link https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#endpoint-callback + * + * @param \WP_REST_Request $request Current \WP_REST_Request object. + * + * @return mixed A \WP_REST_Response, array, or \WP_Error. + */ +function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { + $code = trim( $request->get_param( 'code' ) ); + $refresh_token = trim( $request->get_param( 'refreshToken' ) ); + + if ( ! $code && ! $refresh_token ) { + return new \WP_Error( 'invalid_request', 'Missing authorization code or refresh token.' ); + } + + if ( $refresh_token ) { + $user = get_user_from_refresh_token( $refresh_token ); + } else { + $user = get_user_from_authorization_code( $code ); + } + + if ( ! $user ) { + return new \WP_Error( 'invalid_request', 'Invalid authorization code or refresh token.' ); + } + + $refresh_token_expiration = WEEK_IN_SECONDS * 2; + $access_token_expiration = MINUTE_IN_SECONDS * 5; + + $access_token = generate_access_token( $user, $access_token_expiration ); + $refresh_token = generate_refresh_token( $user, $refresh_token_expiration ); + + return array( + 'accessToken' => $access_token, + 'accessTokenExpiration' => ( time() + $access_token_expiration ), + 'refreshToken' => $refresh_token, + 'refreshTokenExpiration' => ( time() + $refresh_token_expiration ), + ); +} + +/** + * Callback to check permissions for requests to `faustwp/v1/authorize`. + * + * Authorized if the 'secret_key' settings value and http header 'x-faustwp-secret' match. + * + * @link https://developer.wordpress.org/reference/functions/register_rest_route/ + * @link https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#permissions-callback + * + * @param \WP_REST_Request $request The current \WP_REST_Request object. + * + * @return bool True if current user can, false if else. + */ +function rest_validate_secret_key_permission_callback( \WP_REST_Request $request ) { + $secret_key = get_secret_key(); + $header_key = $request->get_header( 'x-faustwp-secret' ); + + if ( $secret_key && $header_key ) { + return $secret_key === $header_key; + } + + return false; +} \ No newline at end of file From 900d903e2d40552993738233efe7f9fb25fb7834 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 6 Feb 2024 09:44:06 -0600 Subject: [PATCH 04/35] Cleaned up testing logs --- packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index a96de12c3..707a491e3 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -30,13 +30,10 @@ export const validateFaustEnvVars = async () => { } if (getWpSecret()) { // send secret key - console.log('NEW TESTING FOR SECRET KEY'); - const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/authorize`; - console.log('apiUrl', apiUrl); + const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/validate_secret_key`; const headers = { 'x-faustwp-secret': getWpSecret() || '', }; - console.log('headers', headers); try { const response = await fetch(apiUrl, { headers, From eee73ec2be5588cae502a4e0eb626f12e7127388 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 6 Feb 2024 09:44:21 -0600 Subject: [PATCH 05/35] Tweaked new endpoint --- plugins/faustwp/includes/rest/callbacks.php | 44 ++++++--------------- 1 file changed, 11 insertions(+), 33 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 543738bd6..01348e26a 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -129,12 +129,11 @@ function register_rest_routes() { ) ); - // TODO: after initial set up of Postman call to auth, uncomment this. register_rest_route( 'faustwp/v1', '/validate_secret_key', array( - 'methods' => 'GET', + 'methods' => 'POST', 'callback' => __NAMESPACE__ . '\\handle_rest_validate_secret_key_callback', 'permission_callback' => __NAMESPACE__ . '\\rest_validate_secret_key_permission_callback', ) @@ -495,53 +494,32 @@ function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { return rest_ensure_response( $response ); } -//TODO: after initial set up of Postman call to auth, uncomment this. /** * Callback for WordPress register_rest_route() 'callback' parameter. * - * Handle POST /faustwp/v1/validate)_secret_key response. + * Handle POST /faustwp/v1/validate_secret_key response. * * @link https://developer.wordpress.org/reference/functions/register_rest_route/ * @link https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#endpoint-callback * * @param \WP_REST_Request $request Current \WP_REST_Request object. * - * @return mixed A \WP_REST_Response, array, or \WP_Error. + * @return mixed A \WP_REST_Response, or \WP_Error. */ function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { - $code = trim( $request->get_param( 'code' ) ); - $refresh_token = trim( $request->get_param( 'refreshToken' ) ); - - if ( ! $code && ! $refresh_token ) { - return new \WP_Error( 'invalid_request', 'Missing authorization code or refresh token.' ); - } - - if ( $refresh_token ) { - $user = get_user_from_refresh_token( $refresh_token ); - } else { - $user = get_user_from_authorization_code( $code ); - } - - if ( ! $user ) { - return new \WP_Error( 'invalid_request', 'Invalid authorization code or refresh token.' ); - } - $refresh_token_expiration = WEEK_IN_SECONDS * 2; - $access_token_expiration = MINUTE_IN_SECONDS * 5; - - $access_token = generate_access_token( $user, $access_token_expiration ); - $refresh_token = generate_refresh_token( $user, $refresh_token_expiration ); - - return array( - 'accessToken' => $access_token, - 'accessTokenExpiration' => ( time() + $access_token_expiration ), - 'refreshToken' => $refresh_token, - 'refreshTokenExpiration' => ( time() + $refresh_token_expiration ), + return new \WP_REST_Response( + sprintf( + /* Translators: %s is replaced with the emoji indicating a successful sync. */ + esc_html__( 'Secret key validated!', 'faustwp' ), + '✅' + ), + 200 ); } /** - * Callback to check permissions for requests to `faustwp/v1/authorize`. + * Callback to check permissions for requests to `faustwp/v1/validate_secret_key`. * * Authorized if the 'secret_key' settings value and http header 'x-faustwp-secret' match. * From 5ed70489ed26e60e6555c004c87540b9813a14d6 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 6 Feb 2024 09:44:42 -0600 Subject: [PATCH 06/35] Updated package-lock --- package-lock.json | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/package-lock.json b/package-lock.json index 6265fe038..0e529a4b2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35589,6 +35589,66 @@ "plugins/faustwp": { "name": "@faustwp/wordpress-plugin", "version": "1.2.0" + }, + "packages/experimental-app-router/node_modules/@next/swc-android-arm-eabi": { + "version": "12.3.4", + "resolved": "https://registry.npmjs.org/@next/swc-android-arm-eabi/-/swc-android-arm-eabi-12.3.4.tgz", + "integrity": "sha512-cM42Cw6V4Bz/2+j/xIzO8nK/Q3Ly+VSlZJTa1vHzsocJRYz8KT6MrreXaci2++SIZCF1rVRCDgAg5PpqRibdIA==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "packages/experimental-app-router/node_modules/@next/swc-android-arm64": { + "version": "12.3.4", + "resolved": "https://registry.npmjs.org/@next/swc-android-arm64/-/swc-android-arm64-12.3.4.tgz", + "integrity": "sha512-5jf0dTBjL+rabWjGj3eghpLUxCukRhBcEJgwLedewEA/LJk2HyqCvGIwj5rH+iwmq1llCWbOky2dO3pVljrapg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "packages/experimental-app-router/node_modules/@next/swc-freebsd-x64": { + "version": "12.3.4", + "resolved": "https://registry.npmjs.org/@next/swc-freebsd-x64/-/swc-freebsd-x64-12.3.4.tgz", + "integrity": "sha512-KM9JXRXi/U2PUM928z7l4tnfQ9u8bTco/jb939pdFUHqc28V43Ohd31MmZD1QzEK4aFlMRaIBQOWQZh4D/E5lQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "packages/experimental-app-router/node_modules/@next/swc-linux-arm-gnueabihf": { + "version": "12.3.4", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-12.3.4.tgz", + "integrity": "sha512-3zqD3pO+z5CZyxtKDTnOJ2XgFFRUBciOox6EWkoZvJfc9zcidNAQxuwonUeNts6Xbm8Wtm5YGIRC0x+12YH7kw==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } } } } From 28dc657844dd0e12748ca8f0d754ebdeee14dd43 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 6 Feb 2024 15:44:53 -0600 Subject: [PATCH 07/35] Added @types/node as part of linting validateFaustEnvVars --- package-lock.json | 104 +++++++++++++++++++--------------------------- package.json | 1 + 2 files changed, 43 insertions(+), 62 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0e529a4b2..7f3200db3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "devDependencies": { "@changesets/cli": "^2.26.2", "@next/bundle-analyzer": "^13.2.4", + "@types/node": "^20.11.16", "@typescript-eslint/eslint-plugin": "^5.18.0", "@typescript-eslint/parser": "^5.18.0", "eslint": "^8.12.0", @@ -2166,6 +2167,12 @@ "npm": ">=6.0.0" } }, + "examples/next/getting-started/node_modules/@types/node": { + "version": "17.0.45", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", + "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==", + "dev": true + }, "examples/next/getting-started/node_modules/dotenv-flow": { "version": "3.2.0", "dev": true, @@ -8164,8 +8171,12 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "17.0.45", - "license": "MIT" + "version": "20.11.16", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.16.tgz", + "integrity": "sha512-gKb0enTmRCzXSSUJDq6/sPcqrfCv2mkkG6Jt/clpn5eiCbKTY+SgZUxo+p8ZKMof5dCp9vHQUAB7wOUTod22wQ==", + "dependencies": { + "undici-types": "~5.26.4" + } }, "node_modules/@types/normalize-package-data": { "version": "2.4.2", @@ -27007,6 +27018,11 @@ "node": ">=14.0" } }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, "node_modules/unicode-canonical-property-names-ecmascript": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz", @@ -29586,6 +29602,12 @@ "pretty-format": "^27.0.0" } }, + "packages/core/node_modules/@types/node": { + "version": "17.0.45", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", + "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==", + "dev": true + }, "packages/core/node_modules/@types/yargs": { "version": "16.0.6", "dev": true, @@ -31682,6 +31704,12 @@ "pretty-format": "^27.0.0" } }, + "packages/faustwp-core/node_modules/@types/node": { + "version": "17.0.45", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", + "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==", + "dev": true + }, "packages/faustwp-core/node_modules/@types/yargs": { "version": "16.0.6", "dev": true, @@ -33096,6 +33124,12 @@ "pretty-format": "^27.0.0" } }, + "packages/next/node_modules/@types/node": { + "version": "17.0.45", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", + "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==", + "dev": true + }, "packages/next/node_modules/@types/yargs": { "version": "16.0.6", "dev": true, @@ -34510,6 +34544,12 @@ "pretty-format": "^27.0.0" } }, + "packages/react/node_modules/@types/node": { + "version": "17.0.45", + "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", + "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==", + "dev": true + }, "packages/react/node_modules/@types/yargs": { "version": "16.0.6", "dev": true, @@ -35589,66 +35629,6 @@ "plugins/faustwp": { "name": "@faustwp/wordpress-plugin", "version": "1.2.0" - }, - "packages/experimental-app-router/node_modules/@next/swc-android-arm-eabi": { - "version": "12.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-android-arm-eabi/-/swc-android-arm-eabi-12.3.4.tgz", - "integrity": "sha512-cM42Cw6V4Bz/2+j/xIzO8nK/Q3Ly+VSlZJTa1vHzsocJRYz8KT6MrreXaci2++SIZCF1rVRCDgAg5PpqRibdIA==", - "cpu": [ - "arm" - ], - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "packages/experimental-app-router/node_modules/@next/swc-android-arm64": { - "version": "12.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-android-arm64/-/swc-android-arm64-12.3.4.tgz", - "integrity": "sha512-5jf0dTBjL+rabWjGj3eghpLUxCukRhBcEJgwLedewEA/LJk2HyqCvGIwj5rH+iwmq1llCWbOky2dO3pVljrapg==", - "cpu": [ - "arm64" - ], - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "packages/experimental-app-router/node_modules/@next/swc-freebsd-x64": { - "version": "12.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-freebsd-x64/-/swc-freebsd-x64-12.3.4.tgz", - "integrity": "sha512-KM9JXRXi/U2PUM928z7l4tnfQ9u8bTco/jb939pdFUHqc28V43Ohd31MmZD1QzEK4aFlMRaIBQOWQZh4D/E5lQ==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 10" - } - }, - "packages/experimental-app-router/node_modules/@next/swc-linux-arm-gnueabihf": { - "version": "12.3.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-12.3.4.tgz", - "integrity": "sha512-3zqD3pO+z5CZyxtKDTnOJ2XgFFRUBciOox6EWkoZvJfc9zcidNAQxuwonUeNts6Xbm8Wtm5YGIRC0x+12YH7kw==", - "cpu": [ - "arm" - ], - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } } } } diff --git a/package.json b/package.json index 7a202bb85..e15d43994 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "devDependencies": { "@changesets/cli": "^2.26.2", "@next/bundle-analyzer": "^13.2.4", + "@types/node": "^20.11.16", "@typescript-eslint/eslint-plugin": "^5.18.0", "@typescript-eslint/parser": "^5.18.0", "eslint": "^8.12.0", From d74940b8f14f4f31f4a3c03c81118249b81aa76a Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 6 Feb 2024 16:17:30 -0600 Subject: [PATCH 08/35] Ran PHP Code Sniffer command on file to fix linting errors --- plugins/faustwp/includes/rest/callbacks.php | 675 ++++++++++---------- 1 file changed, 345 insertions(+), 330 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 01348e26a..e751868e6 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -8,30 +8,30 @@ namespace WPE\FaustWP\REST; use function WPE\FaustWP\Auth\{ - get_user_from_access_token, - get_user_from_refresh_token, - get_user_from_authorization_code, - generate_refresh_token, - generate_access_token + get_user_from_access_token, + get_user_from_refresh_token, + get_user_from_authorization_code, + generate_refresh_token, + generate_access_token }; use function WPE\FaustWP\Settings\get_secret_key; use function WPE\FaustWP\Telemetry\{ - get_wp_version, - is_wpe, - get_anonymous_faustwp_data, - get_anonymous_wpgraphql_content_blocks_data, - get_telemetry_client_id + get_wp_version, + is_wpe, + get_anonymous_faustwp_data, + get_anonymous_wpgraphql_content_blocks_data, + get_telemetry_client_id }; use function WPE\FaustWP\Blocks\handle_uploaded_blockset; use function WPE\FaustWP\Settings\faustwp_get_setting; use function WPE\FaustWP\Settings\faustwp_update_setting; use function WPE\FaustWP\Settings\is_telemetry_enabled; -if ( ! defined( 'ABSPATH' ) ) { - exit; +if (! defined('ABSPATH') ) { + exit; } -add_filter( 'determine_current_user', __NAMESPACE__ . '\\rest_determine_current_user', 20 ); +add_filter('determine_current_user', __NAMESPACE__ . '\\rest_determine_current_user', 20); /** * Callback for WordPress 'determine_current_user' filter. * @@ -44,29 +44,30 @@ * * @return int|bool User ID if one has been determined, false otherwise. */ -function rest_determine_current_user( $user_id ) { - if ( $user_id ) { - return $user_id; - } - - if ( ! isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { - return $user_id; - } - - $parts = explode( ' ', trim( $_SERVER['HTTP_AUTHORIZATION'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - if ( count( $parts ) < 2 ) { - return $user_id; - } - - $wp_user = get_user_from_access_token( $parts[1] ); - if ( $wp_user ) { - $user_id = $wp_user->ID; - } - - return $user_id; +function rest_determine_current_user( $user_id ) +{ + if ($user_id ) { + return $user_id; + } + + if (! isset($_SERVER['HTTP_AUTHORIZATION']) ) { + return $user_id; + } + + $parts = explode(' ', trim($_SERVER['HTTP_AUTHORIZATION'])); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput + if (count($parts) < 2 ) { + return $user_id; + } + + $wp_user = get_user_from_access_token($parts[1]); + if ($wp_user ) { + $user_id = $wp_user->ID; + } + + return $user_id; } -add_action( 'rest_api_init', __NAMESPACE__ . '\\register_rest_routes' ); +add_action('rest_api_init', __NAMESPACE__ . '\\register_rest_routes'); /** * Callback for WordPress 'rest_api_init' action. * @@ -78,118 +79,120 @@ function rest_determine_current_user( $user_id ) { * * @return void */ -function register_rest_routes() { - register_rest_route( - 'faustwp/v1', - '/blockset', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_blockset_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_blockset_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/telemetry/decision', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_decision_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_decision_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/telemetry', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/authorize', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_authorize_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/process_telemetry', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_process_telemetry_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_process_telemetry_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/validate_secret_key', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_validate_secret_key_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_validate_secret_key_permission_callback', - ) - ); - - /** - * Faust.js packages now use `faustwp/v1/authorize`. - * - * @deprecated - */ - register_rest_route( - 'wpac/v1', - '/authorize', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', - 'permission_callback' => __NAMESPACE__ . '\\wpac_authorize_permission_callback', - ) - ); +function register_rest_routes() +{ + register_rest_route( + 'faustwp/v1', + '/blockset', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_blockset_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_blockset_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/telemetry/decision', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_decision_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_decision_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/telemetry', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/authorize', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_authorize_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/process_telemetry', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_process_telemetry_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_process_telemetry_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/validate_secret_key', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_validate_secret_key_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_validate_secret_key_permission_callback', + ) + ); + + /** + * Faust.js packages now use `faustwp/v1/authorize`. + * + * @deprecated + */ + register_rest_route( + 'wpac/v1', + '/authorize', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', + 'permission_callback' => __NAMESPACE__ . '\\wpac_authorize_permission_callback', + ) + ); } /** * Callback function to handle file upload and unzip. * - * @param \WP_REST_Request $request Full data about the request. + * @param \WP_REST_Request $request Full data about the request. * @return \WP_Error|WP_REST_Response */ -function handle_blockset_callback( \WP_REST_Request $request ) { - // Check if file is sent. - $files = $request->get_file_params(); - - if ( empty( $files['zipfile'] ) ) { - return new \WP_Error( 'no_file', __( 'No file was sent', 'faustwp' ), array( 'status' => 400 ) ); - } - - $file = $files['zipfile']; - - // Check for upload errors. - if ( $file['error'] ) { - return new \WP_Error( 'upload_error', __( 'File upload error', 'faustwp' ), array( 'status' => 400 ) ); - } - - $result = handle_uploaded_blockset( $file ); - - if ( is_wp_error( $result ) ) { - return $result; - } - - return new \WP_REST_Response( - sprintf( - /* Translators: %s is replaced with the emoji indicating a successful sync. */ - esc_html__( '%s Blockset sync complete!', 'faustwp' ), - '✅' - ), - 200 - ); +function handle_blockset_callback( \WP_REST_Request $request ) +{ + // Check if file is sent. + $files = $request->get_file_params(); + + if (empty($files['zipfile']) ) { + return new \WP_Error('no_file', __('No file was sent', 'faustwp'), array( 'status' => 400 )); + } + + $file = $files['zipfile']; + + // Check for upload errors. + if ($file['error'] ) { + return new \WP_Error('upload_error', __('File upload error', 'faustwp'), array( 'status' => 400 )); + } + + $result = handle_uploaded_blockset($file); + + if (is_wp_error($result) ) { + return $result; + } + + return new \WP_REST_Response( + sprintf( + /* Translators: %s is replaced with the emoji indicating a successful sync. */ + esc_html__('%s Blockset sync complete!', 'faustwp'), + '✅' + ), + 200 + ); } /** @@ -204,17 +207,18 @@ function handle_blockset_callback( \WP_REST_Request $request ) { * * @return mixed A \WP_REST_Response, array, or \WP_Error. */ -function handle_rest_telemetry_callback( \WP_REST_Request $request ) { - $data = array( - 'faustwp' => get_anonymous_faustwp_data(), - 'wpgraphql_content_blocks' => get_anonymous_wpgraphql_content_blocks_data(), - 'is_wpe' => is_wpe(), - 'multisite' => is_multisite(), - 'php_version' => PHP_VERSION, - 'wp_version' => get_wp_version(), - ); - - return new \WP_REST_Response( $data ); +function handle_rest_telemetry_callback( \WP_REST_Request $request ) +{ + $data = array( + 'faustwp' => get_anonymous_faustwp_data(), + 'wpgraphql_content_blocks' => get_anonymous_wpgraphql_content_blocks_data(), + 'is_wpe' => is_wpe(), + 'multisite' => is_multisite(), + 'php_version' => PHP_VERSION, + 'wp_version' => get_wp_version(), + ); + + return new \WP_REST_Response($data); } /** @@ -229,79 +233,80 @@ function handle_rest_telemetry_callback( \WP_REST_Request $request ) { * * @return mixed A \WP_REST_Response, array, or \WP_Error. */ -function handle_rest_process_telemetry_callback( \WP_REST_Request $request ) { - if ( ! is_telemetry_enabled() ) { - return new \WP_REST_Response( null, 204 ); - } - - $body = $request->get_json_params(); - - $faust_plugin_data = get_anonymous_faustwp_data(); - $content_blocks_plugin_data = get_anonymous_wpgraphql_content_blocks_data(); - - $ga_tracking_endpoint = 'https://www.google-analytics.com/mp/collect'; - $ga_tracking_id = 'G-KPVSTHK1G4'; - $ga_key = '-SLuZb8JTbWkWcT5BD032w'; - - $telemetry_data = array( - 'node_faustwp_core_version' => $body['node_faustwp_core_version'] ?? null, - 'node_faustwp_cli_version' => $body['node_faustwp_cli_version'] ?? null, - 'node_faustwp_blocks_version' => $body['node_faustwp_blocks_version'] ?? null, - 'node_apollo_client_version' => $body['node_apollo_client_version'] ?? null, - 'node_faustwp_block_editor_utils_version' => $body['node_faustwp_block_editor_utils_version'] ?? null, - 'node_faustwp_experimental_app_router_version' => $body['node_faustwp_experimental_app_router_version'] ?? null, - 'node_version' => $body['node_version'] ?? null, - 'node_next_version' => $body['node_next_version'] ?? null, - 'node_is_development' => $body['node_is_development'] ?? null, - 'command' => $body['command'] ?? null, - - 'setting_has_frontend_uri' => $faust_plugin_data['has_frontend_uri'], - 'setting_redirects_enabled' => $faust_plugin_data['redirects_enabled'], - 'setting_rewrites_enabled' => $faust_plugin_data['rewrites_enabled'], - 'setting_themes_disabled' => $faust_plugin_data['themes_disabled'], - 'setting_img_src_replacement_enabled' => $faust_plugin_data['image_source_replacement_enabled'], - 'faustwp_version' => $faust_plugin_data['version'], - - 'wpgraphql_content_blocks_version' => $content_blocks_plugin_data['version'], - - 'is_wpe' => is_wpe(), - 'multisite' => is_multisite(), - 'php_version' => PHP_VERSION, - 'wp_version' => get_wp_version(), - 'engagement_time_msec' => 100, - 'session_id' => md5( get_telemetry_client_id() ), - ); - - // Remove null values since GA rejects them. - $telemetry_data = array_filter( $telemetry_data ); - - $ga_telemetry_url = add_query_arg( - array( - 'measurement_id' => $ga_tracking_id, - 'api_secret' => $ga_key, - ), - $ga_tracking_endpoint - ); - - $telemetry_body = array( - 'client_id' => get_telemetry_client_id(), - 'events' => array( - array( - 'name' => 'telemetry_event', - 'params' => $telemetry_data, - ), - ), - ); - - wp_remote_post( - $ga_telemetry_url, - array( - 'body' => wp_json_encode( $telemetry_body ), - 'blocking' => false, - ) - ); - - return new \WP_REST_Response( array( $telemetry_body, $ga_telemetry_url ), 201 ); +function handle_rest_process_telemetry_callback( \WP_REST_Request $request ) +{ + if (! is_telemetry_enabled() ) { + return new \WP_REST_Response(null, 204); + } + + $body = $request->get_json_params(); + + $faust_plugin_data = get_anonymous_faustwp_data(); + $content_blocks_plugin_data = get_anonymous_wpgraphql_content_blocks_data(); + + $ga_tracking_endpoint = 'https://www.google-analytics.com/mp/collect'; + $ga_tracking_id = 'G-KPVSTHK1G4'; + $ga_key = '-SLuZb8JTbWkWcT5BD032w'; + + $telemetry_data = array( + 'node_faustwp_core_version' => $body['node_faustwp_core_version'] ?? null, + 'node_faustwp_cli_version' => $body['node_faustwp_cli_version'] ?? null, + 'node_faustwp_blocks_version' => $body['node_faustwp_blocks_version'] ?? null, + 'node_apollo_client_version' => $body['node_apollo_client_version'] ?? null, + 'node_faustwp_block_editor_utils_version' => $body['node_faustwp_block_editor_utils_version'] ?? null, + 'node_faustwp_experimental_app_router_version' => $body['node_faustwp_experimental_app_router_version'] ?? null, + 'node_version' => $body['node_version'] ?? null, + 'node_next_version' => $body['node_next_version'] ?? null, + 'node_is_development' => $body['node_is_development'] ?? null, + 'command' => $body['command'] ?? null, + + 'setting_has_frontend_uri' => $faust_plugin_data['has_frontend_uri'], + 'setting_redirects_enabled' => $faust_plugin_data['redirects_enabled'], + 'setting_rewrites_enabled' => $faust_plugin_data['rewrites_enabled'], + 'setting_themes_disabled' => $faust_plugin_data['themes_disabled'], + 'setting_img_src_replacement_enabled' => $faust_plugin_data['image_source_replacement_enabled'], + 'faustwp_version' => $faust_plugin_data['version'], + + 'wpgraphql_content_blocks_version' => $content_blocks_plugin_data['version'], + + 'is_wpe' => is_wpe(), + 'multisite' => is_multisite(), + 'php_version' => PHP_VERSION, + 'wp_version' => get_wp_version(), + 'engagement_time_msec' => 100, + 'session_id' => md5(get_telemetry_client_id()), + ); + + // Remove null values since GA rejects them. + $telemetry_data = array_filter($telemetry_data); + + $ga_telemetry_url = add_query_arg( + array( + 'measurement_id' => $ga_tracking_id, + 'api_secret' => $ga_key, + ), + $ga_tracking_endpoint + ); + + $telemetry_body = array( + 'client_id' => get_telemetry_client_id(), + 'events' => array( + array( + 'name' => 'telemetry_event', + 'params' => $telemetry_data, + ), + ), + ); + + wp_remote_post( + $ga_telemetry_url, + array( + 'body' => wp_json_encode($telemetry_body), + 'blocking' => false, + ) + ); + + return new \WP_REST_Response(array( $telemetry_body, $ga_telemetry_url ), 201); } /** @@ -313,8 +318,9 @@ function handle_rest_process_telemetry_callback( \WP_REST_Request $request ) { * * @return bool True if current user can, false if else. */ -function rest_blockset_permission_callback( \WP_REST_Request $request ) { - return rest_authorize_permission_callback( $request ); +function rest_blockset_permission_callback( \WP_REST_Request $request ) +{ + return rest_authorize_permission_callback($request); } /** @@ -326,8 +332,9 @@ function rest_blockset_permission_callback( \WP_REST_Request $request ) { * * @return bool True if current user can, false if else. */ -function rest_telemetry_permission_callback( \WP_REST_Request $request ) { - return rest_authorize_permission_callback( $request ); +function rest_telemetry_permission_callback( \WP_REST_Request $request ) +{ + return rest_authorize_permission_callback($request); } /** @@ -339,8 +346,9 @@ function rest_telemetry_permission_callback( \WP_REST_Request $request ) { * * @return bool True if current user can, false if else. */ -function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) { - return rest_authorize_permission_callback( $request ); +function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) +{ + return rest_authorize_permission_callback($request); } @@ -359,36 +367,37 @@ function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) * * @return mixed A \WP_REST_Response, array, or \WP_Error. */ -function handle_rest_authorize_callback( \WP_REST_Request $request ) { - $code = trim( $request->get_param( 'code' ) ); - $refresh_token = trim( $request->get_param( 'refreshToken' ) ); - - if ( ! $code && ! $refresh_token ) { - return new \WP_Error( 'invalid_request', 'Missing authorization code or refresh token.' ); - } - - if ( $refresh_token ) { - $user = get_user_from_refresh_token( $refresh_token ); - } else { - $user = get_user_from_authorization_code( $code ); - } - - if ( ! $user ) { - return new \WP_Error( 'invalid_request', 'Invalid authorization code or refresh token.' ); - } - - $refresh_token_expiration = WEEK_IN_SECONDS * 2; - $access_token_expiration = MINUTE_IN_SECONDS * 5; - - $access_token = generate_access_token( $user, $access_token_expiration ); - $refresh_token = generate_refresh_token( $user, $refresh_token_expiration ); - - return array( - 'accessToken' => $access_token, - 'accessTokenExpiration' => ( time() + $access_token_expiration ), - 'refreshToken' => $refresh_token, - 'refreshTokenExpiration' => ( time() + $refresh_token_expiration ), - ); +function handle_rest_authorize_callback( \WP_REST_Request $request ) +{ + $code = trim($request->get_param('code')); + $refresh_token = trim($request->get_param('refreshToken')); + + if (! $code && ! $refresh_token ) { + return new \WP_Error('invalid_request', 'Missing authorization code or refresh token.'); + } + + if ($refresh_token ) { + $user = get_user_from_refresh_token($refresh_token); + } else { + $user = get_user_from_authorization_code($code); + } + + if (! $user ) { + return new \WP_Error('invalid_request', 'Invalid authorization code or refresh token.'); + } + + $refresh_token_expiration = WEEK_IN_SECONDS * 2; + $access_token_expiration = MINUTE_IN_SECONDS * 5; + + $access_token = generate_access_token($user, $access_token_expiration); + $refresh_token = generate_refresh_token($user, $refresh_token_expiration); + + return array( + 'accessToken' => $access_token, + 'accessTokenExpiration' => ( time() + $access_token_expiration ), + 'refreshToken' => $refresh_token, + 'refreshTokenExpiration' => ( time() + $refresh_token_expiration ), + ); } /** @@ -403,20 +412,21 @@ function handle_rest_authorize_callback( \WP_REST_Request $request ) { * * @return bool True if current user can, false if else. */ -function rest_authorize_permission_callback( \WP_REST_Request $request ) { - - $secret_key = get_secret_key(); - $header_key = $request->get_header( 'x-faustwp-secret' ); +function rest_authorize_permission_callback( \WP_REST_Request $request ) +{ + + $secret_key = get_secret_key(); + $header_key = $request->get_header('x-faustwp-secret'); - // Add console log for get_secret_key() - error_log( 'Secret Key: ' . $secret_key ); + // Add console log for get_secret_key() + error_log('Secret Key: ' . $secret_key); - if ( $secret_key && $header_key ) { - return $secret_key === $header_key; - } + if ($secret_key && $header_key ) { + return $secret_key === $header_key; + } - return false; + return false; } /** @@ -433,65 +443,68 @@ function rest_authorize_permission_callback( \WP_REST_Request $request ) { * * @return bool True if current user can, false if else. */ -function wpac_authorize_permission_callback( \WP_REST_Request $request ) { - $secret_key = get_secret_key(); - $header_key = $request->get_header( 'x-wpe-headless-secret' ); +function wpac_authorize_permission_callback( \WP_REST_Request $request ) +{ + $secret_key = get_secret_key(); + $header_key = $request->get_header('x-wpe-headless-secret'); - if ( $secret_key && $header_key ) { - return $secret_key === $header_key; - } + if ($secret_key && $header_key ) { + return $secret_key === $header_key; + } - return false; + return false; } /** * Handles permission checks for the telemetry decision REST route. * - * @param \WP_REST_Request $request REST request object. + * @param \WP_REST_Request $request REST request object. * @return bool Whether the user has permission to make telemetry decisions. */ -function rest_telemetry_decision_permission_callback( \WP_REST_Request $request ) { - return current_user_can( 'manage_options' ); +function rest_telemetry_decision_permission_callback( \WP_REST_Request $request ) +{ + return current_user_can('manage_options'); } /** * Handles user decisions for telemetry opt-in. * - * @param \WP_REST_Request $request REST request object. + * @param \WP_REST_Request $request REST request object. * @return \WP_REST_Response|\WP_Error */ -function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { - $body = json_decode( $request->get_body(), true ); - $decision = $body['decision'] ?? 'remind'; - if ( ! in_array( $decision, array( 'yes', 'no', 'remind' ), true ) ) { - $decision = 'remind'; - } - switch ( $decision ) { - case 'yes': - faustwp_update_setting( 'telemetry_reminder', '0' ); - faustwp_update_setting( 'enable_telemetry', '1' ); - break; - case 'no': - faustwp_update_setting( 'telemetry_reminder', '0' ); - faustwp_update_setting( 'enable_telemetry', 'no' ); - break; - case 'remind': - default: - $date = new \DateTime( '+90 days', new \DateTimeZone( 'UTC' ) ); - faustwp_update_setting( 'enable_telemetry', '0' ); - faustwp_update_setting( 'telemetry_reminder', $date->getTimeStamp() ); - break; - } - - $response = array( - 'decision' => $decision, - 'settings' => array( - 'enabled' => faustwp_get_setting( 'enable_telemetry' ), - 'reminder' => faustwp_get_setting( 'telemetry_reminder' ), - ), - 'success' => true, - ); - return rest_ensure_response( $response ); +function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) +{ + $body = json_decode($request->get_body(), true); + $decision = $body['decision'] ?? 'remind'; + if (! in_array($decision, array( 'yes', 'no', 'remind' ), true) ) { + $decision = 'remind'; + } + switch ( $decision ) { + case 'yes': + faustwp_update_setting('telemetry_reminder', '0'); + faustwp_update_setting('enable_telemetry', '1'); + break; + case 'no': + faustwp_update_setting('telemetry_reminder', '0'); + faustwp_update_setting('enable_telemetry', 'no'); + break; + case 'remind': + default: + $date = new \DateTime('+90 days', new \DateTimeZone('UTC')); + faustwp_update_setting('enable_telemetry', '0'); + faustwp_update_setting('telemetry_reminder', $date->getTimeStamp()); + break; + } + + $response = array( + 'decision' => $decision, + 'settings' => array( + 'enabled' => faustwp_get_setting('enable_telemetry'), + 'reminder' => faustwp_get_setting('telemetry_reminder'), + ), + 'success' => true, + ); + return rest_ensure_response($response); } /** @@ -506,16 +519,17 @@ function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { * * @return mixed A \WP_REST_Response, or \WP_Error. */ -function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { - - return new \WP_REST_Response( - sprintf( - /* Translators: %s is replaced with the emoji indicating a successful sync. */ - esc_html__( 'Secret key validated!', 'faustwp' ), - '✅' - ), - 200 - ); +function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) +{ + + return new \WP_REST_Response( + sprintf( + /* Translators: %s is replaced with the emoji indicating a successful sync. */ + esc_html__('Secret key validated!', 'faustwp'), + '✅' + ), + 200 + ); } /** @@ -530,13 +544,14 @@ function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { * * @return bool True if current user can, false if else. */ -function rest_validate_secret_key_permission_callback( \WP_REST_Request $request ) { - $secret_key = get_secret_key(); - $header_key = $request->get_header( 'x-faustwp-secret' ); +function rest_validate_secret_key_permission_callback( \WP_REST_Request $request ) +{ + $secret_key = get_secret_key(); + $header_key = $request->get_header('x-faustwp-secret'); - if ( $secret_key && $header_key ) { - return $secret_key === $header_key; - } + if ($secret_key && $header_key ) { + return $secret_key === $header_key; + } - return false; -} \ No newline at end of file + return false; +} \ No newline at end of file From 8f6d779e52fa7c270fec113a27e6b467c916b4b4 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 09:11:28 -0600 Subject: [PATCH 09/35] Revert "typo" This reverts commit 9ec13b954e9eb44725eaf615f5a8bf463d787d51. --- packages/faustwp-cli/src/healthCheck/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/src/healthCheck/index.ts b/packages/faustwp-cli/src/healthCheck/index.ts index 83f0cf935..ddfa3929d 100644 --- a/packages/faustwp-cli/src/healthCheck/index.ts +++ b/packages/faustwp-cli/src/healthCheck/index.ts @@ -5,7 +5,7 @@ import { verifyGraphQLEndpoint } from './verifyGraphQLEndpoint.js'; * Ensure that everything Faust requires to run is available. */ export async function healthCheck(): Promise { - // Check Faust Env variables before continuing. + // Check Faust Env varibles before continuing. validateFaustEnvVars(); // Perform our health checks. From 08dd2324eeff7dfb1472a821e5d62797fb433abf Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 11:33:56 -0600 Subject: [PATCH 10/35] Revert "Ran PHP Code Sniffer command on file to fix linting errors" This reverts commit d74940b8f14f4f31f4a3c03c81118249b81aa76a. --- plugins/faustwp/includes/rest/callbacks.php | 675 ++++++++++---------- 1 file changed, 330 insertions(+), 345 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index e751868e6..01348e26a 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -8,30 +8,30 @@ namespace WPE\FaustWP\REST; use function WPE\FaustWP\Auth\{ - get_user_from_access_token, - get_user_from_refresh_token, - get_user_from_authorization_code, - generate_refresh_token, - generate_access_token + get_user_from_access_token, + get_user_from_refresh_token, + get_user_from_authorization_code, + generate_refresh_token, + generate_access_token }; use function WPE\FaustWP\Settings\get_secret_key; use function WPE\FaustWP\Telemetry\{ - get_wp_version, - is_wpe, - get_anonymous_faustwp_data, - get_anonymous_wpgraphql_content_blocks_data, - get_telemetry_client_id + get_wp_version, + is_wpe, + get_anonymous_faustwp_data, + get_anonymous_wpgraphql_content_blocks_data, + get_telemetry_client_id }; use function WPE\FaustWP\Blocks\handle_uploaded_blockset; use function WPE\FaustWP\Settings\faustwp_get_setting; use function WPE\FaustWP\Settings\faustwp_update_setting; use function WPE\FaustWP\Settings\is_telemetry_enabled; -if (! defined('ABSPATH') ) { - exit; +if ( ! defined( 'ABSPATH' ) ) { + exit; } -add_filter('determine_current_user', __NAMESPACE__ . '\\rest_determine_current_user', 20); +add_filter( 'determine_current_user', __NAMESPACE__ . '\\rest_determine_current_user', 20 ); /** * Callback for WordPress 'determine_current_user' filter. * @@ -44,30 +44,29 @@ * * @return int|bool User ID if one has been determined, false otherwise. */ -function rest_determine_current_user( $user_id ) -{ - if ($user_id ) { - return $user_id; - } - - if (! isset($_SERVER['HTTP_AUTHORIZATION']) ) { - return $user_id; - } - - $parts = explode(' ', trim($_SERVER['HTTP_AUTHORIZATION'])); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput - if (count($parts) < 2 ) { - return $user_id; - } - - $wp_user = get_user_from_access_token($parts[1]); - if ($wp_user ) { - $user_id = $wp_user->ID; - } - - return $user_id; +function rest_determine_current_user( $user_id ) { + if ( $user_id ) { + return $user_id; + } + + if ( ! isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { + return $user_id; + } + + $parts = explode( ' ', trim( $_SERVER['HTTP_AUTHORIZATION'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput + if ( count( $parts ) < 2 ) { + return $user_id; + } + + $wp_user = get_user_from_access_token( $parts[1] ); + if ( $wp_user ) { + $user_id = $wp_user->ID; + } + + return $user_id; } -add_action('rest_api_init', __NAMESPACE__ . '\\register_rest_routes'); +add_action( 'rest_api_init', __NAMESPACE__ . '\\register_rest_routes' ); /** * Callback for WordPress 'rest_api_init' action. * @@ -79,120 +78,118 @@ function rest_determine_current_user( $user_id ) * * @return void */ -function register_rest_routes() -{ - register_rest_route( - 'faustwp/v1', - '/blockset', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_blockset_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_blockset_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/telemetry/decision', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_decision_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_decision_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/telemetry', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/authorize', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_authorize_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/process_telemetry', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_process_telemetry_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_process_telemetry_permission_callback', - ) - ); - - register_rest_route( - 'faustwp/v1', - '/validate_secret_key', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_validate_secret_key_callback', - 'permission_callback' => __NAMESPACE__ . '\\rest_validate_secret_key_permission_callback', - ) - ); - - /** - * Faust.js packages now use `faustwp/v1/authorize`. - * - * @deprecated - */ - register_rest_route( - 'wpac/v1', - '/authorize', - array( - 'methods' => 'POST', - 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', - 'permission_callback' => __NAMESPACE__ . '\\wpac_authorize_permission_callback', - ) - ); +function register_rest_routes() { + register_rest_route( + 'faustwp/v1', + '/blockset', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_blockset_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_blockset_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/telemetry/decision', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_decision_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_decision_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/telemetry', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_telemetry_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_telemetry_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/authorize', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_authorize_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/process_telemetry', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_process_telemetry_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_process_telemetry_permission_callback', + ) + ); + + register_rest_route( + 'faustwp/v1', + '/validate_secret_key', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_validate_secret_key_callback', + 'permission_callback' => __NAMESPACE__ . '\\rest_validate_secret_key_permission_callback', + ) + ); + + /** + * Faust.js packages now use `faustwp/v1/authorize`. + * + * @deprecated + */ + register_rest_route( + 'wpac/v1', + '/authorize', + array( + 'methods' => 'POST', + 'callback' => __NAMESPACE__ . '\\handle_rest_authorize_callback', + 'permission_callback' => __NAMESPACE__ . '\\wpac_authorize_permission_callback', + ) + ); } /** * Callback function to handle file upload and unzip. * - * @param \WP_REST_Request $request Full data about the request. + * @param \WP_REST_Request $request Full data about the request. * @return \WP_Error|WP_REST_Response */ -function handle_blockset_callback( \WP_REST_Request $request ) -{ - // Check if file is sent. - $files = $request->get_file_params(); - - if (empty($files['zipfile']) ) { - return new \WP_Error('no_file', __('No file was sent', 'faustwp'), array( 'status' => 400 )); - } - - $file = $files['zipfile']; - - // Check for upload errors. - if ($file['error'] ) { - return new \WP_Error('upload_error', __('File upload error', 'faustwp'), array( 'status' => 400 )); - } - - $result = handle_uploaded_blockset($file); - - if (is_wp_error($result) ) { - return $result; - } - - return new \WP_REST_Response( - sprintf( - /* Translators: %s is replaced with the emoji indicating a successful sync. */ - esc_html__('%s Blockset sync complete!', 'faustwp'), - '✅' - ), - 200 - ); +function handle_blockset_callback( \WP_REST_Request $request ) { + // Check if file is sent. + $files = $request->get_file_params(); + + if ( empty( $files['zipfile'] ) ) { + return new \WP_Error( 'no_file', __( 'No file was sent', 'faustwp' ), array( 'status' => 400 ) ); + } + + $file = $files['zipfile']; + + // Check for upload errors. + if ( $file['error'] ) { + return new \WP_Error( 'upload_error', __( 'File upload error', 'faustwp' ), array( 'status' => 400 ) ); + } + + $result = handle_uploaded_blockset( $file ); + + if ( is_wp_error( $result ) ) { + return $result; + } + + return new \WP_REST_Response( + sprintf( + /* Translators: %s is replaced with the emoji indicating a successful sync. */ + esc_html__( '%s Blockset sync complete!', 'faustwp' ), + '✅' + ), + 200 + ); } /** @@ -207,18 +204,17 @@ function handle_blockset_callback( \WP_REST_Request $request ) * * @return mixed A \WP_REST_Response, array, or \WP_Error. */ -function handle_rest_telemetry_callback( \WP_REST_Request $request ) -{ - $data = array( - 'faustwp' => get_anonymous_faustwp_data(), - 'wpgraphql_content_blocks' => get_anonymous_wpgraphql_content_blocks_data(), - 'is_wpe' => is_wpe(), - 'multisite' => is_multisite(), - 'php_version' => PHP_VERSION, - 'wp_version' => get_wp_version(), - ); - - return new \WP_REST_Response($data); +function handle_rest_telemetry_callback( \WP_REST_Request $request ) { + $data = array( + 'faustwp' => get_anonymous_faustwp_data(), + 'wpgraphql_content_blocks' => get_anonymous_wpgraphql_content_blocks_data(), + 'is_wpe' => is_wpe(), + 'multisite' => is_multisite(), + 'php_version' => PHP_VERSION, + 'wp_version' => get_wp_version(), + ); + + return new \WP_REST_Response( $data ); } /** @@ -233,80 +229,79 @@ function handle_rest_telemetry_callback( \WP_REST_Request $request ) * * @return mixed A \WP_REST_Response, array, or \WP_Error. */ -function handle_rest_process_telemetry_callback( \WP_REST_Request $request ) -{ - if (! is_telemetry_enabled() ) { - return new \WP_REST_Response(null, 204); - } - - $body = $request->get_json_params(); - - $faust_plugin_data = get_anonymous_faustwp_data(); - $content_blocks_plugin_data = get_anonymous_wpgraphql_content_blocks_data(); - - $ga_tracking_endpoint = 'https://www.google-analytics.com/mp/collect'; - $ga_tracking_id = 'G-KPVSTHK1G4'; - $ga_key = '-SLuZb8JTbWkWcT5BD032w'; - - $telemetry_data = array( - 'node_faustwp_core_version' => $body['node_faustwp_core_version'] ?? null, - 'node_faustwp_cli_version' => $body['node_faustwp_cli_version'] ?? null, - 'node_faustwp_blocks_version' => $body['node_faustwp_blocks_version'] ?? null, - 'node_apollo_client_version' => $body['node_apollo_client_version'] ?? null, - 'node_faustwp_block_editor_utils_version' => $body['node_faustwp_block_editor_utils_version'] ?? null, - 'node_faustwp_experimental_app_router_version' => $body['node_faustwp_experimental_app_router_version'] ?? null, - 'node_version' => $body['node_version'] ?? null, - 'node_next_version' => $body['node_next_version'] ?? null, - 'node_is_development' => $body['node_is_development'] ?? null, - 'command' => $body['command'] ?? null, - - 'setting_has_frontend_uri' => $faust_plugin_data['has_frontend_uri'], - 'setting_redirects_enabled' => $faust_plugin_data['redirects_enabled'], - 'setting_rewrites_enabled' => $faust_plugin_data['rewrites_enabled'], - 'setting_themes_disabled' => $faust_plugin_data['themes_disabled'], - 'setting_img_src_replacement_enabled' => $faust_plugin_data['image_source_replacement_enabled'], - 'faustwp_version' => $faust_plugin_data['version'], - - 'wpgraphql_content_blocks_version' => $content_blocks_plugin_data['version'], - - 'is_wpe' => is_wpe(), - 'multisite' => is_multisite(), - 'php_version' => PHP_VERSION, - 'wp_version' => get_wp_version(), - 'engagement_time_msec' => 100, - 'session_id' => md5(get_telemetry_client_id()), - ); - - // Remove null values since GA rejects them. - $telemetry_data = array_filter($telemetry_data); - - $ga_telemetry_url = add_query_arg( - array( - 'measurement_id' => $ga_tracking_id, - 'api_secret' => $ga_key, - ), - $ga_tracking_endpoint - ); - - $telemetry_body = array( - 'client_id' => get_telemetry_client_id(), - 'events' => array( - array( - 'name' => 'telemetry_event', - 'params' => $telemetry_data, - ), - ), - ); - - wp_remote_post( - $ga_telemetry_url, - array( - 'body' => wp_json_encode($telemetry_body), - 'blocking' => false, - ) - ); - - return new \WP_REST_Response(array( $telemetry_body, $ga_telemetry_url ), 201); +function handle_rest_process_telemetry_callback( \WP_REST_Request $request ) { + if ( ! is_telemetry_enabled() ) { + return new \WP_REST_Response( null, 204 ); + } + + $body = $request->get_json_params(); + + $faust_plugin_data = get_anonymous_faustwp_data(); + $content_blocks_plugin_data = get_anonymous_wpgraphql_content_blocks_data(); + + $ga_tracking_endpoint = 'https://www.google-analytics.com/mp/collect'; + $ga_tracking_id = 'G-KPVSTHK1G4'; + $ga_key = '-SLuZb8JTbWkWcT5BD032w'; + + $telemetry_data = array( + 'node_faustwp_core_version' => $body['node_faustwp_core_version'] ?? null, + 'node_faustwp_cli_version' => $body['node_faustwp_cli_version'] ?? null, + 'node_faustwp_blocks_version' => $body['node_faustwp_blocks_version'] ?? null, + 'node_apollo_client_version' => $body['node_apollo_client_version'] ?? null, + 'node_faustwp_block_editor_utils_version' => $body['node_faustwp_block_editor_utils_version'] ?? null, + 'node_faustwp_experimental_app_router_version' => $body['node_faustwp_experimental_app_router_version'] ?? null, + 'node_version' => $body['node_version'] ?? null, + 'node_next_version' => $body['node_next_version'] ?? null, + 'node_is_development' => $body['node_is_development'] ?? null, + 'command' => $body['command'] ?? null, + + 'setting_has_frontend_uri' => $faust_plugin_data['has_frontend_uri'], + 'setting_redirects_enabled' => $faust_plugin_data['redirects_enabled'], + 'setting_rewrites_enabled' => $faust_plugin_data['rewrites_enabled'], + 'setting_themes_disabled' => $faust_plugin_data['themes_disabled'], + 'setting_img_src_replacement_enabled' => $faust_plugin_data['image_source_replacement_enabled'], + 'faustwp_version' => $faust_plugin_data['version'], + + 'wpgraphql_content_blocks_version' => $content_blocks_plugin_data['version'], + + 'is_wpe' => is_wpe(), + 'multisite' => is_multisite(), + 'php_version' => PHP_VERSION, + 'wp_version' => get_wp_version(), + 'engagement_time_msec' => 100, + 'session_id' => md5( get_telemetry_client_id() ), + ); + + // Remove null values since GA rejects them. + $telemetry_data = array_filter( $telemetry_data ); + + $ga_telemetry_url = add_query_arg( + array( + 'measurement_id' => $ga_tracking_id, + 'api_secret' => $ga_key, + ), + $ga_tracking_endpoint + ); + + $telemetry_body = array( + 'client_id' => get_telemetry_client_id(), + 'events' => array( + array( + 'name' => 'telemetry_event', + 'params' => $telemetry_data, + ), + ), + ); + + wp_remote_post( + $ga_telemetry_url, + array( + 'body' => wp_json_encode( $telemetry_body ), + 'blocking' => false, + ) + ); + + return new \WP_REST_Response( array( $telemetry_body, $ga_telemetry_url ), 201 ); } /** @@ -318,9 +313,8 @@ function handle_rest_process_telemetry_callback( \WP_REST_Request $request ) * * @return bool True if current user can, false if else. */ -function rest_blockset_permission_callback( \WP_REST_Request $request ) -{ - return rest_authorize_permission_callback($request); +function rest_blockset_permission_callback( \WP_REST_Request $request ) { + return rest_authorize_permission_callback( $request ); } /** @@ -332,9 +326,8 @@ function rest_blockset_permission_callback( \WP_REST_Request $request ) * * @return bool True if current user can, false if else. */ -function rest_telemetry_permission_callback( \WP_REST_Request $request ) -{ - return rest_authorize_permission_callback($request); +function rest_telemetry_permission_callback( \WP_REST_Request $request ) { + return rest_authorize_permission_callback( $request ); } /** @@ -346,9 +339,8 @@ function rest_telemetry_permission_callback( \WP_REST_Request $request ) * * @return bool True if current user can, false if else. */ -function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) -{ - return rest_authorize_permission_callback($request); +function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) { + return rest_authorize_permission_callback( $request ); } @@ -367,37 +359,36 @@ function rest_process_telemetry_permission_callback( \WP_REST_Request $request ) * * @return mixed A \WP_REST_Response, array, or \WP_Error. */ -function handle_rest_authorize_callback( \WP_REST_Request $request ) -{ - $code = trim($request->get_param('code')); - $refresh_token = trim($request->get_param('refreshToken')); - - if (! $code && ! $refresh_token ) { - return new \WP_Error('invalid_request', 'Missing authorization code or refresh token.'); - } - - if ($refresh_token ) { - $user = get_user_from_refresh_token($refresh_token); - } else { - $user = get_user_from_authorization_code($code); - } - - if (! $user ) { - return new \WP_Error('invalid_request', 'Invalid authorization code or refresh token.'); - } - - $refresh_token_expiration = WEEK_IN_SECONDS * 2; - $access_token_expiration = MINUTE_IN_SECONDS * 5; - - $access_token = generate_access_token($user, $access_token_expiration); - $refresh_token = generate_refresh_token($user, $refresh_token_expiration); - - return array( - 'accessToken' => $access_token, - 'accessTokenExpiration' => ( time() + $access_token_expiration ), - 'refreshToken' => $refresh_token, - 'refreshTokenExpiration' => ( time() + $refresh_token_expiration ), - ); +function handle_rest_authorize_callback( \WP_REST_Request $request ) { + $code = trim( $request->get_param( 'code' ) ); + $refresh_token = trim( $request->get_param( 'refreshToken' ) ); + + if ( ! $code && ! $refresh_token ) { + return new \WP_Error( 'invalid_request', 'Missing authorization code or refresh token.' ); + } + + if ( $refresh_token ) { + $user = get_user_from_refresh_token( $refresh_token ); + } else { + $user = get_user_from_authorization_code( $code ); + } + + if ( ! $user ) { + return new \WP_Error( 'invalid_request', 'Invalid authorization code or refresh token.' ); + } + + $refresh_token_expiration = WEEK_IN_SECONDS * 2; + $access_token_expiration = MINUTE_IN_SECONDS * 5; + + $access_token = generate_access_token( $user, $access_token_expiration ); + $refresh_token = generate_refresh_token( $user, $refresh_token_expiration ); + + return array( + 'accessToken' => $access_token, + 'accessTokenExpiration' => ( time() + $access_token_expiration ), + 'refreshToken' => $refresh_token, + 'refreshTokenExpiration' => ( time() + $refresh_token_expiration ), + ); } /** @@ -412,21 +403,20 @@ function handle_rest_authorize_callback( \WP_REST_Request $request ) * * @return bool True if current user can, false if else. */ -function rest_authorize_permission_callback( \WP_REST_Request $request ) -{ - - $secret_key = get_secret_key(); - $header_key = $request->get_header('x-faustwp-secret'); +function rest_authorize_permission_callback( \WP_REST_Request $request ) { + + $secret_key = get_secret_key(); + $header_key = $request->get_header( 'x-faustwp-secret' ); - // Add console log for get_secret_key() - error_log('Secret Key: ' . $secret_key); + // Add console log for get_secret_key() + error_log( 'Secret Key: ' . $secret_key ); - if ($secret_key && $header_key ) { - return $secret_key === $header_key; - } + if ( $secret_key && $header_key ) { + return $secret_key === $header_key; + } - return false; + return false; } /** @@ -443,68 +433,65 @@ function rest_authorize_permission_callback( \WP_REST_Request $request ) * * @return bool True if current user can, false if else. */ -function wpac_authorize_permission_callback( \WP_REST_Request $request ) -{ - $secret_key = get_secret_key(); - $header_key = $request->get_header('x-wpe-headless-secret'); +function wpac_authorize_permission_callback( \WP_REST_Request $request ) { + $secret_key = get_secret_key(); + $header_key = $request->get_header( 'x-wpe-headless-secret' ); - if ($secret_key && $header_key ) { - return $secret_key === $header_key; - } + if ( $secret_key && $header_key ) { + return $secret_key === $header_key; + } - return false; + return false; } /** * Handles permission checks for the telemetry decision REST route. * - * @param \WP_REST_Request $request REST request object. + * @param \WP_REST_Request $request REST request object. * @return bool Whether the user has permission to make telemetry decisions. */ -function rest_telemetry_decision_permission_callback( \WP_REST_Request $request ) -{ - return current_user_can('manage_options'); +function rest_telemetry_decision_permission_callback( \WP_REST_Request $request ) { + return current_user_can( 'manage_options' ); } /** * Handles user decisions for telemetry opt-in. * - * @param \WP_REST_Request $request REST request object. + * @param \WP_REST_Request $request REST request object. * @return \WP_REST_Response|\WP_Error */ -function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) -{ - $body = json_decode($request->get_body(), true); - $decision = $body['decision'] ?? 'remind'; - if (! in_array($decision, array( 'yes', 'no', 'remind' ), true) ) { - $decision = 'remind'; - } - switch ( $decision ) { - case 'yes': - faustwp_update_setting('telemetry_reminder', '0'); - faustwp_update_setting('enable_telemetry', '1'); - break; - case 'no': - faustwp_update_setting('telemetry_reminder', '0'); - faustwp_update_setting('enable_telemetry', 'no'); - break; - case 'remind': - default: - $date = new \DateTime('+90 days', new \DateTimeZone('UTC')); - faustwp_update_setting('enable_telemetry', '0'); - faustwp_update_setting('telemetry_reminder', $date->getTimeStamp()); - break; - } - - $response = array( - 'decision' => $decision, - 'settings' => array( - 'enabled' => faustwp_get_setting('enable_telemetry'), - 'reminder' => faustwp_get_setting('telemetry_reminder'), - ), - 'success' => true, - ); - return rest_ensure_response($response); +function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { + $body = json_decode( $request->get_body(), true ); + $decision = $body['decision'] ?? 'remind'; + if ( ! in_array( $decision, array( 'yes', 'no', 'remind' ), true ) ) { + $decision = 'remind'; + } + switch ( $decision ) { + case 'yes': + faustwp_update_setting( 'telemetry_reminder', '0' ); + faustwp_update_setting( 'enable_telemetry', '1' ); + break; + case 'no': + faustwp_update_setting( 'telemetry_reminder', '0' ); + faustwp_update_setting( 'enable_telemetry', 'no' ); + break; + case 'remind': + default: + $date = new \DateTime( '+90 days', new \DateTimeZone( 'UTC' ) ); + faustwp_update_setting( 'enable_telemetry', '0' ); + faustwp_update_setting( 'telemetry_reminder', $date->getTimeStamp() ); + break; + } + + $response = array( + 'decision' => $decision, + 'settings' => array( + 'enabled' => faustwp_get_setting( 'enable_telemetry' ), + 'reminder' => faustwp_get_setting( 'telemetry_reminder' ), + ), + 'success' => true, + ); + return rest_ensure_response( $response ); } /** @@ -519,17 +506,16 @@ function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) * * @return mixed A \WP_REST_Response, or \WP_Error. */ -function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) -{ - - return new \WP_REST_Response( - sprintf( - /* Translators: %s is replaced with the emoji indicating a successful sync. */ - esc_html__('Secret key validated!', 'faustwp'), - '✅' - ), - 200 - ); +function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { + + return new \WP_REST_Response( + sprintf( + /* Translators: %s is replaced with the emoji indicating a successful sync. */ + esc_html__( 'Secret key validated!', 'faustwp' ), + '✅' + ), + 200 + ); } /** @@ -544,14 +530,13 @@ function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) * * @return bool True if current user can, false if else. */ -function rest_validate_secret_key_permission_callback( \WP_REST_Request $request ) -{ - $secret_key = get_secret_key(); - $header_key = $request->get_header('x-faustwp-secret'); +function rest_validate_secret_key_permission_callback( \WP_REST_Request $request ) { + $secret_key = get_secret_key(); + $header_key = $request->get_header( 'x-faustwp-secret' ); - if ($secret_key && $header_key ) { - return $secret_key === $header_key; - } + if ( $secret_key && $header_key ) { + return $secret_key === $header_key; + } - return false; -} \ No newline at end of file + return false; +} \ No newline at end of file From f9328a79fc4d00ab3da135436594255a3b15c437 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 13:21:14 -0600 Subject: [PATCH 11/35] phpcs:fix run using composer after adding ignore command to phpcs.xml file --- plugins/faustwp/includes/rest/callbacks.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 01348e26a..c48ef4d9b 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -404,14 +404,12 @@ function handle_rest_authorize_callback( \WP_REST_Request $request ) { * @return bool True if current user can, false if else. */ function rest_authorize_permission_callback( \WP_REST_Request $request ) { - $secret_key = get_secret_key(); $header_key = $request->get_header( 'x-faustwp-secret' ); // Add console log for get_secret_key() error_log( 'Secret Key: ' . $secret_key ); - if ( $secret_key && $header_key ) { return $secret_key === $header_key; } @@ -507,7 +505,6 @@ function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { * @return mixed A \WP_REST_Response, or \WP_Error. */ function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { - return new \WP_REST_Response( sprintf( /* Translators: %s is replaced with the emoji indicating a successful sync. */ @@ -539,4 +536,4 @@ function rest_validate_secret_key_permission_callback( \WP_REST_Request $request } return false; -} \ No newline at end of file +} From 03fb8fb6db94bd5a67127ad93d88d72d8ac93c94 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 13:26:04 -0600 Subject: [PATCH 12/35] Fixed inline phpcs error --- plugins/faustwp/includes/rest/callbacks.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index c48ef4d9b..1784a1be7 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -407,7 +407,7 @@ function rest_authorize_permission_callback( \WP_REST_Request $request ) { $secret_key = get_secret_key(); $header_key = $request->get_header( 'x-faustwp-secret' ); - // Add console log for get_secret_key() + // Add console log for get_secret_key(). error_log( 'Secret Key: ' . $secret_key ); if ( $secret_key && $header_key ) { From 50084f962b392739076e155cc5b6319e75e09686 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 13:30:08 -0600 Subject: [PATCH 13/35] Removed error_log() and corresponding comment --- plugins/faustwp/includes/rest/callbacks.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 1784a1be7..3a01a1626 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -407,9 +407,6 @@ function rest_authorize_permission_callback( \WP_REST_Request $request ) { $secret_key = get_secret_key(); $header_key = $request->get_header( 'x-faustwp-secret' ); - // Add console log for get_secret_key(). - error_log( 'Secret Key: ' . $secret_key ); - if ( $secret_key && $header_key ) { return $secret_key === $header_key; } From 456150dd262c61e83b50ade51f257017d291f6e0 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 13:49:09 -0600 Subject: [PATCH 14/35] Updated experimental-nextjs-app-support to "^0.7.0" --- examples/next/app-router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/next/app-router/package.json b/examples/next/app-router/package.json index 8caf439f9..feb98a23c 100644 --- a/examples/next/app-router/package.json +++ b/examples/next/app-router/package.json @@ -11,7 +11,7 @@ }, "dependencies": { "@apollo/client": "^3.8.0", - "@apollo/experimental-nextjs-app-support": "^0.5.1", + "@apollo/experimental-nextjs-app-support": "^0.7.0", "@faustwp/cli": "^2.0.0", "@faustwp/core": "^2.1.1", "@faustwp/experimental-app-router": "^0.2.2", From 426a93e0cda4b32ef620fcfb323d90a7c765c810 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 14:09:21 -0600 Subject: [PATCH 15/35] Revert "Updated experimental-nextjs-app-support to "^0.7.0"" This reverts commit 456150dd262c61e83b50ade51f257017d291f6e0. --- examples/next/app-router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/next/app-router/package.json b/examples/next/app-router/package.json index feb98a23c..8caf439f9 100644 --- a/examples/next/app-router/package.json +++ b/examples/next/app-router/package.json @@ -11,7 +11,7 @@ }, "dependencies": { "@apollo/client": "^3.8.0", - "@apollo/experimental-nextjs-app-support": "^0.7.0", + "@apollo/experimental-nextjs-app-support": "^0.5.1", "@faustwp/cli": "^2.0.0", "@faustwp/core": "^2.1.1", "@faustwp/experimental-app-router": "^0.2.2", From d6bff3cd3991f1256ef2293058ed4ebe5ccd11f2 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Wed, 7 Feb 2024 16:09:23 -0600 Subject: [PATCH 16/35] Added await to fix linting issue --- packages/faustwp-cli/src/healthCheck/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/index.ts b/packages/faustwp-cli/src/healthCheck/index.ts index ddfa3929d..f427f07f0 100644 --- a/packages/faustwp-cli/src/healthCheck/index.ts +++ b/packages/faustwp-cli/src/healthCheck/index.ts @@ -5,8 +5,8 @@ import { verifyGraphQLEndpoint } from './verifyGraphQLEndpoint.js'; * Ensure that everything Faust requires to run is available. */ export async function healthCheck(): Promise { - // Check Faust Env varibles before continuing. - validateFaustEnvVars(); + // Check Faust Env variables before continuing. + await validateFaustEnvVars(); // Perform our health checks. await verifyGraphQLEndpoint(); From 9120182adc8d34022db0d59436a35a23abc4f81f Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 09:57:43 -0600 Subject: [PATCH 17/35] Awaited function validateFaustEnvVars in test --- .../tests/healthCheck/validateFaustEnvVars.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts index 1d6c86ef5..955ae5201 100644 --- a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts +++ b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts @@ -17,7 +17,7 @@ describe('healthCheck/validateFaustEnvVars', () => { process.env = envBackup; }); - it('exits with a 1 exit code when the WordPress URL is undefined', () => { + it('exits with a 1 exit code when the WordPress URL is undefined', async () => { // @ts-ignore const mockExit = jest.spyOn(process, 'exit').mockImplementation((code) => { if (code && code !== 0) { @@ -27,7 +27,7 @@ describe('healthCheck/validateFaustEnvVars', () => { // Use try/catch block to mock process.exit try { - validateFaustEnvVars(); + await validateFaustEnvVars(); } catch (err) { console.log(err); } @@ -35,7 +35,7 @@ describe('healthCheck/validateFaustEnvVars', () => { expect(mockExit).toHaveBeenCalledWith(1); }); - it('does not exit or throw an error when the WordPress URL is set', () => { + it('does not exit or throw an error when the WordPress URL is set', async () => { // @ts-ignore const mockExit = jest.spyOn(process, 'exit').mockImplementation((code) => { if (code && code !== 0) { @@ -45,7 +45,7 @@ describe('healthCheck/validateFaustEnvVars', () => { process.env.NEXT_PUBLIC_WORDPRESS_URL = 'http://headless.local'; - validateFaustEnvVars(); + await validateFaustEnvVars(); expect(mockExit).toBeCalledTimes(0); }); From 91c7211040fc943e74193addfebb25aa138eab75 Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Fri, 9 Feb 2024 13:21:33 -0600 Subject: [PATCH 18/35] Update packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts Co-authored-by: Blake Wilson --- packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 707a491e3..38b162d80 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -39,7 +39,7 @@ export const validateFaustEnvVars = async () => { headers, method: 'POST', timeout: 30000, // 30 seconds timeout - } as unknown as RequestInit); + }); if (response.status === 204) { // Success: User receives a 204 status code } else if (response.status === 401) { From 7caab397a9f5a0c94c35a7ab16267767afb5dbaa Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 13:43:40 -0600 Subject: [PATCH 19/35] Edited if conditional for secret key validation according to Blake feedback --- .../src/healthCheck/validateFaustEnvVars.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 707a491e3..fae80f142 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -1,5 +1,6 @@ import { getWpSecret, getWpUrl } from '../utils/index.js'; import { errorLog, warnLog } from '../stdout/index.js'; +import { exit } from 'process'; /** * Validates that the appropriate Faust related environment variables are set. @@ -34,19 +35,22 @@ export const validateFaustEnvVars = async () => { const headers = { 'x-faustwp-secret': getWpSecret() || '', }; + console.log('GET WP SECRET CONTENTS', getWpSecret()); try { const response = await fetch(apiUrl, { headers, method: 'POST', - timeout: 30000, // 30 seconds timeout - } as unknown as RequestInit); + }); + console.log('THIS response', response); + console.log('response.status', response.status); if (response.status === 204) { // Success: User receives a 204 status code } else if (response.status === 401) { // Unauthorized: User receives a 401 status code AND the message below - warnLog( + errorLog( 'Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings', ); + exit(1); } } catch (error) { console.log('error', error); From 3b935223adbc8cbc36842c80be6aaa9028710603 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 13:54:34 -0600 Subject: [PATCH 20/35] refactored exit(1) to remove import statement --- packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 5e60a23c6..bd0f1d73b 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -1,6 +1,5 @@ import { getWpSecret, getWpUrl } from '../utils/index.js'; import { errorLog, warnLog } from '../stdout/index.js'; -import { exit } from 'process'; /** * Validates that the appropriate Faust related environment variables are set. @@ -47,7 +46,7 @@ export const validateFaustEnvVars = async () => { errorLog( 'Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings', ); - exit(1); + process.exit(1); } } catch (error) { console.log('error', error); From b2160013077fcf010a499a483c9a320567576e8b Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Fri, 9 Feb 2024 14:04:01 -0600 Subject: [PATCH 21/35] Update plugins/faustwp/includes/rest/callbacks.php Co-authored-by: Blake Wilson --- plugins/faustwp/includes/rest/callbacks.php | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 3a01a1626..1fbae6702 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -525,12 +525,5 @@ function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { * @return bool True if current user can, false if else. */ function rest_validate_secret_key_permission_callback( \WP_REST_Request $request ) { - $secret_key = get_secret_key(); - $header_key = $request->get_header( 'x-faustwp-secret' ); - - if ( $secret_key && $header_key ) { - return $secret_key === $header_key; - } - - return false; + return rest_authorize_permission_callback( $request ); } From ef3ebbde911331ce460eacb3af8f77d2dfbf4bf1 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 14:17:21 -0600 Subject: [PATCH 22/35] Removed devDependency @types/node per Blake feedback --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index e15d43994..7a202bb85 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,6 @@ "devDependencies": { "@changesets/cli": "^2.26.2", "@next/bundle-analyzer": "^13.2.4", - "@types/node": "^20.11.16", "@typescript-eslint/eslint-plugin": "^5.18.0", "@typescript-eslint/parser": "^5.18.0", "eslint": "^8.12.0", From a6785fc33fa1b2e22ca13a79173375d9229c1cc2 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 14:49:55 -0600 Subject: [PATCH 23/35] Added unit test to ensure error is logged when status returns 401 --- .../healthCheck/validateFaustEnvVars.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts index 955ae5201..38a7669b5 100644 --- a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts +++ b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts @@ -1,4 +1,5 @@ import { validateFaustEnvVars } from '../../src/healthCheck/validateFaustEnvVars'; +import fetchMock from 'fetch-mock'; /** * @jest-environment jsdom */ @@ -49,4 +50,19 @@ describe('healthCheck/validateFaustEnvVars', () => { expect(mockExit).toBeCalledTimes(0); }); + + it('logs an error when the secret key validation fails', async () => { + + process.env.NEXT_PUBLIC_WORDPRESS_URL = 'https://headless.local'; + process.env.FAUST_SECRET_KEY = 'invalid-secret-key'; + + fetchMock.post('https://headless.local/wp-json/faustwp/v1/validate_secret_key', { + status: 401, + }); + + await validateFaustEnvVars(); + + return expect(Promise.resolve(validateFaustEnvVars())).toMatchSnapshot('Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings'); + }); + }); From b5363fdafc0abcf1d5b0b1d66a0ba7411f43a3ad Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 15:09:37 -0600 Subject: [PATCH 24/35] Edited snapshot --- .../faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts index 38a7669b5..bf866057a 100644 --- a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts +++ b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts @@ -62,7 +62,7 @@ describe('healthCheck/validateFaustEnvVars', () => { await validateFaustEnvVars(); - return expect(Promise.resolve(validateFaustEnvVars())).toMatchSnapshot('Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings'); + return expect(Promise.resolve(validateFaustEnvVars())).toMatchSnapshot(`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1`); }); }); From 492332995aab260ddf4f6afa7f0ff1730a46a80a Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 15:38:16 -0600 Subject: [PATCH 25/35] Add snapshot --- .../__snapshots__/validateFaustEnvVars.test.ts.snap | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap diff --git a/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap b/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap new file mode 100644 index 000000000..2d4de4a1d --- /dev/null +++ b/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap @@ -0,0 +1,3 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1 1`] = `Promise {}`; From 1450b5a81e89e7d957f5f0556e4be572e8b07400 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Fri, 9 Feb 2024 15:39:01 -0600 Subject: [PATCH 26/35] Tweaked .toMatchSnapshot content --- .../faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts index bf866057a..2188e6cb4 100644 --- a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts +++ b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts @@ -62,6 +62,7 @@ describe('healthCheck/validateFaustEnvVars', () => { await validateFaustEnvVars(); + // return expect(Promise.resolve(await validateFaustEnvVars())).toMatchInlineSnapshot(`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1`); return expect(Promise.resolve(validateFaustEnvVars())).toMatchSnapshot(`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1`); }); From 30f088e9d1d36b6f62f9386425e45b3f5be8b758 Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Tue, 13 Feb 2024 15:49:17 -0600 Subject: [PATCH 27/35] Update packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts Co-authored-by: John Parris --- packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index bd0f1d73b..31603eea3 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -44,7 +44,7 @@ export const validateFaustEnvVars = async () => { } else if (response.status === 401) { // Unauthorized: User receives a 401 status code AND the message below errorLog( - 'Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings', + 'Ensure your FAUST_SECRET_KEY environment variable matches your Secret Key in the Faust WordPress plugin settings', ); process.exit(1); } From 0ea3d5f56228b0d2d96365d2cca4ab0bc672fd27 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Tue, 13 Feb 2024 16:11:05 -0600 Subject: [PATCH 28/35] Removed types/node from package-lock.json --- package-lock.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 7f3200db3..1bb760fdc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,6 @@ "devDependencies": { "@changesets/cli": "^2.26.2", "@next/bundle-analyzer": "^13.2.4", - "@types/node": "^20.11.16", "@typescript-eslint/eslint-plugin": "^5.18.0", "@typescript-eslint/parser": "^5.18.0", "eslint": "^8.12.0", From d5adc5bd1f64ce58d043a21c45c0e98964ac4a17 Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Thu, 15 Feb 2024 11:47:53 -0600 Subject: [PATCH 29/35] Update packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts Co-authored-by: John Parris --- packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 7f9b046aa..0f5ecf89d 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -49,7 +49,7 @@ export const validateFaustEnvVars = async () => { // send secret key const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/validate_secret_key`; const headers = { - 'x-faustwp-secret': getWpSecret() || '', + 'x-faustwp-secret': getWpSecret(), }; try { const response = await fetch(apiUrl, { From 3e70aeae3dfb6f19900f400c4bef46e5cd3bdac1 Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Thu, 15 Feb 2024 11:49:30 -0600 Subject: [PATCH 30/35] Update packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts Co-authored-by: John Parris --- packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 0f5ecf89d..7ed46ba14 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -47,7 +47,7 @@ export const validateFaustEnvVars = async () => { } if (getWpSecret()) { // send secret key - const apiUrl = `${getWpUrl()}/wp-json/faustwp/v1/validate_secret_key`; + const apiUrl = `${getWpUrl()}/?rest_route=/faustwp/v1/validate_secret_key`; const headers = { 'x-faustwp-secret': getWpSecret(), }; From e57516b071bb857131d744ec1309696774813ba7 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Thu, 15 Feb 2024 12:03:35 -0600 Subject: [PATCH 31/35] Refactored getWpSecret to const secretWp --- .../src/healthCheck/validateFaustEnvVars.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts index 7ed46ba14..439bcac10 100644 --- a/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts +++ b/packages/faustwp-cli/src/healthCheck/validateFaustEnvVars.ts @@ -11,6 +11,8 @@ export function isWPEngineComSubdomain(url: string) { * Validates that the appropriate Faust related environment variables are set. */ export const validateFaustEnvVars = async () => { + const secretWp = getWpSecret(); + if (!process.env.NEXT_PUBLIC_WORDPRESS_URL) { errorLog('Could not find NEXT_PUBLIC_WORDPRESS_URL environment variable.'); @@ -28,15 +30,12 @@ export const validateFaustEnvVars = async () => { ); } - if (!getWpSecret()) { + if (!secretWp) { warnLog('Could not find FAUST_SECRET_KEY environment variable.'); warnLog('Some functionality may be limited.'); } - if ( - process.env.NEXT_PUBLIC_WORDPRESS_URL.startsWith('http://') && - getWpSecret() - ) { + if (process.env.NEXT_PUBLIC_WORDPRESS_URL.startsWith('http://') && secretWp) { warnLog('Your WordPress site is not running on https!'); warnLog( 'This is a security concern as all traffic with your secret key is in plain text.', @@ -45,20 +44,19 @@ export const validateFaustEnvVars = async () => { 'Please make sure your production Faust app runs with a WordPress instance on https!', ); } - if (getWpSecret()) { + + if (secretWp) { // send secret key const apiUrl = `${getWpUrl()}/?rest_route=/faustwp/v1/validate_secret_key`; const headers = { - 'x-faustwp-secret': getWpSecret(), + 'x-faustwp-secret': secretWp, }; try { const response = await fetch(apiUrl, { headers, method: 'POST', }); - if (response.status === 204) { - // Success: User receives a 204 status code - } else if (response.status === 401) { + if (response.status === 401) { // Unauthorized: User receives a 401 status code AND the message below errorLog( 'Ensure your FAUST_SECRET_KEY environment variable matches your Secret Key in the Faust WordPress plugin settings', From 7def6f460de5d4319cf44b77415b67fbbce41ddf Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Thu, 15 Feb 2024 12:04:18 -0600 Subject: [PATCH 32/35] Removed the sprintf call --- plugins/faustwp/includes/rest/callbacks.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/plugins/faustwp/includes/rest/callbacks.php b/plugins/faustwp/includes/rest/callbacks.php index 1fbae6702..1c4bf23c4 100644 --- a/plugins/faustwp/includes/rest/callbacks.php +++ b/plugins/faustwp/includes/rest/callbacks.php @@ -503,11 +503,7 @@ function handle_rest_telemetry_decision_callback( \WP_REST_Request $request ) { */ function handle_rest_validate_secret_key_callback( \WP_REST_Request $request ) { return new \WP_REST_Response( - sprintf( - /* Translators: %s is replaced with the emoji indicating a successful sync. */ - esc_html__( 'Secret key validated!', 'faustwp' ), - '✅' - ), + esc_html__( 'Secret key validated!', 'faustwp' ), 200 ); } From 67dd4b8895effd3d8cf6015eba586418b93ed737 Mon Sep 17 00:00:00 2001 From: "Teresa (Terri) Gobble" Date: Thu, 15 Feb 2024 12:37:44 -0600 Subject: [PATCH 33/35] Fixed test and snap to match implementation changes --- .../__snapshots__/validateFaustEnvVars.test.ts.snap | 2 +- .../tests/healthCheck/validateFaustEnvVars.test.ts | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap b/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap index 2d4de4a1d..fa138862d 100644 --- a/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap +++ b/packages/faustwp-cli/tests/healthCheck/__snapshots__/validateFaustEnvVars.test.ts.snap @@ -1,3 +1,3 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1 1`] = `Promise {}`; +exports[`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Ensure your FAUST_SECRET_KEY environment variable matches your Secret Key in the Faust WordPress plugin settings 1`] = `Promise {}`; diff --git a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts index e5367a208..5a010cac0 100644 --- a/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts +++ b/packages/faustwp-cli/tests/healthCheck/validateFaustEnvVars.test.ts @@ -1,8 +1,8 @@ -import fetchMock from 'fetch-mock'; import { isWPEngineComSubdomain, validateFaustEnvVars, } from '../../src/healthCheck/validateFaustEnvVars'; +import fetchMock from 'fetch-mock'; /** * @jest-environment jsdom @@ -66,8 +66,7 @@ describe('healthCheck/validateFaustEnvVars', () => { await validateFaustEnvVars(); - // return expect(Promise.resolve(await validateFaustEnvVars())).toMatchInlineSnapshot(`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1`); - return expect(Promise.resolve(validateFaustEnvVars())).toMatchSnapshot(`healthCheck/validateFaustEnvVars logs an error when the secret key validation fails: Check to ensure your FAUST_SECRET_KEY matches your Faust Secret Key under wp-admin settings 1`); + return expect(Promise.resolve(validateFaustEnvVars())).toMatchSnapshot(`Ensure your FAUST_SECRET_KEY environment variable matches your Secret Key in the Faust WordPress plugin settings`); }); }); From 91b7dc315b7262da8b36d02640dfe4c259c1e251 Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Thu, 15 Feb 2024 12:47:19 -0600 Subject: [PATCH 34/35] Create honest-buckets-cry.md Added error messaging should the user's FAUST_SECRET_KEY env variable not match their key in Faust WordPress plugin settings. --- .changeset/honest-buckets-cry.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/honest-buckets-cry.md diff --git a/.changeset/honest-buckets-cry.md b/.changeset/honest-buckets-cry.md new file mode 100644 index 000000000..ddcb87782 --- /dev/null +++ b/.changeset/honest-buckets-cry.md @@ -0,0 +1,6 @@ +--- +"@faustwp/cli": patch +"@faustwp/wordpress-plugin": patch +--- + +Merl 1749 faust should warn if the secret key is invalid From f00297d6c7baf202b84c43f804e34e99ac1bc25c Mon Sep 17 00:00:00 2001 From: Teresa Gobble Date: Thu, 15 Feb 2024 12:54:08 -0600 Subject: [PATCH 35/35] Update .changeset/honest-buckets-cry.md Co-authored-by: John Parris --- .changeset/honest-buckets-cry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/honest-buckets-cry.md b/.changeset/honest-buckets-cry.md index ddcb87782..c388492f0 100644 --- a/.changeset/honest-buckets-cry.md +++ b/.changeset/honest-buckets-cry.md @@ -3,4 +3,4 @@ "@faustwp/wordpress-plugin": patch --- -Merl 1749 faust should warn if the secret key is invalid +Faust now warns you if the secret key in your environment is invalid or incorrect.