@stonyx/oauth 0.1.1-beta.13 → 0.1.1-beta.131

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
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ [![CI](https://github.com/abofs/stonyx-oauth/actions/workflows/ci.yml/badge.svg)](https://github.com/abofs/stonyx-oauth/actions/workflows/ci.yml)
2
+ [![npm version](https://img.shields.io/npm/v/@stonyx/oauth.svg)](https://www.npmjs.com/package/@stonyx/oauth)
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+
1
5
  # @stonyx/oauth
2
6
 
3
7
  OAuth2 authentication module for the Stonyx framework. Provides a generic OAuth2 Authorization Code flow with a provider pattern — ship with Discord support, extensible to any OAuth2 provider.
@@ -7,7 +11,7 @@ OAuth2 authentication module for the Stonyx framework. Provides a generic OAuth2
7
11
  Add as a devDependency to your Stonyx project:
8
12
 
9
13
  ```bash
10
- npm install @stonyx/oauth
14
+ pnpm add @stonyx/oauth
11
15
  ```
12
16
 
13
17
  Requires `@stonyx/rest-server` as a peer dependency.
@@ -51,10 +55,167 @@ The module self-registers the following routes on the rest server:
51
55
  | Method | Route | Description |
52
56
  |--------|-------|-------------|
53
57
  | `GET` | `/auth` | Validate session — send `session-id` header, returns user or 401 |
54
- | `GET` | `/auth/login/:provider` | Redirects to provider's OAuth2 authorization page |
55
- | `GET` | `/auth/callback/:provider` | OAuth2 callback — exchanges code for tokens, creates session |
58
+ | `GET` | `/auth/login/:provider` | Redirects to provider's OAuth2 authorization page, and sets the state binding cookie |
59
+ | `GET` | `/auth/callback/:provider` | OAuth2 callback — verifies the state binding, exchanges code for tokens, creates session |
56
60
  | `GET` | `/auth/logout` | Destroys session (send `session-id` header) |
57
61
 
62
+ ### Starting the flow
63
+
64
+ Send the browser to `/auth/login/:provider` as a **top-level navigation**:
65
+
66
+ ```javascript
67
+ window.location.href = 'https://api.example.com/auth/login/discord';
68
+ ```
69
+
70
+ Do not start the flow with `fetch()` or `XMLHttpRequest`. The login response
71
+ sets the state binding cookie described below, and the browser must be holding
72
+ that cookie when the provider redirects it back to `/auth/callback/:provider`.
73
+
74
+ ## State Binding (CSRF Protection)
75
+
76
+ The OAuth2 `state` parameter only protects against login CSRF if it is bound to
77
+ the client that started the flow. This module binds it with a cookie.
78
+
79
+ On `GET /auth/login/:provider` the module issues a random 32-byte binding value,
80
+ stores only a SHA-256 digest of it server-side alongside the provider name and
81
+ issue time, and sends the plaintext to the client as a cookie:
82
+
83
+ | Attribute | Value | Why |
84
+ |-----------|-------|-----|
85
+ | Name | `stonyx_oauth_state` | |
86
+ | `HttpOnly` | set | script must not be able to read or forge the binding value |
87
+ | `SameSite` | `Lax` | **required.** The callback is a cross-site, top-level `GET` navigation from the provider. `SameSite=Strict` withholds the cookie on exactly that request and breaks login outright; `SameSite=None` requires `Secure` and widens exposure for no benefit |
88
+ | `Path` | `/auth` | the cookie is only ever read by the callback route |
89
+ | `Secure` | set on every host except loopback | deriving it from `req.secure` would omit it in the standard production topology: behind a TLS-terminating proxy Express reports the request as plaintext unless `trust proxy` is enabled, and `@stonyx/rest-server` leaves that off by default. A non-loopback plaintext deployment therefore cannot store this cookie — that failure is loud and deliberate, in preference to a silently insecure production cookie. The exemption rule is exact; see below |
90
+ | `Max-Age` | 600 (10 minutes) | matches the pending state's lifetime |
91
+
92
+ #### Which hosts are exempt from `Secure`
93
+
94
+ The exemption is decided by parsing the `Host` header and testing the result for
95
+ membership. It is never a prefix or suffix match on the raw header value,
96
+ because `Host` is attacker-controllable from any non-browser client.
97
+
98
+ Exempt, and nothing else:
99
+
100
+ - `localhost` (case-insensitive)
101
+ - any address in `127.0.0.0/8` — a dotted quad of **four** decimal octets whose
102
+ first is `127`, so `127.0.0.2` is exempt and `127.evil.com` is not. The
103
+ resolver shorthands `127.1` and `127.0.0` are *not* exempt: accepting a
104
+ variable number of octets is how a membership test decays back into a prefix
105
+ match. Use the full form
106
+ - `::1` (and its expanded form), and the IPv4-mapped loopback spellings
107
+ `::ffff:127.0.0.1` and `::ffff:7f00:1`
108
+ - the wildcard bind addresses `0.0.0.0` and `::`
109
+
110
+ Everything else gets `Secure`, including:
111
+
112
+ - **`*.localhost`.** A `.localhost` suffix was exempt in an earlier draft of
113
+ this module and is not any more: a split-horizon vhost under that zone would
114
+ have shipped the binding value in cleartext. Develop against `localhost` or
115
+ `127.0.0.1`, which reach the same server.
116
+ - any `Host` that is not a well-formed `host[:port]` — a non-numeric port, a
117
+ userinfo segment (`localhost:80@evil.com`), a comma-joined multi-value, or a
118
+ character a registered name may not contain
119
+ - a request carrying **more than one `Host` header**. Node collapses repeats
120
+ into the first value, so an upstream component that prepends rather than
121
+ replaces a `Host:` line could otherwise downgrade the cookie on a response to
122
+ someone else. RFC 9112 section 3.2 makes such a request invalid; this module
123
+ treats it as unattributable.
124
+ - a request carrying **no `Host` header** at all
125
+
126
+ `X-Forwarded-Host` is deliberately **not** consulted.
127
+
128
+ `GET /auth/callback/:provider` accepts the callback only when all of the
129
+ following hold, and mints no session otherwise:
130
+
131
+ - the `state` is one this server issued and has not already been used
132
+ - it was issued for **this** provider
133
+ - it was issued less than 10 minutes ago
134
+ - the request carries a binding cookie whose value hashes to the stored digest
135
+
136
+ A client can hold more than one cookie of that name — a sibling subdomain can
137
+ set one on the parent domain, and the browser sends every applicable cookie in
138
+ a single header. **Every** value carrying the name is tried, up to eight, and
139
+ the callback is accepted if any of them matches. Reading only the first would
140
+ let anyone who can plant a cookie on the victim's domain deny them login
141
+ permanently: RFC 6265 section 5.4 sorts a planted cookie ahead of the real one
142
+ on equal paths, and the state is burned on every recognised callback, so
143
+ retrying does not help. Trying all of them concedes nothing, because the
144
+ attacker would still have to present the victim's own binding value.
145
+
146
+ The state and the cookie are both single-use: the pending record is consumed on
147
+ any callback that presents a recognised `state` — successful or not — and that
148
+ same response clears the cookie, scoped to `Path=/auth` so the deletion actually
149
+ reaches the cookie that was set.
150
+
151
+ A callback that consumes **nothing** — an unrecognised or absent `state`, a
152
+ provider `error`, a missing `code` — leaves the cookie alone. That is not
153
+ tidiness: `/auth/callback/:provider?code=1` is a request any attacker can induce
154
+ as a top-level navigation while a victim is still at the provider's consent
155
+ screen, and clearing on it would delete the victim's binding cookie without
156
+ touching anything the server could later notice.
157
+
158
+ Two distinct failure modes surface on two different routes. They are unrelated,
159
+ and the route is the fastest way to tell them apart:
160
+
161
+ - **The cookie cannot be set at all.** `GET /auth/login/:provider` responds
162
+ `500` rather than issuing a state it cannot bind, and logs
163
+ `OAuth: unable to set the state binding cookie; login rejected`. This is a
164
+ framework-wiring condition — the response object the module reaches for is
165
+ not there — not a network or proxy one.
166
+ - **`Set-Cookie` is stripped in transit** by a reverse proxy or CDN.
167
+ `GET /auth/login/:provider` **succeeds and redirects normally**; the module
168
+ never learns the header was dropped. The failure surfaces one hop later, at
169
+ `GET /auth/callback/:provider`, as `?error=auth_failed` on
170
+ `frontendCallbackUrl` (or a bare `500` when it is unset), with
171
+ `OAuth: callback rejected — Missing state binding value` in the log. First
172
+ thing to check: does the login response reach the browser carrying
173
+ `Set-Cookie: stonyx_oauth_state`.
174
+
175
+ Every callback rejection is logged server-side with its reason
176
+ (`OAuth: callback rejected — ...`), which distinguishes an unknown state, a
177
+ wrong provider, an expired state, a missing binding value and a wrong binding
178
+ value. Those five strings are this module's own; nothing caller-controlled
179
+ appears in them. The client-facing `auth_failed` stays deliberately opaque.
180
+
181
+ A failure thrown **below** the state check — by `getProvider`, by a provider's
182
+ `exchangeCode`, `fetchUserInfo` or `normalizeUser`, by an `authenticate`
183
+ subscriber, or by session creation — logs the fixed line
184
+ `OAuth: callback failed after state validation` and **nothing from the error
185
+ itself**. Custom providers are consumer code, and a provider error that carries
186
+ request context would otherwise put a `clientSecret` or the caller-supplied
187
+ `code` into your logs verbatim. If you need that detail, log it inside your
188
+ provider, where you control what goes in it.
189
+
190
+ A failed callback **cannot be retried**: the pending record is consumed on any
191
+ callback presenting a recognised `state`, so refreshing the error page or going
192
+ back and forward produces a second `auth_failed`. The user must restart at
193
+ `GET /auth/login/:provider`. Only one login can be in flight per browser at a
194
+ time, for the same reason — the binding cookie has one fixed name, so starting
195
+ a second login overwrites the first flow's binding value and the earlier flow
196
+ will fail at its callback.
197
+
198
+ ### Custom flow drivers
199
+
200
+ Consumers that drive the flow themselves instead of using the routes above must
201
+ carry the binding value between the two calls:
202
+
203
+ ```javascript
204
+ const { url, bindingValue } = oauth.getAuthorizationUrl('discord');
205
+ // hand bindingValue to the client, then on the callback:
206
+ const session = await oauth.handleCallback('discord', code, state, [bindingValue]);
207
+ ```
208
+
209
+ The fourth argument is an **array** — every value the client presented under the
210
+ binding cookie's name. A driver that holds exactly one value passes
211
+ `[bindingValue]`; one that holds none passes `[]`.
212
+
213
+ > **Changed in the release that fixes [#36](https://github.com/abofs/stonyx-oauth/issues/36):**
214
+ > `getAuthorizationUrl(provider)` returned a URL string and now returns
215
+ > `{ url, bindingValue }`; `handleCallback(provider, code, state)` takes a
216
+ > required fourth argument, the client's binding values, as an array.
217
+ > Applications using the self-registering `/auth` routes need no changes.
218
+
58
219
  ## Officially Supported Providers
59
220
 
60
221
  ### Discord
@@ -115,6 +276,12 @@ providers: {
115
276
  ## Session Management
116
277
 
117
278
  Sessions are stored in-memory using a `Map`. Sessions are lost on server restart.
279
+ Pending OAuth states are held in-memory too, so a restart mid-login, or more
280
+ than one instance behind a load balancer, will reject the callback. Pending
281
+ records are removed when a callback consumes them, not swept on a timer — the
282
+ ten-minute age bound is only evaluated when a matching callback arrives, so an
283
+ abandoned flow's record persists until the process restarts. See
284
+ [#38](https://github.com/abofs/stonyx-oauth/issues/38).
118
285
 
119
286
  Clients should store the `sessionId` returned from the callback and send it as a `session-id` header on subsequent requests.
120
287
 
@@ -0,0 +1,147 @@
1
+ import { Request } from '@stonyx/rest-server';
2
+ interface AuthorizationRequest {
3
+ url: string;
4
+ bindingValue: string;
5
+ }
6
+ interface OAuthInstance {
7
+ frontendCallbackUrl?: string;
8
+ getSession(sessionId: string): unknown;
9
+ getAuthorizationUrl(providerName: string): AuthorizationRequest;
10
+ handleCallback(providerName: string, code: string, stateToken: string, bindingValues: readonly string[]): Promise<{
11
+ sessionId: string;
12
+ expiresAt: number;
13
+ }>;
14
+ logout(sessionId: string): void;
15
+ }
16
+ interface CookieOptions {
17
+ httpOnly: boolean;
18
+ sameSite: string;
19
+ path: string;
20
+ secure: boolean;
21
+ maxAge?: number;
22
+ }
23
+ /**
24
+ * The response object Express hangs off the request.
25
+ *
26
+ * `@stonyx/rest-server` hands handlers `(req, state)` only, and `state` has no
27
+ * affordance for response headers, so setting a cookie means reaching for
28
+ * `req.res`. This is a deliberate, temporary escape hatch — tracked by
29
+ * `abofs/stonyx-rest-server#45`, which adds a first-class header affordance to
30
+ * migrate onto.
31
+ */
32
+ interface ResponseLike {
33
+ cookie(name: string, value: string, options: CookieOptions): unknown;
34
+ clearCookie(name: string, options: Omit<CookieOptions, 'maxAge'>): unknown;
35
+ }
36
+ interface RouteRequest {
37
+ headers: Record<string, string | undefined>;
38
+ /**
39
+ * Node's flat `[name, value, name, value, ...]` header list, when the runtime
40
+ * supplies it. Read only to detect a *duplicate* `Host`: Node collapses
41
+ * repeats into the first value, so `req.headers.host` alone cannot tell an
42
+ * unambiguous origin from a smuggled one.
43
+ */
44
+ rawHeaders?: string[];
45
+ params: Record<string, string>;
46
+ query: Record<string, string>;
47
+ secure?: boolean;
48
+ res?: ResponseLike;
49
+ }
50
+ interface RouteState {
51
+ redirect?: string;
52
+ }
53
+ export default class AuthRequest extends Request {
54
+ oauth: OAuthInstance;
55
+ constructor(oauth: OAuthInstance);
56
+ handlers: {
57
+ get: {
58
+ '/': ({ headers }: RouteRequest) => {};
59
+ '/login/:provider': (req: RouteRequest, state: RouteState) => 404 | 500 | undefined;
60
+ '/callback/:provider': (req: RouteRequest, state: RouteState) => Promise<{
61
+ sessionId: string;
62
+ expiresAt: number;
63
+ } | 500 | 400 | undefined>;
64
+ '/logout': ({ headers }: RouteRequest) => void;
65
+ };
66
+ };
67
+ cookieOptions(req: RouteRequest): Omit<CookieOptions, 'maxAge'>;
68
+ /**
69
+ * Whether the binding cookie is issued with `Secure`.
70
+ *
71
+ * Not `req.secure`. Express derives that from the socket unless `trust proxy`
72
+ * is enabled, and `@stonyx/rest-server` leaves it off by default
73
+ * (`trustProxy: REST_TRUST_PROXY === 'true'`). In the standard production
74
+ * topology — TLS terminated at a proxy, plaintext to the origin — `req.secure`
75
+ * is therefore `false` on every request to an HTTPS site, and the binding
76
+ * cookie would ship without `Secure` while the deployment looks correct.
77
+ *
78
+ * So `Secure` is set unconditionally except on a loopback host. Guessing
79
+ * wrong there breaks a non-loopback plaintext development setup, which fails
80
+ * at the first login and is loud. The alternative fails silently, in
81
+ * production, on the one attribute protecting the value this whole mechanism
82
+ * is built around.
83
+ *
84
+ * The exemption is decided by *parsing* the `Host` header and testing the
85
+ * result for membership, never by matching a prefix or a suffix on the raw
86
+ * value — `Host` is attacker-controllable on any non-browser client, and a
87
+ * security predicate written as a substring match drifts. Every shape that
88
+ * cannot be parsed as a bare `host[:port]`, and every request with more than
89
+ * one `Host`, fails secure.
90
+ */
91
+ isSecureContext(req: RouteRequest): boolean;
92
+ /**
93
+ * True when the request carried more than one `Host` header.
94
+ *
95
+ * Node keeps the first and discards the rest, so a component that *prepends*
96
+ * a `Host:` line — request smuggling, or a proxy that appends rather than
97
+ * replaces — can make `req.headers.host` read `localhost` on a request whose
98
+ * real origin is public. RFC 9112 section 3.2 makes such a request invalid;
99
+ * this treats it as unattributable and fails secure rather than trusting it.
100
+ */
101
+ static hasAmbiguousHost(req: RouteRequest): boolean;
102
+ /**
103
+ * The hostname component of a `Host` header, lowercased, or `undefined` when
104
+ * the value is not a well-formed `host[:port]`.
105
+ *
106
+ * `host.split(':')[0]` is not enough: it truncates at the *first* colon, so
107
+ * `localhost:80@evil.com` reduces to `localhost`. The port is therefore
108
+ * required to be decimal, and the hostname to contain only characters a
109
+ * registered name may contain.
110
+ */
111
+ static parseHostname(host: string): string | undefined;
112
+ /**
113
+ * Whether a parsed hostname is a loopback development origin.
114
+ *
115
+ * Membership tests, never prefix or suffix tests. `startsWith('127.')`
116
+ * matched `127.evil.com`, a perfectly registerable name (RFC 1123 permits a
117
+ * leading digit in a label), and `endsWith('.localhost')` exempted an entire
118
+ * suffix — so a `.localhost` split-horizon vhost shipped the binding value in
119
+ * cleartext. The `.localhost` exemption is withdrawn rather than tightened:
120
+ * the README documented `127.0.0.0/8`, `localhost`, `::1` and `0.0.0.0` and
121
+ * never documented it, and a developer on `app.localhost` reaches the same
122
+ * server on `localhost` or `127.0.0.1`.
123
+ */
124
+ static isLoopbackHost(hostname: string): boolean;
125
+ setBindingCookie(req: RouteRequest, bindingValue: string): boolean;
126
+ /**
127
+ * Every value the client presented under the binding cookie's name.
128
+ *
129
+ * Not the first one. A browser sends every applicable cookie in a single
130
+ * header, and a sibling subdomain can set a same-named cookie on the parent
131
+ * domain that RFC 6265 section 5.4 orders *ahead* of the real one — so
132
+ * returning on the first name match handed an attacker a permanent,
133
+ * unauthenticated denial of login for any victim they could plant a cookie
134
+ * on. `Secure`, `HttpOnly` and `SameSite` do not constrain that: the attacker
135
+ * is writing, not reading.
136
+ *
137
+ * Every value is returned, with no cap. A cap here does not bound an attack,
138
+ * it *is* one: truncating the list reinstates exactly the denial above its
139
+ * own threshold, because the planted cookies are the ones that sort first.
140
+ * The work is already bounded by Node's 16 KB header limit — at most 779
141
+ * hashable candidates, 0.32 ms to parse and hash all of them. See
142
+ * `constants.ts` for the measurement.
143
+ */
144
+ readBindingCookies(req: RouteRequest): string[];
145
+ clearBindingCookie(req: RouteRequest): void;
146
+ }
147
+ export {};