From 1805e9570b9c75e6215b0ac699b59489212c90b4 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:29:05 -0800 Subject: [PATCH] Stage static publishes for review, then go live; version history and rollback Add a Review before going live setting (off by default). With it on, static exports finalize without going live and a Staged version card offers a private preview, a copyable preview link, Go live and Discard. A Versions panel lists the last 20 versions with Make live for rollback. Editors can stage; administrators promote, with a spacefast_wordpress_can_promote filter. Static connections now request publish:write, which covers promotion and preview sessions; existing installs see a reconnect notice. When Spacefast requires a person to approve a promotion, keep the continuation token server-side, link to the approval, and resend the same request on Finish. Sync state saved by earlier releases keeps working: compare-and-swap now compares against the stored row. --- README.md | 38 ++ includes/class-spacefast-client.php | 46 ++- includes/class-spacefast-oauth.php | 4 +- includes/class-spacefast-plugin.php | 391 +++++++++++++++++- includes/class-spacefast-settings.php | 2 + .../class-spacefast-simply-static-task.php | 10 +- includes/class-spacefast-static-publisher.php | 10 +- includes/class-spacefast-sync-state.php | 27 +- readme.txt | 20 +- spacefast-wordpress.php | 4 +- tests/acceptance/wordpress.php | 57 ++- tests/behavior.php | 281 ++++++++++++- uninstall.php | 1 + 13 files changed, 856 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 3402c40..b65e742 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,44 @@ Simply Static remains responsible for crawling WordPress and rewriting URLs. Spacefast never reads drafts, WordPress credentials, or the database. Dynamic WordPress features still need a static-compatible replacement. +### Review, publish, and roll back + +Enable **Review before going live** under **Settings → Spacefast → WordPress +sync** to stage exports. The default is off: existing sites continue publishing +directly to live. When enabled, manual, automatic, and partial exports all wait +for approval. Partial exports remain additive and preserve omitted files. + +After an export completes, the **Staged version** card shows added, changed, and +removed file counts. **Open preview** opens that version in a new tab. **Copy +preview link** creates a link for a reviewer; it grants access to that version +for 10 minutes. Generate a fresh link after it expires. **Go live** promotes the +reviewed version. **Discard** permanently deletes that staged version, leaving +the live site alone. A later export replaces the staged card; earlier ready +versions remain in history. + +**Versions** lists the latest 20 versions with their time, file count, live +status, and manual/automatic source for exports recorded by this installation. +Older or externally published versions show an unknown source. Use **Make live** +to roll back to an earlier ready version. Promotion uses Spacefast's default +rewrite refresh and records the returned version ID, including when rollback +creates a new version from the old files. If Spacefast asks for a person to +approve a promotion, a **Waiting for approval** card links to the approval in +Spacefast; after approving, choose **Finish** to resend the same request. The +continuation token stays on the server and is never shown. API failures leave +the staged receipt available for retry. A full staged export after a deletion must go live before +partial publishing resumes. + +Editors (`edit_others_posts`) can stage and preview when review is enabled on a +connected static site. Administrators (`manage_options`) can promote, roll back, +and discard. The `spacefast_wordpress_can_promote` filter receives the default +capability result and can restrict or delegate those version actions; it does +not grant access to connection settings. + +Existing static connections must **Reconnect Spacefast** once for previews and +promotion. New connections request `publish:write`: Spacefast's scope mapping +includes `versions:promote` and `versions:download` (required by preview sessions). +The old `spaces:publish` scope grants only publishing. Headless scopes are unchanged. + ## Headless CMS Open **Use WordPress as a CMS for a repository site** when an Astro or other repository project reads the diff --git a/includes/class-spacefast-client.php b/includes/class-spacefast-client.php index a83295b..d7a5c83 100644 --- a/includes/class-spacefast-client.php +++ b/includes/class-spacefast-client.php @@ -16,7 +16,7 @@ public function __construct( ?callable $transport = null, ?callable $upload_tran /** * @return array{ok:bool,retryable:bool,code:string,message:string,data:array} */ - private function request( string $method, string $path, ?array $body = null, array $headers = array() ): array { + private function request( string $method, string $path, ?array $body = null, array $headers = array(), int $timeout = 10 ): array { $settings = Spacefast_Settings::get(); $access_token = ( new Spacefast_OAuth( $this->transport ) )->access_token(); if ( '' === $access_token ) { @@ -30,7 +30,7 @@ private function request( string $method, string $path, ?array $body = null, arr } $args = array( 'method' => $method, - 'timeout' => 10, + 'timeout' => $timeout, 'redirection' => 0, 'reject_unsafe_urls' => true, 'sslverify' => true, @@ -69,6 +69,7 @@ private function request( string $method, string $path, ?array $body = null, arr if ( $status >= 200 && $status < 300 + && ! ( 'DELETE' === $method && 204 === $status ) && ( '' === $raw_body || JSON_ERROR_NONE !== json_last_error() || ! is_array( $decoded ) ) ) { return array( @@ -110,6 +111,8 @@ private function request( string $method, string $path, ?array $body = null, arr ? 'The Spacefast connection is no longer authorized.' : (string) ( $decoded['detail'] ?? 'Spacefast rejected the request.' ), 'data' => array(), + // Error details carry follow-up steps such as an approval link. + 'details' => isset( $decoded['details'] ) && is_array( $decoded['details'] ) ? $decoded['details'] : array(), ); } @@ -273,7 +276,10 @@ public function get_build( string $build_id ): array { * @param array $files Files. * @return array{ok:bool,retryable:bool,code:string,message:string,data:array} */ - public function create_static_version( array $files, string $event_id, string $publish_mode ): array { + public function create_static_version( array $files, string $event_id, string $publish_mode, ?string $channel = 'live' ): array { + if ( null !== $channel && 'live' !== $channel ) { + throw new InvalidArgumentException( 'Static publish channel is invalid.' ); + } $settings = Spacefast_Settings::get(); return $this->request( 'POST', @@ -281,7 +287,7 @@ public function create_static_version( array $files, string $event_id, string $p array( 'publishMode' => $publish_mode, 'files' => $files, - 'finalize' => array( 'channel' => 'live' ), + 'finalize' => array( 'channel' => $channel ), 'source' => array( 'kind' => 'api', 'client' => 'spacefast-wordpress/' . SPACEFAST_WORDPRESS_VERSION, @@ -300,6 +306,38 @@ public function create_static_version( array $files, string $event_id, string $p /** * @return array{ok:bool,retryable:bool,code:string,message:string,data:array} */ + public function list_versions( int $limit = 20 ): array { + $settings = Spacefast_Settings::get(); + return $this->request( 'GET', '/v1/spaces/' . rawurlencode( $settings['space_id'] ) . '/versions?limit=' . max( 1, min( 20, $limit ) ) ); + } + + public function preview_session( string $version_id, string $landing_path = '/' ): array { + return $this->request( 'POST', $this->version_path( $version_id ) . '/preview-session', array( 'landingPath' => $landing_path ) ); + } + + /** + * @param string $idempotency_key Reused when an approved promotion is resent. + * @param string $continuation_token Token from an approved confirmation_required response. + */ + public function promote_version( string $version_id, string $idempotency_key = '', string $continuation_token = '' ): array { + $headers = array(); + if ( '' !== $idempotency_key ) $headers['Idempotency-Key'] = $idempotency_key; + if ( '' !== $continuation_token ) $headers['X-Spacefast-Continuation-Token'] = $continuation_token; + // Leave refreshRewrites at the server default, including for rollback. + return $this->request( 'POST', $this->version_path( $version_id ) . '/promote', array( 'channel' => 'live' ), $headers, 120 ); + } + + public function delete_version( string $version_id ): array { + return $this->request( 'DELETE', $this->version_path( $version_id ) ); + } + + private function version_path( string $version_id ): string { + if ( ! preg_match( '/^ver_[A-Za-z0-9_-]+$/', $version_id ) ) { + throw new InvalidArgumentException( 'Version ID is invalid.' ); + } + return '/v1/spaces/' . rawurlencode( Spacefast_Settings::get()['space_id'] ) . '/versions/' . rawurlencode( $version_id ); + } + public function resume_static_upload( string $version_id ): array { $settings = Spacefast_Settings::get(); return $this->request( diff --git a/includes/class-spacefast-oauth.php b/includes/class-spacefast-oauth.php index adbfba1..deb83c0 100644 --- a/includes/class-spacefast-oauth.php +++ b/includes/class-spacefast-oauth.php @@ -17,8 +17,10 @@ public function __construct( ?callable $transport = null ) { /** @return array */ public static function scopes( string $mode ): array { + // spaces:publish alone excludes versions:promote and versions:download. + // publish:write includes both, including preview-session access. return Spacefast_Settings::MODE_STATIC === $mode - ? array( 'teams:read', 'spaces:read', 'spaces:write', 'spaces:publish', 'offline_access' ) + ? array( 'teams:read', 'spaces:read', 'spaces:write', 'publish:write', 'offline_access' ) : array( 'teams:read', 'spaces:read', 'spaces:write', 'builds:trigger', 'offline_access' ); } diff --git a/includes/class-spacefast-plugin.php b/includes/class-spacefast-plugin.php index c1d35a8..9ab1d1a 100644 --- a/includes/class-spacefast-plugin.php +++ b/includes/class-spacefast-plugin.php @@ -7,6 +7,7 @@ final class Spacefast_Plugin { const STATIC_DELIVERY_STALE_SECONDS = 2 * HOUR_IN_SECONDS; const LOCK_OPTION = 'spacefast_wordpress_worker_lock'; const NOTICE_TRANSIENT = 'spacefast_wordpress_admin_notice'; + const APPROVAL_OPTION = 'spacefast_wordpress_pending_approval'; /** @var bool */ private static $change_recorded = false; @@ -25,6 +26,9 @@ public static function boot(): void { add_action( 'admin_post_spacefast_wordpress_publish', array( __CLASS__, 'manual_static_publish' ) ); add_action( 'admin_post_spacefast_wordpress_save_settings', array( __CLASS__, 'save_settings' ) ); add_action( 'admin_post_spacefast_wordpress_sync_settings', array( __CLASS__, 'manual_settings_sync' ) ); + foreach ( array( 'go_live', 'rollback', 'discard', 'preview', 'finish_approval', 'cancel_approval' ) as $action ) { + add_action( 'admin_post_spacefast_wordpress_' . $action, array( __CLASS__, $action ) ); + } add_action( Spacefast_Sync_State::HOOK, array( __CLASS__, 'deliver' ) ); add_action( 'init', array( __CLASS__, 'register_simply_static' ), 20 ); add_action( 'transition_post_status', array( __CLASS__, 'post_transition' ), 10, 3 ); @@ -76,7 +80,7 @@ public static function admin_menu(): void { add_options_page( __( 'Spacefast', 'spacefast-wordpress' ), __( 'Spacefast', 'spacefast-wordpress' ), - 'manage_options', + self::can_stage() && ! current_user_can( 'manage_options' ) ? 'edit_others_posts' : 'manage_options', 'spacefast-wordpress', array( __CLASS__, 'render_admin' ) ); @@ -89,6 +93,208 @@ private static function assert_admin( string $action ): void { check_admin_referer( $action ); } + public static function can_promote(): bool { + return (bool) apply_filters( 'spacefast_wordpress_can_promote', current_user_can( 'manage_options' ) ); + } + + public static function can_stage(): bool { + return current_user_can( 'manage_options' ) || ( + Spacefast_Settings::MODE_STATIC === Spacefast_Settings::mode() + && Spacefast_Settings::configured() + && ! empty( Spacefast_Settings::get()['review_before_live'] ) + && current_user_can( 'edit_others_posts' ) + ); + } + + /** Authorize every entry point before using the stored Team credential. */ + /** + * @param array|null $approval Pending approval being finished; its caller checked the nonce. + */ + private static function version_action( string $action, ?Spacefast_Client $client = null, ?array $approval = null ): array { + $allowed = in_array( $action, array( 'go_live', 'rollback', 'discard' ), true ) ? self::can_promote() : self::can_stage(); + if ( ! $allowed ) { + wp_die( esc_html__( 'You are not allowed to manage this version.', 'spacefast-wordpress' ), 403 ); + } + if ( null === $approval ) { + check_admin_referer( 'spacefast_wordpress_' . $action ); + $version_id = isset( $_POST['version_id'] ) && is_string( $_POST['version_id'] ) ? wp_unslash( $_POST['version_id'] ) : ''; + } else { + $version_id = (string) $approval['version_id']; + } + $state = Spacefast_Sync_State::get(); + if ( Spacefast_Settings::MODE_STATIC !== Spacefast_Settings::mode() || ! Spacefast_Settings::selected() + || ! preg_match( '/^ver_[A-Za-z0-9_-]+$/', $version_id ) + || ( in_array( $action, array( 'go_live', 'discard', 'preview' ), true ) && $version_id !== $state['staged_version_id'] ) ) { + return array( 'ok' => false, 'message' => __( 'This version is no longer available for this action. Reload the page.', 'spacefast-wordpress' ) ); + } + if ( ! Spacefast_OAuth::has_scope( 'publish:write' ) ) { + return array( 'ok' => false, 'message' => __( 'Reconnect Spacefast to enable previews, promotion, and rollback.', 'spacefast-wordpress' ) ); + } + $client = $client ?? new Spacefast_Client(); + // Check the server, not the cached card: another publisher may have made it live. + $version = $client->get_static_version( $version_id ); + if ( ! $version['ok'] ) return $version; + if ( 'ready' !== ( $version['data']['status'] ?? '' ) || ! empty( $version['data']['isCurrentProduction'] ) ) { + return array( 'ok' => false, 'message' => __( 'Choose a ready version that is not currently live.', 'spacefast-wordpress' ) ); + } + if ( 'preview' === $action ) return $client->preview_session( $version_id, '/' ); + if ( 'discard' === $action ) { + $result = $client->delete_version( $version_id ); + } else { + $idempotency_key = null === $approval ? wp_generate_uuid4() : (string) $approval['idempotency_key']; + $result = $client->promote_version( $version_id, $idempotency_key, null === $approval ? '' : (string) $approval['token'] ); + if ( ! $result['ok'] && 'confirmation_required' === $result['code'] && null === $approval ) { + return self::remember_approval( $action, $version_id, $idempotency_key, $result ); + } + if ( ! $result['ok'] && 'confirmation_token_required' === $result['code'] && null === $approval ) { + // An earlier request for this exact action is still open in Spacefast. + return array( 'ok' => false, 'code' => 'approval_open', 'message' => __( 'Spacefast already has an approval request open for this action. Decide it in Spacefast or wait for it to expire, then try again.', 'spacefast-wordpress' ) ); + } + if ( ! $result['ok'] && null !== $approval && in_array( $result['code'], array( 'confirmation_required', 'confirmation_pending', 'confirmation_token_required' ), true ) ) { + return array( 'ok' => false, 'code' => 'approval_pending', 'message' => __( 'Spacefast has not recorded an approval yet. Approve it in Spacefast, then choose Finish again.', 'spacefast-wordpress' ) ); + } + } + if ( ! $result['ok'] ) return $result; + if ( 'discard' !== $action && ( 'ready' !== ( $result['data']['status'] ?? '' ) || true !== ( $result['data']['isCurrentProduction'] ?? false ) + || ! preg_match( '/^ver_[A-Za-z0-9_-]+$/', (string) ( $result['data']['id'] ?? '' ) ) ) ) { + return array( 'ok' => false, 'message' => __( 'Promotion is not confirmed yet. Reload Versions to check before retrying.', 'spacefast-wordpress' ) ); + } + $updated = Spacefast_Sync_State::mutate( + static function ( array $current ) use ( $action, $version_id, $result ): array { + if ( $current['staged_version_id'] === $version_id ) { + $current['staged_version_id'] = ''; + $current['staged_publish_mode'] = ''; + } + if ( 'discard' !== $action ) { + $current['last_version_id'] = $result['data']['id']; + $current['last_success_at'] = time(); + $current['version_sources'][ $result['data']['id'] ] = $current['version_sources'][ $result['data']['id'] ] ?? 'manual'; + $current['version_sources'] = array_slice( $current['version_sources'], -20, null, true ); + } + // Do not acknowledge queued edits or overwrite an active export. + if ( ! self::static_delivery_active( $current ) && (int) $current['desired'] <= (int) $current['delivered'] ) { + $current['last_status'] = 'discard' === $action ? 'idle' : 'live'; + } + return $current; + } + ); + if ( 'discard' !== $action ) { + Spacefast_Settings::merge( array( 'verified_at' => time() ) ); + if ( $version_id === $state['staged_version_id'] && 'snapshot' === $state['staged_publish_mode'] + && (int) $updated['desired'] <= (int) $state['delivered'] ) { + delete_option( 'spacefast_wordpress_snapshot_required' ); + } + } + return $result; + } + + /** + * Spacefast can ask a person to approve a promotion before it runs. Keep the + * continuation token server-side and resend the identical request later. + * + * @param array $result confirmation_required response. + */ + private static function remember_approval( string $action, string $version_id, string $idempotency_key, array $result ): array { + $details = $result['details'] ?? array(); + $url = (string) ( $details['url'] ?? '' ); + $token = (string) ( $details['continuationToken'] ?? '' ); + if ( 'https' !== wp_parse_url( $url, PHP_URL_SCHEME ) || '' === $token ) { + return array( 'ok' => false, 'code' => 'confirmation_required', 'message' => __( 'Spacefast asked for an approval it did not describe. Try again from Spacefast.', 'spacefast-wordpress' ) ); + } + $expires_at = strtotime( (string) ( $details['expiresAt'] ?? '' ) ); + update_option( + self::APPROVAL_OPTION, + array( + 'action' => $action, + 'version_id' => $version_id, + 'idempotency_key' => $idempotency_key, + 'token' => $token, + 'url' => $url, + 'expires_at' => false === $expires_at ? time() + 10 * MINUTE_IN_SECONDS : $expires_at, + ), + false + ); + return array( + 'ok' => false, + 'code' => 'approval_required', + 'message' => 'rollback' === $action + ? __( 'Spacefast needs a person to approve this rollback. Approve it in Spacefast, then choose Finish.', 'spacefast-wordpress' ) + : __( 'Spacefast needs a person to approve going live. Approve it in Spacefast, then choose Finish.', 'spacefast-wordpress' ), + ); + } + + /** @return array|null */ + public static function pending_approval(): ?array { + $approval = get_option( self::APPROVAL_OPTION, null ); + if ( ! is_array( $approval ) || ! in_array( $approval['action'] ?? '', array( 'go_live', 'rollback' ), true ) ) return null; + if ( (int) ( $approval['expires_at'] ?? 0 ) <= time() ) { + delete_option( self::APPROVAL_OPTION ); + return null; + } + return $approval; + } + + private static function finish_approval_action( ?Spacefast_Client $client = null ): array { + if ( ! self::can_promote() ) { + wp_die( esc_html__( 'You are not allowed to manage this version.', 'spacefast-wordpress' ), 403 ); + } + check_admin_referer( 'spacefast_wordpress_finish_approval' ); + $approval = self::pending_approval(); + if ( null === $approval ) { + return array( 'ok' => false, 'message' => __( 'The approval request expired. Start the action again.', 'spacefast-wordpress' ) ); + } + $result = self::version_action( (string) $approval['action'], $client, $approval ); + if ( 'approval_pending' !== ( $result['code'] ?? '' ) ) delete_option( self::APPROVAL_OPTION ); + return $result + array( 'action' => $approval['action'] ); + } + + public static function finish_approval(): void { + $result = self::finish_approval_action(); + self::notice( $result['ok'] ? 'success' : 'error', $result['ok'] ? __( 'The selected version is now live.', 'spacefast-wordpress' ) : $result['message'] ); + self::redirect(); + } + + public static function cancel_approval(): void { + if ( ! self::can_promote() ) { + wp_die( esc_html__( 'You are not allowed to manage this version.', 'spacefast-wordpress' ), 403 ); + } + check_admin_referer( 'spacefast_wordpress_cancel_approval' ); + delete_option( self::APPROVAL_OPTION ); + self::notice( 'success', __( 'Approval request dismissed. Nothing changed.', 'spacefast-wordpress' ) ); + self::redirect(); + } + + private static function handle_version_action( string $action ): void { + $result = self::version_action( $action ); + self::notice( $result['ok'] ? 'success' : ( 'approval_required' === ( $result['code'] ?? '' ) ? 'warning' : 'error' ), $result['ok'] + ? ( 'discard' === $action ? __( 'Staged version discarded.', 'spacefast-wordpress' ) : __( 'The selected version is now live.', 'spacefast-wordpress' ) ) + : $result['message'] ); + self::redirect(); + } + + public static function go_live(): void { + self::handle_version_action( 'go_live' ); + } + + public static function rollback(): void { + self::handle_version_action( 'rollback' ); + } + + public static function discard(): void { + self::handle_version_action( 'discard' ); + } + + public static function preview(): void { + $result = self::version_action( 'preview' ); + nocache_headers(); + if ( ! $result['ok'] ) wp_send_json_error( array( 'message' => $result['message'] ), 400 ); + $url = (string) ( $result['data']['url'] ?? '' ); + if ( 'https' !== wp_parse_url( $url, PHP_URL_SCHEME ) ) { + wp_send_json_error( array( 'message' => __( 'Spacefast returned an invalid preview URL.', 'spacefast-wordpress' ) ), 502 ); + } + wp_send_json_success( array( 'url' => $url, 'expiresAt' => (string) ( $result['data']['expiresAt'] ?? '' ) ) ); + } + private static function redirect(): void { wp_safe_redirect( admin_url( 'options-general.php?page=spacefast-wordpress' ) ); exit; @@ -381,7 +587,8 @@ public static function manual_build(): void { } public static function manual_static_publish(): void { - self::assert_admin( 'spacefast_wordpress_publish' ); + if ( ! self::can_stage() ) wp_die( esc_html__( 'You are not allowed to publish.', 'spacefast-wordpress' ), 403 ); + check_admin_referer( 'spacefast_wordpress_publish' ); if ( Spacefast_Settings::MODE_STATIC !== Spacefast_Settings::mode() ) { self::notice( 'error', __( 'Switch to Static WordPress to publish an export.', 'spacefast-wordpress' ) ); self::redirect(); @@ -417,6 +624,7 @@ public static function save_settings(): void { Spacefast_Settings::merge( array( 'automatic_sync' => isset( $_POST['automatic_sync'] ), + 'review_before_live' => isset( $_POST['review_before_live'] ), 'sync_title' => isset( $_POST['sync_title'] ), 'sync_visibility' => isset( $_POST['sync_visibility'] ), 'sync_source' => isset( $_POST['sync_source'] ), @@ -804,6 +1012,8 @@ static function ( array $state ): array { Spacefast_Sync_State::mutate( static function ( array $state ): array { $state['last_attempt_at'] = time(); + $state['active_source'] = $state['pending_source']; + $state['active_review'] = ! empty( Spacefast_Settings::get()['review_before_live'] ); return $state; } ); @@ -944,6 +1154,8 @@ static function ( array $state ): array { (string) wp_generate_uuid4() ); $next['last_status'] = 'exporting'; + $next['active_review'] = ! empty( Spacefast_Settings::get()['review_before_live'] ); + $next['active_source'] = null !== $state['active_review'] ? $state['active_source'] : 'manual'; $next['active_generation'] = (int) $next['desired']; $next['last_attempt_at'] = time(); return $next; @@ -962,13 +1174,13 @@ static function ( array $state ) use ( $status ): array { ); } - public static function static_publish_completed( string $version_id, string $status ): void { + public static function static_publish_completed( string $version_id, string $status, string $publish_mode = 'snapshot' ): void { $current = Spacefast_Sync_State::mutate( - static fn( array $state ): array => Spacefast_Sync_State::acknowledge_static( - $state, - $version_id, - $status - ) + static function ( array $state ) use ( $version_id, $status, $publish_mode ): array { + $state = Spacefast_Sync_State::acknowledge_static( $state, $version_id, $status ); + if ( 'staged' === $status ) $state['staged_publish_mode'] = $publish_mode; + return $state; + } ); if ( 'live' === $status ) Spacefast_Settings::merge( array( 'verified_at' => time() ) ); if ( (int) $current['desired'] > (int) $current['delivered'] ) { @@ -1040,6 +1252,7 @@ public static function status_label( string $status, bool $static_mode ): string 'finalizing' => __( 'Activating new version', 'spacefast-wordpress' ), 'live' => __( 'Published live', 'spacefast-wordpress' ), 'ready' => __( 'Version ready', 'spacefast-wordpress' ), + 'staged' => __( 'Staged for review', 'spacefast-wordpress' ), 'unchanged' => __( 'Already up to date', 'spacefast-wordpress' ), 'retrying' => __( 'Retrying automatically', 'spacefast-wordpress' ), 'blocked' => __( 'Needs attention', 'spacefast-wordpress' ), @@ -1080,11 +1293,20 @@ public static function site_health_result(): array { } public static function render_admin(): void { - if ( ! current_user_can( 'manage_options' ) ) { + if ( ! self::can_stage() ) { return; } $notice = get_transient( self::NOTICE_TRANSIENT ); delete_transient( self::NOTICE_TRANSIENT ); + if ( ! current_user_can( 'manage_options' ) ) { + echo '

