-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRestApi.php
More file actions
876 lines (787 loc) · 25.4 KB
/
Copy pathRestApi.php
File metadata and controls
876 lines (787 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
<?php
/**
* REST endpoints for the WorkOS-verified email-change flow.
*
* @package WorkOS\Auth\ChangeEmail
*/
namespace WorkOS\Auth\ChangeEmail;
use WorkOS\ActivityLog\EventLogger;
use WorkOS\RateLimit\TieredRateLimiter;
use WorkOS\Email\AddressMask;
use WorkOS\Http\ClientIp;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_User;
defined( 'ABSPATH' ) || exit;
/**
* Three endpoints, all under `/wp-json/workos/v1/`:
*
* - `POST users/{id}/email-change` → initiate
* - `POST users/{id}/email-change/confirm` → confirm (consumes token)
* - `POST users/{id}/email-change/cancel` → cancel (consumes cancel token OR uses edit_user)
*
* Auth model mirrors PasswordResetAdmin: `edit_user` on the target,
* which the WP cap mapper grants both for self (the user's own ID) and
* for admins acting on another account.
*
* Initiate is rate-limited on separate per-IP and per-user buckets so a
* flood from one IP can't block legitimate users, using the shared send
* policy: it mails two addresses, so it counts as a send path.
*
* Verification is plugin-side: we generate a hashed token, email the
* plaintext to the new address, then the confirm endpoint:
*
* 1. Re-runs the conflict resolver (a collision can appear between
* initiate and confirm — race guard).
* 2. Sets a transient {@see TRANSIENT_PREFIX} to short-circuit the
* UserSync webhook handler while we're committing.
* 3. Calls `workos()->api()->update_user()` to push the change.
* 4. Mirrors into WordPress with `wp_update_user()`.
* 5. Clears the transient and the pending meta.
*
* The transient TTL is 60 seconds — long enough to outlast the WorkOS
* round-trip + the webhook's typical fan-in window, short enough that
* an orphaned transient can't wedge sync indefinitely.
*/
class RestApi {
public const NAMESPACE = 'workos/v1';
public const TRANSIENT_PREFIX = '_workos_email_change_in_progress_';
public const TRANSIENT_TTL = 60;
/**
* Rate limiter.
*
* @var TieredRateLimiter
*/
private TieredRateLimiter $rate_limiter;
/**
* Client IP resolver.
*
* @var ClientIp
*/
private ClientIp $client_ip;
/**
* Token factory.
*
* @var TokenFactory
*/
private TokenFactory $tokens;
/**
* Pending-change storage.
*
* @var PendingChange
*/
private PendingChange $pending;
/**
* Conflict resolver.
*
* @var ConflictResolver
*/
private ConflictResolver $conflicts;
/**
* Notifier.
*
* @var Notifier
*/
private Notifier $notifier;
/**
* Email-address masker.
*
* @var AddressMask
*/
private AddressMask $masker;
/**
* Constructor.
*
* Redirect-URL validation is done inline in {@see validate_redirect()}
* rather than via the PasswordResetAdmin `RedirectValidator` because
* that helper requires a `Profile` (which doesn't apply to the
* change-email flow). The same same-host policy is enforced.
*
* @param TieredRateLimiter $rate_limiter Rate limiter.
* @param ClientIp $client_ip Client IP resolver.
* @param TokenFactory $tokens Token factory.
* @param PendingChange $pending Pending-change storage.
* @param ConflictResolver $conflicts Conflict resolver.
* @param Notifier $notifier Email notifier.
* @param AddressMask $masker Email-address masker.
*/
public function __construct(
TieredRateLimiter $rate_limiter,
ClientIp $client_ip,
TokenFactory $tokens,
PendingChange $pending,
ConflictResolver $conflicts,
Notifier $notifier,
AddressMask $masker
) {
$this->rate_limiter = $rate_limiter;
$this->client_ip = $client_ip;
$this->tokens = $tokens;
$this->pending = $pending;
$this->conflicts = $conflicts;
$this->notifier = $notifier;
$this->masker = $masker;
}
/**
* Register hooks.
*
* @return void
*/
public function register(): void {
add_action( 'rest_api_init', [ $this, 'register_routes' ] );
}
/**
* Register REST routes.
*
* @return void
*/
public function register_routes(): void {
register_rest_route(
self::NAMESPACE,
'/users/(?P<id>\d+)/email-change',
[
'methods' => 'POST',
'callback' => [ $this, 'initiate' ],
'permission_callback' => [ $this, 'check_permission_initiate' ],
'args' => [
'id' => [ 'sanitize_callback' => 'absint' ],
'new_email' => [ 'sanitize_callback' => 'sanitize_email' ],
'redirect_url' => [ 'sanitize_callback' => 'sanitize_text_field' ],
],
]
);
register_rest_route(
self::NAMESPACE,
'/users/(?P<id>\d+)/email-change/confirm',
[
'methods' => 'POST',
'callback' => [ $this, 'confirm' ],
// Token presence is the authentication — public route by design,
// the token-hash check inside is the real gatekeeper.
'permission_callback' => '__return_true',
'args' => [
'id' => [ 'sanitize_callback' => 'absint' ],
'token' => [ 'sanitize_callback' => 'sanitize_text_field' ],
'redirect_url' => [ 'sanitize_callback' => 'sanitize_text_field' ],
],
]
);
register_rest_route(
self::NAMESPACE,
'/users/(?P<id>\d+)/email-change/cancel',
[
'methods' => 'POST',
'callback' => [ $this, 'cancel' ],
// Permission may be granted via edit_user OR a valid cancel
// token; the handler resolves both paths.
'permission_callback' => '__return_true',
'args' => [
'id' => [ 'sanitize_callback' => 'absint' ],
'token' => [ 'sanitize_callback' => 'sanitize_text_field' ],
],
]
);
}
/**
* Permission callback for initiate — `edit_user` on the target.
*
* @param WP_REST_Request $request REST request.
*
* @return true|WP_Error
*/
public function check_permission_initiate( WP_REST_Request $request ) {
$target_id = absint( $request['id'] ?? 0 );
if ( $target_id <= 0 ) {
return new WP_Error(
'workos_invalid_user',
__( 'Invalid user ID.', 'integration-workos' ),
[ 'status' => 400 ]
);
}
if ( ! current_user_can( 'edit_user', $target_id ) ) {
return new WP_Error(
'workos_forbidden',
__( 'You do not have permission to change this user’s email.', 'integration-workos' ),
[ 'status' => 403 ]
);
}
/**
* Filter whether the current request can initiate a change for
* a given target.
*
* @param bool $allowed Whether the request is allowed.
* @param int $target_id Target user ID.
* @param int $initiator_id Current user ID (0 for unauthenticated).
*/
$allowed = (bool) apply_filters(
'workos_change_email_can_initiate',
true,
$target_id,
get_current_user_id()
);
if ( ! $allowed ) {
return new WP_Error(
'workos_forbidden',
__( 'You do not have permission to change this user’s email.', 'integration-workos' ),
[ 'status' => 403 ]
);
}
return true;
}
/**
* Initiate a pending email change.
*
* @param WP_REST_Request $request REST request.
*
* @return WP_REST_Response|WP_Error
*/
public function initiate( WP_REST_Request $request ) {
$target_id = absint( $request['id'] );
$user = get_userdata( $target_id );
if ( ! $user instanceof WP_User ) {
return new WP_Error(
'workos_user_not_found',
__( 'User not found.', 'integration-workos' ),
[ 'status' => 404 ]
);
}
$new_email = sanitize_email( (string) $request->get_param( 'new_email' ) );
if ( '' === $new_email || ! is_email( $new_email ) ) {
return new WP_Error(
'workos_invalid_email',
__( 'A valid email address is required.', 'integration-workos' ),
[ 'status' => 400 ]
);
}
$new_email = strtolower( $new_email );
$is_admin_action = $this->is_admin_action( (int) $user->ID );
// Rate limits throttle self-service abuse; the capability-gated admin
// path bypasses them so a legitimate cleanup sweep isn't blocked.
if ( ! $is_admin_action ) {
// Recipient is the target account, not $new_email: initiate mails
// both the new address and a notice to the current one, and the
// account is what's common to them.
$rate_ok = $this->rate_limiter->attempt(
'change_email_init_ip',
$this->client_ip->get(),
TieredRateLimiter::SEND_IP
);
if ( is_wp_error( $rate_ok ) ) {
return $rate_ok;
}
$rate_ok = $this->rate_limiter->attempt(
'change_email_init_recipient',
(string) $user->ID,
TieredRateLimiter::SEND_RECIPIENT
);
if ( is_wp_error( $rate_ok ) ) {
return $rate_ok;
}
}
// Treat "change to the address I already have" as a benign no-op
// rather than an error, but also don't ship a verification email
// — there's nothing to verify.
if ( strcasecmp( $new_email, (string) $user->user_email ) === 0 ) {
return new WP_REST_Response(
[
'ok' => true,
'masked_new_email' => $this->masker->mask( $new_email ),
'no_op' => true,
],
200
);
}
$conflict = $this->conflicts->check( $new_email, $user );
if ( is_wp_error( $conflict ) ) {
EventLogger::log(
'email_change.conflict_blocked',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'policy' => $this->conflicts->resolve_policy(),
'initiator_id' => get_current_user_id(),
],
]
);
// A privileged user acting on someone else's account may see the
// real reason — they can already enumerate accounts, so nothing
// leaks. Self-service callers keep the enumeration-safe shape.
if ( $is_admin_action ) {
return new WP_Error(
'workos_change_email_conflict',
__( 'This email is already in use by another account.', 'integration-workos' ),
[ 'status' => 409 ]
);
}
// Enumeration-safe: same shape as success. The conflict is
// surfaced in the activity log, not in the response.
return new WP_REST_Response(
[
'ok' => true,
'masked_new_email' => $this->masker->mask( $new_email ),
],
200
);
}
// Admin-direct path: commit now, no token, no verification email.
if ( $is_admin_action ) {
return $this->commit_admin_change( $user, $new_email );
}
$lifetime = $this->token_lifetime();
$expires = time() + $lifetime;
$confirm_token = $this->tokens->generate();
$cancel_token = $this->tokens->generate();
$this->pending->store(
(int) $user->ID,
$new_email,
$confirm_token,
$cancel_token,
$expires,
get_current_user_id()
);
$redirect_url = (string) $request->get_param( 'redirect_url' );
$confirm_url = $this->build_confirm_url( (int) $user->ID, $confirm_token, $redirect_url );
$cancel_url = $this->build_cancel_url( (int) $user->ID, $cancel_token );
$this->notifier->send_verification( $user, $new_email, $confirm_url, $expires );
$this->notifier->send_old_address_notice( $user, $new_email, $cancel_url, $expires );
EventLogger::log(
'email_change.initiated',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'initiator_id' => get_current_user_id(),
'self_service' => get_current_user_id() === (int) $user->ID,
'expires_at' => $expires,
],
]
);
/**
* Fires after a pending email change is stored and notifications sent.
*
* @param int $user_id Target WP user ID.
* @param string $new_email Requested new address.
* @param int $initiated_by Current user ID (0 for system).
*/
do_action( 'workos_change_email_initiated', (int) $user->ID, $new_email, get_current_user_id() );
return new WP_REST_Response(
[
'ok' => true,
'masked_new_email' => $this->masker->mask( $new_email ),
'expires_at' => $expires,
],
200
);
}
/**
* Commit an admin-initiated change immediately, bypassing verification.
*
* Skips the token round-trip and the user notification — the capability
* is the trust boundary, and the change is audit-logged instead. Echoes
* the new address back unmasked (the admin typed it) so the UI can
* refresh the row in place.
*
* @param WP_User $user Target user (pre-update).
* @param string $new_email Lowercased, validated new address.
*
* @return WP_REST_Response|WP_Error
*/
private function commit_admin_change( WP_User $user, string $new_email ) {
// Admin-direct changes are silent. Beyond skipping our own notifier,
// suppress WP core's "Notice of Email Change" that wp_update_user()
// would otherwise mail to the old address. Scoped to this commit so
// the self-service confirm path keeps its core notice.
$suppress_core_notice = static function () {
return false;
};
add_filter( 'send_email_change_email', $suppress_core_notice );
$commit = $this->commit_change( $user, $new_email );
remove_filter( 'send_email_change_email', $suppress_core_notice );
if ( is_wp_error( $commit ) ) {
return $commit;
}
$old_email = $commit['old_email'];
EventLogger::log(
'email_change.admin_changed',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'masked_old_email' => $this->masker->mask( $old_email ),
'initiator_id' => get_current_user_id(),
'verified' => false,
],
]
);
/**
* Fires after an email change is committed to WorkOS + WP. Shared
* with the verified-confirm path so downstream observers don't have
* to special-case how the change was authorized.
*
* @param int $user_id Target WP user ID.
* @param string $old_email Previous email.
* @param string $new_email New email.
*/
do_action( 'workos_change_email_confirmed', (int) $user->ID, $old_email, $new_email );
return new WP_REST_Response(
[
'ok' => true,
'committed' => true,
'email' => $new_email,
],
200
);
}
/**
* Confirm a pending email change.
*
* @param WP_REST_Request $request REST request.
*
* @return WP_REST_Response|WP_Error
*/
public function confirm( WP_REST_Request $request ) {
$target_id = absint( $request['id'] );
$token = (string) $request->get_param( 'token' );
if ( $target_id <= 0 || '' === $token ) {
return new WP_Error(
'workos_invalid_request',
__( 'Invalid confirmation request.', 'integration-workos' ),
[ 'status' => 400 ]
);
}
$user = get_userdata( $target_id );
if ( ! $user instanceof WP_User ) {
return new WP_Error(
'workos_invalid_token',
__( 'This confirmation link is no longer valid.', 'integration-workos' ),
[ 'status' => 400 ]
);
}
$record = $this->pending->get( (int) $user->ID );
if ( null === $record ) {
return new WP_Error(
'workos_invalid_token',
__( 'This confirmation link is no longer valid.', 'integration-workos' ),
[ 'status' => 400 ]
);
}
if ( $this->pending->expired( $record ) ) {
$this->pending->clear( (int) $user->ID );
EventLogger::log(
'email_change.expired',
[
'user_id' => $user->ID,
'metadata' => [ 'masked_new_email' => $this->masker->mask( $record['new_email'] ) ],
]
);
return new WP_Error(
'workos_token_expired',
__( 'This confirmation link has expired. Please start the change again.', 'integration-workos' ),
[ 'status' => 410 ]
);
}
if ( ! $this->pending->verify_confirm( $record, $token ) ) {
return new WP_Error(
'workos_invalid_token',
__( 'This confirmation link is no longer valid.', 'integration-workos' ),
[ 'status' => 400 ]
);
}
$new_email = (string) $record['new_email'];
// Race re-check: another local user may have started using
// $new_email between initiate and confirm.
$conflict = $this->conflicts->check( $new_email, $user );
if ( is_wp_error( $conflict ) ) {
$this->pending->clear( (int) $user->ID );
EventLogger::log(
'email_change.conflict_blocked',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'phase' => 'confirm',
'policy' => $this->conflicts->resolve_policy(),
],
]
);
return $conflict;
}
$commit = $this->commit_change( $user, $new_email );
if ( is_wp_error( $commit ) ) {
return $commit;
}
$old_email = $commit['old_email'];
// Refresh user object now that the email is committed.
$user = get_userdata( (int) $user->ID );
if ( $user instanceof WP_User ) {
$this->notifier->send_confirmation_notice( $user, $old_email, $new_email );
}
EventLogger::log(
'email_change.confirmed',
[
'user_id' => $target_id,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'masked_old_email' => $this->masker->mask( $old_email ),
],
]
);
/**
* Fires after an email change is committed to WorkOS + WP.
*
* @param int $user_id Target WP user ID.
* @param string $old_email Previous email.
* @param string $new_email New email.
*/
do_action( 'workos_change_email_confirmed', $target_id, $old_email, $new_email );
$redirect_url = $this->validate_redirect( (string) $request->get_param( 'redirect_url' ) );
return new WP_REST_Response(
[
'ok' => true,
'redirect_url' => $redirect_url,
],
200
);
}
/**
* Cancel a pending email change.
*
* @param WP_REST_Request $request REST request.
*
* @return WP_REST_Response|WP_Error
*/
public function cancel( WP_REST_Request $request ) {
$target_id = absint( $request['id'] );
$user = get_userdata( $target_id );
if ( ! $user instanceof WP_User ) {
return new WP_Error(
'workos_user_not_found',
__( 'User not found.', 'integration-workos' ),
[ 'status' => 404 ]
);
}
$record = $this->pending->get( (int) $user->ID );
if ( null === $record ) {
// Nothing to cancel — treat as success so a double-click on
// the cancel link doesn't look like an error.
return new WP_REST_Response( [ 'ok' => true ], 200 );
}
$token = (string) $request->get_param( 'token' );
$by_token = '' !== $token && $this->pending->verify_cancel( $record, $token );
$by_capability = current_user_can( 'edit_user', $user->ID );
if ( ! $by_token && ! $by_capability ) {
return new WP_Error(
'workos_forbidden',
__( 'You do not have permission to cancel this email change.', 'integration-workos' ),
[ 'status' => 403 ]
);
}
$this->pending->clear( (int) $user->ID );
EventLogger::log(
'email_change.cancelled',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( (string) $record['new_email'] ),
'reason' => $by_token ? 'token' : 'capability',
],
]
);
/**
* Fires after a pending change is cancelled.
*
* @param int $user_id Target WP user ID.
* @param string $reason 'token' or 'capability'.
*/
do_action( 'workos_change_email_cancelled', (int) $user->ID, $by_token ? 'token' : 'capability' );
return new WP_REST_Response( [ 'ok' => true ], 200 );
}
/**
* Commit an email change to WorkOS and WordPress.
*
* Shared by the verified-confirm path and the admin-direct path. The
* caller is responsible for permission, conflict, and token checks
* *before* calling this — by the time we're here the change is approved
* and we just need it to land atomically across both stores.
*
* Sets the in-progress transient before touching WorkOS so the
* `user.updated` webhook fan-back is a no-op while we own the
* transition, rolls WorkOS back if the local write fails so the two
* stores can't drift, then refreshes the sync hash so the next webhook
* doesn't see a phantom diff. Does NOT send notifications or fire the
* `confirmed` action — those are the caller's concern.
*
* @param WP_User $user Target user (pre-update).
* @param string $new_email Lowercased, validated new address.
*
* @return array{old_email:string,workos_user_id:string}|WP_Error
*/
private function commit_change( WP_User $user, string $new_email ) {
$old_email = (string) $user->user_email;
$workos_user_id = (string) get_user_meta( $user->ID, '_workos_user_id', true );
set_transient( self::TRANSIENT_PREFIX . (int) $user->ID, 1, self::TRANSIENT_TTL );
if ( '' !== $workos_user_id ) {
$workos_response = workos()->api()->update_user( $workos_user_id, [ 'email' => $new_email ] );
if ( is_wp_error( $workos_response ) ) {
delete_transient( self::TRANSIENT_PREFIX . (int) $user->ID );
EventLogger::log(
'email_change.commit_failed',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'reason' => $workos_response->get_error_message(),
],
]
);
return new WP_Error(
'workos_commit_failed',
__( 'Could not update the email at WorkOS. Please try again.', 'integration-workos' ),
[ 'status' => 502 ]
);
}
}
$wp_update = wp_update_user(
[
'ID' => (int) $user->ID,
'user_email' => $new_email,
]
);
if ( is_wp_error( $wp_update ) ) {
// Rollback WorkOS so the two stores don't drift.
if ( '' !== $workos_user_id && '' !== $old_email ) {
workos()->api()->update_user( $workos_user_id, [ 'email' => $old_email ] );
}
delete_transient( self::TRANSIENT_PREFIX . (int) $user->ID );
EventLogger::log(
'email_change.commit_failed',
[
'user_id' => $user->ID,
'metadata' => [
'masked_new_email' => $this->masker->mask( $new_email ),
'reason' => $wp_update->get_error_message(),
'rolled_back' => true,
],
]
);
return new WP_Error(
'workos_commit_failed',
__( 'Could not update the email locally. Please try again.', 'integration-workos' ),
[ 'status' => 500 ]
);
}
$this->pending->clear( (int) $user->ID );
delete_transient( self::TRANSIENT_PREFIX . (int) $user->ID );
// Keep the sync change-detection hash in step with the new email so
// the next user.updated webhook doesn't see a phantom diff and
// re-mirror a change we already committed.
\WorkOS\Sync\UserSync::refresh_profile_hash( (int) $user->ID );
return [
'old_email' => $old_email,
'workos_user_id' => $workos_user_id,
];
}
/**
* Whether the request is a privileged admin acting on *another* account.
*
* This is the trust boundary for the admin-direct behavior: such a
* caller can already manage every account, so we (a) commit the change
* immediately without an emailed verification step and (b) surface the
* real reason a change was rejected instead of the enumeration-safe
* shape. A self-service change (initiator === target) — or any caller
* without `edit_users` — gets neither: it goes through the verified
* token flow and never learns which addresses are already registered.
*
* @param int $target_id Target user ID.
*
* @return bool
*/
private function is_admin_action( int $target_id ): bool {
return get_current_user_id() !== $target_id && current_user_can( 'edit_users' );
}
/**
* Resolve the configured token lifetime (clamped to [300, 86400]).
*
* @return int
*/
private function token_lifetime(): int {
$lifetime = (int) workos()->option( 'change_email_token_lifetime', 3600 );
/**
* Filter the change-email token lifetime in seconds.
*
* @param int $lifetime Lifetime in seconds.
*/
$lifetime = (int) apply_filters( 'workos_change_email_token_lifetime', $lifetime );
// Defensive clamp so a misconfiguration can't issue infinite or
// 1-second tokens.
return max( 300, min( 86400, $lifetime ) );
}
/**
* Build the frontend confirm URL for an emailed link.
*
* @param int $user_id Target user ID.
* @param string $token Plaintext confirm token.
* @param string $redirect_url Optional same-host redirect after success.
*
* @return string
*/
private function build_confirm_url( int $user_id, string $token, string $redirect_url ): string {
$path = (string) workos()->option( 'change_email_confirm_path', 'workos/change-email' );
$path = trim( $path, '/' );
$base = home_url( '/' . $path . '/' );
$args = [
'user_id' => $user_id,
'token' => $token,
];
if ( '' !== $redirect_url ) {
$args['redirect_to'] = $redirect_url;
}
return add_query_arg( $args, $base );
}
/**
* Build the cancel URL emailed to the old address.
*
* The cancel URL points at the same frontend confirm route with
* `action=cancel`, which the page-side JS picks up to POST to the
* cancel endpoint instead of confirm.
*
* @param int $user_id Target user ID.
* @param string $token Plaintext cancel token.
*
* @return string
*/
private function build_cancel_url( int $user_id, string $token ): string {
$path = (string) workos()->option( 'change_email_confirm_path', 'workos/change-email' );
$path = trim( $path, '/' );
$base = home_url( '/' . $path . '/' );
return add_query_arg(
[
'user_id' => $user_id,
'token' => $token,
'action' => 'cancel',
],
$base
);
}
/**
* Validate a redirect URL against site host, falling back to home.
*
* @param string $url Raw URL.
*
* @return string
*/
private function validate_redirect( string $url ): string {
if ( '' === $url ) {
return home_url( '/' );
}
$candidate = wp_validate_redirect( $url, '' );
if ( '' === $candidate ) {
return home_url( '/' );
}
$url_host = strtolower( (string) wp_parse_url( $candidate, PHP_URL_HOST ) );
$site_host = strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
return $url_host === $site_host ? $candidate : home_url( '/' );
}
}