All files / src/webhooks registry.ts

100% Statements 114/114
100% Branches 56/56
100% Functions 13/13
100% Lines 104/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2851x     1x   1x 1x 1x 1x 1x   1x                                                                     9x   6x 2x           4x             2x 1x           1x             1x         10x                                     9x 3x   6x         9x   6x 6x 6x   2x 2x 2x     9x                             1x       10x 10x 10x 10x 10x 10x   10x 10x   10x     10x     10x 10x 4x 4x 1x           11x 9x       9x 9x   1x 1x     10x   8x 8x     10x       9x   9x 9x 8x     9x 9x 1x 1x 1x           64x 64x   8x 8x   8x 8x   8x 8x       8x 8x 1x   8x 1x   8x 1x     8x 3x 3x 3x             5x   5x       6x 4x 6x   5x   5x 2x   1x 1x     1x 1x     1x 1x     5x 5x 5x 3x   2x         9x       3x       1x  
import {createHmac} from 'crypto';
import http from 'http';
 
import {StatusCode} from '@shopify/network';
 
import {GraphqlClient} from '../clients/graphql/graphql_client';
import {ShopifyHeader} from '../base_types';
import ShopifyUtilities from '../utils';
import {Context} from '../context';
import * as ShopifyErrors from '../error';
 
import {
  DeliveryMethod,
  RegisterOptions,
  RegisterReturn,
  WebhookRegistryEntry,
  WebhookCheckResponse,
} from './types';
 
interface RegistryInterface {
  webhookRegistry: WebhookRegistryEntry[];
 
  /**
   * Registers a Webhook Handler function for a given topic.
   *
   * @param options Parameters to register a handler, including topic, listening address, handler function
   */
  register(options: RegisterOptions): Promise<RegisterReturn>;
 
  /**
   * Processes the webhook request received from the Shopify API
   *
   * @param request HTTP request received from Shopify
   * @param response HTTP response to the request
   */
  process(request: http.IncomingMessage, response: http.ServerResponse): Promise<void>;
 
  /**
   * Confirms that the given path is a webhook path
   *
   * @param string path component of a URI
   */
  isWebhookPath(path: string): boolean;
}
 
function isSuccess(result: any, deliveryMethod: DeliveryMethod, webhookId?: string): boolean {
  switch (deliveryMethod) {
    case DeliveryMethod.Http:
      if (webhookId) {
        return Boolean(
          result.data &&
            result.data.webhookSubscriptionUpdate &&
            result.data.webhookSubscriptionUpdate.webhookSubscription,
        );
      } else {
        return Boolean(
          result.data &&
            result.data.webhookSubscriptionCreate &&
            result.data.webhookSubscriptionCreate.webhookSubscription,
        );
      }
    case DeliveryMethod.EventBridge:
      if (webhookId) {
        return Boolean(
          result.data &&
            result.data.eventBridgeWebhookSubscriptionUpdate &&
            result.data.eventBridgeWebhookSubscriptionUpdate.webhookSubscription,
        );
      } else {
        return Boolean(
          result.data &&
            result.data.eventBridgeWebhookSubscriptionCreate &&
            result.data.eventBridgeWebhookSubscriptionCreate.webhookSubscription,
        );
      }
    default:
      return false;
  }
}
 
function buildCheckQuery(topic: string): string {
  return `{
    webhookSubscriptions(first: 1, topics: ${topic}) {
      edges {
        node {
          id
          callbackUrl
        }
      }
    }
  }`;
}
 
function buildQuery(
  topic: string,
  address: string,
  deliveryMethod: DeliveryMethod,
  webhookId?: string,
): string {
  let identifier: string;
  if (webhookId) {
    identifier = `id: "${webhookId}"`;
  } else {
    identifier = `topic: ${topic}`;
  }
 
  let mutationName: string;
  let webhookSubscriptionArgs: string;
  switch (deliveryMethod) {
    case DeliveryMethod.Http:
      mutationName = webhookId ? 'webhookSubscriptionUpdate' : 'webhookSubscriptionCreate';
      webhookSubscriptionArgs = `{callbackUrl: "${address}"}`;
      break;
    case DeliveryMethod.EventBridge:
      mutationName = webhookId ? 'eventBridgeWebhookSubscriptionUpdate' : 'eventBridgeWebhookSubscriptionCreate';
      webhookSubscriptionArgs = `{arn: "${address}"}`;
      break;
  }
 
  return `
    mutation webhookSubscription {
      ${mutationName}(${identifier}, webhookSubscription: ${webhookSubscriptionArgs}) {
        userErrors {
          field
          message
        }
        webhookSubscription {
          id
        }
      }
    }
  `;
}
 
