Skip to content

Commit fc581de

Browse files
committed
Initial code for plugin.
1 parent 3777228 commit fc581de

File tree

6 files changed

+298
-1
lines changed

6 files changed

+298
-1
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.idea
2+
node_modules

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
# fastify-https-always
2-
A fastify plugin to redirect http requests to https. Useful to ensure connections utilize secure HTTP connection URLs.
2+
This fastify plugin recognizes http requests and either redirects to https or disallows the request. Useful to ensure connections utilize secure HTTP connection URLs. The logic is very similar to the [express-ssl](https://github.com/jclem/express-ssl) plugin. It can examine the request headers to determine if a request has been forwarded from a TLS-terminating proxy, a common deployment model.
3+
4+
### Configuration
5+
6+
### fastify's trustProxy

package.json

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
{
2+
"name": "fastify-https-always",
3+
"version": "1.0.0",
4+
"description": "A fastify plugin to redirect http requests to https.",
5+
"main": "lib/index.js",
6+
"types": "lib/index.d.ts",
7+
"scripts": {
8+
"build": "tsc -p tsconfig.json",
9+
"test": "ts-node test/test.ts"
10+
},
11+
"repository": {
12+
"type": "git",
13+
"url": "git+https://github.com/mattbishop/fastify-https-always.git"
14+
},
15+
"keywords": [
16+
"fastify",
17+
"fastify-plugin",
18+
"https",
19+
"TLS",
20+
"SSL",
21+
"secure"
22+
],
23+
"author": "[email protected]",
24+
"license": "MIT",
25+
"bugs": {
26+
"url": "https://github.com/mattbishop/fastify-https-always/issues"
27+
},
28+
"homepage": "https://github.com/mattbishop/fastify-https-always#readme",
29+
"dependencies": {
30+
"@fastify/error": "3.0.0",
31+
"fastify-plugin": "^3.0.1",
32+
"undici": "5.8.2"
33+
},
34+
"devDependencies": {
35+
"@types/tape": "^4.13.2",
36+
"fastify": "^3.3.0",
37+
"tape": "^5.5.3",
38+
"ts-node": "^10.9.1",
39+
"typescript": "^4.7.4"
40+
}
41+
}

src/index.ts

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import createError from "@fastify/error"
2+
import {FastifyInstance, FastifyPluginOptions, FastifyReply, FastifyRequest, HookHandlerDoneFunction} from "fastify"
3+
import fp from "fastify-plugin"
4+
5+
6+
export interface HttpsAlwaysOptions extends FastifyPluginOptions {
7+
productionOnly: boolean
8+
enabled: boolean
9+
port: number
10+
redirect: boolean
11+
}
12+
13+
14+
type HttpsAlwaysContext = {
15+
port: string
16+
redirect: boolean
17+
}
18+
19+
20+
const HTTP_REQUIRED = createError(
21+
"FST_HTTPS_REQUIRED",
22+
"Please use HTTPS when communicating with this server.",
23+
403)
24+
25+
function handleRequest(ctx: HttpsAlwaysContext,
26+
request: FastifyRequest,
27+
reply: FastifyReply,
28+
next: HookHandlerDoneFunction) {
29+
const {
30+
port,
31+
redirect
32+
} = ctx
33+
34+
const {
35+
hostname,
36+
protocol,
37+
url
38+
} = request
39+
40+
41+
if (protocol !== "https") {
42+
if (redirect) {
43+
const portIdx = hostname.lastIndexOf(":")
44+
const host = portIdx > 0 ? hostname.substring(0, portIdx) : hostname
45+
const httpsUrl = `https://${host}${port}${url}`
46+
reply.redirect(301, httpsUrl)
47+
} else {
48+
next(HTTP_REQUIRED())
49+
return
50+
}
51+
}
52+
53+
next()
54+
}
55+
56+
57+
function plugin(fastify: FastifyInstance,
58+
opts: HttpsAlwaysOptions,
59+
next: () => void) {
60+
const {
61+
enabled = true,
62+
productionOnly = true,
63+
port,
64+
redirect = true,
65+
} = opts
66+
67+
if (enabled) {
68+
const inProd = process.env.NODE_ENV === "production"
69+
if (!productionOnly || (productionOnly && inProd)) {
70+
const ctx: HttpsAlwaysContext = {
71+
redirect,
72+
port: port ? `:${port}` : ""
73+
}
74+
fastify.addHook("onRequest", (q, p, d) => handleRequest(ctx, q, p, d))
75+
}
76+
}
77+
78+
next()
79+
}
80+
81+
82+
export default fp(plugin, {
83+
name: "fastify-https-always",
84+
fastify: ">=3.x"
85+
})

test/test.ts

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import test from "tape"
2+
import Fastify from "fastify"
3+
import {fetch} from "undici"
4+
import httpsAlwaysPlugin, {HttpsAlwaysOptions} from "../src"
5+
6+
7+
8+
// self-signed testing cert
9+
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
10+
11+
const URL = "/a/url"
12+
13+
test("default options for both fastify and https-always", async (t) => {
14+
process.env.NODE_ENV = "production"
15+
const http = Fastify()
16+
const https = Fastify({
17+
https: {
18+
key: httpsKey,
19+
cert: httpsCert
20+
}
21+
})
22+
http.register(httpsAlwaysPlugin)
23+
https.register(httpsAlwaysPlugin)
24+
25+
await http.listen({port: 3080})
26+
await https.listen({port: 3443})
27+
await http.ready()
28+
await https.ready()
29+
30+
t.plan(3)
31+
let result = await fetch(`http://localhost:3080${URL}`, {
32+
redirect: "manual"
33+
/*
34+
headers: {
35+
"x-forwarded-proto": "https",
36+
"x-forwarded-host": "localhost:3443"
37+
}
38+
*/
39+
})
40+
t.equal(result.status, 301, "http Permanently Moved")
41+
t.equal(result.headers.get("location"), `https://localhost${URL}`, "Location is https with no port")
42+
43+
result = await fetch("https://localhost:3443/")
44+
t.equal(result.status, 404, "https Not Found")
45+
46+
await http.close()
47+
await https.close()
48+
})
49+
50+
// test trustProxy
51+
52+
// test each default
53+
54+
55+
56+
const httpsKey = `-----BEGIN PRIVATE KEY-----
57+
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMIiJAhpsXD5D/+5
58+
owjvdgez8Nqm0KLIkld/nVNwzWAVnY12IhkC7hioqRRQCHhPNFElpGVBz3wLWWCj
59+
+koq69yuYiPZljmcBYK/r5JGwG+FFeVVqHjGNAVEbRH6Zvaz3aEqLyOj9wT/F5pJ
60+
BtIPZC1IgTrOw3xS2TjwN/FqL++HAgMBAAECgYAKO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A1UECAwQQnJpdGlzaCBDb2x1bWJpYTESMBAGA1UEBwwJ
80+
VmFuY291dmVyMR0wGwYDVQQKDBRmYXN0aWZ5LWh0dHBzLWFsd2F5czE7MDkGA1UE
81+
AwwyaHR0cHM6Ly9naXRodWIuY29tL21hdHRiaXNob3AvZmFzdGlmeS1odHRwcy1h
82+
bHdheXMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMIiJAhpsXD5D/+5owjv
83+
dgez8Nqm0KLIkld/nVNwzWAVnY12IhkC7hioqRRQCHhPNFElpGVBz3wLWWCj+koq
84+
69yuYiPZljmcBYK/r5JGwG+FFeVVqHjGNAVEbRH6Zvaz3aEqLyOj9wT/F5pJBtIP
85+
ZC1IgTrOw3xS2TjwN/FqL++HAgMBAAEwDQYJKoZIhvcNAQELBQADgYEAu588Rxko
86+
Y994JB9IowC5AWzFLSTm4fzp80JQc1Bv9IapeFxvBucumYEDmQN/opOEcBmzYqRb
87+
iCBkNwSchMbPKWdD0oCU0lIA5CC3jGfKPyFUaFS7RDtDE9GjKHf9iexFxPMNBR3a
88+
kjYW4mD0WOKNcXVIvYfRYtYimf0lyE0Fn9k=
89+
-----END CERTIFICATE-----
90+
`

tsconfig.json

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig.json to read more about this file */
4+
5+
/* Basic Options */
6+
// "incremental": true, /* Enable incremental compilation */
7+
"target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
8+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9+
// "lib": [], /* Specify library files to be included in the compilation. */
10+
// "allowJs": true, /* Allow javascript files to be compiled. */
11+
// "checkJs": true, /* Report errors in .js files. */
12+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
13+
"declaration": true, /* Generates corresponding '.d.ts' file. */
14+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15+
// "sourceMap": true, /* Generates corresponding '.map' file. */
16+
// "outFile": "./", /* Concatenate and emit output to single file. */
17+
"outDir": "./lib", /* Redirect output structure to the directory. */
18+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19+
// "composite": true, /* Enable project compilation */
20+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21+
// "removeComments": true, /* Do not emit comments to output. */
22+
// "noEmit": true, /* Do not emit outputs. */
23+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
24+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26+
27+
/* Strict Type-Checking Options */
28+
"strict": true, /* Enable all strict type-checking options. */
29+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30+
// "strictNullChecks": true, /* Enable strict null checks. */
31+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
32+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36+
37+
/* Additional Checks */
38+
// "noUnusedLocals": true, /* Report errors on unused locals. */
39+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
40+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42+
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
43+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
44+
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
45+
46+
/* Module Resolution Options */
47+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
48+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
49+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
50+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
51+
// "typeRoots": [], /* List of folders to include type definitions from. */
52+
// "types": [], /* Type declaration files to be included in compilation. */
53+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
54+
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
55+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
56+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
57+
58+
/* Source Map Options */
59+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
60+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
61+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
62+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
63+
64+
/* Experimental Options */
65+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
66+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
67+
68+
/* Advanced Options */
69+
"skipLibCheck": true, /* Skip type checking of declaration files. */
70+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
71+
},
72+
"include": [
73+
"src/**/*"
74+
]
75+
}

0 commit comments

Comments
 (0)