@oxyhq/core 20.0.0 → 20.1.0
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/NOTICE +10 -9
- package/dist/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/mixins/OxyServices.chains.js +73 -0
- package/dist/cjs/mixins/OxyServices.store.js +266 -0
- package/dist/cjs/mixins/OxyServices.utility.js +159 -104
- package/dist/cjs/mixins/index.js +7 -0
- package/dist/cjs/server/rateLimit.js +15 -6
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/mixins/OxyServices.chains.js +70 -0
- package/dist/esm/mixins/OxyServices.store.js +263 -0
- package/dist/esm/mixins/OxyServices.utility.js +159 -104
- package/dist/esm/mixins/index.js +7 -0
- package/dist/esm/server/rateLimit.js +15 -6
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +7 -0
- package/dist/types/mixins/OxyServices.chains.d.ts +156 -0
- package/dist/types/mixins/OxyServices.store.d.ts +334 -0
- package/dist/types/mixins/OxyServices.utility.d.ts +31 -8
- package/dist/types/mixins/index.d.ts +3 -1
- package/package.json +1 -1
- package/src/index.ts +30 -0
- package/src/mixins/OxyServices.chains.ts +134 -0
- package/src/mixins/OxyServices.store.ts +585 -0
- package/src/mixins/OxyServices.utility.ts +161 -108
- package/src/mixins/__tests__/chains.test.ts +113 -0
- package/src/mixins/__tests__/store.test.ts +304 -0
- package/src/mixins/__tests__/userTokenAuth.test.ts +746 -0
- package/src/mixins/index.ts +9 -0
- package/src/server/__tests__/rateLimit.test.ts +47 -0
- package/src/server/rateLimit.ts +18 -8
|
@@ -133,18 +133,41 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
133
133
|
* Uses server-side session validation for security (not just JWT decode).
|
|
134
134
|
*
|
|
135
135
|
* **Design note — jwtDecode vs jwt.verify:**
|
|
136
|
-
* This middleware
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
* -
|
|
140
|
-
*
|
|
141
|
-
* -
|
|
142
|
-
*
|
|
143
|
-
*
|
|
136
|
+
* This middleware uses `jwtDecode()` (decode-only, NO signature check) for
|
|
137
|
+
* user tokens, because third-party apps mounting `oxy.auth()` do not hold
|
|
138
|
+
* the Oxy signing secret. **Every claim in a user token is therefore
|
|
139
|
+
* attacker-controlled and proves nothing on its own.** The identity comes
|
|
140
|
+
* from somewhere else entirely:
|
|
141
|
+
* - A user token MUST carry a `sessionId`. That session is validated
|
|
142
|
+
* server-side on every request via `validateSession()`, and the user id
|
|
143
|
+
* is read off the VALIDATED SESSION — never off the token. A token whose
|
|
144
|
+
* `userId` claim disagrees with the session is refused
|
|
145
|
+
* (`SESSION_USER_MISMATCH`); a token with no `sessionId` at all is
|
|
146
|
+
* refused outright (`SESSION_REQUIRED`). There is no local-claims path.
|
|
147
|
+
* - Service tokens (type: 'service') ARE stateless, so they use
|
|
148
|
+
* cryptographic HMAC verification via the `jwtSecret` option, and are
|
|
149
|
+
* additionally checked for `aud`, `iss`, and `type` claims to prevent
|
|
144
150
|
* cross-token-type confusion attacks.
|
|
145
151
|
* - The backend's own `authMiddleware` uses `jwt.verify()` because it has
|
|
146
152
|
* direct access to `SERVICE_TOKEN_SECRET` / `ACCESS_TOKEN_SECRET`.
|
|
147
153
|
*
|
|
154
|
+
* **Why session-less user tokens are refused rather than trusted:**
|
|
155
|
+
* every user access token the Oxy API issues carries a `sessionId` (see
|
|
156
|
+
* `packages/api/src/utils/sessionUtils.ts`, `generateSessionTokens` — the
|
|
157
|
+
* only mint site for user tokens, including the OAuth code exchange). So
|
|
158
|
+
* refusing session-less user tokens costs nothing legitimate, while
|
|
159
|
+
* accepting them let anyone authenticate as anyone by hand-rolling a JWT
|
|
160
|
+
* with a `userId` claim and a garbage signature.
|
|
161
|
+
*
|
|
162
|
+
* **Why the claimed user id is cross-checked against the session:**
|
|
163
|
+
* `GET /session/validate/:sessionId` is UNAUTHENTICATED and does not bind
|
|
164
|
+
* the bearer token — it returns whoever owns the session id it was handed.
|
|
165
|
+
* Trusting the token's `userId` claim after a successful validation would
|
|
166
|
+
* therefore let a caller holding ANY live session id (their own, for
|
|
167
|
+
* instance) pair it with a forged `userId` and be trusted as that user.
|
|
168
|
+
* `authSocket()` has always cross-checked this; the HTTP middleware now
|
|
169
|
+
* does too.
|
|
170
|
+
*
|
|
148
171
|
* **Service-token delegation (X-Oxy-User-Id):**
|
|
149
172
|
* When a service token is accompanied by `X-Oxy-User-Id`, the SDK calls
|
|
150
173
|
* `verifyServiceActingAs(appId, userId)` to confirm an explicit delegation
|
|
@@ -407,8 +430,10 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
407
430
|
}
|
|
408
431
|
return next();
|
|
409
432
|
}
|
|
410
|
-
|
|
411
|
-
|
|
433
|
+
// The CLAIMED user id. Never trusted as an identity — it is only ever
|
|
434
|
+
// compared against the id the validated session resolves to.
|
|
435
|
+
const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
|
|
436
|
+
if (!claimedUserId) {
|
|
412
437
|
if (optional) {
|
|
413
438
|
req.userId = null;
|
|
414
439
|
req.user = null;
|
|
@@ -442,111 +467,129 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
442
467
|
return onError(error);
|
|
443
468
|
return res.status(401).json(error);
|
|
444
469
|
}
|
|
445
|
-
//
|
|
446
|
-
//
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
req.user = null;
|
|
456
|
-
return next();
|
|
457
|
-
}
|
|
458
|
-
const error = {
|
|
459
|
-
error: 'INVALID_SESSION',
|
|
460
|
-
message: 'Session invalid or expired',
|
|
461
|
-
code: 'INVALID_SESSION',
|
|
462
|
-
status: 401
|
|
463
|
-
};
|
|
464
|
-
if (onError)
|
|
465
|
-
return onError(error);
|
|
466
|
-
return res.status(401).json(error);
|
|
467
|
-
}
|
|
468
|
-
// Use validated user data from session validation (already has full user)
|
|
469
|
-
req.userId = userId;
|
|
470
|
-
req.accessToken = token;
|
|
471
|
-
req.sessionId = decoded.sessionId;
|
|
472
|
-
if (loadUser && validationResult.user) {
|
|
473
|
-
// Session validation already returns full user data
|
|
474
|
-
req.user = validationResult.user;
|
|
475
|
-
}
|
|
476
|
-
else {
|
|
477
|
-
req.user = { id: userId };
|
|
478
|
-
}
|
|
479
|
-
if (debug) {
|
|
480
|
-
logger.debug(`[oxy.auth] OK user=${userId} session=${decoded.sessionId}`, {
|
|
481
|
-
component: 'auth',
|
|
482
|
-
method: 'auth',
|
|
483
|
-
});
|
|
484
|
-
}
|
|
470
|
+
// A server-validated session is MANDATORY for a user token. The JWT
|
|
471
|
+
// signature is not verified on this path, so a bare decoded token
|
|
472
|
+
// proves nothing: without the session round-trip a forged token could
|
|
473
|
+
// claim any user id. Mirrors `authSocket()`, which has always
|
|
474
|
+
// required this.
|
|
475
|
+
const sessionId = readStringClaim(decoded.sessionId);
|
|
476
|
+
if (!sessionId) {
|
|
477
|
+
if (optional) {
|
|
478
|
+
req.userId = null;
|
|
479
|
+
req.user = null;
|
|
485
480
|
return next();
|
|
486
481
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
482
|
+
const error = {
|
|
483
|
+
error: 'SESSION_REQUIRED',
|
|
484
|
+
message: 'Access token is not bound to a session',
|
|
485
|
+
code: 'SESSION_REQUIRED',
|
|
486
|
+
status: 401
|
|
487
|
+
};
|
|
488
|
+
if (onError)
|
|
489
|
+
return onError(error);
|
|
490
|
+
return res.status(401).json(error);
|
|
491
|
+
}
|
|
492
|
+
// Validate the token against the Oxy API. This proves the session is
|
|
493
|
+
// real and unrevoked, AND yields the identity it belongs to.
|
|
494
|
+
try {
|
|
495
|
+
const validationResult = await oxyInstance.validateSession(sessionId, {
|
|
496
|
+
useHeaderValidation: true,
|
|
497
|
+
});
|
|
498
|
+
if (!validationResult || !validationResult.valid || !validationResult.user) {
|
|
494
499
|
if (optional) {
|
|
495
500
|
req.userId = null;
|
|
496
501
|
req.user = null;
|
|
497
502
|
return next();
|
|
498
503
|
}
|
|
499
504
|
const error = {
|
|
500
|
-
error: '
|
|
501
|
-
message: 'Session
|
|
502
|
-
code: '
|
|
505
|
+
error: 'INVALID_SESSION',
|
|
506
|
+
message: 'Session invalid or expired',
|
|
507
|
+
code: 'INVALID_SESSION',
|
|
503
508
|
status: 401
|
|
504
509
|
};
|
|
505
510
|
if (onError)
|
|
506
511
|
return onError(error);
|
|
507
512
|
return res.status(401).json(error);
|
|
508
513
|
}
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
try {
|
|
517
|
-
// Temporarily set token to make the API call
|
|
518
|
-
const prevToken = oxyInstance.getAccessToken();
|
|
519
|
-
oxyInstance.setTokens(token);
|
|
520
|
-
const fullUser = await oxyInstance.getCurrentUser();
|
|
521
|
-
// Restore previous token
|
|
522
|
-
if (prevToken) {
|
|
523
|
-
oxyInstance.setTokens(prevToken);
|
|
524
|
-
}
|
|
525
|
-
else {
|
|
526
|
-
oxyInstance.clearTokens();
|
|
514
|
+
// The session — not the token — is the source of truth for identity.
|
|
515
|
+
const validatedUserId = getUserIdentityId(validationResult.user);
|
|
516
|
+
if (!validatedUserId) {
|
|
517
|
+
if (optional) {
|
|
518
|
+
req.userId = null;
|
|
519
|
+
req.user = null;
|
|
520
|
+
return next();
|
|
527
521
|
}
|
|
528
|
-
|
|
529
|
-
|
|
522
|
+
const error = {
|
|
523
|
+
error: 'INVALID_SESSION',
|
|
524
|
+
message: 'Session did not resolve to a usable identity',
|
|
525
|
+
code: 'INVALID_SESSION',
|
|
526
|
+
status: 401
|
|
527
|
+
};
|
|
528
|
+
if (onError)
|
|
529
|
+
return onError(error);
|
|
530
|
+
return res.status(401).json(error);
|
|
531
|
+
}
|
|
532
|
+
if (validatedUserId !== claimedUserId) {
|
|
533
|
+
// Session-id/claim confusion: the caller presented a live session
|
|
534
|
+
// that belongs to somebody else. Worth a warning — it has no
|
|
535
|
+
// benign cause. Ids only; never the token or the payload.
|
|
536
|
+
logger.warn('[oxy.auth] Token rejected — claimed user does not own the session', {
|
|
537
|
+
component: 'auth',
|
|
538
|
+
method: 'auth',
|
|
539
|
+
claimedUserId,
|
|
540
|
+
validatedUserId,
|
|
541
|
+
});
|
|
542
|
+
if (optional) {
|
|
543
|
+
req.userId = null;
|
|
544
|
+
req.user = null;
|
|
545
|
+
return next();
|
|
530
546
|
}
|
|
547
|
+
const error = {
|
|
548
|
+
error: 'SESSION_USER_MISMATCH',
|
|
549
|
+
message: 'Token user does not match the session',
|
|
550
|
+
code: 'SESSION_USER_MISMATCH',
|
|
551
|
+
status: 401
|
|
552
|
+
};
|
|
553
|
+
if (onError)
|
|
554
|
+
return onError(error);
|
|
555
|
+
return res.status(401).json(error);
|
|
531
556
|
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
557
|
+
req.userId = validatedUserId;
|
|
558
|
+
req.accessToken = token;
|
|
559
|
+
req.sessionId = sessionId;
|
|
560
|
+
// Session validation already returned the full user, so `loadUser`
|
|
561
|
+
// costs no extra round-trip.
|
|
562
|
+
req.user = loadUser ? validationResult.user : { id: validatedUserId };
|
|
563
|
+
if (debug) {
|
|
564
|
+
logger.debug(`[oxy.auth] OK user=${validatedUserId} session=${sessionId}`, {
|
|
537
565
|
component: 'auth',
|
|
538
|
-
method: 'auth
|
|
539
|
-
|
|
540
|
-
}, loadUserError);
|
|
566
|
+
method: 'auth',
|
|
567
|
+
});
|
|
541
568
|
}
|
|
569
|
+
return next();
|
|
542
570
|
}
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
571
|
+
catch (validationError) {
|
|
572
|
+
if (debug) {
|
|
573
|
+
logger.debug('[oxy.auth] Session validation failed', {
|
|
574
|
+
component: 'auth',
|
|
575
|
+
method: 'auth',
|
|
576
|
+
}, validationError);
|
|
577
|
+
}
|
|
578
|
+
if (optional) {
|
|
579
|
+
req.userId = null;
|
|
580
|
+
req.user = null;
|
|
581
|
+
return next();
|
|
582
|
+
}
|
|
583
|
+
const error = {
|
|
584
|
+
error: 'SESSION_VALIDATION_ERROR',
|
|
585
|
+
message: 'Session validation failed',
|
|
586
|
+
code: 'SESSION_VALIDATION_ERROR',
|
|
587
|
+
status: 401
|
|
588
|
+
};
|
|
589
|
+
if (onError)
|
|
590
|
+
return onError(error);
|
|
591
|
+
return res.status(401).json(error);
|
|
548
592
|
}
|
|
549
|
-
next();
|
|
550
593
|
}
|
|
551
594
|
catch (error) {
|
|
552
595
|
const handled = oxyInstance.handleError(error);
|
|
@@ -615,7 +658,7 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
615
658
|
}
|
|
616
659
|
return next(new Error('Invalid token'));
|
|
617
660
|
}
|
|
618
|
-
const claimedUserId = decoded.userId
|
|
661
|
+
const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
|
|
619
662
|
if (!claimedUserId) {
|
|
620
663
|
return next(new Error('Invalid token payload'));
|
|
621
664
|
}
|
|
@@ -626,12 +669,13 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
626
669
|
// A server-validated session is mandatory. A bare decoded JWT proves
|
|
627
670
|
// nothing — the signature is not verified here, so without a session
|
|
628
671
|
// round-trip a forged token could claim any user id.
|
|
629
|
-
|
|
672
|
+
const sessionId = readStringClaim(decoded.sessionId);
|
|
673
|
+
if (!sessionId) {
|
|
630
674
|
return next(new Error('Session required'));
|
|
631
675
|
}
|
|
632
676
|
let userId = claimedUserId;
|
|
633
677
|
try {
|
|
634
|
-
const result = await oxyInstance.validateSession(
|
|
678
|
+
const result = await oxyInstance.validateSession(sessionId, {
|
|
635
679
|
useHeaderValidation: true,
|
|
636
680
|
});
|
|
637
681
|
if (!result || !result.valid || !result.user) {
|
|
@@ -661,9 +705,9 @@ export function OxyServicesUtilityMixin(Base) {
|
|
|
661
705
|
// reads from `socket.user.id`.
|
|
662
706
|
socket.data = socket.data || {};
|
|
663
707
|
socket.data.userId = userId;
|
|
664
|
-
socket.data.sessionId =
|
|
708
|
+
socket.data.sessionId = sessionId;
|
|
665
709
|
socket.data.token = token;
|
|
666
|
-
socket.user = { id: userId, userId, sessionId
|
|
710
|
+
socket.user = { id: userId, userId, sessionId };
|
|
667
711
|
if (debug) {
|
|
668
712
|
logger.debug(`[oxy.authSocket] OK user=${userId}`, {
|
|
669
713
|
component: 'auth',
|
|
@@ -807,12 +851,16 @@ async function verifyServiceTokenSignature(token, secret) {
|
|
|
807
851
|
}
|
|
808
852
|
}
|
|
809
853
|
/**
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
*
|
|
814
|
-
*
|
|
854
|
+
* Read a JWT claim that is only usable as a non-empty string.
|
|
855
|
+
*
|
|
856
|
+
* A decoded payload is attacker-controlled JSON: a claim the type declares as
|
|
857
|
+
* `string` can arrive as a number, an object, or `null`. Narrowing here keeps
|
|
858
|
+
* those values out of URL construction and identity comparison, so an
|
|
859
|
+
* unexpected shape becomes a 401 rather than a stringified surprise.
|
|
815
860
|
*/
|
|
861
|
+
function readStringClaim(value) {
|
|
862
|
+
return typeof value === 'string' && value.length > 0 ? value : null;
|
|
863
|
+
}
|
|
816
864
|
/**
|
|
817
865
|
* Resolve the canonical user id from a validated session's user object.
|
|
818
866
|
*
|
|
@@ -825,6 +873,13 @@ function getUserIdentityId(user) {
|
|
|
825
873
|
?? user._id;
|
|
826
874
|
return typeof candidate === 'string' && candidate.length > 0 ? candidate : null;
|
|
827
875
|
}
|
|
876
|
+
/**
|
|
877
|
+
* Verify that a decoded service-token payload carries the expected `aud`,
|
|
878
|
+
* `iss`, and `type` claims. Throws `ServiceTokenClaimError` on mismatch.
|
|
879
|
+
* This is the defence against the H4 vulnerability where a recovery / 2FA /
|
|
880
|
+
* access token signed by the same shared secret could be replayed as a
|
|
881
|
+
* service token because no claim binding existed.
|
|
882
|
+
*/
|
|
828
883
|
function verifyServiceTokenClaims(decoded, expected) {
|
|
829
884
|
if (decoded.type !== 'service') {
|
|
830
885
|
throw new ServiceTokenClaimError(`Service token has unexpected type '${String(decoded.type)}'`);
|
package/dist/esm/mixins/index.js
CHANGED
|
@@ -16,6 +16,7 @@ import { OxyServicesReputationMixin } from './OxyServices.reputation.js';
|
|
|
16
16
|
import { OxyServicesAssetsMixin } from './OxyServices.assets.js';
|
|
17
17
|
import { OxyServicesAccountsMixin } from './OxyServices.accounts.js';
|
|
18
18
|
import { OxyServicesConnectedAppsMixin } from './OxyServices.connectedApps.js';
|
|
19
|
+
import { OxyServicesStoreMixin } from './OxyServices.store.js';
|
|
19
20
|
import { OxyServicesLocationMixin } from './OxyServices.location.js';
|
|
20
21
|
import { OxyServicesAnalyticsMixin } from './OxyServices.analytics.js';
|
|
21
22
|
import { OxyServicesDevicesMixin } from './OxyServices.devices.js';
|
|
@@ -27,6 +28,7 @@ import { OxyServicesContactsMixin } from './OxyServices.contacts.js';
|
|
|
27
28
|
import { OxyServicesNotificationsMixin } from './OxyServices.notifications.js';
|
|
28
29
|
import { OxyServicesAppDataMixin } from './OxyServices.appData.js';
|
|
29
30
|
import { OxyServicesCivicMixin } from './OxyServices.civic.js';
|
|
31
|
+
import { OxyServicesChainsMixin } from './OxyServices.chains.js';
|
|
30
32
|
import { OxyServicesNodesMixin } from './OxyServices.nodes.js';
|
|
31
33
|
import { OxyServicesLinksMixin } from './OxyServices.links.js';
|
|
32
34
|
import { OxyServicesFollowGraphMixin } from './OxyServices.followGraph.js';
|
|
@@ -66,6 +68,10 @@ const MIXIN_PIPELINE = [
|
|
|
66
68
|
// OAuth-consent surface (public app identity + connected-app grants). Kept
|
|
67
69
|
// separate from account ownership.
|
|
68
70
|
OxyServicesConnectedAppsMixin,
|
|
71
|
+
// The app store: the public storefront, the reviews on it, and the listing a
|
|
72
|
+
// publisher edits. A module OVER the platform — turn it off and OAuth still
|
|
73
|
+
// works — so it is its own surface rather than more of `accounts`.
|
|
74
|
+
OxyServicesStoreMixin,
|
|
69
75
|
OxyServicesLocationMixin,
|
|
70
76
|
OxyServicesAnalyticsMixin,
|
|
71
77
|
OxyServicesDevicesMixin,
|
|
@@ -80,6 +86,7 @@ const MIXIN_PIPELINE = [
|
|
|
80
86
|
OxyServicesAppDataMixin,
|
|
81
87
|
// Civic / Commons "Oxy ID" (public signed cards, Oxy ID QR payload)
|
|
82
88
|
OxyServicesCivicMixin,
|
|
89
|
+
OxyServicesChainsMixin,
|
|
83
90
|
// User nodes / decentralization (Fase 5): register/read/revoke/manage the
|
|
84
91
|
// caller's personal data node + ingest hint.
|
|
85
92
|
OxyServicesNodesMixin,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHmac } from 'node:crypto';
|
|
2
2
|
import { isIPv4, isIPv6 } from 'node:net';
|
|
3
3
|
import rateLimit from 'express-rate-limit';
|
|
4
|
+
import { createOptionalOxyAuth } from './auth.js';
|
|
4
5
|
/**
|
|
5
6
|
* Built-in exemptions. A media app's cover-art/avatar fan-out and HLS
|
|
6
7
|
* sub-requests must not consume the coarse global budget; health probes from
|
|
@@ -113,11 +114,12 @@ function hashAnonymousIp(ip) {
|
|
|
113
114
|
/**
|
|
114
115
|
* Resolve the trusted authenticated rate-limit key.
|
|
115
116
|
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
117
|
+
* Only identities that came from a server-validated session or a verified
|
|
118
|
+
* service token/delegation may pick a bucket. `req.sessionId` is the marker
|
|
119
|
+
* for the former: `oxy.auth()` sets it only after `validateSession()` came
|
|
120
|
+
* back valid, so requiring it here means an identity written by some OTHER
|
|
121
|
+
* middleware — which this package cannot vouch for — shares the anonymous
|
|
122
|
+
* per-IP bucket rather than getting the authenticated quota.
|
|
121
123
|
*/
|
|
122
124
|
function resolveTrustedAuthenticatedKey(req) {
|
|
123
125
|
const userId = req.userId ?? req.user?.id ?? req.user?._id;
|
|
@@ -153,7 +155,14 @@ export function createOxyRateLimit(oxy, options = {}) {
|
|
|
153
155
|
const { authenticatedMax = 5000, anonymousMax = 600, windowMs = 15 * 60 * 1000, store, exempt, message = 'Too many requests, please try again later.', auth, } = options;
|
|
154
156
|
// Idempotent optional-auth resolver. Reuses the SAME session resolution as
|
|
155
157
|
// every protected route, so the limiter keys by the real user identity.
|
|
156
|
-
|
|
158
|
+
//
|
|
159
|
+
// `createOptionalOxyAuth` — NOT the raw `oxy.auth({ optional: true })` —
|
|
160
|
+
// because only the former skips resolution when a preceding middleware has
|
|
161
|
+
// already resolved a user. The raw middleware writes `req.userId = null` on
|
|
162
|
+
// every request it cannot authenticate, and because it mutates the shared
|
|
163
|
+
// `req` that erasure is visible to every handler downstream of the limiter,
|
|
164
|
+
// not just to the bucket calculation.
|
|
165
|
+
const resolveSession = createOptionalOxyAuth(oxy, { auth });
|
|
157
166
|
const skip = (req) => isBuiltInExempt(req) || (exempt ? exempt(req) : false);
|
|
158
167
|
const limiter = rateLimit({
|
|
159
168
|
windowMs,
|