Skip to content

Commit

Permalink
chore: set up Prettier with husky pre-commit hook
Browse files Browse the repository at this point in the history
  • Loading branch information
jeandek committed Mar 8, 2024
1 parent 8b4c3ea commit 3d03d07
Show file tree
Hide file tree
Showing 22 changed files with 2,765 additions and 791 deletions.
15 changes: 4 additions & 11 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,14 @@
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
"plugin:@typescript-eslint/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"ignorePatterns": [ "/dist/**" ],
"plugins": ["@typescript-eslint"],
"ignorePatterns": ["/dist/**"],
"rules": {
"indent": ["error", 2],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "single", { "avoidEscape": true }],
"camelcase": [2, { "properties": "never" }],
"semi": ["error", "always"],
"comma-dangle": ["error", "always-multiline"],
"no-console": "off"
}
}
13 changes: 7 additions & 6 deletions .github/ISSUE_TEMPLATE/bug-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,21 @@ about: Report a bug encountered while using cognito-at-edge
labels: kind/bug
---

<!-- Please use this template while reporting a bug and provide as much info as possible. Not providing sufficient detail could result in your bug not being addressed in a timely manner. Thanks!
<!-- Please use this template while reporting a bug and provide as much info as possible. Not providing sufficient detail could result in your bug not being addressed in a timely manner. Thanks!
-->

#### What happened:

#### What did you expect to have happen:
#### What did you expect to have happen:

#### How to reproduce this (as precisely and succinctly as possible):
#### How to reproduce this (as precisely and succinctly as possible):

#### Anything else you think we should know?
#### Anything else you think we should know?

#### Environment:

#### Environment:
- version of cognito-at-edge being used:
- node version of code base which uses cognito-at-edge:
- other:

-
-
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/feature-request.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ labels: kind/feature

#### What would you like to be added:

#### Why is this needed:
#### Why is this needed:
5 changes: 2 additions & 3 deletions .github/ISSUE_TEMPLATE/help.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
name: "⁉️ Need help with cognito-at-edge?"
name: '⁉️ Need help with cognito-at-edge?'
about: Please file an issue in our help repo.

---

#### How can we help?
#### How can we help?
6 changes: 3 additions & 3 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
*Issue # (if available):*
_Issue # (if available):_

*Description of changes:*
_Description of changes:_

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
2 changes: 1 addition & 1 deletion .github/workflows/staticChecks.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Static checks

on: [ pull_request, push ]
on: [pull_request, push]

jobs:
ci-static-checks:
Expand Down
1 change: 1 addition & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
npx lint-staged
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CHANGELOG.md
package-lock.json
3 changes: 3 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"singleQuote": true
}
1 change: 1 addition & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
## Code of Conduct

This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
[email protected] with any additional questions or comments.
24 changes: 12 additions & 12 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,23 @@ documentation, we greatly value feedback and contributions from our community.
Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
information to effectively respond to your bug report or contribution.


## Reporting Bugs/Feature Requests

We welcome you to use the GitHub issue tracker to report bugs or suggest features.

When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:

* A reproducible test case or series of steps
* The version of our code being used
* Any modifications you've made relevant to the bug
* Anything unusual about your environment or deployment

- A reproducible test case or series of steps
- The version of our code being used
- Any modifications you've made relevant to the bug
- Anything unusual about your environment or deployment

## Contributing via Pull Requests

Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:

1. You are working against the latest source on the *master* branch.
1. You are working against the latest source on the _master_ branch.
2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
3. You open an issue to discuss any significant work - we would hate for your time to be wasted.

Expand All @@ -39,8 +38,8 @@ To send us a pull request, please:
GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
[creating a pull request](https://help.github.com/articles/creating-a-pull-request/).


## Finding contributions to work on

Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.

## Development Process
Expand All @@ -55,21 +54,22 @@ npm install
```

### Testing the code
Tests are written using jest. To run tests invoke

Tests are written using jest. To run tests invoke

```
npm test
```


## Code of Conduct

This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
[email protected] with any additional questions or comments.


## Security issue notifications
If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.

If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.

## Licensing

Expand Down
81 changes: 41 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Cognito@Edge

*Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge.*
_Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge._

This Node.js package helps you verify that users making requests to a CloudFront distribution are authenticated using a Cognito user pool. It achieves that by looking at the cookies included in the request and, if the requester is not authenticated, it will redirect then to the user pool's login page.

Expand All @@ -20,17 +20,17 @@ If you need more configuration options (e.g. bring your own user pool or CloudFr

The preferred way to install the AWS cognito-at-edge for Node.js is to use the [npm](http://npmjs.org/) package manager for Node.js. Simply type the following into a terminal window:

``` shell
```shell
npm install cognito-at-edge
```

### Usage

To use the package, you must create a [Lambda@Edge function](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html) and associate it with the CloudFront distribution's *viewer request* events.
To use the package, you must create a [Lambda@Edge function](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html) and associate it with the CloudFront distribution's _viewer request_ events.

Within your Lambda@Edge function, you can import and use the `Authenticator` class as shown here:

``` js
```js
const { Authenticator } = require('cognito-at-edge');

const authenticator = new Authenticator({
Expand All @@ -50,40 +50,40 @@ For an explanation of the interactions between CloudFront, Cognito and Lambda@Ed

### Authenticator(params)

* `params` *Object* Authenticator parameters:
* `region` *string* Cognito UserPool region (eg: `us-east-1`)
* `userPoolId` *string* Cognito UserPool ID (eg: `us-east-1_tyo1a1FHH`)
* `userPoolAppId` *string* Cognito UserPool Application ID (eg: `63gcbm2jmskokurt5ku9fhejc6`)
* `userPoolAppSecret` *string* (Optional) Cognito UserPool Application Secret (eg: `oh470px2i0uvy4i2ha6sju0vxe4ata9ol3m63ufhs2t8yytwjn7p`)
* `userPoolDomain` *string* Cognito UserPool domain (eg: `your-domain.auth.us-east-1.amazoncognito.com`)
* `cookieExpirationDays` *number* (Optional) Number of day to set cookies expiration date, default to 365 days (eg: `365`). It's recommended to set this value to match `refreshTokenValidity` parameter of the pool client.
* `disableCookieDomain` *boolean* (Optional) Sets domain attribute in cookies, defaults to false (eg: `false`)
* `httpOnly` *boolean* (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: `false`). Note, if this is set to `true`, the cookies will not be accessible to Amplify auth if you are using it client side.
* `sameSite` *Strict | Lax | None* (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: `SameSite=None`).
* `parseAuthPath` *string* (Optional) URI path used as redirect target after successful Cognito authentication (eg: `/oauth2/idpresponse`), defaults to the web domain root. Needs to be a path that is handled by the library. When using this parameter, you should also provide a value for `cookiePath` to ensure your cookies are available for the right paths.
* `cookiePath` *string* (Optional) Sets Path attribute in cookies
* `cookieDomain` *string* (Optional) Sets the domain name used for the token cookies
* `cookieSettingsOverrides` *object* (Optional) Cookie settings overrides for different token cookies -- idToken, accessToken and refreshToken
* `idToken` *CookieSettings* (Optional) Setting overrides to use for idToken
* `expirationDays` *number* (Optional) Number of day to set cookies expiration date, default to 365 days (eg: `365`). It's recommended to set this value to match `refreshTokenValidity` parameter of the pool client.
* `path` *string* (Optional) Sets Path attribute in cookies
* `httpOnly` *boolean* (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: `false`). Note, if this is set to `true`, the cookies will not be accessible to Amplify auth if you are using it client side.
* `sameSite` *Strict | Lax | None* (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: `SameSite=None`).
* `accessToken` *CookieSettings* (Optional) Setting overrides to use for accessToken
* `refreshToken` *CookieSettings* (Optional) Setting overrides to use for refreshToken
* `logoutConfiguration` *object* (Optional) Enables logout functionality
* `logoutUri` *string* URI path, which when matched with request, logs user out by revoking tokens and clearing cookies
* `logoutRedirectUri` *string* The URI to which the user is redirected to after logging them out
* `csrfProtection` *object* (Optional) Enables CSRF protection
* `nonceSigningSecret` *string* Secret used for signing nonce cookies
* `logLevel` *string* (Optional) Logging level. Default: `'silent'`. One of `'fatal'`, `'error'`, `'warn'`, `'info'`, `'debug'`, `'trace'` or `'silent'`.

*This is the class constructor.*
- `params` _Object_ Authenticator parameters:
- `region` _string_ Cognito UserPool region (eg: `us-east-1`)
- `userPoolId` _string_ Cognito UserPool ID (eg: `us-east-1_tyo1a1FHH`)
- `userPoolAppId` _string_ Cognito UserPool Application ID (eg: `63gcbm2jmskokurt5ku9fhejc6`)
- `userPoolAppSecret` _string_ (Optional) Cognito UserPool Application Secret (eg: `oh470px2i0uvy4i2ha6sju0vxe4ata9ol3m63ufhs2t8yytwjn7p`)
- `userPoolDomain` _string_ Cognito UserPool domain (eg: `your-domain.auth.us-east-1.amazoncognito.com`)
- `cookieExpirationDays` _number_ (Optional) Number of day to set cookies expiration date, default to 365 days (eg: `365`). It's recommended to set this value to match `refreshTokenValidity` parameter of the pool client.
- `disableCookieDomain` _boolean_ (Optional) Sets domain attribute in cookies, defaults to false (eg: `false`)
- `httpOnly` _boolean_ (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: `false`). Note, if this is set to `true`, the cookies will not be accessible to Amplify auth if you are using it client side.
- `sameSite` _Strict | Lax | None_ (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: `SameSite=None`).
- `parseAuthPath` _string_ (Optional) URI path used as redirect target after successful Cognito authentication (eg: `/oauth2/idpresponse`), defaults to the web domain root. Needs to be a path that is handled by the library. When using this parameter, you should also provide a value for `cookiePath` to ensure your cookies are available for the right paths.
- `cookiePath` _string_ (Optional) Sets Path attribute in cookies
- `cookieDomain` _string_ (Optional) Sets the domain name used for the token cookies
- `cookieSettingsOverrides` _object_ (Optional) Cookie settings overrides for different token cookies -- idToken, accessToken and refreshToken
- `idToken` _CookieSettings_ (Optional) Setting overrides to use for idToken
- `expirationDays` _number_ (Optional) Number of day to set cookies expiration date, default to 365 days (eg: `365`). It's recommended to set this value to match `refreshTokenValidity` parameter of the pool client.
- `path` _string_ (Optional) Sets Path attribute in cookies
- `httpOnly` _boolean_ (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: `false`). Note, if this is set to `true`, the cookies will not be accessible to Amplify auth if you are using it client side.
- `sameSite` _Strict | Lax | None_ (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: `SameSite=None`).
- `accessToken` _CookieSettings_ (Optional) Setting overrides to use for accessToken
- `refreshToken` _CookieSettings_ (Optional) Setting overrides to use for refreshToken
- `logoutConfiguration` _object_ (Optional) Enables logout functionality
- `logoutUri` _string_ URI path, which when matched with request, logs user out by revoking tokens and clearing cookies
- `logoutRedirectUri` _string_ The URI to which the user is redirected to after logging them out
- `csrfProtection` _object_ (Optional) Enables CSRF protection
- `nonceSigningSecret` _string_ Secret used for signing nonce cookies
- `logLevel` _string_ (Optional) Logging level. Default: `'silent'`. One of `'fatal'`, `'error'`, `'warn'`, `'info'`, `'debug'`, `'trace'` or `'silent'`.

_This is the class constructor._

### handle(request)

* `request` *Object* Lambda@Edge request object
* See AWS doc for details: [Lambda@Edge events](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html)
- `request` _Object_ Lambda@Edge request object
- See AWS doc for details: [Lambda@Edge events](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html)

Use it as your Lambda Handler. It will authenticate each query.

Expand All @@ -93,9 +93,11 @@ exports.handler = async (request) => authenticator.handle(request);
```

### Authentication Gateway Setup

This library can also be used in an authentication gateway setup. If you have a frontend client application that uses AWS Cognito for authentication, it fetches and stores authentication tokens in the browser. Depending on where the tokens are stored in the browser (localStorage, cookies, sessionStorage), they may susceptible to token theft and XSS (Cross-Site Scripting). In order to mitigate this risk, a set of Lambda@Edge handlers can be deployed on a CloudFront distribution which act as an authentication gateway intermediary between the frontend app and Cognito. These handlers will authenticate and fetch tokens on the frontend's behalf and set them as [Secure; HttpOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) tokens inside the browser, thereby restricting access to other scripts in the app.

Handlers

1. `handleSignIn` (Can be mapped to `/signIn` in Cloudfront setup): Redirect users to Cognito's authorize endpoint after replacing redirect uri with its own -- for instance, `/parseAuth`.
1. `handleParseAuth` (Can be mapped to `/parseAuth`): Exchange Cognito's OAuth code for tokens. Store tokens in browser as HttpOnly cookies
1. `handleRefreshToken` (Can be mapped to `/refreshToken`): Refresh idToken and accessToken using refreshToken
Expand All @@ -109,13 +111,12 @@ exports.handler = async (request) => authenticator.handleSignIn(request);
// Similar setup for parseAuth, refreshToken and signOut handlers
```


### Getting Help

The best way to interact with our team is through GitHub. You can [open an issue](https://github.com/awslabs/cognito-at-edge/issues/new/choose)
and choose from one of our templates for [bug reports](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=bug%2C+needs-triage&template=---bug-report.md&title=),
[feature requests](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=feature-request&template=---feature-request.md&title=) or
[question](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=question%2C+needs-triage&template=---questions---help.md&title=).
The best way to interact with our team is through GitHub. You can [open an issue](https://github.com/awslabs/cognito-at-edge/issues/new/choose)
and choose from one of our templates for [bug reports](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=bug%2C+needs-triage&template=---bug-report.md&title=),
[feature requests](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=feature-request&template=---feature-request.md&title=) or
[question](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=question%2C+needs-triage&template=---questions---help.md&title=).

## Contributing

Expand Down
Loading

0 comments on commit 3d03d07

Please sign in to comment.