UNPKG

@agnostack/next-shopify

Version:

Please contact agnoStack via info@agnostack.com for any questions

105 lines 6.49 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleSessionToken = void 0; const js_base64_1 = require("js-base64"); const jsonwebtoken_1 = require("jsonwebtoken"); const uuid_1 = require("uuid"); const verifyd_1 = require("@agnostack/verifyd"); const utils_1 = require("../../../utils"); const shared_1 = require("../../../../shared"); // NOTE: typically handling: "/api/token" const handleSessionToken = (serverRuntimeConfig, data) => { const _a = data !== null && data !== void 0 ? data : {}, { signingSecret: _signingSecret, returnResponse = true } = _a, signingData = __rest(_a, ["signingSecret", "returnResponse"]); const { APP_CONFIG } = serverRuntimeConfig !== null && serverRuntimeConfig !== void 0 ? serverRuntimeConfig : {}; const _getVerificationHelpers = (0, verifyd_1.getVerificationHelpers)(serverRuntimeConfig); return (req, res) => __awaiter(void 0, void 0, void 0, function* () { var _b, _c; const { host } = (_b = req.query) !== null && _b !== void 0 ? _b : {}; const _d = (_c = req.headers) !== null && _c !== void 0 ? _c : {}, { 'x-shopify-app-installation-id': shopifyAppInstallationId, 'x-shopify-app-id': shopifyAppId, 'x-app-installation-id': appInstallationId = shopifyAppInstallationId, 'x-app-id': appId = shopifyAppId, // TODO: pass along providerSetId?? 'x-client-id': clientId, 'x-shop-domain': shopDomain, 'x-shopify-shop-domain': shopifyShopDomain, 'x-shopify-shop': shop = shopifyShopDomain !== null && shopifyShopDomain !== void 0 ? shopifyShopDomain : shopDomain } = _d, headers = __rest(_d, ['x-shopify-app-installation-id', 'x-shopify-app-id', 'x-app-installation-id', 'x-app-id', 'x-client-id', 'x-shop-domain', 'x-shopify-shop-domain', 'x-shopify-shop']); const handleResponse = (body, statusCode = 200) => { if (returnResponse) { return res.status(statusCode).json(body); } return { statusCode, body }; }; // TODO: un-btoa the host and check?? if ((0, shared_1.stringEmpty)(shop) || (0, shared_1.stringEmpty)(host)) { return handleResponse({ message: 'Missing required param' }, 412); } let requestBody; let processResponse; try { ({ requestBody, processResponse } = yield _getVerificationHelpers(req)); } catch (error) { if (error instanceof verifyd_1.VerificationError) { return handleResponse(Object.assign({ message: error.message }, error.data), error.code); } return handleResponse({ message: 'Verification error' }, 403); } try { const appClaims = Object.entries(headers).reduce((_appClaims, [headerKey, headerValue]) => (Object.assign(Object.assign({}, _appClaims), headerKey.startsWith('x-shopify-app-metafield-') && { [(0, shared_1.snakecase)(headerKey.replace('x-shopify-app-metafield-', ''))]: headerValue, })), Object.assign(Object.assign({}, appId && { app_id: (0, utils_1.normalizeShopifyId)(appId).id }), appInstallationId && { installation_id: (0, utils_1.normalizeShopifyId)(appInstallationId).id })); const _e = requestBody !== null && requestBody !== void 0 ? requestBody : {}, { sub, aud: _aud } = _e, body = __rest(_e, ["sub", "aud"]); const aud = [clientId, _aud, APP_CONFIG.apiKey].find(shared_1.stringNotEmpty); let { dest, iss, sid, jti } = body, tokenBody = __rest(body, ["dest", "iss", "sid", "jti"]); if ((0, shared_1.stringEmpty)(dest)) { dest = shop; } if ((0, shared_1.stringEmpty)(iss)) { iss = js_base64_1.Base64.decode(host); } if ((0, shared_1.stringEmpty)(sid)) { sid = (0, uuid_1.v4)(); } if ((0, shared_1.stringEmpty)(jti)) { jti = (0, uuid_1.v4)(); sid = `${sid}.${jti}`; } const payload = Object.assign(Object.assign(Object.assign({ shop, host, iss, // NOTE: shop's admin domain (<shop-name.myshopify.com/admin>) dest, // NOTE: shop's domain (<shop-name.myshopify.com>) jti, // NOTE: Secure random UUID sid, // NOTE: Unique session ID per user and app aud }, sub && { sub }), appClaims), tokenBody); // NOTE: signingSecret should only be sent in here from the /api/token/zendesk endpoint const signingSecret = _signingSecret || (0, utils_1.generateHMAC)((0, shared_1.objectToSortedString)(payload), APP_CONFIG.apiSecretKey); const token = (0, jsonwebtoken_1.sign)(payload, signingSecret, signingData); if ((0, shared_1.stringEmpty)(token)) { throw new Error('Error signing token'); } const response = yield processResponse({ token }); return handleResponse(response); } catch (error) { console.error('Error generating session token', error); return handleResponse({ message: 'Error generating session token' }, 500); } }); }; exports.handleSessionToken = handleSessionToken; //# sourceMappingURL=token.js.map