' . esc_html__( 'Spacefast', 'spacefast-wordpress' ) . '

'; + if ( is_array( $notice ) ) echo '

' . esc_html( $notice['message'] ) . '

'; + echo '

' . esc_html( self::status_label( Spacefast_Sync_State::get()['last_status'], true ) ) . '

'; + self::action_form( 'spacefast_wordpress_publish', __( 'Stage now', 'spacefast-wordpress' ), 'primary' ); + self::render_versions(); + echo '
'; + return; + } $state = Spacefast_Sync_State::get(); $settings = Spacefast_Settings::get(); $authorized = Spacefast_Settings::authorized(); @@ -1098,7 +1320,7 @@ public static function render_admin(): void {

-

+

@@ -1173,6 +1395,7 @@ public static function render_admin(): void {
+

@@ -1180,6 +1403,7 @@ public static function render_admin(): void {
+ @@ -1207,6 +1431,153 @@ public static function render_admin(): void {

' . esc_html__( 'Reconnect Spacefast to enable previews, promotion, and rollback.', 'spacefast-wordpress' ) . '

'; + if ( current_user_can( 'manage_options' ) ) self::oauth_action_form( Spacefast_Settings::MODE_STATIC, __( 'Reconnect Spacefast', 'spacefast-wordpress' ) ); + echo ''; + } + $history = $client->list_versions( 20 ); + $versions = $history['ok'] ? $history['data'] : array(); + $staged = null; + foreach ( $versions as $version ) { + if ( is_array( $version ) && ( $version['id'] ?? '' ) === $state['staged_version_id'] ) $staged = $version; + } + if ( null === $staged && '' !== $state['staged_version_id'] ) { + $result = $client->get_static_version( $state['staged_version_id'] ); + if ( $result['ok'] ) $staged = $result['data']; + else echo '

' . esc_html( $result['message'] ) . '

'; + } + $approval = $scoped && self::can_promote() ? self::pending_approval() : null; + if ( null !== $approval ) : + $approval_label = ''; + foreach ( $versions as $version ) { + if ( is_array( $version ) && ( $version['id'] ?? '' ) === $approval['version_id'] ) $approval_label = (string) ( $version['ref'] ?? '' ); + } + $approval_label = '' !== $approval_label ? $approval_label : (string) $approval['version_id']; + ?> +
+

+

+

+

+ + + +

+
+ +
+

+

+

+ + + + + + + +

+ +

+ +
+ + + + +
+ +
+ + +
+

+

+

+

+ + + + + + + + + + +
+ + + +
+ +
+ +
+ + + + +
+ '', 'verified_at' => 0, 'automatic_sync' => true, + 'review_before_live' => false, 'sync_title' => true, 'sync_visibility' => true, 'sync_source' => true, @@ -106,6 +107,7 @@ public static function disconnect(): void { delete_option( Spacefast_OAuth::CHOICES_OPTION ); delete_option( Spacefast_OAuth::CREATION_OPTION ); delete_option( 'spacefast_wordpress_snapshot_required' ); + delete_option( 'spacefast_wordpress_pending_approval' ); Spacefast_Sync_State::reset(); Spacefast_Static_Publisher::reset(); } diff --git a/includes/class-spacefast-simply-static-task.php b/includes/class-spacefast-simply-static-task.php index 769bbd8..377f378 100644 --- a/includes/class-spacefast-simply-static-task.php +++ b/includes/class-spacefast-simply-static-task.php @@ -23,10 +23,12 @@ public function perform() { __( 'Content was deleted. Run a full Export and publish so the old files are removed from Spacefast.', 'spacefast-wordpress' ) ); } + $review = Spacefast_Sync_State::get()['active_review'] ?? Spacefast_Settings::get()['review_before_live']; $result = Spacefast_Static_Publisher::step( $options->get_archive_dir(), null, - $partial_export ? 'additive' : 'snapshot' + $partial_export ? 'additive' : 'snapshot', + $review ? null : 'live' ); if ( ! $result['done'] ) { Spacefast_Plugin::static_publish_progress( $result['status'] ); @@ -43,14 +45,14 @@ public function perform() { return false; } - Spacefast_Plugin::static_publish_completed( $result['version_id'], $result['status'] ); - if ( ! $partial_export ) { + Spacefast_Plugin::static_publish_completed( $result['version_id'], $result['status'], $partial_export ? 'additive' : 'snapshot' ); + if ( ! $partial_export && ( 'live' === $result['status'] || ( ! $review && 'unchanged' === $result['status'] ) ) ) { delete_option( 'spacefast_wordpress_snapshot_required' ); } $this->save_status_message( 'unchanged' === $result['status'] ? __( 'Spacefast is already up to date', 'spacefast-wordpress' ) - : __( 'Published to Spacefast', 'spacefast-wordpress' ) + : ( 'staged' === $result['status'] ? __( 'Staged for review in Settings → Spacefast', 'spacefast-wordpress' ) : __( 'Published to Spacefast', 'spacefast-wordpress' ) ) ); return true; } catch ( Throwable $error ) { diff --git a/includes/class-spacefast-static-publisher.php b/includes/class-spacefast-static-publisher.php index 0e24c12..9ced325 100644 --- a/includes/class-spacefast-static-publisher.php +++ b/includes/class-spacefast-static-publisher.php @@ -22,7 +22,8 @@ final class Spacefast_Static_Publisher { public static function step( string $archive_dir, ?Spacefast_Client $client = null, - string $publish_mode = 'snapshot' + string $publish_mode = 'snapshot', + ?string $channel = 'live' ): array { if ( ! in_array( $publish_mode, array( 'additive', 'snapshot' ), true ) ) { throw new InvalidArgumentException( 'Static publish mode is invalid.' ); @@ -55,7 +56,7 @@ public static function step( ) { $manifest = self::manifest( $root ); $event_id = (string) wp_generate_uuid4(); - $result = $client->create_static_version( $manifest, $event_id, $publish_mode ); + $result = $client->create_static_version( $manifest, $event_id, $publish_mode, $channel ); if ( ! $result['ok'] ) { throw new RuntimeException( $result['message'] ); } @@ -80,6 +81,7 @@ public static function step( $state = array( 'archive_dir' => $root, 'publish_mode' => $publish_mode, + 'channel' => $channel, 'event_id' => $event_id, 'version_id' => $version_id, 'upload' => $upload, @@ -347,7 +349,9 @@ private static function poll_version( array $state, Spacefast_Client $client ): 'version_id' => (string) $state['version_id'], 'uploaded' => (int) $state['uploaded'], 'total' => (int) $state['total'], - 'status' => true === ( $result['data']['isCurrentProduction'] ?? false ) ? 'live' : 'ready', + 'status' => true === ( $result['data']['isCurrentProduction'] ?? false ) + ? 'live' + : ( array_key_exists( 'channel', $state ) && null === $state['channel'] ? 'staged' : 'ready' ), ); } if ( in_array( $status, array( 'failed', 'canceled', 'expired' ), true ) ) { diff --git a/includes/class-spacefast-sync-state.php b/includes/class-spacefast-sync-state.php index 3a2d516..cc51f78 100644 --- a/includes/class-spacefast-sync-state.php +++ b/includes/class-spacefast-sync-state.php @@ -7,7 +7,7 @@ final class Spacefast_Sync_State { const HOOK = 'spacefast_wordpress_deliver'; /** - * @return array{desired:int,delivered:int,event_id:string,reasons:array,attempts:int,next_at:int,last_status:string,last_message:string,last_build_id:string,last_version_id:string,last_change_at:int,last_attempt_at:int,last_success_at:int,last_settings_sync_at:int,active_generation:int,settings_pending:bool} + * @return array{desired:int,delivered:int,event_id:string,reasons:array,attempts:int,next_at:int,last_status:string,last_message:string,last_build_id:string,last_version_id:string,staged_version_id:string,staged_publish_mode:string,active_review:?bool,active_source:string,pending_source:string,version_sources:array,last_change_at:int,last_attempt_at:int,last_success_at:int,last_settings_sync_at:int,active_generation:int,settings_pending:bool} */ public static function defaults(): array { return array( @@ -21,6 +21,12 @@ public static function defaults(): array { 'last_message' => '', 'last_build_id' => '', 'last_version_id' => '', + 'staged_version_id' => '', + 'staged_publish_mode' => '', + 'active_review' => null, + 'active_source' => 'manual', + 'pending_source' => 'manual', + 'version_sources' => array(), 'last_change_at' => 0, 'last_attempt_at' => 0, 'last_success_at' => 0, @@ -31,7 +37,7 @@ public static function defaults(): array { } /** - * @return array{desired:int,delivered:int,event_id:string,reasons:array,attempts:int,next_at:int,last_status:string,last_message:string,last_build_id:string,last_version_id:string,last_change_at:int,last_attempt_at:int,last_success_at:int,last_settings_sync_at:int,active_generation:int,settings_pending:bool} + * @return array{desired:int,delivered:int,event_id:string,reasons:array,attempts:int,next_at:int,last_status:string,last_message:string,last_build_id:string,last_version_id:string,staged_version_id:string,staged_publish_mode:string,active_review:?bool,active_source:string,pending_source:string,version_sources:array,last_change_at:int,last_attempt_at:int,last_success_at:int,last_settings_sync_at:int,active_generation:int,settings_pending:bool} */ public static function get(): array { $value = get_option( self::OPTION, array() ); @@ -47,6 +53,7 @@ public static function get(): array { public static function record_change( array $state, string $reason, string $event_id ): array { $state = array_merge( self::defaults(), $state ); $state['desired'] = (int) $state['desired'] + 1; + if ( 'static_export' !== $reason ) $state['pending_source'] = 'manual' === $reason ? 'manual' : 'auto'; $state['event_id'] = $event_id; $state['reasons'] = array_values( array_unique( @@ -125,6 +132,14 @@ public static function acknowledge_static( array $state, string $version_id, str $state['last_status'] = (int) $state['desired'] > (int) $state['delivered'] ? 'pending' : $status; $state['last_message'] = ''; $state['last_version_id'] = $version_id; + if ( 'staged' === $status ) { + $state['staged_version_id'] = $version_id; + } + if ( '' !== $version_id ) { + $state['version_sources'][ $version_id ] = $state['active_source']; + $state['version_sources'] = array_slice( $state['version_sources'], -20, null, true ); + } + $state['active_review'] = null; $state['last_success_at'] = time(); $state['active_generation'] = 0; return $state; @@ -148,14 +163,18 @@ public static function save( array $state ): void { */ public static function mutate( callable $transition ): array { for ( $attempt = 0; $attempt < 10; $attempt++ ) { - $current = self::get(); + // Compare against the row as stored, not the defaults-merged view: + // state saved by an earlier release lacks newer keys, and swapping + // against the merged array would never match that row. + $stored = get_option( self::OPTION, array() ); + $current = array_merge( self::defaults(), is_array( $stored ) ? $stored : array() ); $next = $transition( $current ); // MySQL reports zero affected rows when the serialized value is // unchanged. That is a successful no-op, not a CAS conflict. if ( $next === $current ) { return $current; } - if ( self::compare_and_swap_option( self::OPTION, $current, $next ) ) { + if ( self::compare_and_swap_option( self::OPTION, $stored, $next ) ) { return $next; } } diff --git a/readme.txt b/readme.txt index a4ceb22..e043cbb 100644 --- a/readme.txt +++ b/readme.txt @@ -3,7 +3,7 @@ Contributors: spacefast Tags: static site, headless cms, simply static, deployment Requires at least: 6.5 Requires PHP: 8.1 -Stable tag: 0.5.8 +Stable tag: 0.6.0 License: GPLv2 or later Publish a Simply Static export to Spacefast, or rebuild a headless site when WordPress content changes. @@ -29,8 +29,26 @@ Both modes include a manual action in Settings > Spacefast. Headless repository OAuth access is limited to the Team you authorize and the mode you choose. WordPress syncs only the selected Space and waits for a real first publish or build before showing the connection as complete. Tokens are stored in non-autoloaded options and are never displayed. +== Review before going live == + +In Settings > Spacefast > WordPress sync, enable Review before going live to stage manual and automatic exports. It is off by default. Partial exports stay additive and preserve omitted files. + +The Staged version card shows file changes. Open preview opens the staged version in a new tab; Copy preview link creates a link that grants access for 10 minutes. Share it with your reviewer, then choose Go live to promote the version, or Discard to permanently delete it. The live site stays in place until promotion succeeds. + +Versions shows the last 20 versions, their time, source, file count, and live status. Make live restores an earlier ready version using Spacefast's default rewrite refresh. Sources are recorded locally; versions from before this update or other publishers show Unknown. + +Editors can stage and preview when review is enabled. Administrators can promote, roll back, and discard; developers can customize those permissions with the spacefast_wordpress_can_promote filter. Reconnect existing static installations once to grant publish:write for promotion and preview sessions. + == Changelog == += 0.6.0 = +* Stage static exports for review with expiring preview links, then promote or discard from WordPress. +* Browse the latest 20 versions and restore an earlier version with Make live. +* Let editors stage while administrators control promotion, with a promotion capability filter. +* Request publish:write for static preview and promotion; existing connections show a reconnect notice. +* When Spacefast requires a person to approve a promotion or rollback, link to the approval and finish the same request afterward. +* Keep sync state written by earlier versions working after upgrade. + = 0.5.8 = * Retry transient upload and upload-refresh failures in place, with exponential backoff for about four minutes, instead of restarting the whole export as a new version. * Once every file has uploaded, ask Spacefast which files it still lacks, upload any it names, and let that check trigger activation instead of depending on the upload-completion signal alone. diff --git a/spacefast-wordpress.php b/spacefast-wordpress.php index 8b775fd..210beef 100644 --- a/spacefast-wordpress.php +++ b/spacefast-wordpress.php @@ -3,7 +3,7 @@ * Plugin Name: Spacefast * Plugin URI: https://spacefast.com/ * Description: Publishes static WordPress exports or rebuilds a headless Spacefast site. - * Version: 0.5.8 + * Version: 0.6.0 * Update URI: https://github.com/spacefast/wordpress * Requires at least: 6.5 * Requires PHP: 8.1 @@ -14,7 +14,7 @@ defined( 'ABSPATH' ) || exit; -define( 'SPACEFAST_WORDPRESS_VERSION', '0.5.8' ); +define( 'SPACEFAST_WORDPRESS_VERSION', '0.6.0' ); define( 'SPACEFAST_WORDPRESS_FILE', __FILE__ ); require_once __DIR__ . '/includes/class-spacefast-settings.php'; diff --git a/tests/acceptance/wordpress.php b/tests/acceptance/wordpress.php index 4572378..c2d646a 100644 --- a/tests/acceptance/wordpress.php +++ b/tests/acceptance/wordpress.php @@ -38,7 +38,7 @@ function spacefast_accept( bool $condition, string $message ): void { 'Space change handler is not registered.' ); spacefast_accept( - array( 'teams:read', 'spaces:read', 'spaces:write', 'spaces:publish', 'offline_access' ) === Spacefast_OAuth::scopes( Spacefast_Settings::MODE_STATIC ), + array( 'teams:read', 'spaces:read', 'spaces:write', 'publish:write', 'offline_access' ) === Spacefast_OAuth::scopes( Spacefast_Settings::MODE_STATIC ), 'Static mode requested unexpected OAuth scopes.' ); spacefast_accept( @@ -113,8 +113,61 @@ function spacefast_accept( bool $condition, string $message ): void { ); $plugin = get_plugin_data( WP_PLUGIN_DIR . '/spacefast-wordpress/spacefast-wordpress.php', false, false ); -spacefast_accept( '0.5.8' === $plugin['Version'], 'Unexpected plugin version.' ); +spacefast_accept( '0.6.0' === $plugin['Version'], 'Unexpected plugin version.' ); spacefast_accept( 'https://github.com/spacefast/wordpress' === $plugin['UpdateURI'], 'Update URI is missing.' ); +foreach ( array( 'go_live', 'rollback', 'discard', 'preview' ) as $action ) { + spacefast_accept( 10 === has_action( 'admin_post_spacefast_wordpress_' . $action, array( 'Spacefast_Plugin', $action ) ), 'Version action is not registered: ' . $action ); +} +spacefast_accept( false === Spacefast_Settings::get()['review_before_live'], 'Review must default to off.' ); +Spacefast_Settings::merge( array( 'review_before_live' => true, 'scope' => 'teams:read spaces:read spaces:write publish:write offline_access' ) ); +Spacefast_Sync_State::save( array_merge( Spacefast_Sync_State::defaults(), array( + 'staged_version_id' => 'ver_review', + 'staged_publish_mode' => 'snapshot', + 'last_status' => 'staged', + 'version_sources' => array( 'ver_review' => 'manual', 'ver_live' => 'auto' ), +) ) ); +$version_http = static function ( $preempt, array $args, string $url ) { + if ( ! str_contains( $url, '/versions' ) ) return $preempt; + return array( 'response' => array( 'code' => 200 ), 'body' => wp_json_encode( array( 'data' => array( + array( 'id' => 'ver_review', 'ref' => 'v3', 'status' => 'ready', 'createdAt' => '2026-11-16T12:00:00Z', 'fileCount' => 12, 'filesAddedCount' => 2, 'filesChangedCount' => 3, 'filesRemovedCount' => 1, 'isCurrentProduction' => false ), + array( 'id' => 'ver_live', 'ref' => 'v2', 'status' => 'ready', 'createdAt' => '2026-11-15T12:00:00Z', 'fileCount' => 11, 'isCurrentProduction' => true ), + array( 'id' => 'ver_old', 'ref' => 'v1', 'status' => 'ready', 'createdAt' => '2026-11-14T12:00:00Z', 'fileCount' => 10, 'isCurrentProduction' => false ), + ) ) ), 'headers' => array() ); +}; +add_filter( 'pre_http_request', $version_http, 10, 3 ); +ob_start(); +Spacefast_Plugin::render_admin(); +$review_markup = (string) ob_get_clean(); +foreach ( array( 'Review before going live', 'Staged version', '2 files added, 3 changed, 1 removed.', 'Open preview', 'Copy preview link', 'Go live', 'Discard', 'Versions', 'Make live', 'Manual', 'Auto', 'Live' ) as $label ) { + spacefast_accept( str_contains( $review_markup, $label ), 'Review UI is missing: ' . $label ); +} +spacefast_accept( str_contains( $review_markup, 'name="version_id" value="ver_old"' ), 'Rollback form omits the old version ID.' ); +spacefast_accept( str_contains( $review_markup, wp_create_nonce( 'spacefast_wordpress_go_live' ) ), 'Go-live form lacks its nonce.' ); +spacefast_accept( ! str_contains( $review_markup, 'acceptance-access' ), 'Review UI exposes an OAuth token.' ); +$editor_id = wp_insert_user( array( 'user_login' => 'review-editor', 'user_pass' => wp_generate_password(), 'role' => 'editor' ) ); +spacefast_accept( ! is_wp_error( $editor_id ), 'Could not create the review editor.' ); +wp_set_current_user( $editor_id ); +ob_start(); +Spacefast_Plugin::render_admin(); +$editor_markup = (string) ob_get_clean(); +spacefast_accept( str_contains( $editor_markup, 'Stage now' ) && str_contains( $editor_markup, 'Open preview' ), 'Editor cannot stage and review.' ); +foreach ( array( 'Go live', 'Make live', 'Discard', 'Save and sync', 'Change connection' ) as $label ) { + spacefast_accept( ! str_contains( $editor_markup, '>' . $label . '<' ), 'Editor sees an administrator action: ' . $label ); +} +spacefast_accept( ! Spacefast_Plugin::can_promote(), 'Editor has promotion capability by default.' ); +wp_set_current_user( 1 ); +$deny_promote = static fn( bool $allowed ): bool => false; +add_filter( 'spacefast_wordpress_can_promote', $deny_promote ); +spacefast_accept( ! Spacefast_Plugin::can_promote(), 'Promotion capability filter is ignored.' ); +remove_filter( 'spacefast_wordpress_can_promote', $deny_promote ); +Spacefast_Settings::merge( array( 'scope' => 'teams:read spaces:read spaces:write spaces:publish offline_access' ) ); +ob_start(); +Spacefast_Plugin::render_admin(); +$legacy_markup = (string) ob_get_clean(); +spacefast_accept( str_contains( $legacy_markup, 'Reconnect Spacefast to enable previews, promotion, and rollback.' ), 'Existing installs do not get a reconnect notice.' ); +spacefast_accept( ! str_contains( $legacy_markup, 'value="spacefast_wordpress_go_live"' ), 'Existing grant exposes an unusable promotion action.' ); +remove_filter( 'pre_http_request', $version_http, 10 ); + Spacefast_Settings::disconnect(); fwrite( STDOUT, "Spacefast WordPress container acceptance: PASS\n" ); diff --git a/tests/behavior.php b/tests/behavior.php index 468f448..6a5c155 100644 --- a/tests/behavior.php +++ b/tests/behavior.php @@ -33,6 +33,45 @@ function untrailingslashit( string $value ): string { function __( string $value ): string { return $value; } +function esc_html__( string $value ): string { + return htmlspecialchars( $value ); +} +function esc_html( string $value ): string { + return htmlspecialchars( $value ); +} +function esc_html_e( string $value ): void { + echo esc_html( $value ); +} +function esc_attr( string $value ): string { + return htmlspecialchars( $value, ENT_QUOTES ); +} +function esc_attr_e( string $value ): void { + echo esc_attr( $value ); +} +function esc_url( string $value ): string { + return esc_attr( $value ); +} +function wp_nonce_field( string $action ): void { + echo ''; +} +function wp_date( string $format, int $timestamp ): string { + return date( $format, $timestamp ); +} +function current_user_can( string $capability ): bool { + return in_array( $capability, $GLOBALS['spacefast_test_caps'] ?? array( 'manage_options' ), true ); +} +function apply_filters( string $hook, $value ) { + return isset( $GLOBALS['spacefast_test_filters'][ $hook ] ) ? $GLOBALS['spacefast_test_filters'][ $hook ]( $value ) : $value; +} +function check_admin_referer( string $action ): void { + if ( ( $_POST['_wpnonce'] ?? '' ) !== $action ) throw new RuntimeException( 'Invalid nonce' ); +} +function wp_unslash( string $value ): string { + return stripslashes( $value ); +} +function wp_die( string $message, $title = '' ): void { + throw new RuntimeException( $message ); +} function sanitize_text_field( string $value ): string { return trim( strip_tags( $value ) ); } @@ -45,8 +84,8 @@ function add_action( string $hook, $callback, int $priority = 10, int $accepted_ function add_filter( string $hook, $callback, int $priority = 10, int $accepted_args = 1 ): void { $GLOBALS['spacefast_hooks'][ $hook ] = array( $callback, $priority, $accepted_args ); } -function wp_parse_url( string $value ) { - return parse_url( $value ); +function wp_parse_url( string $value, int $component = -1 ) { + return parse_url( $value, $component ); } function wp_check_filetype( string $path ): array { return array( @@ -162,6 +201,11 @@ function wp_safe_remote_request( string $url, array $args ) { } final class Spacefast_Test_Wp_Error {} +final class WP_Error { + public function __construct( string $code, string $message ) { + throw new RuntimeException( $code . ': ' . $message ); + } +} final class Spacefast_Test_Wpdb { public string $options = 'wp_options'; @@ -252,7 +296,7 @@ function raw_response( int $status, array $data = array() ): array { check( isset( $GLOBALS['spacefast_hooks']['update_option_home'] ), 'changing the WordPress Site Address queues settings sync' ); check( - array( 'teams:read', 'spaces:read', 'spaces:write', 'spaces:publish', 'offline_access' ) === Spacefast_OAuth::scopes( Spacefast_Settings::MODE_STATIC ), + array( 'teams:read', 'spaces:read', 'spaces:write', 'publish:write', 'offline_access' ) === Spacefast_OAuth::scopes( Spacefast_Settings::MODE_STATIC ), 'static OAuth asks for Team discovery, Space creation and discovery, publishing, and refresh access' ); check( @@ -550,6 +594,18 @@ static function ( string $url, array $args ) use ( &$revoke_requests ): array { unset( $GLOBALS['spacefast_cached_options'][ Spacefast_Sync_State::OPTION ] ); $unchanged_state = Spacefast_Sync_State::mutate( static fn( array $current ): array => $current ); check( $cas_ack === $unchanged_state, 'an unchanged journal transition succeeds without becoming a false CAS conflict' ); +$journal_before_upgrade = $GLOBALS['spacefast_options'][ Spacefast_Sync_State::OPTION ]; +// State saved by 0.5.x has none of the review keys added since. +$GLOBALS['spacefast_options'][ Spacefast_Sync_State::OPTION ] = array_diff_key( + $cas_ack, + array_flip( array( 'staged_version_id', 'staged_publish_mode', 'active_review', 'active_source', 'pending_source', 'version_sources' ) ) +); +$upgraded = Spacefast_Sync_State::mutate( + static fn( array $current ): array => Spacefast_Sync_State::record_change( $current, 'post_publish', 'event-upgrade' ) +); +check( 3 === $upgraded['desired'] && 'auto' === $upgraded['pending_source'], 'state saved by an earlier release still accepts transitions' ); +check( 'event-upgrade' === $GLOBALS['spacefast_options'][ Spacefast_Sync_State::OPTION ]['event_id'], 'upgraded state is written back with the new keys' ); +$GLOBALS['spacefast_options'][ Spacefast_Sync_State::OPTION ] = $journal_before_upgrade; $invalid_response = new Spacefast_Client( static fn(): array => array( @@ -1043,12 +1099,14 @@ static function ( string $url, string $method, array $headers, string $file ) us eval( 'namespace Simply_Static { - class Task {} + class Task { public function save_status_message($message) {} } class Options { private static $instance; public static function instance() { return self::$instance ??= new self(); } public function set($key, $value) { return $this; } public function save() { return true; } + public function get($key) { return $GLOBALS["spacefast_simply_options"][$key] ?? null; } + public function get_archive_dir() { return $GLOBALS["spacefast_simply_archive"]; } } class Plugin { public static $runs = 0; @@ -1269,6 +1327,221 @@ static function ( string $url, array $args ) use ( $retry_target ): array { check( $rejected, 'a rejected upload still ends the publish' ); Spacefast_Static_Publisher::reset(); +// Staging keeps the legacy live payload identical and pins the channel while resuming. +Spacefast_Settings::merge( array_merge( $static_connection, array( 'scope' => 'teams:read spaces:read spaces:write publish:write offline_access', 'review_before_live' => true ) ) ); +$version_requests = array(); +$version_failure = false; +$version_live = false; +$version_client = new Spacefast_Client( + static function ( string $url, array $args ) use ( &$version_requests, &$version_failure, &$version_live ): array { + $version_requests[] = array( $url, $args ); + if ( $version_failure ) return response( 403, array() ); + if ( 'DELETE' === $args['method'] ) return array( 'response' => array( 'code' => 204 ), 'body' => '' ); + if ( str_ends_with( $url, '/preview-session' ) ) return response( 200, array( 'url' => 'https://preview.example.test/?proof=private', 'expiresAt' => '2026-11-16T20:10:00Z' ) ); + if ( str_ends_with( $url, '/promote' ) ) return response( 200, array( 'id' => 'ver_promoted', 'status' => 'ready', 'isCurrentProduction' => true ) ); + if ( str_ends_with( $url, '/versions' ) ) return response( 201, array( 'versionId' => 'ver_staged', 'upload' => null ) ); + if ( str_contains( $url, '/versions?' ) ) return response( 200, array() ); + return response( 200, array( 'id' => 'ver_staged', 'status' => 'ready', 'isCurrentProduction' => $version_live ) ); + } +); +$version_client->create_static_version( $manifest, 'event-legacy', 'snapshot' ); +check( $version_requests[0][1]['body'] === $static_requests[0][1]['body'], 'toggle off preserves the legacy create request byte for byte' ); +$version_requests = array(); +Spacefast_Static_Publisher::step( $archive, $version_client, 'additive', null ); +$staged_body = json_decode( $version_requests[0][1]['body'], true ); +check( array_key_exists( 'channel', $staged_body['finalize'] ) && null === $staged_body['finalize']['channel'], 'staging explicitly serializes channel as null' ); +check( 'additive' === $staged_body['publishMode'], 'partial staging preserves omitted files with additive publishing' ); +Spacefast_Settings::merge( array( 'review_before_live' => false ) ); +$staged_done = Spacefast_Static_Publisher::step( $archive, $version_client, 'additive', 'live' ); +check( $staged_done['done'] && 'staged' === $staged_done['status'], 'changing the toggle during upload cannot promote the staged version' ); +check( 1 === count( array_filter( $version_requests, static fn( array $r ): bool => str_ends_with( $r[0], '/versions' ) ) ), 'resuming staging does not create another version' ); +Spacefast_Sync_State::save( array_merge( Spacefast_Sync_State::defaults(), array( 'desired' => 2, 'active_generation' => 1, 'active_source' => 'auto' ) ) ); +Spacefast_Plugin::static_publish_completed( 'ver_staged', 'staged', 'additive' ); +$staged_state = Spacefast_Sync_State::get(); +check( 'ver_staged' === $staged_state['staged_version_id'] && 'additive' === $staged_state['staged_publish_mode'], 'completion retains staged receipt and publish mode' ); +check( 'auto' === $staged_state['version_sources']['ver_staged'], 'history remembers automatic exports without changing the legacy payload' ); +check( 1 === $staged_state['delivered'] && 'pending' === $staged_state['last_status'], 'staging acknowledges only the exported generation' ); +$action = new ReflectionMethod( Spacefast_Plugin::class, 'version_action' ); +$GLOBALS['spacefast_test_caps'] = array( 'edit_others_posts' ); +check( ! Spacefast_Plugin::can_stage(), 'editors cannot directly publish when review is off' ); +Spacefast_Settings::merge( array( 'review_before_live' => true ) ); +check( Spacefast_Plugin::can_stage() && ! Spacefast_Plugin::can_promote(), 'editors can stage while promotion defaults to administrators' ); +foreach ( array( 'go_live', 'rollback', 'discard' ) as $verb ) { + $_POST = array( 'version_id' => 'ver_staged', '_wpnonce' => 'spacefast_wordpress_' . $verb ); + $before = count( $version_requests ); + $denied = false; + try { $action->invoke( null, $verb, $version_client ); } catch ( RuntimeException $error ) { $denied = true; } + check( $denied && $before === count( $version_requests ), 'editor cannot ' . $verb . ' through a forged form' ); +} +$GLOBALS['spacefast_test_caps'] = array( 'manage_options' ); +$GLOBALS['spacefast_test_filters']['spacefast_wordpress_can_promote'] = static fn( bool $allowed ): bool => false; +check( ! Spacefast_Plugin::can_promote(), 'the promotion capability filter can restrict administrators' ); +$denied = false; +try { $action->invoke( null, 'discard', $version_client ); } catch ( RuntimeException $error ) { $denied = true; } +check( $denied, 'handlers enforce the promotion capability filter' ); +unset( $GLOBALS['spacefast_test_filters']['spacefast_wordpress_can_promote'] ); +foreach ( array( 'go_live', 'rollback', 'discard', 'preview' ) as $verb ) { + $_POST = array( 'version_id' => 'ver_staged', '_wpnonce' => 'wrong-action' ); + $before = count( $version_requests ); + $denied = false; + try { $action->invoke( null, $verb, $version_client ); } catch ( RuntimeException $error ) { $denied = 'Invalid nonce' === $error->getMessage(); } + check( $denied && $before === count( $version_requests ), $verb . ' requires its own valid nonce before HTTP' ); +} +$_POST = array( 'version_id' => 'ver_staged', '_wpnonce' => 'spacefast_wordpress_go_live' ); +Spacefast_Settings::merge( array( 'scope' => 'spaces:publish' ) ); +$before = count( $version_requests ); +check( ! $action->invoke( null, 'go_live', $version_client )['ok'] && $before === count( $version_requests ), 'old grants require reconnection before promotion' ); +Spacefast_Settings::merge( array( 'scope' => 'publish:write spaces:write' ) ); +$_POST['version_id'] = 'ver_other'; +check( ! $action->invoke( null, 'go_live', $version_client )['ok'], 'stale go-live forms cannot promote a different staged version' ); +$_POST['version_id'] = '../live'; +check( ! $action->invoke( null, 'go_live', $version_client )['ok'], 'invalid version ids are rejected before transport' ); +$_POST = array( 'version_id' => 'ver_staged', '_wpnonce' => 'spacefast_wordpress_preview' ); +$GLOBALS['spacefast_test_caps'] = array( 'edit_others_posts' ); +$preview = $action->invoke( null, 'preview', $version_client ); +check( $preview['ok'] && str_ends_with( end( $version_requests )[0], '/ver_staged/preview-session' ), 'editors can request a version-specific preview session' ); +check( '{"landingPath":"/"}' === end( $version_requests )[1]['body'], 'preview opens the exported root' ); +$GLOBALS['spacefast_test_caps'] = array( 'manage_options' ); +$_POST['_wpnonce'] = 'spacefast_wordpress_go_live'; +$version_failure = true; +check( ! $action->invoke( null, 'go_live', $version_client )['ok'] && $staged_state === Spacefast_Sync_State::get(), 'failed actions leave the staged and pending state intact' ); +$version_failure = false; +$before = Spacefast_Sync_State::get(); +foreach ( array( 403, 500, 200 ) as $status_code ) { + $failed_promote = new Spacefast_Client( static function ( string $url ) use ( $status_code ): array { + return str_ends_with( $url, '/promote' ) + ? response( $status_code, array( 'id' => 'ver_waiting', 'status' => 'activating', 'isCurrentProduction' => false ) ) + : response( 200, array( 'id' => 'ver_staged', 'status' => 'ready', 'isCurrentProduction' => false ) ); + } ); + check( ! $action->invoke( null, 'go_live', $failed_promote )['ok'] && $before === Spacefast_Sync_State::get(), 'unconfirmed or failed promotions cannot claim success or clear staging' ); +} +$promoted = $action->invoke( null, 'go_live', $version_client ); +check( $promoted['ok'] && str_ends_with( end( $version_requests )[0], '/ver_staged/promote' ), 'go live promotes the staged version' ); +check( '{"channel":"live"}' === end( $version_requests )[1]['body'], 'promotion retains the server default refreshRewrites behavior' ); +check( 'ver_promoted' === Spacefast_Sync_State::get()['last_version_id'], 'promotion records the returned id, which may be a new rollback version' ); +check( '' === Spacefast_Sync_State::get()['staged_version_id'] && 1 === Spacefast_Sync_State::get()['delivered'], 'promotion clears only its staged card and preserves queued edits' ); +Spacefast_Sync_State::save( $staged_state ); +$_POST = array( 'version_id' => 'ver_older', '_wpnonce' => 'spacefast_wordpress_rollback' ); +$rolled_back = $action->invoke( null, 'rollback', $version_client ); +check( $rolled_back['ok'] && str_ends_with( end( $version_requests )[0], '/ver_older/promote' ), 'rollback promotes the selected old id' ); +check( 'ver_staged' === Spacefast_Sync_State::get()['staged_version_id'], 'rollback does not discard a separate staged review' ); + +// Spacefast can require a person to approve a promotion before it runs. +$approval_requests = array(); +$approval_state = 'required'; +$approval_client = new Spacefast_Client( + static function ( string $url, array $args ) use ( &$approval_requests, &$approval_state ): array { + if ( ! str_ends_with( $url, '/promote' ) ) return response( 200, array( 'id' => 'ver_older', 'status' => 'ready', 'isCurrentProduction' => false ) ); + $approval_requests[] = $args['headers']; + if ( ! isset( $args['headers']['X-Spacefast-Continuation-Token'] ) ) { + return array( 'response' => array( 'code' => 409 ), 'body' => json_encode( array( + 'code' => 'confirmation_required', + 'detail' => 'A person must approve this exact action at url before the agent can continue.', + 'details' => array( 'url' => 'https://my.spacefast.test/approvals/gdc_one', 'continuationToken' => 'secret-continuation', 'expiresAt' => gmdate( 'c', time() + 300 ) ), + ) ) ); + } + if ( 'required' === $approval_state ) return array( 'response' => array( 'code' => 409 ), 'body' => json_encode( array( 'code' => 'confirmation_pending', 'detail' => 'Still waiting.' ) ) ); + return response( 200, array( 'id' => 'ver_rollback', 'status' => 'ready', 'isCurrentProduction' => true ) ); + } +); +$finish = new ReflectionMethod( Spacefast_Plugin::class, 'finish_approval_action' ); +$_POST = array( 'version_id' => 'ver_older', '_wpnonce' => 'spacefast_wordpress_rollback' ); +$asked = $action->invoke( null, 'rollback', $approval_client ); +$pending = Spacefast_Plugin::pending_approval(); +check( ! $asked['ok'] && 'approval_required' === $asked['code'] && str_contains( $asked['message'], 'Approve it in Spacefast' ), 'an approval-gated rollback asks for approval in plain words' ); +check( ! str_contains( $asked['message'], 'agent' ) && ! str_contains( $asked['message'], 'secret-continuation' ), 'the approval notice hides the API agent text and the token' ); +check( is_array( $pending ) && 'rollback' === $pending['action'] && 'ver_older' === $pending['version_id'] && 'https://my.spacefast.test/approvals/gdc_one' === $pending['url'], 'the pending approval is remembered with its link' ); +$_POST = array( '_wpnonce' => 'spacefast_wordpress_finish_approval' ); +$early = $finish->invoke( null, $approval_client ); +check( ! $early['ok'] && 'approval_pending' === $early['code'] && null !== Spacefast_Plugin::pending_approval(), 'finishing before approval keeps the request open' ); +$approval_state = 'approved'; +$finished = $finish->invoke( null, $approval_client ); +$last = end( $approval_requests ); +check( $finished['ok'] && 'ver_rollback' === Spacefast_Sync_State::get()['last_version_id'], 'finishing an approved rollback makes it live' ); +check( 'secret-continuation' === $last['X-Spacefast-Continuation-Token'] && $approval_requests[0]['Idempotency-Key'] === $last['Idempotency-Key'], 'the approved request is resent with its token and original idempotency key' ); +check( null === Spacefast_Plugin::pending_approval(), 'a finished approval is cleared' ); +update_option( Spacefast_Plugin::APPROVAL_OPTION, array_merge( $pending, array( 'expires_at' => time() - 1 ) ) ); +check( null === Spacefast_Plugin::pending_approval() && false === get_option( Spacefast_Plugin::APPROVAL_OPTION, false ), 'an expired approval is dropped' ); +$open_client = new Spacefast_Client( + static fn( string $url ): array => str_ends_with( $url, '/promote' ) + ? array( 'response' => array( 'code' => 409 ), 'body' => json_encode( array( 'code' => 'confirmation_token_required', 'detail' => 'Send this request again with the continuation token in the X-Spacefast-Continuation-Token header.', 'details' => array( 'approvalId' => 'gdc_one' ) ) ) ) + : response( 200, array( 'id' => 'ver_older', 'status' => 'ready', 'isCurrentProduction' => false ) ) +); +$_POST = array( 'version_id' => 'ver_older', '_wpnonce' => 'spacefast_wordpress_rollback' ); +$reopened = $action->invoke( null, 'rollback', $open_client ); +check( ! $reopened['ok'] && 'approval_open' === $reopened['code'] && ! str_contains( $reopened['message'], 'X-Spacefast' ), 'a repeat of an action with an open approval explains itself without API header jargon' ); +Spacefast_Sync_State::save( $staged_state ); +$_POST = array( 'version_id' => 'ver_staged', '_wpnonce' => 'spacefast_wordpress_discard' ); +$version_live = true; +$before = count( $version_requests ); +check( ! $action->invoke( null, 'discard', $version_client )['ok'] && $before + 1 === count( $version_requests ), 'discard refuses a version that another publisher made live' ); +$version_live = false; +check( $action->invoke( null, 'discard', $version_client )['ok'], 'discard accepts the API empty 204 response' ); +check( 'DELETE' === end( $version_requests )[1]['method'] && '' === Spacefast_Sync_State::get()['staged_version_id'], 'discard deletes only the staged version and clears its card' ); +$version_client->list_versions( 100 ); +check( str_ends_with( end( $version_requests )[0], '/versions?limit=20' ), 'history is bounded to the most recent 20 versions' ); +$_POST = array(); +// Exercise the actual Simply Static task for both automatic and partial staging. +require_once dirname( __DIR__ ) . '/includes/class-spacefast-simply-static-task.php'; +$GLOBALS['spacefast_simply_archive'] = $archive; +$task_requests = array(); +$task_live = false; +$GLOBALS['spacefast_remote_handler'] = static function ( string $url, array $args ) use ( &$task_requests, &$task_live ): array { + $task_requests[] = array( $url, $args ); + if ( str_ends_with( $url, '/versions' ) ) return response( 201, array( 'versionId' => 'ver_task', 'upload' => null ) ); + return response( 200, array( 'id' => 'ver_task', 'status' => 'ready', 'isCurrentProduction' => $task_live ) ); +}; +foreach ( array( 'export' => 'snapshot', 'update' => 'additive' ) as $generate_type => $expected_mode ) { + $GLOBALS['spacefast_simply_options'] = array( 'generate_type' => $generate_type ); + Spacefast_Static_Publisher::reset(); + Spacefast_Sync_State::save( array_merge( Spacefast_Sync_State::defaults(), array( 'active_review' => true, 'active_source' => 'auto' ) ) ); + Spacefast_Settings::merge( array( 'review_before_live' => false ) ); + if ( 'export' === $generate_type ) update_option( 'spacefast_wordpress_snapshot_required', true ); + else delete_option( 'spacefast_wordpress_snapshot_required' ); + $task_requests = array(); + $task = new Spacefast_Simply_Static_Publish_Task(); + check( false === $task->perform() && true === $task->perform(), 'the delivery task completes staged ' . $generate_type . ' exports' ); + $body = json_decode( $task_requests[0][1]['body'], true ); + check( null === $body['finalize']['channel'] && $expected_mode === $body['publishMode'], 'delivery carries the pinned review flag and mode for ' . $generate_type ); + check( 'ver_task' === Spacefast_Sync_State::get()['staged_version_id'], 'the delivery task records the staged version' ); + if ( 'export' === $generate_type ) { + check( true === get_option( 'spacefast_wordpress_snapshot_required' ), 'a staged snapshot preserves the deletion guard until it goes live' ); + $_POST = array( 'version_id' => 'ver_task', '_wpnonce' => 'spacefast_wordpress_go_live' ); + check( $action->invoke( null, 'go_live', $version_client )['ok'], 'a complete staged snapshot can be promoted' ); + check( false === get_option( 'spacefast_wordpress_snapshot_required', false ), 'promoting the full snapshot releases the deletion guard' ); + $_POST = array(); + } +} +$task_live = true; +$task_requests = array(); +$GLOBALS['spacefast_simply_options'] = array( 'generate_type' => 'export' ); +Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); +check( false === $task->perform() && true === $task->perform(), 'the delivery task still publishes live with the toggle off' ); +check( $task_requests[0][1]['body'] === $static_requests[0][1]['body'], 'toggle-off delivery keeps the legacy request body byte for byte' ); + +// Render the same version cards exercised by WordPress acceptance, with an injected transport. +Spacefast_Sync_State::save( $staged_state ); +Spacefast_Settings::merge( array( 'review_before_live' => true ) ); +$GLOBALS['spacefast_remote_handler'] = static fn(): array => response( 200, array( + array( 'id' => 'ver_staged', 'status' => 'ready', 'fileCount' => 5, 'filesAddedCount' => 1, 'filesChangedCount' => 2, 'filesRemovedCount' => 3 ), + array( 'id' => 'ver_live', 'status' => 'ready', 'fileCount' => 4, 'isCurrentProduction' => true ), + array( 'id' => 'ver_old', 'status' => 'ready', 'fileCount' => 3 ), +) ); +$render_versions = new ReflectionMethod( Spacefast_Plugin::class, 'render_versions' ); +ob_start(); +$render_versions->invoke( null ); +$markup = (string) ob_get_clean(); +foreach ( array( 'Staged version', '1 files added, 2 changed, 3 removed.', 'Open preview', 'Copy preview link', 'Go live', 'Discard', 'Versions', 'Auto', 'Live', 'Make live' ) as $label ) { + check( str_contains( $markup, $label ), 'the version cards render ' . $label ); +} +check( str_contains( $markup, 'value="ver_old"' ) && str_contains( $markup, 'spacefast_wordpress_rollback' ), 'history forms name the selected version and action nonce' ); +$GLOBALS['spacefast_test_caps'] = array( 'edit_others_posts' ); +ob_start(); +$render_versions->invoke( null ); +$editor_markup = (string) ob_get_clean(); +check( str_contains( $editor_markup, 'Open preview' ) && ! str_contains( $editor_markup, '>Go live<' ) && ! str_contains( $editor_markup, '>Make live<' ), 'editor review cards omit promotion controls' ); +$GLOBALS['spacefast_test_caps'] = array( 'manage_options' ); +$GLOBALS['spacefast_remote_handler'] = null; Spacefast_Settings::merge( $connection ); unlink( $archive . '/assets/app.js' ); diff --git a/uninstall.php b/uninstall.php index 751f686..b992285 100644 --- a/uninstall.php +++ b/uninstall.php @@ -11,4 +11,5 @@ delete_option( 'spacefast_wordpress_oauth_choices' ); delete_option( 'spacefast_wordpress_space_creation' ); delete_option( 'spacefast_wordpress_snapshot_required' ); +delete_option( 'spacefast_wordpress_pending_approval' ); delete_transient( 'spacefast_wordpress_admin_notice' );