@stonyx/oauth 0.1.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/.github/workflows/ci.yml +16 -0
- package/.github/workflows/publish.yml +35 -0
- package/LICENSE.md +203 -0
- package/README.md +123 -0
- package/config/environment.js +6 -0
- package/package.json +41 -0
- package/src/auth-request.js +51 -0
- package/src/main.js +64 -0
- package/src/oauth-flow.js +88 -0
- package/src/providers/discord.js +49 -0
- package/src/session-manager.js +38 -0
- package/src/token-manager.js +26 -0
- package/test/config/environment.js +17 -0
- package/test/integration/oauth-test.js +93 -0
- package/test/sample/providers/mock.js +40 -0
- package/test/sample/requests/.gitkeep +0 -0
- package/test/unit/oauth-flow-test.js +137 -0
- package/test/unit/providers/discord-test.js +115 -0
- package/test/unit/session-manager-test.js +85 -0
- package/test/unit/token-manager-test.js +76 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
pull_request:
|
|
5
|
+
branches: [dev, main]
|
|
6
|
+
|
|
7
|
+
concurrency:
|
|
8
|
+
group: ci-${{ github.head_ref || github.ref }}
|
|
9
|
+
cancel-in-progress: true
|
|
10
|
+
|
|
11
|
+
permissions:
|
|
12
|
+
contents: read
|
|
13
|
+
|
|
14
|
+
jobs:
|
|
15
|
+
test:
|
|
16
|
+
uses: abofs/stonyx-workflows/.github/workflows/ci.yml@main
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: Publish to NPM
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
workflow_dispatch:
|
|
5
|
+
inputs:
|
|
6
|
+
version-type:
|
|
7
|
+
description: 'Version type'
|
|
8
|
+
required: true
|
|
9
|
+
type: choice
|
|
10
|
+
options:
|
|
11
|
+
- patch
|
|
12
|
+
- minor
|
|
13
|
+
- major
|
|
14
|
+
custom-version:
|
|
15
|
+
description: 'Custom version (optional, overrides version-type)'
|
|
16
|
+
required: false
|
|
17
|
+
type: string
|
|
18
|
+
pull_request:
|
|
19
|
+
types: [opened, synchronize, reopened]
|
|
20
|
+
branches: [main]
|
|
21
|
+
push:
|
|
22
|
+
branches: [main]
|
|
23
|
+
|
|
24
|
+
permissions:
|
|
25
|
+
contents: write
|
|
26
|
+
id-token: write
|
|
27
|
+
pull-requests: write
|
|
28
|
+
|
|
29
|
+
jobs:
|
|
30
|
+
publish:
|
|
31
|
+
uses: abofs/stonyx-workflows/.github/workflows/npm-publish.yml@main
|
|
32
|
+
with:
|
|
33
|
+
version-type: ${{ github.event.inputs.version-type }}
|
|
34
|
+
custom-version: ${{ github.event.inputs.custom-version }}
|
|
35
|
+
secrets: inherit
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [2025] [Stone Costa]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# @stonyx/oauth
|
|
2
|
+
|
|
3
|
+
OAuth2 authentication module for the Stonyx framework. Provides a generic OAuth2 Authorization Code flow with a provider pattern — ship with Discord support, extensible to any OAuth2 provider.
|
|
4
|
+
|
|
5
|
+
## Setup
|
|
6
|
+
|
|
7
|
+
Add as a devDependency to your Stonyx project:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @stonyx/oauth
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires `@stonyx/rest-server` as a peer dependency.
|
|
14
|
+
|
|
15
|
+
The module auto-discovers and initializes via the Stonyx module loader — no changes needed in `app.js`.
|
|
16
|
+
|
|
17
|
+
## Configuration
|
|
18
|
+
|
|
19
|
+
Add an `oauth` section to your project's `config/environment.js`:
|
|
20
|
+
|
|
21
|
+
```javascript
|
|
22
|
+
export default {
|
|
23
|
+
// ... other config
|
|
24
|
+
|
|
25
|
+
oauth: {
|
|
26
|
+
providers: {
|
|
27
|
+
discord: {
|
|
28
|
+
clientId: process.env.DISCORD_OAUTH_CLIENT_ID,
|
|
29
|
+
clientSecret: process.env.DISCORD_OAUTH_CLIENT_SECRET,
|
|
30
|
+
redirectUri: process.env.DISCORD_OAUTH_REDIRECT_URI || 'http://localhost:4200/auth/callback/discord',
|
|
31
|
+
scopes: ['identify'],
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
By default no providers are enabled. Add providers as keys in the `providers` object.
|
|
39
|
+
|
|
40
|
+
### Config Options
|
|
41
|
+
|
|
42
|
+
| Option | Default | Description |
|
|
43
|
+
|--------|---------|-------------|
|
|
44
|
+
| `providers` | `{}` | Map of provider name to config |
|
|
45
|
+
| `sessionDuration` | `86400` | Session TTL in seconds (default: 24h) |
|
|
46
|
+
|
|
47
|
+
## Routes
|
|
48
|
+
|
|
49
|
+
The module self-registers the following routes on the rest server:
|
|
50
|
+
|
|
51
|
+
| Method | Route | Description |
|
|
52
|
+
|--------|-------|-------------|
|
|
53
|
+
| `GET` | `/auth` | Validate session — send `session-id` header, returns user or 401 |
|
|
54
|
+
| `GET` | `/auth/login/:provider` | Redirects to provider's OAuth2 authorization page |
|
|
55
|
+
| `GET` | `/auth/callback/:provider` | OAuth2 callback — exchanges code for tokens, creates session |
|
|
56
|
+
| `GET` | `/auth/logout` | Destroys session (send `session-id` header) |
|
|
57
|
+
|
|
58
|
+
## Officially Supported Providers
|
|
59
|
+
|
|
60
|
+
### Discord
|
|
61
|
+
|
|
62
|
+
1. Create a Discord application at https://discord.com/developers/applications
|
|
63
|
+
2. Under OAuth2, add a redirect URL matching your `redirectUri` config
|
|
64
|
+
3. Copy the Client ID and Client Secret to your environment variables
|
|
65
|
+
4. Available scopes: `identify`, `email`, `guilds` (see Discord docs)
|
|
66
|
+
|
|
67
|
+
## Custom Providers
|
|
68
|
+
|
|
69
|
+
Create a provider by extending `OAuthFlow`:
|
|
70
|
+
|
|
71
|
+
```javascript
|
|
72
|
+
import OAuthFlow from '@stonyx/oauth/oauth-flow';
|
|
73
|
+
|
|
74
|
+
export default class MyProvider extends OAuthFlow {
|
|
75
|
+
constructor(config) {
|
|
76
|
+
super({
|
|
77
|
+
...config,
|
|
78
|
+
authorizationUrl: 'https://my-provider.com/oauth/authorize',
|
|
79
|
+
tokenUrl: 'https://my-provider.com/oauth/token',
|
|
80
|
+
userInfoUrl: 'https://my-provider.com/api/me',
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Override if the provider uses a different content type for token exchange
|
|
85
|
+
async exchangeCode(code) { ... }
|
|
86
|
+
|
|
87
|
+
// Map provider-specific user data to a standard shape
|
|
88
|
+
normalizeUser(rawUser) {
|
|
89
|
+
return {
|
|
90
|
+
id: rawUser.id,
|
|
91
|
+
username: rawUser.login,
|
|
92
|
+
displayName: rawUser.name,
|
|
93
|
+
avatar: rawUser.avatar_url,
|
|
94
|
+
email: rawUser.email,
|
|
95
|
+
raw: rawUser,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Place the file at `src/providers/<name>.js` where `<name>` matches the key in your config's `providers` object.
|
|
102
|
+
|
|
103
|
+
Alternatively, specify a custom module path in the provider config:
|
|
104
|
+
|
|
105
|
+
```javascript
|
|
106
|
+
providers: {
|
|
107
|
+
custom: {
|
|
108
|
+
clientId: '...',
|
|
109
|
+
clientSecret: '...',
|
|
110
|
+
module: './lib/my-custom-provider.js',
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Session Management
|
|
116
|
+
|
|
117
|
+
Sessions are stored in-memory using a `Map`. Sessions are lost on server restart.
|
|
118
|
+
|
|
119
|
+
Clients should store the `sessionId` returned from the callback and send it as a `session-id` header on subsequent requests.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
Apache-2.0
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@stonyx/oauth",
|
|
3
|
+
"keywords": [
|
|
4
|
+
"stonyx-async",
|
|
5
|
+
"stonyx-module"
|
|
6
|
+
],
|
|
7
|
+
"version": "0.1.0",
|
|
8
|
+
"description": "OAuth2 authentication module for the Stonyx framework",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/abofs/stonyx-oauth.git"
|
|
12
|
+
},
|
|
13
|
+
"main": "src/main.js",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./src/main.js"
|
|
17
|
+
},
|
|
18
|
+
"author": "Stone Costa",
|
|
19
|
+
"license": "Apache-2.0",
|
|
20
|
+
"contributors": [
|
|
21
|
+
"Stone Costa <stone.costa@synamicd.com>"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"stonyx": "^0.2.0"
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"@stonyx/rest-server": ">=0.2.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@stonyx/rest-server": "^0.2.0",
|
|
34
|
+
"@stonyx/utils": "^0.2.2",
|
|
35
|
+
"qunit": "^2.24.1",
|
|
36
|
+
"sinon": "^21.0.0"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "stonyx test"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Request } from '@stonyx/rest-server';
|
|
2
|
+
|
|
3
|
+
export default class AuthRequest extends Request {
|
|
4
|
+
constructor(oauth) {
|
|
5
|
+
super();
|
|
6
|
+
this.oauth = oauth;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
handlers = {
|
|
10
|
+
get: {
|
|
11
|
+
'/': ({ headers }) => {
|
|
12
|
+
const sessionId = headers['session-id'];
|
|
13
|
+
if (!sessionId) return 401;
|
|
14
|
+
|
|
15
|
+
const user = this.oauth.getSession(sessionId);
|
|
16
|
+
if (!user) return 401;
|
|
17
|
+
|
|
18
|
+
return user;
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
'/login/:provider': (req, state) => {
|
|
22
|
+
const { provider: providerName } = req.params;
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
const url = this.oauth.getAuthorizationUrl(providerName);
|
|
26
|
+
state.redirect = url;
|
|
27
|
+
} catch {
|
|
28
|
+
return 404;
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
|
|
32
|
+
'/callback/:provider': async (req) => {
|
|
33
|
+
const { provider: providerName } = req.params;
|
|
34
|
+
const { code, state: stateToken } = req.query;
|
|
35
|
+
|
|
36
|
+
if (!code) return 400;
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
return await this.oauth.handleCallback(providerName, code, stateToken);
|
|
40
|
+
} catch {
|
|
41
|
+
return 500;
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
'/logout': ({ headers }) => {
|
|
46
|
+
const sessionId = headers['session-id'];
|
|
47
|
+
if (sessionId) this.oauth.logout(sessionId);
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
package/src/main.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import config from 'stonyx/config';
|
|
2
|
+
import log from 'stonyx/log';
|
|
3
|
+
import { waitForModule } from 'stonyx';
|
|
4
|
+
import RestServer from '@stonyx/rest-server';
|
|
5
|
+
import TokenManager from './token-manager.js';
|
|
6
|
+
import SessionManager from './session-manager.js';
|
|
7
|
+
import AuthRequest from './auth-request.js';
|
|
8
|
+
|
|
9
|
+
export default class OAuth {
|
|
10
|
+
providers = new Map();
|
|
11
|
+
|
|
12
|
+
constructor() {
|
|
13
|
+
if (OAuth.instance) return OAuth.instance;
|
|
14
|
+
OAuth.instance = this;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async init() {
|
|
18
|
+
const { providers, sessionDuration } = config.oauth;
|
|
19
|
+
|
|
20
|
+
for (const [name, providerConfig] of Object.entries(providers)) {
|
|
21
|
+
const modulePath = providerConfig.module
|
|
22
|
+
? `${config.rootPath}/${providerConfig.module}`
|
|
23
|
+
: `./providers/${name}.js`;
|
|
24
|
+
const { default: Provider } = await import(modulePath);
|
|
25
|
+
const flow = new Provider(providerConfig);
|
|
26
|
+
this.providers.set(name, { flow, tokenManager: new TokenManager(flow) });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
this.sessionManager = new SessionManager(sessionDuration);
|
|
30
|
+
|
|
31
|
+
await waitForModule('rest-server');
|
|
32
|
+
RestServer.instance.mountRoute(AuthRequest, { name: 'auth', options: this });
|
|
33
|
+
|
|
34
|
+
log.oauth?.('OAuth module initialized');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
getProvider(name) {
|
|
38
|
+
const provider = this.providers.get(name);
|
|
39
|
+
if (!provider) throw new Error(`OAuth provider "${name}" is not configured`);
|
|
40
|
+
return provider;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
getAuthorizationUrl(providerName) {
|
|
44
|
+
const { flow } = this.getProvider(providerName);
|
|
45
|
+
const stateToken = crypto.randomUUID();
|
|
46
|
+
return flow.buildAuthorizationUrl(stateToken);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async handleCallback(providerName, code) {
|
|
50
|
+
const { flow, tokenManager } = this.getProvider(providerName);
|
|
51
|
+
const tokens = await tokenManager.getTokens(code);
|
|
52
|
+
const rawUser = await flow.fetchUserInfo(tokens.accessToken);
|
|
53
|
+
const user = flow.normalizeUser(rawUser);
|
|
54
|
+
return this.sessionManager.create(user, tokens);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
getSession(sessionId) {
|
|
58
|
+
return this.sessionManager.validate(sessionId);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
logout(sessionId) {
|
|
62
|
+
this.sessionManager.destroy(sessionId);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export default class OAuthFlow {
|
|
2
|
+
constructor({ clientId, clientSecret, redirectUri, scopes, authorizationUrl, tokenUrl, userInfoUrl }) {
|
|
3
|
+
this.clientId = clientId;
|
|
4
|
+
this.clientSecret = clientSecret;
|
|
5
|
+
this.redirectUri = redirectUri;
|
|
6
|
+
this.scopes = scopes || [];
|
|
7
|
+
this.authorizationUrl = authorizationUrl;
|
|
8
|
+
this.tokenUrl = tokenUrl;
|
|
9
|
+
this.userInfoUrl = userInfoUrl;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
buildAuthorizationUrl(stateToken) {
|
|
13
|
+
const params = new URLSearchParams({
|
|
14
|
+
client_id: this.clientId,
|
|
15
|
+
redirect_uri: this.redirectUri,
|
|
16
|
+
response_type: 'code',
|
|
17
|
+
scope: this.scopes.join(' '),
|
|
18
|
+
state: stateToken,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
return `${this.authorizationUrl}?${params.toString()}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async exchangeCode(code) {
|
|
25
|
+
const response = await fetch(this.tokenUrl, {
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: { 'Content-Type': 'application/json' },
|
|
28
|
+
body: JSON.stringify({
|
|
29
|
+
client_id: this.clientId,
|
|
30
|
+
client_secret: this.clientSecret,
|
|
31
|
+
grant_type: 'authorization_code',
|
|
32
|
+
code,
|
|
33
|
+
redirect_uri: this.redirectUri,
|
|
34
|
+
}),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
if (!response.ok) throw new Error(`Token exchange failed: ${response.status}`);
|
|
38
|
+
|
|
39
|
+
const data = await response.json();
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
accessToken: data.access_token,
|
|
43
|
+
refreshToken: data.refresh_token || null,
|
|
44
|
+
expiresIn: data.expires_in,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async refreshAccessToken(refreshToken) {
|
|
49
|
+
const response = await fetch(this.tokenUrl, {
|
|
50
|
+
method: 'POST',
|
|
51
|
+
headers: { 'Content-Type': 'application/json' },
|
|
52
|
+
body: JSON.stringify({
|
|
53
|
+
client_id: this.clientId,
|
|
54
|
+
client_secret: this.clientSecret,
|
|
55
|
+
grant_type: 'refresh_token',
|
|
56
|
+
refresh_token: refreshToken,
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
if (!response.ok) throw new Error(`Token refresh failed: ${response.status}`);
|
|
61
|
+
|
|
62
|
+
const data = await response.json();
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
accessToken: data.access_token,
|
|
66
|
+
refreshToken: data.refresh_token || refreshToken,
|
|
67
|
+
expiresIn: data.expires_in,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async fetchUserInfo(accessToken) {
|
|
72
|
+
const response = await fetch(this.userInfoUrl, {
|
|
73
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
if (!response.ok) throw new Error(`User info fetch failed: ${response.status}`);
|
|
77
|
+
|
|
78
|
+
return response.json();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
normalizeUser(rawUser) {
|
|
82
|
+
return { raw: rawUser };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async revokeToken(_accessToken) {
|
|
86
|
+
// Optional — providers override if supported
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import OAuthFlow from '../oauth-flow.js';
|
|
2
|
+
|
|
3
|
+
export default class DiscordProvider extends OAuthFlow {
|
|
4
|
+
constructor(config) {
|
|
5
|
+
super({
|
|
6
|
+
...config,
|
|
7
|
+
authorizationUrl: 'https://discord.com/oauth2/authorize',
|
|
8
|
+
tokenUrl: 'https://discord.com/api/oauth2/token',
|
|
9
|
+
userInfoUrl: 'https://discord.com/api/users/@me',
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async exchangeCode(code) {
|
|
14
|
+
const response = await fetch(this.tokenUrl, {
|
|
15
|
+
method: 'POST',
|
|
16
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
17
|
+
body: new URLSearchParams({
|
|
18
|
+
client_id: this.clientId,
|
|
19
|
+
client_secret: this.clientSecret,
|
|
20
|
+
grant_type: 'authorization_code',
|
|
21
|
+
code,
|
|
22
|
+
redirect_uri: this.redirectUri,
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
if (!response.ok) throw new Error(`Token exchange failed: ${response.status}`);
|
|
27
|
+
|
|
28
|
+
const data = await response.json();
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
accessToken: data.access_token,
|
|
32
|
+
refreshToken: data.refresh_token || null,
|
|
33
|
+
expiresIn: data.expires_in,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
normalizeUser(rawUser) {
|
|
38
|
+
const { id, username, global_name, avatar, email } = rawUser;
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
id,
|
|
42
|
+
username,
|
|
43
|
+
displayName: global_name || username,
|
|
44
|
+
avatar: avatar ? `https://cdn.discordapp.com/avatars/${id}/${avatar}.png` : null,
|
|
45
|
+
email: email || null,
|
|
46
|
+
raw: rawUser,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export default class SessionManager {
|
|
4
|
+
sessions = new Map();
|
|
5
|
+
|
|
6
|
+
constructor(duration) {
|
|
7
|
+
this.duration = duration;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
create(user, tokens) {
|
|
11
|
+
const sessionId = randomUUID();
|
|
12
|
+
const expiresAt = Date.now() + (this.duration * 1000);
|
|
13
|
+
|
|
14
|
+
this.sessions.set(sessionId, { user, tokens, expiresAt });
|
|
15
|
+
|
|
16
|
+
return { sessionId, user, expiresAt };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get(sessionId) {
|
|
20
|
+
return this.sessions.get(sessionId) || null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
destroy(sessionId) {
|
|
24
|
+
this.sessions.delete(sessionId);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
validate(sessionId) {
|
|
28
|
+
const session = this.get(sessionId);
|
|
29
|
+
if (!session) return null;
|
|
30
|
+
|
|
31
|
+
if (Date.now() >= session.expiresAt) {
|
|
32
|
+
this.destroy(sessionId);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return session.user;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export default class TokenManager {
|
|
2
|
+
constructor(flow) {
|
|
3
|
+
this.flow = flow;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
async getTokens(code) {
|
|
7
|
+
const tokens = await this.flow.exchangeCode(code);
|
|
8
|
+
tokens.expiresAt = Date.now() + (tokens.expiresIn * 1000);
|
|
9
|
+
return tokens;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async refresh(refreshToken) {
|
|
13
|
+
const tokens = await this.flow.refreshAccessToken(refreshToken);
|
|
14
|
+
tokens.expiresAt = Date.now() + (tokens.expiresIn * 1000);
|
|
15
|
+
return tokens;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async revoke(accessToken) {
|
|
19
|
+
return this.flow.revokeToken(accessToken);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
isExpired(tokenData) {
|
|
23
|
+
if (!tokenData?.expiresAt) return true;
|
|
24
|
+
return Date.now() >= tokenData.expiresAt;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
restServer: {
|
|
3
|
+
dir: './test/sample/requests',
|
|
4
|
+
},
|
|
5
|
+
oauth: {
|
|
6
|
+
providers: {
|
|
7
|
+
mock: {
|
|
8
|
+
clientId: 'test-client-id',
|
|
9
|
+
clientSecret: 'test-client-secret',
|
|
10
|
+
redirectUri: 'http://localhost:2666/auth/callback/mock',
|
|
11
|
+
scopes: ['identify'],
|
|
12
|
+
module: './test/sample/providers/mock.js',
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
sessionDuration: 3600,
|
|
16
|
+
}
|
|
17
|
+
};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import QUnit from 'qunit';
|
|
2
|
+
import RestServer from '@stonyx/rest-server';
|
|
3
|
+
import config from 'stonyx/config';
|
|
4
|
+
import { setupIntegrationTests } from 'stonyx/test-helpers';
|
|
5
|
+
|
|
6
|
+
const { module, test } = QUnit;
|
|
7
|
+
let endpoint;
|
|
8
|
+
|
|
9
|
+
module('[Integration] OAuth', function(hooks) {
|
|
10
|
+
setupIntegrationTests(hooks);
|
|
11
|
+
|
|
12
|
+
hooks.before(function() {
|
|
13
|
+
endpoint = `http://localhost:${config.restServer.port}`;
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
hooks.after(function() {
|
|
17
|
+
RestServer.close();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('GET /auth/login/mock redirects to provider auth URL', async function(assert) {
|
|
21
|
+
const response = await fetch(`${endpoint}/auth/login/mock`, { redirect: 'manual' });
|
|
22
|
+
|
|
23
|
+
assert.equal(response.status, 302);
|
|
24
|
+
|
|
25
|
+
const location = response.headers.get('location');
|
|
26
|
+
assert.ok(location.startsWith('https://mock.provider/oauth/authorize?'));
|
|
27
|
+
assert.ok(location.includes('client_id=test-client-id'));
|
|
28
|
+
assert.ok(location.includes('response_type=code'));
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('GET /auth/login/nonexistent returns 404', async function(assert) {
|
|
32
|
+
const response = await fetch(`${endpoint}/auth/login/nonexistent`, { redirect: 'manual' });
|
|
33
|
+
|
|
34
|
+
assert.equal(response.status, 404);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('GET /auth/callback/mock exchanges code and returns session', async function(assert) {
|
|
38
|
+
const response = await fetch(`${endpoint}/auth/callback/mock?code=test-auth-code&state=abc`);
|
|
39
|
+
const data = await response.json();
|
|
40
|
+
|
|
41
|
+
assert.equal(response.status, 200);
|
|
42
|
+
assert.ok(data.sessionId);
|
|
43
|
+
assert.ok(data.user);
|
|
44
|
+
assert.equal(data.user.id, 'mock-user-123');
|
|
45
|
+
assert.equal(data.user.username, 'mockuser');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('GET /auth with valid session returns user', async function(assert) {
|
|
49
|
+
// Create a session first
|
|
50
|
+
const callbackResponse = await fetch(`${endpoint}/auth/callback/mock?code=test-code&state=abc`);
|
|
51
|
+
const { sessionId } = await callbackResponse.json();
|
|
52
|
+
|
|
53
|
+
const response = await fetch(`${endpoint}/auth`, {
|
|
54
|
+
headers: { 'session-id': sessionId },
|
|
55
|
+
});
|
|
56
|
+
const data = await response.json();
|
|
57
|
+
|
|
58
|
+
assert.equal(response.status, 200);
|
|
59
|
+
assert.equal(data.id, 'mock-user-123');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('GET /auth without session returns 401', async function(assert) {
|
|
63
|
+
const response = await fetch(`${endpoint}/auth`);
|
|
64
|
+
|
|
65
|
+
assert.equal(response.status, 401);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('GET /auth with invalid session returns 401', async function(assert) {
|
|
69
|
+
const response = await fetch(`${endpoint}/auth`, {
|
|
70
|
+
headers: { 'session-id': 'invalid-session' },
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
assert.equal(response.status, 401);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('GET /auth/logout invalidates session', async function(assert) {
|
|
77
|
+
// Create a session
|
|
78
|
+
const callbackResponse = await fetch(`${endpoint}/auth/callback/mock?code=test-code&state=abc`);
|
|
79
|
+
const { sessionId } = await callbackResponse.json();
|
|
80
|
+
|
|
81
|
+
// Logout
|
|
82
|
+
const logoutResponse = await fetch(`${endpoint}/auth/logout`, {
|
|
83
|
+
headers: { 'session-id': sessionId },
|
|
84
|
+
});
|
|
85
|
+
assert.equal(logoutResponse.status, 200);
|
|
86
|
+
|
|
87
|
+
// Verify session is invalid
|
|
88
|
+
const authResponse = await fetch(`${endpoint}/auth`, {
|
|
89
|
+
headers: { 'session-id': sessionId },
|
|
90
|
+
});
|
|
91
|
+
assert.equal(authResponse.status, 401);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import OAuthFlow from '../../../src/oauth-flow.js';
|
|
2
|
+
|
|
3
|
+
export default class MockProvider extends OAuthFlow {
|
|
4
|
+
constructor(config) {
|
|
5
|
+
super({
|
|
6
|
+
...config,
|
|
7
|
+
authorizationUrl: 'https://mock.provider/oauth/authorize',
|
|
8
|
+
tokenUrl: 'https://mock.provider/oauth/token',
|
|
9
|
+
userInfoUrl: 'https://mock.provider/api/me',
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async exchangeCode(_code) {
|
|
14
|
+
return {
|
|
15
|
+
accessToken: 'mock-access-token',
|
|
16
|
+
refreshToken: 'mock-refresh-token',
|
|
17
|
+
expiresIn: 3600,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async fetchUserInfo(_accessToken) {
|
|
22
|
+
return {
|
|
23
|
+
id: 'mock-user-123',
|
|
24
|
+
username: 'mockuser',
|
|
25
|
+
displayName: 'Mock User',
|
|
26
|
+
email: 'mock@test.com',
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
normalizeUser(rawUser) {
|
|
31
|
+
return {
|
|
32
|
+
id: rawUser.id,
|
|
33
|
+
username: rawUser.username,
|
|
34
|
+
displayName: rawUser.displayName,
|
|
35
|
+
avatar: null,
|
|
36
|
+
email: rawUser.email,
|
|
37
|
+
raw: rawUser,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import QUnit from 'qunit';
|
|
2
|
+
import OAuthFlow from '../../src/oauth-flow.js';
|
|
3
|
+
|
|
4
|
+
const { module, test } = QUnit;
|
|
5
|
+
|
|
6
|
+
const defaultConfig = {
|
|
7
|
+
clientId: 'test-client',
|
|
8
|
+
clientSecret: 'test-secret',
|
|
9
|
+
redirectUri: 'http://localhost/callback',
|
|
10
|
+
scopes: ['read', 'write'],
|
|
11
|
+
authorizationUrl: 'https://provider.com/oauth/authorize',
|
|
12
|
+
tokenUrl: 'https://provider.com/oauth/token',
|
|
13
|
+
userInfoUrl: 'https://provider.com/api/me',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
module('[Unit] OAuthFlow', function() {
|
|
17
|
+
module('buildAuthorizationUrl', function() {
|
|
18
|
+
test('generates a valid authorization URL with all params', function(assert) {
|
|
19
|
+
const flow = new OAuthFlow(defaultConfig);
|
|
20
|
+
const url = flow.buildAuthorizationUrl('test-state-123');
|
|
21
|
+
|
|
22
|
+
assert.ok(url.startsWith('https://provider.com/oauth/authorize?'));
|
|
23
|
+
assert.ok(url.includes('client_id=test-client'));
|
|
24
|
+
assert.ok(url.includes('redirect_uri='));
|
|
25
|
+
assert.ok(url.includes('response_type=code'));
|
|
26
|
+
assert.ok(url.includes('scope=read+write'));
|
|
27
|
+
assert.ok(url.includes('state=test-state-123'));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('handles empty scopes', function(assert) {
|
|
31
|
+
const flow = new OAuthFlow({ ...defaultConfig, scopes: [] });
|
|
32
|
+
const url = flow.buildAuthorizationUrl('state');
|
|
33
|
+
|
|
34
|
+
assert.ok(url.includes('scope='));
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
module('exchangeCode', function() {
|
|
39
|
+
test('makes a POST request to the token URL', async function(assert) {
|
|
40
|
+
const flow = new OAuthFlow(defaultConfig);
|
|
41
|
+
const originalFetch = globalThis.fetch;
|
|
42
|
+
|
|
43
|
+
globalThis.fetch = async (url, options) => {
|
|
44
|
+
assert.equal(url, 'https://provider.com/oauth/token');
|
|
45
|
+
assert.equal(options.method, 'POST');
|
|
46
|
+
assert.equal(options.headers['Content-Type'], 'application/json');
|
|
47
|
+
|
|
48
|
+
const body = JSON.parse(options.body);
|
|
49
|
+
assert.equal(body.grant_type, 'authorization_code');
|
|
50
|
+
assert.equal(body.code, 'test-code');
|
|
51
|
+
assert.equal(body.client_id, 'test-client');
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
ok: true,
|
|
55
|
+
json: async () => ({ access_token: 'abc', refresh_token: 'def', expires_in: 3600 }),
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const result = await flow.exchangeCode('test-code');
|
|
60
|
+
|
|
61
|
+
assert.equal(result.accessToken, 'abc');
|
|
62
|
+
assert.equal(result.refreshToken, 'def');
|
|
63
|
+
assert.equal(result.expiresIn, 3600);
|
|
64
|
+
|
|
65
|
+
globalThis.fetch = originalFetch;
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('throws on failed token exchange', async function(assert) {
|
|
69
|
+
const flow = new OAuthFlow(defaultConfig);
|
|
70
|
+
const originalFetch = globalThis.fetch;
|
|
71
|
+
|
|
72
|
+
globalThis.fetch = async () => ({ ok: false, status: 400 });
|
|
73
|
+
|
|
74
|
+
await assert.rejects(flow.exchangeCode('bad-code'), /Token exchange failed: 400/);
|
|
75
|
+
|
|
76
|
+
globalThis.fetch = originalFetch;
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
module('refreshAccessToken', function() {
|
|
81
|
+
test('makes a refresh grant request', async function(assert) {
|
|
82
|
+
const flow = new OAuthFlow(defaultConfig);
|
|
83
|
+
const originalFetch = globalThis.fetch;
|
|
84
|
+
|
|
85
|
+
globalThis.fetch = async (_url, options) => {
|
|
86
|
+
const body = JSON.parse(options.body);
|
|
87
|
+
assert.equal(body.grant_type, 'refresh_token');
|
|
88
|
+
assert.equal(body.refresh_token, 'old-refresh');
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
ok: true,
|
|
92
|
+
json: async () => ({ access_token: 'new-access', expires_in: 7200 }),
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const result = await flow.refreshAccessToken('old-refresh');
|
|
97
|
+
|
|
98
|
+
assert.equal(result.accessToken, 'new-access');
|
|
99
|
+
assert.equal(result.refreshToken, 'old-refresh', 'falls back to original refresh token');
|
|
100
|
+
assert.equal(result.expiresIn, 7200);
|
|
101
|
+
|
|
102
|
+
globalThis.fetch = originalFetch;
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
module('fetchUserInfo', function() {
|
|
107
|
+
test('sends a Bearer token in the Authorization header', async function(assert) {
|
|
108
|
+
const flow = new OAuthFlow(defaultConfig);
|
|
109
|
+
const originalFetch = globalThis.fetch;
|
|
110
|
+
|
|
111
|
+
globalThis.fetch = async (url, options) => {
|
|
112
|
+
assert.equal(url, 'https://provider.com/api/me');
|
|
113
|
+
assert.equal(options.headers.Authorization, 'Bearer my-token');
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
ok: true,
|
|
117
|
+
json: async () => ({ id: '1', name: 'Test' }),
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const result = await flow.fetchUserInfo('my-token');
|
|
122
|
+
assert.deepEqual(result, { id: '1', name: 'Test' });
|
|
123
|
+
|
|
124
|
+
globalThis.fetch = originalFetch;
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
module('normalizeUser', function() {
|
|
129
|
+
test('returns raw user by default', function(assert) {
|
|
130
|
+
const flow = new OAuthFlow(defaultConfig);
|
|
131
|
+
const raw = { id: '1', name: 'Test' };
|
|
132
|
+
const result = flow.normalizeUser(raw);
|
|
133
|
+
|
|
134
|
+
assert.deepEqual(result, { raw });
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import QUnit from 'qunit';
|
|
2
|
+
import DiscordProvider from '../../../src/providers/discord.js';
|
|
3
|
+
|
|
4
|
+
const { module, test } = QUnit;
|
|
5
|
+
|
|
6
|
+
const defaultConfig = {
|
|
7
|
+
clientId: 'discord-client-id',
|
|
8
|
+
clientSecret: 'discord-client-secret',
|
|
9
|
+
redirectUri: 'http://localhost/auth/callback/discord',
|
|
10
|
+
scopes: ['identify', 'email'],
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
module('[Unit] DiscordProvider', function() {
|
|
14
|
+
module('constructor', function() {
|
|
15
|
+
test('sets correct Discord OAuth2 URLs', function(assert) {
|
|
16
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
17
|
+
|
|
18
|
+
assert.equal(provider.authorizationUrl, 'https://discord.com/oauth2/authorize');
|
|
19
|
+
assert.equal(provider.tokenUrl, 'https://discord.com/api/oauth2/token');
|
|
20
|
+
assert.equal(provider.userInfoUrl, 'https://discord.com/api/users/@me');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('preserves client config', function(assert) {
|
|
24
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
25
|
+
|
|
26
|
+
assert.equal(provider.clientId, 'discord-client-id');
|
|
27
|
+
assert.equal(provider.clientSecret, 'discord-client-secret');
|
|
28
|
+
assert.deepEqual(provider.scopes, ['identify', 'email']);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
module('exchangeCode', function() {
|
|
33
|
+
test('uses form-encoded body for Discord token exchange', async function(assert) {
|
|
34
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
35
|
+
const originalFetch = globalThis.fetch;
|
|
36
|
+
|
|
37
|
+
globalThis.fetch = async (url, options) => {
|
|
38
|
+
assert.equal(url, 'https://discord.com/api/oauth2/token');
|
|
39
|
+
assert.equal(options.headers['Content-Type'], 'application/x-www-form-urlencoded');
|
|
40
|
+
assert.ok(options.body instanceof URLSearchParams);
|
|
41
|
+
|
|
42
|
+
const params = Object.fromEntries(options.body);
|
|
43
|
+
assert.equal(params.grant_type, 'authorization_code');
|
|
44
|
+
assert.equal(params.code, 'discord-auth-code');
|
|
45
|
+
assert.equal(params.client_id, 'discord-client-id');
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
ok: true,
|
|
49
|
+
json: async () => ({ access_token: 'discord-token', refresh_token: 'refresh', expires_in: 604800 }),
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const result = await provider.exchangeCode('discord-auth-code');
|
|
54
|
+
|
|
55
|
+
assert.equal(result.accessToken, 'discord-token');
|
|
56
|
+
assert.equal(result.refreshToken, 'refresh');
|
|
57
|
+
assert.equal(result.expiresIn, 604800);
|
|
58
|
+
|
|
59
|
+
globalThis.fetch = originalFetch;
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
module('normalizeUser', function() {
|
|
64
|
+
test('maps Discord user fields correctly', function(assert) {
|
|
65
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
66
|
+
|
|
67
|
+
const discordUser = {
|
|
68
|
+
id: '123456789',
|
|
69
|
+
username: 'testuser',
|
|
70
|
+
global_name: 'Test User',
|
|
71
|
+
avatar: 'abc123',
|
|
72
|
+
email: 'test@example.com',
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const result = provider.normalizeUser(discordUser);
|
|
76
|
+
|
|
77
|
+
assert.equal(result.id, '123456789');
|
|
78
|
+
assert.equal(result.username, 'testuser');
|
|
79
|
+
assert.equal(result.displayName, 'Test User');
|
|
80
|
+
assert.equal(result.avatar, 'https://cdn.discordapp.com/avatars/123456789/abc123.png');
|
|
81
|
+
assert.equal(result.email, 'test@example.com');
|
|
82
|
+
assert.deepEqual(result.raw, discordUser);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('handles missing avatar', function(assert) {
|
|
86
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
87
|
+
|
|
88
|
+
const result = provider.normalizeUser({
|
|
89
|
+
id: '1', username: 'user', global_name: 'User', avatar: null, email: null,
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
assert.equal(result.avatar, null);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('falls back to username when global_name is missing', function(assert) {
|
|
96
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
97
|
+
|
|
98
|
+
const result = provider.normalizeUser({
|
|
99
|
+
id: '1', username: 'myuser', avatar: null, email: null,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
assert.equal(result.displayName, 'myuser');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test('handles missing email', function(assert) {
|
|
106
|
+
const provider = new DiscordProvider(defaultConfig);
|
|
107
|
+
|
|
108
|
+
const result = provider.normalizeUser({
|
|
109
|
+
id: '1', username: 'user', global_name: 'User', avatar: null,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
assert.equal(result.email, null);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import QUnit from 'qunit';
|
|
2
|
+
import SessionManager from '../../src/session-manager.js';
|
|
3
|
+
|
|
4
|
+
const { module, test } = QUnit;
|
|
5
|
+
|
|
6
|
+
const mockUser = { id: '1', username: 'testuser' };
|
|
7
|
+
const mockTokens = { accessToken: 'abc', expiresAt: Date.now() + 60000 };
|
|
8
|
+
|
|
9
|
+
module('[Unit] SessionManager', function() {
|
|
10
|
+
module('create', function() {
|
|
11
|
+
test('generates a unique session ID and stores session', function(assert) {
|
|
12
|
+
const manager = new SessionManager(3600);
|
|
13
|
+
const session1 = manager.create(mockUser, mockTokens);
|
|
14
|
+
const session2 = manager.create(mockUser, mockTokens);
|
|
15
|
+
|
|
16
|
+
assert.ok(session1.sessionId);
|
|
17
|
+
assert.ok(session2.sessionId);
|
|
18
|
+
assert.notEqual(session1.sessionId, session2.sessionId);
|
|
19
|
+
assert.deepEqual(session1.user, mockUser);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('sets expiresAt based on duration', function(assert) {
|
|
23
|
+
const manager = new SessionManager(3600);
|
|
24
|
+
const before = Date.now();
|
|
25
|
+
const session = manager.create(mockUser, mockTokens);
|
|
26
|
+
|
|
27
|
+
assert.ok(session.expiresAt >= before + 3600 * 1000);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
module('get', function() {
|
|
32
|
+
test('returns session data for a valid session ID', function(assert) {
|
|
33
|
+
const manager = new SessionManager(3600);
|
|
34
|
+
const { sessionId } = manager.create(mockUser, mockTokens);
|
|
35
|
+
const session = manager.get(sessionId);
|
|
36
|
+
|
|
37
|
+
assert.ok(session);
|
|
38
|
+
assert.deepEqual(session.user, mockUser);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('returns null for unknown session ID', function(assert) {
|
|
42
|
+
const manager = new SessionManager(3600);
|
|
43
|
+
const session = manager.get('nonexistent');
|
|
44
|
+
|
|
45
|
+
assert.equal(session, null);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
module('validate', function() {
|
|
50
|
+
test('returns user for a valid, non-expired session', function(assert) {
|
|
51
|
+
const manager = new SessionManager(3600);
|
|
52
|
+
const { sessionId } = manager.create(mockUser, mockTokens);
|
|
53
|
+
const user = manager.validate(sessionId);
|
|
54
|
+
|
|
55
|
+
assert.deepEqual(user, mockUser);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('returns null for an expired session and cleans it up', function(assert) {
|
|
59
|
+
const manager = new SessionManager(0);
|
|
60
|
+
const { sessionId } = manager.create(mockUser, mockTokens);
|
|
61
|
+
const user = manager.validate(sessionId);
|
|
62
|
+
|
|
63
|
+
assert.equal(user, null);
|
|
64
|
+
assert.equal(manager.get(sessionId), null);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('returns null for nonexistent session', function(assert) {
|
|
68
|
+
const manager = new SessionManager(3600);
|
|
69
|
+
const user = manager.validate('missing');
|
|
70
|
+
|
|
71
|
+
assert.equal(user, null);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
module('destroy', function() {
|
|
76
|
+
test('removes the session', function(assert) {
|
|
77
|
+
const manager = new SessionManager(3600);
|
|
78
|
+
const { sessionId } = manager.create(mockUser, mockTokens);
|
|
79
|
+
|
|
80
|
+
manager.destroy(sessionId);
|
|
81
|
+
|
|
82
|
+
assert.equal(manager.get(sessionId), null);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import QUnit from 'qunit';
|
|
2
|
+
import TokenManager from '../../src/token-manager.js';
|
|
3
|
+
|
|
4
|
+
const { module, test } = QUnit;
|
|
5
|
+
|
|
6
|
+
function createMockFlow() {
|
|
7
|
+
return {
|
|
8
|
+
exchangeCode: async (code) => ({
|
|
9
|
+
accessToken: `token-for-${code}`,
|
|
10
|
+
refreshToken: 'refresh-123',
|
|
11
|
+
expiresIn: 3600,
|
|
12
|
+
}),
|
|
13
|
+
refreshAccessToken: async (refreshToken) => ({
|
|
14
|
+
accessToken: 'new-access',
|
|
15
|
+
refreshToken,
|
|
16
|
+
expiresIn: 7200,
|
|
17
|
+
}),
|
|
18
|
+
revokeToken: async () => {},
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module('[Unit] TokenManager', function() {
|
|
23
|
+
module('getTokens', function() {
|
|
24
|
+
test('delegates to flow.exchangeCode and sets expiresAt', async function(assert) {
|
|
25
|
+
const manager = new TokenManager(createMockFlow());
|
|
26
|
+
const before = Date.now();
|
|
27
|
+
const result = await manager.getTokens('my-code');
|
|
28
|
+
|
|
29
|
+
assert.equal(result.accessToken, 'token-for-my-code');
|
|
30
|
+
assert.equal(result.refreshToken, 'refresh-123');
|
|
31
|
+
assert.ok(result.expiresAt >= before + 3600 * 1000);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
module('refresh', function() {
|
|
36
|
+
test('delegates to flow.refreshAccessToken and sets expiresAt', async function(assert) {
|
|
37
|
+
const manager = new TokenManager(createMockFlow());
|
|
38
|
+
const result = await manager.refresh('refresh-123');
|
|
39
|
+
|
|
40
|
+
assert.equal(result.accessToken, 'new-access');
|
|
41
|
+
assert.ok(result.expiresAt > Date.now());
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
module('revoke', function() {
|
|
46
|
+
test('delegates to flow.revokeToken', async function(assert) {
|
|
47
|
+
let revoked = false;
|
|
48
|
+
const flow = { ...createMockFlow(), revokeToken: async () => { revoked = true; } };
|
|
49
|
+
const manager = new TokenManager(flow);
|
|
50
|
+
|
|
51
|
+
await manager.revoke('some-token');
|
|
52
|
+
assert.ok(revoked);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
module('isExpired', function() {
|
|
57
|
+
test('returns true if expiresAt is in the past', function(assert) {
|
|
58
|
+
const manager = new TokenManager(createMockFlow());
|
|
59
|
+
|
|
60
|
+
assert.true(manager.isExpired({ expiresAt: Date.now() - 1000 }));
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('returns false if expiresAt is in the future', function(assert) {
|
|
64
|
+
const manager = new TokenManager(createMockFlow());
|
|
65
|
+
|
|
66
|
+
assert.false(manager.isExpired({ expiresAt: Date.now() + 60000 }));
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('returns true if tokenData is null or missing expiresAt', function(assert) {
|
|
70
|
+
const manager = new TokenManager(createMockFlow());
|
|
71
|
+
|
|
72
|
+
assert.true(manager.isExpired(null));
|
|
73
|
+
assert.true(manager.isExpired({}));
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
});
|