@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.
@@ -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 intentionally uses `jwtDecode()` (decode-only, no signature
137
- * verification) for user tokens. This is by design, NOT a security gap:
138
- * - Third-party apps using `oxy.auth()` don't have the Oxy JWT secret
139
- * - Security comes from API-based session validation (`validateSession()`)
140
- * which checks the session server-side on every request
141
- * - Service tokens (type: 'service') DO use cryptographic HMAC verification
142
- * via the `jwtSecret` option, since they are stateless. Service tokens
143
- * are additionally checked for `aud`, `iss`, and `type` claims to prevent
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
- const userId = decoded.userId || decoded.id;
411
- if (!userId) {
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
- // Validate token against the Oxy API for session-based verification
446
- // This ensures the session hasn't been revoked server-side
447
- if (decoded.sessionId) {
448
- try {
449
- const validationResult = await oxyInstance.validateSession(decoded.sessionId, {
450
- useHeaderValidation: true,
451
- });
452
- if (!validationResult || !validationResult.valid) {
453
- if (optional) {
454
- req.userId = null;
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
- catch (validationError) {
488
- if (debug) {
489
- logger.debug('[oxy.auth] Session validation failed', {
490
- component: 'auth',
491
- method: 'auth',
492
- }, validationError);
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: 'SESSION_VALIDATION_ERROR',
501
- message: 'Session validation failed',
502
- code: 'SESSION_VALIDATION_ERROR',
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
- // Non-session token: use local validation only (userId from JWT)
511
- req.userId = userId;
512
- req.accessToken = token;
513
- req.user = { id: userId };
514
- // If loadUser requested with non-session token, fetch from API
515
- if (loadUser) {
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
- if (fullUser) {
529
- req.user = fullUser;
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
- catch (loadUserError) {
533
- // Loading the full user is best-effort here; the basic { id }
534
- // object is already attached. Log so misconfigured deployments
535
- // can be diagnosed instead of silently failing.
536
- logger.warn('[oxy.auth] loadUser fallback could not fetch full profile', {
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.loadUser',
539
- userId,
540
- }, loadUserError);
566
+ method: 'auth',
567
+ });
541
568
  }
569
+ return next();
542
570
  }
543
- if (debug) {
544
- logger.debug(`[oxy.auth] OK user=${userId} (no session)`, {
545
- component: 'auth',
546
- method: 'auth',
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 || decoded.id;
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
- if (!decoded.sessionId) {
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(decoded.sessionId, {
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 = decoded.sessionId || null;
708
+ socket.data.sessionId = sessionId;
665
709
  socket.data.token = token;
666
- socket.user = { id: userId, userId, sessionId: decoded.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
- * Verify that a decoded service-token payload carries the expected `aud`,
811
- * `iss`, and `type` claims. Throws `ServiceTokenClaimError` on mismatch.
812
- * This is the defence against the H4 vulnerability where a recovery / 2FA /
813
- * access token signed by the same shared secret could be replayed as a
814
- * service token because no claim binding existed.
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)}'`);
@@ -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
- * `oxy.auth({ optional: true })` preserves legacy non-session user tokens by
117
- * decoding their JWT claims locally. Those claims are not cryptographically
118
- * verified and therefore MUST NOT influence abuse-control buckets. Only use
119
- * identities that came from a server-validated session or a verified service
120
- * token/delegation.
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
- const resolveSession = oxy.auth({ ...auth, optional: true });
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,