-
-
Notifications
You must be signed in to change notification settings - Fork 68
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: reference implementation for Hydra+NextJS (#43)
* added hydra-nextjs example * chore: apply suggestions from code review Co-authored-by: Kevin Goslar <[email protected]> --------- Co-authored-by: Vincent <[email protected]> Co-authored-by: Kevin Goslar <[email protected]>
- Loading branch information
1 parent
7a57776
commit 2face08
Showing
35 changed files
with
7,533 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
node_modules | ||
.next | ||
.git | ||
.swc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
SECURITY_HEADERS_ENABLE=false | ||
HYDRA_ADMIN_URL=http://localhost:4445/ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
SECURITY_HEADERS_ENABLE=true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"extends": "next/core-web-vitals" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
FROM node:16.16-alpine3.16 AS builder | ||
|
||
RUN mkdir app | ||
WORKDIR /app | ||
|
||
# install dependencies | ||
COPY package.json yarn.lock ./ | ||
RUN yarn install --production --frozen-lockfile | ||
|
||
# copy code | ||
COPY . . | ||
|
||
# build | ||
RUN yarn build | ||
|
||
# remove unnecessary files | ||
RUN wget https://gobinaries.com/tj/node-prune && sh node-prune | ||
RUN node-prune | ||
|
||
ENTRYPOINT ["yarn", "start"] | ||
CMD [] | ||
|
||
# ----------------------------------------------------------------------------- | ||
|
||
FROM node:16.16-alpine3.16 | ||
|
||
RUN mkdir app | ||
WORKDIR /app | ||
|
||
COPY --from=builder /app/package.json ./ | ||
COPY --from=builder /app/node_modules ./node_modules | ||
COPY --from=builder /app/.env ./ | ||
COPY --from=builder /app/.env.production ./ | ||
COPY --from=builder /app/.next ./.next | ||
|
||
# run as `nextjs` | ||
RUN addgroup --system --gid 1001 nextjs | ||
RUN adduser --system --uid 1001 nextjs | ||
RUN chown nextjs:nextjs /app | ||
USER nextjs:nextjs | ||
|
||
# environment | ||
ENV NODE_ENV production | ||
ENV NEXT_TELEMETRY_DISABLED 1 | ||
ENV PORT 3000 | ||
|
||
EXPOSE 3000 | ||
|
||
ENTRYPOINT ["yarn", "start"] | ||
CMD [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2022 Andres Morey | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# ORY Hydra Next.js Reference Implementation | ||
|
||
This is a Next.js app which sets up a OAuth 2.0 and OpenID Connect Provider using [Ory Hydra](https://www.ory.sh/docs/hydra/) as a backend. It has an unstyled UI and doesn't implement user management but can be easily modified to fit into your existing system. | ||
|
||
# Features | ||
|
||
* User login, logout, registration, consent | ||
* CSRF protection with [edge-csrf](https://github.com/amorey/edge-csrf) | ||
* Super-strict HTTP security headers (configurable) | ||
* Client-side JavaScript disabled by default | ||
* Unit tests with Jest | ||
* E2E tests with Cypress | ||
* Start/stop Hydra in development using docker-compose | ||
* Easily customizable | ||
|
||
## Configuration | ||
|
||
This application can be configured using the following environment variables: | ||
|
||
| Name | Default | | ||
| ----------------------- | ---------------------- | | ||
| SECURITY_HEADERS_ENABLE | false | | ||
| HYDRA_ADMIN_URL | http://localhost:4445/ | | ||
|
||
## Development | ||
|
||
To install dependencies: | ||
|
||
```sh | ||
yarn install | ||
``` | ||
|
||
To run the Next.js app server in development mode: | ||
|
||
```sh | ||
yarn dev | ||
``` | ||
|
||
To start/stop hydra in development you can use the docker-compose file found in the `ory/` directory: | ||
|
||
```sh | ||
# start | ||
docker compose -f ory/docker-compose.yml up -d | ||
|
||
# stop | ||
docker compose -f ory/docker-compose.yml down | ||
|
||
# stop and remove mounted volumes | ||
docker compose -f ory/docker-compose.yml down -v | ||
docker compose -f ory/docker-compose.yml rm -fsv | ||
``` | ||
|
||
## Production | ||
|
||
To run the app in production first run the `build` command then run `start`: | ||
|
||
```sh | ||
yarn build | ||
yarn start | ||
``` | ||
|
||
## Testing | ||
|
||
To run the unit tests (using Jest): | ||
|
||
```sh | ||
yarn test | ||
``` | ||
|
||
To run the E2E tests (using Cypress): | ||
|
||
```sh | ||
yarn build | ||
yarn test-e2e | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
const { defineConfig } = require('cypress'); | ||
|
||
module.exports = defineConfig({ | ||
screenshotOnRunFailure: false, | ||
video: false, | ||
e2e: { | ||
baseUrl: 'http://localhost:3000', | ||
supportFile: false | ||
} | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
describe('CSRF protection tests', () => { | ||
const authPaths = [ | ||
'/sign-in', | ||
'/sign-up', | ||
'/sign-out', | ||
'/consent' | ||
]; | ||
|
||
context('should reject POST request without csrf token', () => { | ||
authPaths.forEach((path) => { | ||
it(path, async () => { | ||
const response = await cy.request({ | ||
method: 'POST', | ||
url: '/auth' + path, | ||
failOnStatusCode: false | ||
}); | ||
expect(response.status).to.equal(403); | ||
}); | ||
}); | ||
}); | ||
|
||
context('should reject POST request with invalid csrf token', () => { | ||
authPaths.forEach((path) => { | ||
it(path, async () => { | ||
const response = await cy.request({ | ||
method: 'POST', | ||
url: '/auth' + path, | ||
form: true, | ||
body: { | ||
csrf_token: 'invalid-token' | ||
}, | ||
failOnStatusCode: false | ||
}); | ||
expect(response.status).to.equal(403); | ||
}); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
describe('HTTP response header tests', () => { | ||
it('should have performance headers present', async () => { | ||
const response = await cy.request('GET', '/'); | ||
expect(response.headers).to.have.property('x-dns-prefetch-control', 'on'); | ||
}); | ||
|
||
it('should have security headers present', async () => { | ||
const securityHeaders = { | ||
'strict-transport-security': 'max-age=31536000 ; includeSubDomains', | ||
'x-frame-options': 'deny', | ||
'x-content-type-options': 'nosniff', | ||
'content-security-policy': "default-src 'self'; object-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; upgrade-insecure-requests; block-all-mixed-content", | ||
'x-permitted-cross-domain-policies': 'none', | ||
'referrer-policy': 'no-referrer', | ||
'cross-origin-embedder-policy': 'require-corp', | ||
'cross-origin-opener-policy': 'same-origin', | ||
'cross-origin-resource-policy': 'same-origin', | ||
'permissions-policy': 'accelerometer=(),autoplay=(),camera=(),display-capture=(),document-domain=(),encrypted-media=(),fullscreen=(),geolocation=(),gyroscope=(),magnetometer=(),microphone=(),midi=(),payment=(),picture-in-picture=(),publickey-credentials-get=(),screen-wake-lock=(),sync-xhr=(self),usb=(),web-share=(),xr-spatial-tracking=()' | ||
}; | ||
|
||
const response = await cy.request('GET', '/'); | ||
for (const [key, val] of Object.entries(securityHeaders)) { | ||
cy.log(key); | ||
expect(response.headers).to.have.property(key, val); | ||
} | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
const nextJest = require("next/jest"); | ||
|
||
const createJestConfig = nextJest({ | ||
dir: "./", | ||
}); | ||
|
||
const customJestConfig = { | ||
moduleDirectories: ["node_modules", "<rootDir>/"], | ||
testEnvironment: "jest-environment-jsdom", | ||
}; | ||
|
||
module.exports = createJestConfig(customJestConfig); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { AdminApi, Configuration } from '@ory/hydra-client'; | ||
|
||
const hydraAdmin = new AdminApi( | ||
new Configuration({ | ||
basePath: process.env.HYDRA_ADMIN_URL | ||
}) | ||
); | ||
|
||
export { hydraAdmin }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { parseBody as nextParseBody } from 'next/dist/server/api-utils/node'; | ||
|
||
export function redirect(statusCode, url) { | ||
return { | ||
redirect: { | ||
statusCode: statusCode, | ||
destination: url, | ||
}, | ||
}; | ||
} | ||
|
||
export function parseBody(req, limit) { | ||
// check cache | ||
if (req.body) return req.body; | ||
|
||
// parse and cache | ||
const body = nextParseBody(req, limit || '1mb'); | ||
req.body = body; | ||
return body; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import csrf from 'edge-csrf'; | ||
import { NextResponse } from 'next/server'; | ||
|
||
// initialize csrf protection function | ||
const csrfProtect = csrf(); | ||
|
||
export async function middleware(request) { | ||
const response = NextResponse.next(); | ||
|
||
// csrf protection | ||
const csrfError = await csrfProtect(request, response); | ||
|
||
// check result | ||
if (csrfError) { | ||
const url = request.nextUrl.clone(); | ||
url.pathname = '/api/csrf-invalid'; | ||
return NextResponse.rewrite(url); | ||
} | ||
|
||
return response; | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
/** @type {import('next').NextConfig} */ | ||
import yn from 'yn'; | ||
|
||
let headers = [ | ||
{ | ||
key: 'X-DNS-Prefetch-Control', | ||
value: 'on' | ||
}, | ||
]; | ||
|
||
// security headers (https://owasp.org/www-project-secure-headers/) | ||
if (yn(process.env.SECURITY_HEADERS_ENABLE) === true) { | ||
headers.push(...[ | ||
{ | ||
key: 'Strict-Transport-Security', | ||
value: 'max-age=31536000 ; includeSubDomains' | ||
}, | ||
{ | ||
key: 'X-Frame-Options', | ||
value: 'deny' | ||
}, | ||
{ | ||
key: 'X-Content-Type-Options', | ||
value: 'nosniff' | ||
}, | ||
{ | ||
key: 'Content-Security-Policy', | ||
value: "default-src 'self'; object-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; upgrade-insecure-requests; block-all-mixed-content" | ||
}, | ||
{ | ||
key: 'X-Permitted-Cross-Domain-Policies', | ||
value: 'none' | ||
}, | ||
{ | ||
key: 'Referrer-Policy', | ||
value: 'no-referrer' | ||
}, | ||
{ | ||
key: 'Cross-Origin-Embedder-Policy', | ||
value: 'require-corp' | ||
}, | ||
{ | ||
key: 'Cross-Origin-Opener-Policy', | ||
value: 'same-origin' | ||
}, | ||
{ | ||
key: 'Cross-Origin-Resource-Policy', | ||
value: 'same-origin' | ||
}, | ||
{ | ||
key: 'Permissions-Policy', | ||
value: 'accelerometer=(),autoplay=(),camera=(),display-capture=(),document-domain=(),encrypted-media=(),fullscreen=(),geolocation=(),gyroscope=(),magnetometer=(),microphone=(),midi=(),payment=(),picture-in-picture=(),publickey-credentials-get=(),screen-wake-lock=(),sync-xhr=(self),usb=(),web-share=(),xr-spatial-tracking=()' | ||
}, | ||
]); | ||
} | ||
|
||
const nextConfig = { | ||
reactStrictMode: true, | ||
webpack5: true, | ||
webpack: (config) => { | ||
// fixes npm packages that depend on `fs` module | ||
config.resolve.fallback = { fs: false }; | ||
return config; | ||
}, | ||
async headers() { | ||
return [ | ||
{ | ||
source: '/:path*', | ||
headers: headers | ||
} | ||
]; | ||
} | ||
}; | ||
|
||
export default nextConfig; |
Oops, something went wrong.