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