|
| 1 | +"use strict"; |
| 2 | +var __importDefault = (this && this.__importDefault) || function (mod) { |
| 3 | + return (mod && mod.__esModule) ? mod : { "default": mod }; |
| 4 | +}; |
| 5 | +Object.defineProperty(exports, "__esModule", { value: true }); |
| 6 | +const error_1 = __importDefault(require("@fastify/error")); |
| 7 | +const fastify_plugin_1 = __importDefault(require("fastify-plugin")); |
| 8 | +const HTTPS_REQUIRED = (0, error_1.default)("FST_HTTPS_REQUIRED", "Please use HTTPS when communicating with this server.", 403); |
| 9 | +function handleRequest(ctx, request, reply, next) { |
| 10 | + const { port, redirect } = ctx; |
| 11 | + const { hostname, protocol, url } = request; |
| 12 | + if (protocol !== "https") { |
| 13 | + if (redirect) { |
| 14 | + const portIdx = hostname.lastIndexOf(":"); |
| 15 | + const host = portIdx > 0 ? hostname.substring(0, portIdx) : hostname; |
| 16 | + const httpsUrl = `https://${host}${port}${url}`; |
| 17 | + reply.redirect(301, httpsUrl); |
| 18 | + } |
| 19 | + else { |
| 20 | + next(HTTPS_REQUIRED()); |
| 21 | + return; |
| 22 | + } |
| 23 | + } |
| 24 | + next(); |
| 25 | +} |
| 26 | +function plugin(fastify, opts, next) { |
| 27 | + const { enabled = true, productionOnly = true, redirect = true, httpsPort } = opts; |
| 28 | + if (enabled) { |
| 29 | + const inProd = process.env.NODE_ENV === "production"; |
| 30 | + if (!productionOnly || inProd) { |
| 31 | + const ctx = { |
| 32 | + redirect, |
| 33 | + port: httpsPort ? `:${httpsPort}` : "" |
| 34 | + }; |
| 35 | + fastify.addHook("onRequest", (q, p, d) => handleRequest(ctx, q, p, d)); |
| 36 | + } |
| 37 | + } |
| 38 | + next(); |
| 39 | +} |
| 40 | +exports.default = (0, fastify_plugin_1.default)(plugin, { |
| 41 | + name: "fastify-https-always", |
| 42 | + fastify: ">=3.x" |
| 43 | +}); |
0 commit comments