Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .distignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@ phpunit.xml.dist
README.md
composer.json
composer.lock

package.json
package-lock.json
/node_modules
/scripts
11 changes: 8 additions & 3 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,24 @@ on:
release:
types: [released]

permissions:
contents: write

jobs:
deploy_to_wordpress_org:
name: Deploy release
runs-on: ubuntu-latest
steps:
# Checkout the code
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
# Optional: if we add a build step to the plugin, we can run it here.
# Deploy the plugin to WordPress.org
- name: WordPress plugin deploy
id: deploy
uses: 10up/action-wordpress-plugin-deploy@stable
uses: 10up/action-wordpress-plugin-deploy@54bd289b8525fd23a5c365ec369185f2966529c2 # stable
with:
generate-zip: true
env:
Expand All @@ -25,7 +30,7 @@ jobs:
# After the deploy, we also want to create a zip and upload it to the release on Github. We don't want
# users to have to go to the repository to find our plugin :).
- name: Upload release asset
uses: Shopify/upload-to-release@master
uses: Shopify/upload-to-release@d0164d4ca84081447a4c6751d3bae0e834c501de # master
with:
name: ${{ github.event.repository.name }}.zip
path: ${{ steps.deploy.outputs.zip-path }}
Expand Down
13 changes: 13 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,16 @@ jobs:

- name: Lint known plugins file
run: composer lint-known-plugins

javascript-regressions:
name: Admin action regressions
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- name: Setup Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: '22'
- name: Test exact option names and deletion confirmation
run: node --test tests/admin-hardening.test.cjs
2 changes: 1 addition & 1 deletion .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest

# Don't run the cronjob in this workflow on forks.
if: github.event_name != 'schedule' || (github.event_name == 'schedule' && github.repository_owner == 'Emilia-Capital')
if: github.event_name != 'schedule' || (github.event_name == 'schedule' && github.repository == 'ProgressPlanner/aaa-option-optimizer')

steps:
- name: Checkout code
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,28 @@ starting the name with AAA made sense.

Yes!! Backup your database.

### Who can view option values?

Every REST route requires `manage_options`. Option values can include API keys, SMTP passwords and licence keys, and the tables return these values to authorized administrators. This also applies to site administrators on multisite. Only enable the plugin where those administrators are trusted to inspect all site options.

### Which actions are protected?

Essential WordPress options, including site URLs, active plugins, the active theme's settings, salts and keys stored in the database, and the current site's roles option, cannot be deleted, created with a false value, or have their autoload state changed through this plugin. Single and bulk deletion require confirmation in the admin screen. Autoload changes preserve the stored value and use WordPress's cache-aware autoload API.

### Why are unused-option recommendations paused?

Tracking stores up to about 10,000 distinct names. The limit is checked without locking, so concurrent requests can push slightly past it. Once it is reached, names already recorded keep counting, but a new name is dropped, and the plugin then marks observations incomplete and pauses unused-option recommendations, because a dropped name could otherwise be reported as unused. Data migrated from older versions is kept in full, even past the limit. A failed tracking write does not pause recommendations; it loses at most that request's counts. Reset tracking to start a fresh observation period.

### How can I add recognized plugins?

