@stonyx/oauth 0.1.1-alpha.2 → 0.1.1-alpha.21

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 +147 -0
  3. package/dist/auth-request.js +342 -0
  4. package/dist/constants.d.ts +33 -0
  5. package/dist/constants.js +42 -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 +116 -0
  15. package/dist/state-store.js +144 -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 +434 -0
  20. package/src/constants.ts +46 -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 +179 -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,342 @@
1
+ import { Request } from '@stonyx/rest-server';
2
+ import log from 'stonyx/log';
3
+ import { StateRejection } from './state-store.js';
4
+ import { 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
+ * Every value is returned, with no cap. A cap here does not bound an attack,
310
+ * it *is* one: truncating the list reinstates exactly the denial above its
311
+ * own threshold, because the planted cookies are the ones that sort first.
312
+ * The work is already bounded by Node's 16 KB header limit — at most 779
313
+ * hashable candidates, 0.32 ms to parse and hash all of them. See
314
+ * `constants.ts` for the measurement.
315
+ */
316
+ readBindingCookies(req) {
317
+ const header = req.headers.cookie;
318
+ if (!header)
319
+ return [];
320
+ const values = [];
321
+ for (const part of header.split(';')) {
322
+ const separator = part.indexOf('=');
323
+ if (separator === -1)
324
+ continue;
325
+ if (part.slice(0, separator).trim() !== STATE_COOKIE_NAME)
326
+ continue;
327
+ // Not decoded. The binding value is base64url, whose alphabet
328
+ // `encodeURIComponent` never escapes, so a decode buys nothing — and
329
+ // `decodeURIComponent` throws `URIError` on malformed input, which any
330
+ // unauthenticated caller can supply, turning the first line of the
331
+ // callback into a 500 with a stack trace.
332
+ values.push(part.slice(separator + 1).trim());
333
+ }
334
+ return values;
335
+ }
336
+ clearBindingCookie(req) {
337
+ const { res } = req;
338
+ if (typeof res?.clearCookie !== 'function')
339
+ return;
340
+ res.clearCookie(STATE_COOKIE_NAME, this.cookieOptions(req));
341
+ }
342
+ }
@@ -0,0 +1,33 @@
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
+ * There is deliberately no cap on how many values carrying `STATE_COOKIE_NAME`
10
+ * a callback will try.
11
+ *
12
+ * A client can hold more than one cookie of the same name — a sibling subdomain
13
+ * can set one on the parent domain — and the browser sends every applicable
14
+ * cookie in one header, so all of them must be tried or a planted cookie denies
15
+ * login by sorting ahead of the real one (RFC 6265 section 5.4).
16
+ *
17
+ * A cap of 8 was tried and withdrawn: it *reinstated* that denial above its own
18
+ * threshold. Measured on the pre-change tree, 7 shadow cookies still minted a
19
+ * session and 8 failed permanently — the same outcome as the original defect,
20
+ * with the attacker's cost raised from one planted cookie to eight. That is
21
+ * reachable: RFC 6265 section 5.4 orders by path length then creation time, so
22
+ * a 4-label API host with a foothold beneath it gets 3 settable parent domains
23
+ * x 3 usable paths = 9 candidates ahead of the real one.
24
+ *
25
+ * What the cap was defending is already bounded, structurally and for free.
26
+ * Node caps the whole header block at `http.maxHeaderSize`, 16 KB by default,
27
+ * and the shortest segment that can reach the hash is `stonyx_oauth_state=x` at
28
+ * 20 bytes, so a request cannot present more than 779 hashable candidates.
29
+ * Parsing and SHA-256-hashing all 779 costs 0.32 ms median / 0.81 ms worst of 9
30
+ * runs (Node 24.13.0, Apple silicon). Paying a permanent, unauthenticated
31
+ * denial of login to avoid a third of a millisecond is the wrong trade, so the
32
+ * bound is left where it already was: the header size limit.
33
+ */
@@ -0,0 +1,42 @@
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
+ * There is deliberately no cap on how many values carrying `STATE_COOKIE_NAME`
19
+ * a callback will try.
20
+ *
21
+ * A client can hold more than one cookie of the same name — a sibling subdomain
22
+ * can set one on the parent domain — and the browser sends every applicable
23
+ * cookie in one header, so all of them must be tried or a planted cookie denies
24
+ * login by sorting ahead of the real one (RFC 6265 section 5.4).
25
+ *
26
+ * A cap of 8 was tried and withdrawn: it *reinstated* that denial above its own
27
+ * threshold. Measured on the pre-change tree, 7 shadow cookies still minted a
28
+ * session and 8 failed permanently — the same outcome as the original defect,
29
+ * with the attacker's cost raised from one planted cookie to eight. That is
30
+ * reachable: RFC 6265 section 5.4 orders by path length then creation time, so
31
+ * a 4-label API host with a foothold beneath it gets 3 settable parent domains
32
+ * x 3 usable paths = 9 candidates ahead of the real one.
33
+ *
34
+ * What the cap was defending is already bounded, structurally and for free.
35
+ * Node caps the whole header block at `http.maxHeaderSize`, 16 KB by default,
36
+ * and the shortest segment that can reach the hash is `stonyx_oauth_state=x` at
37
+ * 20 bytes, so a request cannot present more than 779 hashable candidates.
38
+ * Parsing and SHA-256-hashing all 779 costs 0.32 ms median / 0.81 ms worst of 9
39
+ * runs (Node 24.13.0, Apple silicon). Paying a permanent, unauthenticated
40
+ * denial of login to avoid a third of a millisecond is the wrong trade, so the
41
+ * bound is left where it already was: the header size limit.
42
+ */
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
+ }