All files / src/auth/oauth oauth.ts

98.04% Statements 100/102
97.14% Branches 34/35
92.86% Functions 13/14
98.98% Lines 97/98

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 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  9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x                             16x 16x   16x 16x 15x 14x 14x       14x 14x           14x             14x 14x                                 12x   12x 26x   12x 11x 10x 10x 10x 1x   9x 2x   7x 7x         7x         7x 7x 7x   7x 7x 7x 5x       5x             7x   7x 7x 1x   6x                                         15x               30x                   32x   32x 20x 20x 18x 18x 2x   16x 16x 16x 13x     3x             30x   14x   30x     9x               9x                   24x       24x                   10x       10x                         7x 4x 4x 4x 4x 4x 1x     3x   4x 4x 4x 4x 4x     3x 3x 3x 3x   7x                                                                                                                                                                                
import http from 'http';
import querystring from 'querystring';
 
import {v4 as uuidv4} from 'uuid';
import Cookies from 'cookies';
 
import {Context} from '../../context';
import nonce from '../../utils/nonce';
import validateHmac from '../../utils/hmac-validator';
import safeCompare from '../../utils/safe-compare';
import decodeSessionToken from '../../utils/decode-session-token';
import {Session} from '../session';
import {HttpClient} from '../../clients/http_client/http_client';
import {DataType, RequestReturn} from '../../clients/http_client/types';
import * as ShopifyErrors from '../../error';
import {SessionInterface} from '../session/types';
import {sanitizeShop} from '../../utils/shop-validator';
 
import {
  AuthQuery,
  AccessTokenResponse,
  OnlineAccessResponse,
  OnlineAccessInfo,
} from './types';
 
