@oxyhq/core 19.1.2 → 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/LICENSE +202 -0
- package/NOTICE +16 -0
- package/dist/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/HttpService.js +23 -18
- package/dist/cjs/i18n/accountCategoryLabels.js +44 -0
- package/dist/cjs/i18n/accountRoleLabels.js +27 -0
- package/dist/cjs/i18n/reputationCategoryLabels.js +20 -0
- package/dist/cjs/i18n/trustTierLabels.js +19 -0
- package/dist/cjs/index.js +19 -9
- package/dist/cjs/mixins/OxyServices.chains.js +73 -0
- package/dist/cjs/mixins/OxyServices.followGraph.js +17 -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/cjs/session/accountProjection.js +31 -6
- package/dist/cjs/utils/errorUtils.js +65 -1
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/HttpService.js +24 -19
- package/dist/esm/i18n/accountCategoryLabels.js +37 -0
- package/dist/esm/i18n/accountRoleLabels.js +20 -0
- package/dist/esm/i18n/reputationCategoryLabels.js +13 -0
- package/dist/esm/i18n/trustTierLabels.js +12 -0
- package/dist/esm/index.js +11 -8
- package/dist/esm/mixins/OxyServices.chains.js +70 -0
- package/dist/esm/mixins/OxyServices.followGraph.js +17 -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/esm/session/accountProjection.js +30 -6
- package/dist/esm/utils/errorUtils.js +63 -1
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/i18n/accountCategoryLabels.d.ts +34 -0
- package/dist/types/i18n/accountRoleLabels.d.ts +10 -0
- package/dist/types/i18n/reputationCategoryLabels.d.ts +10 -0
- package/dist/types/i18n/trustTierLabels.d.ts +9 -0
- package/dist/types/index.d.ts +14 -2
- package/dist/types/mixins/OxyServices.chains.d.ts +156 -0
- package/dist/types/mixins/OxyServices.followGraph.d.ts +13 -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/dist/types/session/accountProjection.d.ts +20 -4
- package/dist/types/utils/errorUtils.d.ts +67 -0
- package/package.json +7 -6
- package/src/HttpService.ts +29 -22
- package/src/__tests__/parseHttpErrorBody.test.ts +116 -0
- package/src/__tests__/serverValueImportsDeclared.test.ts +7 -0
- package/src/i18n/__tests__/accountCategoryLabels.test.ts +62 -0
- package/src/i18n/__tests__/accountRoleLabels.test.ts +54 -0
- package/src/i18n/__tests__/reputationCategoryLabels.test.ts +56 -0
- package/src/i18n/__tests__/trustTierLabels.test.ts +47 -0
- package/src/i18n/accountCategoryLabels.ts +44 -0
- package/src/i18n/accountRoleLabels.ts +26 -0
- package/src/i18n/reputationCategoryLabels.ts +20 -0
- package/src/i18n/trustTierLabels.ts +18 -0
- package/src/index.ts +43 -6
- package/src/mixins/OxyServices.chains.ts +134 -0
- package/src/mixins/OxyServices.followGraph.ts +24 -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__/followGraph.test.ts +19 -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
- package/src/session/__tests__/accountProjection.test.ts +98 -0
- package/src/session/accountProjection.ts +37 -6
- package/src/utils/errorUtils.ts +116 -5
|
@@ -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,
|
|
@@ -48,6 +48,30 @@ import { getNormalizedUserHandle } from '../utils/userHandle.js';
|
|
|
48
48
|
export function isSwitchTargetAccount(node) {
|
|
49
49
|
return node.relationship === 'self' || isActAsEligibleKind(node.kind);
|
|
50
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Whether the caller may switch INTO this account — the server-side
|
|
53
|
+
* `account:act_as` gate plus the structural {@link isSwitchTargetAccount} rule.
|
|
54
|
+
*
|
|
55
|
+
* `relationship: 'self'` always passes (returning to the caller's own personal
|
|
56
|
+
* account). Every other ground requires a switch-eligible kind AND
|
|
57
|
+
* `account:act_as` in the resolved membership permissions. When permissions are
|
|
58
|
+
* absent but the relationship is `owner`, the owner baseline is assumed — the
|
|
59
|
+
* API always resolves effective permissions for owned accounts, but test
|
|
60
|
+
* fixtures and stale rows may omit the membership blob.
|
|
61
|
+
*/
|
|
62
|
+
export function canSwitchIntoAccount(node) {
|
|
63
|
+
if (node.relationship === 'self') {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
if (!isSwitchTargetAccount(node)) {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
const permissions = node.callerMembership?.permissions;
|
|
70
|
+
if (permissions) {
|
|
71
|
+
return permissions.includes('account:act_as');
|
|
72
|
+
}
|
|
73
|
+
return node.relationship === 'owner';
|
|
74
|
+
}
|
|
51
75
|
/**
|
|
52
76
|
* Pure union of device sign-ins and account-graph nodes into the flat
|
|
53
77
|
* {@link SwitchableAccount}[] every switcher renders.
|
|
@@ -57,9 +81,9 @@ export function isSwitchTargetAccount(node) {
|
|
|
57
81
|
* and a graph node is deduped into ONE device row enriched with the graph
|
|
58
82
|
* metadata (relationship / kind / parent / membership).
|
|
59
83
|
*
|
|
60
|
-
* Graph nodes
|
|
61
|
-
*
|
|
62
|
-
* below.
|
|
84
|
+
* Graph nodes the caller cannot switch into — a `channel`, or a managed account
|
|
85
|
+
* whose membership lacks `account:act_as` — are omitted.
|
|
86
|
+
* {@link canSwitchIntoAccount} is the rule; see the filter below.
|
|
63
87
|
*/
|
|
64
88
|
export function projectSwitchableAccounts(input) {
|
|
65
89
|
const { state, graph, profilesById, activeUser, locale, resolveAvatarUrl } = input;
|
|
@@ -139,7 +163,7 @@ export function projectSwitchableAccounts(input) {
|
|
|
139
163
|
// An account already on the device skipped this check via the branch above,
|
|
140
164
|
// and correctly: whatever its kind, the caller is signed into it, so
|
|
141
165
|
// switching is a local activation that asks the server for nothing.
|
|
142
|
-
if (!
|
|
166
|
+
if (!canSwitchIntoAccount(node)) {
|
|
143
167
|
continue;
|
|
144
168
|
}
|
|
145
169
|
remember(toRow(node.account, {
|
|
@@ -161,7 +185,7 @@ export function projectSwitchableAccounts(input) {
|
|
|
161
185
|
* document, but including their ids lets the caller pass one id set and lets the
|
|
162
186
|
* projection prefer freshly-fetched profiles uniformly.
|
|
163
187
|
*
|
|
164
|
-
* Applies the SAME {@link
|
|
188
|
+
* Applies the SAME {@link canSwitchIntoAccount} filter as
|
|
165
189
|
* {@link projectSwitchableAccounts} to graph nodes, so this never fetches a
|
|
166
190
|
* profile for a row the projection will drop — and, just as importantly, never
|
|
167
191
|
* SKIPS one the projection will keep, which would leave that row unrendered
|
|
@@ -175,7 +199,7 @@ export function switchableAccountIds(state, graph) {
|
|
|
175
199
|
}
|
|
176
200
|
}
|
|
177
201
|
for (const node of graph) {
|
|
178
|
-
if (node.accountId &&
|
|
202
|
+
if (node.accountId && canSwitchIntoAccount(node)) {
|
|
179
203
|
ids.add(node.accountId);
|
|
180
204
|
}
|
|
181
205
|
}
|
|
@@ -28,6 +28,63 @@ export const ErrorCodes = {
|
|
|
28
28
|
NETWORK_ERROR: 'NETWORK_ERROR',
|
|
29
29
|
CONNECTION_FAILED: 'CONNECTION_FAILED'
|
|
30
30
|
};
|
|
31
|
+
/**
|
|
32
|
+
* Narrow a caught value to {@link HttpRequestError}.
|
|
33
|
+
*
|
|
34
|
+
* Returns `false` for a plain {@link ApiError} object (those are objects, not
|
|
35
|
+
* `Error`s) — run an arbitrary thrown value through {@link handleHttpError}
|
|
36
|
+
* first if you need one normalized.
|
|
37
|
+
*/
|
|
38
|
+
export function isHttpRequestError(value) {
|
|
39
|
+
if (!(value instanceof Error)) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
return typeof value.status === 'number';
|
|
43
|
+
}
|
|
44
|
+
const isPlainRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
45
|
+
const nonEmptyString = (value) => typeof value === 'string' && value.trim().length > 0 ? value : undefined;
|
|
46
|
+
/**
|
|
47
|
+
* Extract `message` / `code` / `details` from a parsed HTTP error response body.
|
|
48
|
+
*
|
|
49
|
+
* Handles every error envelope in use across the Oxy ecosystem:
|
|
50
|
+
*
|
|
51
|
+
* - `{ error: { code, message, details? } }` — nested envelope (CrowdSource and
|
|
52
|
+
* other Oxy services). Never stringify the nested object: `new Error(obj)`
|
|
53
|
+
* yields the literal message `"[object Object]"`.
|
|
54
|
+
* - `{ error: '<CODE>', message, details? }` — oxy-api's canonical shape
|
|
55
|
+
* (`ApiError.toJSON`), where the top-level `error` field IS the code.
|
|
56
|
+
* - `{ error: '<CODE>', error_description }` — RFC 6749 §5.2 / RFC 6750 §3, the
|
|
57
|
+
* OAuth token and userinfo endpoints. `error_description` is the human text
|
|
58
|
+
* and `error` is the machine code, so both survive.
|
|
59
|
+
* - `{ message, code }` — e.g. the API's CSRF rejections.
|
|
60
|
+
* - `{ error: '<human message>' }` — legacy hand-rolled routes. With no sibling
|
|
61
|
+
* `message`/`error_description` the string is the message, not a code: a bare
|
|
62
|
+
* `error` string is not machine-readable enough to promote to `code`.
|
|
63
|
+
*
|
|
64
|
+
* Anything else — a non-object body (`null`, `[]`, `"str"`, `42`), or an object
|
|
65
|
+
* carrying none of these fields — yields an empty result, leaving the caller on
|
|
66
|
+
* its status-based fallback message. Total function: never throws.
|
|
67
|
+
*/
|
|
68
|
+
export function parseHttpErrorBody(body) {
|
|
69
|
+
if (!isPlainRecord(body)) {
|
|
70
|
+
return {};
|
|
71
|
+
}
|
|
72
|
+
const nested = isPlainRecord(body.error) ? body.error : undefined;
|
|
73
|
+
const errorString = nonEmptyString(body.error);
|
|
74
|
+
// A sibling that proves the top-level `error` is a CODE rather than prose.
|
|
75
|
+
const siblingMessage = nonEmptyString(body.message) ?? nonEmptyString(body.error_description);
|
|
76
|
+
return {
|
|
77
|
+
message: siblingMessage ?? (nested ? nonEmptyString(nested.message) : errorString),
|
|
78
|
+
code: (nested ? nonEmptyString(nested.code) : undefined) ??
|
|
79
|
+
nonEmptyString(body.code) ??
|
|
80
|
+
(siblingMessage ? errorString : undefined),
|
|
81
|
+
details: isPlainRecord(body.details)
|
|
82
|
+
? body.details
|
|
83
|
+
: nested && isPlainRecord(nested.details)
|
|
84
|
+
? nested.details
|
|
85
|
+
: undefined,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
31
88
|
/**
|
|
32
89
|
* Create a standardized API error
|
|
33
90
|
*/
|
|
@@ -72,7 +129,12 @@ export function handleHttpError(error) {
|
|
|
72
129
|
const fetchError = error;
|
|
73
130
|
const status = fetchError.response?.status || fetchError.status;
|
|
74
131
|
if (status) {
|
|
75
|
-
|
|
132
|
+
// `details` is carried through when present: a body may ship structured
|
|
133
|
+
// detail without a machine-readable `code` (which is what routes the
|
|
134
|
+
// error to the already-an-ApiError branch above), and dropping it here
|
|
135
|
+
// would make it unreachable to every caller that rethrows via
|
|
136
|
+
// `OxyServices.handleError`.
|
|
137
|
+
return createApiError(fetchError.message || `HTTP ${status} error`, getErrorCodeFromStatus(status), status, isPlainRecord(fetchError.details) ? fetchError.details : undefined);
|
|
76
138
|
}
|
|
77
139
|
}
|
|
78
140
|
// Handle standard errors
|