@constructive-io/oauth 0.2.0
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 +23 -0
- package/README.md +187 -0
- package/esm/index.d.ts +4 -0
- package/esm/index.js +4 -0
- package/esm/middleware/express.d.ts +51 -0
- package/esm/middleware/express.js +172 -0
- package/esm/oauth-client.d.ts +16 -0
- package/esm/oauth-client.js +146 -0
- package/esm/providers/facebook.d.ts +2 -0
- package/esm/providers/facebook.js +21 -0
- package/esm/providers/github.d.ts +10 -0
- package/esm/providers/github.js +30 -0
- package/esm/providers/google.d.ts +2 -0
- package/esm/providers/google.js +20 -0
- package/esm/providers/index.d.ts +9 -0
- package/esm/providers/index.js +17 -0
- package/esm/providers/linkedin.d.ts +2 -0
- package/esm/providers/linkedin.js +20 -0
- package/esm/types.d.ts +55 -0
- package/esm/types.js +7 -0
- package/esm/utils/state.d.ts +1 -0
- package/esm/utils/state.js +1 -0
- package/index.d.ts +4 -0
- package/index.js +20 -0
- package/middleware/express.d.ts +51 -0
- package/middleware/express.js +177 -0
- package/oauth-client.d.ts +16 -0
- package/oauth-client.js +151 -0
- package/package.json +51 -0
- package/providers/facebook.d.ts +2 -0
- package/providers/facebook.js +24 -0
- package/providers/github.d.ts +10 -0
- package/providers/github.js +34 -0
- package/providers/google.d.ts +2 -0
- package/providers/google.js +23 -0
- package/providers/index.d.ts +9 -0
- package/providers/index.js +27 -0
- package/providers/linkedin.d.ts +2 -0
- package/providers/linkedin.js +23 -0
- package/types.d.ts +55 -0
- package/types.js +10 -0
- package/utils/state.d.ts +1 -0
- package/utils/state.js +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# @constructive-io/oauth
|
|
2
|
+
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE">
|
|
12
|
+
<img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
|
|
13
|
+
</a>
|
|
14
|
+
<a href="https://www.npmjs.com/package/@constructive-io/oauth">
|
|
15
|
+
<img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=packages%2Foauth%2Fpackage.json"/>
|
|
16
|
+
</a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
> Minimal OAuth 2.0 client for social authentication
|
|
20
|
+
|
|
21
|
+
A lightweight OAuth 2.0 client for social authentication with Google, GitHub, Facebook, and LinkedIn. Uses [`@constructive-io/csrf`](../csrf) for secure state management. No external auth library dependencies - uses native fetch for HTTP requests.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pnpm add @constructive-io/oauth
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
### Basic Setup
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { createOAuthClient } from '@constructive-io/oauth';
|
|
35
|
+
|
|
36
|
+
const client = createOAuthClient({
|
|
37
|
+
providers: {
|
|
38
|
+
google: {
|
|
39
|
+
clientId: process.env.GOOGLE_CLIENT_ID,
|
|
40
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
41
|
+
},
|
|
42
|
+
github: {
|
|
43
|
+
clientId: process.env.GITHUB_CLIENT_ID,
|
|
44
|
+
clientSecret: process.env.GITHUB_CLIENT_SECRET,
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
baseUrl: 'https://api.example.com',
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Generate authorization URL
|
|
51
|
+
const { url, state } = client.getAuthorizationUrl({ provider: 'google' });
|
|
52
|
+
|
|
53
|
+
// After user authorizes, exchange code for profile
|
|
54
|
+
const profile = await client.handleCallback({ provider: 'google', code });
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Express Middleware
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import express from 'express';
|
|
61
|
+
import cookieParser from 'cookie-parser';
|
|
62
|
+
import { createOAuthMiddleware } from '@constructive-io/oauth';
|
|
63
|
+
|
|
64
|
+
const app = express();
|
|
65
|
+
app.use(cookieParser());
|
|
66
|
+
|
|
67
|
+
const oauth = createOAuthMiddleware({
|
|
68
|
+
providers: {
|
|
69
|
+
google: { clientId: '...', clientSecret: '...' },
|
|
70
|
+
github: { clientId: '...', clientSecret: '...' },
|
|
71
|
+
facebook: { clientId: '...', clientSecret: '...' },
|
|
72
|
+
linkedin: { clientId: '...', clientSecret: '...' },
|
|
73
|
+
},
|
|
74
|
+
baseUrl: 'https://api.example.com',
|
|
75
|
+
onSuccess: async (profile, context) => {
|
|
76
|
+
// Handle successful authentication
|
|
77
|
+
// Create/update user in database, generate session token, etc.
|
|
78
|
+
return { user: profile };
|
|
79
|
+
},
|
|
80
|
+
onError: (error, context) => {
|
|
81
|
+
console.error('OAuth error:', error);
|
|
82
|
+
},
|
|
83
|
+
successRedirect: 'https://app.example.com/dashboard',
|
|
84
|
+
errorRedirect: 'https://app.example.com/login?error=auth_failed',
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// Mount routes
|
|
88
|
+
app.get('/auth/:provider', oauth.initiateAuth);
|
|
89
|
+
app.get('/auth/:provider/callback', oauth.handleCallback);
|
|
90
|
+
app.get('/auth/providers', oauth.getProviders);
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Supported Providers
|
|
94
|
+
|
|
95
|
+
| Provider | Scopes |
|
|
96
|
+
|----------|--------|
|
|
97
|
+
| Google | `openid`, `email`, `profile` |
|
|
98
|
+
| GitHub | `user:email`, `read:user` |
|
|
99
|
+
| Facebook | `email`, `public_profile` |
|
|
100
|
+
| LinkedIn | `openid`, `profile`, `email` |
|
|
101
|
+
|
|
102
|
+
## API
|
|
103
|
+
|
|
104
|
+
### `createOAuthClient(config)`
|
|
105
|
+
|
|
106
|
+
Creates an OAuth client instance.
|
|
107
|
+
|
|
108
|
+
### `createOAuthMiddleware(config)`
|
|
109
|
+
|
|
110
|
+
Creates Express route handlers for OAuth flows.
|
|
111
|
+
|
|
112
|
+
### `OAuthProfile`
|
|
113
|
+
|
|
114
|
+
The normalized user profile returned after authentication:
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
interface OAuthProfile {
|
|
118
|
+
provider: string; // 'google', 'github', etc.
|
|
119
|
+
providerId: string; // Provider's unique user ID
|
|
120
|
+
email: string | null;
|
|
121
|
+
name: string | null;
|
|
122
|
+
picture: string | null;
|
|
123
|
+
raw: unknown; // Original provider response
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
MIT
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## Education and Tutorials
|
|
134
|
+
|
|
135
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
136
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
137
|
+
|
|
138
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
139
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
140
|
+
|
|
141
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
142
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
143
|
+
|
|
144
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
145
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
146
|
+
|
|
147
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
148
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
149
|
+
|
|
150
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
151
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
152
|
+
|
|
153
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
154
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
155
|
+
|
|
156
|
+
## Related Constructive Tooling
|
|
157
|
+
|
|
158
|
+
### 📦 Package Management
|
|
159
|
+
|
|
160
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
161
|
+
|
|
162
|
+
### 🧪 Testing
|
|
163
|
+
|
|
164
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
165
|
+
* [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
|
|
166
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
167
|
+
* [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
168
|
+
* [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
|
|
169
|
+
|
|
170
|
+
### 🧠 Parsing & AST
|
|
171
|
+
|
|
172
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
173
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
174
|
+
* [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
|
|
175
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
176
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
177
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
178
|
+
|
|
179
|
+
## Credits
|
|
180
|
+
|
|
181
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
182
|
+
|
|
183
|
+
## Disclaimer
|
|
184
|
+
|
|
185
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
186
|
+
|
|
187
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/esm/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { OAuthProviderConfig, OAuthProfile, OAuthCredentials, OAuthClientConfig, TokenResponse, AuthorizationUrlParams, CallbackParams, OAuthError, createOAuthError, } from './types';
|
|
2
|
+
export { OAuthClient, createOAuthClient } from './oauth-client';
|
|
3
|
+
export { providers, getProvider, getProviderIds, googleProvider, githubProvider, facebookProvider, linkedinProvider, } from './providers';
|
|
4
|
+
export { createOAuthMiddleware, OAuthMiddlewareConfig, OAuthCallbackContext, OAuthErrorContext, OAuthRouteHandlers, generateState, verifyState, } from './middleware/express';
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createOAuthError, } from './types';
|
|
2
|
+
export { OAuthClient, createOAuthClient } from './oauth-client';
|
|
3
|
+
export { providers, getProvider, getProviderIds, googleProvider, githubProvider, facebookProvider, linkedinProvider, } from './providers';
|
|
4
|
+
export { createOAuthMiddleware, generateState, verifyState, } from './middleware/express';
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { OAuthClientConfig, OAuthProfile } from '../types';
|
|
2
|
+
import { generateState, verifyState } from '../utils/state';
|
|
3
|
+
export interface OAuthMiddlewareConfig extends OAuthClientConfig {
|
|
4
|
+
onSuccess: (profile: OAuthProfile, context: OAuthCallbackContext) => Promise<unknown>;
|
|
5
|
+
onError?: (error: Error, context: OAuthErrorContext) => void;
|
|
6
|
+
successRedirect?: string;
|
|
7
|
+
errorRedirect?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface OAuthCallbackContext {
|
|
10
|
+
provider: string;
|
|
11
|
+
profile: OAuthProfile;
|
|
12
|
+
query: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
export interface OAuthErrorContext {
|
|
15
|
+
provider?: string;
|
|
16
|
+
error: Error;
|
|
17
|
+
query: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
export interface OAuthRouteHandlers {
|
|
20
|
+
initiateAuth: (req: {
|
|
21
|
+
params: {
|
|
22
|
+
provider: string;
|
|
23
|
+
};
|
|
24
|
+
query: Record<string, unknown>;
|
|
25
|
+
}, res: {
|
|
26
|
+
redirect: (url: string) => void;
|
|
27
|
+
cookie: (name: string, value: string, options: Record<string, unknown>) => void;
|
|
28
|
+
status: (code: number) => {
|
|
29
|
+
json: (data: unknown) => void;
|
|
30
|
+
};
|
|
31
|
+
}) => void;
|
|
32
|
+
handleCallback: (req: {
|
|
33
|
+
params: {
|
|
34
|
+
provider: string;
|
|
35
|
+
};
|
|
36
|
+
query: Record<string, unknown>;
|
|
37
|
+
cookies: Record<string, string>;
|
|
38
|
+
}, res: {
|
|
39
|
+
redirect: (url: string) => void;
|
|
40
|
+
clearCookie: (name: string) => void;
|
|
41
|
+
status: (code: number) => {
|
|
42
|
+
json: (data: unknown) => void;
|
|
43
|
+
};
|
|
44
|
+
json: (data: unknown) => void;
|
|
45
|
+
}) => Promise<void>;
|
|
46
|
+
getProviders: (req: unknown, res: {
|
|
47
|
+
json: (data: unknown) => void;
|
|
48
|
+
}) => void;
|
|
49
|
+
}
|
|
50
|
+
export declare function createOAuthMiddleware(config: OAuthMiddlewareConfig): OAuthRouteHandlers;
|
|
51
|
+
export { generateState, verifyState };
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { OAuthClient } from '../oauth-client';
|
|
2
|
+
import { createOAuthError } from '../types';
|
|
3
|
+
import { generateState, verifyState } from '../utils/state';
|
|
4
|
+
import { getProviderIds } from '../providers';
|
|
5
|
+
export function createOAuthMiddleware(config) {
|
|
6
|
+
const client = new OAuthClient(config);
|
|
7
|
+
const clientConfig = client.getConfig();
|
|
8
|
+
const initiateAuth = (req, res) => {
|
|
9
|
+
const { provider } = req.params;
|
|
10
|
+
try {
|
|
11
|
+
const { url, state } = client.getAuthorizationUrl({ provider });
|
|
12
|
+
res.cookie(clientConfig.stateCookieName, state, {
|
|
13
|
+
httpOnly: true,
|
|
14
|
+
secure: process.env.NODE_ENV === 'production',
|
|
15
|
+
maxAge: (clientConfig.stateCookieMaxAge || 600) * 1000,
|
|
16
|
+
sameSite: 'lax',
|
|
17
|
+
});
|
|
18
|
+
res.redirect(url);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (config.onError) {
|
|
22
|
+
config.onError(error, {
|
|
23
|
+
provider,
|
|
24
|
+
error: error,
|
|
25
|
+
query: req.query,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
if (config.errorRedirect) {
|
|
29
|
+
const errorUrl = new URL(config.errorRedirect);
|
|
30
|
+
errorUrl.searchParams.set('error', error.message);
|
|
31
|
+
errorUrl.searchParams.set('provider', provider);
|
|
32
|
+
res.redirect(errorUrl.toString());
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
res.status(400).json({
|
|
36
|
+
error: 'oauth_error',
|
|
37
|
+
message: error.message,
|
|
38
|
+
provider,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const handleCallback = async (req, res) => {
|
|
44
|
+
const { provider } = req.params;
|
|
45
|
+
const { code, state, error: oauthError, error_description } = req.query;
|
|
46
|
+
const storedState = req.cookies[clientConfig.stateCookieName];
|
|
47
|
+
res.clearCookie(clientConfig.stateCookieName);
|
|
48
|
+
if (oauthError) {
|
|
49
|
+
const error = createOAuthError(error_description || oauthError, 'OAUTH_PROVIDER_ERROR', provider);
|
|
50
|
+
if (config.onError) {
|
|
51
|
+
config.onError(error, {
|
|
52
|
+
provider,
|
|
53
|
+
error,
|
|
54
|
+
query: req.query,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (config.errorRedirect) {
|
|
58
|
+
const errorUrl = new URL(config.errorRedirect);
|
|
59
|
+
errorUrl.searchParams.set('error', oauthError);
|
|
60
|
+
if (error_description) {
|
|
61
|
+
errorUrl.searchParams.set('error_description', error_description);
|
|
62
|
+
}
|
|
63
|
+
errorUrl.searchParams.set('provider', provider);
|
|
64
|
+
res.redirect(errorUrl.toString());
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
res.status(400).json({
|
|
68
|
+
error: 'oauth_error',
|
|
69
|
+
message: error_description || oauthError,
|
|
70
|
+
provider,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (!verifyState(storedState, state)) {
|
|
76
|
+
const error = createOAuthError('Invalid state parameter', 'INVALID_STATE', provider);
|
|
77
|
+
if (config.onError) {
|
|
78
|
+
config.onError(error, {
|
|
79
|
+
provider,
|
|
80
|
+
error,
|
|
81
|
+
query: req.query,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (config.errorRedirect) {
|
|
85
|
+
const errorUrl = new URL(config.errorRedirect);
|
|
86
|
+
errorUrl.searchParams.set('error', 'invalid_state');
|
|
87
|
+
errorUrl.searchParams.set('provider', provider);
|
|
88
|
+
res.redirect(errorUrl.toString());
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
res.status(400).json({
|
|
92
|
+
error: 'invalid_state',
|
|
93
|
+
message: 'Invalid state parameter',
|
|
94
|
+
provider,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (!code) {
|
|
100
|
+
const error = createOAuthError('Missing authorization code', 'MISSING_CODE', provider);
|
|
101
|
+
if (config.onError) {
|
|
102
|
+
config.onError(error, {
|
|
103
|
+
provider,
|
|
104
|
+
error,
|
|
105
|
+
query: req.query,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if (config.errorRedirect) {
|
|
109
|
+
const errorUrl = new URL(config.errorRedirect);
|
|
110
|
+
errorUrl.searchParams.set('error', 'missing_code');
|
|
111
|
+
errorUrl.searchParams.set('provider', provider);
|
|
112
|
+
res.redirect(errorUrl.toString());
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
res.status(400).json({
|
|
116
|
+
error: 'missing_code',
|
|
117
|
+
message: 'Missing authorization code',
|
|
118
|
+
provider,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const profile = await client.handleCallback({ provider, code });
|
|
125
|
+
const result = await config.onSuccess(profile, {
|
|
126
|
+
provider,
|
|
127
|
+
profile,
|
|
128
|
+
query: req.query,
|
|
129
|
+
});
|
|
130
|
+
if (config.successRedirect) {
|
|
131
|
+
res.redirect(config.successRedirect);
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
res.json({ success: true, data: result });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (config.onError) {
|
|
139
|
+
config.onError(error, {
|
|
140
|
+
provider,
|
|
141
|
+
error: error,
|
|
142
|
+
query: req.query,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
if (config.errorRedirect) {
|
|
146
|
+
const errorUrl = new URL(config.errorRedirect);
|
|
147
|
+
errorUrl.searchParams.set('error', 'callback_failed');
|
|
148
|
+
errorUrl.searchParams.set('message', error.message);
|
|
149
|
+
errorUrl.searchParams.set('provider', provider);
|
|
150
|
+
res.redirect(errorUrl.toString());
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
res.status(500).json({
|
|
154
|
+
error: 'callback_failed',
|
|
155
|
+
message: error.message,
|
|
156
|
+
provider,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
const getProviders = (_req, res) => {
|
|
162
|
+
const configuredProviders = Object.keys(config.providers);
|
|
163
|
+
const availableProviders = getProviderIds().filter((id) => configuredProviders.includes(id));
|
|
164
|
+
res.json({ providers: availableProviders });
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
initiateAuth,
|
|
168
|
+
handleCallback,
|
|
169
|
+
getProviders,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
export { generateState, verifyState };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { OAuthClientConfig, OAuthProfile, TokenResponse, AuthorizationUrlParams, CallbackParams } from './types';
|
|
2
|
+
export declare class OAuthClient {
|
|
3
|
+
private config;
|
|
4
|
+
constructor(config: OAuthClientConfig);
|
|
5
|
+
getAuthorizationUrl(params: AuthorizationUrlParams): {
|
|
6
|
+
url: string;
|
|
7
|
+
state: string;
|
|
8
|
+
};
|
|
9
|
+
exchangeCode(params: CallbackParams): Promise<TokenResponse>;
|
|
10
|
+
getUserProfile(providerId: string, accessToken: string): Promise<OAuthProfile>;
|
|
11
|
+
handleCallback(params: CallbackParams): Promise<OAuthProfile>;
|
|
12
|
+
private fetchGitHubEmail;
|
|
13
|
+
private getCallbackUrl;
|
|
14
|
+
getConfig(): OAuthClientConfig;
|
|
15
|
+
}
|
|
16
|
+
export declare function createOAuthClient(config: OAuthClientConfig): OAuthClient;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { createOAuthError, } from './types';
|
|
2
|
+
import { getProvider, GITHUB_EMAILS_URL, extractPrimaryEmail } from './providers';
|
|
3
|
+
import { generateState } from './utils/state';
|
|
4
|
+
export class OAuthClient {
|
|
5
|
+
config;
|
|
6
|
+
constructor(config) {
|
|
7
|
+
this.config = {
|
|
8
|
+
callbackPath: '/auth/{provider}/callback',
|
|
9
|
+
stateCookieName: 'oauth_state',
|
|
10
|
+
stateCookieMaxAge: 600,
|
|
11
|
+
...config,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
getAuthorizationUrl(params) {
|
|
15
|
+
const { provider: providerId, state: customState, redirectUri, scopes } = params;
|
|
16
|
+
const provider = getProvider(providerId);
|
|
17
|
+
if (!provider) {
|
|
18
|
+
throw createOAuthError(`Unknown provider: ${providerId}`, 'UNKNOWN_PROVIDER', providerId);
|
|
19
|
+
}
|
|
20
|
+
const credentials = this.config.providers[providerId];
|
|
21
|
+
if (!credentials) {
|
|
22
|
+
throw createOAuthError(`No credentials configured for provider: ${providerId}`, 'MISSING_CREDENTIALS', providerId);
|
|
23
|
+
}
|
|
24
|
+
const state = customState || generateState();
|
|
25
|
+
const callbackUrl = this.getCallbackUrl(providerId, redirectUri || credentials.redirectUri);
|
|
26
|
+
const effectiveScopes = scopes || provider.scopes;
|
|
27
|
+
const url = new URL(provider.authorizationUrl);
|
|
28
|
+
url.searchParams.set('client_id', credentials.clientId);
|
|
29
|
+
url.searchParams.set('redirect_uri', callbackUrl);
|
|
30
|
+
url.searchParams.set('response_type', 'code');
|
|
31
|
+
url.searchParams.set('scope', effectiveScopes.join(' '));
|
|
32
|
+
url.searchParams.set('state', state);
|
|
33
|
+
return { url: url.toString(), state };
|
|
34
|
+
}
|
|
35
|
+
async exchangeCode(params) {
|
|
36
|
+
const { provider: providerId, code, redirectUri } = params;
|
|
37
|
+
const provider = getProvider(providerId);
|
|
38
|
+
if (!provider) {
|
|
39
|
+
throw createOAuthError(`Unknown provider: ${providerId}`, 'UNKNOWN_PROVIDER', providerId);
|
|
40
|
+
}
|
|
41
|
+
const credentials = this.config.providers[providerId];
|
|
42
|
+
if (!credentials) {
|
|
43
|
+
throw createOAuthError(`No credentials configured for provider: ${providerId}`, 'MISSING_CREDENTIALS', providerId);
|
|
44
|
+
}
|
|
45
|
+
const callbackUrl = this.getCallbackUrl(providerId, redirectUri || credentials.redirectUri);
|
|
46
|
+
const body = {
|
|
47
|
+
client_id: credentials.clientId,
|
|
48
|
+
client_secret: credentials.clientSecret,
|
|
49
|
+
code,
|
|
50
|
+
redirect_uri: callbackUrl,
|
|
51
|
+
grant_type: 'authorization_code',
|
|
52
|
+
};
|
|
53
|
+
const headers = {
|
|
54
|
+
Accept: 'application/json',
|
|
55
|
+
};
|
|
56
|
+
let requestBody;
|
|
57
|
+
if (provider.tokenRequestContentType === 'json') {
|
|
58
|
+
headers['Content-Type'] = 'application/json';
|
|
59
|
+
requestBody = JSON.stringify(body);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
63
|
+
requestBody = new URLSearchParams(body).toString();
|
|
64
|
+
}
|
|
65
|
+
const response = await fetch(provider.tokenUrl, {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers,
|
|
68
|
+
body: requestBody,
|
|
69
|
+
});
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
const errorText = await response.text();
|
|
72
|
+
throw createOAuthError(`Token exchange failed: ${errorText}`, 'TOKEN_EXCHANGE_FAILED', providerId, response.status);
|
|
73
|
+
}
|
|
74
|
+
const data = await response.json();
|
|
75
|
+
if (data.error) {
|
|
76
|
+
throw createOAuthError(`Token exchange error: ${data.error_description || data.error}`, 'TOKEN_EXCHANGE_ERROR', providerId);
|
|
77
|
+
}
|
|
78
|
+
return data;
|
|
79
|
+
}
|
|
80
|
+
async getUserProfile(providerId, accessToken) {
|
|
81
|
+
const provider = getProvider(providerId);
|
|
82
|
+
if (!provider) {
|
|
83
|
+
throw createOAuthError(`Unknown provider: ${providerId}`, 'UNKNOWN_PROVIDER', providerId);
|
|
84
|
+
}
|
|
85
|
+
const headers = {
|
|
86
|
+
Authorization: `Bearer ${accessToken}`,
|
|
87
|
+
Accept: 'application/json',
|
|
88
|
+
};
|
|
89
|
+
if (providerId === 'github') {
|
|
90
|
+
headers['User-Agent'] = 'Constructive-OAuth';
|
|
91
|
+
}
|
|
92
|
+
const response = await fetch(provider.userInfoUrl, {
|
|
93
|
+
method: provider.userInfoMethod || 'GET',
|
|
94
|
+
headers,
|
|
95
|
+
});
|
|
96
|
+
if (!response.ok) {
|
|
97
|
+
const errorText = await response.text();
|
|
98
|
+
throw createOAuthError(`Failed to fetch user profile: ${errorText}`, 'USER_PROFILE_FAILED', providerId, response.status);
|
|
99
|
+
}
|
|
100
|
+
const data = await response.json();
|
|
101
|
+
let profile = provider.mapProfile(data);
|
|
102
|
+
if (providerId === 'github' && !profile.email) {
|
|
103
|
+
profile = await this.fetchGitHubEmail(accessToken, profile);
|
|
104
|
+
}
|
|
105
|
+
return profile;
|
|
106
|
+
}
|
|
107
|
+
async handleCallback(params) {
|
|
108
|
+
const tokens = await this.exchangeCode(params);
|
|
109
|
+
return this.getUserProfile(params.provider, tokens.access_token);
|
|
110
|
+
}
|
|
111
|
+
async fetchGitHubEmail(accessToken, profile) {
|
|
112
|
+
try {
|
|
113
|
+
const response = await fetch(GITHUB_EMAILS_URL, {
|
|
114
|
+
headers: {
|
|
115
|
+
Authorization: `Bearer ${accessToken}`,
|
|
116
|
+
Accept: 'application/json',
|
|
117
|
+
'User-Agent': 'Constructive-OAuth',
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
if (response.ok) {
|
|
121
|
+
const emails = await response.json();
|
|
122
|
+
const email = extractPrimaryEmail(emails);
|
|
123
|
+
if (email) {
|
|
124
|
+
return { ...profile, email };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// Ignore email fetch errors, return profile without email
|
|
130
|
+
}
|
|
131
|
+
return profile;
|
|
132
|
+
}
|
|
133
|
+
getCallbackUrl(providerId, customRedirectUri) {
|
|
134
|
+
if (customRedirectUri) {
|
|
135
|
+
return customRedirectUri;
|
|
136
|
+
}
|
|
137
|
+
const path = this.config.callbackPath.replace('{provider}', providerId);
|
|
138
|
+
return `${this.config.baseUrl}${path}`;
|
|
139
|
+
}
|
|
140
|
+
getConfig() {
|
|
141
|
+
return this.config;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export function createOAuthClient(config) {
|
|
145
|
+
return new OAuthClient(config);
|
|
146
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const FACEBOOK_API_VERSION = 'v18.0';
|
|
2
|
+
export const facebookProvider = {
|
|
3
|
+
id: 'facebook',
|
|
4
|
+
name: 'Facebook',
|
|
5
|
+
authorizationUrl: `https://www.facebook.com/${FACEBOOK_API_VERSION}/dialog/oauth`,
|
|
6
|
+
tokenUrl: `https://graph.facebook.com/${FACEBOOK_API_VERSION}/oauth/access_token`,
|
|
7
|
+
userInfoUrl: `https://graph.facebook.com/me?fields=id,name,email,picture`,
|
|
8
|
+
scopes: ['email', 'public_profile'],
|
|
9
|
+
tokenRequestContentType: 'form',
|
|
10
|
+
mapProfile: (data) => {
|
|
11
|
+
const profile = data;
|
|
12
|
+
return {
|
|
13
|
+
provider: 'facebook',
|
|
14
|
+
providerId: profile.id,
|
|
15
|
+
email: profile.email || null,
|
|
16
|
+
name: profile.name || null,
|
|
17
|
+
picture: profile.picture?.data?.url || null,
|
|
18
|
+
raw: data,
|
|
19
|
+
};
|
|
20
|
+
},
|
|
21
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { OAuthProviderConfig } from '../types';
|
|
2
|
+
interface GitHubEmail {
|
|
3
|
+
email: string;
|
|
4
|
+
primary: boolean;
|
|
5
|
+
verified: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare const githubProvider: OAuthProviderConfig;
|
|
8
|
+
export declare const GITHUB_EMAILS_URL = "https://api.github.com/user/emails";
|
|
9
|
+
export declare function extractPrimaryEmail(emails: GitHubEmail[]): string | null;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const githubProvider = {
|
|
2
|
+
id: 'github',
|
|
3
|
+
name: 'GitHub',
|
|
4
|
+
authorizationUrl: 'https://github.com/login/oauth/authorize',
|
|
5
|
+
tokenUrl: 'https://github.com/login/oauth/access_token',
|
|
6
|
+
userInfoUrl: 'https://api.github.com/user',
|
|
7
|
+
scopes: ['user:email', 'read:user'],
|
|
8
|
+
tokenRequestContentType: 'json',
|
|
9
|
+
mapProfile: (data) => {
|
|
10
|
+
const profile = data;
|
|
11
|
+
return {
|
|
12
|
+
provider: 'github',
|
|
13
|
+
providerId: String(profile.id),
|
|
14
|
+
email: profile.email || null,
|
|
15
|
+
name: profile.name || profile.login || null,
|
|
16
|
+
picture: profile.avatar_url || null,
|
|
17
|
+
raw: data,
|
|
18
|
+
};
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
export const GITHUB_EMAILS_URL = 'https://api.github.com/user/emails';
|
|
22
|
+
export function extractPrimaryEmail(emails) {
|
|
23
|
+
const primary = emails.find((e) => e.primary && e.verified);
|
|
24
|
+
if (primary)
|
|
25
|
+
return primary.email;
|
|
26
|
+
const verified = emails.find((e) => e.verified);
|
|
27
|
+
if (verified)
|
|
28
|
+
return verified.email;
|
|
29
|
+
return emails[0]?.email || null;
|
|
30
|
+
}
|