Skip to content
Open
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
92 changes: 89 additions & 3 deletions src/js/_enqueues/admin/application-passwords.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,93 @@
( function( $ ) {
var $appPassSection = $( '#application-passwords-section' ),
$newAppPassForm = $appPassSection.find( '.create-application-password' ),
$newAppPassField = $newAppPassForm.find( '.input' ),
$newAppPassField = $newAppPassForm.find( '#new_application_password_name' ),
$newAppPassPresetField = $newAppPassForm.find( '#new_application_password_expiration_preset' ),
$newAppPassCustomWrap = $newAppPassForm.find( '#new_application_password_custom_expires_wrap' ),
$newAppPassExpiresField = $newAppPassForm.find( '#new_application_password_expires' ),
$newAppPassButton = $newAppPassForm.find( '.button' ),
$appPassTwrapper = $appPassSection.find( '.application-passwords-list-table-wrapper' ),
$appPassTbody = $appPassSection.find( 'tbody' ),
$appPassTrNoItems = $appPassTbody.find( '.no-items' ),
$removeAllBtn = $( '#revoke-all-application-passwords' ),
tmplNewAppPass = wp.template( 'new-application-password' ),
tmplAppPassRow = wp.template( 'application-password-row' ),
userId = $( '#user_id' ).val();
userId = $( '#user_id' ).val(),
settings = window.wpApplicationPasswordsSettings || {};

$newAppPassPresetField.on( 'change', function() {
if ( 'custom' === $( this ).val() ) {
$newAppPassCustomWrap.removeClass( 'hidden' );
$newAppPassExpiresField.trigger( 'focus' );
} else {
$newAppPassCustomWrap.addClass( 'hidden' );
$newAppPassExpiresField.val( '' );
}
} );

/**
* Calculates the ISO string for expiration based on selected preset or custom date.
*
* Expiration is set to 23:59:59 of the target day in the site's local timezone.
*
* @since 7.2.0
* @return {string|null} The ISO 8601 date string, or null if no expiration or invalid.
*/
function calculateExpiresIso() {
var preset = $newAppPassPresetField.val(),
days = 0,
baseDateIso = settings.todayEndIso,
baseDate;

if ( 'no_expiry' === preset ) {
return null;
}

if ( 'custom' === preset ) {
var customVal = $newAppPassExpiresField.val();
if ( ! customVal ) {
return null;
}

// Format custom date string into ISO for end of day in site timezone.
var siteTimezone = wp.date.getSettings().timezone;
var offsetString = '+00:00';
if ( siteTimezone && siteTimezone.offsetFormatted ) {
offsetString = siteTimezone.offsetFormatted;
// Format to standard ISO offset like +06:00 or -05:00.
if ( ! /^[-+]\d{2}:\d{2}$/.test( offsetString ) ) {
var numOffset = parseFloat( siteTimezone.offset || 0 );
var sign = numOffset >= 0 ? '+' : '-';
var absH = Math.floor( Math.abs( numOffset ) );
var absM = Math.round( ( Math.abs( numOffset ) - absH ) * 60 );
offsetString = sign + ( '0' + absH ).slice( -2 ) + ':' + ( '0' + absM ).slice( -2 );
}
}

var customIsoDate = new Date( customVal + 'T23:59:59' + offsetString );
if ( ! isNaN( customIsoDate.getTime() ) ) {
return customIsoDate.toISOString();
}

return null;
}

if ( '7_days' === preset ) {
days = 7;
} else if ( '30_days' === preset ) {
days = 30;
} else if ( '90_days' === preset ) {
days = 90;
}

if ( days > 0 ) {
baseDate = baseDateIso ? new Date( baseDateIso ) : new Date();
baseDate.setUTCDate( baseDate.getUTCDate() + days );
return baseDate.toISOString();
}

return null;
}

$newAppPassButton.on( 'click', function( e ) {
e.preventDefault();
Expand All @@ -41,6 +119,11 @@
name: name
};

var expiresIso = calculateExpiresIso();
if ( expiresIso ) {
request.expires = expiresIso;
}

/**
* Filters the request data used to create a new Application Password.
*
Expand All @@ -59,6 +142,9 @@
$newAppPassButton.removeProp( 'aria-disabled' ).removeClass( 'disabled' );
} ).done( function( response ) {
$newAppPassField.val( '' );
$newAppPassPresetField.val( '30_days' );
$newAppPassCustomWrap.addClass( 'hidden' );
$newAppPassExpiresField.val( '' );
$newAppPassButton.prop( 'disabled', false );

$newAppPassForm.after( tmplNewAppPass( {
Expand All @@ -82,7 +168,7 @@
*/
wp.hooks.doAction( 'wp_application_passwords_created_password', response, request );
} ).fail( handleErrorResponse );
} );
});

