@shopify/shopify-app-remix
Version:
Shopify Remix - to simplify the building of Shopify Apps with Remix
65 lines (62 loc) • 2.39 kB
JavaScript
import { WebhookValidationErrorReason } from '@shopify/shopify-api';
import { adminClientFactory } from '../../clients/admin/factory.mjs';
import '@remix-run/server-runtime';
import { handleClientErrorFactory } from '../admin/helpers/handle-client-error.mjs';
import 'isbot';
import { createOrLoadOfflineSession } from '../helpers/create-or-load-offline-session.mjs';
function authenticateWebhookFactory(params) {
const { api, logger } = params;
return async function authenticate(request) {
if (request.method !== 'POST') {
logger.debug('Received a non-POST request for a webhook. Only POST requests are allowed.', { url: request.url, method: request.method });
throw new Response(undefined, {
status: 405,
statusText: 'Method not allowed',
});
}
const rawBody = await request.text();
const check = await api.webhooks.validate({
rawBody,
rawRequest: request,
});
if (!check.valid) {
if (check.reason === WebhookValidationErrorReason.InvalidHmac) {
logger.debug('Webhook HMAC validation failed', check);
throw new Response(undefined, {
status: 401,
statusText: 'Unauthorized',
});
}
else {
logger.debug('Webhook validation failed', check);
throw new Response(undefined, { status: 400, statusText: 'Bad Request' });
}
}
const session = await createOrLoadOfflineSession(check.domain, params);
const webhookContext = {
apiVersion: check.apiVersion,
shop: check.domain,
topic: check.topic,
webhookId: check.webhookId,
payload: JSON.parse(rawBody),
subTopic: check.subTopic || undefined,
session: undefined,
admin: undefined,
};
if (!session) {
return webhookContext;
}
const admin = adminClientFactory({
params,
session,
handleClientError: handleClientErrorFactory({ request }),
});
return {
...webhookContext,
session,
admin,
};
};
}
export { authenticateWebhookFactory };
//# sourceMappingURL=authenticate.mjs.map