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

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