@hazeljs/oauth 0.2.0-beta.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +192 -0
- package/README.md +200 -0
- package/dist/guards/oauth-state.guard.d.ts +15 -0
- package/dist/guards/oauth-state.guard.d.ts.map +1 -0
- package/dist/guards/oauth-state.guard.js +43 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/oauth.controller.d.ts +29 -0
- package/dist/oauth.controller.d.ts.map +1 -0
- package/dist/oauth.controller.js +134 -0
- package/dist/oauth.module.d.ts +5 -0
- package/dist/oauth.module.d.ts.map +1 -0
- package/dist/oauth.module.js +27 -0
- package/dist/oauth.service.d.ts +36 -0
- package/dist/oauth.service.d.ts.map +1 -0
- package/dist/oauth.service.js +239 -0
- package/dist/providers/facebook.provider.d.ts +11 -0
- package/dist/providers/facebook.provider.d.ts.map +1 -0
- package/dist/providers/facebook.provider.js +63 -0
- package/dist/providers/github.provider.d.ts +11 -0
- package/dist/providers/github.provider.d.ts.map +1 -0
- package/dist/providers/github.provider.js +79 -0
- package/dist/providers/google.provider.d.ts +11 -0
- package/dist/providers/google.provider.d.ts.map +1 -0
- package/dist/providers/google.provider.js +61 -0
- package/dist/providers/index.d.ts +7 -0
- package/dist/providers/index.d.ts.map +1 -0
- package/dist/providers/index.js +22 -0
- package/dist/providers/microsoft.provider.d.ts +11 -0
- package/dist/providers/microsoft.provider.d.ts.map +1 -0
- package/dist/providers/microsoft.provider.js +62 -0
- package/dist/providers/provider.types.d.ts +62 -0
- package/dist/providers/provider.types.d.ts.map +1 -0
- package/dist/providers/provider.types.js +5 -0
- package/dist/providers/twitter.provider.d.ts +11 -0
- package/dist/providers/twitter.provider.d.ts.map +1 -0
- package/dist/providers/twitter.provider.js +67 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2024 HazelJS Team
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
22
|
+
|
|
23
|
+
1. Definitions.
|
|
24
|
+
|
|
25
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
26
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
27
|
+
|
|
28
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
29
|
+
the copyright owner that is granting the License.
|
|
30
|
+
|
|
31
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
32
|
+
other entities that control, are controlled by, or are under common
|
|
33
|
+
control with that entity. For the purposes of this definition,
|
|
34
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
35
|
+
direction or management of such entity, whether by contract or
|
|
36
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
37
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
38
|
+
|
|
39
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
40
|
+
exercising permissions granted by this License.
|
|
41
|
+
|
|
42
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
43
|
+
including but not limited to software source code, documentation
|
|
44
|
+
source, and configuration files.
|
|
45
|
+
|
|
46
|
+
"Object" form shall mean any form resulting from mechanical
|
|
47
|
+
transformation or translation of a Source form, including but
|
|
48
|
+
not limited to compiled object code, generated documentation,
|
|
49
|
+
and conversions to other media types.
|
|
50
|
+
|
|
51
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
52
|
+
Object form, made available under the License, as indicated by a
|
|
53
|
+
copyright notice that is included in or attached to the work
|
|
54
|
+
(an example is provided in the Appendix below).
|
|
55
|
+
|
|
56
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
57
|
+
form, that is based on (or derived from) the Work and for which the
|
|
58
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
59
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
60
|
+
of this License, Derivative Works shall not include works that remain
|
|
61
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
62
|
+
the Work and Derivative Works thereof.
|
|
63
|
+
|
|
64
|
+
"Contribution" shall mean any work of authorship, including
|
|
65
|
+
the original version of the Work and any modifications or additions
|
|
66
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
67
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
68
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
69
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
70
|
+
means any form of electronic, verbal, or written communication sent
|
|
71
|
+
to the Licensor or its representatives, including but not limited to
|
|
72
|
+
communication on electronic mailing lists, source code control systems,
|
|
73
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
74
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
75
|
+
excluding communication that is conspicuously marked or otherwise
|
|
76
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
77
|
+
|
|
78
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
79
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
80
|
+
subsequently incorporated within the Work.
|
|
81
|
+
|
|
82
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
83
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
84
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
85
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
86
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
87
|
+
Work and such Derivative Works in Source or Object form.
|
|
88
|
+
|
|
89
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
90
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
91
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
92
|
+
(except as stated in this section) patent license to make, have made,
|
|
93
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
94
|
+
where such license applies only to those patent claims licensable
|
|
95
|
+
by such Contributor that are necessarily infringed by their
|
|
96
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
97
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
98
|
+
institute patent litigation against any entity (including a
|
|
99
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
100
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
101
|
+
or contributory patent infringement, then any patent licenses
|
|
102
|
+
granted to You under this License for that Work shall terminate
|
|
103
|
+
as of the date such litigation is filed.
|
|
104
|
+
|
|
105
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
106
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
107
|
+
modifications, and in Source or Object form, provided that You
|
|
108
|
+
meet the following conditions:
|
|
109
|
+
|
|
110
|
+
(a) You must give any other recipients of the Work or
|
|
111
|
+
Derivative Works a copy of this License; and
|
|
112
|
+
|
|
113
|
+
(b) You must cause any modified files to carry prominent notices
|
|
114
|
+
stating that You changed the files; and
|
|
115
|
+
|
|
116
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
117
|
+
that You distribute, all copyright, patent, trademark, and
|
|
118
|
+
attribution notices from the Source form of the Work,
|
|
119
|
+
excluding those notices that do not pertain to any part of
|
|
120
|
+
the Derivative Works; and
|
|
121
|
+
|
|
122
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
123
|
+
distribution, then any Derivative Works that You distribute must
|
|
124
|
+
include a readable copy of the attribution notices contained
|
|
125
|
+
within such NOTICE file, excluding those notices that do not
|
|
126
|
+
pertain to any part of the Derivative Works, in at least one
|
|
127
|
+
of the following places: within a NOTICE text file distributed
|
|
128
|
+
as part of the Derivative Works; within the Source form or
|
|
129
|
+
documentation, if provided along with the Derivative Works; or,
|
|
130
|
+
within a display generated by the Derivative Works, if and
|
|
131
|
+
wherever such third-party notices normally appear. The contents
|
|
132
|
+
of the NOTICE file are for informational purposes only and
|
|
133
|
+
do not modify the License. You may add Your own attribution
|
|
134
|
+
notices within Derivative Works that You distribute, alongside
|
|
135
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
136
|
+
that such additional attribution notices cannot be construed
|
|
137
|
+
as modifying the License.
|
|
138
|
+
|
|
139
|
+
You may add Your own copyright statement to Your modifications and
|
|
140
|
+
may provide additional or different license terms and conditions
|
|
141
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
142
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
143
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
144
|
+
the conditions stated in this License.
|
|
145
|
+
|
|
146
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
147
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
148
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
149
|
+
this License, without any additional terms or conditions.
|
|
150
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
151
|
+
the terms of any separate license agreement you may have executed
|
|
152
|
+
with Licensor regarding such Contributions.
|
|
153
|
+
|
|
154
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
155
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
156
|
+
except as required for reasonable and customary use in describing the
|
|
157
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
158
|
+
|
|
159
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
160
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
161
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
162
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
163
|
+
implied, including, without limitation, any warranties or conditions
|
|
164
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
165
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
166
|
+
appropriateness of using or redistributing the Work and assume any
|
|
167
|
+
risks associated with Your exercise of permissions under this License.
|
|
168
|
+
|
|
169
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
170
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
171
|
+
unless required by applicable law (such as deliberate and grossly
|
|
172
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
173
|
+
liable to You for damages, including any direct, indirect, special,
|
|
174
|
+
incidental, or consequential damages of any character arising as a
|
|
175
|
+
result of this License or out of the use or inability to use the
|
|
176
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
177
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
178
|
+
other commercial damages or losses), even if such Contributor
|
|
179
|
+
has been advised of the possibility of such damages.
|
|
180
|
+
|
|
181
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
182
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
183
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
184
|
+
or other liability obligations and/or rights consistent with this
|
|
185
|
+
License. However, in accepting such obligations, You may act only
|
|
186
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
187
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
188
|
+
defend, and hold each Contributor harmless for any liability
|
|
189
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
190
|
+
of your accepting any such warranty or additional liability.
|
|
191
|
+
|
|
192
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# @hazeljs/oauth
|
|
2
|
+
|
|
3
|
+
**"Sign in with Google" in 5 minutes.**
|
|
4
|
+
|
|
5
|
+
Google, Microsoft, GitHub, Facebook, Twitter — one config, ready-made routes. PKCE, user profiles, JWT integration. Built on [Arctic](https://arcticjs.dev) — 50+ providers available if you need more.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@hazeljs/oauth)
|
|
8
|
+
[](https://www.npmjs.com/package/@hazeljs/oauth)
|
|
9
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **Multi-Provider** — Google, Microsoft Entra ID, GitHub, Facebook, Twitter
|
|
14
|
+
- **PKCE Support** — Automatic for Google, Microsoft, Twitter
|
|
15
|
+
- **User Profile** — Fetches id, email, name, picture from provider APIs
|
|
16
|
+
- **Ready-Made Routes** — Optional `/auth/:provider` and `/auth/:provider/callback`
|
|
17
|
+
- **JWT Integration** — Use with `@hazeljs/auth` for session tokens
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install @hazeljs/oauth
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Or with the HazelJS CLI:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
hazel add oauth
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quick Start
|
|
32
|
+
|
|
33
|
+
### 1. Configure Providers
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { HazelModule } from '@hazeljs/core';
|
|
37
|
+
import { OAuthModule } from '@hazeljs/oauth';
|
|
38
|
+
|
|
39
|
+
@HazelModule({
|
|
40
|
+
imports: [
|
|
41
|
+
OAuthModule.forRoot({
|
|
42
|
+
providers: {
|
|
43
|
+
google: {
|
|
44
|
+
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
45
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
46
|
+
redirectUri: process.env.OAUTH_REDIRECT_URI!,
|
|
47
|
+
},
|
|
48
|
+
github: {
|
|
49
|
+
clientId: process.env.GITHUB_CLIENT_ID!,
|
|
50
|
+
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
51
|
+
redirectUri: process.env.OAUTH_REDIRECT_URI!,
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
}),
|
|
55
|
+
],
|
|
56
|
+
})
|
|
57
|
+
export class AppModule {}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 2. Use Built-in Routes
|
|
61
|
+
|
|
62
|
+
The `OAuthController` provides:
|
|
63
|
+
|
|
64
|
+
- **GET /auth/:provider** — Redirects to provider (google, microsoft, github, facebook, twitter)
|
|
65
|
+
- **GET /auth/:provider/callback** — Handles callback, returns `{ accessToken, user }`
|
|
66
|
+
|
|
67
|
+
Example: User visits `/auth/google` → authenticates → callback returns tokens and profile.
|
|
68
|
+
|
|
69
|
+
### 3. Custom Flow with OAuthService
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { OAuthService } from '@hazeljs/oauth';
|
|
73
|
+
|
|
74
|
+
@Injectable()
|
|
75
|
+
export class AuthController {
|
|
76
|
+
constructor(private oauth: OAuthService) {}
|
|
77
|
+
|
|
78
|
+
@Get('login/:provider')
|
|
79
|
+
login(@Param('provider') provider: string, @Res() res: Response) {
|
|
80
|
+
const { url, state, codeVerifier } = this.oauth.getAuthorizationUrl(provider);
|
|
81
|
+
// Store state + codeVerifier in cookies
|
|
82
|
+
res.redirect(url);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
@Get('callback')
|
|
86
|
+
async callback(@Query() q: { code: string; state: string }, @Req() req: Request) {
|
|
87
|
+
const { codeVerifier } = getFromCookies(req);
|
|
88
|
+
const result = await this.oauth.handleCallback(
|
|
89
|
+
'google', q.code, q.state, codeVerifier
|
|
90
|
+
);
|
|
91
|
+
// result: { accessToken, refreshToken?, expiresAt?, user }
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Supported Providers
|
|
98
|
+
|
|
99
|
+
| Provider | PKCE | Default Scopes |
|
|
100
|
+
|----------|------|----------------|
|
|
101
|
+
| Google | Yes | openid, profile, email |
|
|
102
|
+
| Microsoft | Yes | openid, profile, email |
|
|
103
|
+
| GitHub | No | user:email |
|
|
104
|
+
| Facebook | No | email, public_profile |
|
|
105
|
+
| Twitter | Yes | users.read, tweet.read |
|
|
106
|
+
|
|
107
|
+
## Configuration
|
|
108
|
+
|
|
109
|
+
### Microsoft (optional tenant)
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
microsoft: {
|
|
113
|
+
clientId: '...',
|
|
114
|
+
clientSecret: '...',
|
|
115
|
+
redirectUri: '...',
|
|
116
|
+
tenant: 'common', // or your Azure AD tenant ID
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Twitter (optional client secret)
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
twitter: {
|
|
124
|
+
clientId: '...',
|
|
125
|
+
redirectUri: '...',
|
|
126
|
+
clientSecret: null, // for public clients (PKCE-only)
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Custom Scopes
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
OAuthModule.forRoot({
|
|
134
|
+
providers: { google: {...} },
|
|
135
|
+
defaultScopes: {
|
|
136
|
+
google: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/calendar'],
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Integration with @hazeljs/auth
|
|
142
|
+
|
|
143
|
+
After OAuth callback, create a user and issue JWT:
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
import { JwtService } from '@hazeljs/auth';
|
|
147
|
+
import { OAuthService } from '@hazeljs/oauth';
|
|
148
|
+
|
|
149
|
+
async handleOAuthCallback(provider: string, code: string, state: string, codeVerifier?: string) {
|
|
150
|
+
const { user, accessToken } = await this.oauth.handleCallback(provider, code, state, codeVerifier);
|
|
151
|
+
const dbUser = await this.upsertUser(user);
|
|
152
|
+
const jwt = this.jwt.sign({ sub: dbUser.id, email: dbUser.email });
|
|
153
|
+
return { user: dbUser, accessToken: jwt };
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Environment Variables
|
|
158
|
+
|
|
159
|
+
```env
|
|
160
|
+
GOOGLE_CLIENT_ID=
|
|
161
|
+
GOOGLE_CLIENT_SECRET=
|
|
162
|
+
MICROSOFT_CLIENT_ID=
|
|
163
|
+
MICROSOFT_CLIENT_SECRET=
|
|
164
|
+
GITHUB_CLIENT_ID=
|
|
165
|
+
GITHUB_CLIENT_SECRET=
|
|
166
|
+
FACEBOOK_CLIENT_ID=
|
|
167
|
+
FACEBOOK_CLIENT_SECRET=
|
|
168
|
+
TWITTER_CLIENT_ID=
|
|
169
|
+
TWITTER_CLIENT_SECRET=
|
|
170
|
+
OAUTH_REDIRECT_URI=http://localhost:3000/auth/google/callback
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## API Reference
|
|
174
|
+
|
|
175
|
+
### OAuthService
|
|
176
|
+
|
|
177
|
+
- `getAuthorizationUrl(provider, state?, scopes?)` — Returns `{ url, state, codeVerifier? }`
|
|
178
|
+
- `handleCallback(provider, code, state, codeVerifier?)` — Returns `{ accessToken, refreshToken?, expiresAt?, user }`
|
|
179
|
+
- `validateState(received, stored)` — CSRF check
|
|
180
|
+
- `generateState()` — Cryptographically secure state
|
|
181
|
+
|
|
182
|
+
### OAuthStateGuard
|
|
183
|
+
|
|
184
|
+
Validates the `state` parameter on callback. Expects `oauth_stored_state` on the request.
|
|
185
|
+
|
|
186
|
+
## Testing
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
npm test
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Links
|
|
193
|
+
|
|
194
|
+
- [Documentation](https://hazeljs.com/docs/packages/oauth)
|
|
195
|
+
- [GitHub](https://github.com/hazel-js/hazeljs)
|
|
196
|
+
- [Arctic](https://arcticjs.dev)
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
Apache 2.0 © [HazelJS](https://hazeljs.com)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type CanActivate, type ExecutionContext } from '@hazeljs/core';
|
|
2
|
+
import { OAuthService } from '../oauth.service';
|
|
3
|
+
/**
|
|
4
|
+
* Guard that validates the OAuth state parameter against a stored value.
|
|
5
|
+
* Use when handling the OAuth callback to prevent CSRF attacks.
|
|
6
|
+
*
|
|
7
|
+
* Expects storedState to be provided via request (e.g., from cookie or session).
|
|
8
|
+
* Set oauth_state and oauth_code_verifier (for PKCE) before redirecting to provider.
|
|
9
|
+
*/
|
|
10
|
+
export declare class OAuthStateGuard implements CanActivate {
|
|
11
|
+
private readonly oauthService;
|
|
12
|
+
constructor(oauthService: OAuthService);
|
|
13
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=oauth-state.guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-state.guard.d.ts","sourceRoot":"","sources":["../../src/guards/oauth-state.guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,gBAAgB,EAEtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhD;;;;;;GAMG;AACH,qBACa,eAAgB,YAAW,WAAW;IACrC,OAAO,CAAC,QAAQ,CAAC,YAAY;gBAAZ,YAAY,EAAE,YAAY;IAEjD,WAAW,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;CAmB/D"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.OAuthStateGuard = void 0;
|
|
13
|
+
const core_1 = require("@hazeljs/core");
|
|
14
|
+
const oauth_service_1 = require("../oauth.service");
|
|
15
|
+
/**
|
|
16
|
+
* Guard that validates the OAuth state parameter against a stored value.
|
|
17
|
+
* Use when handling the OAuth callback to prevent CSRF attacks.
|
|
18
|
+
*
|
|
19
|
+
* Expects storedState to be provided via request (e.g., from cookie or session).
|
|
20
|
+
* Set oauth_state and oauth_code_verifier (for PKCE) before redirecting to provider.
|
|
21
|
+
*/
|
|
22
|
+
let OAuthStateGuard = class OAuthStateGuard {
|
|
23
|
+
constructor(oauthService) {
|
|
24
|
+
this.oauthService = oauthService;
|
|
25
|
+
}
|
|
26
|
+
async canActivate(context) {
|
|
27
|
+
const request = context.switchToHttp().getRequest();
|
|
28
|
+
const receivedState = request.query?.state ?? request.body?.state;
|
|
29
|
+
const storedState = request.oauth_stored_state;
|
|
30
|
+
if (!receivedState || !storedState) {
|
|
31
|
+
throw new core_1.UnauthorizedError('Missing OAuth state');
|
|
32
|
+
}
|
|
33
|
+
if (!this.oauthService.validateState(receivedState, storedState)) {
|
|
34
|
+
throw new core_1.UnauthorizedError('Invalid OAuth state');
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
exports.OAuthStateGuard = OAuthStateGuard;
|
|
40
|
+
exports.OAuthStateGuard = OAuthStateGuard = __decorate([
|
|
41
|
+
(0, core_1.Injectable)(),
|
|
42
|
+
__metadata("design:paramtypes", [oauth_service_1.OAuthService])
|
|
43
|
+
], OAuthStateGuard);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hazeljs/oauth - OAuth 2.0 social login for HazelJS
|
|
3
|
+
*
|
|
4
|
+
* Supports Google, Microsoft Entra ID, and GitHub.
|
|
5
|
+
* Built on Arctic - 50+ providers available.
|
|
6
|
+
*/
|
|
7
|
+
export { OAuthModule } from './oauth.module';
|
|
8
|
+
export { OAuthService } from './oauth.service';
|
|
9
|
+
export { OAuthController } from './oauth.controller';
|
|
10
|
+
export { OAuthStateGuard } from './guards/oauth-state.guard';
|
|
11
|
+
export type { OAuthModuleOptions, OAuthProvidersConfig, OAuthCallbackResult, OAuthAuthorizationResult, OAuthUser, SupportedProvider, GoogleProviderConfig, MicrosoftProviderConfig, GitHubProviderConfig, FacebookProviderConfig, TwitterProviderConfig, } from './providers/provider.types';
|
|
12
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,YAAY,EACV,kBAAkB,EAClB,oBAAoB,EACpB,mBAAmB,EACnB,wBAAwB,EACxB,SAAS,EACT,iBAAiB,EACjB,oBAAoB,EACpB,uBAAuB,EACvB,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,4BAA4B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @hazeljs/oauth - OAuth 2.0 social login for HazelJS
|
|
4
|
+
*
|
|
5
|
+
* Supports Google, Microsoft Entra ID, and GitHub.
|
|
6
|
+
* Built on Arctic - 50+ providers available.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.OAuthStateGuard = exports.OAuthController = exports.OAuthService = exports.OAuthModule = void 0;
|
|
10
|
+
var oauth_module_1 = require("./oauth.module");
|
|
11
|
+
Object.defineProperty(exports, "OAuthModule", { enumerable: true, get: function () { return oauth_module_1.OAuthModule; } });
|
|
12
|
+
var oauth_service_1 = require("./oauth.service");
|
|
13
|
+
Object.defineProperty(exports, "OAuthService", { enumerable: true, get: function () { return oauth_service_1.OAuthService; } });
|
|
14
|
+
var oauth_controller_1 = require("./oauth.controller");
|
|
15
|
+
Object.defineProperty(exports, "OAuthController", { enumerable: true, get: function () { return oauth_controller_1.OAuthController; } });
|
|
16
|
+
var oauth_state_guard_1 = require("./guards/oauth-state.guard");
|
|
17
|
+
Object.defineProperty(exports, "OAuthStateGuard", { enumerable: true, get: function () { return oauth_state_guard_1.OAuthStateGuard; } });
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Response } from '@hazeljs/core';
|
|
2
|
+
import { OAuthService } from './oauth.service';
|
|
3
|
+
/**
|
|
4
|
+
* Optional controller that provides OAuth routes.
|
|
5
|
+
* Register in your app if you want ready-made /auth/:provider and /auth/:provider/callback routes.
|
|
6
|
+
*/
|
|
7
|
+
export declare class OAuthController {
|
|
8
|
+
private readonly oauthService;
|
|
9
|
+
constructor(oauthService: OAuthService);
|
|
10
|
+
/**
|
|
11
|
+
* GET /auth/:provider - Redirects user to OAuth provider.
|
|
12
|
+
* Sets state and codeVerifier (for PKCE) in cookies.
|
|
13
|
+
*/
|
|
14
|
+
login(provider: string, res: Response): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* GET /auth/:provider/callback - Handles OAuth callback.
|
|
17
|
+
* Returns JSON with accessToken, user. Use successRedirect/errorRedirect query params for redirects.
|
|
18
|
+
*/
|
|
19
|
+
callback(provider: string, query: {
|
|
20
|
+
code?: string;
|
|
21
|
+
state?: string;
|
|
22
|
+
successRedirect?: string;
|
|
23
|
+
errorRedirect?: string;
|
|
24
|
+
}, req: {
|
|
25
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
26
|
+
}, res: Response): Promise<void>;
|
|
27
|
+
private redirectOrJson;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=oauth.controller.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.controller.d.ts","sourceRoot":"","sources":["../src/oauth.controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2C,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAC;AACvF,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAmB/C;;;GAGG;AACH,qBACa,eAAe;IACd,OAAO,CAAC,QAAQ,CAAC,YAAY;gBAAZ,YAAY,EAAE,YAAY;IAEvD;;;OAGG;IAEG,KAAK,CAAoB,QAAQ,EAAE,MAAM,EAAS,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBrF;;;OAGG;IAEG,QAAQ,CACO,QAAQ,EAAE,MAAM,EAEnC,KAAK,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,EACnF,GAAG,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;KAAE,EAChE,GAAG,EAAE,QAAQ,GACnB,OAAO,CAAC,IAAI,CAAC;IA2ChB,OAAO,CAAC,cAAc;CAgBvB"}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.OAuthController = void 0;
|
|
16
|
+
const core_1 = require("@hazeljs/core");
|
|
17
|
+
const oauth_service_1 = require("./oauth.service");
|
|
18
|
+
const STATE_COOKIE = 'oauth_state';
|
|
19
|
+
const CODE_VERIFIER_COOKIE = 'oauth_code_verifier';
|
|
20
|
+
const COOKIE_MAX_AGE = 60 * 10; // 10 minutes
|
|
21
|
+
const COOKIE_OPTS = `Path=/; HttpOnly; SameSite=Lax; Max-Age=${COOKIE_MAX_AGE}`;
|
|
22
|
+
function getCookie(req, name) {
|
|
23
|
+
const h = req?.headers?.['cookie'];
|
|
24
|
+
const cookieHeader = Array.isArray(h) ? h[0] : h;
|
|
25
|
+
if (typeof cookieHeader !== 'string')
|
|
26
|
+
return undefined;
|
|
27
|
+
const part = cookieHeader.split(';').find((c) => c.trim().startsWith(`${name}=`));
|
|
28
|
+
return part?.split('=')[1]?.trim();
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Optional controller that provides OAuth routes.
|
|
32
|
+
* Register in your app if you want ready-made /auth/:provider and /auth/:provider/callback routes.
|
|
33
|
+
*/
|
|
34
|
+
let OAuthController = class OAuthController {
|
|
35
|
+
constructor(oauthService) {
|
|
36
|
+
this.oauthService = oauthService;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* GET /auth/:provider - Redirects user to OAuth provider.
|
|
40
|
+
* Sets state and codeVerifier (for PKCE) in cookies.
|
|
41
|
+
*/
|
|
42
|
+
async login(provider, res) {
|
|
43
|
+
const p = provider.toLowerCase();
|
|
44
|
+
if (!['google', 'microsoft', 'github', 'facebook', 'twitter'].includes(p)) {
|
|
45
|
+
res.status(400).json({ error: 'Invalid provider' });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const { url, state, codeVerifier } = this.oauthService.getAuthorizationUrl(p);
|
|
49
|
+
const cookies = [`${STATE_COOKIE}=${state}; ${COOKIE_OPTS}`];
|
|
50
|
+
if (codeVerifier) {
|
|
51
|
+
cookies.push(`${CODE_VERIFIER_COOKIE}=${codeVerifier}; ${COOKIE_OPTS}`);
|
|
52
|
+
}
|
|
53
|
+
res.setHeader('Set-Cookie', cookies);
|
|
54
|
+
res.status(302);
|
|
55
|
+
res.setHeader('Location', url);
|
|
56
|
+
res.end();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* GET /auth/:provider/callback - Handles OAuth callback.
|
|
60
|
+
* Returns JSON with accessToken, user. Use successRedirect/errorRedirect query params for redirects.
|
|
61
|
+
*/
|
|
62
|
+
async callback(provider, query, req, res) {
|
|
63
|
+
const p = provider.toLowerCase();
|
|
64
|
+
if (!['google', 'microsoft', 'github', 'facebook', 'twitter'].includes(p)) {
|
|
65
|
+
res.status(400).json({ error: 'Invalid provider' });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const code = query?.code;
|
|
69
|
+
if (!code) {
|
|
70
|
+
this.redirectOrJson(res, 400, query.errorRedirect, { error: 'Missing authorization code' });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const storedState = getCookie(req, STATE_COOKIE);
|
|
74
|
+
const codeVerifier = getCookie(req, CODE_VERIFIER_COOKIE);
|
|
75
|
+
res.setHeader('Set-Cookie', [
|
|
76
|
+
`${STATE_COOKIE}=; Path=/; HttpOnly; Max-Age=0`,
|
|
77
|
+
`${CODE_VERIFIER_COOKIE}=; Path=/; HttpOnly; Max-Age=0`,
|
|
78
|
+
]);
|
|
79
|
+
if (!storedState || query.state !== storedState) {
|
|
80
|
+
this.redirectOrJson(res, 400, query.errorRedirect, { error: 'Invalid state' });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const result = await this.oauthService.handleCallback(p, code, storedState, codeVerifier);
|
|
85
|
+
if (query.successRedirect) {
|
|
86
|
+
res.status(302);
|
|
87
|
+
res.setHeader('Location', query.successRedirect);
|
|
88
|
+
res.end();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
res.status(200).json(result);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
const message = err instanceof Error ? err.message : 'OAuth callback failed';
|
|
95
|
+
this.redirectOrJson(res, 401, query.errorRedirect, { error: message });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
redirectOrJson(res, status, errorRedirect, json) {
|
|
99
|
+
if (errorRedirect) {
|
|
100
|
+
const url = new URL(errorRedirect);
|
|
101
|
+
if (json?.error)
|
|
102
|
+
url.searchParams.set('error', json.error);
|
|
103
|
+
res.status(302);
|
|
104
|
+
res.setHeader('Location', url.toString());
|
|
105
|
+
res.end();
|
|
106
|
+
}
|
|
107
|
+
else if (json) {
|
|
108
|
+
res.status(status).json(json);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
exports.OAuthController = OAuthController;
|
|
113
|
+
__decorate([
|
|
114
|
+
(0, core_1.Get)('/:provider'),
|
|
115
|
+
__param(0, (0, core_1.Param)('provider')),
|
|
116
|
+
__param(1, (0, core_1.Res)()),
|
|
117
|
+
__metadata("design:type", Function),
|
|
118
|
+
__metadata("design:paramtypes", [String, Object]),
|
|
119
|
+
__metadata("design:returntype", Promise)
|
|
120
|
+
], OAuthController.prototype, "login", null);
|
|
121
|
+
__decorate([
|
|
122
|
+
(0, core_1.Get)('/:provider/callback'),
|
|
123
|
+
__param(0, (0, core_1.Param)('provider')),
|
|
124
|
+
__param(1, (0, core_1.Query)()),
|
|
125
|
+
__param(2, (0, core_1.Req)()),
|
|
126
|
+
__param(3, (0, core_1.Res)()),
|
|
127
|
+
__metadata("design:type", Function),
|
|
128
|
+
__metadata("design:paramtypes", [String, Object, Object, Object]),
|
|
129
|
+
__metadata("design:returntype", Promise)
|
|
130
|
+
], OAuthController.prototype, "callback", null);
|
|
131
|
+
exports.OAuthController = OAuthController = __decorate([
|
|
132
|
+
(0, core_1.Controller)('/auth'),
|
|
133
|
+
__metadata("design:paramtypes", [oauth_service_1.OAuthService])
|
|
134
|
+
], OAuthController);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.module.d.ts","sourceRoot":"","sources":["../src/oauth.module.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAErE,qBAKa,WAAW;IACtB,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,WAAW;CAIhE"}
|