$appPassTbody.on( 'click', '.delete', function( e ) {
e.preventDefault();
Expand Down
4 changes: 4 additions & 0 deletions src/wp-admin/css/forms.css
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,10 @@ table.form-table td .updated p {
max-width: 20em;
}

.column-expires {
vertical-align: top;
}

.auth-app-card.card {
max-width: 768px;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function get_columns() {
'created' => __( 'Created' ),
'last_used' => __( 'Last Used' ),
'last_ip' => __( 'Last IP' ),
'expires' => __( 'Expires' ),
'revoke' => __( 'Revoke' ),
);
}
Expand Down Expand Up @@ -101,6 +102,30 @@ public function column_last_ip( $item ) {
}
}

/**
* Handles the expires column output.
*
* @since 7.2.0
*
* @param array $item The current application password item.
*/
public function column_expires( $item ) {
if ( empty( $item['expires'] ) ) {
echo '—';
} else {
$date = date_i18n( __( 'F j, Y' ), $item['expires'] );
if ( time() > $item['expires'] ) {
printf(
'%s',
/* translators: %s: Expiration date for the Application Password. */
sprintf( esc_html__( 'Expired on %s' ), esc_html( $date ) )
);
} else {
echo esc_html( $date );
}
}
}

/**
* Handles the revoke column output.
*
Expand Down Expand Up @@ -235,6 +260,24 @@ public function print_js_template_row() {
case 'last_ip':
echo "{{ data.last_ip || '—' }}";
break;
case 'expires':
?>
<# if ( data.expires ) { #>
<# var isExpired = new Date().getTime() > new Date( data.expires ).getTime(); #>
<# var formattedDate = wp.date.dateI18n( <?php echo wp_json_encode( __( 'F j, Y' ) ); ?>, data.expires ); #>
<# if ( isExpired ) { #>
<?php
/* translators: %s: Expiration date for the Application Password. */
printf( esc_html__( 'Expired on %s' ), '{{ formattedDate }}' );
?>
<# } else { #>
{{ formattedDate }}
<# } #>
<# } else { #>
—
<# } #>
<?php
break;
case 'revoke':
printf(
'<button type="button" class="button delete" aria-label="%1$s">%2$s</button>',
Expand Down
30 changes: 30 additions & 0 deletions src/wp-admin/user-edit.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@

if ( wp_is_application_passwords_available_for_user( $user_id ) ) {
wp_enqueue_script( 'application-passwords' );
wp_localize_script(
'application-passwords',
'wpApplicationPasswordsSettings',
array(
'currentDate' => wp_date( 'Y-m-d' ),
'todayEndIso' => wp_date( 'c', strtotime( 'today 23:59:59', current_datetime()->getTimestamp() ) ),
)
);
}

if ( IS_PROFILE_PAGE ) {
Expand Down Expand Up @@ -848,6 +856,28 @@
<p class="description" id="new_application_password_name_desc"><?php _e( 'Required to create an Application Password, but not to update the user.' ); ?></p>
</div>

<?php
/**
* Expires field added @since 7.2.0
*/
?>
<div class="form-field">
<label for="new_application_password_expiration_preset"><?php _e( 'Expiration' ); ?></label>
<select id="new_application_password_expiration_preset" name="new_application_password_expiration_preset">
<?php foreach ( WP_Application_Passwords::get_expiry_presets() as $preset_key => $preset_label ) : ?>
<option value="<?php echo esc_attr( $preset_key ); ?>" <?php selected( $preset_key, WP_Application_Passwords::EXPIRY_30_DAYS ); ?>>
<?php echo esc_html( $preset_label ); ?>
</option>
<?php endforeach; ?>
</select>
</div>

<div class="form-field hidden" id="new_application_password_custom_expires_wrap">
<label for="new_application_password_expires"><?php _e( 'Custom expiration date' ); ?></label>
<input type="date" id="new_application_password_expires" name="new_application_password_expires" class="input ltr" min="<?php echo esc_attr( wp_date( 'Y-m-d' ) ); ?>" />
<p class="description"><?php _e( 'The password will expire at the end of the selected day in your site timezone.' ); ?></p>
</div>

<?php
/**
* Fires in the create Application Passwords form.
Expand Down
50 changes: 50 additions & 0 deletions src/wp-includes/class-wp-application-passwords.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,34 @@ class WP_Application_Passwords {
*/
const PW_LENGTH = 24;

/**
* Expiration preset constants.
*
* @since 7.2.0
*/
const EXPIRY_NO_EXPIRY = 'no_expiry';
const EXPIRY_7_DAYS = '7_days';
const EXPIRY_30_DAYS = '30_days';
const EXPIRY_90_DAYS = '90_days';
const EXPIRY_CUSTOM = 'custom';

/**
* Gets the supported expiration presets and their labels.
*
* @since 7.2.0
*
* @return array<string, string> Array of preset keys and translatable labels.
*/
public static function get_expiry_presets() {
return array(
self::EXPIRY_7_DAYS => __( '7 days' ),
self::EXPIRY_30_DAYS => __( '30 days' ),
self::EXPIRY_90_DAYS => __( '90 days' ),
self::EXPIRY_NO_EXPIRY => __( 'No expiry' ),
self::EXPIRY_CUSTOM => __( 'Custom date' ),
);
}

/**
* Checks if application passwords are being used by the site.
*
Expand All @@ -61,6 +89,7 @@ public static function is_in_use() {
* @since 5.6.0
* @since 5.7.0 Returns WP_Error if application name already exists.
* @since 6.8.0 The hashed password value now uses wp_fast_hash() instead of phpass.
* @since 7.2.0 The application password expiration functionality added.
*
* @param int $user_id User ID.
* @param array $args {
Expand Down Expand Up @@ -98,6 +127,18 @@ public static function create_new_application_password( $user_id, $args = array(
$new_password = wp_generate_password( static::PW_LENGTH, false );
$hashed_password = self::hash_password( $new_password );

$expires = null;
if ( ! empty( $args['expires'] ) ) {
$expires = (int) $args['expires'];
if ( $expires <= time() ) {
return new WP_Error(
'application_password_past_expiration',
__( 'Application password expiration date must be in the future.' ),
array( 'status' => 400 )
);
}
}

$new_item = array(
'uuid' => wp_generate_uuid4(),
'app_id' => empty( $args['app_id'] ) ? '' : $args['app_id'],
Expand All @@ -106,6 +147,7 @@ public static function create_new_application_password( $user_id, $args = array(
'created' => time(),
'last_used' => null,
'last_ip' => null,
'expires' => $expires,
);

$passwords = static::get_user_application_passwords( $user_id );
Expand Down Expand Up @@ -282,6 +324,14 @@ public static function update_application_password( $user_id, $uuid, $update = a

$save = false;

if ( array_key_exists( 'expires', $update ) ) {
$expires = null === $update['expires'] ? null : (int) $update['expires'];
if ( ! array_key_exists( 'expires', $item ) || $item['expires'] !== $expires ) {
$item['expires'] = $expires;
$save = true;
}
}

if ( ! empty( $update['name'] ) && $item['name'] !== $update['name'] ) {
$item['name'] = $update['name'];
$save = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,11 @@
$prepared->app_id = $request['app_id'];
}

$prepared->expires = null;
if ( isset( $request['expires'] ) && null !== $request['expires'] ) {

Check warning on line 587 in src/wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php

View workflow job for this annotation

GitHub Actions / PHP static analysis / Run PHP static analysis

Strict comparison using !== between null and mixed will always evaluate to true.
$prepared->expires = rest_parse_date( $request['expires'] );
}

/**
* Filters an application password before it is inserted via the REST API.
*
Expand Down Expand Up @@ -619,6 +624,7 @@
'created' => gmdate( 'Y-m-d\TH:i:s', $item['created'] ),
'last_used' => $item['last_used'] ? gmdate( 'Y-m-d\TH:i:s', $item['last_used'] ) : null,
'last_ip' => $item['last_ip'] ? $item['last_ip'] : null,
'expires' => ! empty( $item['expires'] ) ? gmdate( 'Y-m-d\TH:i:s', $item['expires'] ) : null,
);

if ( isset( $item['new_password'] ) ) {
Expand Down Expand Up @@ -849,6 +855,12 @@
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'expires' => array(
'description' => __( 'The GMT date the application password expires.' ),
'type' => array( 'string', 'null' ),
'format' => 'date-time',
'context' => array( 'view', 'edit' ),
),
),
);

Expand Down
7 changes: 7 additions & 0 deletions src/wp-includes/user.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,13 @@

$error = new WP_Error();

if ( ! empty( $item['expires'] ) && time() > $item['expires'] ) {

Check warning on line 466 in src/wp-includes/user.php

View workflow job for this annotation

GitHub Actions / PHP static analysis / Run PHP static analysis

Offset 'expires' does not exist on array{uuid: string, app_id: string, name: string, password: string, created: int, last_used: int|null, last_ip: string|null}.
$error->add(
'application_password_expired',
__( 'The provided application password has expired.' )
);
}

/**
* Fires when an application password has been successfully checked as valid.
*
Expand Down
1 change: 1 addition & 0 deletions tests/e2e/playwright.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import path from 'node:path';
import { defineConfig } from '@playwright/test';
import 'dotenv/config';

/**
* WordPress dependencies
Expand Down
Loading
Loading