Skip to content

Commit

Permalink
added hydra-nextjs-ts example (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
amorey authored May 27, 2024
1 parent 2e8850d commit a085b65
Show file tree
Hide file tree
Showing 30 changed files with 7,338 additions and 0 deletions.
3 changes: 3 additions & 0 deletions hydra-nextjs-ts/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
SECURITY_HEADERS_ENABLE=false
HYDRA_ADMIN_URL=http://localhost:4445/

1 change: 1 addition & 0 deletions hydra-nextjs-ts/.env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SECURITY_HEADERS_ENABLE=true
3 changes: 3 additions & 0 deletions hydra-nextjs-ts/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
7 changes: 7 additions & 0 deletions hydra-nextjs-ts/LICENSE.txt
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.
76 changes: 76 additions & 0 deletions hydra-nextjs-ts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# ORY Hydra Next.js Reference Implementation (TypeScript)

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
* Written in TypeScript

## 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
```
10 changes: 10 additions & 0 deletions hydra-nextjs-ts/cypress.config.js
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
}
});
38 changes: 38 additions & 0 deletions hydra-nextjs-ts/cypress/e2e/csrf.cy.js
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);
});
});
});
});
27 changes: 27 additions & 0 deletions hydra-nextjs-ts/cypress/e2e/headers.cy.js
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);
}
});
});
15 changes: 15 additions & 0 deletions hydra-nextjs-ts/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const nextJest = require("next/jest");

const createJestConfig = nextJest({
dir: "./"
});

const customJestConfig = {
moduleNameMapper: {
'^@/lib/(.*)$': '<rootDir>/lib/$1',
'^@/pages/(.*)$': '<rootDir>/pages/$1'
},
testEnvironment: "jest-environment-jsdom"
};

module.exports = createJestConfig(customJestConfig);
9 changes: 9 additions & 0 deletions hydra-nextjs-ts/lib/hydra.ts
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 }
19 changes: 19 additions & 0 deletions hydra-nextjs-ts/lib/ssr-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { IncomingMessage } from 'http';
import type { GetServerSidePropsResult, Redirect } from 'next'
import { parseBody as nextParseBody } from 'next/dist/server/api-utils/node';
import { MockRequest } from 'node-mocks-http';
//import getRawBody from 'raw-body';

export function redirect(statusCode: 303 | 301 | 302 | 307 | 308, url: string): GetServerSidePropsResult<Redirect> {
return {
redirect: {
statusCode: statusCode,
destination: url,
},
};
}

export async function parseBody(req: IncomingMessage | MockRequest<any>, limit: string = '1mb'): Promise<any> {
if (req instanceof IncomingMessage) return await nextParseBody(req, limit);
return req.body;
}
21 changes: 21 additions & 0 deletions hydra-nextjs-ts/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import csrf from 'edge-csrf';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const csrfProtect = csrf();

export async function middleware(request: NextRequest) {
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;
}
5 changes: 5 additions & 0 deletions hydra-nextjs-ts/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
76 changes: 76 additions & 0 deletions hydra-nextjs-ts/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/** @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,
swcMinify: 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;
47 changes: 47 additions & 0 deletions hydra-nextjs-ts/ory/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
version: '3.8'

services:
hydra-migrate:
image: oryd/hydra:v1.10.7-sqlite
environment:
- DSN=sqlite:///var/lib/sqlite/db.sqlite?_fk=true&mode=rwc
command: migrate -c /etc/config/hydra/hydra.yml sql -e --yes
volumes:
- type: volume
source: hydra-sqlite
target: /var/lib/sqlite
read_only: false
- type: bind
source: ./hydra
target: /etc/config/hydra
restart: on-failure
networks:
- intranet

hydra:
depends_on:
- hydra-migrate
image: oryd/hydra:v1.10.7-sqlite
ports:
- "4444:4444" # Public port
- "4445:4445" # Admin port
- "5555:5555" # Port for hydra token user
environment:
- DSN=sqlite:///var/lib/sqlite/db.sqlite?_fk=true
command: serve -c /etc/config/hydra/hydra.yml all --dangerous-force-http
volumes:
- type: volume
source: hydra-sqlite
target: /var/lib/sqlite
read_only: false
- type: bind
source: ./hydra
target: /etc/config/hydra
restart: unless-stopped
networks:
- intranet
networks:
intranet:

volumes:
hydra-sqlite:
Loading

0 comments on commit a085b65

Please sign in to comment.