namespace, '/subscribe', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'subscribe' ), 'permission_callback' => array( $this, 'check_api_key' ), ) ); register_rest_route( $this->namespace, '/api-key', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_key' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/api-key/regenerate', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'regenerate_key' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); } /** * POST /subscribe: sign an address up through the site's API key, the same * way a signup form does (Mailpuff_Subscription::signup()): a confirmation * email first, public tags only. The site's own code, signed in as an * administrator, may skip the confirmation (`double_opt_in: false`) and * use internal tags, and gets the outcome back. Any other caller gets the * same answer whatever the address's state, so the key can't be used to * find out who is on the list. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function subscribe( $request ) { // Rate limit: fixed window per IP per minute. if ( ! $this->within_rate_limit() ) { return $this->error( 'rate_limit', __( 'Too many requests. Try again in a minute.', 'mailpuff' ), 429 ); } $email = sanitize_email( (string) $request->get_param( 'email' ) ); if ( ! is_email( $email ) ) { return $this->error( 'invalid_email', __( 'A valid email address is required.', 'mailpuff' ), 400 ); } $trusted = current_user_can( $this->capability ); /** * Whether this API-key call may add someone as subscribed with no * confirmation email. By default only the site's own code (a request * signed in as an administrator) may; a key pasted into a script or a * third-party form always sends the confirmation first. * * @param bool $allow Default: the current user can manage options. * @param WP_REST_Request $request The request. */ $direct = (bool) apply_filters( 'mailpuff_subscribe_direct', $trusted, $request ); $doi = ! ( $direct && false === rest_sanitize_boolean( $request->get_param( 'double_opt_in' ) ?? true ) ); $groups = $this->parse_group_ids( $request ); $result = Mailpuff_Subscription::signup( $email, array( 'first_name' => (string) $request->get_param( 'first_name' ), 'last_name' => (string) $request->get_param( 'last_name' ), 'group_ids' => $groups, 'double_opt_in' => $doi, 'consent_source' => 'api', 'source' => 'api', ) ); // signup() joins public tags only; internal ones the caller may use. $contact = 'ignored' !== $result ? Mailpuff_Contact::find_by_email( $email ) : null; if ( $contact ) { $now = current_time( 'mysql' ); foreach ( $groups as $gid ) { $this->maybe_add_to_group( (int) $contact->id, $gid, $now ); } } if ( ! $trusted ) { return $this->success( array( 'received' => true ), 202 ); } return $this->success( array( 'received' => true, 'result' => $result, 'id' => $contact ? (int) $contact->id : 0, 'status' => $contact ? (string) $contact->status : '', ), 'subscribed' === $result || 'pending' === $result ? 201 : 200 ); } /** * Permission for POST /subscribe: the site's API key, compared in * constant time. No user session is needed or used. A key that passes * records when it was last used; a failed check writes nothing. * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public function check_api_key( $request ) { $key = $this->extract_key( $request ); $stored = (string) get_option( self::OPTION_KEY, '' ); if ( '' === $stored || '' === $key || ! hash_equals( $stored, $key ) ) { return $this->error( 'invalid_key', __( 'Invalid or missing API key.', 'mailpuff' ), 401 ); } $this->mark_used( $stored ); return true; } /** * GET /api-key — return (or auto-create) the API key. * * @return WP_REST_Response */ public function get_key() { return $this->success( $this->key_response( $this->ensure_key() ) ); } /** * POST /api-key/regenerate — rotate the key and return the new one. The * old key stops working at once. * * @return WP_REST_Response */ public function regenerate_key() { return $this->success( $this->key_response( $this->new_key() ) ); } // Private helpers /** * Return stored key, creating it if it doesn't exist yet. * * @return string */ private function ensure_key() { $key = (string) get_option( self::OPTION_KEY, '' ); return '' !== $key ? $key : $this->new_key(); } /** * Store a fresh key, made now and not used yet. * * @return string The new key. */ private function new_key() { $key = $this->generate_key(); update_option( self::OPTION_KEY, $key, false ); update_option( self::META_OPTION, array( 'fp' => self::fingerprint( $key ), 'created_at' => time(), 'last_used_at' => null, ), false ); return $key; } /** * Which key a meta entry belongs to: the first 16 hex characters of the * key's SHA-256. * * @param string $key The key. * @return string */ private static function fingerprint( $key ) { return substr( hash( 'sha256', (string) $key ), 0, 16 ); } /** * The key with its times, as both admin routes answer. * * @param string $key The key. * @return array { key, created_at: int|null, last_used_at: int|null } */ private function key_response( $key ) { return array_merge( array( 'key' => $key ), $this->key_meta( $key ) ); } /** * The stored meta option as an array. * * @return array */ private function stored_meta() { $meta = get_option( self::META_OPTION, array() ); return is_array( $meta ) ? $meta : array(); } /** * The times stored for $key, each Unix seconds (UTC) or null when not * recorded. Meta that names another key holds no times for this one. * * @param string $key The key. * @return array { created_at: int|null, last_used_at: int|null } */ private function key_meta( $key ) { $meta = $this->stored_meta(); if ( isset( $meta['fp'] ) && self::fingerprint( $key ) !== (string) $meta['fp'] ) { $meta = array(); } $out = array(); foreach ( array( 'created_at', 'last_used_at' ) as $name ) { $out[ $name ] = empty( $meta[ $name ] ) ? null : (int) $meta[ $name ]; } return $out; } /** * Record that $key authorised a request: only when nothing is stored * yet, the stored time is more than USED_EVERY seconds old, or it is in * the future (the clock was set back), so a burst of signups does not * write the options table on every request. * * The meta must name $key. Meta that names no key takes $key's. Meta naming another key is left alone when $key was replaced * while this request ran; when $key is still the stored one, the key was * changed some other way and $key takes the meta over, with no * creation time. * * @param string $key The key that passed the check. * @return void */ private function mark_used( $key ) { $fp = self::fingerprint( $key ); $meta = $this->stored_meta(); if ( isset( $meta['fp'] ) && (string) $meta['fp'] !== $fp && $key !== $this->key_in_database() ) { return; } $times = $this->key_meta( $key ); $last = $times['last_used_at']; $now = time(); if ( null !== $last && $last <= $now && $now - $last <= self::USED_EVERY ) { return; } update_option( self::META_OPTION, array( 'fp' => $fp, 'created_at' => $times['created_at'], 'last_used_at' => $now, ), false ); } /** * The key as stored now, read past this request's options cache, which * still holds the old key when another request replaced it meanwhile. * Read only when the meta names another key. * * @return string */ private function key_in_database() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the cached copy is the one that may be stale. $raw = $wpdb->get_var( $wpdb->prepare( 'SELECT option_value FROM %i WHERE option_name = %s LIMIT 1', $wpdb->options, self::OPTION_KEY ) ); return (string) maybe_unserialize( (string) $raw ); } /** * Generate a new random API key with a `mailpuff_` prefix. * * @return string */ private function generate_key() { return 'mailpuff_' . wp_generate_password( 40, false ); } /** * Pull the key from the X-Mailpuff-Key header, or an `api_key` in the * request body. Never from the URL: a key in a query string ends up in * server and proxy logs. * * @param WP_REST_Request $request Request object. * @return string */ private function extract_key( $request ) { $header = $request->get_header( 'x-mailpuff-key' ); if ( $header ) { return sanitize_text_field( $header ); } $body = array_merge( (array) $request->get_body_params(), (array) $request->get_json_params() ); return sanitize_text_field( (string) ( $body['api_key'] ?? '' ) ); } /** * Return a deduplicated array of positive group IDs from the request. * * Thin wrapper over the shared parser in Mailpuff_Contact_Service, then * limited to public groups unless the caller is the site's own admin. * * @param WP_REST_Request $request Request object. * @return int[] */ private function parse_group_ids( $request ) { $ids = Mailpuff_Contact_Service::parse_group_ids( $request ); /** * Whether this API-key call may use internal groups. By default only * the site's own code (a request signed in as an administrator) may; * a key pasted into a script or a third-party form may join public * groups only. * * @param bool $allow Default: the current user can manage options. * @param WP_REST_Request $request The request. */ $allow_internal = (bool) apply_filters( 'mailpuff_subscribe_internal_groups', current_user_can( $this->capability ), $request ); return $allow_internal ? $ids : Mailpuff_Subscription::only_public_groups( $ids ); } /** * Add a contact to a group if group_id > 0. * * @param int $contact_id Contact ID. * @param int $group_id Group ID (0 = skip). * @param string $now MySQL datetime. */ private function maybe_add_to_group( $contact_id, $group_id, $now ) { Mailpuff_Contact_Service::add_to_group( $contact_id, $group_id, $now ); } }