Please do a pull request via GitHub on [this file](https://github.com/ProgressPlanner/aaa-option-optimizer/blob/develop/known-plugins/known-plugins.json) in the plugin.

### How can I report security bugs?

You can report security bugs through the Patchstack Vulnerability Disclosure Program. The Patchstack team help validate, triage and handle any security vulnerabilities. [Report a security vulnerability.](https://patchstack.com/database/vdp/aaa-option-optimizer)

## Development checks

Run `composer lint`, `composer check-cs`, `composer phpstan`, and `composer lint-known-plugins` with the development dependencies installed, and `npm run test:hardening:js` for the admin action regressions. The plugin-map validator requires an object keyed by plugin slug, with exactly a non-empty `name` and a non-empty array of unique string `option_prefixes` per entry.

Run `wp eval-file /path/to/aaa-option-optimizer/tests/hardening.php` only on a disposable WordPress installation with an administrator at user ID 1 and `define( 'AAAOO_DISPOSABLE_TEST_SITE', true );` in its configuration. The test creates and deletes fixtures and resets tracking data. It covers REST validation, exact option names, protected options, failed autoload updates, raw-value preservation, malformed sorting, and tracking limits.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"@php -r \"exit( intval( is_null( json_decode( file_get_contents( './.wordpress-org/blueprints/blueprint.json' ) ) ) ) );\""
],
"lint-known-plugins": [
"@php -r \"exit( intval( is_null( json_decode( file_get_contents( './known-plugins/known-plugins.json' ) ) ) ) );\""
"@php scripts/validate-known-plugins.php"
],
"test": [
"@php ./vendor/phpunit/phpunit/phpunit"
Expand Down
95 changes: 74 additions & 21 deletions js/admin-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ jQuery( document ).ready( function () {
responsive: true,
columns: getColumns( selector ),
rowId( data ) {
return generateRowId( data.name );
return (
selector.substring( 1 ) + '-' + generateRowId( data.name )
);
},
initComplete() {
this.api().columns( 'source:name' ).every( filterSetup );
Expand All @@ -122,6 +124,16 @@ jQuery( document ).ready( function () {
headers: { 'X-WP-Nonce': aaaOptionOptimizer.nonce },
type: 'GET',
dataSrc( json ) {
if (
json.tracking_limited &&
! jQuery( '#aaa-tracking-limited' ).length
) {
jQuery(
'<p id="aaa-tracking-limited" role="status"></p>'
)
.text( aaaOptionOptimizer.i18n.trackingLimited )
.insertBefore( selector );
}
tableSources[ selector ] = json.sources || [];
return json.data;
},
Expand Down Expand Up @@ -444,7 +456,7 @@ jQuery( document ).ready( function () {
</button>`,
];

return actions.join( '' );
return ( row.protected ? actions.slice( 0, 2 ) : actions ).join( '' );
}

/**
Expand All @@ -455,6 +467,9 @@ jQuery( document ).ready( function () {
* @return {string} - The HTML for the value column.
*/
function renderNonExistingOptionsColumn( row ) {
if ( row.protected ) {
return '';
}
return `<button class="button button-primary create-option-false" data-option="${ escapeHtml(
row.name
) }">
Expand All @@ -471,6 +486,9 @@ jQuery( document ).ready( function () {
* @return {string} - The HTML for the value column.
*/
function renderCheckboxColumn( row, tableId ) {
if ( row.protected ) {
return '';
}
// Build the checkbox id from the sanitized row id, never the raw name, so
// the id and its matching label `for` cannot break out of the markup.
// The same option can be listed in several tables, so prefix the table id to keep it unique.
Expand All @@ -494,8 +512,13 @@ jQuery( document ).ready( function () {
response // eslint-disable-line no-unused-vars
) =>
( window.location = `${ window.location.href }&tracking_reset=true` ),
error: ( response ) =>
console.error( 'Failed to reset tracking.', response ), // eslint-disable-line no-console
error: ( response ) => {
// eslint-disable-next-line no-alert
alert(
response.responseJSON?.message ||
aaaOptionOptimizer.i18n.actionFailed
);
},
} );
} );

Expand All @@ -507,8 +530,7 @@ jQuery( document ).ready( function () {
function handleTableActions( e ) {
e.preventDefault();
const button = jQuery( this );
const table = button.closest( 'table' ).DataTable();
const optionName = button.data( 'option' );
const optionName = button.attr( 'data-option' );

const requestData = { option_name: optionName };
let action = '';
Expand All @@ -517,6 +539,14 @@ jQuery( document ).ready( function () {
if ( button.hasClass( 'create-option-false' ) ) {
action = route = 'create-option-false';
} else if ( button.hasClass( 'delete-option' ) ) {
if (
// eslint-disable-next-line no-alert
! window.confirm(
aaaOptionOptimizer.i18n.confirmDelete + '\n' + optionName
)
) {
return;
}
action = route = 'delete-option';
} else {
action = button.hasClass( 'add-autoload' )
Expand All @@ -526,6 +556,8 @@ jQuery( document ).ready( function () {
requestData.autoload = action === 'add-autoload' ? 'yes' : 'no';
}

const table = button.closest( 'table' ).DataTable();

jQuery.ajax( {
url: `${ aaaOptionOptimizer.root }aaa-option-optimizer/v1/${ route }`,
method: 'POST',
Expand All @@ -534,12 +566,14 @@ jQuery( document ).ready( function () {
data: requestData,
success: ( response ) =>
updateRowOnSuccess( response, table, optionName, action ),
error: ( response ) =>
// eslint-disable-next-line no-console
console.error(
`Failed to ${ action } for ${ optionName }.`,
response
),
error: ( response ) => {
table.ajax.reload( null, false );
// eslint-disable-next-line no-alert
alert(
response.responseJSON?.message ||
aaaOptionOptimizer.i18n.actionFailed
);
},
} );
}

Expand All @@ -553,7 +587,9 @@ jQuery( document ).ready( function () {
*/
function updateRowOnSuccess( response, table, optionName, action ) {
// Look the row up by DataTables row ID, not a CSS selector, so option names with special characters still match.
const row = table.row( '#' + generateRowId( optionName ) );
const row = table.row(
'#' + table.table().node().id + '-' + generateRowId( optionName )
);
if ( action === 'delete-option' || action === 'create-option-false' ) {
row.remove().draw( 'full-hold' );
} else if (
Expand Down Expand Up @@ -658,7 +694,19 @@ jQuery( document ).ready( function () {
return;
}

// For now we only have delete in bulk action.
if (
bulkAction === 'delete' &&
// eslint-disable-next-line no-alert
! window.confirm(
aaaOptionOptimizer.i18n.confirmDelete +
'\n' +
selectedOptions.length +
' ' +
aaaOptionOptimizer.i18n.selectedOptions
)
) {
return;
}

const requestData = {
option_names: Array.from( selectedOptions ).map( ( option ) =>
Expand Down Expand Up @@ -691,18 +739,20 @@ jQuery( document ).ready( function () {
success: () => {
const dt = table.DataTable();

requestData.option_names.forEach( ( optionName ) => {
dt.row( '#' + generateRowId( optionName ) ).remove();
} );

dt.draw( 'full-hold' );
dt.ajax.reload( null, false );

// Clear the select-all checkbox.
table
.find( '.select-all-checkbox' )
.prop( 'checked', false );
},
error: ( response ) => {
table.DataTable().ajax.reload( null, false );
// eslint-disable-next-line no-alert
alert(
response.responseJSON?.message ||
aaaOptionOptimizer.i18n.actionFailed
);
// eslint-disable-next-line no-console
console.error( 'Failed to delete options.', response );
},
Expand Down Expand Up @@ -783,8 +833,11 @@ jQuery( document ).ready( function () {
}, 1000 );
}
},
error() {
statusText.text( aaaOptionOptimizer.i18n.migrationError );
error( response ) {
statusText.text(
response.responseJSON?.message ||
aaaOptionOptimizer.i18n.migrationError
);
button.prop( 'disabled', false );
},
} );
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"stylelint": "^16.26.1"
},
"scripts": {
"test:hardening:js": "node --test tests/admin-hardening.test.cjs",
"format": "wp-scripts format ./assets",
"lint:css": "wp-scripts lint-style \"**/*.css\"",
"lint:css:fix": "npm run lint:css -- --fix",
Expand Down
72 changes: 72 additions & 0 deletions scripts/validate-known-plugins.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php
/**
* Validate the community-maintained plugin map without dependencies.
*
* @package Progress_Planner\OptionOptimizer
*/

namespace Progress_Planner\OptionOptimizer;

if ( PHP_SAPI !== 'cli' ) {
exit;
}

// phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fwrite -- Standalone CLI.

/**
* Validate a local plugin map and exit with a CI-friendly status.
*
* @param string $filename JSON file path.
* @return void
*/
function validate_known_plugins( $filename ) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local CLI input.
$contents = file_get_contents( $filename );
$plugins = false === $contents ? null : json_decode( $contents );
$errors = [];

if ( ! $plugins instanceof \stdClass || ! count( get_object_vars( $plugins ) ) ) {
$errors[] = 'The plugin map must be a non-empty JSON object.';
} else {
foreach ( get_object_vars( $plugins ) as $slug => $plugin ) {
if ( ! preg_match( '/^[a-z0-9][a-z0-9_-]*$/D', (string) $slug ) ) {
$errors[] = "Invalid plugin slug: $slug";
}
if ( ! $plugin instanceof \stdClass ) {
$errors[] = "$slug must be an object.";
continue;
}
$keys = array_keys( get_object_vars( $plugin ) );
sort( $keys );
if ( [ 'name', 'option_prefixes' ] !== $keys ) {
$errors[] = "$slug must contain exactly name and option_prefixes.";
}
if ( ! isset( $plugin->name ) || ! is_string( $plugin->name ) || '' === trim( $plugin->name ) ) {
$errors[] = "$slug.name must be a non-empty string.";
}
if ( ! isset( $plugin->option_prefixes ) || ! is_array( $plugin->option_prefixes ) || ! $plugin->option_prefixes ) {
$errors[] = "$slug.option_prefixes must be a non-empty array.";
continue;
}
$seen = [];
foreach ( $plugin->option_prefixes as $prefix ) {
if ( ! is_string( $prefix ) || '' === trim( $prefix ) || preg_match( '/[\x00-\x1f\x7f]/', $prefix ) || preg_match_all( '/./us', $prefix ) > 191 ) {
$errors[] = "$slug has an invalid option prefix.";
continue;
}
if ( in_array( $prefix, $seen, true ) ) {
$errors[] = "$slug has a duplicate option prefix.";
}
$seen[] = $prefix;
}
}
}

if ( $errors ) {
fwrite( STDERR, implode( "\n", $errors ) . "\n" );
exit( 1 );
}
fwrite( STDOUT, "Known plugins schema is valid.\n" );
}

validate_known_plugins( $argv[1] ?? dirname( __DIR__ ) . '/known-plugins/known-plugins.json' );
Loading
Loading