@stonyx/oauth 0.1.1-alpha.2 → 0.1.1-alpha.20
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/README.md +170 -3
- package/dist/auth-request.d.ts +143 -0
- package/dist/auth-request.js +340 -0
- package/dist/constants.d.ts +19 -0
- package/dist/constants.js +28 -0
- package/dist/main.d.ts +45 -0
- package/dist/main.js +81 -0
- package/dist/oauth-flow.d.ts +30 -0
- package/dist/oauth-flow.js +83 -0
- package/dist/providers/discord.d.ts +30 -0
- package/dist/providers/discord.js +43 -0
- package/dist/session-manager.d.ts +20 -0
- package/dist/session-manager.js +30 -0
- package/dist/state-store.d.ts +114 -0
- package/dist/state-store.js +142 -0
- package/dist/token-manager.d.ts +15 -0
- package/dist/token-manager.js +24 -0
- package/package.json +45 -9
- package/src/auth-request.ts +433 -0
- package/src/constants.ts +32 -0
- package/src/main.ts +123 -0
- package/src/{oauth-flow.js → oauth-flow.ts} +31 -7
- package/src/providers/{discord.js → discord.ts} +29 -3
- package/src/{session-manager.js → session-manager.ts} +19 -6
- package/src/state-store.ts +177 -0
- package/src/token-manager.ts +35 -0
- package/src/types/node.d.ts +10 -0
- package/src/types/stonyx-events.d.ts +4 -0
- package/src/types/stonyx-rest-server.d.ts +11 -0
- package/src/types/stonyx.d.ts +38 -0
- package/.github/workflows/ci.yml +0 -16
- package/.github/workflows/publish.yml +0 -51
- package/src/auth-request.js +0 -74
- package/src/main.js +0 -83
- package/src/token-manager.js +0 -26
- package/test/config/environment.js +0 -18
- package/test/integration/oauth-test.js +0 -149
- package/test/sample/providers/mock.js +0 -40
- package/test/sample/requests/.gitkeep +0 -0
- package/test/unit/oauth-flow-test.js +0 -137
- package/test/unit/providers/discord-test.js +0 -115
- package/test/unit/session-manager-test.js +0 -85
- package/test/unit/state-validation-test.js +0 -118
- package/test/unit/token-manager-test.js +0 -76
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { Request } from '@stonyx/rest-server';
|
|
2
|
+
import log from 'stonyx/log';
|
|
3
|
+
import { StateRejection } from './state-store.js';
|
|
4
|
+
import { MAX_BINDING_COOKIE_CANDIDATES, STATE_COOKIE_NAME, STATE_COOKIE_PATH, STATE_COOKIE_SAME_SITE, STATE_TTL_MS, } from './constants.js';
|
|
5
|
+
/**
|
|
6
|
+
* Hosts treated as a development origin by exact match, and — together with
|
|
7
|
+
* `127.0.0.0/8` and the IPv4-mapped IPv6 spellings of it — the only ones exempt
|
|
8
|
+
* from `Secure` on the binding cookie. See `AuthRequest.isSecureContext`.
|
|
9
|
+
*
|
|
10
|
+
* `0.0.0.0` and `::` are the wildcard bind addresses a developer reaches a
|
|
11
|
+
* local server on; `127.0.0.1` is covered by the `127.0.0.0/8` test rather than
|
|
12
|
+
* listed here, so the two are not silently redundant.
|
|
13
|
+
*/
|
|
14
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '::1', '0:0:0:0:0:0:0:1', '0.0.0.0', '::']);
|
|
15
|
+
/** `host` values whose port component is anything but a decimal port are rejected. */
|
|
16
|
+
const PORT_PATTERN = /^\d{1,5}$/;
|
|
17
|
+
/**
|
|
18
|
+
* The characters RFC 1123 permits in a registered hostname, plus `.`.
|
|
19
|
+
*
|
|
20
|
+
* Anything else — `@`, `,`, whitespace, `/` — means the value is not a bare
|
|
21
|
+
* hostname, and the caller fails secure rather than guessing. This is what
|
|
22
|
+
* rejects `localhost:80@evil.com` and a comma-joined multi-value `Host`.
|
|
23
|
+
*/
|
|
24
|
+
const HOSTNAME_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
25
|
+
/** A dotted-quad whose first octet is 127, i.e. real `127.0.0.0/8` membership. */
|
|
26
|
+
function isLoopbackIpv4(hostname) {
|
|
27
|
+
const octets = hostname.split('.');
|
|
28
|
+
if (octets.length !== 4)
|
|
29
|
+
return false;
|
|
30
|
+
if (!octets.every(octet => /^\d{1,3}$/.test(octet) && Number(octet) <= 255))
|
|
31
|
+
return false;
|
|
32
|
+
return Number(octets[0]) === 127;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* IPv4-mapped IPv6 loopback, in both spellings a dual-stack listener produces:
|
|
36
|
+
* `::ffff:127.0.0.1` and `::ffff:7f00:1`.
|
|
37
|
+
*/
|
|
38
|
+
function isLoopbackIpv6(hostname) {
|
|
39
|
+
const mapped = /^::ffff:(.+)$/.exec(hostname);
|
|
40
|
+
if (!mapped)
|
|
41
|
+
return false;
|
|
42
|
+
const rest = mapped[1];
|
|
43
|
+
if (isLoopbackIpv4(rest))
|
|
44
|
+
return true;
|
|
45
|
+
const hextets = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(rest);
|
|
46
|
+
if (!hextets)
|
|
47
|
+
return false;
|
|
48
|
+
return parseInt(hextets[1], 16) >>> 8 === 127;
|
|
49
|
+
}
|
|
50
|
+
export default class AuthRequest extends Request {
|
|
51
|
+
oauth;
|
|
52
|
+
constructor(oauth) {
|
|
53
|
+
super();
|
|
54
|
+
this.oauth = oauth;
|
|
55
|
+
}
|
|
56
|
+
handlers = {
|
|
57
|
+
get: {
|
|
58
|
+
'/': ({ headers }) => {
|
|
59
|
+
const sessionId = headers['session-id'];
|
|
60
|
+
if (!sessionId)
|
|
61
|
+
return 401;
|
|
62
|
+
const user = this.oauth.getSession(sessionId);
|
|
63
|
+
if (!user)
|
|
64
|
+
return 401;
|
|
65
|
+
return user;
|
|
66
|
+
},
|
|
67
|
+
'/login/:provider': (req, state) => {
|
|
68
|
+
const { provider: providerName } = req.params;
|
|
69
|
+
let authorization;
|
|
70
|
+
try {
|
|
71
|
+
authorization = this.oauth.getAuthorizationUrl(providerName);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return 404;
|
|
75
|
+
}
|
|
76
|
+
// Fail closed: a state we cannot bind to this client is exactly the
|
|
77
|
+
// defect this mechanism exists to prevent, so never issue one.
|
|
78
|
+
if (!this.setBindingCookie(req, authorization.bindingValue))
|
|
79
|
+
return 500;
|
|
80
|
+
state.redirect = authorization.url;
|
|
81
|
+
},
|
|
82
|
+
'/callback/:provider': async (req, state) => {
|
|
83
|
+
const { provider: providerName } = req.params;
|
|
84
|
+
const { code, state: stateToken, error } = req.query;
|
|
85
|
+
const bindingValues = this.readBindingCookies(req);
|
|
86
|
+
if (error) {
|
|
87
|
+
if (this.oauth.frontendCallbackUrl) {
|
|
88
|
+
state.redirect = `${this.oauth.frontendCallbackUrl}?error=${encodeURIComponent(error)}`;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
return 400;
|
|
92
|
+
}
|
|
93
|
+
if (!code)
|
|
94
|
+
return 400;
|
|
95
|
+
try {
|
|
96
|
+
const session = await this.oauth.handleCallback(providerName, code, stateToken, bindingValues);
|
|
97
|
+
// The binding value is single-use and the state has now been
|
|
98
|
+
// consumed, so this is the end of that cookie's life.
|
|
99
|
+
this.clearBindingCookie(req);
|
|
100
|
+
if (this.oauth.frontendCallbackUrl) {
|
|
101
|
+
const params = new URLSearchParams({
|
|
102
|
+
sessionId: session.sessionId,
|
|
103
|
+
expiresAt: String(session.expiresAt),
|
|
104
|
+
});
|
|
105
|
+
state.redirect = `${this.oauth.frontendCallbackUrl}?${params}`;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
return session;
|
|
109
|
+
}
|
|
110
|
+
catch (rejection) {
|
|
111
|
+
// Clear only when this request actually spent the cookie.
|
|
112
|
+
//
|
|
113
|
+
// Moving the clear below the `error` and `!code` returns was not
|
|
114
|
+
// enough: it still ran unconditionally for any request carrying a
|
|
115
|
+
// `code`, and `code` is attacker-supplied and unvalidated. So
|
|
116
|
+
// `?code=1` — one query parameter, no knowledge of the victim's state
|
|
117
|
+
// — deleted the binding cookie of a client still at the provider's
|
|
118
|
+
// consent screen, leaving their pending state untouched so nothing
|
|
119
|
+
// was detectable server-side, and their real callback then failed.
|
|
120
|
+
//
|
|
121
|
+
// `StateRejection.consumed` is the only thing that distinguishes
|
|
122
|
+
// "nothing of this client's was touched" from "one attempt was
|
|
123
|
+
// spent". Anything that is not a `StateRejection` was thrown below
|
|
124
|
+
// the state check, which means the record was already burned.
|
|
125
|
+
if (!(rejection instanceof StateRejection) || rejection.consumed) {
|
|
126
|
+
this.clearBindingCookie(req);
|
|
127
|
+
}
|
|
128
|
+
// `StateStore.consume` distinguishes five rejection reasons that
|
|
129
|
+
// otherwise collapse into one opaque outcome with no server-side
|
|
130
|
+
// signal at all. The client-facing `auth_failed` stays opaque; the
|
|
131
|
+
// server has no reason to be.
|
|
132
|
+
//
|
|
133
|
+
// Only a `StateRejection`'s message is logged, and those are the
|
|
134
|
+
// fixed strings in `STATE_REJECTION`. The `try` above spans far more
|
|
135
|
+
// than `consume` — `getProvider`, `TokenManager.getTokens` ->
|
|
136
|
+
// `flow.exchangeCode`, `flow.fetchUserInfo`, `flow.normalizeUser`,
|
|
137
|
+
// `emit('authenticate')`, `sessionManager.create` — and three of
|
|
138
|
+
// those are consumer-overridable through the documented
|
|
139
|
+
// `providers.<name>.module` extension point. A provider that puts
|
|
140
|
+
// request context in its error, which is ordinary practice, would
|
|
141
|
+
// otherwise land its `clientSecret` and the caller-supplied `code` in
|
|
142
|
+
// the log verbatim; `@stonyx/logs` appends content raw when
|
|
143
|
+
// `logToFile` is enabled, so an echoed `code` is also a CRLF
|
|
144
|
+
// log-forging primitive for an unauthenticated caller. Before this
|
|
145
|
+
// module logged anything, all of that was swallowed.
|
|
146
|
+
//
|
|
147
|
+
// Anything below the state check therefore gets a fixed
|
|
148
|
+
// discriminator, and the detail is left to whatever the provider
|
|
149
|
+
// itself logs.
|
|
150
|
+
if (rejection instanceof StateRejection) {
|
|
151
|
+
log.error(`OAuth: callback rejected — ${rejection.message}`);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
log.error('OAuth: callback failed after state validation');
|
|
155
|
+
}
|
|
156
|
+
if (this.oauth.frontendCallbackUrl) {
|
|
157
|
+
state.redirect = `${this.oauth.frontendCallbackUrl}?error=auth_failed`;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
return 500;
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
'/logout': ({ headers }) => {
|
|
164
|
+
const sessionId = headers['session-id'];
|
|
165
|
+
if (sessionId)
|
|
166
|
+
this.oauth.logout(sessionId);
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
cookieOptions(req) {
|
|
171
|
+
return {
|
|
172
|
+
httpOnly: true,
|
|
173
|
+
// Load-bearing: the callback is a cross-site top-level GET navigation
|
|
174
|
+
// from the provider. `Strict` withholds the cookie on exactly that
|
|
175
|
+
// request and breaks login outright.
|
|
176
|
+
sameSite: STATE_COOKIE_SAME_SITE,
|
|
177
|
+
path: STATE_COOKIE_PATH,
|
|
178
|
+
secure: this.isSecureContext(req),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Whether the binding cookie is issued with `Secure`.
|
|
183
|
+
*
|
|
184
|
+
* Not `req.secure`. Express derives that from the socket unless `trust proxy`
|
|
185
|
+
* is enabled, and `@stonyx/rest-server` leaves it off by default
|
|
186
|
+
* (`trustProxy: REST_TRUST_PROXY === 'true'`). In the standard production
|
|
187
|
+
* topology — TLS terminated at a proxy, plaintext to the origin — `req.secure`
|
|
188
|
+
* is therefore `false` on every request to an HTTPS site, and the binding
|
|
189
|
+
* cookie would ship without `Secure` while the deployment looks correct.
|
|
190
|
+
*
|
|
191
|
+
* So `Secure` is set unconditionally except on a loopback host. Guessing
|
|
192
|
+
* wrong there breaks a non-loopback plaintext development setup, which fails
|
|
193
|
+
* at the first login and is loud. The alternative fails silently, in
|
|
194
|
+
* production, on the one attribute protecting the value this whole mechanism
|
|
195
|
+
* is built around.
|
|
196
|
+
*
|
|
197
|
+
* The exemption is decided by *parsing* the `Host` header and testing the
|
|
198
|
+
* result for membership, never by matching a prefix or a suffix on the raw
|
|
199
|
+
* value — `Host` is attacker-controllable on any non-browser client, and a
|
|
200
|
+
* security predicate written as a substring match drifts. Every shape that
|
|
201
|
+
* cannot be parsed as a bare `host[:port]`, and every request with more than
|
|
202
|
+
* one `Host`, fails secure.
|
|
203
|
+
*/
|
|
204
|
+
isSecureContext(req) {
|
|
205
|
+
if (req.secure === true)
|
|
206
|
+
return true;
|
|
207
|
+
if (AuthRequest.hasAmbiguousHost(req))
|
|
208
|
+
return true;
|
|
209
|
+
const host = req.headers.host;
|
|
210
|
+
if (!host)
|
|
211
|
+
return true;
|
|
212
|
+
const hostname = AuthRequest.parseHostname(host);
|
|
213
|
+
if (hostname === undefined)
|
|
214
|
+
return true;
|
|
215
|
+
return !AuthRequest.isLoopbackHost(hostname);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* True when the request carried more than one `Host` header.
|
|
219
|
+
*
|
|
220
|
+
* Node keeps the first and discards the rest, so a component that *prepends*
|
|
221
|
+
* a `Host:` line — request smuggling, or a proxy that appends rather than
|
|
222
|
+
* replaces — can make `req.headers.host` read `localhost` on a request whose
|
|
223
|
+
* real origin is public. RFC 9112 section 3.2 makes such a request invalid;
|
|
224
|
+
* this treats it as unattributable and fails secure rather than trusting it.
|
|
225
|
+
*/
|
|
226
|
+
static hasAmbiguousHost(req) {
|
|
227
|
+
const raw = req.rawHeaders;
|
|
228
|
+
if (!Array.isArray(raw))
|
|
229
|
+
return false;
|
|
230
|
+
let seen = 0;
|
|
231
|
+
for (let index = 0; index < raw.length; index += 2) {
|
|
232
|
+
if (typeof raw[index] === 'string' && raw[index].toLowerCase() === 'host')
|
|
233
|
+
seen++;
|
|
234
|
+
}
|
|
235
|
+
return seen > 1;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The hostname component of a `Host` header, lowercased, or `undefined` when
|
|
239
|
+
* the value is not a well-formed `host[:port]`.
|
|
240
|
+
*
|
|
241
|
+
* `host.split(':')[0]` is not enough: it truncates at the *first* colon, so
|
|
242
|
+
* `localhost:80@evil.com` reduces to `localhost`. The port is therefore
|
|
243
|
+
* required to be decimal, and the hostname to contain only characters a
|
|
244
|
+
* registered name may contain.
|
|
245
|
+
*/
|
|
246
|
+
static parseHostname(host) {
|
|
247
|
+
if (host.startsWith('[')) {
|
|
248
|
+
const close = host.indexOf(']');
|
|
249
|
+
if (close === -1)
|
|
250
|
+
return undefined;
|
|
251
|
+
const port = host.slice(close + 1);
|
|
252
|
+
if (port !== '' && !(port.startsWith(':') && PORT_PATTERN.test(port.slice(1))))
|
|
253
|
+
return undefined;
|
|
254
|
+
const literal = host.slice(1, close);
|
|
255
|
+
if (!/^[0-9A-Fa-f:.]+$/.test(literal))
|
|
256
|
+
return undefined;
|
|
257
|
+
return literal.toLowerCase();
|
|
258
|
+
}
|
|
259
|
+
const colon = host.indexOf(':');
|
|
260
|
+
if (colon === -1)
|
|
261
|
+
return HOSTNAME_PATTERN.test(host) ? host.toLowerCase() : undefined;
|
|
262
|
+
if (!PORT_PATTERN.test(host.slice(colon + 1)))
|
|
263
|
+
return undefined;
|
|
264
|
+
const name = host.slice(0, colon);
|
|
265
|
+
return HOSTNAME_PATTERN.test(name) ? name.toLowerCase() : undefined;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Whether a parsed hostname is a loopback development origin.
|
|
269
|
+
*
|
|
270
|
+
* Membership tests, never prefix or suffix tests. `startsWith('127.')`
|
|
271
|
+
* matched `127.evil.com`, a perfectly registerable name (RFC 1123 permits a
|
|
272
|
+
* leading digit in a label), and `endsWith('.localhost')` exempted an entire
|
|
273
|
+
* suffix — so a `.localhost` split-horizon vhost shipped the binding value in
|
|
274
|
+
* cleartext. The `.localhost` exemption is withdrawn rather than tightened:
|
|
275
|
+
* the README documented `127.0.0.0/8`, `localhost`, `::1` and `0.0.0.0` and
|
|
276
|
+
* never documented it, and a developer on `app.localhost` reaches the same
|
|
277
|
+
* server on `localhost` or `127.0.0.1`.
|
|
278
|
+
*/
|
|
279
|
+
static isLoopbackHost(hostname) {
|
|
280
|
+
if (LOOPBACK_HOSTS.has(hostname))
|
|
281
|
+
return true;
|
|
282
|
+
if (isLoopbackIpv4(hostname))
|
|
283
|
+
return true;
|
|
284
|
+
return isLoopbackIpv6(hostname);
|
|
285
|
+
}
|
|
286
|
+
setBindingCookie(req, bindingValue) {
|
|
287
|
+
const { res } = req;
|
|
288
|
+
if (typeof res?.cookie !== 'function') {
|
|
289
|
+
log.error('OAuth: unable to set the state binding cookie; login rejected');
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
res.cookie(STATE_COOKIE_NAME, bindingValue, {
|
|
293
|
+
...this.cookieOptions(req),
|
|
294
|
+
maxAge: STATE_TTL_MS,
|
|
295
|
+
});
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Every value the client presented under the binding cookie's name.
|
|
300
|
+
*
|
|
301
|
+
* Not the first one. A browser sends every applicable cookie in a single
|
|
302
|
+
* header, and a sibling subdomain can set a same-named cookie on the parent
|
|
303
|
+
* domain that RFC 6265 section 5.4 orders *ahead* of the real one — so
|
|
304
|
+
* returning on the first name match handed an attacker a permanent,
|
|
305
|
+
* unauthenticated denial of login for any victim they could plant a cookie
|
|
306
|
+
* on. `Secure`, `HttpOnly` and `SameSite` do not constrain that: the attacker
|
|
307
|
+
* is writing, not reading.
|
|
308
|
+
*
|
|
309
|
+
* Bounded at `MAX_BINDING_COOKIE_CANDIDATES`, so the work an unauthenticated
|
|
310
|
+
* caller can ask for is capped whatever the header contains.
|
|
311
|
+
*/
|
|
312
|
+
readBindingCookies(req) {
|
|
313
|
+
const header = req.headers.cookie;
|
|
314
|
+
if (!header)
|
|
315
|
+
return [];
|
|
316
|
+
const values = [];
|
|
317
|
+
for (const part of header.split(';')) {
|
|
318
|
+
if (values.length >= MAX_BINDING_COOKIE_CANDIDATES)
|
|
319
|
+
break;
|
|
320
|
+
const separator = part.indexOf('=');
|
|
321
|
+
if (separator === -1)
|
|
322
|
+
continue;
|
|
323
|
+
if (part.slice(0, separator).trim() !== STATE_COOKIE_NAME)
|
|
324
|
+
continue;
|
|
325
|
+
// Not decoded. The binding value is base64url, whose alphabet
|
|
326
|
+
// `encodeURIComponent` never escapes, so a decode buys nothing — and
|
|
327
|
+
// `decodeURIComponent` throws `URIError` on malformed input, which any
|
|
328
|
+
// unauthenticated caller can supply, turning the first line of the
|
|
329
|
+
// callback into a 500 with a stack trace.
|
|
330
|
+
values.push(part.slice(separator + 1).trim());
|
|
331
|
+
}
|
|
332
|
+
return values;
|
|
333
|
+
}
|
|
334
|
+
clearBindingCookie(req) {
|
|
335
|
+
const { res } = req;
|
|
336
|
+
if (typeof res?.clearCookie !== 'function')
|
|
337
|
+
return;
|
|
338
|
+
res.clearCookie(STATE_COOKIE_NAME, this.cookieOptions(req));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const STATE_COOKIE_NAME = "stonyx_oauth_state";
|
|
2
|
+
export declare const STATE_COOKIE_PATH = "/auth";
|
|
3
|
+
export declare const STATE_COOKIE_SAME_SITE = "lax";
|
|
4
|
+
/** Lifetime of a pending state record, and the binding cookie's Max-Age. */
|
|
5
|
+
export declare const STATE_TTL_MS: number;
|
|
6
|
+
/** Entropy of the client-held binding value, in bytes. */
|
|
7
|
+
export declare const BINDING_VALUE_BYTES = 32;
|
|
8
|
+
/**
|
|
9
|
+
* Most values carrying `STATE_COOKIE_NAME` that a single callback will try.
|
|
10
|
+
*
|
|
11
|
+
* A client can hold more than one cookie of the same name — a sibling
|
|
12
|
+
* subdomain can set one on the parent domain, and the browser sends every
|
|
13
|
+
* applicable cookie in one header. All of them are tried, so a planted cookie
|
|
14
|
+
* cannot deny login by sorting ahead of the real one; the cap bounds the work
|
|
15
|
+
* an unauthenticated caller can ask for. It is not a brute-force control: the
|
|
16
|
+
* pending record is consumed on recognition, so a state gets one attempt
|
|
17
|
+
* whatever the cap.
|
|
18
|
+
*/
|
|
19
|
+
export declare const MAX_BINDING_COOKIE_CANDIDATES = 8;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Shared constants for the OAuth state/client-binding mechanism (#36).
|
|
2
|
+
//
|
|
3
|
+
// The binding cookie attributes are load-bearing, not cosmetic:
|
|
4
|
+
// - `SameSite=Lax` — the OAuth callback is a cross-site, top-level GET
|
|
5
|
+
// navigation initiated by the provider. `Strict` withholds the cookie on
|
|
6
|
+
// exactly that request and breaks login; `None` requires `Secure` and
|
|
7
|
+
// widens exposure for no benefit. `Lax` is the only correct value.
|
|
8
|
+
// - `Path=/auth` — the cookie is only ever read by the callback route.
|
|
9
|
+
// - `HttpOnly` — script must not be able to read or forge the binding value.
|
|
10
|
+
export const STATE_COOKIE_NAME = 'stonyx_oauth_state';
|
|
11
|
+
export const STATE_COOKIE_PATH = '/auth';
|
|
12
|
+
export const STATE_COOKIE_SAME_SITE = 'lax';
|
|
13
|
+
/** Lifetime of a pending state record, and the binding cookie's Max-Age. */
|
|
14
|
+
export const STATE_TTL_MS = 10 * 60 * 1000;
|
|
15
|
+
/** Entropy of the client-held binding value, in bytes. */
|
|
16
|
+
export const BINDING_VALUE_BYTES = 32;
|
|
17
|
+
/**
|
|
18
|
+
* Most values carrying `STATE_COOKIE_NAME` that a single callback will try.
|
|
19
|
+
*
|
|
20
|
+
* A client can hold more than one cookie of the same name — a sibling
|
|
21
|
+
* subdomain can set one on the parent domain, and the browser sends every
|
|
22
|
+
* applicable cookie in one header. All of them are tried, so a planted cookie
|
|
23
|
+
* cannot deny login by sorting ahead of the real one; the cap bounds the work
|
|
24
|
+
* an unauthenticated caller can ask for. It is not a brute-force control: the
|
|
25
|
+
* pending record is consumed on recognition, so a state gets one attempt
|
|
26
|
+
* whatever the cap.
|
|
27
|
+
*/
|
|
28
|
+
export const MAX_BINDING_COOKIE_CANDIDATES = 8;
|
package/dist/main.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import TokenManager from './token-manager.js';
|
|
2
|
+
import SessionManager from './session-manager.js';
|
|
3
|
+
import StateStore from './state-store.js';
|
|
4
|
+
import type OAuthFlow from './oauth-flow.js';
|
|
5
|
+
interface ProviderEntry {
|
|
6
|
+
flow: OAuthFlow;
|
|
7
|
+
tokenManager: TokenManager;
|
|
8
|
+
}
|
|
9
|
+
export interface AuthorizationRequest {
|
|
10
|
+
/** Provider authorization URL to redirect the client to. */
|
|
11
|
+
url: string;
|
|
12
|
+
/**
|
|
13
|
+
* Client-held half of the state binding (#36). The caller must hand this to
|
|
14
|
+
* the client that started the flow — the auth routes set it as an HttpOnly
|
|
15
|
+
* cookie — and present it back to `handleCallback`.
|
|
16
|
+
*/
|
|
17
|
+
bindingValue: string;
|
|
18
|
+
}
|
|
19
|
+
export default class OAuth {
|
|
20
|
+
static instance: OAuth | null;
|
|
21
|
+
providers: Map<string, ProviderEntry>;
|
|
22
|
+
stateStore: StateStore;
|
|
23
|
+
sessionManager: SessionManager;
|
|
24
|
+
frontendCallbackUrl?: string;
|
|
25
|
+
constructor();
|
|
26
|
+
init(): Promise<void>;
|
|
27
|
+
getProvider(name: string): ProviderEntry;
|
|
28
|
+
getAuthorizationUrl(providerName: string): AuthorizationRequest;
|
|
29
|
+
/**
|
|
30
|
+
* `bindingValues` is required, not optional (#36). An optional parameter lets
|
|
31
|
+
* an existing three-argument call site keep compiling and then fail at
|
|
32
|
+
* runtime on the first real login; a compile error is the loudest disclosure
|
|
33
|
+
* channel available for this break.
|
|
34
|
+
*
|
|
35
|
+
* It is an array, not a single value, because a client can hold more than one
|
|
36
|
+
* cookie of the binding cookie's name and every one of them has to be tried —
|
|
37
|
+
* see `StateStore.anyCandidateMatches`. A caller driving the flow itself
|
|
38
|
+
* passes `[bindingValue]`; the route handler passes through every value the
|
|
39
|
+
* client presented, which may be none.
|
|
40
|
+
*/
|
|
41
|
+
handleCallback(providerName: string, code: string, stateToken: string, bindingValues: readonly string[]): Promise<import("./session-manager.js").SessionResult>;
|
|
42
|
+
getSession(sessionId: string): unknown;
|
|
43
|
+
logout(sessionId: string): void;
|
|
44
|
+
}
|
|
45
|
+
export {};
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import config from 'stonyx/config';
|
|
2
|
+
import log from 'stonyx/log';
|
|
3
|
+
import { waitForModule } from 'stonyx';
|
|
4
|
+
import { setup, emit } from '@stonyx/events';
|
|
5
|
+
import RestServer from '@stonyx/rest-server';
|
|
6
|
+
import TokenManager from './token-manager.js';
|
|
7
|
+
import SessionManager from './session-manager.js';
|
|
8
|
+
import AuthRequest from './auth-request.js';
|
|
9
|
+
import StateStore from './state-store.js';
|
|
10
|
+
setup(['authenticate']);
|
|
11
|
+
export default class OAuth {
|
|
12
|
+
static instance;
|
|
13
|
+
providers = new Map();
|
|
14
|
+
stateStore = new StateStore();
|
|
15
|
+
sessionManager;
|
|
16
|
+
frontendCallbackUrl;
|
|
17
|
+
constructor() {
|
|
18
|
+
if (OAuth.instance)
|
|
19
|
+
return OAuth.instance;
|
|
20
|
+
OAuth.instance = this;
|
|
21
|
+
}
|
|
22
|
+
async init() {
|
|
23
|
+
// Self-register so log.oauth works even when @stonyx/oauth is in the
|
|
24
|
+
// consumer's `dependencies` (stonyx loader only merges devDependencies).
|
|
25
|
+
const { logColor = 'magenta', logMethod = 'oauth' } = config.oauth;
|
|
26
|
+
log.defineType(logMethod, logColor);
|
|
27
|
+
const oauthConfig = config.oauth;
|
|
28
|
+
const { providers, sessionDuration, frontendCallbackUrl } = oauthConfig;
|
|
29
|
+
this.frontendCallbackUrl = frontendCallbackUrl;
|
|
30
|
+
for (const [name, providerConfig] of Object.entries(providers)) {
|
|
31
|
+
const modulePath = providerConfig.module
|
|
32
|
+
? `${config.rootPath}/${providerConfig.module}`
|
|
33
|
+
: `./providers/${name}.js`;
|
|
34
|
+
const { default: Provider } = await import(modulePath);
|
|
35
|
+
const flow = new Provider(providerConfig);
|
|
36
|
+
this.providers.set(name, { flow, tokenManager: new TokenManager(flow) });
|
|
37
|
+
}
|
|
38
|
+
this.sessionManager = new SessionManager(sessionDuration);
|
|
39
|
+
await waitForModule('rest-server');
|
|
40
|
+
RestServer.instance.mountRoute(AuthRequest, { name: 'auth', options: this });
|
|
41
|
+
log.oauth?.('OAuth module initialized');
|
|
42
|
+
}
|
|
43
|
+
getProvider(name) {
|
|
44
|
+
const provider = this.providers.get(name);
|
|
45
|
+
if (!provider)
|
|
46
|
+
throw new Error(`OAuth provider "${name}" is not configured`);
|
|
47
|
+
return provider;
|
|
48
|
+
}
|
|
49
|
+
getAuthorizationUrl(providerName) {
|
|
50
|
+
const { flow } = this.getProvider(providerName);
|
|
51
|
+
const { stateToken, bindingValue } = this.stateStore.issue(providerName);
|
|
52
|
+
return { url: flow.buildAuthorizationUrl(stateToken), bindingValue };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* `bindingValues` is required, not optional (#36). An optional parameter lets
|
|
56
|
+
* an existing three-argument call site keep compiling and then fail at
|
|
57
|
+
* runtime on the first real login; a compile error is the loudest disclosure
|
|
58
|
+
* channel available for this break.
|
|
59
|
+
*
|
|
60
|
+
* It is an array, not a single value, because a client can hold more than one
|
|
61
|
+
* cookie of the binding cookie's name and every one of them has to be tried —
|
|
62
|
+
* see `StateStore.anyCandidateMatches`. A caller driving the flow itself
|
|
63
|
+
* passes `[bindingValue]`; the route handler passes through every value the
|
|
64
|
+
* client presented, which may be none.
|
|
65
|
+
*/
|
|
66
|
+
async handleCallback(providerName, code, stateToken, bindingValues) {
|
|
67
|
+
this.stateStore.consume(stateToken, providerName, bindingValues);
|
|
68
|
+
const { flow, tokenManager } = this.getProvider(providerName);
|
|
69
|
+
const tokens = await tokenManager.getTokens(code);
|
|
70
|
+
const rawUser = await flow.fetchUserInfo(tokens.accessToken);
|
|
71
|
+
const user = flow.normalizeUser(rawUser);
|
|
72
|
+
await emit('authenticate', user);
|
|
73
|
+
return this.sessionManager.create(user, tokens);
|
|
74
|
+
}
|
|
75
|
+
getSession(sessionId) {
|
|
76
|
+
return this.sessionManager.validate(sessionId);
|
|
77
|
+
}
|
|
78
|
+
logout(sessionId) {
|
|
79
|
+
this.sessionManager.destroy(sessionId);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface OAuthConfig {
|
|
2
|
+
clientId: string;
|
|
3
|
+
clientSecret: string;
|
|
4
|
+
redirectUri: string;
|
|
5
|
+
scopes?: string[];
|
|
6
|
+
authorizationUrl: string;
|
|
7
|
+
tokenUrl: string;
|
|
8
|
+
userInfoUrl: string;
|
|
9
|
+
}
|
|
10
|
+
export interface TokenResult {
|
|
11
|
+
accessToken: string;
|
|
12
|
+
refreshToken: string | null;
|
|
13
|
+
expiresIn: number;
|
|
14
|
+
}
|
|
15
|
+
export default class OAuthFlow {
|
|
16
|
+
clientId: string;
|
|
17
|
+
clientSecret: string;
|
|
18
|
+
redirectUri: string;
|
|
19
|
+
scopes: string[];
|
|
20
|
+
authorizationUrl: string;
|
|
21
|
+
tokenUrl: string;
|
|
22
|
+
userInfoUrl: string;
|
|
23
|
+
constructor({ clientId, clientSecret, redirectUri, scopes, authorizationUrl, tokenUrl, userInfoUrl }: OAuthConfig);
|
|
24
|
+
buildAuthorizationUrl(stateToken: string): string;
|
|
25
|
+
exchangeCode(code: string): Promise<TokenResult>;
|
|
26
|
+
refreshAccessToken(refreshToken: string): Promise<TokenResult>;
|
|
27
|
+
fetchUserInfo(accessToken: string): Promise<unknown>;
|
|
28
|
+
normalizeUser(rawUser: unknown): unknown;
|
|
29
|
+
revokeToken(_accessToken: string): Promise<void>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export default class OAuthFlow {
|
|
2
|
+
clientId;
|
|
3
|
+
clientSecret;
|
|
4
|
+
redirectUri;
|
|
5
|
+
scopes;
|
|
6
|
+
authorizationUrl;
|
|
7
|
+
tokenUrl;
|
|
8
|
+
userInfoUrl;
|
|
9
|
+
constructor({ clientId, clientSecret, redirectUri, scopes, authorizationUrl, tokenUrl, userInfoUrl }) {
|
|
10
|
+
this.clientId = clientId;
|
|
11
|
+
this.clientSecret = clientSecret;
|
|
12
|
+
this.redirectUri = redirectUri;
|
|
13
|
+
this.scopes = scopes || [];
|
|
14
|
+
this.authorizationUrl = authorizationUrl;
|
|
15
|
+
this.tokenUrl = tokenUrl;
|
|
16
|
+
this.userInfoUrl = userInfoUrl;
|
|
17
|
+
}
|
|
18
|
+
buildAuthorizationUrl(stateToken) {
|
|
19
|
+
const params = new URLSearchParams({
|
|
20
|
+
client_id: this.clientId,
|
|
21
|
+
redirect_uri: this.redirectUri,
|
|
22
|
+
response_type: 'code',
|
|
23
|
+
scope: this.scopes.join(' '),
|
|
24
|
+
state: stateToken,
|
|
25
|
+
});
|
|
26
|
+
return `${this.authorizationUrl}?${params.toString()}`;
|
|
27
|
+
}
|
|
28
|
+
async exchangeCode(code) {
|
|
29
|
+
const response = await fetch(this.tokenUrl, {
|
|
30
|
+
method: 'POST',
|
|
31
|
+
headers: { 'Content-Type': 'application/json' },
|
|
32
|
+
body: JSON.stringify({
|
|
33
|
+
client_id: this.clientId,
|
|
34
|
+
client_secret: this.clientSecret,
|
|
35
|
+
grant_type: 'authorization_code',
|
|
36
|
+
code,
|
|
37
|
+
redirect_uri: this.redirectUri,
|
|
38
|
+
}),
|
|
39
|
+
});
|
|
40
|
+
if (!response.ok)
|
|
41
|
+
throw new Error(`Token exchange failed: ${response.status}`);
|
|
42
|
+
const data = await response.json();
|
|
43
|
+
return {
|
|
44
|
+
accessToken: data.access_token,
|
|
45
|
+
refreshToken: data.refresh_token || null,
|
|
46
|
+
expiresIn: data.expires_in,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
async refreshAccessToken(refreshToken) {
|
|
50
|
+
const response = await fetch(this.tokenUrl, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: { 'Content-Type': 'application/json' },
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
client_id: this.clientId,
|
|
55
|
+
client_secret: this.clientSecret,
|
|
56
|
+
grant_type: 'refresh_token',
|
|
57
|
+
refresh_token: refreshToken,
|
|
58
|
+
}),
|
|
59
|
+
});
|
|
60
|
+
if (!response.ok)
|
|
61
|
+
throw new Error(`Token refresh failed: ${response.status}`);
|
|
62
|
+
const data = await response.json();
|
|
63
|
+
return {
|
|
64
|
+
accessToken: data.access_token,
|
|
65
|
+
refreshToken: data.refresh_token || refreshToken,
|
|
66
|
+
expiresIn: data.expires_in,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
async fetchUserInfo(accessToken) {
|
|
70
|
+
const response = await fetch(this.userInfoUrl, {
|
|
71
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
72
|
+
});
|
|
73
|
+
if (!response.ok)
|
|
74
|
+
throw new Error(`User info fetch failed: ${response.status}`);
|
|
75
|
+
return response.json();
|
|
76
|
+
}
|
|
77
|
+
normalizeUser(rawUser) {
|
|
78
|
+
return { raw: rawUser };
|
|
79
|
+
}
|
|
80
|
+
async revokeToken(_accessToken) {
|
|
81
|
+
// Optional — providers override if supported
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import OAuthFlow from '../oauth-flow.js';
|
|
2
|
+
import type { TokenResult } from '../oauth-flow.js';
|
|
3
|
+
interface DiscordProviderConfig {
|
|
4
|
+
clientId: string;
|
|
5
|
+
clientSecret: string;
|
|
6
|
+
redirectUri: string;
|
|
7
|
+
scopes?: string[];
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
interface DiscordUser {
|
|
11
|
+
id: string;
|
|
12
|
+
username: string;
|
|
13
|
+
global_name?: string;
|
|
14
|
+
avatar: string | null;
|
|
15
|
+
email?: string | null;
|
|
16
|
+
}
|
|
17
|
+
interface NormalizedDiscordUser {
|
|
18
|
+
id: string;
|
|
19
|
+
username: string;
|
|
20
|
+
displayName: string;
|
|
21
|
+
avatar: string | null;
|
|
22
|
+
email: string | null;
|
|
23
|
+
raw: DiscordUser;
|
|
24
|
+
}
|
|
25
|
+
export default class DiscordProvider extends OAuthFlow {
|
|
26
|
+
constructor(config: DiscordProviderConfig);
|
|
27
|
+
exchangeCode(code: string): Promise<TokenResult>;
|
|
28
|
+
normalizeUser(rawUser: DiscordUser): NormalizedDiscordUser;
|
|
29
|
+
}
|
|
30
|
+
export {};
|