@stonyx/oauth 0.1.1-alpha.20 → 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.20",
7
+ "version": "0.1.1-alpha.22",
8
8
  "description": "OAuth2 authentication module for the Stonyx framework",
9
9
  "repository": {
10
10
  "type": "git",
@@ -55,13 +55,13 @@
55
55
  },
56
56
  "dependencies": {
57
57
  "@stonyx/events": "0.1.1-beta.52",
58
- "stonyx": "0.2.3-beta.76"
58
+ "stonyx": "0.2.3-beta.77"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@stonyx/rest-server": ">=0.2.1-beta.11"
62
62
  },
63
63
  "devDependencies": {
64
- "@stonyx/rest-server": "0.2.1-beta.82",
64
+ "@stonyx/rest-server": "0.2.1-beta.83",
65
65
  "@stonyx/utils": "0.2.3-beta.26",
66
66
  "@stonyx/logs": "1.0.1-beta.19",
67
67
  "@types/qunit": "^2.19.13",
@@ -1,116 +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
- 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
2
 
66
3
  interface OAuthInstance {
67
4
  frontendCallbackUrl?: string;
68
5
  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 }>;
6
+ getAuthorizationUrl(providerName: string): string;
7
+ handleCallback(providerName: string, code: string, stateToken: string): Promise<{ sessionId: string; expiresAt: number }>;
76
8
  logout(sessionId: string): void;
77
9
  }
78
10
 
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
11
  interface RouteRequest {
102
12
  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
13
  params: Record<string, string>;
111
14
  query: Record<string, string>;
112
- secure?: boolean;
113
- res?: ResponseLike;
114
15
  }
115
16
 
116
17
  interface RouteState {
@@ -140,26 +41,18 @@ export default class AuthRequest extends Request {
140
41
  '/login/:provider': (req: RouteRequest, state: RouteState) => {
141
42
  const { provider: providerName } = req.params;
142
43
 
143
- let authorization: AuthorizationRequest;
144
44
  try {
145
- authorization = this.oauth.getAuthorizationUrl(providerName);
45
+ const url = this.oauth.getAuthorizationUrl(providerName);
46
+ state.redirect = url;
146
47
  } catch {
147
48
  return 404;
148
49
  }
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
50
  },
156
51
 
157
52
  '/callback/:provider': async (req: RouteRequest, state: RouteState) => {
158
53
  const { provider: providerName } = req.params;
159
54
  const { code, state: stateToken, error } = req.query;
160
55
 
161
- const bindingValues = this.readBindingCookies(req);
162
-
163
56
  if (error) {
164
57
  if (this.oauth.frontendCallbackUrl) {
165
58
  state.redirect = `${this.oauth.frontendCallbackUrl}?error=${encodeURIComponent(error)}`;
@@ -171,11 +64,7 @@ export default class AuthRequest extends Request {
171
64
  if (!code) return 400;
172
65
 
173
66
  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);
67
+ const session = await this.oauth.handleCallback(providerName, code, stateToken);
179
68
 
180
69
  if (this.oauth.frontendCallbackUrl) {
181
70
  const params = new URLSearchParams({
@@ -187,53 +76,7 @@ export default class AuthRequest extends Request {
187
76
  }
188
77
 
189
78
  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
-
79
+ } catch {
237
80
  if (this.oauth.frontendCallbackUrl) {
238
81
  state.redirect = `${this.oauth.frontendCallbackUrl}?error=auth_failed`;
239
82
  return;
@@ -248,186 +91,4 @@ export default class AuthRequest extends Request {
248
91
  },
249
92
  }
250
93
  };
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
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,19 +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
- * Most values carrying `STATE_COOKIE_NAME` that a single callback will try.
10
- *
11
- * A client can hold more than one cookie of the same name — a sibling
12
- * subdomain can set one on the parent domain, and the browser sends every
13
- * applicable cookie in one header. All of them are tried, so a planted cookie
14
- * cannot deny login by sorting ahead of the real one; the cap bounds the work
15
- * an unauthenticated caller can ask for. It is not a brute-force control: the
16
- * pending record is consumed on recognition, so a state gets one attempt
17
- * whatever the cap.
18
- */
19
- export declare const MAX_BINDING_COOKIE_CANDIDATES = 8;