const WebhooksRegistry: RegistryInterface = {
  webhookRegistry: [],
 
  async register({
    path,
    topic,
    accessToken,
    shop,
    deliveryMethod = DeliveryMethod.Http,
    webhookHandler,
  }: RegisterOptions): Promise<RegisterReturn> {
    const client = new GraphqlClient(shop, accessToken);
    const address = `https://${Context.HOST_NAME}${path}`;
 
    const checkResult = await client.query({
      data: buildCheckQuery(topic),
    });
    const checkBody = checkResult.body as WebhookCheckResponse;
 
    let webhookId: string | undefined;
    let mustRegister = true;
    if (checkBody.data.webhookSubscriptions.edges.length) {
      webhookId = checkBody.data.webhookSubscriptions.edges[0].node.id;
      if (checkBody.data.webhookSubscriptions.edges[0].node.callbackUrl === address) {
        mustRegister = false;
      }
    }
 
    let success: boolean;
    let body: unknown;
    if (mustRegister) {
      const result = await client.query({
        data: buildQuery(topic, address, deliveryMethod, webhookId),
      });
 
      success = isSuccess(result.body, deliveryMethod, webhookId);
      body = result.body;
    } else {
      success = true;
      body = {};
    }
 
    if (success) {
      // Remove this topic from the registry if it is already there
      WebhooksRegistry.webhookRegistry = WebhooksRegistry.webhookRegistry.filter((item) => item.topic !== topic);
      WebhooksRegistry.webhookRegistry.push({path, topic, webhookHandler});
    }
 
    return {success, result: body};
  },
 
  async process(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
    let reqBody = '';
 
    const promise: Promise<void> = new Promise((resolve, reject) => {
      request.on('data', (chunk) => {
        reqBody += chunk;
      });
 
      request.on('end', async () => {
        if (!reqBody.length) {
          response.writeHead(StatusCode.BadRequest);
          response.end();
          return reject(new ShopifyErrors.InvalidWebhookError('No body was received when processing webhook'));
        }
 
        let hmac: string | string [] | undefined;
        let topic: string | string [] | undefined;
        let domain: string | string [] | undefined;
        Object.entries(request.headers).map(([header, value]) => {
          switch (header.toLowerCase()) {
            case ShopifyHeader.Hmac.toLowerCase():
              hmac = value;
              break;
            case ShopifyHeader.Topic.toLowerCase():
              topic = value;
              break;
            case ShopifyHeader.Domain.toLowerCase():
              domain = value;
              break;
          }
        });
 
        const missingHeaders = [];
        if (!hmac) {
          missingHeaders.push(ShopifyHeader.Hmac);
        }
        if (!topic) {
          missingHeaders.push(ShopifyHeader.Topic);
        }
        if (!domain) {
          missingHeaders.push(ShopifyHeader.Domain);
        }
 
        if (missingHeaders.length) {
          response.writeHead(StatusCode.BadRequest);
          response.end();
          return reject(new ShopifyErrors.InvalidWebhookError(
            `Missing one or more of the required HTTP headers to process webhooks: [${missingHeaders.join(', ')}]`,
          ));
        }
 
        let statusCode: StatusCode | undefined;
        let responseError: Error | undefined;
        const headers = {};
 
        const generatedHash = createHmac('sha256', Context.API_SECRET_KEY)
          .update(reqBody, 'utf8')
          .digest('base64');
 
        if (ShopifyUtilities.safeCompare(generatedHash, hmac as string)) {
          const graphqlTopic = (topic as string).toUpperCase().replace(/\//g, '_');
          const webhookEntry = WebhooksRegistry.webhookRegistry.find((entry) => entry.topic === graphqlTopic);
 
          if (webhookEntry) {
            try {
              await webhookEntry.webhookHandler(graphqlTopic, domain as string, reqBody);
              statusCode = StatusCode.Ok;
            } catch (error) {
              statusCode = StatusCode.InternalServerError;
              responseError = error;
            }
          } else {
            statusCode = StatusCode.Forbidden;
            responseError = new ShopifyErrors.InvalidWebhookError(`No webhook is registered for topic ${topic}`);
          }
        } else {
          statusCode = StatusCode.Forbidden;
          responseError = new ShopifyErrors.InvalidWebhookError(`Could not validate request for topic ${topic}`);
        }
 
        response.writeHead(statusCode, headers);
        response.end();
        if (responseError) {
          return reject(responseError);
        } else {
          return resolve();
        }
      });
    });
 
    return promise;
  },
 
  isWebhookPath(path: string): boolean {
    return Boolean(WebhooksRegistry.webhookRegistry.find((entry) => entry.path === path));
  },
};
 
export {WebhooksRegistry, RegistryInterface};