PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.9.16
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.9.16
1.10.19 1.10.18 1.10.17 1.10.16 1.10.15 1.10.13 1.10.14 1.10.12 1.10.11 1.10.10 1.10.9 1.10.8 untagged-3d9b7ccddc54df87c672 1.10.7 1.10.6 1.10.5 1.10.3 1.10.4 1.10.2 1.10.1 1.10.0 1.9.17 1.9.15 1.9.16 1.9.14 All 163 releases
woocommerce-pos / includes / Services / Cloud_Print_Relay_Service.php

Cloud_Print_Relay_Service.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.9.16, at includes/Services/Cloud_Print_Relay_Service.php

445 lines 14.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WCPOS Cloud Print relay integration.
4 *
5 * @package WCPOS\WooCommercePOS\Services
6 */
7
8 namespace WCPOS\WooCommercePOS\Services;
9
10 use WP_Error;
11
12 /**
13 * Talks to the WCPOS Cloud Print relay: registration/consent, job-pending
14 * hints, and printer status queries. All relay knowledge lives here; the
15 * REST controller only wraps these methods in responses.
16 */
17 class Cloud_Print_Relay_Service {
18 const RELAY_URL = 'https://cloudprint.wcpos.com';
19
20 /**
21 * Server-owned relay state {enabled, site_key, hint_secret, registered_at}.
22 * Deliberately a separate option from the client-writable cloud-print
23 * settings so no settings write path can clobber or leak it.
24 */
25 const OPTION = 'woocommerce_pos_cloud_print_relay';
26
27 const VERIFY_TRANSIENT = 'wcpos_relay_verify_token';
28 const STATUS_CACHE_TTL = 30;
29 const STATUS_TRANSIENT_PREFIX = 'wcpos_relay_status_';
30
31 /**
32 * Site-wide "relay unreachable" marker: one failed status call stops
33 * further calls for the cache window, so a hanging relay costs one
34 * timeout per window instead of one per printer per admin tab.
35 */
36 const DOWN_TRANSIENT = 'wcpos_relay_down';
37
38 const REREGISTER_GUARD = 3600;
39 const REREGISTER_TRANSIENT = 'wcpos_relay_reregister_guard';
40 const REREGISTER_HOOK = 'wcpos_relay_reregister';
41
42 /**
43 * Register relay event handlers.
44 */
45 public function __construct() {
46 add_action( 'woocommerce_pos_print_job_created', array( $this, 'send_hint' ), 10, 2 );
47 add_action( self::REREGISTER_HOOK, array( $this, 'reregister' ) );
48 }
49
50 /**
51 * Return the pending verification token, if a registration is in flight.
52 *
53 * @return string|null
54 */
55 public static function pending_verification_token(): ?string {
56 $token = get_transient( self::VERIFY_TRANSIENT );
57 if ( false === $token ) {
58 return null;
59 }
60 // Single-use: consumed on first read, so a second reader (or a racing
61 // registration attempt for this site) cannot replay the proof.
62 delete_transient( self::VERIFY_TRANSIENT );
63
64 return (string) $token;
65 }
66
67 /**
68 * Register this site with the relay and persist its credentials.
69 *
70 * The relay fetches the verification token from this site while the
71 * outbound request below is still open, proving consent and that WCPOS
72 * is actually installed at the claimed URL.
73 *
74 * @param bool $admin_initiated True for an explicit admin action; false for
75 * background re-registration, which must never
76 * flip a relay the admin has since disabled.
77 *
78 * @return array|WP_Error Public relay fields or an error.
79 */
80 public static function register_site( bool $admin_initiated = true ) {
81 if ( ! self::is_enabled() ) {
82 return new WP_Error(
83 'wcpos_relay_disabled',
84 __( 'WCPOS Cloud Print is disabled on this site.', 'woocommerce-pos' ),
85 array( 'status' => 403 )
86 );
87 }
88 try {
89 $token = bin2hex( random_bytes( 24 ) );
90 } catch ( \Exception $exception ) {
91 return self::registration_error( __( 'Could not create a relay verification token.', 'woocommerce-pos' ) );
92 }
93 set_transient( self::VERIFY_TRANSIENT, $token, 5 * MINUTE_IN_SECONDS );
94 $response = wp_remote_post(
95 self::relay_url() . '/api/register',
96 array(
97 'timeout' => 15,
98 'headers' => array( 'Content-Type' => 'application/json' ),
99 'body' => wp_json_encode(
100 array(
101 'site_url' => home_url(),
102 'verify_token' => $token,
103 )
104 ),
105 )
106 );
107 delete_transient( self::VERIFY_TRANSIENT );
108
109 if ( is_wp_error( $response ) ) {
110 return self::registration_error( $response->get_error_message() );
111 }
112
113 $data = json_decode( wp_remote_retrieve_body( $response ), true );
114 if ( 201 !== wp_remote_retrieve_response_code( $response ) ) {
115 $message = \is_array( $data ) ? (string) ( $data['message'] ?? $data['error'] ?? '' ) : '';
116
117 return self::registration_error( '' !== $message ? sanitize_text_field( $message ) : __( 'Relay registration failed.', 'woocommerce-pos' ) );
118 }
119
120 $data = \is_array( $data ) ? $data : array();
121 $site_key = sanitize_text_field( (string) ( $data['site_key'] ?? '' ) );
122 $hint_secret = sanitize_text_field( (string) ( $data['hint_secret'] ?? '' ) );
123 if ( 1 !== preg_match( '/^[a-f0-9]{32}$/i', $site_key ) || 1 !== preg_match( '/^[a-f0-9]{64}$/i', $hint_secret ) ) {
124 return self::registration_error( __( 'Relay registration returned invalid credentials.', 'woocommerce-pos' ) );
125 }
126
127 // Re-read at completion time: a background re-registration must adopt
128 // the admin's latest enabled/disabled intent, not the state at launch.
129 $current = self::settings();
130 update_option(
131 self::OPTION,
132 array(
133 'enabled' => $admin_initiated ? true : ! empty( $current['enabled'] ),
134 'site_key' => strtolower( $site_key ),
135 'hint_secret' => strtolower( $hint_secret ),
136 'registered_at' => time(),
137 )
138 );
139 delete_transient( self::DOWN_TRANSIENT );
140
141 // The printer URL is always rebuilt from the validated site_key —
142 // never from the relay response — so a compromised relay cannot
143 // point printers (and their tokens) at another host.
144 return array(
145 'enabled' => true,
146 'printer_base_url' => self::printer_base_url( strtolower( $site_key ) ),
147 );
148 }
149
150 /**
151 * Disable relay use while retaining the deterministic site credentials.
152 *
153 * @deprecated The stored flag is no longer consulted; opt out with the
154 * `woocommerce_pos_cloud_print_relay_enabled` filter.
155 *
156 * @return array Public relay state.
157 */
158 public static function disable(): array {
159 $stored = self::settings();
160 $stored['enabled'] = false;
161 update_option( self::OPTION, $stored );
162
163 return array( 'enabled' => false );
164 }
165
166 /**
167 * Whether the relay service may be used at all.
168 *
169 * The relay is on by default — there is no admin toggle. Sites that
170 * really want to opt out do so in code:
171 *
172 * add_filter( 'woocommerce_pos_cloud_print_relay_enabled', '__return_false' );
173 */
174 public static function is_enabled(): bool {
175 return (bool) apply_filters( 'woocommerce_pos_cloud_print_relay_enabled', true );
176 }
177
178 /**
179 * Public relay state for REST responses: never includes the secret.
180 *
181 * `enabled` means registered and usable; `available` tells the settings
182 * app whether it should self-register (false only when the opt-out
183 * filter is in place). The stored `enabled` flag is deliberately not
184 * consulted — the filter is the only off switch.
185 *
186 * @return array
187 */
188 public static function public_state(): array {
189 if ( ! self::is_enabled() ) {
190 return array(
191 'enabled' => false,
192 'available' => false,
193 );
194 }
195
196 $relay = self::settings();
197 $state = array(
198 'enabled' => false,
199 'available' => true,
200 );
201 if ( 1 === preg_match( '/^[a-f0-9]{32}$/', (string) ( $relay['site_key'] ?? '' ) ) ) {
202 $state['enabled'] = true;
203 $state['printer_base_url'] = self::printer_base_url( (string) $relay['site_key'] );
204 }
205
206 return $state;
207 }
208
209 /**
210 * Send a best-effort hint when a polling printer gets a job.
211 *
212 * @param int $job_id Print job ID.
213 * @param string $printer_id Printer ID.
214 */
215 public function send_hint( $job_id, $printer_id ): void {
216 $relay = self::settings();
217 if ( ! self::is_enabled() || ! self::valid_credentials( $relay ) ) {
218 return;
219 }
220
221 $printer = ( new Cloud_Print_Registry() )->get_printer( sanitize_text_field( (string) $printer_id ) );
222 if ( null === $printer || ! Provider::is_polling( (string) ( $printer['provider'] ?? '' ) ) ) {
223 return;
224 }
225
226 $site_key = (string) $relay['site_key'];
227 $path = '/api/hint/' . $site_key;
228 $timestamp = (string) time();
229 $body = wp_json_encode( array( 'printer_id' => (string) $printer_id ) );
230
231 // Best-effort by design: a lost hint costs at most one heartbeat
232 // interval of print latency, so failures are deliberately silent.
233 wp_remote_post(
234 self::relay_url() . $path,
235 array(
236 'blocking' => false,
237 'timeout' => 2,
238 'headers' => self::signed_headers( 'POST', $path, $timestamp, $body, (string) $relay['hint_secret'] ),
239 'body' => $body,
240 )
241 );
242 }
243
244 /**
245 * Query the cached relay status for a printer.
246 *
247 * @param string $printer_id Printer ID.
248 *
249 * @return array|null Relay status or null on failure/when disabled.
250 */
251 public static function status( string $printer_id ): ?array {
252 $relay = self::settings();
253 if ( ! self::is_enabled() || ! self::valid_credentials( $relay ) ) {
254 return null;
255 }
256
257 $key = self::STATUS_TRANSIENT_PREFIX . $printer_id;
258 $cached = get_transient( $key );
259 if ( false !== $cached ) {
260 return ! empty( $cached['failed'] ) ? null : $cached;
261 }
262 if ( false !== get_transient( self::DOWN_TRANSIENT ) ) {
263 return null;
264 }
265
266 $site_key = (string) $relay['site_key'];
267 $path = '/api/status/' . $site_key;
268 $timestamp = (string) time();
269 $response = wp_remote_get(
270 self::relay_url() . $path . '?printer_id=' . rawurlencode( $printer_id ),
271 array(
272 'timeout' => 3,
273 'headers' => self::signed_headers( 'GET', $path, $timestamp, $printer_id, (string) $relay['hint_secret'] ),
274 )
275 );
276
277 if ( is_wp_error( $response ) ) {
278 self::note_status_failure( $key );
279
280 return null;
281 }
282
283 $code = wp_remote_retrieve_response_code( $response );
284 $data = json_decode( wp_remote_retrieve_body( $response ), true );
285 // Exact match on the relay's machine-readable error field; the
286 // registry was rebuilt, so a guarded re-registration restores the
287 // same deterministic site key.
288 if ( 404 === $code && \is_array( $data ) && 'unknown site' === ( $data['error'] ?? '' ) ) {
289 self::schedule_reregistration();
290 }
291 if ( 200 !== $code || ! \is_array( $data ) ) {
292 self::note_status_failure( $key );
293
294 return null;
295 }
296
297 $status = array(
298 'origin_status' => sanitize_text_field( (string) ( $data['origin_status'] ?? '' ) ),
299 'origin_block_signal' => sanitize_text_field( (string) ( $data['origin_block_signal'] ?? '' ) ),
300 'last_seen_seconds_ago' => isset( $data['last_seen_seconds_ago'] ) ? max( 0, (int) $data['last_seen_seconds_ago'] ) : null,
301 );
302 set_transient( $key, $status, self::STATUS_CACHE_TTL );
303
304 return $status;
305 }
306
307 /**
308 * The relay's block signal for a printer, when it reports one.
309 *
310 * Reads the same transient cache as status(), so calling both costs one
311 * relay round-trip at most.
312 *
313 * @param string $printer_id Printer ID.
314 *
315 * @return string|null
316 */
317 public static function status_detail( string $printer_id ): ?string {
318 $status = self::status( $printer_id );
319 if ( null !== $status && 'blocked' === $status['origin_status'] && '' !== $status['origin_block_signal'] ) {
320 return $status['origin_block_signal'];
321 }
322
323 return null;
324 }
325
326 /**
327 * Build a relay-compatible HMAC signature.
328 *
329 * @param string $method HTTP method.
330 * @param string $path Request path without query string.
331 * @param string $timestamp Unix timestamp.
332 * @param string $payload Signed payload.
333 * @param string $secret Hex-encoded signing secret.
334 *
335 * @return string Lowercase hexadecimal signature.
336 */
337 public static function sign( string $method, string $path, string $timestamp, string $payload, string $secret ): string {
338 $key = hex2bin( $secret );
339
340 return false === $key ? '' : hash_hmac( 'sha256', $method . "\n" . $path . "\n" . $timestamp . "\n" . $payload, $key );
341 }
342
343 /**
344 * Build the public printer URL for a registered site.
345 *
346 * @param string $site_key Relay site key.
347 */
348 public static function printer_base_url( string $site_key ): string {
349 return self::relay_url() . '/p/' . rawurlencode( $site_key );
350 }
351
352 /**
353 * Re-register after the relay reports an unknown site.
354 *
355 * Bails only when the code-level opt-out filter is in place — a pending
356 * cron event must never register a site that opted out.
357 */
358 public function reregister(): void {
359 if ( ! self::is_enabled() ) {
360 return;
361 }
362 self::register_site( false );
363 }
364
365 /**
366 * Return stored relay settings.
367 *
368 * @return array
369 */
370 private static function settings(): array {
371 $stored = get_option( self::OPTION, array() );
372
373 return \is_array( $stored ) ? $stored : array();
374 }
375
376 /**
377 * Check stored relay credentials before using them for signing.
378 *
379 * @param array $relay Relay settings.
380 */
381 private static function valid_credentials( array $relay ): bool {
382 return 1 === preg_match( '/^[a-f0-9]{32}$/i', (string) ( $relay['site_key'] ?? '' ) )
383 && 1 === preg_match( '/^[a-f0-9]{64}$/i', (string) ( $relay['hint_secret'] ?? '' ) );
384 }
385
386 /**
387 * Build signed relay request headers.
388 *
389 * @param string $method HTTP method.
390 * @param string $path Request path.
391 * @param string $timestamp Unix timestamp.
392 * @param string $payload Signed payload.
393 * @param string $secret Hex-encoded signing secret.
394 *
395 * @return array
396 */
397 private static function signed_headers( string $method, string $path, string $timestamp, string $payload, string $secret ): array {
398 return array(
399 'X-Relay-Timestamp' => $timestamp,
400 'X-Relay-Signature' => self::sign( $method, $path, $timestamp, $payload, $secret ),
401 'Content-Type' => 'application/json',
402 );
403 }
404
405 /**
406 * Record a failed status call: per-printer negative cache plus the
407 * site-wide down marker so other printers skip their calls entirely.
408 *
409 * @param string $transient_key Per-printer status transient key.
410 */
411 private static function note_status_failure( string $transient_key ): void {
412 set_transient( $transient_key, array( 'failed' => true ), self::STATUS_CACHE_TTL );
413 set_transient( self::DOWN_TRANSIENT, true, self::STATUS_CACHE_TTL );
414 }
415
416 /**
417 * Schedule one guarded background re-registration.
418 */
419 private static function schedule_reregistration(): void {
420 if ( false !== get_transient( self::REREGISTER_TRANSIENT ) ) {
421 return;
422 }
423 set_transient( self::REREGISTER_TRANSIENT, true, self::REREGISTER_GUARD );
424 wp_schedule_single_event( time(), self::REREGISTER_HOOK );
425 }
426
427 /**
428 * Build a consistent registration error.
429 *
430 * @param string $message Error message.
431 *
432 * @return WP_Error
433 */
434 private static function registration_error( string $message ): WP_Error {
435 return new WP_Error( 'wcpos_relay_registration_failed', $message, array( 'status' => 502 ) );
436 }
437
438 /**
439 * Return the filterable relay base URL.
440 */
441 private static function relay_url(): string {
442 return untrailingslashit( esc_url_raw( (string) apply_filters( 'woocommerce_pos_cloud_print_relay_url', self::RELAY_URL ) ) );
443 }
444 }
445