const ShopifyOAuth = {
  SESSION_COOKIE_NAME: 'shopify_app_session',
  STATE_COOKIE_NAME: 'shopify_app_state',
 
  /**
   * Initializes a session and cookie for the OAuth process, and returns the necessary authorization url.
   *
   * @param request Current HTTP Request
   * @param response Current HTTP Response
   * @param shop Shop url: {shop}.myshopify.com
   * @param redirect Redirect url for callback
   * @param isOnline Boolean value. If true, appends 'per-user' grant options to authorization url to receive online access token.
   *                 During final oauth request, will receive back the online access token and current online session information.
   *                 Defaults to online access.
   */
  async beginAuth(
    request: http.IncomingMessage,
    response: http.ServerResponse,
    shop: string,
    redirectPath: string,
    isOnline = true,
  ): Promise<string> {
    Context.throwIfUninitialized();
    Context.throwIfPrivateApp('Cannot perform OAuth for private apps');
    const cleanShop = sanitizeShop(shop, true)!;
 
    const cookies = new Cookies(request, response, {
      keys: [Context.API_SECRET_KEY],
      secure: true,
    });
 
    const state = isOnline ? `online_${nonce()}` : `offline_${nonce()}`;
 
    cookies.set(ShopifyOAuth.STATE_COOKIE_NAME, state, {
      signed: true,
      expires: new Date(Date.now() + 60000),
      sameSite: 'lax',
      secure: true,
    });
 
    /* eslint-disable @typescript-eslint/naming-convention */
    const query = {
      client_id: Context.API_KEY,
      scope: Context.SCOPES.toString(),
      redirect_uri: `${Context.HOST_SCHEME}://${Context.HOST_NAME}${redirectPath}`,
      state,
      'grant_options[]': isOnline ? 'per-user' : '',
    };
    /* eslint-enable @typescript-eslint/naming-convention */
 
    const queryString = querystring.stringify(query);
 
    return `https://${cleanShop}/admin/oauth/authorize?${queryString}`;
  },
 
  /**
   * Validates the received callback query.
   * If valid, will make the subsequent request to update the current session with the appropriate access token.
   * Throws errors for missing sessions and invalid callbacks.
   *
   * @param request Current HTTP Request
   * @param response Current HTTP Response
   * @param query Current HTTP Request Query, containing the information to be validated.
   *              Depending on framework, this may need to be cast as "unknown" before being passed.
   * @param isOnline Boolean value. Defaults to true (online access).
   * @returns SessionInterface
   */
  async validateAuthCallback(
    request: http.IncomingMessage,
    response: http.ServerResponse,
    query: AuthQuery,
  ): Promise<SessionInterface> {
    Context.throwIfUninitialized();
    Context.throwIfPrivateApp('Cannot perform OAuth for private apps');
 
    const stateFromCookie = getValueFromCookie(
      request,
      response,
      this.STATE_COOKIE_NAME,
    );
    deleteCookie(request, response, this.STATE_COOKIE_NAME);
 
    if (!stateFromCookie) {
      throw new ShopifyErrors.CookieNotFound(
        `Cannot complete OAuth process. Could not find an OAuth cookie for shop url: ${query.shop}`,
      );
    }
 
    if (!validQuery(query, stateFromCookie)) {
      throw new ShopifyErrors.InvalidOAuthError('Invalid OAuth callback.');
    }
 
    const isOnline = stateFromCookie.startsWith('online_');
 
    /* eslint-disable @typescript-eslint/naming-convention */
    const body = {
      client_id: Context.API_KEY,
      client_secret: Context.API_SECRET_KEY,
      code: query.code,
    };
    /* eslint-enable @typescript-eslint/naming-convention */
 
    const postParams = {
      path: '/admin/oauth/access_token',
      type: DataType.JSON,
      data: body,
    };
    const cleanShop = sanitizeShop(query.shop, true)!;
 
    const client = new HttpClient(cleanShop);
    const postResponse = await client.post(postParams);

    const session: Session = createSession(
      postResponse,
      cleanShop,
      stateFromCookie,
      isOnline,
    );
 
    if (!Context.IS_EMBEDDED_APP) {
      const cookies = new Cookies(request, response, {
        keys: [Context.API_SECRET_KEY],
        secure: true,
      });
 
      cookies.set(ShopifyOAuth.SESSION_COOKIE_NAME, session.id, {
        signed: true,
        expires: session.expires,
        sameSite: 'lax',
        secure: true,
      });
    }
 
    const sessionStored = await Context.SESSION_STORAGE.storeSession(session);
    if (!sessionStored) {
      throw new ShopifyErrors.SessionStorageError(
        'Session could not be saved. Please check your session storage functionality.',
      );
    }
I
    return session;
  },
 
  /**
   * Loads the current session id from the session cookie.
   *
   * @param request HTTP request object
   * @param response HTTP response object
   */
  getCookieSessionId(
    request: http.IncomingMessage,
    response: http.ServerResponse,
  ): string | undefined {
    return getValueFromCookie(request, response, this.SESSION_COOKIE_NAME);
  },
 
  /**
   * Builds a JWT session id from the current shop and user.
   *
   * @param shop Shopify shop domain
   * @param userId Current actor id
   */
  getJwtSessionId(shop: string, userId: string): string {
    return `${sanitizeShop(shop, true)}_${userId}`;
  },
 
  /**
   * Builds an offline session id for the given shop.
   *
   * @param shop Shopify shop domain
   */
  getOfflineSessionId(shop: string): string {
    return `offline_${sanitizeShop(shop, true)}`;
  },
 
  /**
   * Extracts the current session id from the request / response pair.
   *
   * @param request  HTTP request object
   * @param response HTTP response object
   * @param isOnline Whether to load online (default) or offline sessions (optional)
   */
  getCurrentSessionId(
    request: http.IncomingMessage,
    response: http.ServerResponse,
    isOnline = true,
  ): string | undefined {
    let currentSessionId: string | undefined;
 
    if (Context.IS_EMBEDDED_APP) {
      const authHeader = request.headers.authorization;
      if (authHeader) {
        const matches = authHeader.match(/^Bearer (.+)$/);
        if (!matches) {
          throw new ShopifyErrors.MissingJwtTokenError(
            'Missing Bearer token in authorization header',
          );
        }
 
        const jwtPayload = decodeSessionToken(matches[1]);
        const shop = jwtPayload.dest.replace(/^https:\/\//, '');
        if (isOnline) {
          currentSessionId = this.getJwtSessionId(shop, jwtPayload.sub);
        } else {
          currentSessionId = this.getOfflineSessionId(shop);
        }
      }
    }
 
    // Non-embedded apps will always load sessions using cookies. However, we fall back to the cookie session for
    // embedded apps to allow apps to load their skeleton page after OAuth, so they can set up App Bridge and get a new
    // JWT.
    if (!currentSessionId) {
      // We still want to get the offline session id from the cookie to make sure it's validated
      currentSessionId = getValueFromCookie(
        request,
        response,
        this.SESSION_COOKIE_NAME,
      );
    }
 
    return currentSessionId;
  },
};
 
/**
 * Uses the validation utils validateHmac, and safeCompare to assess whether the callback is valid.
 *
 * @param query Current HTTP Request Query
 * @param stateFromCookie state value from the current cookie
 */
function validQuery(query: AuthQuery, stateFromCookie: string): boolean {
  return validateHmac(query) && safeCompare(query.state, stateFromCookie);
}
 
/**
 * Loads a given value from the cookie
 *
 * @param request HTTP request object
 * @param response HTTP response object
 * @param name Name of the cookie to load
 */
function getValueFromCookie(
  request: http.IncomingMessage,
  response: http.ServerResponse,
  name: string,
): string | undefined {
  const cookies = new Cookies(request, response, {
    secure: true,
    keys: [Context.API_SECRET_KEY],
  });
  return cookies.get(name, {signed: true});
}
 
/**
 * Loads a given value from the cookie
 *
 * @param request HTTP request object
 * @param response HTTP response object
 * @param name Name of the cookie to load
 */
function deleteCookie(
  request: http.IncomingMessage,
  response: http.ServerResponse,
  name: string,
): void {
  const cookies = new Cookies(request, response, {
    secure: true,
    keys: [Context.API_SECRET_KEY],
  });
  cookies.set(name);
}
 
/**
 * Creates a new session from the response from the access token request.
 *
 * @param postResponse Response from the access token request
 * @param shop Shop url: {shop}.myshopify.com
 * @param stateFromCookie State from the cookie received by the OAuth callback
 * @param isOnline Boolean indicating if the access token is for online access
 * @returns SessionInterface
 */
function createSession(
  postResponse: RequestReturn,
  shop: string,
  stateFromCookie: string,
  isOnline: boolean,
): SessionInterface {
  let session: Session;
 
  if (isOnline) {
    let sessionId: string;
    const responseBody = postResponse.body as OnlineAccessResponse;
    const {access_token, scope, ...rest} = responseBody; // eslint-disable-line @typescript-eslint/naming-convention
    const sessionExpiration = new Date(
      Date.now() + responseBody.expires_in * 1000,
    );
 
    if (Context.IS_EMBEDDED_APP) {
      sessionId = ShopifyOAuth.getJwtSessionId(
        shop,
        `${(rest as OnlineAccessInfo).associated_user.id}`,
      );
    } else {
      sessionId = uuidv4();
    }
 
    session = new Session(sessionId, shop, stateFromCookie, isOnline);
    session.accessToken = access_token;
    session.scope = scope;
    session.expires = sessionExpiration;
    session.onlineAccessInfo = rest;
  } else {
    const responseBody = postResponse.body as AccessTokenResponse;
    session = new Session(
      ShopifyOAuth.getOfflineSessionId(shop),
      shop,
      stateFromCookie,
      isOnline,
    );
    session.accessToken = responseBody.access_token;
    session.scope = responseBody.scope;
  }
 
  return session;
}
 
export {ShopifyOAuth};