PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.17
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.17
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.10.17, at includes/Services/Cloud_Print_Relay_Service.php

491 lines 16.7 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 // status() consults the per-printer negative cache before DOWN_TRANSIENT,
141 // so clearing the site-wide marker alone is not enough: a printer that hit
142 // an "unknown site" 404 backed off for REREGISTER_GUARD, and without this
143 // it would keep returning null for the full hour even though the site_key
144 // is valid again. Dropping those entries lets status resume on the next call.
145 self::clear_status_cache();
146
147 // The printer URL is always rebuilt from the validated site_key —
148 // never from the relay response — so a compromised relay cannot
149 // point printers (and their tokens) at another host.
150 return array(
151 'enabled' => true,
152 'printer_base_url' => self::printer_base_url( strtolower( $site_key ) ),
153 );
154 }
155
156 /**
157 * Disable relay use while retaining the deterministic site credentials.
158 *
159 * @deprecated The stored flag is no longer consulted; opt out with the
160 * `woocommerce_pos_cloud_print_relay_enabled` filter.
161 *
162 * @return array Public relay state.
163 */
164 public static function disable(): array {
165 $stored = self::settings();
166 $stored['enabled'] = false;
167 update_option( self::OPTION, $stored );
168
169 return array( 'enabled' => false );
170 }
171
172 /**
173 * Whether the relay service may be used at all.
174 *
175 * The relay is on by default — there is no admin toggle. Sites that
176 * really want to opt out do so in code:
177 *
178 * add_filter( 'woocommerce_pos_cloud_print_relay_enabled', '__return_false' );
179 */
180 public static function is_enabled(): bool {
181 return (bool) apply_filters( 'woocommerce_pos_cloud_print_relay_enabled', true );
182 }
183
184 /**
185 * Public relay state for REST responses: never includes the secret.
186 *
187 * `enabled` means registered and usable; `available` tells the settings
188 * app whether it should self-register (false only when the opt-out
189 * filter is in place). The stored `enabled` flag is deliberately not
190 * consulted — the filter is the only off switch.
191 *
192 * @return array
193 */
194 public static function public_state(): array {
195 if ( ! self::is_enabled() ) {
196 return array(
197 'enabled' => false,
198 'available' => false,
199 );
200 }
201
202 $relay = self::settings();
203 $state = array(
204 'enabled' => false,
205 'available' => true,
206 );
207 // Case-insensitive to match valid_credentials(): registration lowercases
208 // on write, but a legacy uppercase key still signs hints and status
209 // calls fine, so it must not report itself disabled to the settings app.
210 if ( 1 === preg_match( '/^[a-f0-9]{32}$/i', (string) ( $relay['site_key'] ?? '' ) ) ) {
211 $state['enabled'] = true;
212 $state['printer_base_url'] = self::printer_base_url( (string) $relay['site_key'] );
213 }
214
215 return $state;
216 }
217
218 /**
219 * Send a best-effort hint when a polling printer gets a job.
220 *
221 * @param int $job_id Print job ID.
222 * @param string $printer_id Printer ID.
223 */
224 public function send_hint( $job_id, $printer_id ): void {
225 $relay = self::settings();
226 if ( ! self::is_enabled() || ! self::valid_credentials( $relay ) ) {
227 return;
228 }
229
230 $printer = ( new Cloud_Print_Registry() )->get_printer( sanitize_text_field( (string) $printer_id ) );
231 if ( null === $printer || ! Provider::is_polling( (string) ( $printer['provider'] ?? '' ) ) ) {
232 return;
233 }
234
235 $site_key = (string) $relay['site_key'];
236 $path = '/api/hint/' . $site_key;
237 $timestamp = (string) time();
238 $body = wp_json_encode( array( 'printer_id' => (string) $printer_id ) );
239
240 // Best-effort by design: a lost hint costs at most one heartbeat
241 // interval of print latency, so failures are deliberately silent.
242 wp_remote_post(
243 self::relay_url() . $path,
244 array(
245 'blocking' => false,
246 'timeout' => 2,
247 'headers' => self::signed_headers( 'POST', $path, $timestamp, $body, (string) $relay['hint_secret'] ),
248 'body' => $body,
249 )
250 );
251 }
252
253 /**
254 * Query the cached relay status for a printer.
255 *
256 * @param string $printer_id Printer ID.
257 *
258 * @return array|null Relay status or null on failure/when disabled.
259 */
260 public static function status( string $printer_id ): ?array {
261 $relay = self::settings();
262 if ( ! self::is_enabled() || ! self::valid_credentials( $relay ) ) {
263 return null;
264 }
265
266 $key = self::STATUS_TRANSIENT_PREFIX . $printer_id;
267 $cached = get_transient( $key );
268 if ( false !== $cached ) {
269 return ! empty( $cached['failed'] ) ? null : $cached;
270 }
271 if ( false !== get_transient( self::DOWN_TRANSIENT ) ) {
272 return null;
273 }
274
275 $site_key = (string) $relay['site_key'];
276 $path = '/api/status/' . $site_key;
277 $timestamp = (string) time();
278 $response = wp_remote_get(
279 self::relay_url() . $path . '?printer_id=' . rawurlencode( $printer_id ),
280 array(
281 'timeout' => 3,
282 'headers' => self::signed_headers( 'GET', $path, $timestamp, $printer_id, (string) $relay['hint_secret'] ),
283 )
284 );
285
286 if ( is_wp_error( $response ) ) {
287 self::note_status_failure( $key );
288
289 return null;
290 }
291
292 $code = wp_remote_retrieve_response_code( $response );
293 $data = json_decode( wp_remote_retrieve_body( $response ), true );
294 // Exact match on the relay's machine-readable error field; the
295 // registry was rebuilt, so a guarded re-registration restores the
296 // same deterministic site key.
297 if ( 404 === $code && \is_array( $data ) && 'unknown site' === ( $data['error'] ?? '' ) ) {
298 self::schedule_reregistration();
299
300 // Back off for the re-registration window, not the cache window.
301 // This 404 is not a transient relay hiccup: the stored site_key is
302 // not in the relay's registry, and nothing about that changes until
303 // a re-registration succeeds — which is itself rate-limited to once
304 // per REREGISTER_GUARD. Falling through to the 30s failure window
305 // would replay the identical 404 twice a minute forever whenever a
306 // site cannot re-register (the relay cannot reach its verification
307 // endpoint, say), which is exactly what one site was doing: ~2,000
308 // pointless requests a day. A successful registration deletes
309 // DOWN_TRANSIENT, so this self-heals the moment re-registration
310 // works rather than pinning the site down for the full hour.
311 self::note_status_failure( $key, self::REREGISTER_GUARD );
312
313 return null;
314 }
315 if ( 200 !== $code || ! \is_array( $data ) ) {
316 self::note_status_failure( $key );
317
318 return null;
319 }
320
321 $status = array(
322 'origin_status' => sanitize_text_field( (string) ( $data['origin_status'] ?? '' ) ),
323 'origin_block_signal' => sanitize_text_field( (string) ( $data['origin_block_signal'] ?? '' ) ),
324 'last_seen_seconds_ago' => isset( $data['last_seen_seconds_ago'] ) ? max( 0, (int) $data['last_seen_seconds_ago'] ) : null,
325 );
326 set_transient( $key, $status, self::STATUS_CACHE_TTL );
327
328 return $status;
329 }
330
331 /**
332 * The relay's block signal for a printer, when it reports one.
333 *
334 * Reads the same transient cache as status(), so calling both costs one
335 * relay round-trip at most.
336 *
337 * @param string $printer_id Printer ID.
338 *
339 * @return string|null
340 */
341 public static function status_detail( string $printer_id ): ?string {
342 $status = self::status( $printer_id );
343 if ( null !== $status && 'blocked' === $status['origin_status'] && '' !== $status['origin_block_signal'] ) {
344 return $status['origin_block_signal'];
345 }
346
347 return null;
348 }
349
350 /**
351 * Build a relay-compatible HMAC signature.
352 *
353 * @param string $method HTTP method.
354 * @param string $path Request path without query string.
355 * @param string $timestamp Unix timestamp.
356 * @param string $payload Signed payload.
357 * @param string $secret Hex-encoded signing secret.
358 *
359 * @return string Lowercase hexadecimal signature.
360 */
361 public static function sign( string $method, string $path, string $timestamp, string $payload, string $secret ): string {
362 $key = hex2bin( $secret );
363
364 return false === $key ? '' : hash_hmac( 'sha256', $method . "\n" . $path . "\n" . $timestamp . "\n" . $payload, $key );
365 }
366
367 /**
368 * Build the public printer URL for a registered site.
369 *
370 * @param string $site_key Relay site key.
371 */
372 public static function printer_base_url( string $site_key ): string {
373 return self::relay_url() . '/p/' . rawurlencode( $site_key );
374 }
375
376 /**
377 * Re-register after the relay reports an unknown site.
378 *
379 * Bails only when the code-level opt-out filter is in place — a pending
380 * cron event must never register a site that opted out.
381 */
382 public function reregister(): void {
383 if ( ! self::is_enabled() ) {
384 return;
385 }
386 self::register_site( false );
387 }
388
389 /**
390 * Return stored relay settings.
391 *
392 * @return array
393 */
394 private static function settings(): array {
395 $stored = get_option( self::OPTION, array() );
396
397 return \is_array( $stored ) ? $stored : array();
398 }
399
400 /**
401 * Check stored relay credentials before using them for signing.
402 *
403 * @param array $relay Relay settings.
404 */
405 private static function valid_credentials( array $relay ): bool {
406 return 1 === preg_match( '/^[a-f0-9]{32}$/i', (string) ( $relay['site_key'] ?? '' ) )
407 && 1 === preg_match( '/^[a-f0-9]{64}$/i', (string) ( $relay['hint_secret'] ?? '' ) );
408 }
409
410 /**
411 * Build signed relay request headers.
412 *
413 * @param string $method HTTP method.
414 * @param string $path Request path.
415 * @param string $timestamp Unix timestamp.
416 * @param string $payload Signed payload.
417 * @param string $secret Hex-encoded signing secret.
418 *
419 * @return array
420 */
421 private static function signed_headers( string $method, string $path, string $timestamp, string $payload, string $secret ): array {
422 return array(
423 'X-Relay-Timestamp' => $timestamp,
424 'X-Relay-Signature' => self::sign( $method, $path, $timestamp, $payload, $secret ),
425 'Content-Type' => 'application/json',
426 );
427 }
428
429 /**
430 * Record a failed status call: per-printer negative cache plus the
431 * site-wide down marker so other printers skip their calls entirely.
432 *
433 * @param string $transient_key Per-printer status transient key.
434 * @param int|null $ttl Backoff seconds; defaults to STATUS_CACHE_TTL.
435 * Callers pass a longer window when the
436 * failure cannot clear on its own within it.
437 */
438 private static function note_status_failure( string $transient_key, ?int $ttl = null ): void {
439 $ttl = null === $ttl ? self::STATUS_CACHE_TTL : max( 1, $ttl );
440 set_transient( $transient_key, array( 'failed' => true ), $ttl );
441 set_transient( self::DOWN_TRANSIENT, true, $ttl );
442 }
443
444 /**
445 * Drop every per-printer status cache.
446 *
447 * Because status() checks the per-printer negative cache before DOWN_TRANSIENT,
448 * a successful (re-)registration must clear these entries too — otherwise a
449 * printer that backed off on an "unknown site" 404 keeps returning null for
450 * the full REREGISTER_GUARD window despite the site_key being valid again.
451 * Dropping any live positive caches is harmless: the next call re-polls.
452 */
453 private static function clear_status_cache(): void {
454 foreach ( ( new Cloud_Print_Registry() )->get_printers() as $printer ) {
455 $printer_id = (string) ( $printer['id'] ?? '' );
456 if ( '' !== $printer_id ) {
457 delete_transient( self::STATUS_TRANSIENT_PREFIX . $printer_id );
458 }
459 }
460 }
461
462 /**
463 * Schedule one guarded background re-registration.
464 */
465 private static function schedule_reregistration(): void {
466 if ( false !== get_transient( self::REREGISTER_TRANSIENT ) ) {
467 return;
468 }
469 set_transient( self::REREGISTER_TRANSIENT, true, self::REREGISTER_GUARD );
470 wp_schedule_single_event( time(), self::REREGISTER_HOOK );
471 }
472
473 /**
474 * Build a consistent registration error.
475 *
476 * @param string $message Error message.
477 *
478 * @return WP_Error
479 */
480 private static function registration_error( string $message ): WP_Error {
481 return new WP_Error( 'wcpos_relay_registration_failed', $message, array( 'status' => 502 ) );
482 }
483
484 /**
485 * Return the filterable relay base URL.
486 */
487 private static function relay_url(): string {
488 return untrailingslashit( esc_url_raw( (string) apply_filters( 'woocommerce_pos_cloud_print_relay_url', self::RELAY_URL ) ) );
489 }
490 }
491